diff --git a/ara/evidence/README.md b/ara/evidence/README.md index 78c741cb..df3f19a8 100644 --- a/ara/evidence/README.md +++ b/ara/evidence/README.md @@ -29,6 +29,7 @@ Instead, per the project's own decision, the empirical signal that grounds each |------|--------|--------|-------------| | [results/prop_layer.md](results/prop_layer.md) | `cabal build`/`cabal test` on `Lara.Prop` | C01 | Build + property-suite run record for carve-out layer 1 | | [results/map_bench_2026-09-11.md](results/map_bench_2026-09-11.md) | `make bench-map` at `ad513b5` | C56 (context) | First run of the committed map harness: shipped four-member map 2778.2 µs per full pass, 272.9 µs of it linking and the linked check | +| [results/checker_timing_2026-11-10.md](results/checker_timing_2026-11-10.md) | `make bench-container` batches at `018a2ae` + `scripts/bench_compare.py` | O221 (staged) | 25 container runs (10 unpinned, 5 with host busy loops, 10 pinned to the VM's isolated CPU) with in-run load; ~200 µs check + render, 1.2–2.3% run spread, +5.8% under host load; two failed 0.5-load quiet windows | | [results/executable_nd_adapter.md](results/executable_nd_adapter.md) | Lean/Haskell ND adapter gates | C03, C05 | Exact replay adequacy, proved Atom codec inverse, shared golden vectors, and full gate results | | [results/strict_certificate_frontend.md](results/strict_certificate_frontend.md) | S1 `.lara` → elaborate → `nd@1` replay + both-driver differential | C03, C05 | Policy-carried theory and surface assurance reach an accepted, justified verdict; missing theory rejects R13 | | [results/numeric_quarantine_parity.md](results/numeric_quarantine_parity.md) | Real Haskell/Lean drivers + full regression gates | C12, C25 | Shared `canonNum` closes false-justified numeric divergence; two blocked queries retain positional byte parity | diff --git a/ara/evidence/results/checker_timing_2026-11-10.md b/ara/evidence/results/checker_timing_2026-11-10.md new file mode 100644 index 00000000..07556590 --- /dev/null +++ b/ara/evidence/results/checker_timing_2026-11-10.md @@ -0,0 +1,94 @@ +# Checker timing batches, 2026-11-10 + +Run record for `docs/checker-timing.md`. Trace nodes: `N425_quiet_window_unreachable`, `N426_bench_repeat_and_report`, `N427_checker_timing_batches`. + +- Commit: `018a2ae1e6309351b23f9768f5f1bb2b700a990c` (branch `docs/checker-timing`, PR #69), clean tree; Haskell CI run 42882314673 completed success on that exact SHA. +- Host: Apple M5 Pro, 64 GB RAM, macOS 27.2 (Darwin 27.2.0). +- VM: OrbStack 2.2.5, Docker engine 29.8.2, kernel 7.2.12-orbstack, 18 virtual CPUs; `/sys/devices/system/cpu/isolated` read `17`. +- Image: `sha256:62a8d63db1220caaa072fbe4f2aacc19ee9f25d12d8d8457948d45e100474754` (GHC 9.14.1, Lean 4.32.0). +- Conditions: `--quiet-seconds 0`; Spotlight indexing active; `corespotlightd` (PID 1076) demoted with `taskpolicy -b` for all three batches and restored afterwards; desktop apps open. +- Run directories: `measurements/bench-runs/` on the measuring host (gitignored). + +## Failed quiet-window attempts at 9c3f6fa + +| Run directory | Status | Load samples | Load min | Load median | Load max | +| --- | --- | ---: | ---: | ---: | ---: | +| `20261110T054940Z-9c3f6fa65f32` | failed: host did not remain below load 0.5 for 120.0s within 3600.0s | 720 | 1.30 | 2.64 | 7.16 | +| `20261110T074841Z-9c3f6fa65f32` | failed: host did not remain below load 0.5 for 120.0s within 3600.0s | 720 | 0.83 | 2.11 | 6.49 | + +## `bench_compare.py` output, verbatim + +Unpinned, batch `20261110T191630Z`: + +``` +| Run | Pinned CPUs | Status | Control median (µs) | Load during run (min / median / max) | +| --- | --- | --- | ---: | --- | +| `20261110T191630Z-018a2ae1e630-r01` | - | included | 202.3 | 2.41 / 2.54 / 3.00 | +| `20261110T191657Z-018a2ae1e630-r02` | - | included | 204.1 | 2.84 / 2.92 / 3.08 | +| `20261110T191725Z-018a2ae1e630-r03` | - | included | 204.0 | 2.72 / 2.84 / 2.94 | +| `20261110T191751Z-018a2ae1e630-r04` | - | included | 203.3 | 2.75 / 2.87 / 2.98 | +| `20261110T191818Z-018a2ae1e630-r05` | - | included | 203.6 | 2.76 / 2.82 / 2.98 | +| `20261110T191845Z-018a2ae1e630-r06` (table) | - | included | 201.0 | 2.76 / 2.80 / 2.98 | +| `20261110T191912Z-018a2ae1e630-r07` | - | included | 200.2 | 2.63 / 2.76 / 2.94 | +| `20261110T191938Z-018a2ae1e630-r08` | - | included | 199.5 | 2.63 / 2.82 / 2.94 | +| `20261110T192004Z-018a2ae1e630-r09` | - | included | 199.9 | 2.69 / 2.84 / 2.91 | +| `20261110T192030Z-018a2ae1e630-r10` | - | included | 200.6 | 2.69 / 2.85 / 2.89 | + +Across 10 included runs the control-row median is 201.6 µs (range 199.5 to 204.1 µs, 2.3% of the median). Per unit, the range across runs is 5.8% of the unit's median at the median unit and 23.5% at most. +``` + +Unpinned with four host `yes > /dev/null` loops, batch `20261110T192100Z`: + +``` +| Run | Pinned CPUs | Status | Control median (µs) | Load during run (min / median / max) | +| --- | --- | --- | ---: | --- | +| `20261110T192100Z-018a2ae1e630-r01` | - | included | 208.0 | 3.03 / 3.83 / 4.30 | +| `20261110T192128Z-018a2ae1e630-r02` (table) | - | included | 213.2 | 4.30 / 4.59 / 4.97 | +| `20261110T192156Z-018a2ae1e630-r03` | - | included | 215.3 | 4.97 / 5.28 / 5.78 | +| `20261110T192224Z-018a2ae1e630-r04` | - | included | 211.6 | 5.78 / 6.13 / 6.27 | +| `20261110T192252Z-018a2ae1e630-r05` | - | included | 214.1 | 6.17 / 6.37 / 6.71 | + +Across 5 included runs the control-row median is 213.2 µs (range 208.0 to 215.3 µs, 3.4% of the median). Per unit, the range across runs is 6.6% of the unit's median at the median unit and 12.8% at most. +``` + +Pinned to VM CPU 17, batch `20261110T192322Z`: + +``` +| Run | Pinned CPUs | Status | Control median (µs) | Load during run (min / median / max) | +| --- | --- | --- | ---: | --- | +| `20261110T192322Z-018a2ae1e630-r01` | 17 | included | 200.1 | 5.16 / 5.96 / 6.71 | +| `20261110T192349Z-018a2ae1e630-r02` | 17 | included | 199.8 | 3.92 / 4.45 / 5.16 | +| `20261110T192415Z-018a2ae1e630-r03` | 17 | included | 199.6 | 3.38 / 3.64 / 3.92 | +| `20261110T192441Z-018a2ae1e630-r04` | 17 | included | 200.9 | 3.38 / 3.47 / 3.52 | +| `20261110T192507Z-018a2ae1e630-r05` | 17 | included | 199.5 | 3.32 / 3.39 / 3.52 | +| `20261110T192533Z-018a2ae1e630-r06` | 17 | included | 200.3 | 3.20 / 3.39 / 3.59 | +| `20261110T192559Z-018a2ae1e630-r07` | 17 | included | 200.2 | 3.25 / 3.35 / 3.59 | +| `20261110T192626Z-018a2ae1e630-r08` | 17 | included | 199.5 | 3.25 / 3.78 / 4.19 | +| `20261110T192652Z-018a2ae1e630-r09` (table) | 17 | included | 199.6 | 3.36 / 3.56 / 3.70 | +| `20261110T192718Z-018a2ae1e630-r10` | 17 | included | 198.5 | 3.00 / 3.20 / 3.41 | + +Across 10 included runs the control-row median is 199.7 µs (range 198.5 to 200.9 µs, 1.2% of the median). Per unit, the range across runs is 3.9% of the unit's median at the median unit and 9.1% at most. +``` + +## Published table run `20261110T192652Z-018a2ae1e630-r09`, `performance.md` verbatim + +``` +| | median | worst | +| --- | ---: | ---: | +| Corpus unit, end-to-end (µs) | 437.6 | 472.4 | +|   parse (µs) | 238.4 | 248.8 | +|   check + render, pre-decoded (µs) | 199.8 | 226.5 | +|   validate (µs) | 0.1 | 0.2 | +|   check (µs) | 194.0 | 221.4 | +|   compile (µs) | 0.0 | 0.6 | +|   evaluate (µs) | 0.6 | 1.1 | +| Per-artifact total (27 artifacts, µs) | 878.7 | 1751.4 | +| Framework size (nodes / edges) | 0 / 0 | 2 / 1 | +| Lean reference driver, subprocess (ms) | 1.1 | 1.3 | +| | | | +| 660-record harness, one full pass (ms) | 172.2 | | +``` + +## Reading + +The batches ran in sequence (unpinned, busy, pinned), so the pinned batch's narrower spread is confounded with time order and with the one-minute load average left by the stopped busy loops. Every busy run was slower than every unpinned run (208.0 µs minimum against 204.1 µs maximum). The selection rule fixed in the plan before the runs (`plans/checker-timing-run.md` as of commit `15c9d45`, removed once executed: keep unpinned unless pinned has a narrower range and a median that is not higher) chose the pinned batch. diff --git a/ara/logic/solution/constraints.md b/ara/logic/solution/constraints.md index d0cdeb00..7ae3fedf 100644 --- a/ara/logic/solution/constraints.md +++ b/ara/logic/solution/constraints.md @@ -145,7 +145,7 @@ disagreement; dependent claims surface as `gap`). does not transfer to the concrete-syntax Haskell parser; the QuickCheck round-trip (`SyntaxSpec`, 2000 iters) remains the surface-syntax conformance evidence. -- **The two checking-time columns are different protocols and must never be ratioed (from O31).** +- **The two checking-time columns are different protocols and must never be ratioed (from O31).** `hs_check` is in-process, decode excluded, verdict forced (median ~7 µs); `lean_wall` is subprocess wall time including startup + decode (median ~2.6 ms, trace N96). The ~370× gap is process startup, not semantics — any cross-driver speed claim needs a same-protocol measurement. diff --git a/ara/staging/observations.yaml b/ara/staging/observations.yaml index 560a1f7b..8c582371 100644 --- a/ara/staging/observations.yaml +++ b/ara/staging/observations.yaml @@ -4454,3 +4454,24 @@ observations: promoted_to: logic/claims.md:C58 crystallized_via: verbal-affirmation stale: false +- id: O221 + timestamp: '2026-11-10T19:40:00Z' + provenance: ai-suggested + content: >- + On the Apple M5 Pro desktop under OrbStack, the bench control row (check + render, pre-decoded) + repeats within about 1-2% across back-to-back container runs under steady host load, but host + load itself moves it: four extra busy processes raised it about 6%, beyond the run spread. Run + agreement on this host therefore bounds repeatability, not interference, and checker timing + claims from it should be stated as magnitudes under recorded load. Whether pinning to the VM's + isolated CPU reduces spread is not separated from batch order. + context: >- + Three batches at 018a2ae (N427) after the quiet-window gate proved unreachable (N425). The + researcher has not yet commented on the results. CONFLICT: see N428_hs_check_magnitude_conflict + for the stale ~7 us figure in logic/solution/constraints.md. + potential_type: constraint + bound_to: + - N427_checker_timing_batches + promoted: false + promoted_to: null + crystallized_via: null + stale: false diff --git a/ara/trace/exploration_tree.yaml b/ara/trace/exploration_tree.yaml index 0fcca1b9..c633ecb0 100644 --- a/ara/trace/exploration_tree.yaml +++ b/ara/trace/exploration_tree.yaml @@ -11777,3 +11777,85 @@ tree: status: resolved also_depends_on: - N423_online_fdr_proved +- id: N425_quiet_window_unreachable + type: dead_end + title: Wait for a quiet desktop host before timing the checker + provenance: ai-executed + timestamp: '2026-11-10T08:48:00Z' + hypothesis: >- + The publication runner's default gate (macOS one-minute load average below 0.5 for 120 + continuous seconds, waiting up to 3600 s) can be met on the working Apple M5 Pro desktop if + other apps are closed. + failure_mode: >- + Two one-hour attempts at 9c3f6fa timed out before any timing: 720 load samples each, lowest + readings 1.30 and 0.83, with Spotlight indexing (corespotlightd), gh and desktop apps running. + The gate also sampled load only before docker run, so it said nothing about the timed interval. + lesson: >- + On a shared desktop, replace the pre-run gate with repeated runs, load sampled during each timed + run, and a report of the spread; a quiet gate needs a dedicated host. + evidence: + - ara/evidence/results/checker_timing_2026-11-10.md + status: resolved +- id: N426_bench_repeat_and_report + type: decision + title: Repeat-and-report timing protocol with verified isolated-CPU pinning + provenance: user-revised + timestamp: '2026-11-10T19:00:00Z' + choice: >- + Drop the load gate for publication batches (--quiet-seconds 0); run the container N times per + batch with host load sampled during each timed run; keep every run and exclude only non-success + runs; choose the table run by a lower-median rule and the batch by a rule fixed before the runs; + pin only to a Docker VM CPU the guest lists in /sys/devices/system/cpu/isolated; state that run + agreement shows repeatability, not absence of interference. Implemented in 018a2ae + (scripts/bench_container.py, scripts/bench_compare.py); protocol in docs/evaluation.md. + alternatives: + - Keep the 0.5 load gate and wait for an idle machine (N425) + - Reserve physical cores on macOS (no CPU affinity on Apple Silicon; VM vCPUs are host threads) + - Move the run to a dedicated Linux host with isolcpus or cset shield + - Count instructions instead of wall time + evidence: + - docs/evaluation.md + - scripts/bench_container.py + - scripts/bench_compare.py + status: resolved + also_depends_on: + - N425_quiet_window_unreachable +- id: N427_checker_timing_batches + type: experiment + title: Three container timing batches at 018a2ae on the Apple M5 Pro + provenance: ai-executed + timestamp: '2026-11-10T19:27:00Z' + result: >- + 25 runs, none failed. Control row (check + render, pre-decoded) median across runs: unpinned + 201.6 us (range 2.3%, load median 2.83), four host busy loops 213.2 us (range 3.4%, load median + 5.28), pinned to VM CPU 17 199.7 us (range 1.2%, load median 3.52). Every busy run was slower than + every unpinned run. Published table run 20261110T192652Z-018a2ae1e630-r09: end to end 437.6 us, + check + render 199.8 us, Lean subprocess 1.1 ms, harness pass 172.2 ms. Batches ran in sequence, + so the pinned batch's narrower spread is confounded with time order and lingering busy-loop load. + evidence: + - ara/evidence/results/checker_timing_2026-11-10.md + - docs/checker-timing.md + status: resolved + also_depends_on: + - N426_bench_repeat_and_report +- id: N428_hs_check_magnitude_conflict + type: decision + title: Stale hs_check magnitude in the checking-time constraint + provenance: ai-suggested + timestamp: '2026-11-10T19:40:00Z' + choice: >- + Unresolved. logic/solution/constraints.md (checking-time columns entry, from O31 and N96) states + an hs_check median of ~7 us and a ~370x gap to lean_wall. On 2026-11-10 the bench control row + measured ~200 us per unit (N427), measure.hs single-shot hs-check-ns had median 186 us at 4cca881, + and the frozen v8 report.json has median 344 us. The constraint's rule (never ratio the two + columns) is unaffected; only its stated magnitudes conflict. Left for the researcher to adjudicate. + alternatives: + - Revise the constraint's magnitudes to the current measurements + - Keep the historical N96 figures with an explicit date + evidence: + - ara/evidence/results/checker_timing_2026-11-10.md + - measurements/frozen/report.json + status: unresolved + also_depends_on: + - N96 + - N427_checker_timing_batches diff --git a/ara/trace/pm_reasoning_log.yaml b/ara/trace/pm_reasoning_log.yaml index 153eb8d7..0d6d945e 100644 --- a/ara/trace/pm_reasoning_log.yaml +++ b/ara/trace/pm_reasoning_log.yaml @@ -1945,3 +1945,9 @@ entries: notes: - Record N424 as an experiment (proof plus gates) depending on N423. It closes the product-law gap N423 recorded; N423 itself is left as written because the trace is append-only. - No claim, staged observation or constraints edit. The weaker premise is a mechanized standard result documented in docs/theory-process.md, and the constraints Open line never mentioned the premise. +- turn: 2026-11-10_001#1 + notes: + - Record N425 as a dead_end (the 0.5-load gate never opened in two hours) and N426 as a user-revised decision; the AI proposed the protocol and the researcher directed implementing and running it. + - Record N427 as an experiment and stage O221 as a constraint candidate. Not crystallized: the researcher has not commented on the results, and the pinning comparison is confounded by batch order. + - Flag the ~7 us hs_check magnitude in constraints.md as a CONFLICT with N428 instead of rewriting it, per the contradiction rule; the never-ratio rule itself stands. + - No claim touched. C32 and C33 report parse-latency deltas under their own protocols and are not contradicted by an absolute timing record. diff --git a/ara/trace/sessions/2026-11-10_001.yaml b/ara/trace/sessions/2026-11-10_001.yaml new file mode 100644 index 00000000..4da73b02 --- /dev/null +++ b/ara/trace/sessions/2026-11-10_001.yaml @@ -0,0 +1,81 @@ +session: + id: 2026-11-10_001 + date: '2026-11-10' + started: 2026-11-10T05:49 + last_turn: '2026-11-10T19:40:00Z' + turn_count: 1 + summary: 'Paper-side reruns and checker timing: deterministic gates reproduced v8 at 4cca881 after + harness fixes (#67, #68); the 0.5-load quiet window proved unreachable on the desktop host; a + repeat-and-report protocol with verified isolated-CPU pinning landed at 018a2ae (PR #69) and + three timing batches put check + render near 200 us per corpus unit.' +events_logged: +- turn: 1 + type: dead_end + id: N425_quiet_window_unreachable + routing: direct + provenance: ai-executed + summary: Two 1 h quiet-window attempts at 9c3f6fa never reached load < 0.5 (min 0.83) +- turn: 1 + type: decision + id: N426_bench_repeat_and_report + routing: direct + provenance: user-revised + summary: No load gate; N runs with in-run load; keep all runs; predeclared table and batch rules; verified isolated-CPU pinning +- turn: 1 + type: experiment + id: N427_checker_timing_batches + routing: direct + provenance: ai-executed + summary: 25 runs at 018a2ae; control row 201.6 / 213.2 (busy) / 199.7 (pinned) us; spreads 2.3 / 3.4 / 1.2% +- turn: 1 + type: decision + id: N428_hs_check_magnitude_conflict + routing: direct + provenance: ai-suggested + summary: Unresolved conflict between constraints.md ~7 us hs_check and ~200 us measured +- turn: 1 + type: observation + id: O221 + routing: staged + provenance: ai-suggested + summary: Run spread bounds repeatability, not interference; host load moves the control row ~6% +ai_actions: +- turn: 1 + action: Reran paper evaluation gates at 4cca881 (axiom audit, differentials, presentation parity, + surface conformance, measure.hs, claim-support); report and ablation hashes matched frozen v8 + provenance: ai-executed + files_changed: [] +- turn: 1 + action: 'Fixed harness drift: D7 inquiry inputs excluded from core anchor discovery (#67); bench image + copies cbits and builds only lara-driver (#68)' + provenance: ai-executed + files_changed: + - scripts/differential.sh + - scripts/gen-anchor-manifest.sh + - containers/bench/Dockerfile +- turn: 1 + action: Implemented repeated runs, in-run load sampling, verified --cpuset-cpus and bench_compare.py + (018a2ae); ran three batches; wrote docs/checker-timing.md and the protocol in docs/evaluation.md + provenance: ai-executed + files_changed: + - scripts/bench_container.py + - scripts/bench_compare.py + - scripts/test_bench_container.py + - docs/checker-timing.md + - docs/evaluation.md + - docs/README.md + - scripts/bench.hs + - ara/evidence/results/checker_timing_2026-11-10.md +claims_touched: [] +logic_revisions: [] +key_context: +- turn: 1 + excerpt: 'Researcher: "finish task 1 and run and update doc. pin the task 1''s commit. and I will create + merge commit pr instead of squash"' +open_threads: +- 'Refresh the paper''s tables/performance.tex from the published table run (#70)' +- Adjudicate N428 (stale hs_check magnitude in constraints.md) +- Interleave pinned and unpinned runs before adopting pinning as the default +- Human review of the corpus-study annotations remains pending in the paper +ai_suggestions_pending: +- O221 (timing claims as magnitudes under recorded load) diff --git a/ara/trace/sessions/session_index.yaml b/ara/trace/sessions/session_index.yaml index a6db48f9..9dd25d27 100644 --- a/ara/trace/sessions/session_index.yaml +++ b/ara/trace/sessions/session_index.yaml @@ -783,3 +783,11 @@ sessions: events_count: 4 claims_touched: [] open_threads: 1 + +- id: 2026-11-10_001 + date: '2026-11-10' + summary: Deterministic paper reruns reproduced v8 after harness fixes; quiet-window gate unreachable on the desktop; repeat-and-report timing protocol landed at 018a2ae and three batches put check + render near 200 us per corpus unit. + turn_count: 1 + events_count: 5 + claims_touched: [] + open_threads: 4 diff --git a/docs/README.md b/docs/README.md index 949362ce..a91587c2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -34,6 +34,7 @@ The [worked-example catalogue](../examples/README.md) lists executable artifacts | --- | --- | | [Corpus lowering map](corpus-map.md) | How research-artifact content becomes Lara declarations | | [Evaluation](evaluation.md) | Performance, mutation and localization contracts and frozen inputs | +| [Checker timing](checker-timing.md) | Dated publication timing record for the Haskell checker: commit, host, every run and its load, spread and claim limits | | [Measured-input freeze](../measurements/frozen/evidence-measured-inputs-v2.md) | Certified-evidence evaluation inputs | ## How is the implementation maintained? diff --git a/docs/checker-timing.md b/docs/checker-timing.md new file mode 100644 index 00000000..c33cf57a --- /dev/null +++ b/docs/checker-timing.md @@ -0,0 +1,124 @@ +# Checker timing on the Apple M5 Pro, 2026-11-10 + +**Date:** 2026-11-10 + +## TL;DR + +At commit `018a2ae`, the Haskell checker took about 200 µs to check one corpus unit and render its verdict, and about 440 µs end to end once decoding is included. Ten repeated runs agreed closely: the per-run median of the control row (check and render on an already decoded unit) varied by 2.3% in the unpinned batch and 1.2% in the later batch pinned to the Docker VM's isolated CPU. Host load moves the numbers: four extra busy processes on the Mac raised the control row by about 6%, more than the spread between ordinary runs. The published table comes from the pinned batch, under a selection rule fixed before the runs, and it describes the checker on a working desktop under the load recorded for each run. + +## How long does one check take? + +The published table is the table run of the pinned batch, chosen by the rule in [Evaluation](evaluation.md#running-the-bench): the run whose control-row median is the lower median of its batch. Each figure is the median over the 60 corpus units of a per-unit value, and each per-unit value is the median of 5 timed sections of 100 repetitions, divided by 100. "Worst" is the slowest unit. + +| Row | Median | Worst | +| --- | ---: | ---: | +| Corpus unit, end to end (µs) | 437.6 | 472.4 | +| Parse, the marginal decode cost (µs) | 238.4 | 248.8 | +| Check and render, pre-decoded: the control row (µs) | 199.8 | 226.5 | +| Validate (µs) | 0.1 | 0.2 | +| Check (µs) | 194.0 | 221.4 | +| Compile (µs) | 0.0 | 0.6 | +| Evaluate (µs) | 0.6 | 1.1 | +| Per-artifact total, 27 artifacts (µs) | 878.7 | 1751.4 | +| Lean reference driver, one subprocess (ms) | 1.1 | 1.3 | +| 660-record harness, one full pass (ms) | 172.2 | | + +Decoding and checking cost about the same: of the 437.6 µs end to end, 238.4 µs is parsing the wire format and 199.8 µs is checking and rendering. Almost all of the check is the six-stage acceptance check; compiling the attack graph and evaluating statuses each take under a microsecond, because the median corpus unit has no graph nodes and the largest has two nodes and one edge. The Lean row is a whole process, startup included, so it shows why the Lean executable stays a test oracle; it must not be divided into the Haskell rows. + +## Do repeated runs agree? + +Three batches ran back to back at the same commit and image. Each run took about 27 seconds. The table lists the across-run median of each run's per-unit median, its range, and the host's one-minute load average sampled every 5 seconds while the runs were timed. + +| Batch | Runs | Host load during runs (min / median / max) | Control row median (µs) | Range across runs | End to end (µs) | Lean subprocess (ms) | Harness pass (ms) | +| --- | ---: | --- | ---: | --- | ---: | ---: | ---: | +| Unpinned | 10 | 2.41 / 2.83 / 3.08 | 201.6 | 199.5 to 204.1 (2.3%) | 445.4 | 1.33 | 174.6 | +| Pinned to VM CPU 17 | 10 | 3.00 / 3.52 / 6.71 | 199.7 | 198.5 to 200.9 (1.2%) | 437.9 | 1.11 | 171.1 | +| Unpinned, 4 host busy loops | 5 | 3.03 / 5.28 / 6.71 | 213.2 | 208.0 to 215.3 (3.4%) | 464.6 | 1.33 | 178.1 | + +Run-level medians hide some per-unit noise. In the unpinned batch, a typical unit's control row varied by 5.8% across the ten runs and the noisiest unit by 23.5%; in the pinned batch the same figures were 3.9% and 9.1%. A claim about one unit therefore needs the batch median, while a claim about the corpus median is stable to a few percent. + +No run failed, so none was excluded. Every run, with its control-row median and the load sampled while it was timed, is listed in [Appendix: Every run](#appendix-every-run). + +## Does host load move the numbers? + +Four `yes > /dev/null` processes on the Mac pushed the load average from about 3 to about 5, and the control row rose from 201.6 µs to 213.2 µs, 5.8% above the unpinned batch. Every busy run was slower than every unpinned run, so the difference is larger than run-to-run noise. + +That result limits what the other batches can claim. Repeated runs agreeing shows that the measurement repeats on this host; it does not show that background work had no effect, because a steady load can slow every run alike. All three batches ran with Spotlight indexing active and desktop apps open, and the load average never fell below 2.41 during a timed run. Two earlier attempts on the same host that day waited an hour each for the runner's default quiet window (load below 0.5 for two minutes) and never reached it; the lowest reading in 1,440 samples was 0.83. These numbers describe the checker under that load. How much faster it would be on an idle machine was not measured. + +## Does pinning to the VM's isolated CPU help? + +The pinned batch, which ran last, had a narrower spread than the unpinned batch. OrbStack 2.2.5 boots its Linux VM with `isolcpus=17`, which keeps ordinary Linux work off virtual CPU 17, and the runner confirmed that `/sys/devices/system/cpu/isolated` read `17` before pinning. The pinned batch had half the unpinned batch's spread (1.2% against 2.3%) and a slightly lower median (199.7 µs against 201.6 µs), and its Lean subprocess row was lower, 1.11 ms against 1.33 ms. These are observed differences between two batches, not a measured effect of pinning. The batches ran one after the other (unpinned, then busy loops, then pinned), so pinning is confounded with time order and any thermal drift, and the load readings of the first pinned runs (up to 6.71) still carry the one-minute average left by the busy loops, which had already been stopped. Interleaving pinned and unpinned runs would be needed to attribute the difference to pinning. + +Pinning isolates the benchmark only from work inside the VM. Virtual CPU 17 is still an ordinary macOS thread, and macOS decides which physical core runs it; the guest cannot reserve a performance core. macOS on Apple Silicon has no CPU affinity to reserve cores from the host side either. The one host-side lever used here was `taskpolicy -b` on `corespotlightd` (PID 1076), which confines that process to the efficiency cores; it slows other work and reserves nothing. + +The rule for choosing between batches was fixed before either ran: keep the unpinned batch unless the pinned batch has a narrower control-row range and a median that is not higher. The pinned batch met both conditions, so its table run supplies the published table. The unpinned table run (`20261110T191845Z-018a2ae1e630-r06`, control-row median 201.0 µs) differs by about 1%, well within the claims this report supports. + +## How were the runs made? + +| Item | Value | +| --- | --- | +| Commit | `018a2ae1e6309351b23f9768f5f1bb2b700a990c`, clean tree, Haskell CI [run 42882314673](https://github.com/ARA-Labs/Lara/actions/runs/42882314673) passed | +| Host | Apple M5 Pro, 64 GB RAM, macOS 27.2 | +| VM | OrbStack 2.2.5, Docker engine 29.8.2, Linux 7.2.12-orbstack, 18 virtual CPUs, about 16 GB | +| Image | `sha256:62a8d63db1220caaa072fbe4f2aacc19ee9f25d12d8d8457948d45e100474754`, GHC 9.14.1, Lean 4.32.0, no network, read-only root | +| Batches | unpinned `20261110T191630Z`, busy `20261110T192100Z`, pinned `20261110T192322Z` | +| Table run | `20261110T192652Z-018a2ae1e630-r09` | +| Quiet window | bypassed (`--quiet-seconds 0`); load sampled during each timed run instead | +| Host conditions | Spotlight indexing active, `corespotlightd` demoted with `taskpolicy -b`, desktop apps open | + +The run directories under `measurements/bench-runs/` are gitignored and exist only on the measuring host. Each holds `provenance.json` with the CI run, image ID, batch, pinning check, every load sample and the SHA-256 digests of the outputs, plus `bench.json` and the rendered tables. The per-run values this report relies on are copied into [Appendix: Every run](#appendix-every-run). + +## Recommendations + +1. Quote the checker as taking about 200 µs per corpus unit for check and render, and about 440 µs including decoding, on this host. Do not quote single figures more precisely than the batch range. +2. Refresh the paper's `tables/performance.tex` from the table run's `performance.tex`, and state the commit, host and the load caveat beside it. +3. Before adopting pinning as the default, interleave pinned and unpinned runs in one session, because the batches here ran in sequence and cannot separate pinning from time order. +4. If a later claim needs precision better than about 5%, measure on a dedicated Linux host with isolated cores, because this Mac cannot remove the load that moved these numbers. + +## Appendix: Reproduction + +A rerun from a clean checkout of `018a2ae`, with Haskell CI green on that commit, produces new batch ids and new run directories; the ids in this report name the 2026-11-10 runs on the measuring host. The busy batch ran with four `yes > /dev/null` processes started before it and stopped after it. + +```sh +taskpolicy -b -p +BENCH_ARGS="--quiet-seconds 0 --runs 10 --demoted-pid " make bench-container +BENCH_ARGS="--quiet-seconds 0 --runs 5 --demoted-pid " make bench-container # with 4 busy loops +BENCH_ARGS="--quiet-seconds 0 --runs 10 --demoted-pid --cpuset-cpus 17" make bench-container +taskpolicy -B -p + +python3 scripts/bench_compare.py --batch +``` + +`bench_compare.py` prints every run with its control-row median and in-run load, and the across-run summary used above. The end-to-end, Lean and harness columns in the batch table are medians across runs of the same per-run statistics, read from each run's `bench.json`. + +## Appendix: Every run + +Control-row median is the median across the 60 corpus units of `kernel_ns` in that run's `bench.json`. Load is the host's one-minute load average sampled every 5 seconds from just before the container started to just after it exited. + +| Batch | Run | Control-row median (µs) | Load during run (min / median / max) | +| --- | --- | ---: | --- | +| Unpinned | `20261110T191630Z-018a2ae1e630-r01` | 202.3 | 2.41 / 2.54 / 3.00 | +| Unpinned | `20261110T191657Z-018a2ae1e630-r02` | 204.1 | 2.84 / 2.92 / 3.08 | +| Unpinned | `20261110T191725Z-018a2ae1e630-r03` | 204.0 | 2.72 / 2.84 / 2.94 | +| Unpinned | `20261110T191751Z-018a2ae1e630-r04` | 203.3 | 2.75 / 2.87 / 2.98 | +| Unpinned | `20261110T191818Z-018a2ae1e630-r05` | 203.6 | 2.76 / 2.82 / 2.98 | +| Unpinned | `20261110T191845Z-018a2ae1e630-r06` (table run) | 201.0 | 2.76 / 2.80 / 2.98 | +| Unpinned | `20261110T191912Z-018a2ae1e630-r07` | 200.2 | 2.63 / 2.76 / 2.94 | +| Unpinned | `20261110T191938Z-018a2ae1e630-r08` | 199.5 | 2.63 / 2.82 / 2.94 | +| Unpinned | `20261110T192004Z-018a2ae1e630-r09` | 199.9 | 2.69 / 2.84 / 2.91 | +| Unpinned | `20261110T192030Z-018a2ae1e630-r10` | 200.6 | 2.69 / 2.85 / 2.89 | +| Busy loops | `20261110T192100Z-018a2ae1e630-r01` | 208.0 | 3.03 / 3.83 / 4.30 | +| Busy loops | `20261110T192128Z-018a2ae1e630-r02` (table run) | 213.2 | 4.30 / 4.59 / 4.97 | +| Busy loops | `20261110T192156Z-018a2ae1e630-r03` | 215.3 | 4.97 / 5.28 / 5.78 | +| Busy loops | `20261110T192224Z-018a2ae1e630-r04` | 211.6 | 5.78 / 6.13 / 6.27 | +| Busy loops | `20261110T192252Z-018a2ae1e630-r05` | 214.1 | 6.17 / 6.37 / 6.71 | +| Pinned to VM CPU 17 | `20261110T192322Z-018a2ae1e630-r01` | 200.1 | 5.16 / 5.96 / 6.71 | +| Pinned to VM CPU 17 | `20261110T192349Z-018a2ae1e630-r02` | 199.8 | 3.92 / 4.45 / 5.16 | +| Pinned to VM CPU 17 | `20261110T192415Z-018a2ae1e630-r03` | 199.6 | 3.38 / 3.64 / 3.92 | +| Pinned to VM CPU 17 | `20261110T192441Z-018a2ae1e630-r04` | 200.9 | 3.38 / 3.47 / 3.52 | +| Pinned to VM CPU 17 | `20261110T192507Z-018a2ae1e630-r05` | 199.5 | 3.32 / 3.39 / 3.52 | +| Pinned to VM CPU 17 | `20261110T192533Z-018a2ae1e630-r06` | 200.3 | 3.20 / 3.39 / 3.59 | +| Pinned to VM CPU 17 | `20261110T192559Z-018a2ae1e630-r07` | 200.2 | 3.25 / 3.35 / 3.59 | +| Pinned to VM CPU 17 | `20261110T192626Z-018a2ae1e630-r08` | 199.5 | 3.25 / 3.78 / 4.19 | +| Pinned to VM CPU 17 | `20261110T192652Z-018a2ae1e630-r09` (table run, published) | 199.6 | 3.36 / 3.56 / 3.70 | +| Pinned to VM CPU 17 | `20261110T192718Z-018a2ae1e630-r10` | 198.5 | 3.00 / 3.20 / 3.41 | diff --git a/docs/evaluation.md b/docs/evaluation.md index c1aaf992..b8009b1b 100644 --- a/docs/evaluation.md +++ b/docs/evaluation.md @@ -385,7 +385,7 @@ The [P9 report](../ara/evidence/inquiry-p9/report.md) gives the observations, th ## Checker performance -E1 is the checker-performance bench: it times the Haskell checker over the frozen evaluation corpus, both the per-unit check cost and one full pass over the harness records, via `make bench`. Bench timings are not frozen evaluation numbers: they describe one machine at one commit, and no timing snapshot is published here. Run the bench to obtain numbers. The paper's typeset table is generated separately and is not tracked in this repository. +E1 is the checker-performance bench: it times the Haskell checker over the frozen evaluation corpus, both the per-unit check cost and one full pass over the harness records, via `make bench`. Bench timings are not frozen evaluation numbers: they describe one machine at one commit. The one committed timing record is [Checker timing](checker-timing.md), which names its commit, host, image and batches. The paper's typeset table is generated separately and is not tracked in this repository. ### Running the bench @@ -397,25 +397,28 @@ make bench FORMAT=latex OUT=../paper/tables/performance.tex The table goes to stdout unless `--out` names a file, and progress goes to stderr, so stdout stays pipeable. Every run also writes the raw per-unit record to `measurements/bench.json`, which is gitignored as regenerable output. `make bench` builds the Haskell benchmark executable and the Lean driver before it runs; a direct `lara-bench --prebuilt` invocation suppresses that build only when an existing Lean driver is present. -A publication measurement uses a pinned Linux/arm64 container on the local Apple M5 Pro: +A publication measurement is a batch of repeated runs in a pinned Linux/arm64 container on the local Apple M5 Pro, reported together: ```sh -make bench-container +BENCH_ARGS="--quiet-seconds 0 --runs 10" make bench-container +python3 scripts/bench_compare.py --batch ``` -The host runner requires a clean commit with successful GitHub Actions CI for that exact SHA. It builds the image before measurement, then waits until the macOS one-minute load average remains below `0.5` for 120 continuous seconds; any excursion resets the quiet interval. The timed container has no network, uses a read-only root filesystem, and performs no compilation. A successful run writes `provenance.json`, `bench.json`, and text, Markdown, and LaTeX tables under `measurements/bench-runs/-/`; those regenerable files remain gitignored, and `provenance.json` records the exact CI and job times, host and container resources, the image ID, every quiet-window sample, the timed command, and SHA-256 digests of the four benchmark outputs. For a local wiring smoke test that does not claim a publication measurement, use `BENCH_ARGS="--skip-ci --quiet-seconds 0" make bench-container`; the bypass is explicit in its provenance. +The host runner requires a clean commit with successful GitHub Actions CI for that exact SHA and builds the image once per batch. `--runs N` then runs the container N times in sequence, each into `measurements/bench-runs/--rNN/` (a single run has no `-rNN` suffix). The runner can still wait before each run until the macOS one-minute load average stays below `--load-threshold` (default `0.5`) for `--quiet-seconds` (default 120). A desktop host never reached that default in two hours on 2026-11-10 (lowest reading 0.83), so a publication batch sets `--quiet-seconds 0`, and the bypass is recorded. During each timed run the runner samples the host's one-minute load every `--sample-interval` seconds (default 5), from just before `docker run` starts to just after it exits. `--cpuset-cpus` pins the container to Docker VM CPUs and refuses any CPU missing from the VM's `/sys/devices/system/cpu/isolated`, recording that list and the VM kernel command line, because Docker accepts the option for any CPU whether or not it is isolated. `--demoted-pid` records host processes the operator moved to the efficiency cores with `taskpolicy -b`, and `--batch-note` records host conditions as free text. The timed container has no network, uses a read-only root filesystem, and performs no compilation. Each run's `provenance.json` (`lara-bench-provenance@2`) records the CI run and jobs, host and container resources, the image ID, the batch id and index, any pinning, every load sample, the timed command, and SHA-256 digests of the four benchmark outputs; those regenerable files remain gitignored. For a local wiring smoke test that does not claim a publication measurement, use `BENCH_ARGS="--skip-ci --quiet-seconds 0" make bench-container`; the bypass is explicit in its provenance. + +`scripts/bench_compare.py` reads one batch and reports every run: its control-row median, the load sampled while it was timed, and the per-unit median and range across runs. A run leaves the statistics only for a reason fixed in advance, a provenance status other than `success`. Outputs that no longer match their recorded digests, and a batch that mixes commits or images, are refused. The published table comes from the run whose control-row median is the lower median of the batch. Agreement between runs shows that the measurement repeats; it does not show that background work had no effect, because a steady load can slow every run by the same amount. ### What is measured The bench runs the production checker over the frozen corpus units and the manifest-discovered harness, and its protocols are deliberately aligned with `scripts/measure.hs`. -- Haskell sections are in-process and exclude decode. The timed work is `runCheck` plus forcing the rendered verdict text. One check runs in single-digit microseconds, below timer noise, so each section runs the work 100 times and divides; the reported value is the median of 5 such sections. +- Haskell sections are in-process and exclude decode. The timed work is `runCheck` plus forcing the rendered verdict text. One corpus check takes a few hundred microseconds; each section runs the work 100 times and divides, and the reported value is the median of 5 such sections. - Phases are timed against forced outputs, with earlier stages pre-forced: parse (decode plus forced re-encode), validate (replay preflight plus group boundary), check (the six-stage `checkUnitWith`), compile (the cached-adjacency AF and its closure edges), and evaluate (grounded labels plus per-query four-state statuses). Phases are therefore attributable but need not sum to the end-to-end row. - `parse` is the marginal decode cost inside the real pipeline: end-to-end minus the pre-decoded check and render section. - The Lean row is full subprocess wall time of the reference driver, startup and decode included. This is a different protocol, reported only to justify why the Lean executable stays a test oracle rather than a production path. No cross-driver ratio may be derived from it. - The harness sweep pre-reads every manifest input, then times one full in-memory pass (decode, check, and render, or the codec-failure path). - The multi-artifact map is measured separately and never in these rows, because a `.laramap` run is a different shape of work that scales with member count rather than with one unit's size. -- The `check + render, pre-decoded` row is the stable control, because it sits downstream of the decode boundary and no wire-codec change can move it. A run whose control row deviates markedly from repeated runs on the same machine and commit is measuring machine load rather than the checker and should be discarded rather than quoted. +- The `check + render, pre-decoded` row is the stable control, because it sits downstream of the decode boundary and no wire-codec change can move it. Compare it across a batch's runs: a run whose control row deviates markedly is reported with the load recorded during it, not dropped, since choosing runs after seeing their numbers would let the outcome pick the evidence. ## The multi-artifact map: a separate protocol @@ -433,8 +436,8 @@ make bench-map FORMAT=markdown # markdown No number from the map table may be set beside the kernel table's. The two protocols time different work on different inputs. -## Why no rendered table is committed +## Why rendered tables stay out of the source tree -A timing table is machine state, not source: it is valid only for the machine and the commit that produced it, so a tracked rendered table eventually disagrees with the code beside it. `measurements/` is gitignored under the same rule. +A timing table is machine state, not source: it is valid only for the machine and the commit that produced it, so a tracked rendered table eventually disagrees with the code beside it. `measurements/` is gitignored under the same rule. [Checker timing](checker-timing.md) is a dated measurement record pinned to its commit and host, not a table the current code is expected to reproduce. -The bench prints, and each consumer owns its rendered copy. The paper repository owns the `tables/performance.tex` it typesets and refreshes it with one `make bench FORMAT=latex OUT=…`. +The bench prints, and each consumer owns its rendered copy. The paper repository owns the `tables/performance.tex` it typesets and refreshes it from the `performance.tex` of a publication batch's table run, or with one `make bench FORMAT=latex OUT=…` for an informal number. diff --git a/scripts/bench.hs b/scripts/bench.hs index 4b8ec31d..7b8cb5dd 100644 --- a/scripts/bench.hs +++ b/scripts/bench.hs @@ -8,10 +8,10 @@ -- Protocols (deliberately aligned with @scripts\/measure.hs@): -- -- * @hs@ sections are in-process and exclude decode: the timed work is --- @runCheck@ plus forcing the rendered verdict text. Because one check runs --- in single-digit microseconds (below timer noise), every timed section --- here runs the work 'reps' times and divides; the reported value is the --- median of 'samples' such sections. +-- @runCheck@ plus forcing the rendered verdict text. One corpus check takes +-- a few hundred microseconds; every timed section here runs the work 'reps' +-- times and divides, and the reported value is the median of 'samples' such +-- sections, which damps single-shot scheduling jitter. -- * Phase sections time the pipeline's stages against their forced outputs: -- parse (decode + forced re-encode), validate (replay preflight + group -- boundary), check (the six-stage @checkUnitWith@, deep-forced), compile @@ -107,8 +107,8 @@ import Lara.Wire leanBin :: FilePath leanBin = "lean/.lake/build/bin/lara-driver" --- | Repetitions inside one timed section: one corpus check runs in --- single-digit microseconds, below single-shot timer noise. +-- | Repetitions inside one timed section; the section time is divided by this +-- to give the per-check figure. reps :: Int reps = 100 diff --git a/scripts/bench_compare.py b/scripts/bench_compare.py new file mode 100755 index 00000000..26b6ae8c --- /dev/null +++ b/scripts/bench_compare.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Compare the timed runs of one `make bench-container` batch. + +Reads every run directory under the output root whose provenance names the +batch, and reports, for the `check + render, pre-decoded` control row +(`kernel_ns` in bench.json), each run's median across corpus units, the host +load sampled while that run was timed, and the per-unit median and range +across runs. Every run is listed. A run is excluded from the statistics only +for the reasons fixed in advance: its provenance status is not `success`, or +its outputs no longer match the digests the runner recorded. + +The table run is chosen by a rule fixed in advance: sort the included runs by +their control-row median (ties broken by directory name) and take the lower +median, index (n - 1) // 2. + +Usage: bench_compare.py --batch ID [--output-root DIR] [--json PATH] +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +CONTROL = "kernel_ns" +CONTROL_LABEL = "check + render, pre-decoded" + + +class CompareError(RuntimeError): + """A batch that cannot be compared.""" + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def read_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + raise CompareError(f"cannot read {path}: {error}") from error + + +def load_summary(samples: Sequence[Dict[str, Any]]) -> Optional[Dict[str, float]]: + loads = [float(sample["load_1m"]) for sample in samples] + if not loads: + return None + return { + "samples": len(loads), + "min": min(loads), + "median": statistics.median(loads), + "max": max(loads), + } + + +def batch_runs(output_root: Path, batch_id: str) -> List[Path]: + if not output_root.is_dir(): + raise CompareError(f"output root {output_root} is not a directory") + runs = [] + for run_dir in sorted(output_root.iterdir()): + provenance_path = run_dir / "provenance.json" + if not provenance_path.is_file(): + continue + provenance = read_json(provenance_path) + batch = provenance.get("batch") if isinstance(provenance, dict) else None + if isinstance(batch, dict) and batch.get("id") == batch_id: + runs.append(run_dir) + if not runs: + raise CompareError(f"no run directory under {output_root} belongs to batch {batch_id}") + return runs + + +def describe_run(run_dir: Path) -> Dict[str, Any]: + provenance = read_json(run_dir / "provenance.json") + benchmark = provenance.get("benchmark") or {} + record: Dict[str, Any] = { + "run": run_dir.name, + "index": (provenance.get("batch") or {}).get("index"), + "git_rev": (provenance.get("source") or {}).get("git_rev"), + "image": (provenance.get("image") or {}).get("id"), + "cpuset": (provenance.get("cpuset") or {}).get("requested"), + "status": provenance.get("status"), + "load_during_run": load_summary(benchmark.get("load_samples") or []), + "included": False, + "exclusion": None, + } + if provenance.get("status") != "success": + record["exclusion"] = f"status {provenance.get('status')}: {provenance.get('error')}" + return record + recorded = provenance.get("outputs") + if not isinstance(recorded, dict) or not recorded: + record["exclusion"] = "no recorded output digests" + return record + for name, digest in recorded.items(): + path = run_dir / name + if not path.is_file() or sha256_file(path) != digest: + raise CompareError( + f"{run_dir.name}: {name} does not match the digest the runner recorded" + ) + bench = read_json(run_dir / "bench.json") + units = bench.get("units") + if not isinstance(units, list) or not units: + raise CompareError(f"{run_dir.name}: bench.json has no units") + record["units"] = {str(unit["base"]): int(unit[CONTROL]) for unit in units} + record["control_median_ns"] = statistics.median(record["units"].values()) + record["included"] = True + return record + + +def compare(output_root: Path, batch_id: str) -> Dict[str, Any]: + runs = [describe_run(run_dir) for run_dir in batch_runs(output_root, batch_id)] + included = [run for run in runs if run["included"]] + if not included: + raise CompareError(f"batch {batch_id} has no successful run") + revisions = {run["git_rev"] for run in included} + images = {run["image"] for run in included} + if len(revisions) != 1 or len(images) != 1: + raise CompareError(f"batch {batch_id} mixes revisions {revisions} or images {images}") + unit_sets = {tuple(sorted(run["units"])) for run in included} + if len(unit_sets) != 1: + raise CompareError(f"batch {batch_id} runs measured different unit sets") + bases = sorted(included[0]["units"]) + per_unit = [] + for base in bases: + values = [run["units"][base] for run in included] + median = statistics.median(values) + per_unit.append( + { + "base": base, + "median_ns": median, + "min_ns": min(values), + "max_ns": max(values), + "range_pct": 100.0 * (max(values) - min(values)) / median, + } + ) + medians = [run["control_median_ns"] for run in included] + ordered = sorted(included, key=lambda run: (run["control_median_ns"], run["run"])) + table_run = ordered[(len(ordered) - 1) // 2]["run"] + batch_median = statistics.median(medians) + for run in runs: + run.pop("units", None) + return { + "batch": batch_id, + "control_row": CONTROL_LABEL, + "git_rev": revisions.pop(), + "image": images.pop(), + "runs": runs, + "included_runs": len(included), + "control_median_ns": { + "median": batch_median, + "min": min(medians), + "max": max(medians), + "range_pct": 100.0 * (max(medians) - min(medians)) / batch_median, + }, + "per_unit_range_pct": { + "median": statistics.median(unit["range_pct"] for unit in per_unit), + "max": max(unit["range_pct"] for unit in per_unit), + }, + "per_unit": per_unit, + "table_run": table_run, + } + + +def us(ns: float) -> str: + return f"{ns / 1000:.1f}" + + +def render_markdown(result: Dict[str, Any]) -> str: + lines = [ + f"Batch `{result['batch']}` at `{result['git_rev'][:12]}`, image `{result['image']}`.", + f"Control row: {result['control_row']} (µs, median over corpus units).", + "", + "| Run | Pinned CPUs | Status | Control median (µs) | Load during run (min / median / max) |", + "| --- | --- | --- | ---: | --- |", + ] + for run in result["runs"]: + load = run["load_during_run"] + load_text = ( + "-" if load is None else f"{load['min']:.2f} / {load['median']:.2f} / {load['max']:.2f}" + ) + status = "included" if run["included"] else f"excluded: {run['exclusion']}" + control = us(run["control_median_ns"]) if run["included"] else "-" + marker = " (table)" if run["run"] == result["table_run"] else "" + lines.append( + f"| `{run['run']}`{marker} | {run['cpuset'] or '-'} | {status} | {control} | {load_text} |" + ) + summary = result["control_median_ns"] + spread = result["per_unit_range_pct"] + lines += [ + "", + f"Across {result['included_runs']} included runs the control-row median is " + f"{us(summary['median'])} µs (range {us(summary['min'])} to {us(summary['max'])} µs, " + f"{summary['range_pct']:.1f}% of the median). Per unit, the range across runs is " + f"{spread['median']:.1f}% of the unit's median at the median unit and " + f"{spread['max']:.1f}% at most.", + ] + return "\n".join(lines) + "\n" + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--batch", required=True, help="batch id recorded in provenance.json") + parser.add_argument("--output-root", type=Path, default=Path("measurements/bench-runs")) + parser.add_argument("--json", type=Path, help="also write the full comparison as JSON") + args = parser.parse_args(argv) + try: + result = compare(args.output_root, args.batch) + except CompareError as error: + print(f"bench-compare: {error}", file=sys.stderr) + return 1 + if args.json is not None: + args.json.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + sys.stdout.write(render_markdown(result)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/bench_container.py b/scripts/bench_container.py index c02cde3c..36f86f8c 100755 --- a/scripts/bench_container.py +++ b/scripts/bench_container.py @@ -10,10 +10,14 @@ import platform import subprocess import sys +import threading import time from datetime import datetime, timezone from pathlib import Path -from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, TypeVar + + +T = TypeVar("T") WORKFLOW = "Haskell" @@ -158,6 +162,135 @@ def wait_for_quiet( raise QuietWindowInterrupted(events) from error +def run_with_load_samples( + action: Callable[[], T], + samples: List[Dict[str, Any]], + *, + load_average: Callable[[], float], + monotonic: Callable[[], float], + interval: float, +) -> T: + """Run ``action`` while sampling host load into ``samples``. + + One sample is taken before the action starts, one every ``interval`` + seconds while it runs, and one after it returns or raises, so the list + always brackets the timed interval and survives a failed run. + """ + if interval <= 0: + raise BenchError("load sample interval must be positive") + lock = threading.Lock() + + def record() -> None: + sample = {"monotonic_seconds": monotonic(), "load_1m": float(load_average())} + with lock: + samples.append(sample) + + stop = threading.Event() + + def sample_until_stopped() -> None: + while not stop.wait(interval): + record() + + record() + sampler = threading.Thread(target=sample_until_stopped, daemon=True) + sampler.start() + try: + return action() + finally: + stop.set() + sampler.join() + record() + + +def parse_cpu_list(text: str) -> List[int]: + """Parse a Linux CPU list such as ``17``, ``2-3,17`` or the empty string.""" + cpus: List[int] = [] + for part in text.strip().split(","): + part = part.strip() + if not part: + continue + try: + if "-" in part: + low_text, high_text = part.split("-", 1) + low, high = int(low_text), int(high_text) + if low < 0 or high < low: + raise ValueError(part) + cpus.extend(range(low, high + 1)) + else: + cpu = int(part) + if cpu < 0: + raise ValueError(part) + cpus.append(cpu) + except ValueError as error: + raise BenchError(f"invalid CPU list {text!r}") from error + return sorted(set(cpus)) + + +def require_isolated_cpus(requested: str, isolated: str) -> List[int]: + """The requested CPUs, provided every one is in the VM's isolated list. + + Docker accepts ``--cpuset-cpus`` for any CPU that exists, so pinning alone + says nothing about isolation; the guest's own isolated list decides. + """ + cpus = parse_cpu_list(requested) + if not cpus: + raise BenchError("--cpuset-cpus names no CPU") + available = set(parse_cpu_list(isolated)) + shared = [cpu for cpu in cpus if cpu not in available] + if shared: + raise BenchError( + f"--cpuset-cpus {requested} includes CPUs that are not isolated in the " + f"Docker VM ({', '.join(map(str, shared))}); " + f"/sys/devices/system/cpu/isolated reads {isolated.strip()!r}" + ) + return cpus + + +def guest_read_command(image_id: str, path: str) -> List[str]: + return [ + "docker", + "run", + "--rm", + "--platform", + PLATFORM, + "--network", + "none", + "--read-only", + "--entrypoint", + "cat", + image_id, + path, + ] + + +def cpuset_metadata(root: Path, image_id: str, requested: str) -> Dict[str, Any]: + isolated = run_command( + guest_read_command(image_id, "/sys/devices/system/cpu/isolated"), cwd=root + ) + cmdline = run_command(guest_read_command(image_id, "/proc/cmdline"), cwd=root) + cpus = require_isolated_cpus(requested, isolated) + return { + "requested": requested, + "cpus": cpus, + "guest_isolated": isolated, + "guest_cmdline": cmdline, + } + + +def demoted_process_metadata(root: Path, pids: Sequence[int]) -> List[Dict[str, Any]]: + """Name each process the operator demoted with ``taskpolicy -b``. + + The runner records the demotion; it does not perform it, because demoting + another user's or a system process needs privileges the runner should not + hold. + """ + processes = [] + for pid in pids: + command = run_command(["ps", "-o", "comm=", "-p", str(pid)], cwd=root) + processes.append({"pid": pid, "command": command}) + return processes + + def docker_run_command( *, image_id: str, @@ -165,7 +298,9 @@ def docker_run_command( git_sha: str, host_cpu: str, host_ram_bytes: int, + cpuset_cpus: Optional[str] = None, ) -> List[str]: + pinning = [] if cpuset_cpus is None else ["--cpuset-cpus", cpuset_cpus] return [ "docker", "run", @@ -185,6 +320,7 @@ def docker_run_command( f"LARA_BENCH_HOST_CPU={host_cpu}", "-e", f"LARA_BENCH_HOST_RAM_BYTES={host_ram_bytes}", + *pinning, image_id, ] @@ -412,12 +548,37 @@ def parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace: parser.add_argument("--image", help="image tag; defaults to lara-bench:") parser.add_argument("--no-build", action="store_true", help="reuse the named image") parser.add_argument("--output-root", type=Path, default=Path("measurements/bench-runs")) + parser.add_argument( + "--runs", + type=int, + default=1, + help="timed container runs in this batch, each in its own run directory", + ) + parser.add_argument( + "--cpuset-cpus", + help="pin the container to these Docker VM CPUs; every one must be in the " + "VM's isolated list", + ) + parser.add_argument( + "--demoted-pid", + type=int, + action="append", + default=[], + help="record a host process the operator demoted with taskpolicy -b (repeatable)", + ) + parser.add_argument( + "--batch-note", + default="", + help="free-text description of the batch's host conditions, recorded verbatim", + ) return parser.parse_args(argv) -def run_publication(args: argparse.Namespace) -> Path: +def run_publication(args: argparse.Namespace) -> List[Path]: if args.no_build and not args.skip_ci: raise BenchError("--no-build requires --skip-ci; reused images are smoke-only") + if args.runs < 1: + raise BenchError("--runs must be at least 1") root = Path(run_command(["git", "rev-parse", "--show-toplevel"])).resolve() if platform.system() != "Darwin" or platform.machine() != "arm64": raise BenchError("publication runner requires a Darwin/arm64 physical host") @@ -442,9 +603,55 @@ def run_publication(args: argparse.Namespace) -> Path: if not args.no_build: run_command(build_command, cwd=root) image_info = image_metadata(root, image, sha) + cpuset = ( + None + if args.cpuset_cpus is None + else cpuset_metadata(root, str(image_info["id"]), args.cpuset_cpus) + ) + demoted = demoted_process_metadata(root, args.demoted_pid) + batch_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + run_dirs: List[Path] = [] + for index in range(1, args.runs + 1): + run_dirs.append( + run_once( + args, + root=root, + sha=sha, + host=host, + docker=docker, + ci=ci, + image_info=image_info, + build_command=build_command, + batch={ + "id": batch_id, + "index": index, + "runs": args.runs, + "note": args.batch_note, + "demoted_processes": demoted, + }, + cpuset=cpuset, + ) + ) + return run_dirs + +def run_once( + args: argparse.Namespace, + *, + root: Path, + sha: str, + host: Mapping[str, Any], + docker: Mapping[str, Any], + ci: Mapping[str, Any], + image_info: Mapping[str, Any], + build_command: Sequence[str], + batch: Mapping[str, Any], + cpuset: Optional[Mapping[str, Any]], +) -> Path: stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") - run_dir = (root / args.output_root / f"{stamp}-{sha[:12]}").resolve() + suffix = "" if batch["runs"] == 1 else f"-r{batch['index']:02d}" + run_dir = (root / args.output_root / f"{stamp}-{sha[:12]}{suffix}").resolve() try: run_dir.mkdir(parents=True, exist_ok=False) except OSError as error: @@ -453,16 +660,22 @@ def run_publication(args: argparse.Namespace) -> Path: ) from error provenance_path = run_dir / "provenance.json" provenance: Dict[str, Any] = { - "schema": "lara-bench-provenance@1", + "schema": "lara-bench-provenance@2", "status": "preparing", "stage": "quiet-window", "created_at": utc_now(), "source": {"git_rev": sha, "clean": True}, - "ci": ci, - "host": host, - "docker": docker, - "image": image_info, - "build": {"skipped": bool(args.no_build), "command": build_command}, + "ci": dict(ci), + "host": dict(host), + "docker": dict(docker), + "image": dict(image_info), + "build": { + "skipped": bool(args.no_build), + "scope": "batch: built once before run 1; every run of the batch uses this image", + "command": list(build_command), + }, + "batch": dict(batch), + "cpuset": None if cpuset is None else dict(cpuset), "quiet_window": { "threshold_1m": args.load_threshold, "required_seconds": args.quiet_seconds, @@ -496,11 +709,24 @@ def run_publication(args: argparse.Namespace) -> Path: git_sha=sha, host_cpu=str(host["cpu"]), host_ram_bytes=int(host["ram_bytes"]), + cpuset_cpus=None if cpuset is None else str(cpuset["requested"]), ) + load_samples: List[Dict[str, Any]] = [] provenance["stage"] = "benchmark" - provenance["benchmark"] = {"command": command, "started_at": utc_now()} + provenance["benchmark"] = { + "command": command, + "started_at": utc_now(), + "load_sample_interval_seconds": args.sample_interval, + "load_samples": load_samples, + } write_json_atomic(provenance_path, provenance) - run_command(command, cwd=root) + run_with_load_samples( + lambda: run_command(command, cwd=root), + load_samples, + load_average=lambda: os.getloadavg()[0], + monotonic=time.monotonic, + interval=args.sample_interval, + ) provenance["benchmark"]["completed_at"] = utc_now() provenance["outputs"] = validate_outputs(run_dir, expected_git_rev=sha) provenance["status"] = "success" @@ -527,14 +753,15 @@ def run_publication(args: argparse.Namespace) -> Path: def main(argv: Optional[Sequence[str]] = None) -> int: try: - run_dir = run_publication(parse_args(argv)) + run_dirs = run_publication(parse_args(argv)) except BenchError as error: print(f"bench-container: {error}", file=sys.stderr) return 1 except KeyboardInterrupt: print("bench-container: interrupted", file=sys.stderr) return 130 - print(run_dir) + for run_dir in run_dirs: + print(run_dir) return 0 diff --git a/scripts/test_bench_container.py b/scripts/test_bench_container.py index ba211c53..b4024840 100755 --- a/scripts/test_bench_container.py +++ b/scripts/test_bench_container.py @@ -3,17 +3,20 @@ from __future__ import annotations +import hashlib import io import json import os import subprocess import sys import tempfile +import threading import unittest from contextlib import ExitStack, redirect_stderr from pathlib import Path from unittest.mock import patch +from scripts.bench_compare import CompareError, compare from scripts.bench_container import ( BenchError, compact_docker_metadata, @@ -21,7 +24,10 @@ image_metadata, main, parse_args, + parse_cpu_list, + require_isolated_cpus, run_publication, + run_with_load_samples, select_ci_run, validate_outputs, wait_for_quiet, @@ -248,6 +254,170 @@ def test_interrupt_uses_cli_exit_semantics(self) -> None: self.assertIn("bench-container: interrupted", stderr.getvalue()) self.assertNotIn("Traceback", stderr.getvalue()) + def test_batch_records_every_run_with_load_during_the_run(self) -> None: + with tempfile.TemporaryDirectory() as raw_dir: + with ExitStack() as stack: + self.stub_publication_dependencies(stack) + stack.enter_context( + patch("scripts.bench_container.validate_outputs", return_value={}) + ) + stack.enter_context( + patch( + "scripts.bench_container.os.getloadavg", + return_value=(1.25, 1.0, 1.0), + ) + ) + run_dirs = run_publication( + parse_args( + [ + "--skip-ci", + "--no-build", + "--image", + "lara-bench:test", + "--quiet-seconds", + "0", + "--runs", + "3", + "--batch-note", + "spotlight paused", + "--output-root", + raw_dir, + ] + ) + ) + provenances = [ + json.loads((run_dir / "provenance.json").read_text(encoding="utf-8")) + for run_dir in run_dirs + ] + self.assertEqual(len(run_dirs), 3) + self.assertEqual(len({run_dir.name for run_dir in run_dirs}), 3) + self.assertEqual([p["batch"]["index"] for p in provenances], [1, 2, 3]) + self.assertEqual(len({p["batch"]["id"] for p in provenances}), 1) + for provenance in provenances: + self.assertEqual(provenance["status"], "success") + self.assertEqual(provenance["batch"]["note"], "spotlight paused") + self.assertIsNone(provenance["cpuset"]) + samples = provenance["benchmark"]["load_samples"] + self.assertGreaterEqual(len(samples), 2) + self.assertTrue(all(sample["load_1m"] == 1.25 for sample in samples)) + + def test_failed_run_stops_the_batch_and_keeps_its_load_samples(self) -> None: + def command(arguments, cwd=None, env=None): # noqa: ANN001 + if arguments[:2] == ["docker", "run"]: + raise BenchError("container exited 1") + return str(ROOT) + + with tempfile.TemporaryDirectory() as raw_dir: + with ExitStack() as stack: + self.stub_publication_dependencies(stack) + stack.enter_context( + patch("scripts.bench_container.run_command", side_effect=command) + ) + with self.assertRaisesRegex(BenchError, "container exited 1"): + run_publication( + parse_args( + [ + "--skip-ci", + "--no-build", + "--image", + "lara-bench:test", + "--quiet-seconds", + "0", + "--runs", + "3", + "--output-root", + raw_dir, + ] + ) + ) + run_dirs = list(Path(raw_dir).iterdir()) + provenance = json.loads( + (run_dirs[0] / "provenance.json").read_text(encoding="utf-8") + ) + self.assertEqual(len(run_dirs), 1) + self.assertEqual(provenance["status"], "failed") + self.assertEqual(provenance["failed_stage"], "benchmark") + self.assertGreaterEqual(len(provenance["benchmark"]["load_samples"]), 2) + + def test_refuses_to_pin_a_cpu_the_vm_does_not_isolate(self) -> None: + def command(arguments, cwd=None, env=None): # noqa: ANN001 + if arguments[-1] == "/sys/devices/system/cpu/isolated": + return "17" + if arguments[-1] == "/proc/cmdline": + return "isolcpus=17" + return str(ROOT) + + with tempfile.TemporaryDirectory() as raw_dir: + with ExitStack() as stack: + self.stub_publication_dependencies(stack) + stack.enter_context( + patch("scripts.bench_container.run_command", side_effect=command) + ) + with self.assertRaisesRegex(BenchError, "not isolated"): + run_publication( + parse_args( + [ + "--skip-ci", + "--no-build", + "--image", + "lara-bench:test", + "--cpuset-cpus", + "16", + "--output-root", + raw_dir, + ] + ) + ) + self.assertEqual(list(Path(raw_dir).iterdir()), []) + + def test_pinned_run_records_the_guest_isolation_it_checked(self) -> None: + commands = [] + + def command(arguments, cwd=None, env=None): # noqa: ANN001 + commands.append(list(arguments)) + if arguments[-1] == "/sys/devices/system/cpu/isolated": + return "17" + if arguments[-1] == "/proc/cmdline": + return "quiet isolcpus=17" + return str(ROOT) + + with tempfile.TemporaryDirectory() as raw_dir: + with ExitStack() as stack: + self.stub_publication_dependencies(stack) + stack.enter_context( + patch("scripts.bench_container.run_command", side_effect=command) + ) + stack.enter_context( + patch("scripts.bench_container.validate_outputs", return_value={}) + ) + (run_dir,) = run_publication( + parse_args( + [ + "--skip-ci", + "--no-build", + "--image", + "lara-bench:test", + "--quiet-seconds", + "0", + "--cpuset-cpus", + "17", + "--output-root", + raw_dir, + ] + ) + ) + provenance = json.loads((run_dir / "provenance.json").read_text(encoding="utf-8")) + self.assertEqual(provenance["cpuset"]["cpus"], [17]) + self.assertEqual(provenance["cpuset"]["guest_isolated"], "17") + self.assertEqual(provenance["cpuset"]["guest_cmdline"], "quiet isolcpus=17") + timed = [c for c in commands if c[:2] == ["docker", "run"] and "--entrypoint" not in c] + self.assertEqual(len(timed), 1) + self.assertEqual(timed[0][-3:], ["--cpuset-cpus", "17", IMAGE_ID]) + + def test_rejects_an_empty_batch(self) -> None: + with self.assertRaisesRegex(BenchError, "--runs must be at least 1"): + run_publication(parse_args(["--runs", "0"])) + SHA = "a" * 40 IMAGE_ID = "sha256:" + "1" * 64 @@ -367,6 +537,69 @@ def test_timeout_retains_collected_samples(self) -> None: self.assertEqual([event["monotonic_seconds"] for event in events], [0.0, 5.0, 10.0]) +class LoadSamplingTests(unittest.TestCase): + def test_samples_bracket_the_action_and_continue_while_it_runs(self) -> None: + clock = FakeClock() + sampled_during = threading.Event() + calls = [] + + def load() -> float: + calls.append(len(calls)) + if len(calls) >= 3: + sampled_during.set() + return float(len(calls)) + + samples: list[dict[str, object]] = [] + events: list[str] = [] + + def action() -> str: + events.append(f"start after {len(samples)} samples") + self.assertTrue(sampled_during.wait(5), "sampler did not run during the action") + return "done" + + result = run_with_load_samples( + action, samples, load_average=load, monotonic=clock.monotonic, interval=0.001 + ) + self.assertEqual(result, "done") + self.assertEqual(events, ["start after 1 samples"]) + self.assertGreaterEqual(len(samples), 3) + self.assertEqual([sample["load_1m"] for sample in samples], sorted(s["load_1m"] for s in samples)) + + def test_failed_action_still_gets_a_closing_sample(self) -> None: + samples: list[dict[str, object]] = [] + + def action() -> None: + raise BenchError("boom") + + with self.assertRaisesRegex(BenchError, "boom"): + run_with_load_samples( + action, samples, load_average=lambda: 2.0, monotonic=lambda: 0.0, interval=60 + ) + self.assertEqual(len(samples), 2) + + +class CpuIsolationTests(unittest.TestCase): + def test_parses_linux_cpu_lists(self) -> None: + self.assertEqual(parse_cpu_list("17"), [17]) + self.assertEqual(parse_cpu_list("2-3,17"), [2, 3, 17]) + self.assertEqual(parse_cpu_list(""), []) + self.assertEqual(parse_cpu_list("\n"), []) + for bad in ["a", "3-1", "-1", "1-x"]: + with self.subTest(bad=bad): + with self.assertRaisesRegex(BenchError, "invalid CPU list"): + parse_cpu_list(bad) + + def test_accepts_only_isolated_cpus(self) -> None: + self.assertEqual(require_isolated_cpus("17", "17"), [17]) + self.assertEqual(require_isolated_cpus("16-17", "16-17"), [16, 17]) + with self.assertRaisesRegex(BenchError, "not isolated.*16"): + require_isolated_cpus("16-17", "17") + with self.assertRaisesRegex(BenchError, "not isolated"): + require_isolated_cpus("17", "") + with self.assertRaisesRegex(BenchError, "names no CPU"): + require_isolated_cpus(",", "17") + + class DockerCommandTests(unittest.TestCase): def test_runtime_is_networkless_read_only_and_prebuilt(self) -> None: command = docker_run_command( @@ -462,5 +695,84 @@ def test_rejects_missing_output(self) -> None: validate_outputs(Path(raw_dir), expected_git_rev=SHA) +def write_run( + root: Path, + name: str, + *, + batch: str = "B", + status: str = "success", + kernels: dict[str, int] | None = None, + rev: str = SHA, +) -> Path: + run_dir = root / name + run_dir.mkdir() + provenance: dict[str, object] = { + "status": status, + "error": None if status == "success" else "container exited 1", + "source": {"git_rev": rev}, + "image": {"id": IMAGE_ID}, + "batch": {"id": batch, "index": 1}, + "cpuset": None, + "benchmark": {"load_samples": [{"load_1m": 1.0}, {"load_1m": 3.0}]}, + } + if status == "success": + units = [{"base": base, "kernel_ns": ns} for base, ns in (kernels or {}).items()] + (run_dir / "bench.json").write_text(json.dumps({"units": units}), encoding="utf-8") + provenance["outputs"] = {"bench.json": file_sha256(run_dir / "bench.json")} + (run_dir / "provenance.json").write_text(json.dumps(provenance), encoding="utf-8") + return run_dir + + +def file_sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +class BatchComparisonTests(unittest.TestCase): + def test_reports_every_run_and_picks_the_lower_median_run(self) -> None: + with tempfile.TemporaryDirectory() as raw_dir: + root = Path(raw_dir) + write_run(root, "r1", kernels={"u1": 200_000, "u2": 220_000}) + write_run(root, "r2", kernels={"u1": 210_000, "u2": 230_000}) + write_run(root, "r3", kernels={"u1": 190_000, "u2": 200_000}) + write_run(root, "r4", kernels={"u1": 400_000, "u2": 400_000}) + write_run(root, "r5", status="failed") + write_run(root, "other", batch="C", kernels={"u1": 1, "u2": 1}) + result = compare(root, "B") + self.assertEqual([run["run"] for run in result["runs"]], ["r1", "r2", "r3", "r4", "r5"]) + self.assertEqual(result["included_runs"], 4) + excluded = [run for run in result["runs"] if not run["included"]] + self.assertEqual([run["run"] for run in excluded], ["r5"]) + self.assertIn("container exited 1", excluded[0]["exclusion"]) + # Run medians 210k, 220k, 195k, 400k; sorted r3, r1, r2, r4; lower median r1. + self.assertEqual(result["table_run"], "r1") + self.assertEqual(result["control_median_ns"]["median"], 215_000) + self.assertEqual(result["control_median_ns"]["min"], 195_000) + self.assertEqual(result["control_median_ns"]["max"], 400_000) + u1 = next(unit for unit in result["per_unit"] if unit["base"] == "u1") + self.assertEqual((u1["min_ns"], u1["max_ns"], u1["median_ns"]), (190_000, 400_000, 205_000)) + self.assertEqual(result["runs"][0]["load_during_run"]["max"], 3.0) + + def test_refuses_outputs_changed_after_the_run(self) -> None: + with tempfile.TemporaryDirectory() as raw_dir: + root = Path(raw_dir) + run_dir = write_run(root, "r1", kernels={"u1": 1}) + (run_dir / "bench.json").write_text(json.dumps({"units": []}), encoding="utf-8") + with self.assertRaisesRegex(CompareError, "does not match the digest"): + compare(root, "B") + + def test_refuses_a_batch_mixing_revisions(self) -> None: + with tempfile.TemporaryDirectory() as raw_dir: + root = Path(raw_dir) + write_run(root, "r1", kernels={"u1": 1}) + write_run(root, "r2", kernels={"u1": 1}, rev="b" * 40) + with self.assertRaisesRegex(CompareError, "mixes revisions"): + compare(root, "B") + + def test_refuses_an_unknown_batch(self) -> None: + with tempfile.TemporaryDirectory() as raw_dir: + with self.assertRaisesRegex(CompareError, "belongs to batch"): + compare(Path(raw_dir), "B") + + if __name__ == "__main__": unittest.main()