omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
GitHub aien-dev/omega-mv#270 (code only)
Apply it
git checkout -b patch-4cb5f6b7efa2a264 00f54b6b19e5e64e8947aea2890e688511d897a8 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/4cb5f6b7efa2a264.patch | git am
Provenance
github-import 1
aien-dev/omega-mv
270
3d4a6b5770bc53b2eaa9ab896cf6a3d2fd953727
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":270,"url":"https://github.com/aien-dev/omega-mv/pull/270","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:04Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 091c4fa26..182fcb709 100644 --- a/.crumb +++ b/.crumb @@ -52,7 +52,7 @@ }, { "digest": "e555caa4954d4dde3e499f37df8c9af2efc41cf349dc8096273b0e062dd07a01", - "last_commit": "5f18839", + "last_commit": "00f54b6", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -63,8 +63,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "322e59de081336c07865c29e4143728f3b25333ecd102f662a319074fca76f5c", - "last_commit": "5f18839", + "digest": "566d430880c69205dd89c06d645f5030442c526a97ce3e2c386276c282792e9f", + "last_commit": "1fb209a", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -87,33 +87,33 @@ "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "0f3a63e432e9beed1a353d1570bc416f0bae07e99a45be15b0b885cbbedfb8ea", - "last_commit": "5f18839", + "digest": "8e9dd6f8117c615273c291427db9ad14abaa907bc05741145bb9892706f68efa", + "last_commit": "1fb209a", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "e9bfa25f9d911bbcb636a73ecedea1df90b2a7e0ff9782fb43cf794d8aecdb4c", - "last_commit": "5f18839", + "digest": "e96dec62800dc6dae755ebe10eacfedcb0959e29e00a3540284cb585f8f9716f", + "last_commit": "1fb209a", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "49be2149359521a3a0f87c12aa31e565c6575309bd099aff8daa216b25052ed6", - "last_commit": "5f18839", + "last_commit": "00f54b6", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:4494a74564f7c8c8c7041f9583c2fa9b03e0fb7039e275587528de1ec291f477", - "compiled_at": "2026-10-04T18:38:56Z", + "children_root": "sha256:0d2e5faff3d6519826a4922d03e6258a03c42792caee91a6a4bc0d6cba17dfa2", + "compiled_at": "2026-10-04T18:45:19Z", "compiler": "crumb-compile/1", - "digest": "sha256:1f47bad7815a9be11b9dc20381e3c58441e331a7a29759fb2363e1dc3ea600c8", - "evidence_files": 1287, - "evidence_root": "sha256:5e4b538bcd3cc124b345b1f12b0953c988f327cf3c3e9fc989cdb02cdb2dcd3e", - "files": 3039, - "generated_at_commit": "c8e9d2e8e293079f197382ad7dd116113dd21939", - "source_tree": "sha256:f8b6cb55822b0aba92caf34688c984c5ed578085b73730e32a8c15b44bb66ebe" + "digest": "sha256:b0b3f7ca6dda9afa4b09fa49f49e397ecfce7737dfd34ea426bcc2b905364232", + "evidence_files": 1288, + "evidence_root": "sha256:5e3386545c3742835ee2e90f3c06e6bfeeb9725fb51664e6c25cb59822356642", + "files": 3043, + "generated_at_commit": "393fa208a1a662de5ccb6c877d8d7c8b22fc1bf7", + "source_tree": "sha256:499774e2016130a9904f3fda0dbe4c7c852fa5b6109b60f44bde780b49cb1eb1" }, "owner_lane": "", "provenance": { diff --git a/evidence/DUAL/3a-jspace-tap/receipt.md b/evidence/DUAL/3a-jspace-tap/receipt.md new file mode 100644 index 000000000..d0f3fc935 --- /dev/null +++ b/evidence/DUAL/3a-jspace-tap/receipt.md @@ -0,0 +1,274 @@ +# DUAL-3a receipt: read-only observation tap at decision site `jspace.residency` + +Lane: DUAL-3a (ADR 0031 section 7.3 and section 8 row DUAL-3; `DUAL_CURRENT_STATE.md` slice 5). +Repository: aien-dev/omega. Branch `dual/3a-jspace-tap`. +Host only (CPU); no GPU, no chip test touched. + +| Field | Value | +|---|---| +| Base (GitHub main at clone, re-fetched) | `cb7cc216147664549484fcca8e8ceadbd6f6cdbf` | +| Candidate, implementation commit | `9f78d35` (parent `cb7cc216`) | +| Candidate, final | the commit carrying this receipt (PR head) | +| Working tree at each run | clean, `git status --short` empty (section 6) | +| Compiler | `gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0` | +| Flags, tap suite | `-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -pthread`; ASan/UBSan leg adds `-O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all` | +| Flags, existing suite | repository `CFLAGS` (`-std=gnu11 -Wall -Wextra -Werror -MMD -MP -D_GNU_SOURCE -O2 ...`) with `PHYSICS_DIR=$HOME/workspace/physics` | +| Verdict | **DUAL-3a tap IMPLEMENTED; DUAL_ADVISORY_SCHEDULER NOT CLAIMED** | + +## 1. What changed + +`src/runtime/rx_jspace.h`, `src/runtime/rx_jspace.c` only (production). Decision changes: none. + +- `choose()` is now a wrapper over `decide()`, a pure extraction of the same body + with its working set exposed (the alternatives built, in build order, each + alternative's score when it frees bytes, the cheapest score). Same conditions, + same arithmetic, same strict `<` tie rule, same keep test. The alternative + table literal is untouched; scores go to a side array. +- `js_forge_enforce` / `enforce_u`: one NULL check per decision selects + `observed_u()` when `s->dual_observer` is set, else `choose()` as before. +- `observed_u()` makes the same `decide()` call, builds one + `JsDualObservation`, encodes it canonically, digests it, hands the `const` + record to the observer and returns the chooser's own local result. The + observer cannot change the decision by type; writing into the record (a + copy) changes nothing (scenario `record-tamper`). +- `js_dual_set_observer(JsSpace *, JsDualObserver, const void *ctx)`; default + NULL = today's behaviour; `dual_seq` advances only while an observer is set. +- `js_dual_observation_encode()`: canonical little-endian layout. +- No limit, error path, `JsPolicyReport` field, pruning or externalization + changed. No wall clock anywhere in the record. + +## 2. Record schema (version 1) + +Kind byte `0xD3`, version `1`, digest domain `omega.dual.site.jspace_residency.v1`, +decision-site id `jspace.residency`. Canonical encoding is 302 bytes, fixed +little-endian layout, kind and version first; `digest = SHA-256(domain || 0x00 || canonical bytes)`. + +| Offset | Bytes | Field | +|---|---|---| +| 0 | 1 | kind `0xD3` | +| 1 | 1 | version `1` | +| 2 | 1 | site id length (16) | +| 3 | 16 | site id `jspace.residency` | +| 19 | 8 | seq (u64, monotonically increasing per space) | +| 27 | 8 | pressure (f64 bits; the value the chooser used: `1e9` or `1e3`) | +| 35 | 1 | pressure case: 1 = CAPACITY (total residency over budget, stays hard), 2 = SOFT (hot arena over half the budget) | +| 36 | 1 | allow_move | +| 37 | 1 | chosen action (`JsAction`; 8 = keep) | +| 38 | 1 | number of priced alternatives | +| 39 | 4 x 34 | alternatives in chooser order MOVE, COMPRESS, SPILL, EVICT: action u8, status u8 (0 inadmissible, 1 built but frees nothing, 2 priced), now_ns f64, later_ns f64, freed_bytes f64, score f64 | +| 175 | 8 | best score (cheapest priced; 0 when none) | +| 183 | 8 | keep threshold = pressure x retain_ns_per_byte | +| 191 | 8 | expected reads | +| 199 | 4 | realization slot (`JsRealId.slot`) | +| 203 | 8 | realization generation (`JsRealId.gen`) | +| 211 | 3 | realization type, placement, recipe | +| 214 | 16 | unit bytes, held (resident) bytes | +| 230 | 8 | holders u32, refs u32 | +| 238 | 8 | last_use (J-Space logical clock) | +| 246 | 32 | semantic state id | +| 278 | 24 | budget bytes, resident bytes, hot-arena bytes at the instant of the decision | + +## 3. R16 loop-inventory rule and how it is met + +Rule (spec/r16-orchestrator-retirement.md section 4; scanner +`tools/r16_loop_inventory.c`, `--patterns`): every `while(`/`for(`/`do{` in a +tracked `.c/.h/.rs` file is a site when it is unbounded (`while(1)`, `for(;;)`, +...) or its condition/body contains a wait word (`sleep poll recv heartbeat tick +dispatch schedule orchestrate turn pulse yield epoll`), or when a line names +`run_until_complete`, `max_steps`, `max_turns`. New code under `src/runtime/` +must add no site. + +Check: `./tools/r16_loop_inventory.sh` before: `sites=387 unclassified=60` +(pre-existing drift in other repositories, unrelated), zero sites in +`src/runtime/rx_jspace.c`. After (new test files tracked): `sites=387 +unclassified=60`, zero sites in `src/runtime/rx_jspace.c`, +`tests/runtime/rx_dual_jspace_tap.c`, `tests/runtime/rx_dual_jspace_tap_bench.c`. +Every new loop is bounded and contains no wait word; the tap polls nothing, +sleeps nowhere and sequences nothing. + +## 4. Pre-registered benchmark thresholds + +Workload (`tests/runtime/rx_dual_jspace_tap_bench.c`, public API only, in +`9f78d35`): fan-out 256 branches over a depth-4 root, 4096-byte units, fixed +`JsCosts`, 40 rounds per trial, each round two timed `js_forge_enforce` calls +(SOFT case at budget 3/2 of residency, CAPACITY case at budget 1/2), 7 trials +per leg, legs interleaved, medians reported. Three legs: base commit +`rx_jspace.c` (observer absent from the code), candidate with observer NULL, +candidate with a recording observer that encodes every record and folds its +digest. + +- T1 (cost when off): median wall of candidate/observer=NULL within +-10 % of + the base commit's median. Below -10 % is noise, not a win claim. +- T2 (cost when on): added nanoseconds per record = (median on - median off) / + records <= 10 000 ns. +- T3 (bookkeeping): records emitted == decisions considered; bytes emitted == + 302 x records. +- The on/off wall ratio is reported as information, not a bar: the tap is off + in production and the per-decision work in this synthetic workload is a few + hundred nanoseconds, so the ratio measures SHA-256 against memcpy. + +A miss is recorded as FAIL in section 6 and not re-run silently. + +**Pre-registration caveat (honest record).** This section was written to this +file and staged before the benchmark ran, and the implementation commit +`9f78d35` was meant to carry it. It did not: `evidence/DUAL/` was gone from +the working tree and the index by the time that commit was made (cause +UNKNOWN; `crumb compile` was tested afterwards and does not remove it; no +Makefile rule touches `evidence/`). The thresholds were therefore written +before the run but first committed after it, in the commit carrying this +receipt. The workload and the bench program were committed before the run in +`9f78d35`; the threshold numbers rest on this statement. A reader who wants +a stronger pre-registration should treat T1-T3 as declared-then-run, not +committed-then-run. + +## 5. Tests and commands + +### 5.1 Existing suite covering rx_jspace.c + +`make test-jspace-prod PHYSICS_DIR=$HOME/workspace/physics` + +- before (base `cb7cc21`): `checks=40376 failed=0`, `M20_JSPACE_PROD=PASS` +- after (`9f78d35`): `checks=40376 failed=0`, `M20_JSPACE_PROD=PASS` + +Other targets that compile rx_jspace.c: + +- `build/rx_branch_reuse`: builds after the change (not run: it is the + OMEGA_BRANCH_STATE_REUSE gate with energy counters and 128 forked + processes, out of scope for a host-only slice). +- `build/rx_compose_test` (with `AIENOS_LOCK_REPO=$HOME/workspace/dual/aienos`): + builds after the change, exit 0 (not run). +- `rx_compose_living` / R13 living and C4 requalification binaries: not built + (chip-side or long-running gates; out of scope). + +### 5.2 New targets (`mk/dual_jspace_tap.mk`, not part of `all` or `test`) + +`make test-dual-3a` = purity + hygiene + parity (plain and ASan/UBSan) + hostile. + +Parity suite `tests/runtime/rx_dual_jspace_tap.c` (includes `rx_jspace.c` +as one translation unit so the reference oracle can call the static cost +helpers). Per scenario three legs: silent, observer A, observer B. Asserted: +identical `js_forge_enforce` return codes, identical `JsPolicyReport`, +identical `JsStats`, identical final space digest (every branch, unit, +placement, extent, content check, then full content digests); A and B record +streams byte-identical; records == considered; seq 1..n; 302 bytes each; +digest recomputed equal; chosen == chooser rule over the record's own +alternatives; chosen == the placement transition that realization (slot, +generation) underwent in the silent run (the failed last decision of an +error-terminated round excepted, and asserted as such); pressure value and +case consistent with the recorded budget and residency. + +What "identical sequence of chosen actions" means here: the silent run +exposes no per-decision sequence (that is the point of the tap), so sequence +identity is proven per realization against the silent run (every record's +chosen action equals what the silent run did to that very realization, keyed +by slot and generation) and as a byte-identical record stream between the two +observer legs. + +Scenarios: under-budget (0 records), soft-hot-arena (1e3), over-total-capacity +(1e9, then SOFT in the same call once total residency is back under budget), +ties (COMPRESS == EVICT exactly, first built wins), exactly-at-budget, +one-byte-below, one-byte-above, spill-exhaustion (`max_spill_bytes` = 2 units, +rc `JS_ERR_FULL` (-2) in both legs), evict-drain (budget 0), fanout-500 (and +32 in the others), rep-null, record-tamper (observer writes into the const +record: decisions unchanged). Pure extraction: 1752 decisions over 3 cost sets +x 4 pressures x 2 allow_move on mixed placements, `choose()` == verbatim +pre-tap body, 0 mismatches; `js_forge_choose` agrees as well. + +Result: `DUAL_3A_JSPACE_TAP_PARITY=PASS (failures=0)` in the plain and the +ASan/UBSan build (no leak, no UB report). + +### 5.3 Negative control (REQUIRED) + +`make test-dual-jspace-tap-hostile` builds the same suite with +`-DDUAL_TAP_HOSTILE_TEST`: the leg-A observer casts its ctx to the space and +sets `costs.retain_ns_per_byte = 0` on its third record, so the chooser keeps +everything afterwards. Output (abridged): + +``` +DUAL-3a jspace.residency tap: parity [HOSTILE NEGATIVE CONTROL: the observer mutates the space; this run must FAIL] + FAIL: soft: a record chose something other than MOVE + FAIL: soft-hot-arena round 0: JsPolicyReport differs with observer + FAIL: soft-hot-arena round 1: JsPolicyReport differs with observer + FAIL: soft-hot-arena: JsStats differ with observer (resident silent 151552 A 151552 B 151552) + FAIL: soft-hot-arena: final space digest differs with observer + ... (2035 FAIL lines in all, across every scenario, including per-realization + "observer saw keep, silent run did move on slot N" lines) +DUAL_3A_JSPACE_TAP_PARITY=FAIL (failures=2035) +test-dual-jspace-tap-hostile: hostile observer detected (parity suite failed as required) +``` + +The normal build has no such seam: `grep -rn DUAL_TAP_HOSTILE src/` finds +nothing (`make dual-jspace-tap-hygiene`). An earlier hostile variant that +raised the retain price a million-fold was found ineffective (every +alternative was already far below the keep threshold, so no decision moved and +only 1 assertion fired); it was replaced by the retain = 0 variant before the +implementation commit. Recorded so the negative control is known to be a real +one. + +### 5.4 Purity + +`make dual-jspace-tap-purity`: `nm -u` on `rx_jspace.o` matches none of +`aienos_cap_`, `rx_gen_`, `aegis`. (The tap is inside rx_jspace.c; the object +was also clean before the change.) + +## 6. Run log (in order; nothing edited after the fact) + +### 6.1 Implementation commit + +`9f78d35` on `dual/3a-jspace-tap` (parent `cb7cc216`), working tree clean +(`git status --short | wc -l` = 0) when the benchmark below started. See the +section 4 caveat about the receipt file. + +### 6.2 Existing and new suites at `9f78d35` + +- `make test-jspace-prod PHYSICS_DIR=$HOME/workspace/physics`: `checks=40376 failed=0`, `M20_JSPACE_PROD=PASS` +- `make test-dual-3a`: purity PASS, hygiene PASS, parity PASS (plain and ASan/UBSan, `failures=0`), hostile detected (`failures=2035`, exit 1 as required) +- `./tools/r16_loop_inventory.sh`: `sites=387 unclassified=60` before and after (pre-existing cross-repository drift; zero sites in the touched files) +- `make build/rx_compose_test PHYSICS_DIR=... AIENOS_LOCK_REPO=$HOME/workspace/dual/aienos`: exit 0 + +### 6.3 Benchmark (`make bench-dual-jspace-tap`, wall clock, medians of 7 trials) + +Run 1 (the pre-registered run): + +``` +bench[base] observer=NULL median_wall_ns=2520658 decisions=5410 records=0 bytes=0 (rounds 40, trials 7, fanout 256, unit 4096) +bench[tap] observer=NULL median_wall_ns=2510132 decisions=5410 records=0 bytes=0 (rounds 40, trials 7, fanout 256, unit 4096) +bench[tap] observer=record median_wall_ns=13637213 decisions=5410 records=5410 bytes=1633820 +bench[tap] ratio_on_off=5.433 added_ns_per_record=2056.8 records_equal_decisions=yes +``` + +Run 2 (repeated once, for noise; not used to pick a result): + +``` +bench[base] observer=NULL median_wall_ns=2498835 ... +bench[tap] observer=NULL median_wall_ns=2488819 ... +bench[tap] observer=record median_wall_ns=13628270 decisions=5410 records=5410 bytes=1633820 +bench[tap] ratio_on_off=5.476 added_ns_per_record=2059.0 records_equal_decisions=yes +``` + +| Threshold | Measured (run 1) | Verdict | +|---|---|---| +| T1 observer NULL within +-10 % of base | 2 510 132 / 2 520 658 = -0.42 % (run 2: -0.40 %) | PASS | +| T2 added ns per record <= 10 000 | 2 056.8 ns (run 2: 2 059.0) | PASS | +| T3 records == decisions, bytes == 302 x records | 5410 == 5410; 1 633 820 == 302 x 5410 | PASS | +| ratio on/off (information only, not a bar) | 5.43x (run 2: 5.48x) | reported | + +Reading: with the observer off the change costs nothing measurable (T1). With +a recording observer every decision pays about 2.1 microseconds, almost all +of it the plain-C SHA-256 over 302 + 37 bytes; on this synthetic workload a +decision itself is about 0.46 microseconds (memcpy-sized moves and frees), so +the ratio is large while the absolute cost is small. The ratio is what a +DUAL-3b campaign must budget for when it turns the tap on; it is not a +production cost today because production has no observer. + +## 7. Limits + +- Host only, synthetic workload, fixed costs; no claim about calibrated + costs, real workloads or GPU residency. +- The record is this site's own format (kind `0xD3`, version 1). The DUAL + record module (DUAL-0a, not merged) will reference these digests; no + dependency on it was taken. +- `rx_branch_reuse`, `rx_compose_test` were built, not run. +- `DUAL_ADVISORY_SCHEDULER` (DUAL-3 exit) is not claimed: no + `DualRecommendation`, no pre-registered workload set, no + recommendation-versus-actual analysis. This slice is the tap only. diff --git a/mk/.crumb b/mk/.crumb index b8591e3d9..c9b3fb4ad 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T18:38:56Z", + "compiled_at": "2026-10-04T18:45:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:322e59de081336c07865c29e4143728f3b25333ecd102f662a319074fca76f5c", + "digest": "sha256:566d430880c69205dd89c06d645f5030442c526a97ce3e2c386276c282792e9f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 51, - "generated_at_commit": "3bebcc68321fcc876b88df129f41d6190411a926", - "source_tree": "sha256:bd6e0dd0b4f8b32551e3c35f14fc530b77bd33fbb53fb9c4ad61b13d6ae04f13" + "files": 52, + "generated_at_commit": "00f54b6b19e5e64e8947aea2890e688511d897a8", + "source_tree": "sha256:e29b35006332b572af186fdd10bdef7ca6a8531766b44d075485e7ded46be9df" }, "owner_lane": "", "provenance": { diff --git a/mk/dual_jspace_tap.mk b/mk/dual_jspace_tap.mk new file mode 100644 index 000000000..1172b740e --- /dev/null +++ b/mk/dual_jspace_tap.mk @@ -0,0 +1,80 @@ +# DUAL-3a: read-only observation tap at decision site "jspace.residency" +# (ADR 0031 section 7.3; src/runtime/rx_jspace.c js_forge_enforce). +# Not part of `all` or `test`. Host only; no GPU. +# +# test-dual-jspace-tap parity suite, plain + ASan/UBSan builds +# test-dual-jspace-tap-hostile negative control: a hostile observer mutates the +# space through its ctx; the parity suite must FAIL +# dual-jspace-tap-purity nm -u on rx_jspace.o: no aienos_cap_*, rx_gen_*, aegis +# dual-jspace-tap-hygiene the hostile seam exists in tests only (grep src/) +# bench-dual-jspace-tap observer NULL vs recording observer vs the base +# commit's rx_jspace.c (DJT_BASE_SHA), same workload +# test-dual-3a purity + hygiene + parity + hostile +ifndef DUAL_JSPACE_TAP_MK +DUAL_JSPACE_TAP_MK := 1 +.PHONY: test-dual-jspace-tap test-dual-jspace-tap-hostile dual-jspace-tap-purity \ + dual-jspace-tap-hygiene bench-dual-jspace-tap test-dual-3a +DJT_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -pthread +DJT_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all +DJT_DIR = $(OUT_DIR)/tests-dual-jspace-tap +DJT_BASE_SHA ?= cb7cc216147664549484fcca8e8ceadbd6f6cdbf +DJT_JSPACE = src/runtime/rx_jspace.c src/runtime/rx_jspace.h src/runtime/aien_machine_id.h src/sha256.h +DJT_TEST = tests/runtime/rx_dual_jspace_tap.c +DJT_BENCH = tests/runtime/rx_dual_jspace_tap_bench.c + +# The parity test includes rx_jspace.c (reference oracle needs its statics). +$(DJT_DIR)/rx_dual_jspace_tap: $(DJT_TEST) $(DJT_JSPACE) src/sha256.c + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) -o $@ $(DJT_TEST) src/sha256.c -lm +$(DJT_DIR)/rx_dual_jspace_tap_asan: $(DJT_TEST) $(DJT_JSPACE) src/sha256.c + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) $(DJT_ASAN) -o $@ $(DJT_TEST) src/sha256.c -lm +$(DJT_DIR)/rx_dual_jspace_tap_hostile: $(DJT_TEST) $(DJT_JSPACE) src/sha256.c + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) -DDUAL_TAP_HOSTILE_TEST -o $@ $(DJT_TEST) src/sha256.c -lm + +test-dual-jspace-tap: $(DJT_DIR)/rx_dual_jspace_tap $(DJT_DIR)/rx_dual_jspace_tap_asan + ./$(DJT_DIR)/rx_dual_jspace_tap + ./$(DJT_DIR)/rx_dual_jspace_tap_asan + @echo "test-dual-jspace-tap: parity with and without the observer, plain and ASan/UBSan" + +test-dual-jspace-tap-hostile: $(DJT_DIR)/rx_dual_jspace_tap_hostile + @if ./$(DJT_DIR)/rx_dual_jspace_tap_hostile; then \ + echo "test-dual-jspace-tap-hostile: a hostile observer changed decisions and went UNDETECTED"; exit 1; fi + @echo "test-dual-jspace-tap-hostile: hostile observer detected (parity suite failed as required)" + +$(DJT_DIR)/rx_jspace.o: $(DJT_JSPACE) + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) -c -o $@ src/runtime/rx_jspace.c +dual-jspace-tap-purity: $(DJT_DIR)/rx_jspace.o + @if nm -u $< | grep -E 'aienos_cap_|rx_gen_|aegis'; then \ + echo "rx_jspace.o references an authority or promotion symbol"; exit 1; fi + @echo "dual-jspace-tap-purity: rx_jspace.o references no aienos_cap_*, rx_gen_* or aegis symbol" + +dual-jspace-tap-hygiene: + @if grep -rn 'DUAL_TAP_HOSTILE' src/ ; then \ + echo "the hostile test seam leaked into src/"; exit 1; fi + @echo "dual-jspace-tap-hygiene: DUAL_TAP_HOSTILE appears nowhere under src/" + +# Benchmark: the base commit's rx_jspace.c/.h are extracted next to each other +# so its own #include "rx_jspace.h" resolves to the old header. +DJT_BASE_DIR = $(DJT_DIR)/base-$(DJT_BASE_SHA) +$(DJT_BASE_DIR)/rx_jspace.c: + @mkdir -p $(DJT_BASE_DIR) + git show $(DJT_BASE_SHA):src/runtime/rx_jspace.c > $@ + git show $(DJT_BASE_SHA):src/runtime/rx_jspace.h > $(DJT_BASE_DIR)/rx_jspace.h + git show $(DJT_BASE_SHA):src/runtime/aien_machine_id.h > $(DJT_BASE_DIR)/aien_machine_id.h +$(DJT_DIR)/rx_dual_jspace_tap_bench_base: $(DJT_BENCH) $(DJT_BASE_DIR)/rx_jspace.c src/sha256.c + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) -DDUAL_TAP_BENCH_BASE -I$(DJT_BASE_DIR) -o $@ $(DJT_BENCH) $(DJT_BASE_DIR)/rx_jspace.c src/sha256.c -lm +$(DJT_DIR)/rx_dual_jspace_tap_bench: $(DJT_BENCH) $(DJT_JSPACE) src/sha256.c + @mkdir -p $(DJT_DIR) + $(CC) $(DJT_CFLAGS) -o $@ $(DJT_BENCH) src/runtime/rx_jspace.c src/sha256.c -lm + +bench-dual-jspace-tap: $(DJT_DIR)/rx_dual_jspace_tap_bench_base $(DJT_DIR)/rx_dual_jspace_tap_bench + ./$(DJT_DIR)/rx_dual_jspace_tap_bench_base + ./$(DJT_DIR)/rx_dual_jspace_tap_bench + +test-dual-3a: dual-jspace-tap-purity dual-jspace-tap-hygiene test-dual-jspace-tap test-dual-jspace-tap-hostile + @echo "test-dual-3a: DUAL-3a tap implemented; DUAL_ADVISORY_SCHEDULER not claimed" +endif diff --git a/src/.crumb b/src/.crumb index 91ed38273..2f84e2beb 100644 --- a/src/.crumb +++ b/src/.crumb @@ -92,7 +92,7 @@ }, { "digest": "945ae745a338467614bee287efb628f38f53ad83e4842c1a7fbf7d0b91a8da57", - "last_commit": "", + "last_commit": "00f54b6", "name": "dual_experiment", "purpose": "DUAL applicability experiment library (ARCH-0031 offline evidence lane): deterministic discrete " }, @@ -133,7 +133,7 @@ "purpose": "Directory src/polyglot. Purpose not yet described by a human." }, { - "digest": "8c39d0297ac6c935fb1523cca42272afb9ac38e88d5a49f0f0f0858f0f1cab3e", + "digest": "779e416daad95fc928a9217a06a2897d29930df83b61423d2496fb71f7c42355", "last_commit": "f523edd", "name": "runtime", "purpose": "Directory src/runtime. Purpose not yet described by a human." @@ -169,15 +169,15 @@ "purpose": "Directory src/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:012a29562eacfedf192c3784423554a0e6bb28432e32d1c4b36b24dd9d7884f0", - "compiled_at": "2026-10-04T18:38:56Z", + "children_root": "sha256:607467f8ea6e425bf33f7a0df65a411055a569e302b8127ab84822a0b4559109", + "compiled_at": "2026-10-04T18:45:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:0f3a63e432e9beed1a353d1570bc416f0bae07e99a45be15b0b885cbbedfb8ea", + "digest": "sha256:8e9dd6f8117c615273c291427db9ad14abaa907bc05741145bb9892706f68efa", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 401, - "generated_at_commit": "3bebcc68321fcc876b88df129f41d6190411a926", - "source_tree": "sha256:e2650d5adf6e6892199cd649097d7c347bf6240a1b743c79431d744358ede5a0" + "generated_at_commit": "00f54b6b19e5e64e8947aea2890e688511d897a8", + "source_tree": "sha256:5613ea31519d6c5e879b868b3b0beee43e6afa8199bd6e4d9fe48b2ecc18a7ff" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/.crumb b/src/runtime/.crumb index 2b9f40978..2a30739d3 100644 --- a/src/runtime/.crumb +++ b/src/runtime/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:12:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:8c39d0297ac6c935fb1523cca42272afb9ac38e88d5a49f0f0f0858f0f1cab3e", + "digest": "sha256:779e416daad95fc928a9217a06a2897d29930df83b61423d2496fb71f7c42355", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 59, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:f0f9272607f2cf9892a2f84c97cebcf67fe147140a347d775e83a2ec4daba5ba" + "generated_at_commit": "cb7cc216147664549484fcca8e8ceadbd6f6cdbf", + "source_tree": "sha256:2f806e4c07c8f93a4e613c242c515990f8193fdafd41f8ba85e30bcc5f795393" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/rx_jspace.c b/src/runtime/rx_jspace.c index 7b00125e5..3621abbc3 100644 --- a/src/runtime/rx_jspace.c +++ b/src/runtime/rx_jspace.c @@ -954,16 +954,28 @@ static double expected_reads(const JsReal *r) { return (double)(r->holders ? r->holders : 1); } -static JsAction choose(const JsSpace *s, const JsReal *r, double pressure, bool allow_move) { +/* One alternative the residency chooser builds: its cost inputs. Its score + * (nanoseconds of expected work per byte given back) goes to score[] below. */ +typedef struct { JsAction a; double now, later, freed; } Alt; + +/* The residency decision for one candidate, with its working set exposed: + * opt[0..*k_out) are the alternatives in build order (MOVE, COMPRESS, SPILL, + * EVICT), score[i] the score of opt[i] when it frees bytes (untouched when it + * does not); *best_out is the cheapest score (0 when none). choose() is this + * decision with the working set dropped. + * DUAL-3a observation reads the working set; nothing else does. */ +static JsAction decide(const JsSpace *s, const JsReal *r, double pressure, bool allow_move, + Alt opt[4], double score[4], int *k_out, double *best_out) { const JsCosts *c = &s->costs; double n = (double)r->realizer->unit_bytes; double e = expected_reads(r); double best = 0; JsAction act = JS_ACT_COUNT; /* keep */ + *k_out = 0; + *best_out = 0; if (r->placement != JS_PLACE_HOT && r->placement != JS_PLACE_COLD && r->placement != JS_PLACE_COMPRESSED) return JS_ACT_COUNT; double held = r->placement == JS_PLACE_COMPRESSED ? (double)r->packed_len : n; - struct { JsAction a; double now, later, freed; } opt[4]; int k = 0; if (r->placement == JS_PLACE_HOT && allow_move) { /* MOVE frees hot-arena bytes, not total residency. */ @@ -986,13 +998,149 @@ static JsAction choose(const JsSpace *s, const JsReal *r, double pressure, bool if (opt[i].freed <= 0) continue; /* nanoseconds of expected work per byte of residency given back */ double cost = (opt[i].now + e * opt[i].later) / opt[i].freed; + score[i] = cost; if (act == JS_ACT_COUNT || cost < best) { best = cost; act = opt[i].a; } } + *k_out = k; + *best_out = best; /* Keep when holding the bytes is cheaper than the best way to give them up. */ if (act != JS_ACT_COUNT && best >= pressure * c->retain_ns_per_byte) return JS_ACT_COUNT; return act; } +static JsAction choose(const JsSpace *s, const JsReal *r, double pressure, bool allow_move) { + Alt opt[4]; + double score[4]; + int k; + double best; + return decide(s, r, pressure, allow_move, opt, score, &k, &best); +} + +/* ---- DUAL-3a decision-site observation ("jspace.residency", rx_jspace.h) -- */ + +static uint8_t *put_u8(uint8_t *p, uint64_t v) { *p = (uint8_t)v; return p + 1; } +static uint8_t *put_u32(uint8_t *p, uint32_t v) { + for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); + return p + 4; +} +static uint8_t *put_u64(uint8_t *p, uint64_t v) { + for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); + return p + 8; +} +static uint8_t *put_f64(uint8_t *p, double d) { + uint64_t v; + memcpy(&v, &d, 8); + return put_u64(p, v); +} + +size_t js_dual_observation_encode(const JsDualObservation *o, uint8_t out[JS_DUAL_OBS_BYTES]) { + uint8_t *p = out; + p = put_u8(p, o->kind); + p = put_u8(p, o->version); + p = put_u8(p, JS_DUAL_SITE_ID_LEN); + memcpy(p, JS_DUAL_SITE_ID, JS_DUAL_SITE_ID_LEN); p += JS_DUAL_SITE_ID_LEN; + p = put_u64(p, o->seq); + p = put_f64(p, o->pressure); + p = put_u8(p, o->pressure_case); + p = put_u8(p, o->allow_move); + p = put_u8(p, o->chosen); + p = put_u8(p, o->n_priced); + for (unsigned i = 0; i < JS_DUAL_OBS_N_ALT; i++) { + p = put_u8(p, o->alt[i].action); + p = put_u8(p, o->alt[i].status); + p = put_f64(p, o->alt[i].now_ns); + p = put_f64(p, o->alt[i].later_ns); + p = put_f64(p, o->alt[i].freed_bytes); + p = put_f64(p, o->alt[i].score); + } + p = put_f64(p, o->best_score); + p = put_f64(p, o->keep_threshold); + p = put_f64(p, o->expected_reads); + p = put_u32(p, o->real_slot); + p = put_u64(p, o->real_gen); + p = put_u8(p, o->real_type); + p = put_u8(p, o->placement); + p = put_u8(p, o->recipe); + p = put_u64(p, o->unit_bytes); + p = put_u64(p, o->held_bytes); + p = put_u32(p, o->holders); + p = put_u32(p, o->refs); + p = put_u64(p, o->last_use); + memcpy(p, o->semantic_state_id, 32); p += 32; + p = put_u64(p, o->budget_bytes); + p = put_u64(p, o->resident_bytes); + p = put_u64(p, o->hot_bytes); + return (size_t)(p - out); +} + +void js_dual_set_observer(JsSpace *s, JsDualObserver fn, const void *ctx) { + LOCK(s); + s->dual_observer = fn; + s->dual_ctx = fn ? ctx : NULL; + UNLOCK(s); +} + +/* The same decision as choose(), followed by one observation record handed to + * the observer. The returned action is the chooser's own local result; the + * record is a copy the observer cannot act through. */ +static JsAction observed_u(JsSpace *s, const JsReal *r, double pressure, bool over_total, + uint64_t budget_bytes, uint64_t hot) { + Alt opt[4]; + double score[4] = { 0, 0, 0, 0 }; + int k; + double best; + JsAction a = decide(s, r, pressure, !over_total, opt, score, &k, &best); + JsDualObservation o; + memset(&o, 0, sizeof o); + o.kind = JS_DUAL_OBS_KIND; + o.version = JS_DUAL_OBS_VERSION; + o.seq = ++s->dual_seq; + o.pressure = pressure; + o.pressure_case = over_total ? JS_DUAL_PRESSURE_CAPACITY : JS_DUAL_PRESSURE_SOFT; + o.allow_move = !over_total; + o.chosen = (uint8_t)a; + for (unsigned i = 0; i < JS_DUAL_OBS_N_ALT; i++) { + o.alt[i].action = (uint8_t)(JS_ACT_MOVE + i); + o.alt[i].status = JS_DUAL_ALT_INADMISSIBLE; + } + for (int i = 0; i < k; i++) { + JsDualAlternative *d = &o.alt[opt[i].a - JS_ACT_MOVE]; + d->status = opt[i].freed > 0 ? JS_DUAL_ALT_PRICED : JS_DUAL_ALT_UNPRICED; + d->now_ns = opt[i].now; + d->later_ns = opt[i].later; + d->freed_bytes = opt[i].freed; + d->score = score[i]; + if (opt[i].freed > 0) o.n_priced++; + } + o.best_score = best; + o.keep_threshold = pressure * s->costs.retain_ns_per_byte; + o.expected_reads = expected_reads(r); + o.real_slot = r->slot; + o.real_gen = r->gen; + o.real_type = (uint8_t)r->realization_type; + o.placement = (uint8_t)r->placement; + o.recipe = (uint8_t)r->recipe; + o.unit_bytes = r->realizer->unit_bytes; + o.held_bytes = resident_of(r); + o.holders = r->holders; + o.refs = r->refs; + o.last_use = r->last_use; + memcpy(o.semantic_state_id, r->semantic_state_id.b, 32); + o.budget_bytes = budget_bytes; + o.resident_bytes = s->stats.resident_bytes; + o.hot_bytes = hot; + uint8_t enc[JS_DUAL_OBS_BYTES]; + size_t len = js_dual_observation_encode(&o, enc); + sha256_ctx h; + sha256_init(&h); + /* domain string including its terminating zero byte */ + sha256_update(&h, (const uint8_t *)JS_DUAL_OBS_DOMAIN, sizeof JS_DUAL_OBS_DOMAIN); + sha256_update(&h, enc, len); + sha256_final(&h, o.digest); + s->dual_observer(&o, s->dual_ctx); + return a; +} + JsAction js_forge_choose(const JsSpace *s, const JsReal *r, double pressure) { return choose(s, r, pressure, true); } @@ -1051,7 +1199,8 @@ static int enforce_u(JsSpace *s, uint64_t budget_bytes, JsPolicyReport *rep) { JsReal *r = cs[i].r; double pressure = over_total ? 1e9 : 1e3; /* A move lowers hot-arena bytes, not total residency. */ - JsAction a = choose(s, r, pressure, !over_total); + JsAction a = s->dual_observer ? observed_u(s, r, pressure, over_total, budget_bytes, hot) + : choose(s, r, pressure, !over_total); if (rep) rep->considered++; if (a == JS_ACT_COUNT) { if (rep) rep->kept++; continue; } uint64_t before_hot = r->placement == JS_PLACE_HOT ? r->realizer->unit_bytes : 0; diff --git a/src/runtime/rx_jspace.h b/src/runtime/rx_jspace.h index 70469dc4a..86cd67035 100644 --- a/src/runtime/rx_jspace.h +++ b/src/runtime/rx_jspace.h @@ -268,6 +268,10 @@ typedef struct { uint64_t corrupt_restores; } JsStats; +/* DUAL-3a observer (declared in full after the policy section below). */ +typedef struct JsDualObservation_ JsDualObservation; +typedef void (*JsDualObserver)(const JsDualObservation *obs, const void *ctx); + #define JS_MAX_BRANCHES 4096u #define JS_INDEX_BUCKETS 65536u @@ -309,6 +313,10 @@ typedef struct { uint8_t anchor[48]; /* opaque client anchor (v3 checkpoint) */ bool anchor_set; JsHome local_home; /* home given to locally created branches */ + /* DUAL-3a decision-site observer; NULL = no observation (default) */ + JsDualObserver dual_observer; + const void *dual_ctx; + uint64_t dual_seq; } JsSpace; #define JS_SLAB_CHUNK 1024u @@ -419,6 +427,83 @@ typedef struct { JsAction js_forge_choose(const JsSpace *s, const JsReal *r, double pressure); int js_forge_enforce(JsSpace *s, uint64_t budget_bytes, JsPolicyReport *rep); +/* ---- DUAL decision site "jspace.residency" (ADR 0031 section 7.3, DUAL-3a) -- + * + * A read-only observation tap on the residency decision inside + * js_forge_enforce. When an observer is set, each candidate the chooser + * decides on emits one JsDualObservation: the alternatives it priced (every + * action with the cost inputs and the score the chooser computed, and whether + * the action was admissible), the chosen action, the pressure value and which + * case produced it (over total budget: CAPACITY, stays hard; hot arena over + * half the budget: SOFT), the realization's identity, and the budget and + * residency bytes at that instant. The observer receives a const record and + * returns nothing: it cannot alter the decision by type. With no observer (the + * default) the policy runs exactly as before and no record is built. The + * observer runs under the space lock and must not mutate the space or any + * realization. There is no wall-clock field: seq is a per-space logical + * counter that only advances while an observer is set. + * + * Canonical encoding (js_dual_observation_encode): fixed little-endian layout + * of every field but digest, JS_DUAL_OBS_BYTES long, kind byte and version + * first so the record is self-describing. digest = SHA-256 over + * JS_DUAL_OBS_DOMAIN, one zero byte, then the canonical bytes. */ +#define JS_DUAL_SITE_ID "jspace.residency" +#define JS_DUAL_SITE_ID_LEN 16u +#define JS_DUAL_OBS_KIND 0xD3u /* kind byte: DUAL decision-site observation */ +#define JS_DUAL_OBS_VERSION 1u +#define JS_DUAL_OBS_DOMAIN "omega.dual.site.jspace_residency.v1" +#define JS_DUAL_OBS_N_ALT 4u /* MOVE, COMPRESS, SPILL, EVICT: the chooser's order */ +#define JS_DUAL_OBS_BYTES 302u /* canonical encoding length (version 1) */ + +typedef enum { + JS_DUAL_PRESSURE_CAPACITY = 1, /* total residency over budget: pressure 1e9, MOVE not allowed */ + JS_DUAL_PRESSURE_SOFT = 2 /* only the hot arena over half the budget: pressure 1e3 */ +} JsDualPressureCase; + +typedef enum { + JS_DUAL_ALT_INADMISSIBLE = 0, /* not built: MOVE without allow_move or not HOT; COMPRESS of a + compressed realization or one predicted not to shrink */ + JS_DUAL_ALT_UNPRICED = 1, /* built but frees no bytes: skipped by the chooser */ + JS_DUAL_ALT_PRICED = 2 /* scored: (now + expected_reads * later) / freed */ +} JsDualAltStatus; + +typedef struct { + uint8_t action; /* JsAction */ + uint8_t status; /* JsDualAltStatus */ + double now_ns, later_ns, freed_bytes; /* chooser inputs; 0 when inadmissible */ + double score; /* nanoseconds per byte given back; 0 unless PRICED */ +} JsDualAlternative; + +struct JsDualObservation_ { + uint8_t kind, version; + uint64_t seq; /* monotonically increasing per space */ + double pressure; /* the value the chooser used */ + uint8_t pressure_case; /* JsDualPressureCase */ + uint8_t allow_move; + uint8_t chosen; /* JsAction; JS_ACT_COUNT = keep */ + uint8_t n_priced; + JsDualAlternative alt[JS_DUAL_OBS_N_ALT]; + double best_score; /* cheapest priced score; 0 when none was priced */ + double keep_threshold; /* pressure * retain_ns_per_byte: keep when best >= this */ + double expected_reads; + /* realization identity and state at the instant of the decision */ + uint32_t real_slot; + uint64_t real_gen; + uint8_t real_type, placement, recipe; + uint64_t unit_bytes, held_bytes; + uint32_t holders, refs; + uint64_t last_use; + uint8_t semantic_state_id[32]; + /* the instant */ + uint64_t budget_bytes, resident_bytes, hot_bytes; + uint8_t digest[32]; +}; + +/* NULL fn restores the default (no observation). */ +void js_dual_set_observer(JsSpace *s, JsDualObserver fn, const void *ctx); +/* Canonical bytes of obs (all fields but digest). Returns JS_DUAL_OBS_BYTES. */ +size_t js_dual_observation_encode(const JsDualObservation *obs, uint8_t out[JS_DUAL_OBS_BYTES]); + const char *js_action_name(JsAction a); const char *js_placement_name(JsPlacement p); const char *js_real_type_name(JsRealType t); diff --git a/tests/.crumb b/tests/.crumb index 043f22d95..7d6c3ffef 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -152,7 +152,7 @@ }, { "digest": "d57833fb3f63ef6475cf25e2e16319d818a0a407b825d5b4c5cbdd3cc0e06492", - "last_commit": "", + "last_commit": "00f54b6", "name": "dual_experiment", "purpose": "Tests for the DUAL applicability experiment: determinism (same seed, byte-identical results dige" }, @@ -253,7 +253,7 @@ "purpose": "Directory tests/relations. Purpose not yet described by a human." }, { - "digest": "646c5c0b1c7160f73031fe4aebaae5558abe4e26fb6d54f925df311f9e648e1b", + "digest": "f49db08f5e2f8ad20c9e10f7eaaa27e7f264b6bfc17e4d4fad16e60eb1495f1d", "last_commit": "f523edd", "name": "runtime", "purpose": "Directory tests/runtime. Purpose not yet described by a human." @@ -283,15 +283,15 @@ "purpose": "Directory tests/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:bcae6f913b37bfcb59d06e2942acc649d5803a2521f4d50beb450a04e6f24b81", - "compiled_at": "2026-10-04T18:38:56Z", + "children_root": "sha256:0a4e348cf355e1fa5924f9c76a460d1d49bc285687b134365ef0fb9dab4f0855", + "compiled_at": "2026-10-04T18:45:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:e9bfa25f9d911bbcb636a73ecedea1df90b2a7e0ff9782fb43cf794d8aecdb4c", + "digest": "sha256:e96dec62800dc6dae755ebe10eacfedcb0959e29e00a3540284cb585f8f9716f", "evidence_files": 11, "evidence_root": "sha256:d5c1bceb4d57ef0eb42797c58801b5926509711614c3e38bb7105b6efa3942f2", - "files": 785, - "generated_at_commit": "3bebcc68321fcc876b88df129f41d6190411a926", - "source_tree": "sha256:e3fa566d5c75465dd85467a30bc713269c6e125280fdaef48b1a0f196e20d79f" + "files": 787, + "generated_at_commit": "00f54b6b19e5e64e8947aea2890e688511d897a8", + "source_tree": "sha256:1a35905c6c7254bc66bf0519cac4d23e5b1c2d7722356a0e06401faec581448f" }, "owner_lane": "", "provenance": { diff --git a/tests/runtime/.crumb b/tests/runtime/.crumb index 16c519d53..867d1c133 100644 --- a/tests/runtime/.crumb +++ b/tests/runtime/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:12:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:646c5c0b1c7160f73031fe4aebaae5558abe4e26fb6d54f925df311f9e648e1b", + "digest": "sha256:f49db08f5e2f8ad20c9e10f7eaaa27e7f264b6bfc17e4d4fad16e60eb1495f1d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 50, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:5e6a07b58035b6297687422093c23d333e675085c60ea4a586a698a49fde3904" + "files": 52, + "generated_at_commit": "cb7cc216147664549484fcca8e8ceadbd6f6cdbf", + "source_tree": "sha256:cc6b64472b5dadb93de40b9efbe2ca53931138d538323a2683b79d9fe3ec2df4" }, "owner_lane": "", "provenance": { diff --git a/tests/runtime/rx_dual_jspace_tap.c b/tests/runtime/rx_dual_jspace_tap.c new file mode 100644 index 000000000..a0afdd06e --- /dev/null +++ b/tests/runtime/rx_dual_jspace_tap.c @@ -0,0 +1,672 @@ +/* + * rx_dual_jspace_tap.c -- DUAL-3a parity tests for the read-only observation + * tap at decision site "jspace.residency" (js_forge_enforce, rx_jspace.c). + * + * Every scenario builds the same deterministic J-Space workload three times: + * once with no observer (today's behaviour), twice with a recording observer + * (legs A and B). Fixed JsCosts replace calibration so the chooser's inputs are + * identical run to run. Checked, per scenario: + * + * - every js_forge_enforce return code and every JsPolicyReport identical + * with and without the observer; + * - JsStats (actions, residency, peak, spilled, live, derives, copies) and + * the final space digest (every branch, unit, placement, extent, content + * check, then full content digests) identical with and without; + * - the record stream of leg A is byte-identical to leg B (determinism); + * - one record per considered candidate (count == JsPolicyReport.considered), + * seq strictly increasing from 1, canonical length JS_DUAL_OBS_BYTES, digest + * recomputed and equal; + * - each record's chosen action equals the decision the chooser rule gives on + * the record's own alternatives (first cheapest priced alternative, keep when + * its score is at or above pressure * retain); + * - each record's chosen action equals the placement transition that very + * realization underwent in the NO-OBSERVER run (slot + generation keyed), so + * the observer run took the same decision per realization as the silent run; + * - pressure value and case agree with the budget/residency bytes recorded. + * + * Pure-extraction check: choose() was split into decide() (working set exposed) + * plus a wrapper. reference_choose_pre_tap() below is the verbatim pre-change + * body (a class D reference oracle, test only). On every live realization of a + * fan-out workload, for both pressure values and both allow_move values, the + * two must agree. + * + * Negative control: built with -DDUAL_TAP_HOSTILE_TEST the leg-A observer casts + * its ctx to the space and raises retain_ns_per_byte on its third record. The + * decisions that follow differ from the silent run and this program MUST exit 1. + * The production source never defines or tests that macro (checked by grep in + * mk/dual_jspace_tap.mk). + * + * This file includes rx_jspace.c (not linked with it) so the reference oracle + * can call the static cost helpers and the digest can walk the index. + */ +#include "runtime/rx_jspace.c" + +#include <inttypes.h> +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#define UNIT 4096u +#define U(x) ((unsigned long long)(x)) + +static int g_fail; +#define CHECK(c, ...) do { if (!(c)) { g_fail++; printf(" FAIL: " __VA_ARGS__); printf("\n"); } } while (0) + +/* ---- deterministic realizer -------------------------------------------------- */ + +static uint64_t splitmix(uint64_t *x) { + uint64_t z = (*x += 0x9e3779b97f4a7c15ull); + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + return z ^ (z >> 31); +} + +/* Root: pseudo-random fill. Derive: one word in eight changes, so a delta + * against the parent is compressible (COMPRESS becomes a real alternative). */ +static void derive_sparse(const uint8_t *prev, uint64_t token, uint8_t *out, size_t n) { + uint64_t x = token; + if (!prev) { + for (size_t i = 0; i + 8 <= n; i += 8) { uint64_t v = splitmix(&x); memcpy(out + i, &v, 8); } + return; + } + memcpy(out, prev, n); + for (size_t i = (size_t)(token % 8) * 8; i + 8 <= n; i += 64) { + uint64_t v = splitmix(&x); + memcpy(out + i, &v, 8); + } +} + +static const JsRealizer RZ = { JS_REAL_LATENT_CHECKPOINT, "sparse", UNIT, derive_sparse }; + +/* Fixed costs. With n = UNIT, e = 1, parent HOT: + * MOVE 0.25 COMPRESS (0.5 + 0.5) / 0.75 = 1.333 SPILL 2 + 4 = 6 EVICT 1.0 + * Soft threshold 1e3 * retain = 0.9765625: MOVE is taken, nothing else. + * Capacity threshold 1e9 * retain: EVICT (1.0) beats COMPRESS (1.333). */ +static void costs_plain(JsSpace *s) { + JsCosts c = { 0 }; + c.derive_ns = (double)UNIT; + c.copy_ns_per_byte = 0.125; + c.move_ns_per_byte = 0.125; + c.compress_ns_per_byte = 0.5; + c.decompress_ns_per_byte = 0.5; + c.compress_ratio = 0.25; + c.spill_write_ns_per_byte = 2.0; + c.spill_read_ns_per_byte = 4.0; + c.retain_ns_per_byte = 1.0 / 1024.0; + s->costs = c; +} + +/* Tie costs: COMPRESS = (0.25 + 0.25) / 0.5 = 1.0 and EVICT = 1.0 exactly + * (parent HOT, e = 1). The chooser's strict "<" keeps the first built. */ +static void costs_tie(JsSpace *s) { + costs_plain(s); + s->costs.compress_ns_per_byte = 0.25; + s->costs.decompress_ns_per_byte = 0.25; + s->costs.compress_ratio = 0.5; +} + +/* Spill-cheap costs: SPILL (0.125 + 0.125) = 0.25 beats EVICT 1.0 and COMPRESS. */ +static void costs_spill(JsSpace *s) { + costs_plain(s); + s->costs.spill_write_ns_per_byte = 0.125; + s->costs.spill_read_ns_per_byte = 0.125; +} + +/* ---- record store ------------------------------------------------------------ */ + +typedef struct { + uint8_t *bytes; /* JS_DUAL_OBS_BYTES + 32 digest per record */ + size_t n, cap; + JsDualObservation last; + int bad_len, bad_digest, bad_seq, bad_rule; + uint64_t next_seq; + JsSpace *space; /* hostile build only: the observer's way in */ + int tamper_record; /* normal build: write into the const record */ +} Rec; + +#define REC_STRIDE (JS_DUAL_OBS_BYTES + 32u) + +/* The chooser rule restated over a record's alternatives. */ +static uint8_t rule_of(const JsDualObservation *o) { + uint8_t act = JS_ACT_COUNT; + double best = 0; + for (unsigned i = 0; i < JS_DUAL_OBS_N_ALT; i++) { + if (o->alt[i].status != JS_DUAL_ALT_PRICED) continue; + if (act == JS_ACT_COUNT || o->alt[i].score < best) { best = o->alt[i].score; act = o->alt[i].action; } + } + if (act != JS_ACT_COUNT && best >= o->keep_threshold) return JS_ACT_COUNT; + return act; +} + +static void record(const JsDualObservation *o, const void *ctx) { + Rec *r = (Rec *)ctx; + if (r->n == r->cap) { + r->cap = r->cap ? r->cap * 2 : 64; + r->bytes = realloc(r->bytes, r->cap * REC_STRIDE); + } + uint8_t *dst = r->bytes + r->n * REC_STRIDE; + size_t len = js_dual_observation_encode(o, dst); + if (len != JS_DUAL_OBS_BYTES) r->bad_len++; + sha256_ctx h; + uint8_t d[32]; + sha256_init(&h); + sha256_update(&h, (const uint8_t *)JS_DUAL_OBS_DOMAIN, sizeof JS_DUAL_OBS_DOMAIN); + sha256_update(&h, dst, len); + sha256_final(&h, d); + if (memcmp(d, o->digest, 32)) r->bad_digest++; + memcpy(dst + JS_DUAL_OBS_BYTES, o->digest, 32); + if (o->seq != r->next_seq) r->bad_seq++; + r->next_seq = o->seq + 1; + if (rule_of(o) != o->chosen) r->bad_rule++; + r->last = *o; + r->n++; + if (r->tamper_record) { + /* A hostile observer writes into the record it was handed. The chooser's + * result is a separate local: the production decision must not move. */ + JsDualObservation *w = (JsDualObservation *)o; + w->chosen = JS_ACT_EVICT; + w->pressure = 0; + } +#ifdef DUAL_TAP_HOSTILE_TEST + /* retain price 0 makes every priced alternative "at or above" the keep + * threshold: from here on the chooser keeps everything. */ + if (r->n == 3 && r->space) r->space->costs.retain_ns_per_byte = 0.0; +#endif +} + +static void rec_free(Rec *r) { free(r->bytes); memset(r, 0, sizeof *r); } + +/* ---- workload ---------------------------------------------------------------- */ + +typedef struct { + const char *name; + void (*costs)(JsSpace *); + unsigned fanout, depth; + uint64_t max_spill; /* 0 = unlimited */ + int rounds; + /* budget per round: resident_bytes * num / den + add, computed when the round starts */ + struct { unsigned num, den; int64_t add; } budget[4]; + int rep_null; /* pass rep = NULL to enforce */ + int tamper; /* observer writes into the record */ +} Scenario; + +static unsigned g_spill_seq; + +static void space_open(JsSpace *s, const Scenario *sc) { + char path[128]; + snprintf(path, sizeof path, "/tmp/jstap_%ld_%u", (long)getpid(), g_spill_seq++); + JsLimits l; + js_limits_default(&l); + l.max_spill_bytes = sc->max_spill; + CHECK(js_space_init_limits(s, path, &l) == JS_OK, "%s: init", sc->name); + sc->costs(s); +} + +/* One root with `depth` derived units, then `fanout` forks each deriving one + * more unit: fanout + depth + 1 realizations, all HOT. */ +static void program(JsSpace *s, const Scenario *sc, uint32_t *root_out) { + uint32_t root; + CHECK(js_branch_root(s, &RZ, 7, &root) == JS_OK, "%s: root", sc->name); + for (unsigned i = 0; i < sc->depth; i++) CHECK(js_branch_derive(s, root, 100 + i) == JS_OK, "%s: derive", sc->name); + for (unsigned k = 0; k < sc->fanout; k++) { + uint32_t c; + CHECK(js_branch_fork(s, root, &c) == JS_OK, "%s: fork %u", sc->name, k); + CHECK(js_branch_derive(s, c, 1000 + k) == JS_OK, "%s: derive %u", sc->name, k); + } + *root_out = root; +} + +/* ---- state view -------------------------------------------------------------- */ + +typedef struct { uint32_t slot; uint64_t gen; uint8_t placement; } Place; + +static int place_cmp(const void *a, const void *b) { + const Place *x = a, *y = b; + return (x->slot > y->slot) - (x->slot < y->slot); +} + +static uint32_t placements(JsSpace *s, Place **out) { + Cand *cs; + uint32_t n = collect(s, &cs); + Place *p = calloc(n ? n : 1, sizeof *p); + for (uint32_t i = 0; i < n; i++) { + p[i].slot = cs[i].r->slot; p[i].gen = cs[i].r->gen; p[i].placement = (uint8_t)cs[i].r->placement; + } + free(cs); + qsort(p, n, sizeof *p, place_cmp); + *out = p; + return n; +} + +static void space_digest(JsSpace *s, uint8_t out[32]) { + sha256_ctx h; + sha256_init(&h); + for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + JsBranch *br = s->branches[b]; + if (!br) continue; + sha256_update(&h, (const uint8_t *)&b, 4); + sha256_update(&h, (const uint8_t *)&br->n_units, 4); + for (uint32_t i = 0; i < br->n_units; i++) { + const JsReal *r = br->units[i]; + uint64_t v[5] = { r->slot, r->gen, r->placement, r->packed_len, + r->placement == JS_PLACE_SPILLED ? r->spill_off : 0 }; + sha256_update(&h, (const uint8_t *)v, sizeof v); + sha256_update(&h, r->content, 32); + sha256_update(&h, r->semantic_state_id.b, 32); + } + } + sha256_update(&h, (const uint8_t *)&s->stats, sizeof s->stats); + sha256_update(&h, (const uint8_t *)&s->spill_end, sizeof s->spill_end); + /* Full content digests last: they restore bytes, identically in every leg. */ + for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + if (!s->branches[b]) continue; + uint8_t d[32] = { 0 }; + int rc = js_branch_content_digest(s, b, d); + sha256_update(&h, (const uint8_t *)&rc, sizeof rc); + sha256_update(&h, d, 32); + } + sha256_final(&h, out); +} + +/* ---- one leg ----------------------------------------------------------------- */ + +typedef struct { + int rc[4]; + JsPolicyReport rep[4]; + JsStats stats; + uint8_t digest[32]; + /* per round, the silent run's placement before and after enforce */ + Place *before[4], *after[4]; + uint32_t n_place[4]; + uint64_t resident_before[4], budget[4]; +} Leg; + +static uint64_t budget_of(const Scenario *sc, int round, uint64_t resident) { + int64_t b = (int64_t)(resident * sc->budget[round].num / sc->budget[round].den) + sc->budget[round].add; + return b < 0 ? 0 : (uint64_t)b; +} + +static void run_leg(const Scenario *sc, Rec *rec, Leg *leg, int keep_places) { + JsSpace s; + uint32_t root; + memset(leg, 0, sizeof *leg); + space_open(&s, sc); + program(&s, sc, &root); + if (rec) { rec->space = &s; js_dual_set_observer(&s, record, rec); } + for (int k = 0; k < sc->rounds; k++) { + /* Make everything resident again between rounds (COLD stays COLD) so + * each round decides again. */ + if (k) for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + JsBranch *br = s.branches[b]; + if (!br) continue; + for (uint32_t i = 0; i < br->n_units; i++) js_real_restore(&s, br->units[i]); + } + leg->resident_before[k] = s.stats.resident_bytes; + leg->budget[k] = budget_of(sc, k, s.stats.resident_bytes); + if (keep_places) leg->n_place[k] = placements(&s, &leg->before[k]); + memset(&leg->rep[k], 0, sizeof leg->rep[k]); + leg->rc[k] = js_forge_enforce(&s, leg->budget[k], sc->rep_null ? NULL : &leg->rep[k]); + if (keep_places) placements(&s, &leg->after[k]); + } + leg->stats = s.stats; + space_digest(&s, leg->digest); + js_space_destroy(&s); +} + +static void leg_free(Leg *l) { + for (int k = 0; k < 4; k++) { free(l->before[k]); free(l->after[k]); } +} + +static uint8_t transition(uint8_t from, uint8_t to) { + if (from == to) return JS_ACT_COUNT; + if (from == JS_PLACE_HOT && to == JS_PLACE_COLD) return JS_ACT_MOVE; + if (to == JS_PLACE_COMPRESSED) return JS_ACT_COMPRESS; + if (to == JS_PLACE_SPILLED) return JS_ACT_SPILL; + if (to == JS_PLACE_EVICTED) return JS_ACT_EVICT; + return 0xff; +} + +/* ---- scenario ---------------------------------------------------------------- */ + +static int same_rep(const JsPolicyReport *a, const JsPolicyReport *b) { return !memcmp(a, b, sizeof *a); } + +static void run_scenario(const Scenario *sc) { + Leg silent, la, lb; + Rec ra = { 0 }, rb = { 0 }; + ra.next_seq = rb.next_seq = 1; + ra.tamper_record = rb.tamper_record = sc->tamper; + run_leg(sc, NULL, &silent, 1); + run_leg(sc, &ra, &la, 0); + run_leg(sc, &rb, &lb, 0); + + uint64_t considered = 0; + for (int k = 0; k < sc->rounds; k++) { + CHECK(silent.rc[k] == la.rc[k] && silent.rc[k] == lb.rc[k], + "%s round %d: rc silent %d A %d B %d", sc->name, k, silent.rc[k], la.rc[k], lb.rc[k]); + CHECK(same_rep(&silent.rep[k], &la.rep[k]) && same_rep(&silent.rep[k], &lb.rep[k]), + "%s round %d: JsPolicyReport differs with observer", sc->name, k); + CHECK(silent.budget[k] == la.budget[k] && silent.resident_before[k] == la.resident_before[k], + "%s round %d: budget/residency differ before enforce", sc->name, k); + considered += silent.rep[k].considered; + } + CHECK(!memcmp(&silent.stats, &la.stats, sizeof silent.stats) && !memcmp(&silent.stats, &lb.stats, sizeof silent.stats), + "%s: JsStats differ with observer (resident silent %llu A %llu B %llu)", sc->name, + U(silent.stats.resident_bytes), U(la.stats.resident_bytes), U(lb.stats.resident_bytes)); + CHECK(!memcmp(silent.digest, la.digest, 32) && !memcmp(silent.digest, lb.digest, 32), + "%s: final space digest differs with observer", sc->name); + CHECK(ra.n == rb.n && (ra.n == 0 || !memcmp(ra.bytes, rb.bytes, ra.n * REC_STRIDE)), + "%s: record streams A (%zu) and B (%zu) differ", sc->name, ra.n, rb.n); + if (!sc->rep_null) + CHECK(ra.n == considered, "%s: %zu records for %llu considered candidates", sc->name, ra.n, U(considered)); + CHECK(!ra.bad_len && !ra.bad_digest && !ra.bad_seq, "%s: records malformed (len %d digest %d seq %d)", + sc->name, ra.bad_len, ra.bad_digest, ra.bad_seq); + CHECK(!ra.bad_rule, "%s: %d records whose chosen action is not the chooser rule on their alternatives", + sc->name, ra.bad_rule); + + /* Per-realization parity with the silent run: walk leg A's records round by + * round (records are in enforce order; a round emits rep.considered of them) + * and compare chosen with the placement transition the silent run shows. */ + size_t at = 0; + for (int k = 0; k < sc->rounds && !sc->rep_null; k++) { + uint64_t n = silent.rep[k].considered; + for (uint64_t j = 0; j < n && at < ra.n; j++, at++) { + const uint8_t *enc = ra.bytes + at * REC_STRIDE; + /* fixed offsets of the canonical layout */ + uint8_t chosen = enc[37]; + uint8_t pcase = enc[35]; + double pressure; memcpy(&pressure, enc + 27, 8); + uint32_t slot; memcpy(&slot, enc + 199, 4); + uint64_t gen; memcpy(&gen, enc + 203, 8); + uint64_t budget, resident; memcpy(&budget, enc + 278, 8); memcpy(&resident, enc + 286, 8); + CHECK(budget == silent.budget[k], "%s round %d rec %llu: budget %llu != %llu", sc->name, k, U(j), U(budget), U(silent.budget[k])); + CHECK((pcase == JS_DUAL_PRESSURE_CAPACITY) == (resident > budget), + "%s round %d rec %llu: pressure case %u with resident %llu budget %llu", sc->name, k, U(j), pcase, U(resident), U(budget)); + CHECK(pressure == (pcase == JS_DUAL_PRESSURE_CAPACITY ? 1e9 : 1e3), + "%s round %d rec %llu: pressure %g for case %u", sc->name, k, U(j), pressure, pcase); + Place key = { slot, 0, 0 }, *pb, *pa; + pb = bsearch(&key, silent.before[k], silent.n_place[k], sizeof key, place_cmp); + pa = bsearch(&key, silent.after[k], silent.n_place[k], sizeof key, place_cmp); + CHECK(pb && pa && pb->gen == gen, "%s round %d rec %llu: realization slot %u gen %llu unknown to the silent run", + sc->name, k, U(j), slot, U(gen)); + if (!pb || !pa) continue; + uint8_t tr = transition(pb->placement, pa->placement); + /* The last record of a round that ended in an error names an action + * that was chosen but failed; its placement did not change. */ + int failed_last = silent.rc[k] != JS_OK && j == n - 1; + if (!failed_last) + CHECK(tr == chosen, "%s round %d rec %llu: observer saw %s, silent run did %s on slot %u", + sc->name, k, U(j), js_action_name(chosen), js_action_name(tr), slot); + else + CHECK(tr == JS_ACT_COUNT && chosen != JS_ACT_COUNT, + "%s round %d: failed last decision not visible as expected", sc->name, k); + } + } + + printf(" %-22s rounds %d records %zu considered %llu rc[0] %d resident %llu digest %02x%02x%02x%02x %s\n", + sc->name, sc->rounds, ra.n, U(considered), silent.rc[0], U(silent.stats.resident_bytes), + silent.digest[0], silent.digest[1], silent.digest[2], silent.digest[3], + g_fail ? "(failures above)" : "ok"); + rec_free(&ra); rec_free(&rb); + leg_free(&silent); leg_free(&la); leg_free(&lb); +} + +/* ---- scenario-specific assertions on record content -------------------------- */ + +static void check_cases(void) { + /* Soft case: all HOT, total under budget, hot over half: every record is + * SOFT with pressure 1e3, MOVE allowed and chosen (0.25 < 0.9765625). */ + Scenario soft = { "soft-case", costs_plain, 16, 4, 0, 1, { { 3, 2, 0 } }, 0, 0 }; + Rec r = { 0 }; r.next_seq = 1; + Leg l; + run_leg(&soft, &r, &l, 0); + CHECK(r.n > 0, "soft: no records"); + int all_soft = 1, all_move = 1; + for (size_t i = 0; i < r.n; i++) { + const uint8_t *e = r.bytes + i * REC_STRIDE; + if (e[35] != JS_DUAL_PRESSURE_SOFT || e[36] != 1) all_soft = 0; + if (e[37] != JS_ACT_MOVE) all_move = 0; + } + CHECK(all_soft, "soft: a record was not the SOFT case with MOVE allowed"); + CHECK(all_move, "soft: a record chose something other than MOVE"); + CHECK(r.last.alt[0].status == JS_DUAL_ALT_PRICED && r.last.alt[0].score == 0.25, + "soft: MOVE score %g", r.last.alt[0].score); + CHECK(r.last.alt[3].status == JS_DUAL_ALT_PRICED && r.last.alt[3].score == 1.0, + "soft: EVICT score %g", r.last.alt[3].score); + CHECK(r.last.keep_threshold == 1e3 / 1024.0, "soft: keep threshold %g", r.last.keep_threshold); + CHECK(r.last.kind == JS_DUAL_OBS_KIND && r.last.version == JS_DUAL_OBS_VERSION, "soft: kind/version"); + CHECK(r.last.unit_bytes == UNIT && r.last.held_bytes == UNIT, "soft: unit/held bytes"); + rec_free(&r); leg_free(&l); + + /* Capacity case: total over budget: MOVE inadmissible, EVICT chosen. */ + Scenario cap = { "capacity-case", costs_plain, 16, 4, 0, 1, { { 1, 2, 0 } }, 0, 0 }; + memset(&r, 0, sizeof r); r.next_seq = 1; + run_leg(&cap, &r, &l, 0); + /* Once total residency is back under budget the same enforce call goes on + * with the hot-arena SOFT case, so a run holds both cases: every CAPACITY + * record must have MOVE inadmissible and allow_move 0; the first record is + * CAPACITY with EVICT chosen under the 1e9 threshold. */ + CHECK(r.n > 0, "capacity: no records"); + int n_cap = 0, n_soft = 0, bad = 0; + for (size_t i = 0; i < r.n; i++) { + const uint8_t *e = r.bytes + i * REC_STRIDE; + if (e[35] == JS_DUAL_PRESSURE_CAPACITY) { + n_cap++; + if (e[36] != 0 || e[39] != JS_ACT_MOVE || e[40] != JS_DUAL_ALT_INADMISSIBLE) bad++; + } else n_soft++; + } + CHECK(n_cap > 0 && !bad, "capacity: %d CAPACITY records, %d with MOVE admissible", n_cap, bad); + { + const uint8_t *e0 = r.bytes; + double thr; memcpy(&thr, e0 + 183, 8); + CHECK(e0[35] == JS_DUAL_PRESSURE_CAPACITY && e0[37] == JS_ACT_EVICT && thr == 1e9 / 1024.0, + "capacity: first record case %u chose %s threshold %g", e0[35], js_action_name(e0[37]), thr); + } + printf(" capacity: %d CAPACITY then %d SOFT records in one enforce call\n", n_cap, n_soft); + rec_free(&r); leg_free(&l); + + /* Ties: COMPRESS and EVICT price to exactly 1.0; the first built wins. */ + Scenario tie = { "tie-case", costs_tie, 16, 4, 0, 1, { { 1, 2, 0 } }, 0, 0 }; + memset(&r, 0, sizeof r); r.next_seq = 1; + run_leg(&tie, &r, &l, 0); + int ties = 0, tie_ok = 1; + for (size_t i = 0; i < r.n; i++) { + const uint8_t *e = r.bytes + i * REC_STRIDE; + double sc_c, sc_e, best; memcpy(&sc_c, e + 73 + 26, 8); memcpy(&sc_e, e + 141 + 26, 8); + memcpy(&best, e + 175, 8); + /* a tie between COMPRESS and EVICT that is also the cheapest price */ + if (e[74] == JS_DUAL_ALT_PRICED && e[142] == JS_DUAL_ALT_PRICED && sc_c == sc_e && best == sc_c) { + ties++; + if (e[37] != JS_ACT_COMPRESS) tie_ok = 0; + } + } + CHECK(ties > 0, "tie: no record where COMPRESS == EVICT is the cheapest price"); + printf(" ties: %d records with COMPRESS and EVICT tied at the cheapest price\n", ties); + CHECK(tie_ok, "tie: a tied record did not choose the first-built alternative"); + rec_free(&r); leg_free(&l); +} + +/* ---- pure extraction: decide()/choose() against the pre-tap body ------------- */ + +/* Verbatim copy of choose() as it was before DUAL-3a (reference oracle). */ +static JsAction reference_choose_pre_tap(const JsSpace *s, const JsReal *r, double pressure, bool allow_move) { + const JsCosts *c = &s->costs; + double n = (double)r->realizer->unit_bytes; + double e = expected_reads(r); + double best = 0; + JsAction act = JS_ACT_COUNT; /* keep */ + if (r->placement != JS_PLACE_HOT && r->placement != JS_PLACE_COLD && + r->placement != JS_PLACE_COMPRESSED) return JS_ACT_COUNT; + double held = r->placement == JS_PLACE_COMPRESSED ? (double)r->packed_len : n; + struct { JsAction a; double now, later, freed; } opt[4]; + int k = 0; + if (r->placement == JS_PLACE_HOT && allow_move) { + /* MOVE frees hot-arena bytes, not total residency. */ + opt[k++] = (typeof(opt[0])){ JS_ACT_MOVE, n * c->move_ns_per_byte, 0, n * 0.5 }; + } + if (r->placement != JS_PLACE_COMPRESSED) { + double p = predicted_packed(s, r); + if (p < n) + /* A delta is decoded against its parent's bytes, so restoring it + * also pays for producing those. */ + opt[k++] = (typeof(opt[0])){ JS_ACT_COMPRESS, n * c->compress_ns_per_byte, + n * c->decompress_ns_per_byte + + (r->parent_realization ? restore_cost(s, r->parent_realization) : 0), + n - p }; + } + opt[k++] = (typeof(opt[0])){ JS_ACT_SPILL, n * c->spill_write_ns_per_byte, + n * c->spill_read_ns_per_byte, held }; + opt[k++] = (typeof(opt[0])){ JS_ACT_EVICT, 0, recompute_cost(s, r), held }; + for (int i = 0; i < k; i++) { + if (opt[i].freed <= 0) continue; + /* nanoseconds of expected work per byte of residency given back */ + double cost = (opt[i].now + e * opt[i].later) / opt[i].freed; + if (act == JS_ACT_COUNT || cost < best) { best = cost; act = opt[i].a; } + } + /* Keep when holding the bytes is cheaper than the best way to give them up. */ + if (act != JS_ACT_COUNT && best >= pressure * c->retain_ns_per_byte) return JS_ACT_COUNT; + return act; +} + +static void check_extraction(void) { + static void (*const cost_sets[3])(JsSpace *) = { costs_plain, costs_tie, costs_spill }; + static const double pressures[4] = { 1e3, 1e9, 0.0, 1e-3 }; + unsigned compared = 0, mismatches = 0; + for (int cs = 0; cs < 3; cs++) { + Scenario sc = { "extraction", cost_sets[cs], 64, 8, 0, 1, { { 1, 1, 0 } }, 0, 0 }; + JsSpace s; + uint32_t root; + space_open(&s, &sc); + program(&s, &sc, &root); + /* Mixed placements: some COLD, COMPRESSED, SPILLED, EVICTED. */ + Cand *cands; + uint32_t n = collect(&s, &cands); + for (uint32_t i = 0; i < n; i++) { + JsReal *r = cands[i].r; + switch (i % 5) { + case 1: js_real_move(&s, r); break; + case 2: js_real_compress(&s, r); break; + case 3: js_real_spill(&s, r); break; + case 4: js_real_evict(&s, r); break; + default: break; + } + } + for (uint32_t i = 0; i < n; i++) + for (int p = 0; p < 4; p++) + for (int am = 0; am < 2; am++) { + JsAction a = choose(&s, cands[i].r, pressures[p], am); + JsAction b = reference_choose_pre_tap(&s, cands[i].r, pressures[p], am); + compared++; + if (a != b) mismatches++; + /* and the public pure entry point stays the allow_move = true decision */ + if (am && js_forge_choose(&s, cands[i].r, pressures[p]) != b) mismatches++; + } + free(cands); + js_space_destroy(&s); + } + CHECK(mismatches == 0, "extraction: %u of %u decisions differ from the pre-tap chooser", mismatches, compared); + printf(" extraction: %u decisions compared with the pre-tap chooser, %u mismatches\n", compared, mismatches); +} + +/* ---- encoding ----------------------------------------------------------------- */ + +static void check_encoding(void) { + JsDualObservation o; + memset(&o, 0, sizeof o); + o.kind = JS_DUAL_OBS_KIND; o.version = JS_DUAL_OBS_VERSION; o.seq = 0x0102030405060708ull; + o.pressure = 1e3; o.pressure_case = JS_DUAL_PRESSURE_SOFT; o.allow_move = 1; o.chosen = JS_ACT_MOVE; + o.real_slot = 0xAABBCCDDu; o.budget_bytes = 0x1122334455667788ull; + uint8_t enc[JS_DUAL_OBS_BYTES]; + size_t len = js_dual_observation_encode(&o, enc); + CHECK(len == JS_DUAL_OBS_BYTES, "encode: %zu bytes, declared %u", len, JS_DUAL_OBS_BYTES); + CHECK(enc[0] == JS_DUAL_OBS_KIND && enc[1] == JS_DUAL_OBS_VERSION && enc[2] == JS_DUAL_SITE_ID_LEN, + "encode: kind/version/site length header"); + CHECK(!memcmp(enc + 3, JS_DUAL_SITE_ID, JS_DUAL_SITE_ID_LEN), "encode: site id"); + CHECK(enc[19] == 0x08 && enc[26] == 0x01, "encode: seq little-endian"); + CHECK(enc[199] == 0xDD && enc[202] == 0xAA, "encode: slot little-endian"); + CHECK(enc[278] == 0x88 && enc[285] == 0x11, "encode: budget little-endian at offset 278"); + uint8_t enc2[JS_DUAL_OBS_BYTES]; + js_dual_observation_encode(&o, enc2); + CHECK(!memcmp(enc, enc2, len), "encode: not deterministic"); + o.digest[0] = 1; + js_dual_observation_encode(&o, enc2); + CHECK(!memcmp(enc, enc2, len), "encode: digest field leaked into the canonical bytes"); + printf(" encoding: %zu canonical bytes, kind 0x%02x version %u, domain \"%s\"\n", + len, JS_DUAL_OBS_KIND, JS_DUAL_OBS_VERSION, JS_DUAL_OBS_DOMAIN); +} + +/* ---- observer lifecycle ------------------------------------------------------- */ + +static void check_lifecycle(void) { + Scenario sc = { "lifecycle", costs_plain, 8, 2, 0, 1, { { 1, 2, 0 } }, 0, 0 }; + JsSpace s; + uint32_t root; + space_open(&s, &sc); + program(&s, &sc, &root); + CHECK(s.dual_observer == NULL && s.dual_ctx == NULL && s.dual_seq == 0, "lifecycle: fresh space has an observer"); + JsPolicyReport rep = { 0 }; + CHECK(js_forge_enforce(&s, s.stats.resident_bytes / 2, &rep) == JS_OK, "lifecycle: enforce"); + CHECK(s.dual_seq == 0, "lifecycle: seq advanced without an observer"); + Rec r = { 0 }; r.next_seq = 1; + js_dual_set_observer(&s, record, &r); + for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + JsBranch *br = s.branches[b]; + if (!br) continue; + for (uint32_t i = 0; i < br->n_units; i++) js_real_restore(&s, br->units[i]); + } + memset(&rep, 0, sizeof rep); + CHECK(js_forge_enforce(&s, s.stats.resident_bytes / 2, &rep) == JS_OK, "lifecycle: enforce observed"); + CHECK(r.n == rep.considered && s.dual_seq == r.n, "lifecycle: %zu records, %llu considered, seq %llu", + r.n, U(rep.considered), U(s.dual_seq)); + js_dual_set_observer(&s, NULL, &r); + CHECK(s.dual_observer == NULL && s.dual_ctx == NULL, "lifecycle: clearing the observer left ctx behind"); + size_t before = r.n; + for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + JsBranch *br = s.branches[b]; + if (!br) continue; + for (uint32_t i = 0; i < br->n_units; i++) js_real_restore(&s, br->units[i]); + } + CHECK(js_forge_enforce(&s, s.stats.resident_bytes / 2, NULL) == JS_OK, "lifecycle: enforce after clear"); + CHECK(r.n == before, "lifecycle: records emitted after the observer was cleared"); + uint64_t seq = s.dual_seq; + rec_free(&r); + js_space_destroy(&s); + printf(" lifecycle: observer set, counted, cleared; seq %llu\n", U(seq)); +} + +/* ---- main ---------------------------------------------------------------------- */ + +int main(void) { + printf("DUAL-3a jspace.residency tap: parity%s\n", +#ifdef DUAL_TAP_HOSTILE_TEST + " [HOSTILE NEGATIVE CONTROL: the observer mutates the space; this run must FAIL]" +#else + "" +#endif + ); + check_encoding(); + check_lifecycle(); + check_extraction(); + check_cases(); + + const Scenario scenarios[] = { + /* name, costs, fanout, depth, max_spill, rounds, budgets {num, den, add}, rep NULL, tamper */ + { "under-budget", costs_plain, 16, 4, 0, 1, { { 1000, 1, 0 } }, 0, 0 }, + { "soft-hot-arena", costs_plain, 32, 4, 0, 2, { { 3, 2, 0 }, { 3, 2, 0 } }, 0, 0 }, + { "over-total-capacity", costs_plain, 32, 4, 0, 2, { { 1, 2, 0 }, { 1, 4, 0 } }, 0, 0 }, + { "ties", costs_tie, 32, 4, 0, 2, { { 1, 2, 0 }, { 3, 2, 0 } }, 0, 0 }, + { "exactly-at-budget", costs_plain, 32, 4, 0, 1, { { 1, 1, 0 } }, 0, 0 }, + { "one-byte-below", costs_plain, 32, 4, 0, 1, { { 1, 1, +1 } }, 0, 0 }, + { "one-byte-above", costs_plain, 32, 4, 0, 1, { { 1, 1, -1 } }, 0, 0 }, + { "spill-exhaustion", costs_spill, 32, 4, 2 * UNIT, 2, { { 1, 2, 0 }, { 1, 2, 0 } }, 0, 0 }, + { "evict-drain", costs_plain, 32, 4, 0, 3, { { 0, 1, 0 }, { 0, 1, 0 }, { 1, 2, 0 } }, 0, 0 }, + { "fanout-500", costs_plain, 500, 4, 0, 3, { { 3, 2, 0 }, { 1, 2, 0 }, { 1, 8, 0 } }, 0, 0 }, + { "rep-null", costs_plain, 32, 4, 0, 2, { { 1, 2, 0 }, { 3, 2, 0 } }, 1, 0 }, + { "record-tamper", costs_plain, 32, 4, 0, 2, { { 1, 2, 0 }, { 3, 2, 0 } }, 0, 1 }, + }; + for (size_t i = 0; i < sizeof scenarios / sizeof scenarios[0]; i++) run_scenario(&scenarios[i]); + + printf("DUAL_3A_JSPACE_TAP_PARITY=%s (failures=%d)\n", g_fail ? "FAIL" : "PASS", g_fail); + return g_fail ? 1 : 0; +} diff --git a/tests/runtime/rx_dual_jspace_tap_bench.c b/tests/runtime/rx_dual_jspace_tap_bench.c new file mode 100644 index 000000000..78a3dfbeb --- /dev/null +++ b/tests/runtime/rx_dual_jspace_tap_bench.c @@ -0,0 +1,177 @@ +/* + * rx_dual_jspace_tap_bench.c -- overhead of the DUAL-3a observation tap at + * decision site "jspace.residency". Public API only. + * + * Built twice by mk/dual_jspace_tap.mk: against the base commit's rx_jspace.c + * (-DDUAL_TAP_BENCH_BASE: observer-off leg only, the pre-change timing) and + * against the current one (observer off, then a recording observer that + * encodes and keeps every record). Same workload, fixed costs, trials + * interleaved; medians reported. Thresholds are pre-registered in + * evidence/DUAL/3a-jspace-tap/receipt.md, not here. + * + * Workload per round: make every unit resident again (untimed), then two timed + * js_forge_enforce calls: hot-arena SOFT case (budget 3/2 of residency) and + * over-total CAPACITY case (budget 1/2 of residency). + */ +#include "runtime/rx_jspace.h" + +#include <inttypes.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#define UNIT 4096u +#define FANOUT 256u +#define DEPTH 4u +#define ROUNDS 40 +#define TRIALS 7 + +static uint64_t splitmix(uint64_t *x) { + uint64_t z = (*x += 0x9e3779b97f4a7c15ull); + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + return z ^ (z >> 31); +} + +static void derive_sparse(const uint8_t *prev, uint64_t token, uint8_t *out, size_t n) { + uint64_t x = token; + if (!prev) { + for (size_t i = 0; i + 8 <= n; i += 8) { uint64_t v = splitmix(&x); memcpy(out + i, &v, 8); } + return; + } + memcpy(out, prev, n); + for (size_t i = (size_t)(token % 8) * 8; i + 8 <= n; i += 64) { + uint64_t v = splitmix(&x); + memcpy(out + i, &v, 8); + } +} + +static const JsRealizer RZ = { JS_REAL_LATENT_CHECKPOINT, "sparse", UNIT, derive_sparse }; + +static void costs_plain(JsSpace *s) { + JsCosts c = { 0 }; + c.derive_ns = (double)UNIT; + c.copy_ns_per_byte = 0.125; + c.move_ns_per_byte = 0.125; + c.compress_ns_per_byte = 0.5; + c.decompress_ns_per_byte = 0.5; + c.compress_ratio = 0.25; + c.spill_write_ns_per_byte = 2.0; + c.spill_read_ns_per_byte = 4.0; + c.retain_ns_per_byte = 1.0 / 1024.0; + s->costs = c; +} + +static uint64_t now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; +} + +#ifndef DUAL_TAP_BENCH_BASE +typedef struct { uint64_t records, bytes; uint8_t xor_digest[32]; } Sink; +static void sink(const JsDualObservation *o, const void *ctx) { + Sink *k = (Sink *)ctx; + uint8_t enc[JS_DUAL_OBS_BYTES]; + k->bytes += js_dual_observation_encode(o, enc); + for (int i = 0; i < 32; i++) k->xor_digest[i] ^= o->digest[i]; + k->records++; +} +#endif + +typedef struct { uint64_t wall_ns, decisions, records, bytes; } Trial; + +static Trial trial(int observe) { + Trial t = { 0, 0, 0, 0 }; + JsSpace s; + char path[96]; + snprintf(path, sizeof path, "/tmp/jstap_bench_%ld", (long)getpid()); + if (js_space_init(&s, path) != JS_OK) { fprintf(stderr, "init failed\n"); exit(2); } + costs_plain(&s); + uint32_t root; + js_branch_root(&s, &RZ, 7, &root); + for (unsigned i = 0; i < DEPTH; i++) js_branch_derive(&s, root, 100 + i); + for (unsigned k = 0; k < FANOUT; k++) { + uint32_t c; + js_branch_fork(&s, root, &c); + js_branch_derive(&s, c, 1000 + k); + } +#ifndef DUAL_TAP_BENCH_BASE + Sink snk; + memset(&snk, 0, sizeof snk); + if (observe) js_dual_set_observer(&s, sink, &snk); +#else + (void)observe; +#endif + for (int round = 0; round < ROUNDS; round++) { + for (uint32_t b = 0; b < JS_MAX_BRANCHES; b++) { + JsBranch *br = s.branches[b]; + if (!br) continue; + for (uint32_t i = 0; i < br->n_units; i++) js_real_restore(&s, br->units[i]); + } + JsPolicyReport rep; + uint64_t res = s.stats.resident_bytes; + memset(&rep, 0, sizeof rep); + uint64_t t0 = now_ns(); + js_forge_enforce(&s, res * 3 / 2, &rep); + uint64_t t1 = now_ns(); + t.wall_ns += t1 - t0; + t.decisions += rep.considered; + res = s.stats.resident_bytes; + memset(&rep, 0, sizeof rep); + t0 = now_ns(); + js_forge_enforce(&s, res / 2, &rep); + t1 = now_ns(); + t.wall_ns += t1 - t0; + t.decisions += rep.considered; + } +#ifndef DUAL_TAP_BENCH_BASE + t.records = snk.records; + t.bytes = snk.bytes; +#endif + js_space_destroy(&s); + return t; +} + +static int cmp_u64(const void *a, const void *b) { + uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; + return (x > y) - (x < y); +} + +static uint64_t median(uint64_t *v, int n) { qsort(v, n, sizeof *v, cmp_u64); return v[n / 2]; } + +int main(void) { +#ifdef DUAL_TAP_BENCH_BASE + const char *build = "base"; +#else + const char *build = "tap"; +#endif + uint64_t off[TRIALS], on[TRIALS]; + Trial last_off = { 0, 0, 0, 0 }, last_on = { 0, 0, 0, 0 }; + for (int i = 0; i < TRIALS; i++) { + last_off = trial(0); off[i] = last_off.wall_ns; +#ifndef DUAL_TAP_BENCH_BASE + last_on = trial(1); on[i] = last_on.wall_ns; +#else + on[i] = 0; +#endif + } + uint64_t m_off = median(off, TRIALS); +#ifdef DUAL_TAP_BENCH_BASE + (void)on; (void)last_on; +#endif + printf("bench[%s] observer=NULL median_wall_ns=%" PRIu64 " decisions=%" PRIu64 " records=0 bytes=0 " + "(rounds %d, trials %d, fanout %u, unit %u)\n", build, m_off, last_off.decisions, ROUNDS, TRIALS, FANOUT, UNIT); +#ifndef DUAL_TAP_BENCH_BASE + uint64_t m_on = median(on, TRIALS); + printf("bench[%s] observer=record median_wall_ns=%" PRIu64 " decisions=%" PRIu64 " records=%" PRIu64 " bytes=%" PRIu64 "\n", + build, m_on, last_on.decisions, last_on.records, last_on.bytes); + double per_record = last_on.records ? ((double)m_on - (double)m_off) / (double)last_on.records : 0; + printf("bench[%s] ratio_on_off=%.3f added_ns_per_record=%.1f records_equal_decisions=%s\n", + build, m_off ? (double)m_on / (double)m_off : 0, per_record, + last_on.records == last_on.decisions ? "yes" : "NO"); +#endif + return 0; +}