Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/a4d90512936f5bae # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#267 (code only) closed derived `a4d90512936f5bae` #267 Imported from GitHub aien-dev/omega-mv#267 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `559f6e5da0ee78565add0031cd0c1d990874765d` · Head `0899c412c33eb37a0012170de7604e4dbd4bf963` ### Apply it ``` git checkout -b patch-a4d90512936f5bae 559f6e5da0ee78565add0031cd0c1d990874765d curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/a4d90512936f5bae.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 267 0899c412c33eb37a0012170de7604e4dbd4bf963 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":267,"url":"https://github.com/aien-dev/omega-mv/pull/267","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:02Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 7587492c8..492355b59 100644 --- a/.crumb +++ b/.crumb @@ -51,8 +51,8 @@ "purpose": "Directory calibration. Purpose not yet described by a human." }, { - "digest": "8d5c3cf3a9e79394bc0eec459944b261a8a76df2b97d31bb1b027e05345b8932", - "last_commit": "834ee93", + "digest": "1e31dff42b3f696c641f95733d670af27b72f77bd0e1708d42e3a879e9e45ffc", + "last_commit": "403ef98", "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": "a94c180092a775bcca35a556f3baeabd78b7c203101df273e8d0fe1784a8033e", - "last_commit": "834ee93", + "digest": "4bd9775399bb986340328ed1b843506e06ba0cd3126269518e85669c3b79417f", + "last_commit": "403ef98", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -76,7 +76,7 @@ }, { "digest": "8178197a3e956890d6194e5b4fcc0e0b5c4ec67b0749f0d257f2ed17c8ca7465", - "last_commit": "cfd6716", + "last_commit": "559f6e5", "name": "research", "purpose": "Directory research. Purpose not yet described by a human." }, @@ -87,14 +87,14 @@ "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "21b5108bb68fda6f98b1f64d1c13e115b26a3e639c0994c230557282383c60dd", - "last_commit": "834ee93", + "digest": "4507760d5412654a2c14457a0a900a76a54dd99729acb54d764925bc6dad4d2b", + "last_commit": "403ef98", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "fd4612cad3b13815413dcb30e65d0b1ae796b19f0296b2942f29ef96b3ebe78f", - "last_commit": "834ee93", + "digest": "3cf64120d367b0ec3b8cb61415ddc3ba7f8b42e04c79d3a0e958b7eb8eef1622", + "last_commit": "403ef98", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, @@ -105,15 +105,15 @@ "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:a38f511e9e18d70372456f1c5f25dce89541dab4cdca2e5a5a294b08df8ce32d", - "compiled_at": "2026-10-04T18:19:24Z", + "children_root": "sha256:53c927616046363118eba9033e24e3cf283edad7f5369da568c4bbe306afbfbd", + "compiled_at": "2026-10-04T18:24:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:faf2d30aed5b89d6d8d443b4a8c9d481a8898a2fc854ff88a545e020dd60ca04", - "evidence_files": 1281, - "evidence_root": "sha256:dee3289b97696aca382dc07d6fb8efd69f5165225b425936c923bb4050d735e4", - "files": 3010, - "generated_at_commit": "cfd67162853eb0c0fbb73758e3dfb9837676e2a2", - "source_tree": "sha256:903a9252d33a0905a57aac27b3bc0b42f660b1588cb99808f35a3c823f7e7663" + "digest": "sha256:70665ffd4eae02082919ea7e35a2a9d98f763259a987b743e70c4b4fe20b75aa", + "evidence_files": 1283, + "evidence_root": "sha256:faaf0962528d6ab359bd4702bafe3a263a8c79ab6fc8802c0ea45ed0390c8e05", + "files": 3026, + "generated_at_commit": "403ef98a510f61d77f77c2033ecc31de82d2fc85", + "source_tree": "sha256:ef319b183d3499cb4129cf5a2a05c4c60abfe1dcf0e7d3c16a5c287775f38d90" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index 56bc5ceb1..b676081e1 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -112,14 +112,14 @@ } ], "children_root": "sha256:c250a1e7a18e576884d3bf007849954a7adbe0b0ab8d6e261303c62e67d8c34c", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:16:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:8d5c3cf3a9e79394bc0eec459944b261a8a76df2b97d31bb1b027e05345b8932", + "digest": "sha256:1e31dff42b3f696c641f95733d670af27b72f77bd0e1708d42e3a879e9e45ffc", "evidence_files": 26, "evidence_root": "sha256:f58236184eadc5f8c8f95499127a9f43c2f4dc702ddca267853d8c3dee0690f1", - "files": 98, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:4d8468afb7027b95cbab56c1d02d6494134f95ab9ecc1767beffbbdd868c44b7" + "files": 99, + "generated_at_commit": "41dcb768a955c1027d60d8b86d4ff6629118b9e6", + "source_tree": "sha256:4ed995ad9f9645169f2fbf1bbf513db9e0352b200eebfd674ad520d412805289" }, "owner_lane": "", "provenance": { diff --git a/docs/dual/DUAL_RECORDS.md b/docs/dual/DUAL_RECORDS.md new file mode 100644 index 000000000..06dd4ad92 --- /dev/null +++ b/docs/dual/DUAL_RECORDS.md @@ -0,0 +1,32 @@ +# DUAL records (DUAL-0a), ADR 0031 / ARCH-0031 + +Standalone module `src/dual/` (`mk/dual.mk`, targets `test-dual-types`, `dual-purity`, `test-dual`; not in `all` or `test`; +nothing under `src/runtime/` includes it). DUAL is scarcity information. It never authorizes, promotes or decides validity. + +## Records and kind bytes (format version 1) +| Kind | Byte | Domain | Fields (canonical little-endian order) | +|---|---|---|---| +| resource | 1 | `omega.dual.resource.v1` | u32 resource_id, u32 unit, f64 scale, dig contract | +| constraint | 2 | `omega.dual.constraint.v1` | u32 resource_id, u32 unit, u32 class, f64 budget, dig budget_contract, dig observation_ref, dig estimate_ref, u32 estimate_kind, f64 estimate, f64 uncertainty, dig calibration_ref, f64 lambda, u32 lambda_state, dig controller_id, u64 generation, u64 tick, dig evidence_root, dig parent | +| controller | 3 | `omega.dual.controller.v1` | f64 eta, f64 rho, f64 k_sigma, u64 max_age, u64 cadence, u32 n, n x (u32 resource_id, f64 lambda_max) | +| price vector | 4 | `omega.dual.pricevec.v1` | u64 generation, dig context, u32 n, n x (u32 resource_id, dig state) | +| recommendation | 5 | `omega.dual.recommendation.v1` | dig decision_site, dig price_vector, u64 generation, u32 n_candidates, n x dig, u32 actual, u32 recommended, u32 n_consequences, n x (u32 resource_id, u32 unit, f64 predicted, f64 predicted_sd, u32 has_measured, f64 measured, f64 error), u32 authority (= 0) | +| outcome | 6 | `omega.dual.outcome.v1` | dig recommendation, dig before_vector, dig after_vector, u32 target_resource_id, u64 generation_before, u64 generation_after, f64 lambda_before, f64 lambda_after | +| site | 7 | `omega.dual.site.v1` | u32 site_id, 32 bytes name (printable ASCII, NUL padded), dig owner, u32 max_alternatives | + +Every encoding starts with `u8 kind, u8 version`. Doubles are IEEE-754 binary64 bits; -0.0 is written as +0.0; NaN and Inf are +refused before encoding. Digest = SHA-256(domain || 0x00 || encoding). Decoders refuse a wrong kind byte, a wrong version, +truncation and trailing bytes, then run the same validation as the constructor. No wall-clock value is part of any identity. + +## Rules enforced by `rx_dual_check_*` (ADR 0031 section 3 and 4) +- Class: only `CAPACITY` (diagnostic price) and `SOFT` (priceable) construct. `INVARIANT` and an undeclared class are refused. +- Units: the unit registry is closed (`RxDualUnit`); `NONE` is refused; a constraint whose unit differs from its registry entry is refused (no implicit conversion). +- Scale strictly positive and finite. Uncertainty and lambda finite and nonnegative. lambda <= lambda_max is enforced by the controller (DUAL-1a). +- `FRESH` requires a calibration receipt digest; a zero `calibration_ref` may only be `UNCALIBRATED`, `STALE`, `FROZEN` or `REFUSED`. +- `MEASURED` requires an `observation_ref`. `estimate_ref`, `budget_contract`, `controller_id`, `evidence_root` are required. +- History: `tick == 0` iff `parent` is zero. +- Price vector: strictly ascending resource ids (duplicates and unordered input refused, never sorted), all states at one generation, nonzero context. +- Recommendation: `authority` must be `NONE`; indices in range; consequences in ascending resource order; `error` must equal the recomputed `(measured - predicted) / predicted_sd`; an unmeasured row carries zero. +- Controller: eta >= 0, rho in [0,1], k_sigma >= 0, max_age >= 1, cadence >= 1, per-resource lambda_max > 0, ascending ids. Any parameter change changes `controller_id`. + +Status: DUAL-0a, DUAL-0b (rx_dual_bind.h: binding to est_* records, evidence verification, FRESH/STALE/FROZEN/UNCALIBRATED/REFUSED) and DUAL-1a (rx_dual_update.h: reference update) IMPLEMENTED; `DUAL_CONSTRAINT_CONTRACT = PASS` on host (evidence/DUAL/0b-1a-binding-controller); `DUAL_PRICE_REFERENCE` waits for DUAL-1b replay. diff --git a/evidence/DUAL/0a-records/receipt.md b/evidence/DUAL/0a-records/receipt.md new file mode 100644 index 000000000..8f92257c9 --- /dev/null +++ b/evidence/DUAL/0a-records/receipt.md @@ -0,0 +1,45 @@ +# DUAL-0a receipt: records and registry (ADR 0031 section 4) + +| Field | Value | +|---|---| +| repository | aien-dev/omega | +| base commit | cb7cc216147664549484fcca8e8ceadbd6f6cdbf (GitHub main, fetched 2026-10-04) | +| candidate commit | (this commit; see git log) | +| working tree | clean at commit (crumb compiled last) | +| compiler | cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 | +| flags | EST_CFLAGS: -std=c11 -Wall -Wextra -Werror -pedantic -O2 -D_POSIX_C_SOURCE=200809L -ffp-contract=off -fno-fast-math; ASan/UBSan: -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all | +| host | Spark (aarch64 Linux); host-only; no GPU exercised | +| record schema | format version 1, kind bytes 1..7, domains omega.dual.*.v1 (docs/dual/DUAL_RECORDS.md) | + +## Baseline before changes (same tree at cb7cc216147664549484fcca8e8ceadbd6f6cdbf) +`make test-estimation test-inertial-alignment`: test_est_types PASS, test_est_kf PASS, est_ref PASS, test_ans 1372 checks PASS (plain and ASan); exit 0. + +## Commands and results +| Command | Result | +|---|---| +| `make dual-purity` | PASS: rx_dual.o references only memmove/memset/strlen/sha256_* (nm -u) | +| `make test-dual-types` (plain, PROP_ROUNDS=2000) | test_dual_types: 14107 checks, 0 failures: PASS | +| `make test-dual-types` (ASan/UBSan, PROP_ROUNDS=200) | test_dual_types: 1667 checks, 0 failures: PASS | + +## Hostile cases covered (all refused) +invalid kind byte; kind confusion (resource bytes decoded as constraint/outcome, constraint bytes as resource); unsupported version; +truncated encoding; trailing bytes; capacity-short buffer; negative scale; zero scale; NaN; +Inf; -Inf (scale, lambda, estimate, +budget, uncertainty, eta, lambda_max, predicted); negative lambda; negative uncertainty; unit NONE / unknown unit; unit mismatch +against registry; unknown resource id (registry find, controller lambda_max); duplicate resource (registry, controller, price vector, +recommendation consequences); unordered resource list (controller, price vector, builder); undeclared class; INVARIANT construction +(checker, digest, decoder bytes, price-vector builder); broken parent linkage both ways; missing estimate_ref / controller_id / +evidence_root / budget_contract / observation_ref (MEASURED); FRESH without calibration; recommendation authority != NONE (struct and +bytes); out-of-range actual/recommended; lying error field; unmeasured row with a value; outcome generation going backwards; +controller count above capacity in bytes; site name canonical padding / unterminated / non-printable. + +## Negative controls (mutants of src/dual/rx_dual.c, same suite) +| Mutant | Result | +|---|---| +| allow INVARIANT to construct | 14155 checks, 5 failures: FAIL (killed) | +| drop -0.0 canonicalization | 14107 checks, 1 failure: FAIL (killed) | +| accept trailing bytes | 14107 checks, 8 failures: FAIL (killed) | +| drop authority check | 14107 checks, 2 failures: FAIL (killed) | + +## Verdict +DUAL-0a: IMPLEMENTED, tests PASS on host. `DUAL_CONSTRAINT_CONTRACT`: NOT CLAIMED (needs DUAL-0b binding and staleness). +No production influence. No runtime linkage. diff --git a/evidence/DUAL/0b-1a-binding-controller/receipt.md b/evidence/DUAL/0b-1a-binding-controller/receipt.md new file mode 100644 index 000000000..5e8db9540 --- /dev/null +++ b/evidence/DUAL/0b-1a-binding-controller/receipt.md @@ -0,0 +1,40 @@ +# DUAL-0b + DUAL-1a receipt: ESTIMATION binding, staleness, reference controller (ADR 0031 s4.2, s5) + +| Field | Value | +|---|---| +| repository | aien-dev/omega | +| base commit | f056b77f64ee94a80f4ed2899b5f9495aa3ef840 (branch dual/0a-records, PR #266, on top of main cb7cc216147664549484fcca8e8ceadbd6f6cdbf) | +| candidate commit | this commit | +| compiler | cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 | +| flags | EST_CFLAGS (-std=c11 -Wall -Wextra -Werror -pedantic -O2 -ffp-contract=off -fno-fast-math) and EST_ASAN | +| host | Spark aarch64 Linux, host-only, no GPU | +| controller schema | RxDualController (eta, rho, k_sigma, max_age, cadence, per-resource lambda_max), digest domain omega.dual.controller.v1 = controller_id | + +## Commands and results +| Command | Result | +|---|---| +| make dual-purity | PASS (rx_dual.o, rx_dual_bind.o, rx_dual_update.o: no authority/promotion/process symbol) | +| make test-dual-types | 14107 / 1667 (ASan) checks, 0 failures | +| make test-dual-bind | 85 / 85 checks, 0 failures | +| make test-dual-update | 355348 / 35837 (ASan) checks, 0 failures | + +## What is proven +- Binding: estimate and uncertainty are copied from est_belief / est_prediction / est_observation and the record digest is cited; a prediction must cite the exact model (unit source) and prior belief (evidence source) by digest; a declared prior (zero evidence root) is refused as evidence; est units map by one explicit table, NONE/unknown refused. +- Evidence: a belief's root must equal est_evidence_root_extend(parent_root, digest(obs)); broken root, wrong observation, wrong parent root and an input not bound from the belief are all refused. The DUAL state root chains estimate_ref digests with the same primitive. +- Classification: REFUSED (NaN/Inf/negative uncertainty/missing digests/future generation), STALE (age > max_age, older than prev, unverified evidence), FROZEN (regime signal), UNCALIBRATED (no EST-3 receipt), FRESH; unit mismatch is a structural refusal (no conversion). +- Controller: analytic cases match the independent closed form (tests/dual/dual_ref.c, derived on paper from s5.1) to 1e-9: single binding constraint, slack constraint decaying to 0, two competing constraints, inside-deadband no movement, clip saturation, zero eta no movement, rho>0 geometric forgetting; byte-identical records for identical inputs. Property suite (3000 rounds x 39 ticks): lambda finite, 0 <= lambda <= lambda_max, held under STALE, equals clipped recursion otherwise. Held states keep lambda, estimate, generation and evidence root; parent/tick advance. Parameter mutation (controller_id mismatch), unknown resource, unit/id mismatch, zero/negative scale, INVARIANT class, lambda above max, malformed parent, overflow to Inf are refused with no record. + +## Negative controls (mutants, same suites) +| Mutant | Result | +|---|---| +| remove lambda_max clipping | test_dual_update 35634 failures: FAIL (killed) | +| remove deadband (g always = pressure) | test_dual_update 1052 failures: FAIL (killed) | +| remove controller_id check | test_dual_update 1 failure: FAIL (killed) | +| unverified evidence no longer STALE | test_dual_bind 1 failure: FAIL (killed) | +| evidence root comparison removed | test_dual_bind 4 failures: FAIL (killed) | + +## Verdict +DUAL-0b IMPLEMENTED. DUAL-1a IMPLEMENTED. DUAL_CONSTRAINT_CONTRACT: PASS on host for the record/binding contract (typed records, +canonical round trip, kind bytes and digest domains, unit registry, class rules, staleness detection, property tests, zero runtime +linkage). DUAL_PRICE_REFERENCE: NOT YET CLAIMED (needs DUAL-1b replay on digest-bound traces with the oscillation bound). +No production influence. EST-3 remains FAILED on main, so no price may control anything. diff --git a/mk/.crumb b/mk/.crumb index cd0aba25e..a659d4fd8 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:16:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:a94c180092a775bcca35a556f3baeabd78b7c203101df273e8d0fe1784a8033e", + "digest": "sha256:4bd9775399bb986340328ed1b843506e06ba0cd3126269518e85669c3b79417f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 49, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:aa4056f2e1b37177d3fe9f3a0a7cfa07ea3c654890200e78a01ddf7e5d9e7d55" + "files": 50, + "generated_at_commit": "41dcb768a955c1027d60d8b86d4ff6629118b9e6", + "source_tree": "sha256:078bf208413c507fba44fb779fa801998ee5f961aae7cb0575d3957c1eaf5ca8" }, "owner_lane": "", "provenance": { diff --git a/mk/dual.mk b/mk/dual.mk new file mode 100644 index 000000000..7f73d0c2c --- /dev/null +++ b/mk/dual.mk @@ -0,0 +1,73 @@ +# DUAL, constraint pricing for soft resource budgets (ADR 0031 / ARCH-0031). +# Standalone: new files only under src/dual/, tests/dual/, docs/dual/. Picked up +# by `-include mk/*.mk`; not part of `all` or `test`. Nothing in src/runtime/ +# includes or links it. DUAL is scarcity information: it never authorizes, +# never promotes, never decides validity. +# +# test-dual-types DUAL-0a contract: validation, refusal, canonical encoding, digests, properties +# dual-purity nm -u on every dual object against authority / promotion / process symbols +# test-dual everything above, plain + ASan/UBSan +ifndef DUAL_MK +DUAL_MK := 1 +include mk/estimation.mk +.PHONY: test-dual-types test-dual-bind test-dual-update dual-purity test-dual +DUAL_CFLAGS = $(EST_CFLAGS) -Isrc/dual -Itests/dual +DUAL_DIR = $(OUT_DIR)/tests-dual +DUAL_CORE_SRCS = src/dual/rx_dual.c src/sha256.c +DUAL_SRCS = src/dual/rx_dual.c src/dual/rx_dual_bind.c src/dual/rx_dual_update.c $(EST_TYPES_SRCS) +DUAL_HDRS = src/dual/rx_dual.h src/dual/rx_dual_bind.h src/dual/rx_dual_update.h $(EST_HDRS) +# A price is information, not authority: no capability, promotion, generation +# administration, World, ARGUS, AEGIS, memory-mapping or process symbol. +DUAL_FORBIDDEN = 'aienos_|rx_gen_|rx_cap|rx_world|rx_js|argus_|forge_|aegis|mmap|mprotect|fork|exec|dlopen|system|socket|fopen|open$$' + +$(DUAL_DIR)/%.o: src/dual/%.c $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) -c -o $@ $< + +dual-purity: $(DUAL_DIR)/rx_dual.o $(DUAL_DIR)/rx_dual_bind.o $(DUAL_DIR)/rx_dual_update.o + @if nm -u $^ | grep -E $(DUAL_FORBIDDEN) ; then \ + echo "dual object references an operation a pricing module must not have"; exit 1; fi + @echo "dual-purity: $(notdir $^) reference no authority, promotion or process symbol" + +$(DUAL_DIR)/test_dual_types: tests/dual/test_dual_types.c $(DUAL_CORE_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) -o $@ tests/dual/test_dual_types.c $(DUAL_CORE_SRCS) -lm +$(DUAL_DIR)/test_dual_types_asan: tests/dual/test_dual_types.c $(DUAL_CORE_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) $(EST_ASAN) -DPROP_ROUNDS=200 -o $@ tests/dual/test_dual_types.c $(DUAL_CORE_SRCS) -lm + +test-dual-types: $(DUAL_DIR)/test_dual_types $(DUAL_DIR)/test_dual_types_asan + ./$(DUAL_DIR)/test_dual_types + ./$(DUAL_DIR)/test_dual_types_asan + @echo "test-dual-types: DUAL-0a contract checks pass in plain and ASan/UBSan builds" + +test-dual: dual-purity test-dual-types test-dual-bind test-dual-update + @echo "test-dual: DUAL standalone module passes" +endif + +# DUAL-0b binding and DUAL-1a controller (appended; same fragment) +ifndef DUAL_MK_2 +DUAL_MK_2 := 1 +$(DUAL_DIR)/test_dual_bind: tests/dual/test_dual_bind.c tests/dual/dual_fixtures.h $(DUAL_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) -o $@ tests/dual/test_dual_bind.c $(DUAL_SRCS) -lm +$(DUAL_DIR)/test_dual_bind_asan: tests/dual/test_dual_bind.c tests/dual/dual_fixtures.h $(DUAL_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) $(EST_ASAN) -o $@ tests/dual/test_dual_bind.c $(DUAL_SRCS) -lm +test-dual-bind: $(DUAL_DIR)/test_dual_bind $(DUAL_DIR)/test_dual_bind_asan + ./$(DUAL_DIR)/test_dual_bind + ./$(DUAL_DIR)/test_dual_bind_asan + @echo "test-dual-bind: DUAL-0b binding and staleness checks pass in plain and ASan/UBSan builds" + +DUAL_REF_SRCS = tests/dual/dual_ref.c +$(DUAL_DIR)/test_dual_update: tests/dual/test_dual_update.c tests/dual/dual_fixtures.h tests/dual/dual_ref.h $(DUAL_REF_SRCS) $(DUAL_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) -o $@ tests/dual/test_dual_update.c $(DUAL_REF_SRCS) $(DUAL_SRCS) -lm +$(DUAL_DIR)/test_dual_update_asan: tests/dual/test_dual_update.c tests/dual/dual_fixtures.h tests/dual/dual_ref.h $(DUAL_REF_SRCS) $(DUAL_SRCS) $(DUAL_HDRS) + @mkdir -p $(DUAL_DIR) + $(CC) $(DUAL_CFLAGS) $(EST_ASAN) -DPROP_ROUNDS=300 -o $@ tests/dual/test_dual_update.c $(DUAL_REF_SRCS) $(DUAL_SRCS) -lm +test-dual-update: $(DUAL_DIR)/test_dual_update $(DUAL_DIR)/test_dual_update_asan + ./$(DUAL_DIR)/test_dual_update + ./$(DUAL_DIR)/test_dual_update_asan + @echo "test-dual-update: DUAL-1a reference update passes analytic, property and refusal checks in plain and ASan/UBSan builds" +endif diff --git a/src/.crumb b/src/.crumb index 5e8a4e947..56d340d21 100644 --- a/src/.crumb +++ b/src/.crumb @@ -164,14 +164,14 @@ } ], "children_root": "sha256:342b19861dd2ee471546469278de0fa357eed3720995ee57366bbaaf75cf4f49", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:16:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:21b5108bb68fda6f98b1f64d1c13e115b26a3e639c0994c230557282383c60dd", + "digest": "sha256:4507760d5412654a2c14457a0a900a76a54dd99729acb54d764925bc6dad4d2b", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 390, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:96cf34ca55d22ef1c0686794dd4339261248ee1a8b9b5214cc9f1ce11b3a8296" + "files": 396, + "generated_at_commit": "41dcb768a955c1027d60d8b86d4ff6629118b9e6", + "source_tree": "sha256:ae9262b9e9d06668b482e95027148f7c5df9a94c6a276adaf19e02588f09c29e" }, "owner_lane": "", "provenance": { diff --git a/src/dual/rx_dual.c b/src/dual/rx_dual.c new file mode 100644 index 000000000..cc16f38a7 --- /dev/null +++ b/src/dual/rx_dual.c @@ -0,0 +1,645 @@ +/* DUAL-0a: typed records, registry, validation, canonical encoding and + * digests (ADR 0031 section 4). See rx_dual.h for the contract. */ +#include "rx_dual.h" +#include "sha256.h" + +#include +#include + +/* ---------------------------------------------------------------- helpers */ +int rx_dual_digest_is_zero(const RxDualDigest *d) +{ + uint8_t acc = 0; + if (!d) return 1; + for (size_t i = 0; i < RX_DUAL_DIGEST_SIZE; i++) acc |= d->b[i]; + return acc == 0; +} +int rx_dual_digest_eq(const RxDualDigest *a, const RxDualDigest *b) +{ + if (!a || !b) return 0; + return memcmp(a->b, b->b, RX_DUAL_DIGEST_SIZE) == 0; +} +int rx_dual_unit_valid(RxDualUnit u) +{ + return (uint32_t)u > (uint32_t)RX_DUAL_UNIT_NONE && (uint32_t)u < (uint32_t)RX_DUAL_UNIT_MAX_; +} +static int fin(double d) { return isfinite(d) != 0; } +static int ids_ascending(const uint32_t *ids, uint32_t n) +{ + for (uint32_t i = 1; i < n; i++) if (ids[i] <= ids[i - 1]) return 0; + return 1; +} + +/* ----------------------------------------------------------------- writer */ +typedef struct { uint8_t *p; size_t cap, pos; int overflow; } wr; +static void w_raw(wr *w, const uint8_t *src, size_t n) +{ + if (w->pos + n > w->cap) { w->overflow = 1; w->pos += n; return; } + memcpy(w->p + w->pos, src, n); + w->pos += n; +} +static void w_u8(wr *w, uint8_t v) { w_raw(w, &v, 1); } +static void w_u32(wr *w, uint32_t v) +{ + uint8_t b[4]; + for (int i = 0; i < 4; i++) b[i] = (uint8_t)(v >> (8 * i)); + w_raw(w, b, 4); +} +static void w_u64(wr *w, uint64_t v) +{ + uint8_t b[8]; + for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); + w_raw(w, b, 8); +} +static void w_f64(wr *w, double d) +{ + uint64_t u = 0; /* +0.0 and -0.0 both encode as all-zero bits */ + if (d != 0.0) memcpy(&u, &d, 8); + w_u64(w, u); +} +static void w_dig(wr *w, const RxDualDigest *d) { w_raw(w, d->b, RX_DUAL_DIGEST_SIZE); } +static void w_hdr(wr *w, RxDualKind k) { w_u8(w, (uint8_t)k); w_u8(w, (uint8_t)RX_DUAL_FORMAT_VERSION); } + +/* ----------------------------------------------------------------- reader */ +typedef struct { const uint8_t *p; size_t len, pos; RxDualStatus st; } rd; +static void r_fail(rd *r, RxDualStatus s) { if (r->st == RX_DUAL_OK) r->st = s; } +static int r_need(rd *r, size_t n) +{ + if (r->st != RX_DUAL_OK) return 0; + if (r->pos + n > r->len) { r_fail(r, RX_DUAL_ERR_ENCODING); return 0; } + return 1; +} +static uint8_t r_u8(rd *r) +{ + if (!r_need(r, 1)) return 0; + return r->p[r->pos++]; +} +static uint32_t r_u32(rd *r) +{ + uint32_t v = 0; + if (!r_need(r, 4)) return 0; + for (int i = 0; i < 4; i++) v |= (uint32_t)r->p[r->pos + (size_t)i] << (8 * i); + r->pos += 4; + return v; +} +static uint64_t r_u64(rd *r) +{ + uint64_t v = 0; + if (!r_need(r, 8)) return 0; + for (int i = 0; i < 8; i++) v |= (uint64_t)r->p[r->pos + (size_t)i] << (8 * i); + r->pos += 8; + return v; +} +static double r_f64(rd *r) +{ + uint64_t u = r_u64(r); + double d; + memcpy(&d, &u, 8); + return d; +} +static void r_dig(rd *r, RxDualDigest *d) +{ + if (!r_need(r, RX_DUAL_DIGEST_SIZE)) { memset(d, 0, sizeof *d); return; } + memcpy(d->b, r->p + r->pos, RX_DUAL_DIGEST_SIZE); + r->pos += RX_DUAL_DIGEST_SIZE; +} +static void r_hdr(rd *r, RxDualKind want) +{ + uint8_t k = r_u8(r), v = r_u8(r); + if (r->st != RX_DUAL_OK) return; + if (k != (uint8_t)want) { r_fail(r, RX_DUAL_ERR_KIND); return; } + if (v != (uint8_t)RX_DUAL_FORMAT_VERSION) r_fail(r, RX_DUAL_ERR_ENCODING); +} +static RxDualStatus r_end(rd *r) +{ + if (r->st != RX_DUAL_OK) return r->st; + if (r->pos != r->len) return RX_DUAL_ERR_ENCODING; /* trailing bytes */ + return RX_DUAL_OK; +} + +/* ------------------------------------------------------------- validation */ +RxDualStatus rx_dual_check_resource(const RxDualResource *r) +{ + if (!r) return RX_DUAL_ERR_NULL; + if (!rx_dual_unit_valid(r->unit)) return RX_DUAL_ERR_UNIT; + if (!fin(r->scale)) return RX_DUAL_ERR_NONFINITE; + if (!(r->scale > 0.0)) return RX_DUAL_ERR_SCALE; + if (rx_dual_digest_is_zero(&r->contract)) return RX_DUAL_ERR_DIGEST; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_constraint(const RxDualConstraintState *s) +{ + if (!s) return RX_DUAL_ERR_NULL; + if (!rx_dual_unit_valid(s->unit)) return RX_DUAL_ERR_UNIT; + /* INVARIANT is unconstructible; UNDECLARED is never defaulted. */ + if (s->cls != RX_DUAL_CLASS_CAPACITY && s->cls != RX_DUAL_CLASS_SOFT) return RX_DUAL_ERR_CLASS; + if (!fin(s->budget) || !fin(s->estimate) || !fin(s->uncertainty) || !fin(s->lambda)) + return RX_DUAL_ERR_NONFINITE; + if (s->uncertainty < 0.0 || s->lambda < 0.0) return RX_DUAL_ERR_RANGE; + if ((uint32_t)s->estimate_kind < 1u || (uint32_t)s->estimate_kind >= (uint32_t)RX_DUAL_EST_MAX_) + return RX_DUAL_ERR_KIND; + if ((uint32_t)s->lambda_state < 1u || (uint32_t)s->lambda_state >= (uint32_t)RX_DUAL_LAMBDA_MAX_) + return RX_DUAL_ERR_RANGE; + if (rx_dual_digest_is_zero(&s->budget_contract) || rx_dual_digest_is_zero(&s->estimate_ref) || + rx_dual_digest_is_zero(&s->controller_id) || rx_dual_digest_is_zero(&s->evidence_root)) + return RX_DUAL_ERR_DIGEST; + if (s->estimate_kind == RX_DUAL_EST_MEASURED && rx_dual_digest_is_zero(&s->observation_ref)) + return RX_DUAL_ERR_DIGEST; + if (rx_dual_digest_is_zero(&s->calibration_ref) && s->lambda_state == RX_DUAL_LAMBDA_FRESH) + return RX_DUAL_ERR_CALIBRATION; + if ((s->tick == 0) != (rx_dual_digest_is_zero(&s->parent) != 0)) return RX_DUAL_ERR_DIGEST; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_constraint_against(const RxDualConstraintState *s, const RxDualResource *r) +{ + RxDualStatus st; + if (!s || !r) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_constraint(s)) != RX_DUAL_OK) return st; + if ((st = rx_dual_check_resource(r)) != RX_DUAL_OK) return st; + if (s->resource_id != r->resource_id) return RX_DUAL_ERR_RESOURCE; + if (s->unit != r->unit) return RX_DUAL_ERR_UNIT; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_controller(const RxDualController *c) +{ + if (!c) return RX_DUAL_ERR_NULL; + if (!fin(c->eta) || !fin(c->rho) || !fin(c->k_sigma)) return RX_DUAL_ERR_NONFINITE; + if (c->eta < 0.0 || c->rho < 0.0 || c->rho > 1.0 || c->k_sigma < 0.0) return RX_DUAL_ERR_RANGE; + if (c->max_age == 0 || c->cadence == 0) return RX_DUAL_ERR_RANGE; + if (c->n == 0 || c->n > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + if (!ids_ascending(c->resource_id, c->n)) return RX_DUAL_ERR_RESOURCE; + for (uint32_t i = 0; i < c->n; i++) { + if (!fin(c->lambda_max[i])) return RX_DUAL_ERR_NONFINITE; + if (!(c->lambda_max[i] > 0.0)) return RX_DUAL_ERR_RANGE; + } + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_controller_lambda_max(const RxDualController *c, uint32_t resource_id, double *out) +{ + RxDualStatus st; + if (!c || !out) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_controller(c)) != RX_DUAL_OK) return st; + for (uint32_t i = 0; i < c->n; i++) + if (c->resource_id[i] == resource_id) { *out = c->lambda_max[i]; return RX_DUAL_OK; } + return RX_DUAL_ERR_RESOURCE; +} + +RxDualStatus rx_dual_check_price_vector(const RxDualPriceVector *v) +{ + if (!v) return RX_DUAL_ERR_NULL; + if (rx_dual_digest_is_zero(&v->context)) return RX_DUAL_ERR_DIGEST; + if (v->n == 0 || v->n > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + if (!ids_ascending(v->resource_id, v->n)) return RX_DUAL_ERR_RESOURCE; + for (uint32_t i = 0; i < v->n; i++) + if (rx_dual_digest_is_zero(&v->state[i])) return RX_DUAL_ERR_DIGEST; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_site(const RxDualSite *s) +{ + size_t i, end; + if (!s) return RX_DUAL_ERR_NULL; + if (s->name[0] == 0 || s->name[RX_DUAL_SITE_NAME_SIZE - 1] != 0) return RX_DUAL_ERR_SITE; + for (end = 0; end < RX_DUAL_SITE_NAME_SIZE && s->name[end] != 0; end++) + if (s->name[end] < 0x21 || s->name[end] > 0x7E) return RX_DUAL_ERR_SITE; + for (i = end; i < RX_DUAL_SITE_NAME_SIZE; i++) + if (s->name[i] != 0) return RX_DUAL_ERR_SITE; /* canonical NUL padding */ + if (rx_dual_digest_is_zero(&s->owner)) return RX_DUAL_ERR_DIGEST; + if (s->max_alternatives == 0 || s->max_alternatives > RX_DUAL_MAX_CANDIDATES) return RX_DUAL_ERR_RANGE; + return RX_DUAL_OK; +} + +static RxDualStatus check_consequence(const RxDualConsequence *c) +{ + if (!rx_dual_unit_valid(c->unit)) return RX_DUAL_ERR_UNIT; + if (!fin(c->predicted) || !fin(c->predicted_sd) || !fin(c->measured) || !fin(c->error)) + return RX_DUAL_ERR_NONFINITE; + if (c->predicted_sd < 0.0) return RX_DUAL_ERR_RANGE; + if (c->has_measured > 1u) return RX_DUAL_ERR_RANGE; + if (c->has_measured) { + double e; + if (!(c->predicted_sd > 0.0)) return RX_DUAL_ERR_RANGE; + e = (c->measured - c->predicted) / c->predicted_sd; + if (!fin(e)) return RX_DUAL_ERR_NONFINITE; + if (!(e == c->error)) return RX_DUAL_ERR_RANGE; /* error must be the recomputed value */ + } else if (c->measured != 0.0 || c->error != 0.0) { + return RX_DUAL_ERR_RANGE; + } + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_recommendation(const RxDualRecommendation *r) +{ + if (!r) return RX_DUAL_ERR_NULL; + if (r->authority != RX_DUAL_AUTHORITY_NONE) return RX_DUAL_ERR_AUTHORITY; + if (rx_dual_digest_is_zero(&r->decision_site) || rx_dual_digest_is_zero(&r->price_vector)) + return RX_DUAL_ERR_DIGEST; + if (r->n_candidates == 0 || r->n_candidates > RX_DUAL_MAX_CANDIDATES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < r->n_candidates; i++) + if (rx_dual_digest_is_zero(&r->candidates[i])) return RX_DUAL_ERR_DIGEST; + if (r->actual >= r->n_candidates || r->recommended >= r->n_candidates) return RX_DUAL_ERR_RANGE; + if (r->n_consequences > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < r->n_consequences; i++) { + RxDualStatus st = check_consequence(&r->c[i]); + if (st != RX_DUAL_OK) return st; + if (i > 0 && r->c[i].resource_id <= r->c[i - 1].resource_id) return RX_DUAL_ERR_RESOURCE; + } + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_outcome(const RxDualOutcome *o) +{ + if (!o) return RX_DUAL_ERR_NULL; + if (rx_dual_digest_is_zero(&o->recommendation) || rx_dual_digest_is_zero(&o->before_vector) || + rx_dual_digest_is_zero(&o->after_vector)) + return RX_DUAL_ERR_DIGEST; + if (o->generation_after < o->generation_before) return RX_DUAL_ERR_GENERATION; + if (!fin(o->lambda_before) || !fin(o->lambda_after)) return RX_DUAL_ERR_NONFINITE; + if (o->lambda_before < 0.0 || o->lambda_after < 0.0) return RX_DUAL_ERR_RANGE; + return RX_DUAL_OK; +} + +/* --------------------------------------------------------------- registry */ +void rx_dual_registry_init(RxDualRegistry *reg) { if (reg) memset(reg, 0, sizeof *reg); } + +RxDualStatus rx_dual_registry_add(RxDualRegistry *reg, const RxDualResource *r) +{ + RxDualStatus st; + uint32_t pos; + if (!reg) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_resource(r)) != RX_DUAL_OK) return st; + for (pos = 0; pos < reg->n && reg->r[pos].resource_id < r->resource_id; pos++) {} + if (pos < reg->n && reg->r[pos].resource_id == r->resource_id) return RX_DUAL_ERR_RESOURCE; + if (reg->n >= RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_FULL; + for (uint32_t i = reg->n; i > pos; i--) reg->r[i] = reg->r[i - 1]; + reg->r[pos] = *r; + reg->n++; + return RX_DUAL_OK; +} + +const RxDualResource *rx_dual_registry_find(const RxDualRegistry *reg, uint32_t resource_id) +{ + if (!reg) return NULL; + for (uint32_t i = 0; i < reg->n; i++) + if (reg->r[i].resource_id == resource_id) return ®->r[i]; + return NULL; +} + +/* --------------------------------------------------------- encode / decode */ +static RxDualStatus finish(const wr *w, size_t *len) +{ + if (w->overflow) return RX_DUAL_ERR_ENCODING; + if (len) *len = w->pos; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_encode_resource(const RxDualResource *r, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_resource(r); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_RESOURCE); + w_u32(&w, r->resource_id); + w_u32(&w, (uint32_t)r->unit); + w_f64(&w, r->scale); + w_dig(&w, &r->contract); + return finish(&w, len); +} +RxDualStatus rx_dual_decode_resource(const uint8_t *buf, size_t len, RxDualResource *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_RESOURCE); + out->resource_id = r_u32(&r); + out->unit = (RxDualUnit)r_u32(&r); + out->scale = r_f64(&r); + r_dig(&r, &out->contract); + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_resource(out); +} + +RxDualStatus rx_dual_encode_constraint(const RxDualConstraintState *s, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_constraint(s); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_CONSTRAINT); + w_u32(&w, s->resource_id); + w_u32(&w, (uint32_t)s->unit); + w_u32(&w, (uint32_t)s->cls); + w_f64(&w, s->budget); + w_dig(&w, &s->budget_contract); + w_dig(&w, &s->observation_ref); + w_dig(&w, &s->estimate_ref); + w_u32(&w, (uint32_t)s->estimate_kind); + w_f64(&w, s->estimate); + w_f64(&w, s->uncertainty); + w_dig(&w, &s->calibration_ref); + w_f64(&w, s->lambda); + w_u32(&w, (uint32_t)s->lambda_state); + w_dig(&w, &s->controller_id); + w_u64(&w, s->generation); + w_u64(&w, s->tick); + w_dig(&w, &s->evidence_root); + w_dig(&w, &s->parent); + return finish(&w, len); +} +RxDualStatus rx_dual_decode_constraint(const uint8_t *buf, size_t len, RxDualConstraintState *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_CONSTRAINT); + out->resource_id = r_u32(&r); + out->unit = (RxDualUnit)r_u32(&r); + out->cls = (RxDualClass)r_u32(&r); + out->budget = r_f64(&r); + r_dig(&r, &out->budget_contract); + r_dig(&r, &out->observation_ref); + r_dig(&r, &out->estimate_ref); + out->estimate_kind = (RxDualEstimateKind)r_u32(&r); + out->estimate = r_f64(&r); + out->uncertainty = r_f64(&r); + r_dig(&r, &out->calibration_ref); + out->lambda = r_f64(&r); + out->lambda_state = (RxDualLambdaState)r_u32(&r); + r_dig(&r, &out->controller_id); + out->generation = r_u64(&r); + out->tick = r_u64(&r); + r_dig(&r, &out->evidence_root); + r_dig(&r, &out->parent); + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_constraint(out); +} + +RxDualStatus rx_dual_encode_controller(const RxDualController *c, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_controller(c); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_CONTROLLER); + w_f64(&w, c->eta); + w_f64(&w, c->rho); + w_f64(&w, c->k_sigma); + w_u64(&w, c->max_age); + w_u64(&w, c->cadence); + w_u32(&w, c->n); + for (uint32_t i = 0; i < c->n; i++) { w_u32(&w, c->resource_id[i]); w_f64(&w, c->lambda_max[i]); } + return finish(&w, len); +} +RxDualStatus rx_dual_decode_controller(const uint8_t *buf, size_t len, RxDualController *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_CONTROLLER); + out->eta = r_f64(&r); + out->rho = r_f64(&r); + out->k_sigma = r_f64(&r); + out->max_age = r_u64(&r); + out->cadence = r_u64(&r); + out->n = r_u32(&r); + if (r.st != RX_DUAL_OK) return r.st; + if (out->n == 0 || out->n > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < out->n; i++) { out->resource_id[i] = r_u32(&r); out->lambda_max[i] = r_f64(&r); } + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_controller(out); +} + +RxDualStatus rx_dual_encode_price_vector(const RxDualPriceVector *v, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_price_vector(v); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_PRICE_VECTOR); + w_u64(&w, v->generation); + w_dig(&w, &v->context); + w_u32(&w, v->n); + for (uint32_t i = 0; i < v->n; i++) { w_u32(&w, v->resource_id[i]); w_dig(&w, &v->state[i]); } + return finish(&w, len); +} +RxDualStatus rx_dual_decode_price_vector(const uint8_t *buf, size_t len, RxDualPriceVector *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_PRICE_VECTOR); + out->generation = r_u64(&r); + r_dig(&r, &out->context); + out->n = r_u32(&r); + if (r.st != RX_DUAL_OK) return r.st; + if (out->n == 0 || out->n > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < out->n; i++) { out->resource_id[i] = r_u32(&r); r_dig(&r, &out->state[i]); } + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_price_vector(out); +} + +RxDualStatus rx_dual_encode_site(const RxDualSite *s, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_site(s); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_SITE); + w_u32(&w, s->site_id); + w_raw(&w, s->name, RX_DUAL_SITE_NAME_SIZE); + w_dig(&w, &s->owner); + w_u32(&w, s->max_alternatives); + return finish(&w, len); +} +RxDualStatus rx_dual_decode_site(const uint8_t *buf, size_t len, RxDualSite *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_SITE); + out->site_id = r_u32(&r); + if (r_need(&r, RX_DUAL_SITE_NAME_SIZE)) { memcpy(out->name, r.p + r.pos, RX_DUAL_SITE_NAME_SIZE); r.pos += RX_DUAL_SITE_NAME_SIZE; } + r_dig(&r, &out->owner); + out->max_alternatives = r_u32(&r); + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_site(out); +} + +RxDualStatus rx_dual_encode_recommendation(const RxDualRecommendation *rc, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_recommendation(rc); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_RECOMMENDATION); + w_dig(&w, &rc->decision_site); + w_dig(&w, &rc->price_vector); + w_u64(&w, rc->generation); + w_u32(&w, rc->n_candidates); + for (uint32_t i = 0; i < rc->n_candidates; i++) w_dig(&w, &rc->candidates[i]); + w_u32(&w, rc->actual); + w_u32(&w, rc->recommended); + w_u32(&w, rc->n_consequences); + for (uint32_t i = 0; i < rc->n_consequences; i++) { + const RxDualConsequence *c = &rc->c[i]; + w_u32(&w, c->resource_id); + w_u32(&w, (uint32_t)c->unit); + w_f64(&w, c->predicted); + w_f64(&w, c->predicted_sd); + w_u32(&w, c->has_measured); + w_f64(&w, c->measured); + w_f64(&w, c->error); + } + w_u32(&w, rc->authority); + return finish(&w, len); +} +RxDualStatus rx_dual_decode_recommendation(const uint8_t *buf, size_t len, RxDualRecommendation *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_RECOMMENDATION); + r_dig(&r, &out->decision_site); + r_dig(&r, &out->price_vector); + out->generation = r_u64(&r); + out->n_candidates = r_u32(&r); + if (r.st != RX_DUAL_OK) return r.st; + if (out->n_candidates == 0 || out->n_candidates > RX_DUAL_MAX_CANDIDATES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < out->n_candidates; i++) r_dig(&r, &out->candidates[i]); + out->actual = r_u32(&r); + out->recommended = r_u32(&r); + out->n_consequences = r_u32(&r); + if (r.st != RX_DUAL_OK) return r.st; + if (out->n_consequences > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + for (uint32_t i = 0; i < out->n_consequences; i++) { + RxDualConsequence *c = &out->c[i]; + c->resource_id = r_u32(&r); + c->unit = (RxDualUnit)r_u32(&r); + c->predicted = r_f64(&r); + c->predicted_sd = r_f64(&r); + c->has_measured = r_u32(&r); + c->measured = r_f64(&r); + c->error = r_f64(&r); + } + out->authority = r_u32(&r); + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_recommendation(out); +} + +RxDualStatus rx_dual_encode_outcome(const RxDualOutcome *o, uint8_t *buf, size_t cap, size_t *len) +{ + wr w = { buf, buf ? cap : 0, 0, 0 }; + RxDualStatus st = rx_dual_check_outcome(o); + if (st != RX_DUAL_OK) return st; + if (!buf) return RX_DUAL_ERR_NULL; + w_hdr(&w, RX_DUAL_KIND_OUTCOME); + w_dig(&w, &o->recommendation); + w_dig(&w, &o->before_vector); + w_dig(&w, &o->after_vector); + w_u32(&w, o->target_resource_id); + w_u64(&w, o->generation_before); + w_u64(&w, o->generation_after); + w_f64(&w, o->lambda_before); + w_f64(&w, o->lambda_after); + return finish(&w, len); +} +RxDualStatus rx_dual_decode_outcome(const uint8_t *buf, size_t len, RxDualOutcome *out) +{ + rd r = { buf, len, 0, RX_DUAL_OK }; + RxDualStatus st; + if (!buf || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + r_hdr(&r, RX_DUAL_KIND_OUTCOME); + r_dig(&r, &out->recommendation); + r_dig(&r, &out->before_vector); + r_dig(&r, &out->after_vector); + out->target_resource_id = r_u32(&r); + out->generation_before = r_u64(&r); + out->generation_after = r_u64(&r); + out->lambda_before = r_f64(&r); + out->lambda_after = r_f64(&r); + if ((st = r_end(&r)) != RX_DUAL_OK) return st; + return rx_dual_check_outcome(out); +} + +/* ---------------------------------------------------------------- digests */ +static void domain_digest(const char *domain, const uint8_t *enc, size_t len, RxDualDigest *out) +{ + sha256_ctx ctx; + uint8_t zero = 0; + sha256_init(&ctx); + sha256_update(&ctx, (const uint8_t *)domain, strlen(domain)); + sha256_update(&ctx, &zero, 1); + sha256_update(&ctx, enc, len); + sha256_final(&ctx, out->b); +} +#define DIGEST_FN(fname, type, encfn, domain) \ + RxDualStatus fname(const type *x, RxDualDigest *out) \ + { \ + uint8_t buf[RX_DUAL_ENCODED_MAX]; \ + size_t len = 0; \ + RxDualStatus st; \ + if (!out) return RX_DUAL_ERR_NULL; \ + if ((st = encfn(x, buf, sizeof buf, &len)) != RX_DUAL_OK) return st; \ + domain_digest(domain, buf, len, out); \ + return RX_DUAL_OK; \ + } +DIGEST_FN(rx_dual_digest_resource, RxDualResource, rx_dual_encode_resource, RX_DUAL_DOMAIN_RESOURCE) +DIGEST_FN(rx_dual_digest_constraint, RxDualConstraintState, rx_dual_encode_constraint, RX_DUAL_DOMAIN_CONSTRAINT) +DIGEST_FN(rx_dual_digest_controller, RxDualController, rx_dual_encode_controller, RX_DUAL_DOMAIN_CONTROLLER) +DIGEST_FN(rx_dual_digest_price_vector, RxDualPriceVector, rx_dual_encode_price_vector, RX_DUAL_DOMAIN_PRICE_VECTOR) +DIGEST_FN(rx_dual_digest_site, RxDualSite, rx_dual_encode_site, RX_DUAL_DOMAIN_SITE) +DIGEST_FN(rx_dual_digest_recommendation, RxDualRecommendation, rx_dual_encode_recommendation, RX_DUAL_DOMAIN_RECOMMENDATION) +DIGEST_FN(rx_dual_digest_outcome, RxDualOutcome, rx_dual_encode_outcome, RX_DUAL_DOMAIN_OUTCOME) + +/* ----------------------------------------------------------- constructors */ +RxDualStatus rx_dual_price_vector_build(const RxDualConstraintState *const *states, uint32_t n, + const RxDualDigest *context, RxDualPriceVector *out) +{ + RxDualStatus st; + if (!states || !context || !out) return RX_DUAL_ERR_NULL; + if (n == 0 || n > RX_DUAL_MAX_RESOURCES) return RX_DUAL_ERR_RANGE; + if (rx_dual_digest_is_zero(context)) return RX_DUAL_ERR_DIGEST; + memset(out, 0, sizeof *out); + for (uint32_t i = 0; i < n; i++) { + if (!states[i]) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_constraint(states[i])) != RX_DUAL_OK) return st; + if (i > 0 && states[i]->resource_id <= states[i - 1]->resource_id) return RX_DUAL_ERR_RESOURCE; + if (states[i]->generation != states[0]->generation) return RX_DUAL_ERR_GENERATION; + out->resource_id[i] = states[i]->resource_id; + if ((st = rx_dual_digest_constraint(states[i], &out->state[i])) != RX_DUAL_OK) return st; + } + out->n = n; + out->generation = states[0]->generation; + out->context = *context; + return rx_dual_check_price_vector(out); +} + +RxDualStatus rx_dual_consequence_set(RxDualConsequence *c, uint32_t resource_id, RxDualUnit unit, + double predicted, double predicted_sd, + int has_measured, double measured) +{ + if (!c) return RX_DUAL_ERR_NULL; + memset(c, 0, sizeof *c); + c->resource_id = resource_id; + c->unit = unit; + c->predicted = predicted; + c->predicted_sd = predicted_sd; + c->has_measured = has_measured ? 1u : 0u; + if (c->has_measured) { + c->measured = measured; + c->error = (fin(predicted_sd) && predicted_sd > 0.0) ? (measured - predicted) / predicted_sd : 0.0; + } + return check_consequence(c); +} diff --git a/src/dual/rx_dual.h b/src/dual/rx_dual.h new file mode 100644 index 000000000..b1f4c1360 --- /dev/null +++ b/src/dual/rx_dual.h @@ -0,0 +1,304 @@ +/* DUAL: constraint pricing for soft resource budgets (ARCH-0031 / ADR 0031). + * + * DUAL estimates a nonnegative price (a dual variable) for each DECLARED soft + * resource budget, from calibrated ESTIMATION records (ARCH-0020), bound to a + * World generation and an evidence root. Prices order alternatives that have + * already passed every hard gate and already survived Pareto filtering. They + * never decide validity, eligibility, promotion or authority. + * + * price != truth scarcity != correctness + * price != permission cheap != valid + * + * This header is the DUAL-0 record contract (ADR 0031 section 4). It is a + * standalone module: no file under src/runtime/ includes it, it is not part + * of `all` or `test`, and its objects pass an `nm -u` refusal check against + * every authority, promotion, World, capability and process symbol + * (mk/dual.mk, `dual-purity`). Bounded: no allocation, no globals, no I/O, + * deterministic. Every input is const, every output a new record. Refusals + * are never silently repaired (fail closed). + * + * Classes (section 3). INVARIANT is unconstructible here: a constraint of that + * class has no lambda field to fill and rx_dual_check_constraint refuses it. + * CAPACITY carries a diagnostic lambda only and is never relaxed by DUAL. + * SOFT is priceable. An undeclared class is refused, never defaulted. + * + * Records are digested as SHA-256(domain || 0x00 || canonical encoding) with + * domains "omega.dual..v1" and fixed little-endian encodings (doubles + * as IEEE-754 binary64 bits, -0.0 canonicalized to +0.0, NaN/Inf refused + * before encoding). Each record kind has its own kind byte and digest domain; + * a decoder refuses a kind byte, version or length that does not match the + * target type. No wall-clock value appears in any identity: `generation` is + * the World generation of the bound estimate and `tick` is the controller's + * logical update index. + * + * Naming: the house prefix is RxDual* / rx_dual_*. "Shadow" is not used (omega + * already has a Shadow structure in rx_graph.c). No physics-themed names. */ +#ifndef OMEGA_RX_DUAL_H +#define OMEGA_RX_DUAL_H + +#include +#include + +#define RX_DUAL_DIGEST_SIZE 32u +#define RX_DUAL_FORMAT_VERSION 1u +#define RX_DUAL_MAX_RESOURCES 32u +#define RX_DUAL_MAX_CANDIDATES 64u +#define RX_DUAL_SITE_NAME_SIZE 32u + +#define RX_DUAL_DOMAIN_RESOURCE "omega.dual.resource.v1" +#define RX_DUAL_DOMAIN_CONSTRAINT "omega.dual.constraint.v1" +#define RX_DUAL_DOMAIN_CONTROLLER "omega.dual.controller.v1" +#define RX_DUAL_DOMAIN_PRICE_VECTOR "omega.dual.pricevec.v1" +#define RX_DUAL_DOMAIN_RECOMMENDATION "omega.dual.recommendation.v1" +#define RX_DUAL_DOMAIN_OUTCOME "omega.dual.outcome.v1" +#define RX_DUAL_DOMAIN_SITE "omega.dual.site.v1" + +typedef struct { uint8_t b[RX_DUAL_DIGEST_SIZE]; } RxDualDigest; /* all-zero = absent */ + +typedef enum { + RX_DUAL_KIND_RESOURCE = 1, + RX_DUAL_KIND_CONSTRAINT = 2, + RX_DUAL_KIND_CONTROLLER = 3, + RX_DUAL_KIND_PRICE_VECTOR = 4, + RX_DUAL_KIND_RECOMMENDATION = 5, + RX_DUAL_KIND_OUTCOME = 6, + RX_DUAL_KIND_SITE = 7 +} RxDualKind; + +/* Unit registry (ADR 0031 section 4.1). Two values are comparable only if + * their units are identical. Conversion is explicit (rx_dual_unit_from_est in + * rx_dual_bind.c) and recorded; an implicit conversion is a refusal. + * RX_DUAL_UNIT_NONE is refused everywhere. */ +typedef enum { + RX_DUAL_UNIT_NONE = 0, + RX_DUAL_UNIT_PS = 1, /* picoseconds */ + RX_DUAL_UNIT_PJ = 2, /* picojoules */ + RX_DUAL_UNIT_BYTES = 3, + RX_DUAL_UNIT_BYTES_PER_S = 4, + RX_DUAL_UNIT_KV_BLOCKS = 5, + RX_DUAL_UNIT_PPM_OCCUPANCY = 6, + RX_DUAL_UNIT_NS_VERIFY = 7, + RX_DUAL_UNIT_NS_SYNTH = 8, + RX_DUAL_UNIT_NS = 9, /* = EST_UNIT_NANOSECOND */ + RX_DUAL_UNIT_WATT = 10, /* = EST_UNIT_WATT */ + RX_DUAL_UNIT_WATT_PER_S = 11, + RX_DUAL_UNIT_MILLI_CELSIUS = 12, + RX_DUAL_UNIT_MILLI_CELSIUS_PER_S = 13, + RX_DUAL_UNIT_DIMENSIONLESS = 14, + RX_DUAL_UNIT_LOG2_PS = 15, + RX_DUAL_UNIT_MAX_ = 16 +} RxDualUnit; + +/* Constraint class, declared by the owning contract, never by DUAL. */ +typedef enum { + RX_DUAL_CLASS_UNDECLARED = 0, /* refused: never defaulted to SOFT */ + RX_DUAL_CLASS_INVARIANT = 1, /* refused at construction: unpriceable */ + RX_DUAL_CLASS_CAPACITY = 2, /* diagnostic lambda only; never relaxed */ + RX_DUAL_CLASS_SOFT = 3, /* priceable */ + RX_DUAL_CLASS_MAX_ = 4 +} RxDualClass; + +typedef enum { + RX_DUAL_EST_MEASURED = 1, /* estimate_ref is an ARCH-0020 observation */ + RX_DUAL_EST_ESTIMATED = 2, /* estimate_ref is an ARCH-0020 belief */ + RX_DUAL_EST_PREDICTED = 3, /* estimate_ref is an ARCH-0020 prediction */ + RX_DUAL_EST_MAX_ = 4 +} RxDualEstimateKind; + +/* Consumers treat everything but FRESH as absent (ADR 0031 section 5.2, 10). */ +typedef enum { + RX_DUAL_LAMBDA_FRESH = 1, + RX_DUAL_LAMBDA_STALE = 2, /* generation too old or evidence root failed; lambda held */ + RX_DUAL_LAMBDA_FROZEN = 3, /* regime change signalled; lambda held until requalified */ + RX_DUAL_LAMBDA_UNCALIBRATED = 4, /* no EST-3 calibration receipt; recorded, never production */ + RX_DUAL_LAMBDA_REFUSED = 5, /* malformed input values; lambda held */ + RX_DUAL_LAMBDA_MAX_ = 6 +} RxDualLambdaState; + +#define RX_DUAL_AUTHORITY_NONE 0u /* the only legal RxDualRecommendation.authority */ + +typedef enum { + RX_DUAL_OK = 0, + RX_DUAL_ERR_NULL = -1, + RX_DUAL_ERR_NONFINITE = -2, /* NaN or Inf anywhere */ + RX_DUAL_ERR_UNIT = -3, /* missing, unknown or mismatched unit */ + RX_DUAL_ERR_CLASS = -4, /* undeclared, INVARIANT or unknown class */ + RX_DUAL_ERR_SCALE = -5, /* scale not strictly positive */ + RX_DUAL_ERR_RANGE = -6, /* negative uncertainty/lambda, lambda above max, bad enum, bad index */ + RX_DUAL_ERR_KIND = -7, /* wrong record kind */ + RX_DUAL_ERR_ENCODING = -8, /* truncated, trailing bytes, bad version */ + RX_DUAL_ERR_RESOURCE = -9, /* unknown, duplicate or unordered resource id */ + RX_DUAL_ERR_DIGEST = -10, /* required digest absent, or parent/contract mismatch */ + RX_DUAL_ERR_GENERATION = -11, /* generation inconsistent across a record or vector */ + RX_DUAL_ERR_CONTROLLER = -12, /* controller malformed or does not match controller_id */ + RX_DUAL_ERR_AUTHORITY = -13, /* recommendation claims authority */ + RX_DUAL_ERR_SITE = -14, /* decision site malformed or does not match */ + RX_DUAL_ERR_FULL = -15, /* registry or vector capacity */ + RX_DUAL_ERR_EVIDENCE = -16, /* evidence root does not verify */ + RX_DUAL_ERR_CALIBRATION = -17 /* FRESH claimed without a calibration receipt */ +} RxDualStatus; + +/* ---- 4.1 resource registry entry ---- */ +typedef struct { + uint32_t resource_id; + RxDualUnit unit; + double scale; /* positive normalizer in `unit`; makes pressure dimensionless */ + RxDualDigest contract; /* non-zero: the contract that declared this resource */ +} RxDualResource; + +/* Registry: bounded, kept in strictly ascending resource_id order. */ +typedef struct { + uint32_t n; + RxDualResource r[RX_DUAL_MAX_RESOURCES]; +} RxDualRegistry; + +/* ---- 4.2 constraint state ---- */ +typedef struct { + uint32_t resource_id; + RxDualUnit unit; + RxDualClass cls; /* CAPACITY or SOFT only */ + double budget; /* in `unit` */ + RxDualDigest budget_contract; /* non-zero: digest of the contract that declared budget and class */ + RxDualDigest observation_ref; /* ARCH-0020 observation digest; non-zero when estimate_kind == MEASURED */ + RxDualDigest estimate_ref; /* non-zero: ARCH-0020 observation/belief/prediction digest */ + RxDualEstimateKind estimate_kind; + double estimate; /* copied from the referenced record, never computed by DUAL */ + double uncertainty; /* standard deviation in `unit`, >= 0, copied likewise */ + RxDualDigest calibration_ref; /* EST-3 receipt digest; zero means UNCALIBRATED */ + double lambda; /* finite, >= 0, <= controller lambda_max */ + RxDualLambdaState lambda_state; + RxDualDigest controller_id; /* non-zero: rx_dual_digest_controller of the producing controller */ + uint64_t generation; /* World generation of the bound estimate */ + uint64_t tick; /* controller logical update index; 0 for the initial state */ + RxDualDigest evidence_root; /* non-zero: chain over every estimate record consumed */ + RxDualDigest parent; /* previous state digest; zero only when tick == 0 */ +} RxDualConstraintState; + +/* ---- controller parameters (section 5.1); their digest is controller_id ---- */ +typedef struct { + double eta; /* step, >= 0 finite (0 = no gradient movement) */ + double rho; /* leak toward zero, in [0, 1] */ + double k_sigma; /* deadband width in standard deviations, >= 0 finite */ + uint64_t max_age; /* maximum (now - estimate generation) accepted, >= 1 */ + uint64_t cadence; /* update cadence in ticks, >= 1 */ + uint32_t n; /* resources this controller prices, 1..RX_DUAL_MAX_RESOURCES */ + uint32_t resource_id[RX_DUAL_MAX_RESOURCES]; /* strictly ascending */ + double lambda_max[RX_DUAL_MAX_RESOURCES]; /* > 0 finite, per resource */ +} RxDualController; + +/* ---- 4.3 price vector: one decision context, one generation ---- */ +typedef struct { + uint64_t generation; + RxDualDigest context; /* non-zero: the decision context (site digest or caller record) */ + uint32_t n; /* 1..RX_DUAL_MAX_RESOURCES */ + uint32_t resource_id[RX_DUAL_MAX_RESOURCES]; /* strictly ascending */ + RxDualDigest state[RX_DUAL_MAX_RESOURCES]; /* RxDualConstraintState digests, non-zero */ +} RxDualPriceVector; + +/* ---- registered decision site (section 7.3) ---- */ +typedef struct { + uint32_t site_id; + uint8_t name[RX_DUAL_SITE_NAME_SIZE]; /* printable ASCII, NUL padded, e.g. "jspace.residency" */ + RxDualDigest owner; /* non-zero: digest naming the production owner */ + uint32_t max_alternatives; /* 1..RX_DUAL_MAX_CANDIDATES */ +} RxDualSite; + +/* ---- 4.4 recommendation (advisory; authority is always NONE) ---- */ +typedef struct { + uint32_t resource_id; + RxDualUnit unit; + double predicted; /* predicted consequence of `recommended`, in `unit` */ + double predicted_sd; /* > 0 when has_measured, else >= 0 */ + uint32_t has_measured; /* 0 or 1 */ + double measured; /* 0 when has_measured == 0 */ + double error; /* (measured - predicted) / predicted_sd when has_measured, else 0 */ +} RxDualConsequence; + +typedef struct { + RxDualDigest decision_site; /* non-zero: RxDualSite digest */ + RxDualDigest price_vector; /* non-zero: RxDualPriceVector digest */ + uint64_t generation; + uint32_t n_candidates; /* 1..RX_DUAL_MAX_CANDIDATES */ + RxDualDigest candidates[RX_DUAL_MAX_CANDIDATES]; /* non-zero, nondominated alternatives offered */ + uint32_t actual; /* index of the production choice */ + uint32_t recommended; /* index DUAL would have chosen */ + uint32_t n_consequences; /* 0..RX_DUAL_MAX_RESOURCES */ + RxDualConsequence c[RX_DUAL_MAX_RESOURCES]; /* strictly ascending resource_id */ + uint32_t authority; /* RX_DUAL_AUTHORITY_NONE; anything else is malformed */ +} RxDualRecommendation; + +/* ---- 4.5 outcome ---- */ +typedef struct { + RxDualDigest recommendation; + RxDualDigest before_vector; + RxDualDigest after_vector; + uint32_t target_resource_id; + uint64_t generation_before; + uint64_t generation_after; /* >= generation_before */ + double lambda_before; + double lambda_after; /* both finite, >= 0 */ +} RxDualOutcome; + +/* ---- helpers ---- */ +int rx_dual_digest_is_zero(const RxDualDigest *d); +int rx_dual_digest_eq(const RxDualDigest *a, const RxDualDigest *b); +int rx_dual_unit_valid(RxDualUnit u); /* 1 if known and not NONE */ + +/* ---- registry ---- */ +void rx_dual_registry_init(RxDualRegistry *reg); +RxDualStatus rx_dual_registry_add(RxDualRegistry *reg, const RxDualResource *r); /* refuses duplicate id */ +const RxDualResource *rx_dual_registry_find(const RxDualRegistry *reg, uint32_t resource_id); + +/* ---- validation (every constructor, digest and encoder calls these) ---- */ +RxDualStatus rx_dual_check_resource(const RxDualResource *r); +RxDualStatus rx_dual_check_constraint(const RxDualConstraintState *s); +RxDualStatus rx_dual_check_controller(const RxDualController *c); +RxDualStatus rx_dual_check_price_vector(const RxDualPriceVector *v); +RxDualStatus rx_dual_check_site(const RxDualSite *s); +RxDualStatus rx_dual_check_recommendation(const RxDualRecommendation *r); +RxDualStatus rx_dual_check_outcome(const RxDualOutcome *o); + +/* Constraint against its registry entry: id, unit and class rules. */ +RxDualStatus rx_dual_check_constraint_against(const RxDualConstraintState *s, const RxDualResource *r); +/* lambda_max for a resource under a controller; RX_DUAL_ERR_RESOURCE if not priced by it. */ +RxDualStatus rx_dual_controller_lambda_max(const RxDualController *c, uint32_t resource_id, double *out); + +/* ---- identity ---- */ +RxDualStatus rx_dual_digest_resource(const RxDualResource *r, RxDualDigest *out); +RxDualStatus rx_dual_digest_constraint(const RxDualConstraintState *s, RxDualDigest *out); +RxDualStatus rx_dual_digest_controller(const RxDualController *c, RxDualDigest *out); +RxDualStatus rx_dual_digest_price_vector(const RxDualPriceVector *v, RxDualDigest *out); +RxDualStatus rx_dual_digest_site(const RxDualSite *s, RxDualDigest *out); +RxDualStatus rx_dual_digest_recommendation(const RxDualRecommendation *r, RxDualDigest *out); +RxDualStatus rx_dual_digest_outcome(const RxDualOutcome *o, RxDualDigest *out); + +/* Price vector builder: every state must validate, share `generation`, and be + * supplied in strictly ascending resource_id order (canonical; unordered or + * duplicate input is refused, not sorted). */ +RxDualStatus rx_dual_price_vector_build(const RxDualConstraintState *const *states, uint32_t n, + const RxDualDigest *context, RxDualPriceVector *out); + +/* Fill one consequence row; computes `error` exactly as the checker recomputes it. */ +RxDualStatus rx_dual_consequence_set(RxDualConsequence *c, uint32_t resource_id, RxDualUnit unit, + double predicted, double predicted_sd, + int has_measured, double measured); + +/* ---- serialization: exact round trip; decode validates and refuses a kind + * byte, version, truncation or trailing bytes ---- */ +#define RX_DUAL_ENCODED_MAX 4096u +RxDualStatus rx_dual_encode_resource(const RxDualResource *r, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_resource(const uint8_t *buf, size_t len, RxDualResource *out); +RxDualStatus rx_dual_encode_constraint(const RxDualConstraintState *s, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_constraint(const uint8_t *buf, size_t len, RxDualConstraintState *out); +RxDualStatus rx_dual_encode_controller(const RxDualController *c, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_controller(const uint8_t *buf, size_t len, RxDualController *out); +RxDualStatus rx_dual_encode_price_vector(const RxDualPriceVector *v, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_price_vector(const uint8_t *buf, size_t len, RxDualPriceVector *out); +RxDualStatus rx_dual_encode_site(const RxDualSite *s, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_site(const uint8_t *buf, size_t len, RxDualSite *out); +RxDualStatus rx_dual_encode_recommendation(const RxDualRecommendation *r, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_recommendation(const uint8_t *buf, size_t len, RxDualRecommendation *out); +RxDualStatus rx_dual_encode_outcome(const RxDualOutcome *o, uint8_t *buf, size_t cap, size_t *len); +RxDualStatus rx_dual_decode_outcome(const uint8_t *buf, size_t len, RxDualOutcome *out); + +#endif /* OMEGA_RX_DUAL_H */ diff --git a/src/dual/rx_dual_bind.c b/src/dual/rx_dual_bind.c new file mode 100644 index 000000000..b3a5fd810 --- /dev/null +++ b/src/dual/rx_dual_bind.c @@ -0,0 +1,168 @@ +/* DUAL-0b: binding to ESTIMATION records and freshness classification. */ +#include "rx_dual_bind.h" + +#include +#include + +static void cp(RxDualDigest *d, const est_digest *e) { memcpy(d->b, e->b, RX_DUAL_DIGEST_SIZE); } + +RxDualStatus rx_dual_unit_from_est(est_unit u, RxDualUnit *out) +{ + if (!out) return RX_DUAL_ERR_NULL; + switch (u) { + case EST_UNIT_MILLI_CELSIUS: *out = RX_DUAL_UNIT_MILLI_CELSIUS; return RX_DUAL_OK; + case EST_UNIT_MILLI_CELSIUS_PER_S: *out = RX_DUAL_UNIT_MILLI_CELSIUS_PER_S; return RX_DUAL_OK; + case EST_UNIT_WATT: *out = RX_DUAL_UNIT_WATT; return RX_DUAL_OK; + case EST_UNIT_WATT_PER_S: *out = RX_DUAL_UNIT_WATT_PER_S; return RX_DUAL_OK; + case EST_UNIT_NANOSECOND: *out = RX_DUAL_UNIT_NS; return RX_DUAL_OK; + case EST_UNIT_BYTE: *out = RX_DUAL_UNIT_BYTES; return RX_DUAL_OK; + case EST_UNIT_DIMENSIONLESS: *out = RX_DUAL_UNIT_DIMENSIONLESS; return RX_DUAL_OK; + case EST_UNIT_LOG2_PICOSECOND: *out = RX_DUAL_UNIT_LOG2_PS; return RX_DUAL_OK; + case EST_UNIT_NONE: + case EST_UNIT_MAX_: + default: + *out = RX_DUAL_UNIT_NONE; + return RX_DUAL_ERR_UNIT; + } +} + +static RxDualStatus sd_from_var(double var, double *sd) +{ + if (!isfinite(var)) return RX_DUAL_ERR_NONFINITE; + if (var < 0.0) return RX_DUAL_ERR_RANGE; + *sd = sqrt(var); + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_bind_belief(const est_belief *b, uint32_t k, const RxDualDigest *calibration_ref, + RxDualInput *out) +{ + est_digest d; + RxDualStatus st; + if (!b || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + if (est_check_belief(b) != EST_OK) return RX_DUAL_ERR_KIND; + if (k >= b->n) return RX_DUAL_ERR_RANGE; + if (est_digest_is_zero(&b->evidence_root)) return RX_DUAL_ERR_EVIDENCE; /* a prior is not evidence */ + if ((st = rx_dual_unit_from_est(b->unit[k], &out->unit)) != RX_DUAL_OK) return st; + if (est_digest_belief(b, &d) != EST_OK) return RX_DUAL_ERR_KIND; + cp(&out->estimate_ref, &d); + out->estimate_kind = RX_DUAL_EST_ESTIMATED; + out->estimate = b->x[k]; + if ((st = sd_from_var(b->P[k * b->n + k], &out->uncertainty)) != RX_DUAL_OK) return st; + out->generation = b->generation; + cp(&out->evidence_root, &b->evidence_root); + if (calibration_ref) out->calibration_ref = *calibration_ref; + return rx_dual_check_input(out); +} + +RxDualStatus rx_dual_bind_prediction(const est_prediction *p, const est_model *model, const est_belief *prior, + uint32_t k, const RxDualDigest *calibration_ref, RxDualInput *out) +{ + est_digest d; + RxDualStatus st; + if (!p || !model || !prior || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + if (est_check_prediction(p) != EST_OK || est_check_model(model) != EST_OK || est_check_belief(prior) != EST_OK) + return RX_DUAL_ERR_KIND; + if (k >= p->n || k >= model->n) return RX_DUAL_ERR_RANGE; + if (est_digest_model(model, &d) != EST_OK || memcmp(d.b, p->model.b, EST_DIGEST_SIZE) != 0) return RX_DUAL_ERR_DIGEST; + if (est_digest_belief(prior, &d) != EST_OK || memcmp(d.b, p->prior.b, EST_DIGEST_SIZE) != 0) return RX_DUAL_ERR_DIGEST; + if (est_digest_is_zero(&prior->evidence_root)) return RX_DUAL_ERR_EVIDENCE; + if ((st = rx_dual_unit_from_est(model->state_unit[k], &out->unit)) != RX_DUAL_OK) return st; + if (est_digest_prediction(p, &d) != EST_OK) return RX_DUAL_ERR_KIND; + cp(&out->estimate_ref, &d); + out->estimate_kind = RX_DUAL_EST_PREDICTED; + out->estimate = p->x[k]; + if ((st = sd_from_var(p->P[k * p->n + k], &out->uncertainty)) != RX_DUAL_OK) return st; + out->generation = p->generation; + cp(&out->evidence_root, &prior->evidence_root); + if (calibration_ref) out->calibration_ref = *calibration_ref; + return rx_dual_check_input(out); +} + +RxDualStatus rx_dual_bind_observation(const est_observation *o, uint32_t k, uint64_t generation, + const RxDualDigest *calibration_ref, RxDualInput *out) +{ + est_digest d; + RxDualStatus st; + if (!o || !out) return RX_DUAL_ERR_NULL; + memset(out, 0, sizeof *out); + if (est_check_observation(o) != EST_OK) return RX_DUAL_ERR_KIND; + if (k >= o->m) return RX_DUAL_ERR_RANGE; + if ((st = rx_dual_unit_from_est(o->unit[k], &out->unit)) != RX_DUAL_OK) return st; + if (est_digest_observation(o, &d) != EST_OK) return RX_DUAL_ERR_KIND; + cp(&out->estimate_ref, &d); + cp(&out->observation_ref, &d); + out->estimate_kind = RX_DUAL_EST_MEASURED; + out->estimate = o->z[k]; + if ((st = sd_from_var(o->R[k * o->m + k], &out->uncertainty)) != RX_DUAL_OK) return st; + out->generation = generation; + cp(&out->evidence_root, &o->evidence); /* the raw-bytes digest the sensor path declared */ + out->evidence_verified = 1; /* an observation is its own evidence (ARCH-0020 caller rule) */ + if (calibration_ref) out->calibration_ref = *calibration_ref; + return rx_dual_check_input(out); +} + +RxDualStatus rx_dual_verify_belief_evidence(const est_belief *b, const est_digest *parent_root, + const est_observation *obs, RxDualInput *in) +{ + est_digest obs_d, want, have; + if (!b || !parent_root || !obs || !in) return RX_DUAL_ERR_NULL; + if (est_check_belief(b) != EST_OK || est_check_observation(obs) != EST_OK) return RX_DUAL_ERR_KIND; + if (est_digest_belief(b, &have) != EST_OK) return RX_DUAL_ERR_KIND; + if (memcmp(have.b, in->estimate_ref.b, EST_DIGEST_SIZE) != 0) return RX_DUAL_ERR_DIGEST; /* input not bound from b */ + if (est_digest_observation(obs, &obs_d) != EST_OK) return RX_DUAL_ERR_KIND; + if (est_evidence_root_extend(parent_root, &obs_d, &want) != EST_OK) return RX_DUAL_ERR_EVIDENCE; + if (memcmp(want.b, b->evidence_root.b, EST_DIGEST_SIZE) != 0) { in->evidence_verified = 0; return RX_DUAL_ERR_EVIDENCE; } + in->evidence_verified = 1; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_check_input(const RxDualInput *in) +{ + if (!in) return RX_DUAL_ERR_NULL; + if (!rx_dual_unit_valid(in->unit)) return RX_DUAL_ERR_UNIT; + if ((uint32_t)in->estimate_kind < 1u || (uint32_t)in->estimate_kind >= (uint32_t)RX_DUAL_EST_MAX_) return RX_DUAL_ERR_KIND; + if (!isfinite(in->estimate) || !isfinite(in->uncertainty)) return RX_DUAL_ERR_NONFINITE; + if (in->uncertainty < 0.0) return RX_DUAL_ERR_RANGE; + if (rx_dual_digest_is_zero(&in->estimate_ref) || rx_dual_digest_is_zero(&in->evidence_root)) return RX_DUAL_ERR_DIGEST; + if (in->estimate_kind == RX_DUAL_EST_MEASURED && rx_dual_digest_is_zero(&in->observation_ref)) return RX_DUAL_ERR_DIGEST; + if (in->evidence_verified > 1u || in->regime_change > 1u) return RX_DUAL_ERR_RANGE; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_classify_input(const RxDualInput *in, const RxDualConstraintState *prev, + const RxDualController *ctl, uint64_t now_generation, + RxDualLambdaState *out) +{ + RxDualStatus st; + if (!in || !ctl || !out) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_controller(ctl)) != RX_DUAL_OK) return st; + if (prev) { + if ((st = rx_dual_check_constraint(prev)) != RX_DUAL_OK) return st; + if (in->unit != prev->unit) return RX_DUAL_ERR_UNIT; /* structural: never converted */ + } + /* value problems: the input is refused for this tick */ + if (rx_dual_check_input(in) != RX_DUAL_OK) { *out = RX_DUAL_LAMBDA_REFUSED; return RX_DUAL_OK; } + if (in->generation > now_generation) { *out = RX_DUAL_LAMBDA_REFUSED; return RX_DUAL_OK; } /* future generation */ + /* staleness */ + if (now_generation - in->generation > ctl->max_age) { *out = RX_DUAL_LAMBDA_STALE; return RX_DUAL_OK; } + if (prev && in->generation < prev->generation) { *out = RX_DUAL_LAMBDA_STALE; return RX_DUAL_OK; } + if (!in->evidence_verified) { *out = RX_DUAL_LAMBDA_STALE; return RX_DUAL_OK; } + if (in->regime_change) { *out = RX_DUAL_LAMBDA_FROZEN; return RX_DUAL_OK; } + if (rx_dual_digest_is_zero(&in->calibration_ref)) { *out = RX_DUAL_LAMBDA_UNCALIBRATED; return RX_DUAL_OK; } + *out = RX_DUAL_LAMBDA_FRESH; + return RX_DUAL_OK; +} + +RxDualStatus rx_dual_evidence_extend(const RxDualDigest *root, const RxDualDigest *estimate_ref, RxDualDigest *out) +{ + est_digest r, e, o; + if (!root || !estimate_ref || !out) return RX_DUAL_ERR_NULL; + if (rx_dual_digest_is_zero(estimate_ref)) return RX_DUAL_ERR_DIGEST; + memcpy(r.b, root->b, 32); memcpy(e.b, estimate_ref->b, 32); + if (est_evidence_root_extend(&r, &e, &o) != EST_OK) return RX_DUAL_ERR_EVIDENCE; + memcpy(out->b, o.b, 32); + return RX_DUAL_OK; +} diff --git a/src/dual/rx_dual_bind.h b/src/dual/rx_dual_bind.h new file mode 100644 index 000000000..4cf19df31 --- /dev/null +++ b/src/dual/rx_dual_bind.h @@ -0,0 +1,81 @@ +/* DUAL-0b: binding DUAL inputs to ESTIMATION records (ARCH-0020) and + * classifying their freshness (ADR 0031 sections 4.2, 5.2, 8.1). + * + * DUAL never reads a raw counter and never computes an estimate. Every + * estimate and uncertainty in a DUAL record is COPIED from an est_* record + * whose digest is cited (estimate_ref), together with that record's World + * generation and evidence root. The dependency direction is fixed: + * + * exact counters -> est_observation -> ESTIMATION -> est_belief / est_prediction + * -> RxDualInput (this file) -> controller (rx_dual_update.h) + * + * Units are converted from est_unit to RxDualUnit by one explicit table + * (rx_dual_unit_from_est); an unknown or NONE unit is refused. + * + * Evidence verification reuses est_evidence_root_extend: a belief's root must + * equal extend(parent_root, digest(observation)); only then is the input + * marked evidence_verified. An unverified input can only yield STALE. */ +#ifndef OMEGA_RX_DUAL_BIND_H +#define OMEGA_RX_DUAL_BIND_H + +#include "rx_dual.h" +#include "est_types.h" + +/* What the controller may read from ESTIMATION for one resource at one tick. */ +typedef struct { + RxDualDigest estimate_ref; /* digest of the est record the values come from */ + RxDualDigest observation_ref; /* digest of the observation (MEASURED), else zero */ + RxDualEstimateKind estimate_kind; + RxDualUnit unit; /* converted from the record's est_unit */ + double estimate; /* copied component value */ + double uncertainty; /* sqrt of the component variance, copied */ + uint64_t generation; /* World generation of the record */ + RxDualDigest evidence_root; /* the record's evidence root (non-zero) */ + uint32_t evidence_verified; /* 1 only after rx_dual_verify_belief_evidence passed */ + RxDualDigest calibration_ref; /* EST-3 receipt digest for this signal; zero = UNCALIBRATED */ + uint32_t regime_change; /* 1 = out-of-calibration (EST-9 style) signal: freeze */ +} RxDualInput; + +RxDualStatus rx_dual_unit_from_est(est_unit u, RxDualUnit *out); + +/* Bind component `k` of a belief. calibration_ref may be NULL (UNCALIBRATED). + * Refuses an invalid belief, k >= n, a zero evidence root (a declared prior + * is not evidence), or a negative variance. evidence_verified starts at 0. */ +RxDualStatus rx_dual_bind_belief(const est_belief *b, uint32_t k, const RxDualDigest *calibration_ref, + RxDualInput *out); +/* Bind component `k` of a prediction. The model (for the unit) and the prior + * belief (for the evidence root) must be the records the prediction cites: + * their digests must equal p->model and p->prior, else RX_DUAL_ERR_DIGEST. */ +RxDualStatus rx_dual_bind_prediction(const est_prediction *p, const est_model *model, const est_belief *prior, + uint32_t k, const RxDualDigest *calibration_ref, RxDualInput *out); +/* Bind component `k` of an observation as a MEASURED input. An observation + * carries no World generation, so the caller states it. */ +RxDualStatus rx_dual_bind_observation(const est_observation *o, uint32_t k, uint64_t generation, + const RxDualDigest *calibration_ref, RxDualInput *out); + +/* Verify a belief's evidence root against the parent root and the observation + * that produced it (root' = extend(parent_root, digest(obs))). On success sets + * in->evidence_verified = 1; on mismatch returns RX_DUAL_ERR_EVIDENCE and + * leaves it 0. `in` must have been bound from `b` (estimate_ref must match). */ +RxDualStatus rx_dual_verify_belief_evidence(const est_belief *b, const est_digest *parent_root, + const est_observation *obs, RxDualInput *in); + +/* Structural validity of an input (finite, unit known, kind known, digests present). */ +RxDualStatus rx_dual_check_input(const RxDualInput *in); + +/* Classify an input for the next tick (ADR 0031 section 5.2): + * REFUSED nonfinite or negative values, missing digests, generation in the future + * STALE now - generation > max_age, generation older than prev, or evidence not verified + * FROZEN regime_change set + * UNCALIBRATED no calibration_ref + * FRESH otherwise + * Unit mismatch against prev is a structural refusal (RX_DUAL_ERR_UNIT), not a state. + * prev may be NULL for an initial state. */ +RxDualStatus rx_dual_classify_input(const RxDualInput *in, const RxDualConstraintState *prev, + const RxDualController *ctl, uint64_t now_generation, + RxDualLambdaState *out); + +/* DUAL state evidence chain: root' = est_evidence_root_extend(root, estimate_ref). */ +RxDualStatus rx_dual_evidence_extend(const RxDualDigest *root, const RxDualDigest *estimate_ref, RxDualDigest *out); + +#endif /* OMEGA_RX_DUAL_BIND_H */ diff --git a/src/dual/rx_dual_update.c b/src/dual/rx_dual_update.c new file mode 100644 index 000000000..5624dc67a --- /dev/null +++ b/src/dual/rx_dual_update.c @@ -0,0 +1,123 @@ +/* DUAL-1a: reference price update. */ +#include "rx_dual_update.h" + +#include +#include + +RxDualStatus rx_dual_step_lambda(double lambda, double estimate, double uncertainty, double budget, + double scale, const RxDualController *ctl, double lambda_max, double *out) +{ + double pressure, deadband, g, next; + RxDualStatus st; + if (!ctl || !out) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_controller(ctl)) != RX_DUAL_OK) return st; + if (!isfinite(lambda) || !isfinite(estimate) || !isfinite(uncertainty) || !isfinite(budget) || + !isfinite(scale) || !isfinite(lambda_max)) + return RX_DUAL_ERR_NONFINITE; + if (!(scale > 0.0)) return RX_DUAL_ERR_SCALE; + if (lambda < 0.0 || uncertainty < 0.0 || !(lambda_max > 0.0) || lambda > lambda_max) return RX_DUAL_ERR_RANGE; + pressure = (estimate - budget) / scale; + deadband = ctl->k_sigma * uncertainty / scale; + if (fabs(pressure) <= deadband) g = 0.0; + else g = pressure - (pressure > 0.0 ? deadband : -deadband); + next = (1.0 - ctl->rho) * lambda + ctl->eta * g; + if (!isfinite(next)) return RX_DUAL_ERR_NONFINITE; + if (next < 0.0) next = 0.0; + if (next > lambda_max) next = lambda_max; + *out = next; + return RX_DUAL_OK; +} + +/* Shared structural checks for init and update. */ +static RxDualStatus common(const RxDualResource *res, const RxDualInput *in, const RxDualController *ctl, + double *lambda_max, RxDualDigest *ctl_id) +{ + RxDualStatus st; + if (!res || !in || !ctl) return RX_DUAL_ERR_NULL; + if ((st = rx_dual_check_resource(res)) != RX_DUAL_OK) return st; + if ((st = rx_dual_check_controller(ctl)) != RX_DUAL_OK) return st; + if ((st = rx_dual_controller_lambda_max(ctl, res->resource_id, lambda_max)) != RX_DUAL_OK) return st; + if ((st = rx_dual_digest_controller(ctl, ctl_id)) != RX_DUAL_OK) return st; + return RX_DUAL_OK; +} + +static void take_input(RxDualConstraintState *s, const RxDualInput *in) +{ + s->observation_ref = in->observation_ref; + s->estimate_ref = in->estimate_ref; + s->estimate_kind = in->estimate_kind; + s->estimate = in->estimate; + s->uncertainty = in->uncertainty; + s->calibration_ref = in->calibration_ref; + s->generation = in->generation; +} + +RxDualStatus rx_dual_init_state(const RxDualResource *res, RxDualClass cls, double budget, + const RxDualDigest *budget_contract, const RxDualInput *in, + const RxDualController *ctl, uint64_t now_generation, + RxDualConstraintState *out) +{ + double lmax = 0.0, next = 0.0; + RxDualDigest ctl_id, zero; + RxDualLambdaState cls_state; + RxDualStatus st; + if (!budget_contract || !out) return RX_DUAL_ERR_NULL; + if ((st = common(res, in, ctl, &lmax, &ctl_id)) != RX_DUAL_OK) return st; + if (cls != RX_DUAL_CLASS_CAPACITY && cls != RX_DUAL_CLASS_SOFT) return RX_DUAL_ERR_CLASS; + if (!isfinite(budget)) return RX_DUAL_ERR_NONFINITE; + if (rx_dual_digest_is_zero(budget_contract)) return RX_DUAL_ERR_DIGEST; + /* The very first input must be structurally valid and in the resource's unit. */ + if ((st = rx_dual_check_input(in)) != RX_DUAL_OK) return st; + if (in->unit != res->unit) return RX_DUAL_ERR_UNIT; + if ((st = rx_dual_classify_input(in, NULL, ctl, now_generation, &cls_state)) != RX_DUAL_OK) return st; + memset(out, 0, sizeof *out); + out->resource_id = res->resource_id; + out->unit = res->unit; + out->cls = cls; + out->budget = budget; + out->budget_contract = *budget_contract; + take_input(out, in); + out->controller_id = ctl_id; + out->tick = 0; + memset(&zero, 0, sizeof zero); + if ((st = rx_dual_evidence_extend(&zero, &in->estimate_ref, &out->evidence_root)) != RX_DUAL_OK) return st; + out->lambda = 0.0; + out->lambda_state = cls_state; + if (cls_state == RX_DUAL_LAMBDA_FRESH || cls_state == RX_DUAL_LAMBDA_UNCALIBRATED) { + if ((st = rx_dual_step_lambda(0.0, in->estimate, in->uncertainty, budget, res->scale, ctl, lmax, &next)) != RX_DUAL_OK) + return st; + out->lambda = next; + } + return rx_dual_check_constraint(out); +} + +RxDualStatus rx_dual_update(const RxDualConstraintState *prev, const RxDualResource *res, + const RxDualInput *in, const RxDualController *ctl, + uint64_t now_generation, RxDualConstraintState *out) +{ + double lmax = 0.0, next = 0.0; + RxDualDigest ctl_id, parent; + RxDualLambdaState state; + RxDualStatus st; + if (!prev || !out) return RX_DUAL_ERR_NULL; + if ((st = common(res, in, ctl, &lmax, &ctl_id)) != RX_DUAL_OK) return st; + if ((st = rx_dual_check_constraint_against(prev, res)) != RX_DUAL_OK) return st; /* malformed parent, id, unit */ + if (!rx_dual_digest_eq(&prev->controller_id, &ctl_id)) return RX_DUAL_ERR_CONTROLLER; /* parameter mutation */ + if (prev->lambda > lmax) return RX_DUAL_ERR_RANGE; + if ((st = rx_dual_digest_constraint(prev, &parent)) != RX_DUAL_OK) return st; + if ((st = rx_dual_classify_input(in, prev, ctl, now_generation, &state)) != RX_DUAL_OK) return st; + *out = *prev; + out->parent = parent; + out->tick = prev->tick + 1; + out->lambda_state = state; + if (state == RX_DUAL_LAMBDA_FRESH || state == RX_DUAL_LAMBDA_UNCALIBRATED) { + if (in->unit != res->unit) return RX_DUAL_ERR_UNIT; + if ((st = rx_dual_step_lambda(prev->lambda, in->estimate, in->uncertainty, prev->budget, res->scale, ctl, lmax, &next)) != RX_DUAL_OK) + return st; + take_input(out, in); + out->lambda = next; + if ((st = rx_dual_evidence_extend(&prev->evidence_root, &in->estimate_ref, &out->evidence_root)) != RX_DUAL_OK) return st; + } + /* STALE / FROZEN / REFUSED: lambda, estimate fields, generation and evidence root are held. */ + return rx_dual_check_constraint(out); +} diff --git a/src/dual/rx_dual_update.h b/src/dual/rx_dual_update.h new file mode 100644 index 000000000..ae81d1898 --- /dev/null +++ b/src/dual/rx_dual_update.h @@ -0,0 +1,46 @@ +/* DUAL-1a: the reference price update (ADR 0031 section 5.1) as a pure, + * deterministic function of (previous state, bound input, controller). + * + * pressure = (estimate - budget) / scale + * deadband = k_sigma * uncertainty / scale + * g = 0 if |pressure| <= deadband else pressure - sign(pressure) * deadband + * lambda' = clip((1 - rho) * lambda + eta * g, 0, lambda_max) + * + * Properties (checked by tests/dual): lambda' is finite, 0 <= lambda' <= + * lambda_max; inside the deadband there is no pressure-driven movement; + * persistent positive pressure raises lambda until clipped; slack decays it + * toward zero; eta = 0 never moves on gradient; rho > 0 forgets old scarcity; + * the same inputs give byte-identical records. + * + * Refusals (negative status, no record): NULL, malformed prev/resource/ + * controller, controller digest != prev.controller_id, resource not priced by + * the controller, resource id or unit mismatch, prev.lambda above lambda_max. + * Held states (record produced, lambda unchanged): REFUSED (bad values, future + * generation), STALE (too old, going backwards, evidence not verified), + * FROZEN (regime change). UNCALIBRATED updates lambda but may never influence + * production. The cadence parameter is identity only: the caller invokes the + * update once per cadence tick. */ +#ifndef OMEGA_RX_DUAL_UPDATE_H +#define OMEGA_RX_DUAL_UPDATE_H + +#include "rx_dual_bind.h" + +/* Initial state (tick 0, parent zero) from a first input. The class and budget + * come from the owning contract (budget_contract cites it). INVARIANT and + * undeclared classes are refused here as everywhere. lambda starts at 0. */ +RxDualStatus rx_dual_init_state(const RxDualResource *res, RxDualClass cls, double budget, + const RxDualDigest *budget_contract, const RxDualInput *in, + const RxDualController *ctl, uint64_t now_generation, + RxDualConstraintState *out); + +/* One tick. out->parent = digest(prev), out->tick = prev->tick + 1. */ +RxDualStatus rx_dual_update(const RxDualConstraintState *prev, const RxDualResource *res, + const RxDualInput *in, const RxDualController *ctl, + uint64_t now_generation, RxDualConstraintState *out); + +/* The arithmetic alone, for the independent reference test. Returns the new + * lambda or refuses on nonfinite / nonpositive scale. */ +RxDualStatus rx_dual_step_lambda(double lambda, double estimate, double uncertainty, double budget, + double scale, const RxDualController *ctl, double lambda_max, double *out); + +#endif /* OMEGA_RX_DUAL_UPDATE_H */ diff --git a/tests/.crumb b/tests/.crumb index 967863929..83424cbce 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -278,14 +278,14 @@ } ], "children_root": "sha256:4401e9b1951727dd948e583dc596ca7330946f64fe8aba7466569aa7e09e8672", - "compiled_at": "2026-10-04T13:47:05Z", + "compiled_at": "2026-10-04T18:16:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:fd4612cad3b13815413dcb30e65d0b1ae796b19f0296b2942f29ef96b3ebe78f", + "digest": "sha256:3cf64120d367b0ec3b8cb61415ddc3ba7f8b42e04c79d3a0e958b7eb8eef1622", "evidence_files": 11, "evidence_root": "sha256:d5c1bceb4d57ef0eb42797c58801b5926509711614c3e38bb7105b6efa3942f2", - "files": 778, - "generated_at_commit": "834ee93e4314a42c1127a2fcda8b29cf3b511245", - "source_tree": "sha256:ff45409a0dfc5ef134291962476f9a21c80d3d4749d7eca347253def3bee54f5" + "files": 784, + "generated_at_commit": "41dcb768a955c1027d60d8b86d4ff6629118b9e6", + "source_tree": "sha256:4fd150be03a6ea339696b23754f5048eec519a311613508eeca32069d87453c6" }, "owner_lane": "", "provenance": { diff --git a/tests/dual/dual_fixtures.h b/tests/dual/dual_fixtures.h new file mode 100644 index 000000000..e043ae404 --- /dev/null +++ b/tests/dual/dual_fixtures.h @@ -0,0 +1,60 @@ +/* Shared fixtures for DUAL-0b / DUAL-1a tests: minimal valid ESTIMATION + * records (n = m = 1) and a controller. */ +#ifndef DUAL_FIXTURES_H +#define DUAL_FIXTURES_H +#include "rx_dual_update.h" +#include + +static inline RxDualDigest fx_dig(uint8_t v) { RxDualDigest d; memset(d.b, v, 32); return d; } + +static inline est_model fx_model(est_unit unit) +{ + est_model m; memset(&m, 0, sizeof m); + m.n = 1; m.m = 1; m.estimator = EST_ESTIMATOR_LINEAR_KALMAN; m.meaning = EST_UNCERTAINTY_GAUSSIAN_COVARIANCE; + m.state_unit[0] = unit; m.obs_unit[0] = unit; + m.F[0] = 1.0; m.Q[0] = 0.01; m.H[0] = 1.0; m.R[0] = 0.04; m.step_ns = 1000; + return m; +} +static inline est_observation fx_obs(est_unit unit, double z, double var, uint64_t seq) +{ + est_observation o; memset(&o, 0, sizeof o); + o.m = 1; o.unit[0] = unit; o.z[0] = z; o.R[0] = var; o.t_ns = (int64_t)seq * 1000; o.seq = seq; + memset(o.source.b, 0x5A, 32); memset(o.evidence.b, 0xE1 + (uint8_t)seq, 32); + return o; +} +/* Belief at `generation` with x, variance; evidence_root = extend(parent_root, digest(obs)). */ +static inline est_belief fx_belief(const est_model *m, const est_observation *obs, const est_digest *parent_root, + est_unit unit, double x, double var, uint64_t generation) +{ + est_belief b; est_digest od; memset(&b, 0, sizeof b); + b.n = 1; b.unit[0] = unit; b.x[0] = x; b.P[0] = var; b.generation = generation; b.t_ns = (int64_t)generation * 1000; + est_digest_model(m, &b.model); + memset(b.parent.b, 0x77, 32); + est_digest_observation(obs, &od); + est_evidence_root_extend(parent_root, &od, &b.evidence_root); + return b; +} +static inline RxDualController fx_ctl(uint32_t id, double eta, double rho, double k_sigma, double lmax, uint64_t max_age) +{ + RxDualController c; memset(&c, 0, sizeof c); + c.eta = eta; c.rho = rho; c.k_sigma = k_sigma; c.max_age = max_age; c.cadence = 1; + c.n = 1; c.resource_id[0] = id; c.lambda_max[0] = lmax; + return c; +} +static inline RxDualResource fx_res(uint32_t id, RxDualUnit unit, double scale) +{ + RxDualResource r; memset(&r, 0, sizeof r); + r.resource_id = id; r.unit = unit; r.scale = scale; r.contract = fx_dig(0x11); + return r; +} +/* A verified, calibrated input: estimate x, sd, at generation g, unit bytes. */ +static inline RxDualInput fx_input(double x, double sd, uint64_t g, int calibrated) +{ + RxDualInput in; memset(&in, 0, sizeof in); + in.estimate_ref = fx_dig(0x30 + (uint8_t)(g & 0x3F)); in.estimate_kind = RX_DUAL_EST_ESTIMATED; + in.unit = RX_DUAL_UNIT_BYTES; in.estimate = x; in.uncertainty = sd; in.generation = g; + in.evidence_root = fx_dig(0x66); in.evidence_verified = 1; + if (calibrated) in.calibration_ref = fx_dig(0x44); + return in; +} +#endif diff --git a/tests/dual/dual_ref.c b/tests/dual/dual_ref.c new file mode 100644 index 000000000..26775f9e2 --- /dev/null +++ b/tests/dual/dual_ref.c @@ -0,0 +1,17 @@ +#include "dual_ref.h" +#include +double dual_ref_gradient(double estimate, double budget, double scale, double uncertainty, double k_sigma) +{ + double p = (estimate - budget) / scale, band = k_sigma * uncertainty / scale; + if (p > band) return p - band; + if (p < -band) return p + band; + return 0.0; +} +double dual_ref_closed_form(double l0, double g, double eta, double rho, unsigned long t) +{ + double a; + if (rho == 0.0) return l0 + eta * g * (double)t; + a = pow(1.0 - rho, (double)t); + return a * l0 + eta * g * (1.0 - a) / rho; +} +double dual_ref_fixed_point(double g, double eta, double rho) { return eta * g / rho; } diff --git a/tests/dual/dual_ref.h b/tests/dual/dual_ref.h new file mode 100644 index 000000000..fd7ac94b0 --- /dev/null +++ b/tests/dual/dual_ref.h @@ -0,0 +1,16 @@ +/* Independent analytic reference for the DUAL-1a update, derived from ADR 0031 + * section 5.1 on paper, not from rx_dual_update.c. Closed forms for a constant + * input: with g constant and no clipping, the recursion + * l(t+1) = (1 - rho) l(t) + eta g + * has the solution + * l(t) = (1 - rho)^t l(0) + eta g (1 - (1 - rho)^t) / rho (rho > 0) + * l(t) = l(0) + eta g t (rho = 0) + * and the fixed point l* = eta g / rho. Clipping to [0, lambda_max] is applied + * per step, so the closed form holds exactly while the trajectory stays inside + * the bounds, and the implementation must saturate at the bound afterwards. */ +#ifndef DUAL_REF_H +#define DUAL_REF_H +double dual_ref_gradient(double estimate, double budget, double scale, double uncertainty, double k_sigma); +double dual_ref_closed_form(double l0, double g, double eta, double rho, unsigned long t); +double dual_ref_fixed_point(double g, double eta, double rho); +#endif diff --git a/tests/dual/test_dual_bind.c b/tests/dual/test_dual_bind.c new file mode 100644 index 000000000..d8eb784d0 --- /dev/null +++ b/tests/dual/test_dual_bind.c @@ -0,0 +1,141 @@ +/* DUAL-0b tests: binding to est_* records, unit table, evidence verification, + * freshness classification. */ +#include "dual_fixtures.h" +#include +#include + +static int g_checks, g_fail; +#define CHECK(c) do { g_checks++; if (!(c)) { g_fail++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0) +#define CHECK_ST(expr, want) do { RxDualStatus s_ = (expr); g_checks++; if (s_ != (want)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s -> %d, want %d\n", __FILE__, __LINE__, #expr, (int)s_, (int)(want)); } } while (0) + +static void test_units(void) +{ + RxDualUnit u; + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_BYTE, &u), RX_DUAL_OK); CHECK(u == RX_DUAL_UNIT_BYTES); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_NANOSECOND, &u), RX_DUAL_OK); CHECK(u == RX_DUAL_UNIT_NS); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_WATT, &u), RX_DUAL_OK); CHECK(u == RX_DUAL_UNIT_WATT); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_LOG2_PICOSECOND, &u), RX_DUAL_OK); CHECK(u == RX_DUAL_UNIT_LOG2_PS); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_NONE, &u), RX_DUAL_ERR_UNIT); CHECK(u == RX_DUAL_UNIT_NONE); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_MAX_, &u), RX_DUAL_ERR_UNIT); + CHECK_ST(rx_dual_unit_from_est((est_unit)77, &u), RX_DUAL_ERR_UNIT); + CHECK_ST(rx_dual_unit_from_est(EST_UNIT_BYTE, NULL), RX_DUAL_ERR_NULL); +} + +static void test_bind_belief_and_evidence(void) +{ + est_model m = fx_model(EST_UNIT_BYTE); + est_observation o = fx_obs(EST_UNIT_BYTE, 5200.0, 100.0, 1); + est_digest zero; memset(&zero, 0, sizeof zero); + est_belief b = fx_belief(&m, &o, &zero, EST_UNIT_BYTE, 5150.0, 64.0, 7); + RxDualInput in; RxDualDigest cal = fx_dig(0x44); est_digest bd; + CHECK(est_check_belief(&b) == EST_OK); + CHECK_ST(rx_dual_bind_belief(&b, 0, &cal, &in), RX_DUAL_OK); + CHECK(in.estimate == 5150.0 && in.uncertainty == 8.0 && in.unit == RX_DUAL_UNIT_BYTES && in.generation == 7); + CHECK(in.estimate_kind == RX_DUAL_EST_ESTIMATED && in.evidence_verified == 0 && rx_dual_digest_is_zero(&in.observation_ref)); + est_digest_belief(&b, &bd); CHECK(memcmp(bd.b, in.estimate_ref.b, 32) == 0); /* cites the record, copies nothing else */ + CHECK(memcmp(in.evidence_root.b, b.evidence_root.b, 32) == 0); + /* evidence verification: pass, then a broken root, then a wrong observation */ + CHECK_ST(rx_dual_verify_belief_evidence(&b, &zero, &o, &in), RX_DUAL_OK); CHECK(in.evidence_verified == 1); + { est_belief bad = b; bad.evidence_root.b[3] ^= 1; RxDualInput in2; + CHECK_ST(rx_dual_bind_belief(&bad, 0, &cal, &in2), RX_DUAL_OK); + CHECK_ST(rx_dual_verify_belief_evidence(&bad, &zero, &o, &in2), RX_DUAL_ERR_EVIDENCE); CHECK(in2.evidence_verified == 0); } + { est_observation o2 = fx_obs(EST_UNIT_BYTE, 5200.0, 100.0, 2); RxDualInput in3; + CHECK_ST(rx_dual_bind_belief(&b, 0, &cal, &in3), RX_DUAL_OK); + CHECK_ST(rx_dual_verify_belief_evidence(&b, &zero, &o2, &in3), RX_DUAL_ERR_EVIDENCE); } + { est_digest other; memset(other.b, 0x99, 32); RxDualInput in4; + CHECK_ST(rx_dual_bind_belief(&b, 0, &cal, &in4), RX_DUAL_OK); + CHECK_ST(rx_dual_verify_belief_evidence(&b, &other, &o, &in4), RX_DUAL_ERR_EVIDENCE); } + /* input not bound from this belief */ + { RxDualInput in5 = fx_input(1.0, 1.0, 7, 1); CHECK_ST(rx_dual_verify_belief_evidence(&b, &zero, &o, &in5), RX_DUAL_ERR_DIGEST); } + /* refusals */ + CHECK_ST(rx_dual_bind_belief(&b, 1, &cal, &in), RX_DUAL_ERR_RANGE); /* component out of range */ + { est_belief prior = b; prior.generation = 0; memset(prior.parent.b, 0, 32); memset(prior.evidence_root.b, 0, 32); + CHECK(est_check_belief(&prior) == EST_OK); + CHECK_ST(rx_dual_bind_belief(&prior, 0, &cal, &in), RX_DUAL_ERR_EVIDENCE); } /* a prior is not evidence */ + { est_belief nf = b; nf.x[0] = NAN; CHECK_ST(rx_dual_bind_belief(&nf, 0, &cal, &in), RX_DUAL_ERR_KIND); } /* est refuses it first */ + { est_belief nu = b; nu.unit[0] = EST_UNIT_NONE; CHECK(rx_dual_bind_belief(&nu, 0, &cal, &in) != RX_DUAL_OK); } + CHECK_ST(rx_dual_bind_belief(NULL, 0, &cal, &in), RX_DUAL_ERR_NULL); + /* uncalibrated binding is allowed and recorded as such */ + CHECK_ST(rx_dual_bind_belief(&b, 0, NULL, &in), RX_DUAL_OK); CHECK(rx_dual_digest_is_zero(&in.calibration_ref)); +} + +static void test_bind_prediction_and_observation(void) +{ + est_model m = fx_model(EST_UNIT_NANOSECOND); + est_observation o = fx_obs(EST_UNIT_NANOSECOND, 10.0, 1.0, 1); + est_digest zero; memset(&zero, 0, sizeof zero); + est_belief prior = fx_belief(&m, &o, &zero, EST_UNIT_NANOSECOND, 10.0, 1.0, 3); + est_prediction p; RxDualInput in; est_digest pd; + memset(&p, 0, sizeof p); + est_digest_belief(&prior, &p.prior); est_digest_model(&m, &p.model); + p.horizon = 2; p.generation = 5; p.t_ns = 5000; p.n = 1; p.m = 1; p.x[0] = 12.0; p.P[0] = 2.25; p.y_mean[0] = 12.0; p.S[0] = 2.29; + CHECK(est_check_prediction(&p) == EST_OK); + CHECK_ST(rx_dual_bind_prediction(&p, &m, &prior, 0, NULL, &in), RX_DUAL_OK); + CHECK(in.estimate == 12.0 && in.uncertainty == 1.5 && in.unit == RX_DUAL_UNIT_NS && in.generation == 5 && in.estimate_kind == RX_DUAL_EST_PREDICTED); + est_digest_prediction(&p, &pd); CHECK(memcmp(pd.b, in.estimate_ref.b, 32) == 0); + CHECK(memcmp(in.evidence_root.b, prior.evidence_root.b, 32) == 0); + { est_model m2 = m; m2.Q[0] = 0.02; CHECK_ST(rx_dual_bind_prediction(&p, &m2, &prior, 0, NULL, &in), RX_DUAL_ERR_DIGEST); } /* wrong model */ + { est_belief b2 = prior; b2.x[0] = 11.0; CHECK_ST(rx_dual_bind_prediction(&p, &m, &b2, 0, NULL, &in), RX_DUAL_ERR_DIGEST); } /* wrong prior */ + CHECK_ST(rx_dual_bind_prediction(&p, &m, &prior, 1, NULL, &in), RX_DUAL_ERR_RANGE); + /* observation: MEASURED, its own evidence */ + CHECK_ST(rx_dual_bind_observation(&o, 0, 9, NULL, &in), RX_DUAL_OK); + CHECK(in.estimate_kind == RX_DUAL_EST_MEASURED && in.estimate == 10.0 && in.uncertainty == 1.0 && in.generation == 9); + CHECK(rx_dual_digest_eq(&in.estimate_ref, &in.observation_ref) && in.evidence_verified == 1); + CHECK(memcmp(in.evidence_root.b, o.evidence.b, 32) == 0); + { est_observation bad = o; memset(bad.evidence.b, 0, 32); CHECK_ST(rx_dual_bind_observation(&bad, 0, 9, NULL, &in), RX_DUAL_ERR_KIND); } + CHECK_ST(rx_dual_bind_observation(&o, 3, 9, NULL, &in), RX_DUAL_ERR_RANGE); +} + +static void test_classify(void) +{ + RxDualController ctl = fx_ctl(1, 0.1, 0.01, 2.0, 10.0, 4); + RxDualLambdaState st; + RxDualInput in = fx_input(5200.0, 100.0, 10, 1); + RxDualConstraintState prev; memset(&prev, 0, sizeof prev); + prev.resource_id = 1; prev.unit = RX_DUAL_UNIT_BYTES; prev.cls = RX_DUAL_CLASS_SOFT; prev.budget = 5000.0; + prev.budget_contract = fx_dig(0x22); prev.estimate_ref = fx_dig(0x33); prev.estimate_kind = RX_DUAL_EST_ESTIMATED; + prev.estimate = 5000.0; prev.uncertainty = 100.0; prev.calibration_ref = fx_dig(0x44); prev.lambda = 0.0; + prev.lambda_state = RX_DUAL_LAMBDA_FRESH; prev.controller_id = fx_dig(0x55); prev.generation = 9; prev.tick = 0; + prev.evidence_root = fx_dig(0x66); + CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_FRESH); + CHECK_ST(rx_dual_classify_input(&in, NULL, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_FRESH); + in.calibration_ref = fx_dig(0); CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_UNCALIBRATED); + in = fx_input(5200.0, 100.0, 10, 1); + in.regime_change = 1; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_FROZEN); + in.regime_change = 0; + in.evidence_verified = 0; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_STALE); + in.evidence_verified = 1; + CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 14, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_FRESH); /* age 4 == max_age ok */ + CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 15, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_STALE); /* age 5 > max_age */ + in.generation = 8; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_STALE); /* older than prev */ + in.generation = 11; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_REFUSED); /* future */ + in.generation = 10; + in.estimate = NAN; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_REFUSED); + in.estimate = INFINITY; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_REFUSED); + in.estimate = 5200.0; in.uncertainty = -1.0; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_REFUSED); + in.uncertainty = 100.0; memset(&in.evidence_root, 0, 32); CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_OK); CHECK(st == RX_DUAL_LAMBDA_REFUSED); + in = fx_input(5200.0, 100.0, 10, 1); + in.unit = RX_DUAL_UNIT_NS; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_ERR_UNIT); /* structural */ + in.unit = RX_DUAL_UNIT_BYTES; + prev.cls = RX_DUAL_CLASS_INVARIANT; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_ERR_CLASS); + prev.cls = RX_DUAL_CLASS_SOFT; + ctl.max_age = 0; CHECK_ST(rx_dual_classify_input(&in, &prev, &ctl, 10, &st), RX_DUAL_ERR_RANGE); + /* evidence chain */ + { RxDualDigest zero = fx_dig(0), r1, r2, r3, e = fx_dig(0x33); + CHECK_ST(rx_dual_evidence_extend(&zero, &e, &r1), RX_DUAL_OK); + CHECK_ST(rx_dual_evidence_extend(&r1, &e, &r2), RX_DUAL_OK); + CHECK_ST(rx_dual_evidence_extend(&zero, &e, &r3), RX_DUAL_OK); + CHECK(!rx_dual_digest_is_zero(&r1) && !rx_dual_digest_eq(&r1, &r2) && rx_dual_digest_eq(&r1, &r3)); + CHECK_ST(rx_dual_evidence_extend(&zero, &zero, &r1), RX_DUAL_ERR_DIGEST); } +} + +int main(void) +{ + test_units(); + test_bind_belief_and_evidence(); + test_bind_prediction_and_observation(); + test_classify(); + printf("test_dual_bind: %d checks, %d failures: %s\n", g_checks, g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +} diff --git a/tests/dual/test_dual_types.c b/tests/dual/test_dual_types.c new file mode 100644 index 000000000..74df8f8e7 --- /dev/null +++ b/tests/dual/test_dual_types.c @@ -0,0 +1,427 @@ +/* DUAL-0a contract tests: validation, refusal, canonical encoding, digests, + * properties (ADR 0031 sections 3, 4, 8.1). Plain C, assert-style: every + * CHECK counts as one case; any failure exits nonzero. */ +#include "rx_dual.h" + +#include +#include +#include +#include + +#ifndef PROP_ROUNDS +#define PROP_ROUNDS 2000 +#endif + +static int g_checks, g_fail; +#define CHECK(c) do { g_checks++; if (!(c)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0) +#define CHECK_ST(expr, want) do { RxDualStatus s_ = (expr); g_checks++; if (s_ != (want)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s -> %d, want %d\n", __FILE__, __LINE__, #expr, (int)s_, (int)(want)); } } while (0) + +static uint64_t g_rng = 0x9E3779B97F4A7C15ull; +static uint64_t rnd(void) +{ + g_rng ^= g_rng >> 12; g_rng ^= g_rng << 25; g_rng ^= g_rng >> 27; + return g_rng * 0x2545F4914F6CDD1Dull; +} +static double rdbl(double lo, double hi) { return lo + (hi - lo) * ((double)(rnd() >> 11) / 9007199254740992.0); } +static RxDualUnit runit(void) { return (RxDualUnit)(1u + (uint32_t)(rnd() % (RX_DUAL_UNIT_MAX_ - 1u))); } +static void rdig(RxDualDigest *d) { for (int i = 0; i < 32; i++) d->b[i] = (uint8_t)rnd(); } +static RxDualDigest fixed(uint8_t v) { RxDualDigest d; memset(d.b, v, 32); return d; } + +/* ---- fixtures ---- */ +static RxDualResource mk_resource(uint32_t id, RxDualUnit u) +{ + RxDualResource r; + memset(&r, 0, sizeof r); + r.resource_id = id; r.unit = u; r.scale = 1000.0; r.contract = fixed(0x11); + return r; +} +static RxDualConstraintState mk_constraint(uint32_t id, RxDualUnit u, RxDualClass cls) +{ + RxDualConstraintState s; + memset(&s, 0, sizeof s); + s.resource_id = id; s.unit = u; s.cls = cls; + s.budget = 5000.0; s.budget_contract = fixed(0x22); + s.estimate_ref = fixed(0x33); s.estimate_kind = RX_DUAL_EST_ESTIMATED; + s.estimate = 5200.0; s.uncertainty = 100.0; + s.calibration_ref = fixed(0x44); + s.lambda = 0.25; s.lambda_state = RX_DUAL_LAMBDA_FRESH; + s.controller_id = fixed(0x55); s.generation = 7; s.tick = 3; + s.evidence_root = fixed(0x66); s.parent = fixed(0x77); + return s; +} +static RxDualController mk_controller(void) +{ + RxDualController c; + memset(&c, 0, sizeof c); + c.eta = 0.1; c.rho = 0.01; c.k_sigma = 2.0; c.max_age = 4; c.cadence = 1; + c.n = 3; + c.resource_id[0] = 1; c.resource_id[1] = 2; c.resource_id[2] = 9; + c.lambda_max[0] = 10.0; c.lambda_max[1] = 10.0; c.lambda_max[2] = 1.0; + return c; +} +static RxDualPriceVector mk_pv(void) +{ + RxDualPriceVector v; + memset(&v, 0, sizeof v); + v.generation = 7; v.context = fixed(0x88); v.n = 2; + v.resource_id[0] = 1; v.resource_id[1] = 2; + v.state[0] = fixed(0x91); v.state[1] = fixed(0x92); + return v; +} +static RxDualSite mk_site(void) +{ + RxDualSite s; + memset(&s, 0, sizeof s); + s.site_id = 1; memcpy(s.name, "jspace.residency", 16); s.owner = fixed(0xA1); s.max_alternatives = 5; + return s; +} +static RxDualRecommendation mk_rec(void) +{ + RxDualRecommendation r; + memset(&r, 0, sizeof r); + r.decision_site = fixed(0xB1); r.price_vector = fixed(0xB2); r.generation = 7; + r.n_candidates = 3; r.candidates[0] = fixed(0xC1); r.candidates[1] = fixed(0xC2); r.candidates[2] = fixed(0xC3); + r.actual = 0; r.recommended = 2; r.n_consequences = 2; + rx_dual_consequence_set(&r.c[0], 1, RX_DUAL_UNIT_PS, 100.0, 10.0, 1, 112.0); + rx_dual_consequence_set(&r.c[1], 2, RX_DUAL_UNIT_PJ, 50.0, 5.0, 0, 0.0); + r.authority = RX_DUAL_AUTHORITY_NONE; + return r; +} +static RxDualOutcome mk_outcome(void) +{ + RxDualOutcome o; + memset(&o, 0, sizeof o); + o.recommendation = fixed(0xD1); o.before_vector = fixed(0xD2); o.after_vector = fixed(0xD3); + o.target_resource_id = 1; o.generation_before = 7; o.generation_after = 9; + o.lambda_before = 0.5; o.lambda_after = 0.3; + return o; +} + +/* ---- round trip + digest determinism, per record kind ---- */ +#define ROUNDTRIP(T, enc, dec, dig, obj, kindbyte) \ + do { \ + uint8_t b1[RX_DUAL_ENCODED_MAX], b2[RX_DUAL_ENCODED_MAX]; \ + size_t l1 = 0, l2 = 0; T back; RxDualDigest d1, d2, d3; \ + CHECK_ST(enc(&(obj), b1, sizeof b1, &l1), RX_DUAL_OK); \ + CHECK(l1 > 2 && b1[0] == (kindbyte) && b1[1] == RX_DUAL_FORMAT_VERSION); \ + CHECK_ST(dec(b1, l1, &back), RX_DUAL_OK); \ + CHECK_ST(enc(&back, b2, sizeof b2, &l2), RX_DUAL_OK); \ + CHECK(l1 == l2 && memcmp(b1, b2, l1) == 0); \ + CHECK_ST(dig(&(obj), &d1), RX_DUAL_OK); \ + CHECK_ST(dig(&back, &d2), RX_DUAL_OK); \ + CHECK_ST(dig(&(obj), &d3), RX_DUAL_OK); \ + CHECK(rx_dual_digest_eq(&d1, &d2) && rx_dual_digest_eq(&d1, &d3)); \ + CHECK_ST(dec(b1, l1 - 1, &back), RX_DUAL_ERR_ENCODING); /* truncated */ \ + CHECK_ST(dec(b1, l1 + 1, &back), RX_DUAL_ERR_ENCODING); /* trailing byte */ \ + CHECK_ST(dec(b1, 1, &back), RX_DUAL_ERR_ENCODING); \ + b1[1] = 2; CHECK_ST(dec(b1, l1, &back), RX_DUAL_ERR_ENCODING); b1[1] = 1; /* version */ \ + b1[0] = 99; CHECK_ST(dec(b1, l1, &back), RX_DUAL_ERR_KIND); b1[0] = (kindbyte); \ + CHECK_ST(enc(&(obj), b1, 4, &l1), RX_DUAL_ERR_ENCODING); /* capacity */ \ + CHECK_ST(enc(&(obj), NULL, 0, &l1), RX_DUAL_ERR_NULL); \ + CHECK_ST(dec(NULL, l1, &back), RX_DUAL_ERR_NULL); \ + } while (0) + +static void test_roundtrips(void) +{ + RxDualResource r = mk_resource(1, RX_DUAL_UNIT_PS); + RxDualConstraintState s = mk_constraint(1, RX_DUAL_UNIT_PS, RX_DUAL_CLASS_SOFT); + RxDualController c = mk_controller(); + RxDualPriceVector v = mk_pv(); + RxDualSite site = mk_site(); + RxDualRecommendation rec = mk_rec(); + RxDualOutcome o = mk_outcome(); + ROUNDTRIP(RxDualResource, rx_dual_encode_resource, rx_dual_decode_resource, rx_dual_digest_resource, r, RX_DUAL_KIND_RESOURCE); + ROUNDTRIP(RxDualConstraintState, rx_dual_encode_constraint, rx_dual_decode_constraint, rx_dual_digest_constraint, s, RX_DUAL_KIND_CONSTRAINT); + ROUNDTRIP(RxDualController, rx_dual_encode_controller, rx_dual_decode_controller, rx_dual_digest_controller, c, RX_DUAL_KIND_CONTROLLER); + ROUNDTRIP(RxDualPriceVector, rx_dual_encode_price_vector, rx_dual_decode_price_vector, rx_dual_digest_price_vector, v, RX_DUAL_KIND_PRICE_VECTOR); + ROUNDTRIP(RxDualSite, rx_dual_encode_site, rx_dual_decode_site, rx_dual_digest_site, site, RX_DUAL_KIND_SITE); + ROUNDTRIP(RxDualRecommendation, rx_dual_encode_recommendation, rx_dual_decode_recommendation, rx_dual_digest_recommendation, rec, RX_DUAL_KIND_RECOMMENDATION); + ROUNDTRIP(RxDualOutcome, rx_dual_encode_outcome, rx_dual_decode_outcome, rx_dual_digest_outcome, o, RX_DUAL_KIND_OUTCOME); +} + +/* ---- kind confusion and digest-domain separation ---- */ +static void test_kind_confusion(void) +{ + uint8_t buf[RX_DUAL_ENCODED_MAX]; size_t len = 0; + RxDualResource r = mk_resource(1, RX_DUAL_UNIT_PS); + RxDualConstraintState s = mk_constraint(1, RX_DUAL_UNIT_PS, RX_DUAL_CLASS_SOFT); + RxDualConstraintState sback; RxDualResource rback; RxDualOutcome oback; + RxDualDigest d_res, d_con, d_pv, d_site; + RxDualPriceVector v = mk_pv(); + RxDualSite site = mk_site(); + + CHECK_ST(rx_dual_encode_resource(&r, buf, sizeof buf, &len), RX_DUAL_OK); + CHECK_ST(rx_dual_decode_constraint(buf, len, &sback), RX_DUAL_ERR_KIND); + CHECK_ST(rx_dual_decode_outcome(buf, len, &oback), RX_DUAL_ERR_KIND); + CHECK_ST(rx_dual_encode_constraint(&s, buf, sizeof buf, &len), RX_DUAL_OK); + CHECK_ST(rx_dual_decode_resource(buf, len, &rback), RX_DUAL_ERR_KIND); + /* Same payload bytes under another kind byte must not decode as that kind + * (length and validation differ), and digests of distinct kinds differ. */ + buf[0] = (uint8_t)RX_DUAL_KIND_RESOURCE; + CHECK(rx_dual_decode_resource(buf, len, &rback) != RX_DUAL_OK); + CHECK_ST(rx_dual_digest_resource(&r, &d_res), RX_DUAL_OK); + CHECK_ST(rx_dual_digest_constraint(&s, &d_con), RX_DUAL_OK); + CHECK_ST(rx_dual_digest_price_vector(&v, &d_pv), RX_DUAL_OK); + CHECK_ST(rx_dual_digest_site(&site, &d_site), RX_DUAL_OK); + CHECK(!rx_dual_digest_eq(&d_res, &d_con) && !rx_dual_digest_eq(&d_pv, &d_site) && !rx_dual_digest_eq(&d_res, &d_pv)); +} + +/* ---- hostile resource / registry ---- */ +static void test_resource_registry(void) +{ + RxDualRegistry reg; RxDualResource r = mk_resource(5, RX_DUAL_UNIT_BYTES); + RxDualDigest d; + rx_dual_registry_init(®); + CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_OK); + CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_ERR_RESOURCE); /* duplicate id */ + r.resource_id = 2; CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_OK); + r.resource_id = 9; CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_OK); + CHECK(reg.n == 3 && reg.r[0].resource_id == 2 && reg.r[1].resource_id == 5 && reg.r[2].resource_id == 9); + CHECK(rx_dual_registry_find(®, 5) != NULL && rx_dual_registry_find(®, 7) == NULL); + r.resource_id = 3; r.scale = -1.0; CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_ERR_SCALE); /* negative scale */ + r.scale = 0.0; CHECK_ST(rx_dual_registry_add(®, &r), RX_DUAL_ERR_SCALE); /* zero scale */ + r.scale = NAN; CHECK_ST(rx_dual_check_resource(&r), RX_DUAL_ERR_NONFINITE); + r.scale = INFINITY; CHECK_ST(rx_dual_check_resource(&r), RX_DUAL_ERR_NONFINITE); + r.scale = -INFINITY; CHECK_ST(rx_dual_check_resource(&r), RX_DUAL_ERR_NONFINITE); + r.scale = 1.0; r.unit = RX_DUAL_UNIT_NONE; CHECK_ST(rx_dual_check_resource(&r), RX_DUAL_ERR_UNIT); + r.unit = (RxDualUnit)RX_DUAL_UNIT_MAX_; CHECK_ST(rx_dual_check_resource(&r), RX_DUAL_ERR_UNIT); + r.unit = RX_DUAL_UNIT_KV_BLOCKS; memset(&r.contract, 0, 32); CHECK_ST(rx_dual_digest_resource(&r, &d), RX_DUAL_ERR_DIGEST); + CHECK_ST(rx_dual_check_resource(NULL), RX_DUAL_ERR_NULL); + /* capacity */ + rx_dual_registry_init(®); + for (uint32_t i = 0; i < RX_DUAL_MAX_RESOURCES; i++) { RxDualResource x = mk_resource(100 + i, RX_DUAL_UNIT_PS); CHECK_ST(rx_dual_registry_add(®, &x), RX_DUAL_OK); } + { RxDualResource x = mk_resource(999, RX_DUAL_UNIT_PS); CHECK_ST(rx_dual_registry_add(®, &x), RX_DUAL_ERR_FULL); } +} + +/* ---- hostile constraint ---- */ +static void test_constraint_rules(void) +{ + RxDualConstraintState s = mk_constraint(1, RX_DUAL_UNIT_PS, RX_DUAL_CLASS_SOFT); + RxDualResource r = mk_resource(1, RX_DUAL_UNIT_PS); + RxDualDigest d; + CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + CHECK_ST(rx_dual_check_constraint_against(&s, &r), RX_DUAL_OK); + s.cls = RX_DUAL_CLASS_INVARIANT; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_CLASS); /* INVARIANT unconstructible */ + CHECK_ST(rx_dual_digest_constraint(&s, &d), RX_DUAL_ERR_CLASS); + s.cls = RX_DUAL_CLASS_UNDECLARED; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_CLASS); /* never defaulted */ + s.cls = (RxDualClass)RX_DUAL_CLASS_MAX_; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_CLASS); + s.cls = RX_DUAL_CLASS_CAPACITY; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); /* diagnostic price allowed */ + s.cls = RX_DUAL_CLASS_SOFT; + s.lambda = -0.1; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_RANGE); + s.lambda = NAN; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_NONFINITE); + s.lambda = INFINITY; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_NONFINITE); + s.lambda = 0.25; + s.uncertainty = -1.0; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_RANGE); + s.uncertainty = -INFINITY; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_NONFINITE); + s.uncertainty = 100.0; + s.estimate = NAN; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_NONFINITE); s.estimate = 5200.0; + s.budget = INFINITY; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_NONFINITE); s.budget = 5000.0; + s.unit = RX_DUAL_UNIT_NONE; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_UNIT); s.unit = RX_DUAL_UNIT_PS; + /* unit mismatch against the registry: refused, never converted */ + r.unit = RX_DUAL_UNIT_NS; CHECK_ST(rx_dual_check_constraint_against(&s, &r), RX_DUAL_ERR_UNIT); r.unit = RX_DUAL_UNIT_PS; + r.resource_id = 2; CHECK_ST(rx_dual_check_constraint_against(&s, &r), RX_DUAL_ERR_RESOURCE); r.resource_id = 1; + /* kinds */ + s.estimate_kind = (RxDualEstimateKind)0; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_KIND); + s.estimate_kind = RX_DUAL_EST_MEASURED; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); /* measured needs observation_ref */ + s.observation_ref = fixed(0x12); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + s.estimate_kind = RX_DUAL_EST_ESTIMATED; + /* lambda state */ + s.lambda_state = (RxDualLambdaState)0; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_RANGE); + s.lambda_state = (RxDualLambdaState)RX_DUAL_LAMBDA_MAX_; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_RANGE); + s.lambda_state = RX_DUAL_LAMBDA_FRESH; + /* FRESH requires calibration; UNCALIBRATED may be recorded */ + memset(&s.calibration_ref, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_CALIBRATION); + s.lambda_state = RX_DUAL_LAMBDA_UNCALIBRATED; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + s.lambda_state = RX_DUAL_LAMBDA_STALE; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + s.calibration_ref = fixed(0x44); s.lambda_state = RX_DUAL_LAMBDA_FRESH; + /* required digests */ + memset(&s.estimate_ref, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); s.estimate_ref = fixed(0x33); + memset(&s.controller_id, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); s.controller_id = fixed(0x55); + memset(&s.evidence_root, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); s.evidence_root = fixed(0x66); + memset(&s.budget_contract, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); s.budget_contract = fixed(0x22); + /* parent / tick linkage: broken parent refused both ways */ + memset(&s.parent, 0, 32); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); + s.tick = 0; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + s.parent = fixed(0x77); CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_ERR_DIGEST); + s.tick = 3; CHECK_ST(rx_dual_check_constraint(&s), RX_DUAL_OK); + /* a decoder refuses what the checker refuses: craft bytes with class INVARIANT */ + { + uint8_t buf[RX_DUAL_ENCODED_MAX]; size_t len = 0; RxDualConstraintState back; + CHECK_ST(rx_dual_encode_constraint(&s, buf, sizeof buf, &len), RX_DUAL_OK); + buf[2 + 4 + 4] = (uint8_t)RX_DUAL_CLASS_INVARIANT; /* class field follows id and unit */ + CHECK_ST(rx_dual_decode_constraint(buf, len, &back), RX_DUAL_ERR_CLASS); + buf[2 + 4 + 4] = (uint8_t)RX_DUAL_CLASS_UNDECLARED; + CHECK_ST(rx_dual_decode_constraint(buf, len, &back), RX_DUAL_ERR_CLASS); + } + /* -0.0 canonicalizes to +0.0: same digest */ + { + RxDualConstraintState a = mk_constraint(1, RX_DUAL_UNIT_PS, RX_DUAL_CLASS_SOFT), b = a; RxDualDigest da, db; + a.lambda = 0.0; b.lambda = -0.0; + CHECK_ST(rx_dual_digest_constraint(&a, &da), RX_DUAL_OK); + CHECK_ST(rx_dual_digest_constraint(&b, &db), RX_DUAL_OK); + CHECK(rx_dual_digest_eq(&da, &db)); + } +} + +/* ---- controller ---- */ +static void test_controller(void) +{ + RxDualController c = mk_controller(); RxDualDigest d1, d2; double lm = 0; + CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_OK); + CHECK_ST(rx_dual_digest_controller(&c, &d1), RX_DUAL_OK); + CHECK_ST(rx_dual_controller_lambda_max(&c, 9, &lm), RX_DUAL_OK); CHECK(lm == 1.0); + CHECK_ST(rx_dual_controller_lambda_max(&c, 4, &lm), RX_DUAL_ERR_RESOURCE); /* unknown resource */ + c.eta = 0.1000001; CHECK_ST(rx_dual_digest_controller(&c, &d2), RX_DUAL_OK); + CHECK(!rx_dual_digest_eq(&d1, &d2)); /* parameter mutation = new controller */ + c.eta = 0.1; + c.eta = -0.1; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); c.eta = 0.1; + c.eta = NAN; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_NONFINITE); c.eta = 0.1; + c.rho = 1.5; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); c.rho = 0.01; + c.k_sigma = -1.0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); c.k_sigma = 2.0; + c.max_age = 0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); c.max_age = 4; + c.cadence = 0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); c.cadence = 1; + c.lambda_max[1] = 0.0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); + c.lambda_max[1] = INFINITY; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_NONFINITE); c.lambda_max[1] = 10.0; + c.resource_id[1] = 1; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RESOURCE); /* duplicate */ + c.resource_id[1] = 0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RESOURCE); /* unordered */ + c.resource_id[1] = 2; + c.n = 0; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); + c.n = RX_DUAL_MAX_RESOURCES + 1; CHECK_ST(rx_dual_check_controller(&c), RX_DUAL_ERR_RANGE); + c.n = 3; + /* malformed controller bytes: n above capacity is refused before any read */ + { + uint8_t buf[RX_DUAL_ENCODED_MAX]; size_t len = 0; RxDualController back; + CHECK_ST(rx_dual_encode_controller(&c, buf, sizeof buf, &len), RX_DUAL_OK); + buf[2 + 8 * 5] = 0xFF; buf[2 + 8 * 5 + 1] = 0xFF; + CHECK_ST(rx_dual_decode_controller(buf, len, &back), RX_DUAL_ERR_RANGE); + } +} + +/* ---- price vector ---- */ +static void test_price_vector(void) +{ + RxDualPriceVector v = mk_pv(); RxDualDigest d; + RxDualConstraintState a = mk_constraint(1, RX_DUAL_UNIT_PS, RX_DUAL_CLASS_SOFT); + RxDualConstraintState b = mk_constraint(2, RX_DUAL_UNIT_PJ, RX_DUAL_CLASS_CAPACITY); + RxDualConstraintState c = mk_constraint(1, RX_DUAL_UNIT_PJ, RX_DUAL_CLASS_SOFT); + const RxDualConstraintState *ok[2] = { &a, &b }, *dup[2] = { &a, &c }, *rev[2] = { &b, &a }; + RxDualPriceVector built; RxDualDigest ctx = fixed(0x88); + CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_OK); + v.resource_id[1] = 1; CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_ERR_RESOURCE); /* duplicate */ + v.resource_id[1] = 0; CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_ERR_RESOURCE); /* unordered */ + v.resource_id[1] = 2; + memset(&v.state[1], 0, 32); CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_ERR_DIGEST); v.state[1] = fixed(0x92); + memset(&v.context, 0, 32); CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_ERR_DIGEST); v.context = fixed(0x88); + v.n = 0; CHECK_ST(rx_dual_check_price_vector(&v), RX_DUAL_ERR_RANGE); v.n = 2; + CHECK_ST(rx_dual_price_vector_build(ok, 2, &ctx, &built), RX_DUAL_OK); + CHECK(built.n == 2 && built.generation == 7 && built.resource_id[1] == 2); + CHECK_ST(rx_dual_digest_constraint(&b, &d), RX_DUAL_OK); CHECK(rx_dual_digest_eq(&d, &built.state[1])); + CHECK_ST(rx_dual_price_vector_build(dup, 2, &ctx, &built), RX_DUAL_ERR_RESOURCE); /* duplicate resource */ + CHECK_ST(rx_dual_price_vector_build(rev, 2, &ctx, &built), RX_DUAL_ERR_RESOURCE); /* noncanonical order */ + b.generation = 8; CHECK_ST(rx_dual_price_vector_build(ok, 2, &ctx, &built), RX_DUAL_ERR_GENERATION); b.generation = 7; + b.cls = RX_DUAL_CLASS_INVARIANT; CHECK_ST(rx_dual_price_vector_build(ok, 2, &ctx, &built), RX_DUAL_ERR_CLASS); b.cls = RX_DUAL_CLASS_CAPACITY; + memset(&ctx, 0, 32); CHECK_ST(rx_dual_price_vector_build(ok, 2, &ctx, &built), RX_DUAL_ERR_DIGEST); +} + +/* ---- site, recommendation, outcome ---- */ +static void test_site_rec_outcome(void) +{ + RxDualSite s = mk_site(); RxDualRecommendation r = mk_rec(); RxDualOutcome o = mk_outcome(); + RxDualConsequence c; + CHECK_ST(rx_dual_check_site(&s), RX_DUAL_OK); + s.name[16] = 'x'; CHECK_ST(rx_dual_check_site(&s), RX_DUAL_OK); /* longer name still canonical */ + s.name[20] = 'y'; CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_SITE); /* embedded NUL then data */ + s = mk_site(); s.name[3] = ' '; CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_SITE); /* non-printable */ + s = mk_site(); s.name[0] = 0; CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_SITE); + s = mk_site(); memset(s.name, 'a', 32); CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_SITE); /* unterminated */ + s = mk_site(); s.max_alternatives = 0; CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_RANGE); + s = mk_site(); memset(&s.owner, 0, 32); CHECK_ST(rx_dual_check_site(&s), RX_DUAL_ERR_DIGEST); + + CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_OK); + CHECK(r.c[0].error == 1.2); + r.authority = 1; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_AUTHORITY); r.authority = 0; + r.actual = 3; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); r.actual = 0; + r.recommended = 99; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); r.recommended = 2; + r.n_candidates = 0; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); r.n_candidates = 3; + memset(&r.candidates[1], 0, 32); CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_DIGEST); r.candidates[1] = fixed(0xC2); + memset(&r.price_vector, 0, 32); CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_DIGEST); r.price_vector = fixed(0xB2); + memset(&r.decision_site, 0, 32); CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_DIGEST); r.decision_site = fixed(0xB1); + r.c[1].resource_id = 1; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RESOURCE); r.c[1].resource_id = 2; + r.c[0].error = 1.3; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); /* lying error field */ + r.c[0].error = 1.2; + r.c[1].measured = 1.0; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); /* unmeasured with a value */ + r.c[1].measured = 0.0; + r.c[0].predicted_sd = 0.0; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_RANGE); /* measured needs sd > 0 */ + r.c[0].predicted_sd = 10.0; + r.c[0].unit = RX_DUAL_UNIT_NONE; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_UNIT); r.c[0].unit = RX_DUAL_UNIT_PS; + r.c[0].predicted = NAN; CHECK_ST(rx_dual_check_recommendation(&r), RX_DUAL_ERR_NONFINITE); r.c[0].predicted = 100.0; + /* authority byte in the encoding is refused by the decoder too */ + { + uint8_t buf[RX_DUAL_ENCODED_MAX]; size_t len = 0; RxDualRecommendation back; + CHECK_ST(rx_dual_encode_recommendation(&r, buf, sizeof buf, &len), RX_DUAL_OK); + buf[len - 4] = 1; + CHECK_ST(rx_dual_decode_recommendation(buf, len, &back), RX_DUAL_ERR_AUTHORITY); + } + CHECK_ST(rx_dual_consequence_set(&c, 1, RX_DUAL_UNIT_PS, 1.0, 0.0, 1, 2.0), RX_DUAL_ERR_RANGE); + CHECK_ST(rx_dual_consequence_set(&c, 1, RX_DUAL_UNIT_PS, 1.0, NAN, 0, 0.0), RX_DUAL_ERR_NONFINITE); + CHECK_ST(rx_dual_consequence_set(&c, 1, RX_DUAL_UNIT_PS, 1.0, 2.0, 1, INFINITY), RX_DUAL_ERR_NONFINITE); + CHECK_ST(rx_dual_consequence_set(&c, 1, RX_DUAL_UNIT_PS, 1.0, 2.0, 0, 0.0), RX_DUAL_OK); + + CHECK_ST(rx_dual_check_outcome(&o), RX_DUAL_OK); + o.generation_after = 6; CHECK_ST(rx_dual_check_outcome(&o), RX_DUAL_ERR_GENERATION); o.generation_after = 9; + o.lambda_after = -1.0; CHECK_ST(rx_dual_check_outcome(&o), RX_DUAL_ERR_RANGE); o.lambda_after = 0.3; + o.lambda_before = NAN; CHECK_ST(rx_dual_check_outcome(&o), RX_DUAL_ERR_NONFINITE); o.lambda_before = 0.5; + memset(&o.after_vector, 0, 32); CHECK_ST(rx_dual_check_outcome(&o), RX_DUAL_ERR_DIGEST); +} + +/* ---- properties: random valid records round-trip byte-identically; any + * single-byte mutation of the encoding either fails to decode or yields a + * different digest (no two distinct encodings share an identity). ---- */ +static void test_properties(void) +{ + for (int round = 0; round < PROP_ROUNDS; round++) { + RxDualConstraintState s = mk_constraint(1u + (uint32_t)(rnd() % 1000u), runit(), + (rnd() & 1) ? RX_DUAL_CLASS_SOFT : RX_DUAL_CLASS_CAPACITY); + uint8_t b1[RX_DUAL_ENCODED_MAX], b2[RX_DUAL_ENCODED_MAX]; size_t l1 = 0, l2 = 0; + RxDualConstraintState back; RxDualDigest d1, d2; + s.budget = rdbl(-1e6, 1e6); s.estimate = rdbl(-1e6, 1e6); s.uncertainty = rdbl(0, 1e3); + s.lambda = rdbl(0, 10); s.generation = rnd(); s.tick = 1 + (rnd() % 1000); + rdig(&s.estimate_ref); rdig(&s.parent); rdig(&s.evidence_root); rdig(&s.controller_id); rdig(&s.budget_contract); + s.estimate_kind = (RxDualEstimateKind)(1u + (uint32_t)(rnd() % 3u)); + if (s.estimate_kind == RX_DUAL_EST_MEASURED) rdig(&s.observation_ref); + s.lambda_state = (RxDualLambdaState)(1u + (uint32_t)(rnd() % 5u)); + if (rnd() % 4 == 0) { memset(&s.calibration_ref, 0, 32); if (s.lambda_state == RX_DUAL_LAMBDA_FRESH) s.lambda_state = RX_DUAL_LAMBDA_UNCALIBRATED; } + else rdig(&s.calibration_ref); + CHECK_ST(rx_dual_encode_constraint(&s, b1, sizeof b1, &l1), RX_DUAL_OK); + CHECK_ST(rx_dual_decode_constraint(b1, l1, &back), RX_DUAL_OK); + CHECK_ST(rx_dual_encode_constraint(&back, b2, sizeof b2, &l2), RX_DUAL_OK); + CHECK(l1 == l2 && memcmp(b1, b2, l1) == 0); + CHECK_ST(rx_dual_digest_constraint(&s, &d1), RX_DUAL_OK); + { + size_t pos = 2 + (size_t)(rnd() % (l1 - 2)); + uint8_t saved = b1[pos]; + b1[pos] ^= (uint8_t)(1u << (rnd() % 8)); + if (rx_dual_decode_constraint(b1, l1, &back) == RX_DUAL_OK) { + CHECK_ST(rx_dual_digest_constraint(&back, &d2), RX_DUAL_OK); + CHECK(!rx_dual_digest_eq(&d1, &d2)); + } + b1[pos] = saved; + } + } +} + +int main(void) +{ + test_roundtrips(); + test_kind_confusion(); + test_resource_registry(); + test_constraint_rules(); + test_controller(); + test_price_vector(); + test_site_rec_outcome(); + test_properties(); + printf("test_dual_types: %d checks, %d failures: %s\n", g_checks, g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +} diff --git a/tests/dual/test_dual_update.c b/tests/dual/test_dual_update.c new file mode 100644 index 000000000..eb0a8790b --- /dev/null +++ b/tests/dual/test_dual_update.c @@ -0,0 +1,207 @@ +/* DUAL-1a tests: the reference update as a pure function; analytic cases + * against an independent closed form (dual_ref.c); property suite; hostile + * structural cases. */ +#include "dual_fixtures.h" +#include "dual_ref.h" +#include +#include + +#ifndef PROP_ROUNDS +#define PROP_ROUNDS 3000 +#endif +static int g_checks, g_fail; +#define CHECK(c) do { g_checks++; if (!(c)) { g_fail++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0) +#define CHECK_ST(expr, want) do { RxDualStatus s_ = (expr); g_checks++; if (s_ != (want)) { g_fail++; \ + fprintf(stderr, "FAIL %s:%d: %s -> %d, want %d\n", __FILE__, __LINE__, #expr, (int)s_, (int)(want)); } } while (0) +static uint64_t g_rng = 0xD1B54A32D192ED03ull; +static uint64_t rnd(void) { g_rng ^= g_rng >> 12; g_rng ^= g_rng << 25; g_rng ^= g_rng >> 27; return g_rng * 0x2545F4914F6CDD1Dull; } +static double rdbl(double lo, double hi) { return lo + (hi - lo) * ((double)(rnd() >> 11) / 9007199254740992.0); } + +static const double BUDGET = 5000.0, SCALE = 1000.0; +static RxDualDigest BC; + +static RxDualStatus run(const RxDualController *ctl, const RxDualResource *res, const double *est, const double *sd, + uint32_t n, RxDualConstraintState *out, double *trace) +{ + RxDualConstraintState s, nx; RxDualStatus st; + RxDualInput in = fx_input(est[0], sd[0], 1, 1); + if ((st = rx_dual_init_state(res, RX_DUAL_CLASS_SOFT, BUDGET, &BC, &in, ctl, 1, &s)) != RX_DUAL_OK) return st; + if (trace) trace[0] = s.lambda; + for (uint32_t t = 1; t < n; t++) { + in = fx_input(est[t], sd[t], t + 1, 1); + if ((st = rx_dual_update(&s, res, &in, ctl, t + 1, &nx)) != RX_DUAL_OK) return st; + if (trace) trace[t] = nx.lambda; + s = nx; + } + *out = s; + return RX_DUAL_OK; +} + +/* ---- analytic cases vs the independent closed form ---- */ +static void test_analytic(void) +{ + enum { N = 60 }; + double est[N], sd[N], tr[N]; + RxDualResource res = fx_res(1, RX_DUAL_UNIT_BYTES, SCALE); + RxDualConstraintState fin; + /* 1. single binding constraint: estimate 5500 (pressure 0.5), sd 100 (band 0.2) -> g = 0.3 */ + { RxDualController ctl = fx_ctl(1, 0.1, 0.05, 2.0, 10.0, 4); double g = dual_ref_gradient(5500, BUDGET, SCALE, 100, 2.0); + for (int i = 0; i < N; i++) { est[i] = 5500; sd[i] = 100; } + CHECK(fabs(g - 0.3) < 1e-12); + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + for (unsigned long t = 0; t < N; t++) CHECK(fabs(tr[t] - dual_ref_closed_form(0.0, g, 0.1, 0.05, t + 1)) < 1e-9); + CHECK(tr[N - 1] > tr[0] && tr[N - 1] <= dual_ref_fixed_point(g, 0.1, 0.05) + 1e-9 && fin.lambda_state == RX_DUAL_LAMBDA_FRESH); } + /* 2. slack constraint from a nonzero price: estimate 4000 (pressure -1), band 0.2 -> g = -0.8: decays to 0 and stays */ + { RxDualController ctl = fx_ctl(1, 0.1, 0.05, 2.0, 10.0, 4); + for (int i = 0; i < N; i++) { est[i] = (i < 20) ? 5500 : 4000; sd[i] = 100; } + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + CHECK(tr[19] > 0.3 && fin.lambda == 0.0); + for (int i = 20; i < N; i++) CHECK(tr[i] <= tr[i - 1] && tr[i] >= 0.0); } + /* 3. two competing constraints: memory binding, latency slack; each priced independently */ + { RxDualController ctl; RxDualResource rm = fx_res(1, RX_DUAL_UNIT_BYTES, SCALE), rl = fx_res(2, RX_DUAL_UNIT_BYTES, SCALE); + RxDualConstraintState fm, fl; double gm, gl; + memset(&ctl, 0, sizeof ctl); ctl.eta = 0.2; ctl.rho = 0.1; ctl.k_sigma = 1.0; ctl.max_age = 4; ctl.cadence = 1; ctl.n = 2; + ctl.resource_id[0] = 1; ctl.resource_id[1] = 2; ctl.lambda_max[0] = 5.0; ctl.lambda_max[1] = 5.0; + for (int i = 0; i < N; i++) { est[i] = 6000; sd[i] = 50; } + CHECK_ST(run(&ctl, &rm, est, sd, N, &fm, tr), RX_DUAL_OK); + gm = dual_ref_gradient(6000, BUDGET, SCALE, 50, 1.0); + CHECK(fabs(tr[N - 1] - dual_ref_closed_form(0.0, gm, 0.2, 0.1, N)) < 1e-9); + for (int i = 0; i < N; i++) { est[i] = 4900; sd[i] = 50; } + CHECK_ST(run(&ctl, &rl, est, sd, N, &fl, tr), RX_DUAL_OK); + gl = dual_ref_gradient(4900, BUDGET, SCALE, 50, 1.0); + CHECK(gl < 0.0 && fl.lambda == 0.0 && fm.lambda > 1.0); } + /* 4. inside the deadband: estimate 5100, sd 100, k 2 -> band 0.2 >= pressure 0.1: no movement, ever */ + { RxDualController ctl = fx_ctl(1, 0.5, 0.0, 2.0, 10.0, 4); + for (int i = 0; i < N; i++) { est[i] = 5100; sd[i] = 100; } + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + for (int i = 0; i < N; i++) CHECK(tr[i] == 0.0); } + /* 5. clip: eta 1, rho 0, pressure 2 -> hits lambda_max 3 at step 2 and stays */ + { RxDualController ctl = fx_ctl(1, 1.0, 0.0, 0.0, 3.0, 4); + for (int i = 0; i < N; i++) { est[i] = 7000; sd[i] = 0; } + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + CHECK(tr[0] == 2.0 && tr[1] == 3.0 && tr[N - 1] == 3.0); } + /* 6. zero eta: never moves; 7. rho > 0 forgets scarcity after pressure disappears (inside band) */ + { RxDualController ctl = fx_ctl(1, 0.0, 0.1, 2.0, 10.0, 4); + for (int i = 0; i < N; i++) { est[i] = 9000; sd[i] = 0; } + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + for (int i = 0; i < N; i++) CHECK(tr[i] == 0.0); } + { RxDualController ctl = fx_ctl(1, 0.5, 0.1, 2.0, 10.0, 4); + for (int i = 0; i < N; i++) { est[i] = (i < 10) ? 7000 : 5000; sd[i] = 100; } + CHECK_ST(run(&ctl, &res, est, sd, N, &fin, tr), RX_DUAL_OK); + CHECK(tr[9] > 1.0); + for (int i = 10; i < N; i++) CHECK(fabs(tr[i] - tr[9] * pow(0.9, (double)(i - 9))) < 1e-9); + CHECK(fin.lambda < 0.01 * tr[9]); } + /* 8. determinism: same inputs -> byte-identical records */ + { RxDualController ctl = fx_ctl(1, 0.1, 0.05, 2.0, 10.0, 4); RxDualConstraintState a, b; uint8_t ea[4096], eb[4096]; size_t la, lb; + for (int i = 0; i < N; i++) { est[i] = 5300 + 200 * sin(i * 0.3); sd[i] = 80; } + CHECK_ST(run(&ctl, &res, est, sd, N, &a, NULL), RX_DUAL_OK); + CHECK_ST(run(&ctl, &res, est, sd, N, &b, NULL), RX_DUAL_OK); + CHECK_ST(rx_dual_encode_constraint(&a, ea, sizeof ea, &la), RX_DUAL_OK); + CHECK_ST(rx_dual_encode_constraint(&b, eb, sizeof eb, &lb), RX_DUAL_OK); + CHECK(la == lb && memcmp(ea, eb, la) == 0 && a.tick == N - 1); } +} + +/* ---- held states and structural refusals ---- */ +static void test_states_and_refusals(void) +{ + RxDualController ctl = fx_ctl(1, 0.1, 0.05, 2.0, 10.0, 4); + RxDualResource res = fx_res(1, RX_DUAL_UNIT_BYTES, SCALE); + RxDualInput in = fx_input(5500, 100, 1, 1); + RxDualConstraintState s0, s1, s2; RxDualDigest d0; + CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_SOFT, BUDGET, &BC, &in, &ctl, 1, &s0), RX_DUAL_OK); + CHECK(s0.tick == 0 && rx_dual_digest_is_zero(&s0.parent) && s0.lambda > 0.0 && s0.lambda_state == RX_DUAL_LAMBDA_FRESH); + CHECK_ST(rx_dual_digest_constraint(&s0, &d0), RX_DUAL_OK); + /* stale input: lambda, estimate, generation, evidence root held; parent/tick advance */ + in = fx_input(9000, 100, 2, 1); in.evidence_verified = 0; + CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); + CHECK(s1.lambda_state == RX_DUAL_LAMBDA_STALE && s1.lambda == s0.lambda && s1.estimate == s0.estimate && s1.generation == s0.generation); + CHECK(rx_dual_digest_eq(&s1.parent, &d0) && s1.tick == 1 && rx_dual_digest_eq(&s1.evidence_root, &s0.evidence_root)); + /* too old */ + in = fx_input(9000, 100, 2, 1); CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 7, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_STALE && s1.lambda == s0.lambda); + /* refused values: held, REFUSED */ + in = fx_input(NAN, 100, 2, 1); CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_REFUSED && s1.lambda == s0.lambda); + in = fx_input(9000, -1, 2, 1); CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_REFUSED); + in = fx_input(9000, 100, 5, 1); CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_REFUSED); /* future generation */ + /* frozen: regime change holds the price */ + in = fx_input(9000, 100, 2, 1); in.regime_change = 1; + CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_FROZEN && s1.lambda == s0.lambda); + /* uncalibrated: lambda moves but is marked; a later calibrated input is FRESH again */ + in = fx_input(9000, 100, 2, 0); + CHECK_ST(rx_dual_update(&s0, &res, &in, &ctl, 2, &s1), RX_DUAL_OK); CHECK(s1.lambda_state == RX_DUAL_LAMBDA_UNCALIBRATED && s1.lambda > s0.lambda); + in = fx_input(9000, 100, 3, 1); + CHECK_ST(rx_dual_update(&s1, &res, &in, &ctl, 3, &s2), RX_DUAL_OK); CHECK(s2.lambda_state == RX_DUAL_LAMBDA_FRESH && s2.tick == 2); + /* structural refusals: no record */ + in = fx_input(9000, 100, 2, 1); + { RxDualController m = ctl; m.eta = 0.2; CHECK_ST(rx_dual_update(&s0, &res, &in, &m, 2, &s1), RX_DUAL_ERR_CONTROLLER); } /* mutated parameters */ + { RxDualController m = ctl; m.resource_id[0] = 2; CHECK_ST(rx_dual_update(&s0, &res, &in, &m, 2, &s1), RX_DUAL_ERR_RESOURCE); } /* resource not priced */ + { RxDualResource r2 = res; r2.unit = RX_DUAL_UNIT_NS; CHECK_ST(rx_dual_update(&s0, &r2, &in, &ctl, 2, &s1), RX_DUAL_ERR_UNIT); } + { RxDualResource r2 = res; r2.resource_id = 3; CHECK_ST(rx_dual_update(&s0, &r2, &in, &ctl, 2, &s1), RX_DUAL_ERR_RESOURCE); } + { RxDualResource r2 = res; r2.scale = 0.0; CHECK_ST(rx_dual_update(&s0, &r2, &in, &ctl, 2, &s1), RX_DUAL_ERR_SCALE); } + { RxDualResource r2 = res; r2.scale = -1.0; CHECK_ST(rx_dual_update(&s0, &r2, &in, &ctl, 2, &s1), RX_DUAL_ERR_SCALE); } + { RxDualInput u = in; u.unit = RX_DUAL_UNIT_NS; CHECK_ST(rx_dual_update(&s0, &res, &u, &ctl, 2, &s1), RX_DUAL_ERR_UNIT); } /* unit mismatch */ + { RxDualConstraintState bad = s0; bad.cls = RX_DUAL_CLASS_INVARIANT; CHECK_ST(rx_dual_update(&bad, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_CLASS); } + { RxDualConstraintState bad = s0; bad.lambda = 11.0; CHECK_ST(rx_dual_update(&bad, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_RANGE); } /* above max */ + { RxDualConstraintState bad = s0; bad.lambda = -1.0; CHECK_ST(rx_dual_update(&bad, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_RANGE); } + { RxDualConstraintState bad = s0; bad.parent = fx_dig(0x01); CHECK_ST(rx_dual_update(&bad, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_DIGEST); } /* malformed parent */ + { RxDualConstraintState bad = s0; memset(&bad.controller_id, 0, 32); CHECK_ST(rx_dual_update(&bad, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_DIGEST); } + CHECK_ST(rx_dual_update(NULL, &res, &in, &ctl, 2, &s1), RX_DUAL_ERR_NULL); + CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_INVARIANT, BUDGET, &BC, &in, &ctl, 1, &s1), RX_DUAL_ERR_CLASS); + CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_UNDECLARED, BUDGET, &BC, &in, &ctl, 1, &s1), RX_DUAL_ERR_CLASS); + CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_SOFT, INFINITY, &BC, &in, &ctl, 1, &s1), RX_DUAL_ERR_NONFINITE); + { RxDualDigest z = fx_dig(0); CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_SOFT, BUDGET, &z, &in, &ctl, 1, &s1), RX_DUAL_ERR_DIGEST); } + { RxDualInput u = in; u.estimate = NAN; CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_SOFT, BUDGET, &BC, &u, &ctl, 1, &s1), RX_DUAL_ERR_NONFINITE); } + /* CAPACITY: diagnostic price computed; class preserved */ + CHECK_ST(rx_dual_init_state(&res, RX_DUAL_CLASS_CAPACITY, BUDGET, &BC, &in, &ctl, 2, &s1), RX_DUAL_OK); + CHECK(s1.cls == RX_DUAL_CLASS_CAPACITY && s1.lambda > 0.0); + /* step function edge cases */ + { double o; CHECK_ST(rx_dual_step_lambda(0.5, INFINITY, 1, BUDGET, SCALE, &ctl, 10, &o), RX_DUAL_ERR_NONFINITE); + CHECK_ST(rx_dual_step_lambda(0.5, -INFINITY, 1, BUDGET, SCALE, &ctl, 10, &o), RX_DUAL_ERR_NONFINITE); + CHECK_ST(rx_dual_step_lambda(0.5, 1, 1, BUDGET, 0.0, &ctl, 10, &o), RX_DUAL_ERR_SCALE); + CHECK_ST(rx_dual_step_lambda(0.5, 1, 1, BUDGET, -1.0, &ctl, 10, &o), RX_DUAL_ERR_SCALE); + CHECK_ST(rx_dual_step_lambda(-0.5, 1, 1, BUDGET, SCALE, &ctl, 10, &o), RX_DUAL_ERR_RANGE); + CHECK_ST(rx_dual_step_lambda(0.5, 1, -1, BUDGET, SCALE, &ctl, 10, &o), RX_DUAL_ERR_RANGE); + CHECK_ST(rx_dual_step_lambda(11, 1, 1, BUDGET, SCALE, &ctl, 10, &o), RX_DUAL_ERR_RANGE); + CHECK_ST(rx_dual_step_lambda(0.5, 1e308, 1, -1e308, SCALE, &ctl, 10, &o), RX_DUAL_ERR_NONFINITE); } /* overflow refused, never clipped into range */ +} + +/* ---- property suite ---- */ +static void test_properties(void) +{ + for (int round = 0; round < PROP_ROUNDS; round++) { + RxDualController ctl = fx_ctl(1, rdbl(0, 2), rdbl(0, 1), rdbl(0, 4), rdbl(0.01, 50), 1 + rnd() % 8); + RxDualResource res = fx_res(1, RX_DUAL_UNIT_BYTES, rdbl(1e-3, 1e6)); + RxDualInput in = fx_input(rdbl(-1e6, 1e6), rdbl(0, 1e4), 1, 1); + RxDualConstraintState s, nx; RxDualStatus st; + double budget = rdbl(-1e6, 1e6), lmax = ctl.lambda_max[0]; + st = rx_dual_init_state(&res, RX_DUAL_CLASS_SOFT, budget, &BC, &in, &ctl, 1, &s); + CHECK_ST(st, RX_DUAL_OK); + for (uint64_t t = 2; t <= 40; t++) { + double g, want, prev = s.lambda; + in = fx_input(rdbl(-1e6, 1e6), rdbl(0, 1e4), t, (rnd() % 5) != 0); + if (rnd() % 7 == 0) in.evidence_verified = 0; + CHECK_ST(rx_dual_update(&s, &res, &in, &ctl, t, &nx), RX_DUAL_OK); + CHECK(isfinite(nx.lambda) && nx.lambda >= 0.0 && nx.lambda <= lmax && nx.tick == t - 1); + if (nx.lambda_state == RX_DUAL_LAMBDA_STALE) CHECK(nx.lambda == prev); + else { + g = dual_ref_gradient(in.estimate, budget, res.scale, in.uncertainty, ctl.k_sigma); + want = (1.0 - ctl.rho) * prev + ctl.eta * g; + if (want < 0) want = 0; + if (want > lmax) want = lmax; + CHECK(fabs(nx.lambda - want) <= 1e-9 * (1.0 + fabs(want))); + if (g == 0.0) CHECK(nx.lambda <= prev); /* inside deadband: only the leak can act */ + if (ctl.eta == 0.0) CHECK(nx.lambda <= prev); + } + s = nx; + } + } +} + +int main(void) +{ + BC = fx_dig(0x22); + test_analytic(); + test_states_and_refusals(); + test_properties(); + printf("test_dual_update: %d checks, %d failures: %s\n", g_checks, g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +} ```