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/512c7dc5e039e075 # 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#373 (code only) closed derived `512c7dc5e039e075` #373 Imported from GitHub aien-dev/omega-mv#373 (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 `790e1ef745f907d11fa95c18e88f3299c56881b6` · Head `f1bb56ee862d0975acdb660a090e6910b0d3d9e1` ### Fetch it A git bundle of the pull request's head, 82192 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/512c7dc5e039e075.bundle -o 512c7dc5e039e075.bundle git fetch 512c7dc5e039e075.bundle refs/pull/373/head ``` Raw bundle · 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 373 f1bb56ee862d0975acdb660a090e6910b0d3d9e1 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":373,"url":"https://github.com/aien-dev/omega-mv/pull/373","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:35Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 51c94f682..92fe51b82 100644 --- a/.crumb +++ b/.crumb @@ -46,74 +46,74 @@ "children": [ { "digest": "fb7cc6e608fdbe68a9735a1313285782b9717ff12bde17343f8ce635de3644f6", - "last_commit": "62b6a28", + "last_commit": "190ff891", "name": "calibration", "purpose": "Directory calibration. Purpose not yet described by a human." }, { "digest": "24d7c03a26a7ffe9b181b73585480b5801289accbdf63146edbc36cf3e1cf21f", - "last_commit": "6637b32", + "last_commit": "6637b32b", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { "digest": "536f7b8db9a92a1f586bad4379d47544a30d1b8e83c2d799c18e66cf8660c9ae", - "last_commit": "62b6a28", + "last_commit": "30bb116c", "name": "doctrine", "purpose": "Directory doctrine. Purpose not yet described by a human." }, { "digest": "d9fc697e5709ba2f0facb12f9a0ec8f4aa01474882c8d0311da037c00b8e7338", - "last_commit": "7843a74", + "last_commit": "7843a748", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, { "digest": "69cbb8ef13ccce47ccc21f159e95f1eac58679319e2cc25937065f95c4eb9207", - "last_commit": "62b6a28", + "last_commit": "ae8c7c54", "name": "polyglot", "purpose": "Directory polyglot. Purpose not yet described by a human." }, { - "digest": "3c5265c592dfea3520521c55f789a97014b081fd81b5e7bd8e4f685490ab0a01", - "last_commit": "3bb365b", + "digest": "a5b94f7b1e45a598d529101b45877c7315c73837788e3a5d1a0fac0935b6bd71", + "last_commit": "7874df24", "name": "research", "purpose": "Directory research. Purpose not yet described by a human." }, { "digest": "830ce7faaea9ae86190aa304fd8d7797881fbaca9d14fc39a327d202712f73fb", - "last_commit": "9e168fc", + "last_commit": "9e168fc8", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { "digest": "c06c116644765d66e2c7346e99179861cbb7bba7e8e932ff40b6c51983d90d01", - "last_commit": "22f7fb7", + "last_commit": "22f7fb72", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { "digest": "6632b2d7fadadd84a7188d5ddefc5029ba0c0492cd29672269dd2b198f787112", - "last_commit": "19f73c7", + "last_commit": "19f73c70", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { "digest": "acd42de9387a133f34b4b6afca962c82d340fba67c6a770a74852406769b4186", - "last_commit": "7683eaa", + "last_commit": "7683eaaa", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:f3c767c48e0f6951118a51fe813553053d6a7f99cf08d3764eb2aca676541e5b", - "compiled_at": "2026-10-10T03:25:07Z", + "children_root": "sha256:764ad5e1f01d6b92b78e9051c37150f937c4b73d0cc82380ad64e45f58277147", + "compiled_at": "2026-10-10T03:57:59Z", "compiler": "crumb-compile/1", - "digest": "sha256:3d32abfc784c29969348ec0571ffa8e3ee5c075f0dd6d38a644b3812d02c4acc", + "digest": "sha256:43e0faa75cc73967c2bd18d3deb774f6a7e121b0eea884f2f62d7a042aa62d1d", "evidence_files": 5533, "evidence_root": "sha256:8ca3b3e15e055b21c3e96200e3c76f26c3b139e6db06f5a94bc62c97f67157f5", - "files": 7794, - "generated_at_commit": "3bb365b850107cafd3938ec5100c56629c2055e6", - "source_tree": "sha256:b319ba36a9e330ba732855764dda71d2e047f0d7463e04d8b0d78899d1f62a13" + "files": 7807, + "generated_at_commit": "47e752ebdf1407e744109e0a97b0edc3631aef51", + "source_tree": "sha256:e0d264b198c59921b18afd26260950efe88f2210d0cd6ff5ab931d2833909dfe" }, "owner_lane": "", "provenance": { diff --git a/research/.crumb b/research/.crumb index 318e908ad..4d82a565b 100644 --- a/research/.crumb +++ b/research/.crumb @@ -21,27 +21,27 @@ "generated": { "children": [ { - "digest": "05f79da818f3feaf713351c4ca1871857f9c8f53d7e30c85f1a368c880b216ed", - "last_commit": "3bb365b", + "digest": "5bf3b79478c5af75db3590831b7d2b3e6d7533c171f586e709590ac61fd451e4", + "last_commit": "7874df24", "name": "atemporal", "purpose": "AT-0 Clock-Free Universe research program: relational (Page-Wootters) quantum models with no ext" }, { "digest": "7597531ca9a2cdce9e840dda55ce639f86c4237eda3f2e3d1d5b10c599966a33", - "last_commit": "62b6a28", + "last_commit": "458c57f5", "name": "dirac-oracle", "purpose": "Directory research/dirac-oracle. Purpose not yet described by a human." } ], - "children_root": "sha256:3a052883492cfa24539ee6c5909d40ea840407c82f1bdc223ce03bc914f23261", - "compiled_at": "2026-10-10T03:25:07Z", + "children_root": "sha256:3b10c7f4ec14c758f1cec14bf3c49700006285eda7bb043ad061206e70a0e6c8", + "compiled_at": "2026-10-10T03:57:59Z", "compiler": "crumb-compile/1", - "digest": "sha256:3c5265c592dfea3520521c55f789a97014b081fd81b5e7bd8e4f685490ab0a01", + "digest": "sha256:a5b94f7b1e45a598d529101b45877c7315c73837788e3a5d1a0fac0935b6bd71", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 395, - "generated_at_commit": "3bb365b850107cafd3938ec5100c56629c2055e6", - "source_tree": "sha256:ddbf9a9d76f9277c3016e42945e126cb0d822404ffbb5bf4663954efbb911596" + "files": 408, + "generated_at_commit": "47e752ebdf1407e744109e0a97b0edc3631aef51", + "source_tree": "sha256:73dbded4f5bb6dc3f4972a9f14d6df3cdaa710a0ac68de53840e97321880dda3" }, "owner_lane": "", "provenance": { diff --git a/research/atemporal/.crumb b/research/atemporal/.crumb index 7952d31c6..ecdf7d2a0 100644 --- a/research/atemporal/.crumb +++ b/research/atemporal/.crumb @@ -4,20 +4,20 @@ "children": [ { "digest": "b5ce051e4052120508499aeed3c249cbc4ef5c0e46b2386e8a8916c7bdb9f7f9", - "last_commit": "bacc4b6", + "last_commit": "bacc4b6b", "name": "at0", "purpose": "AT-0 V1: finite clock plus one qubit under the AT0_CASE_V1 / AT0_RESULT_V1 contracts" } ], "children_root": "sha256:f7bd1d7019a69ef57140cd019f86634f3cb80c1e31ca3063dfdf73ac9deef7c6", - "compiled_at": "2026-10-10T03:25:07Z", + "compiled_at": "2026-10-10T03:57:59Z", "compiler": "crumb-compile/1", - "digest": "sha256:05f79da818f3feaf713351c4ca1871857f9c8f53d7e30c85f1a368c880b216ed", + "digest": "sha256:5bf3b79478c5af75db3590831b7d2b3e6d7533c171f586e709590ac61fd451e4", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 249, - "generated_at_commit": "3bb365b850107cafd3938ec5100c56629c2055e6", - "source_tree": "sha256:0ec61582c7a335edd7ea619fa7fe0f7611507282de695d97a606b3f9c463f7ed" + "files": 262, + "generated_at_commit": "47e752ebdf1407e744109e0a97b0edc3631aef51", + "source_tree": "sha256:a2581a64a5578d6191586a5e3f4150fa71ca4d124bcf0da45eef1cf00fd38249" } }, "name": "atemporal", diff --git a/research/atemporal/at1/model/.gitignore b/research/atemporal/at1/model/.gitignore new file mode 100644 index 000000000..567609b12 --- /dev/null +++ b/research/atemporal/at1/model/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/research/atemporal/at1/model/Makefile b/research/atemporal/at1/model/Makefile new file mode 100644 index 000000000..6138456d0 --- /dev/null +++ b/research/atemporal/at1/model/Makefile @@ -0,0 +1,36 @@ +# AT-1 candidate engine (Agent 3). POSIX make: works with GNU Make 3.81 (macOS) and later. +# Only cc, libc and libm. Override the compiler with: make CC=clang +CC = cc +CFLAGS = -std=c11 -O2 -ffp-contract=off -Wall -Wextra -Werror -pedantic +SANFLAGS = -std=c11 -O1 -g -ffp-contract=off -Wall -Wextra -Werror -pedantic -fno-omit-frame-pointer -fsanitize=address,undefined -fno-sanitize-recover=all +LDLIBS = -lm +SHA = ../../../../src +LIB = at1_bn.c at1_case.c at1_exact.c at1_numeric.c at1_result.c at1_io.c $(SHA)/sha256.c +HDR = at1_model.h $(SHA)/sha256.h + +all: build/at1-model build/test_model + +build/at1-model: $(LIB) at1_main.c $(HDR) + mkdir -p build + $(CC) $(CFLAGS) -I$(SHA) -o build/at1-model $(LIB) at1_main.c $(LDLIBS) + +build/test_model: $(LIB) tests/test_model.c $(HDR) + mkdir -p build + $(CC) $(CFLAGS) -I$(SHA) -I. -o build/test_model $(LIB) tests/test_model.c $(LDLIBS) + +test: all + ./build/test_model tests/cases build/at1-model + +# Sanitizer run, only where the compiler supports the flags (probed first; skipped otherwise). +asan: + mkdir -p build + @if echo 'int main(void){return 0;}' > build/probe.c && $(CC) $(SANFLAGS) -o build/probe build/probe.c 2>/dev/null && ./build/probe; then \ + $(CC) $(SANFLAGS) -I$(SHA) -o build/at1-model-asan $(LIB) at1_main.c $(LDLIBS) && \ + $(CC) $(SANFLAGS) -I$(SHA) -I. -o build/test_model-asan $(LIB) tests/test_model.c $(LDLIBS) && \ + ASAN_OPTIONS=detect_leaks=1 ./build/test_model-asan tests/cases build/at1-model-asan; \ + else echo "asan: -fsanitize=address,undefined not supported by $(CC) here; skipped"; fi + +clean: + rm -rf build + +.PHONY: all test asan clean diff --git a/research/atemporal/at1/model/README.md b/research/atemporal/at1/model/README.md new file mode 100644 index 000000000..e7514d9e0 --- /dev/null +++ b/research/atemporal/at1/model/README.md @@ -0,0 +1,178 @@ +# AT-1 candidate engine (Agent 3) + +The candidate relational quantum engine for AT-1, tracked on aien-dev/omega#371. It reads one `AT1_CASE_V1` case, validates it, builds the literal constraint matrix `H_total = H_C (x) I_S + I_C (x) H_S + V`, finds its exact nullspace, applies the covariant clock POVM and writes one `AT1_RESULT_V1` result. + +Portable C11, libc and libm only (plus the repository's own `src/sha256.c`). No Python, no clock, no randomness, no threads, no network. A PASS from this engine means conformance with the frozen contracts and `AT1_SPEC.md`; it says nothing about physics. + +Contracts (aien-architecture `docs/plans/atemporal`, main `ea91d7c`): `AT1_CASE_V1.md` (sha256 `e62018d8...`), `AT1_RESULT_V1.md` (sha256 `3e6efd7e...`), `AT0_RESULT_V2.md` sections 2, 4, 5, 7 (sha256 `bd0f9eb8...`), `AT1_SPEC.md` (merged at `81047f5`), charter readings (c), (d), (e). + +## Build and run + +``` +make # build/at1-model and build/test_model +make test # every test below; exit status 0 only if all pass +make asan # the same tests under -fsanitize=address,undefined, if the compiler supports it +make CC=clang test # another compiler +``` + +The Makefile is plain POSIX make (works with GNU Make 3.81 on macOS). Flags: `-std=c11 -O2 -ffp-contract=off -Wall -Wextra -Werror -pedantic`. `-ffp-contract=off` keeps compilers from fusing multiply-adds, so gcc and clang round the same way. Without make: + +``` +cc -std=c11 -O2 -ffp-contract=off -I../../../../src -o at1-model \ + at1_bn.c at1_case.c at1_exact.c at1_numeric.c at1_result.c at1_io.c ../../../../src/sha256.c at1_main.c -lm +``` + +### Command line + +``` +at1-model result [--reversed] +at1-model values [--reversed] +``` + +- `result` writes the complete `AT1_RESULT_V1` file to standard output. + - The `reference_label`, `reference_clock_probability`, `reference_ideal` and `reference_interacting` lines are copied verbatim from the oracle record (charter reading (c)): every line whose key is one of those four, in the contract order. If the record has a `begin values` block, only lines inside it count. + - `case_id` / `acceptance_id` lines in the record must match the case. Count, order, index, label, axis, sign and token grammar are checked. + - The placement of `undefined` is checked against section 1: `reference_ideal` is never `undefined`; the six `reference_interacting` lines of a label are `undefined` exactly when its `reference_label` is not `DEFINED`; `reference_clock_probability` is `undefined` only in the trivial shape (all labels at once, every `reference_label` `UNDEFINED`); and every written `reference_label` must follow the status rule applied to its own `reference_clock_probability` value and bound. A record that breaks any of these is refused (exit 1), so a blanked-out record can never reach the judge. + - `none`, or an oracle record file that cannot be read, writes an `ERROR` result with `error_code ORACLE_UNAVAILABLE`, with the oracle provenance fields set to `none`. +- The case is parsed and validated before the oracle record and the provenance file are opened, so a refusal is never masked by a missing file. +- The provenance file holds the provenance lines in contract order, `source_repo` through `run_finished_utc`, then optional `artifact` lines. The runner supplies them, so the engine never reads a clock. The writer refuses `build_cc` starting with `oracle ` and `engine_sha256` equal to `oracle_sha256` (oracle-written records are never candidate results). +- `values` prints only the engine's own values lines. It is component output for debugging, not a contract file. +- `--reversed` evaluates the labels in reverse order. The output is bit-identical (test T8). +- Exit status: + - `0`: written. + - `2`: case refused. Exactly one line `AT1_CASE_REFUSED ` on stderr, nothing on stdout. + - `1`: engine error. One line `AT1_ENGINE_ERROR ` on stderr, nothing on stdout. Causes: an unreadable case or provenance file, a malformed or inconsistent oracle record, a malformed provenance file, or an engine limit hit while parsing. + - A failure after the case was accepted (an internal consistency check) is written as an `ERROR` result with `INTERNAL_ERROR`. + +## Method + +| File | Role | +|---|---| +| `at1_bn.c` | Arbitrary-precision integers, reduced rationals, Gaussian rationals; correctly rounded rational to binary64. | +| `at1_case.c` | `AT1_CASE_V1` parser. Rules 1 to 6 of section 4 in order, first failure wins: shape, then non-canonical forms (decided after the whole shape pass), versions, ranges, per-level rational spectrum (exact integer square roots of the reduced `\|h + v_j\|^2`), identities, acceptance codes. Readings (d) (version lines: key in step 1, value in step 2) and (e) (index tokens compared by value; `01` is `CASE_NONCANONICAL`) are applied. | +| `at1_exact.c` | Builds `H_total` term by term with explicit Kronecker products as a `2N x 2N` matrix of exact Gaussian rationals, assuming no block structure. Exact Gauss-Jordan elimination gives rank and kernel basis `B`. Checks `H_total B = 0` exactly. Forms `P_0 = B (B^dagger B)^-1 B^dagger` exactly. Computes `y_j = P_0 (\|E_j> (x) psi_0)` exactly. Exact zero test: supports of the nonzero `y_j` checked pairwise disjoint, then `Psi = 0` iff every `y_j = 0`. | +| `at1_numeric.c` | Binary64 physics (formulas below). | +| `at1_result.c` | Oracle splice, provenance checks, the 12 checks in exact rational arithmetic on the written tokens, the writer, `verdict_id`, `evidence_digest`. | +| `at1_io.c`, `at1_main.c` | File reading (the only file access) and the tool. | + +### The projected state + +The brief asks for the projection from the literal matrix, independent of the oracle's closed form. `AT1_SPEC.md` 8.4 item 3 warns that a *numerical* projector (eigen-decomposition with a threshold) loses accuracy like `1/delta_min` and fails P6. This engine does neither: + +- The kernel and `P_0` are exact, from the literal matrix. +- `Psi = P_0 (|t_r> (x) psi_0) = sum_j y_j` by linearity. Each entry of `Psi` is one clock amplitude times one exact `y_j` entry rounded once. +- So there is no `1/delta_min` loss (P6 measures like every other case) and no cancellation, even when `psi_0` is nearly orthogonal to the kernel (control C1). + +The closed forms of `AT1_SPEC.md` sections 2 to 4 appear only in the tests, as the expected answers. + +### Numerics + +| Quantity | How it is computed | +|---|---| +| Clock amplitudes `` | Phase `exp(-2 pi i E_j k tau)` from the turn count `E_j k tau`, reduced modulo 1 exactly in int64 (8.4 item 1), then `cos`, `sin` and `N^(-1/2)`. | +| `phi_k` | `(=` is verified exactly. Minimality is tested: one unit less in the seventh significant digit is below the binary64 bound. The label status rule (section 3) is decided exactly on the binary64 value and the bound as written. + +The judge compares the written tokens in exact rational arithmetic, never in floating point: +- Absolute form: PASS if `|v| + b <= tol`, FAIL if `|v| - b > tol`, else INDETERMINATE. Check 7 uses the signed form. +- Check 10 uses the exact rational `w/N` as the ideal clock marginal. +- Aggregation is per-input `NOT_EVALUATED`. Any INDETERMINATE check or label adds `PRECISION_INSUFFICIENT`. + +### Measured (this host only) + +Host: Linux aarch64 (DGX Spark), gcc 13.3.0, `make test`, 2026-10-09. Every number below comes from that run. + +| Quantity | Measured | Ratio to its own bound | +|---|---|---| +| `\|p(k) - exact\|`, all section 13 cases and controls | at most `1.78e-16` | at most `0.0129` | +| `\|pauli - exact\|`, all DEFINED labels | at most `3.89e-16` | at most `0.00973` | +| `constraint_residual` | at most `5.72e-17` | at most `0.007` | +| `povm_residual`, complete clocks | at most `4e-16` | | +| `povm_residual`, N4a and N4b | `1` and `sqrt(42)/4` within their bounds | | +| Large case N = 64, M = 256 | `sum p - 1 = 0`, `constraint_residual 0` (bound `8.17e-15`), `povm_residual 1.33e-15` (bound `2.31e-13`) | | +| Review reproducer N = 64, M = 1, `w = 1/3`, exact `sqrt(571)/3` | value `7.9652020968990138`, equal to the binary64 `sqrt(571.0)/3.0`; inside `[exact - bound, exact + bound]` in exact arithmetic, bound `3066656@20` | | + +For comparison, `AT1_SPEC.md` 8.4 item 5 reports `5.6e-16` from its scratch builds. The bounds are 75 to 150 times the largest errors seen. The whole test program runs in about 0.1 s on this host. + +## Tests (`make test`) + +`tests/test_model.c` currently passes 1390 assertions, 0 failures. Clean under `-fsanitize=address,undefined` with leak detection (`make asan`, gcc 13.3). + +1. **Worked example** `tests/cases/at1-kat-rotated-level-n4.case`, byte-identical to `AT1_CASE_V1` section 6. + - File sha256 `76e282fe...`, `case_id 890980a4...`, `acceptance_id d63246c3...`. + - The test generator reproduces the file byte for byte. + - Kernel dimension 2, `p = 5/28, 1/4, 9/28, 1/4`. +2. **Every `AT1_SPEC.md` section 13 class**, generated with recomputed identities: + - Positive: P1a, P1b, P1c, P2, P3, P3b, P4, P5, P6. + - N1 to N1f: the positive cases with target IDEAL, giving `SCHRODINGER_DEVIATION_EXCEEDED`. + - Negative: N2, N3, N4a, N4b, N5, N6. + - Each one checks: + - the kernel dimension; + - every `p(k)` and Pauli value against the exact table, `|value - exact| <= written bound`, in exact arithmetic; + - label status and the trivial-kernel rule; + - a full result written with an oracle record built from the exact tables; + - the 12-check vector, outcome, failure codes and `expectation_met YES` against section 13; + - line count, byte range, `verdict_id` and `evidence_digest`. +3. **Controls added here:** + - C1: `psi_0` nearly orthogonal to the only kernel vector. PASS, exact values met. + - C2: energies shifted by 1000, cancelled by `h0`. P2's table, PASS. + - C3: a kernel level with `|E_j + h0| = R_j = 1025/2` on a rotated axis. Check 4 INDETERMINATE, `PRECISION_INSUFFICIENT` (the declared limit below, shown working). +4. **Refusals:** 67 files with exact codes. + - R0 to R14 of section 13.5, including R2b, R2c, R3b, R5b, R6b, R12b. + - All 42 inherited AT-0 rows re-expressed on P2 (R01 to R39, R06b to R06d, CRLF, missing final LF, empty file). + - Readings (d) and (e): `OMEGA-AT0-CASE v1` gives `CASE_PARSE_ERROR`; `domain omega.at0.case.v1` gives `CASE_UNSUPPORTED_VERSION`; index `01` gives `CASE_NONCANONICAL`; index `x` or `5` gives `CASE_PARSE_ERROR`. + - A 5001-digit token is an engine limit error, not a refusal. +5. **Invariance (spec section 9.1)**, on P2 and P4: + - T4 phase times `i`; T5 scale times 2; T6 purity; + - T7 shift of `r` by one shifts the labels; + - T8 reversed order bit-identical; T9 second run bit-identical. +6. **Large case:** N = 64, M = 256, two kernel levels, full result PASS. +7. **Judge and tool rules:** + - Status disagreement gives check 12 FAIL; an INDETERMINATE reference label gives `PRECISION_INSUFFICIENT`. + - A wrong oracle marginal gives `INTERACTING_DEVIATION_EXCEEDED`; a wrong `reference_interacting` under IDEAL gives check 11 `ORACLE_DISAGREEMENT`; a `nonfinite` reference gives `NONFINITE_VALUE`. + - Malformed oracle records are rejected: missing line, wrong label, `-0.0`, foreign `case_id`. + - Refused provenance: `build_cc oracle ...`, equal engine and oracle digests, duplicate artifact path, bad timestamp. + - `ORACLE_UNAVAILABLE` and `INTERNAL_ERROR` result shapes. + - Through the CLI: output equals the library output, `--reversed`, `none`, refusal exit 2 with the exact stderr line, bad provenance exit 1 with empty stdout. + - Oracle `undefined` placement: one clock line undefined, a status that contradicts its own clock value, an all-`undefined` record with `DEFINED` labels, a status change without its lines, `reference_ideal` undefined, `reference_interacting` undefined on a `DEFINED` label: all refused. A consistent trivial-shape oracle record against a nontrivial engine is accepted and gives check 12 FAIL. +8. **Independent review findings** (46 assertions; 28 of them fail on the pre-review code, all pass now): + - The review reproducer above for the POVM bound (the pre-review code was 58 times over its bound). + - Minimal bound tokens: `1` is `1@0`, `0.25` is `25@2`, plus the minimality property on 12 values from `3e-41` to `123456789`. + - Label status rule at its exact boundaries (`p + b == tol` is `UNDEFINED`, `p - b == tol` is `INDETERMINATE`). + - Absolute-form boundary on check 10: `|d| + b == tol` is PASS; one ulp more is INDETERMINATE with `PRECISION_INSUFFICIENT`. + - An oracle record that is a full result file: reference-like lines outside its `begin values` block are ignored. + - Through the CLI: an unreadable oracle record gives `ERROR ORACLE_UNAVAILABLE` with exit 0; a refused case with unreadable oracle and provenance still exits 2 with its refusal line; an unreadable provenance file exits 1. + +## Declared limits + +- **`bound_kind ESTIMATED`, not RIGOROUS.** Cases with `min_bound_kind RIGOROUS` fail check 1 by design (N5). +- **Large matrix entries.** `constraint_residual` is evaluated in binary64. When `|H_total|` acting on `Psi` has row sums `Hpsi` above about 187 (where `48 eps Hpsi` reaches `1e-12`), its bound exceeds `tol_constraint_residual 1@12`, and check 4 is INDETERMINATE (`PRECISION_INSUFFICIENT`) even though the measured residual stays small. C3 (`Hpsi` near 1230) shows this. A shift common to `E_j` and `h0` does not count, because the matrix entries are exact sums (C2). +- **Small marginals.** Bounds on conditional probabilities grow like `1/sqrt(p(k))`. `AT1_SPEC.md` 8.3 keeps `p(k) >= 1e-3` in every case. +- **Engine limits.** Case, oracle and provenance files up to 1 MiB; numeric tokens up to 4096 digits (the contract's own limits are far below). Beyond these the tool exits 1 with `AT1_ENGINE_ERROR RESOURCE_LIMIT`, which is not a refusal code. +- **Exact arithmetic cost.** The exact elimination of the `2N x 2N` matrix is cheap at contract sizes (N = 64, M = 256 runs in milliseconds here). It was not timed beyond the contract limits. +- **ERROR results.** The labels are written `UNDEFINED`, the same reading as the trivial-kernel rule; the contract fixes values and bounds for `ERROR` but not the label status token. +- **Platforms.** Built and tested only on Linux aarch64 with gcc 13.3. Not yet built here with clang. macOS arm64 with Apple clang 17 and GNU Make 3.81 is the stated replication target: no GNU-make-4 features, no glibc-only calls, no Linux-only headers in the engine, no `long double`, digests computed in C. The sanitizer target probes the compiler first and skips if unsupported. Values may differ in the last bits across libm implementations (`cos`, `sin`); verdicts are designed not to (spec 8.3 margins). diff --git a/research/atemporal/at1/model/at1_bn.c b/research/atemporal/at1/model/at1_bn.c new file mode 100644 index 000000000..4bc4e7859 --- /dev/null +++ b/research/atemporal/at1/model/at1_bn.c @@ -0,0 +1,447 @@ +/* Exact arithmetic for the AT-1 engine: arbitrary-precision integers (32-bit limbs, Knuth + * algorithm D for division), reduced rationals and Gaussian rationals. Used for validation + * (rules 3 and 4 of AT1_CASE_V1 section 4 are decided exactly for every in-limit case, as + * section 2 requires), for the exact nullspace of the literal H_total, and for the exact + * verdict comparisons of AT0_RESULT_V2 section 4. Nothing here ever wraps around. */ +#include "at1_model.h" + +#include +#include +#include +#include + +void *at1_xmalloc(size_t n) +{ + void *p = malloc(n ? n : 1); + if (!p) { fputs("AT1_ENGINE_ERROR RESOURCE_LIMIT\n", stderr); exit(1); } + return p; +} +void *at1_xcalloc(size_t n, size_t sz) +{ + void *p = calloc(n ? n : 1, sz ? sz : 1); + if (!p) { fputs("AT1_ENGINE_ERROR RESOURCE_LIMIT\n", stderr); exit(1); } + return p; +} +void *at1_xrealloc(void *p, size_t n) +{ + void *q = realloc(p, n ? n : 1); + if (!q) { fputs("AT1_ENGINE_ERROR RESOURCE_LIMIT\n", stderr); exit(1); } + return q; +} + +/* ---- integers ------------------------------------------------------------------------------ */ +void bn_init(bn *a) { a->neg = 0; a->n = 0; a->cap = 0; a->d = NULL; } +void bn_free(bn *a) { free(a->d); bn_init(a); } + +static void bn_reserve(bn *a, int n) +{ + if (a->cap >= n) return; + int cap = a->cap ? a->cap : 4; + while (cap < n) cap *= 2; + a->d = at1_xrealloc(a->d, (size_t)cap * sizeof(uint32_t)); + a->cap = cap; +} +static void bn_trim(bn *a) +{ + while (a->n > 0 && a->d[a->n - 1] == 0) a->n--; + if (a->n == 0) a->neg = 0; +} +static void bn_swap(bn *a, bn *b) { bn t = *a; *a = *b; *b = t; } + +void bn_copy(bn *r, const bn *a) +{ + if (r == a) return; + bn_reserve(r, a->n); + if (a->n) memcpy(r->d, a->d, (size_t)a->n * sizeof(uint32_t)); + r->n = a->n; r->neg = a->neg; +} +void bn_set_u64(bn *r, uint64_t v) +{ + bn_reserve(r, 2); + r->d[0] = (uint32_t)v; r->d[1] = (uint32_t)(v >> 32); r->n = 2; r->neg = 0; + bn_trim(r); +} +void bn_set_i64(bn *r, int64_t v) +{ + uint64_t m = v < 0 ? (uint64_t)0 - (uint64_t)v : (uint64_t)v; + bn_set_u64(r, m); + r->neg = v < 0 && m != 0; +} +int bn_is_zero(const bn *a) { return a->n == 0; } +int bn_sign(const bn *a) { return a->n == 0 ? 0 : a->neg ? -1 : 1; } + +static int mag_cmp(const uint32_t *a, int an, const uint32_t *b, int bn_) +{ + if (an != bn_) return an < bn_ ? -1 : 1; + for (int i = an - 1; i >= 0; i--) if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1; + return 0; +} +int bn_cmp_abs(const bn *a, const bn *b) { return mag_cmp(a->d, a->n, b->d, b->n); } +int bn_cmp(const bn *a, const bn *b) +{ + int sa = bn_sign(a), sb = bn_sign(b); + if (sa != sb) return sa < sb ? -1 : 1; + int c = bn_cmp_abs(a, b); + return sa < 0 ? -c : c; +} + +/* r = |a| + |b| (magnitudes), sign set by caller */ +static void mag_add(bn *r, const bn *a, const bn *b) +{ + bn t; bn_init(&t); + int n = (a->n > b->n ? a->n : b->n) + 1; + bn_reserve(&t, n); + uint64_t c = 0; + for (int i = 0; i < n; i++) { + c += (i < a->n ? a->d[i] : 0u); + c += (i < b->n ? b->d[i] : 0u); + t.d[i] = (uint32_t)c; c >>= 32; + } + t.n = n; t.neg = 0; bn_trim(&t); + bn_swap(r, &t); bn_free(&t); +} +/* r = |a| - |b|, requires |a| >= |b| */ +static void mag_sub(bn *r, const bn *a, const bn *b) +{ + bn t; bn_init(&t); + bn_reserve(&t, a->n); + int64_t br = 0; + for (int i = 0; i < a->n; i++) { + int64_t x = (int64_t)a->d[i] - (i < b->n ? (int64_t)b->d[i] : 0) - br; + br = x < 0; + if (x < 0) x += (int64_t)1 << 32; + t.d[i] = (uint32_t)x; + } + t.n = a->n; t.neg = 0; bn_trim(&t); + bn_swap(r, &t); bn_free(&t); +} +void bn_add(bn *r, const bn *a, const bn *b) +{ + int an = a->neg, bneg = b->neg; + if (an == bneg) { mag_add(r, a, b); r->neg = an && r->n; return; } + int c = bn_cmp_abs(a, b); + if (c == 0) { r->n = 0; r->neg = 0; return; } + if (c > 0) { mag_sub(r, a, b); r->neg = an && r->n; } + else { mag_sub(r, b, a); r->neg = bneg && r->n; } +} +void bn_neg(bn *r, const bn *a) { bn_copy(r, a); if (r->n) r->neg = !r->neg; } +void bn_abs(bn *r, const bn *a) { bn_copy(r, a); r->neg = 0; } +void bn_sub(bn *r, const bn *a, const bn *b) +{ + bn nb; bn_init(&nb); bn_neg(&nb, b); + bn_add(r, a, &nb); + bn_free(&nb); +} +void bn_mul(bn *r, const bn *a, const bn *b) +{ + if (a->n == 0 || b->n == 0) { r->n = 0; r->neg = 0; return; } + bn t; bn_init(&t); + int n = a->n + b->n; + bn_reserve(&t, n); + memset(t.d, 0, (size_t)n * sizeof(uint32_t)); + for (int i = 0; i < a->n; i++) { + uint64_t c = 0, ai = a->d[i]; + for (int j = 0; j < b->n; j++) { + c += ai * b->d[j] + t.d[i + j]; + t.d[i + j] = (uint32_t)c; c >>= 32; + } + t.d[i + b->n] = (uint32_t)c; + } + t.n = n; t.neg = a->neg != b->neg; bn_trim(&t); + bn_swap(r, &t); bn_free(&t); +} + +static int clz32(uint32_t x) { int n = 0; if (!x) return 32; while (!(x & 0x80000000u)) { x <<= 1; n++; } return n; } + +/* Knuth TAOCP vol. 2, 4.3.1 algorithm D, on magnitudes; truncated signs applied after */ +void bn_divmod(bn *q, bn *rem, const bn *a, const bn *b) +{ + if (b->n == 0) { fputs("AT1_ENGINE_ERROR INTERNAL_ERROR division by zero\n", stderr); exit(1); } + int qneg = a->neg != b->neg, rneg = a->neg; + if (bn_cmp_abs(a, b) < 0) { + if (rem) { bn_copy(rem, a); } + if (q) { q->n = 0; q->neg = 0; } + return; + } + bn Q, R; bn_init(&Q); bn_init(&R); + if (b->n == 1) { + uint64_t d = b->d[0], r = 0; + bn_reserve(&Q, a->n); + for (int i = a->n - 1; i >= 0; i--) { + uint64_t cur = (r << 32) | a->d[i]; + Q.d[i] = (uint32_t)(cur / d); r = cur % d; + } + Q.n = a->n; bn_trim(&Q); + bn_set_u64(&R, r); + } else { + int s = clz32(b->d[b->n - 1]); + int n = b->n, m = a->n - b->n; + uint32_t *v = at1_xmalloc((size_t)n * sizeof(uint32_t)); + uint32_t *u = at1_xmalloc((size_t)(a->n + 1) * sizeof(uint32_t)); + for (int i = n - 1; i > 0; i--) v[i] = (b->d[i] << s) | (s ? (uint32_t)((uint64_t)b->d[i - 1] >> (32 - s)) : 0); + v[0] = b->d[0] << s; + u[a->n] = s ? (uint32_t)((uint64_t)a->d[a->n - 1] >> (32 - s)) : 0; + for (int i = a->n - 1; i > 0; i--) u[i] = (a->d[i] << s) | (s ? (uint32_t)((uint64_t)a->d[i - 1] >> (32 - s)) : 0); + u[0] = a->d[0] << s; + bn_reserve(&Q, m + 1); + for (int j = m; j >= 0; j--) { + uint64_t num = ((uint64_t)u[j + n] << 32) | u[j + n - 1]; + uint64_t qhat = num / v[n - 1], rhat = num % v[n - 1]; + while (qhat >= ((uint64_t)1 << 32) || qhat * v[n - 2] > ((rhat << 32) | u[j + n - 2])) { + qhat--; rhat += v[n - 1]; + if (rhat >= ((uint64_t)1 << 32)) break; + } + int64_t borrow = 0; uint64_t carry = 0; + for (int i = 0; i < n; i++) { + uint64_t p = qhat * v[i] + carry; + carry = p >> 32; + int64_t t = (int64_t)u[i + j] - (int64_t)(uint32_t)p - borrow; + borrow = t < 0; + u[i + j] = (uint32_t)(t + (borrow ? ((int64_t)1 << 32) : 0)); + } + int64_t t = (int64_t)u[j + n] - (int64_t)carry - borrow; + borrow = t < 0; + u[j + n] = (uint32_t)(t + (borrow ? ((int64_t)1 << 32) : 0)); + if (borrow) { + qhat--; + uint64_t c = 0; + for (int i = 0; i < n; i++) { + c += (uint64_t)u[i + j] + v[i]; + u[i + j] = (uint32_t)c; c >>= 32; + } + u[j + n] = (uint32_t)((uint64_t)u[j + n] + c); + } + Q.d[j] = (uint32_t)qhat; + } + Q.n = m + 1; bn_trim(&Q); + bn_reserve(&R, n); + for (int i = 0; i < n; i++) R.d[i] = (u[i] >> s) | (s ? (uint32_t)((uint64_t)u[i + 1] << (32 - s)) : 0); + R.n = n; bn_trim(&R); + free(u); free(v); + } + Q.neg = qneg && Q.n; R.neg = rneg && R.n; + if (q) bn_swap(q, &Q); + if (rem) bn_swap(rem, &R); + bn_free(&Q); bn_free(&R); +} + +void bn_gcd(bn *r, const bn *a, const bn *b) +{ + bn x, y, t; bn_init(&x); bn_init(&y); bn_init(&t); + bn_abs(&x, a); bn_abs(&y, b); + while (y.n) { bn_divmod(NULL, &t, &x, &y); bn_swap(&x, &y); bn_swap(&y, &t); } + bn_swap(r, &x); + bn_free(&x); bn_free(&y); bn_free(&t); +} + +void bn_shl(bn *r, const bn *a, unsigned bits) +{ + if (a->n == 0) { r->n = 0; r->neg = 0; return; } + unsigned ws = bits / 32, bs = bits % 32; + bn t; bn_init(&t); + int n = a->n + (int)ws + 1; + bn_reserve(&t, n); + memset(t.d, 0, (size_t)n * sizeof(uint32_t)); + for (int i = 0; i < a->n; i++) { + uint64_t x = (uint64_t)a->d[i] << bs; + t.d[i + (int)ws] |= (uint32_t)x; + t.d[i + (int)ws + 1] |= (uint32_t)(x >> 32); + } + t.n = n; t.neg = a->neg; bn_trim(&t); + bn_swap(r, &t); bn_free(&t); +} + +void bn_pow10(bn *r, unsigned k) +{ + bn ten; bn_init(&ten); bn_set_u64(&ten, 10); + bn_set_u64(r, 1); + for (unsigned i = 0; i < k; i++) bn_mul(r, r, &ten); + bn_free(&ten); +} + +int bn_bitlen(const bn *a) +{ + if (a->n == 0) return 0; + return 32 * (a->n - 1) + (32 - clz32(a->d[a->n - 1])); +} + +int bn_isqrt_exact(const bn *a, bn *root) +{ + if (a->neg) return 0; + if (a->n == 0) { root->n = 0; root->neg = 0; return 1; } + /* Newton from above: x0 = 2^ceil(bits/2) >= sqrt(a) */ + bn x, y, t, one, two; bn_init(&x); bn_init(&y); bn_init(&t); bn_init(&one); bn_init(&two); + bn_set_u64(&one, 1); bn_set_u64(&two, 2); + bn_shl(&x, &one, (unsigned)(bn_bitlen(a) + 1) / 2 + 1); + for (;;) { + bn_divmod(&t, NULL, a, &x); + bn_add(&y, &x, &t); + bn_divmod(&y, NULL, &y, &two); + if (bn_cmp(&y, &x) >= 0) break; + bn_swap(&x, &y); + } + bn_mul(&t, &x, &x); + int sq = bn_cmp(&t, a) == 0; + if (sq) bn_copy(root, &x); + bn_free(&x); bn_free(&y); bn_free(&t); bn_free(&one); bn_free(&two); + return sq; +} + +int bn_fits_i64(const bn *a, int64_t *out) +{ + if (a->n > 2) return 0; + uint64_t m = a->n == 0 ? 0 : a->n == 1 ? a->d[0] : ((uint64_t)a->d[1] << 32) | a->d[0]; + if (m > (uint64_t)INT64_MAX) return 0; + *out = a->neg ? -(int64_t)m : (int64_t)m; + return 1; +} + +int bn_from_digits(bn *r, const char *s, size_t len) +{ + if (len > AT1_TOKEN_DIGITS_MAX) return 0; + bn t, chunk, scale; bn_init(&t); bn_init(&chunk); bn_init(&scale); + size_t i = 0; + while (i < len) { + size_t take = len - i < 9 ? len - i : 9; + uint64_t v = 0, sc = 1; + for (size_t j = 0; j < take; j++) { v = v * 10 + (uint64_t)(s[i + j] - '0'); sc *= 10; } + bn_set_u64(&scale, sc); bn_set_u64(&chunk, v); + bn_mul(&t, &t, &scale); bn_add(&t, &t, &chunk); + i += take; + } + bn_swap(r, &t); + bn_free(&t); bn_free(&chunk); bn_free(&scale); + return 1; +} + +/* ---- rationals ------------------------------------------------------------------------------ */ +void bq_init(bq *a) { bn_init(&a->num); bn_init(&a->den); bn_set_u64(&a->den, 1); } +void bq_free(bq *a) { bn_free(&a->num); bn_free(&a->den); } +void bq_copy(bq *r, const bq *a) { bn_copy(&r->num, &a->num); bn_copy(&r->den, &a->den); } + +static void bq_reduce(bq *r) +{ + if (r->den.neg) { bn_neg(&r->den, &r->den); bn_neg(&r->num, &r->num); } + if (r->num.n == 0) { bn_set_u64(&r->den, 1); return; } + bn g; bn_init(&g); + bn_gcd(&g, &r->num, &r->den); + if (!(g.n == 1 && g.d[0] == 1)) { + bn_divmod(&r->num, NULL, &r->num, &g); + bn_divmod(&r->den, NULL, &r->den, &g); + } + bn_free(&g); +} +void bq_set_bn(bq *r, const bn *n, const bn *d) { bn_copy(&r->num, n); bn_copy(&r->den, d); bq_reduce(r); } +void bq_set_i64(bq *r, int64_t n, int64_t d) { bn_set_i64(&r->num, n); bn_set_i64(&r->den, d); bq_reduce(r); } +int bq_is_zero(const bq *a) { return a->num.n == 0; } +int bq_sign(const bq *a) { return bn_sign(&a->num); } +int bq_cmp(const bq *a, const bq *b) +{ + bn x, y; bn_init(&x); bn_init(&y); + bn_mul(&x, &a->num, &b->den); bn_mul(&y, &b->num, &a->den); + int c = bn_cmp(&x, &y); + bn_free(&x); bn_free(&y); + return c; +} +void bq_add(bq *r, const bq *a, const bq *b) +{ + bn x, y, d; bn_init(&x); bn_init(&y); bn_init(&d); + bn_mul(&x, &a->num, &b->den); bn_mul(&y, &b->num, &a->den); bn_mul(&d, &a->den, &b->den); + bn_add(&r->num, &x, &y); bn_swap(&r->den, &d); + bq_reduce(r); + bn_free(&x); bn_free(&y); bn_free(&d); +} +void bq_neg(bq *r, const bq *a) { bq_copy(r, a); bn_neg(&r->num, &r->num); } +void bq_abs(bq *r, const bq *a) { bq_copy(r, a); r->num.neg = 0; } +void bq_sub(bq *r, const bq *a, const bq *b) +{ + bq nb; bq_init(&nb); bq_neg(&nb, b); bq_add(r, a, &nb); bq_free(&nb); +} +void bq_mul(bq *r, const bq *a, const bq *b) +{ + bn x, d; bn_init(&x); bn_init(&d); + bn_mul(&x, &a->num, &b->num); bn_mul(&d, &a->den, &b->den); + bn_swap(&r->num, &x); bn_swap(&r->den, &d); + bq_reduce(r); + bn_free(&x); bn_free(&d); +} +void bq_div(bq *r, const bq *a, const bq *b) +{ + bn x, d; bn_init(&x); bn_init(&d); + bn_mul(&x, &a->num, &b->den); bn_mul(&d, &a->den, &b->num); + bn_swap(&r->num, &x); bn_swap(&r->den, &d); + bq_reduce(r); + bn_free(&x); bn_free(&d); +} + +double bq_to_double(const bq *a) +{ + if (a->num.n == 0) return 0.0; + /* q = floor(|num| 2^s / den) with 65..66 significant bits, sticky bit for the remainder, + * then one correctly rounded uint64 -> double conversion and an exact scaling */ + bn n, d, q, rem; bn_init(&n); bn_init(&d); bn_init(&q); bn_init(&rem); + bn_abs(&n, &a->num); bn_copy(&d, &a->den); + int s = 66 + bn_bitlen(&d) - bn_bitlen(&n); + if (s >= 0) bn_shl(&n, &n, (unsigned)s); else bn_shl(&d, &d, (unsigned)(-s)); + bn_divmod(&q, &rem, &n, &d); + int qb = bn_bitlen(&q), drop = qb - 63; /* keep 63 bits, fold the rest into sticky */ + uint64_t top = 0; int sticky = rem.n != 0; + for (int i = qb - 1; i >= 0; i--) { + int bit = (int)((q.d[i / 32] >> (i % 32)) & 1u); + if (i >= drop) top = (top << 1) | (uint64_t)bit; else if (bit) sticky = 1; + } + top = (top << 1) | (uint64_t)sticky; /* 64 bits: 63 significant + sticky */ + double r = ldexp((double)top, drop - 1 - s); + bn_free(&n); bn_free(&d); bn_free(&q); bn_free(&rem); + return a->num.neg ? -r : r; +} + +void bq_from_double(bq *r, double x) +{ + uint64_t bits; memcpy(&bits, &x, sizeof bits); + int neg = (int)(bits >> 63); + int e = (int)((bits >> 52) & 0x7ff); + uint64_t m = bits & (((uint64_t)1 << 52) - 1); + if (e == 0) e = 1; else m |= (uint64_t)1 << 52; + int p = e - 1075; /* x = m * 2^p */ + bn one; bn_init(&one); + bn_set_u64(&r->num, m); bn_set_u64(&r->den, 1); bn_set_u64(&one, 1); + if (p >= 0) bn_shl(&r->num, &r->num, (unsigned)p); else bn_shl(&r->den, &one, (unsigned)(-p)); + if (neg && r->num.n) r->num.neg = 1; + bq_reduce(r); + bn_free(&one); +} + +void bq_from_scaled(bq *r, const bn *n, unsigned k) +{ + bn d; bn_init(&d); bn_pow10(&d, k); + bq_set_bn(r, n, &d); + bn_free(&d); +} + +/* ---- Gaussian rationals -------------------------------------------------------------------- */ +void gq_init(gq *a) { bq_init(&a->re); bq_init(&a->im); } +void gq_free(gq *a) { bq_free(&a->re); bq_free(&a->im); } +void gq_copy(gq *r, const gq *a) { bq_copy(&r->re, &a->re); bq_copy(&r->im, &a->im); } +int gq_is_zero(const gq *a) { return bq_is_zero(&a->re) && bq_is_zero(&a->im); } +void gq_add(gq *r, const gq *a, const gq *b) { bq_add(&r->re, &a->re, &b->re); bq_add(&r->im, &a->im, &b->im); } +void gq_sub(gq *r, const gq *a, const gq *b) { bq_sub(&r->re, &a->re, &b->re); bq_sub(&r->im, &a->im, &b->im); } +void gq_conj(gq *r, const gq *a) { bq_copy(&r->re, &a->re); bq_neg(&r->im, &a->im); } +void gq_neg(gq *r, const gq *a) { bq_neg(&r->re, &a->re); bq_neg(&r->im, &a->im); } +void gq_mul(gq *r, const gq *a, const gq *b) +{ + bq t1, t2, re, im; bq_init(&t1); bq_init(&t2); bq_init(&re); bq_init(&im); + bq_mul(&t1, &a->re, &b->re); bq_mul(&t2, &a->im, &b->im); bq_sub(&re, &t1, &t2); + bq_mul(&t1, &a->re, &b->im); bq_mul(&t2, &a->im, &b->re); bq_add(&im, &t1, &t2); + bq_copy(&r->re, &re); bq_copy(&r->im, &im); + bq_free(&t1); bq_free(&t2); bq_free(&re); bq_free(&im); +} +void gq_div(gq *r, const gq *a, const gq *b) +{ + gq cb, num; bq n2, t; gq_init(&cb); gq_init(&num); bq_init(&n2); bq_init(&t); + gq_conj(&cb, b); + gq_mul(&num, a, &cb); + bq_mul(&n2, &b->re, &b->re); bq_mul(&t, &b->im, &b->im); bq_add(&n2, &n2, &t); + bq_div(&r->re, &num.re, &n2); bq_div(&r->im, &num.im, &n2); + gq_free(&cb); gq_free(&num); bq_free(&n2); bq_free(&t); +} diff --git a/research/atemporal/at1/model/at1_case.c b/research/atemporal/at1/model/at1_case.c new file mode 100644 index 000000000..1aaf315e5 --- /dev/null +++ b/research/atemporal/at1/model/at1_case.c @@ -0,0 +1,552 @@ +/* AT1_CASE_V1 codec: parse and validate a case in the order of AT1_CASE_V1 section 4, first + * failure wins: + * 1. shape and encodings: CASE_PARSE_ERROR for any shape failure anywhere in the file, then + * CASE_NONCANONICAL for a parsed but non-canonical token (decided after the whole shape pass); + * 2. values of the three version-bearing lines: CASE_UNSUPPORTED_VERSION; + * 3. ranges and fixed values: CASE_INVALID_PARAMETER; + * 4. rational spectrum per clock level: CASE_IRRATIONAL_SPECTRUM; + * 5. identities: CASE_ID_MISMATCH; + * 6. acceptance codes: CASE_INVALID_PARAMETER. + * Readings applied (AT1_CHARTER.md section 8 and the inherited AT-0 readings): + * - (d) the first token of each version-bearing line is its key (checked in step 1), the rest + * of the line is its value (checked in step 2); + * - (e) an index token (interaction_pauli, clock_label) is compared with its zero-based + * position by parsed integer value in the shape pass; canonical form is decided afterwards; + * - shape before range: count lines that disagree with their repeated block, fixed literals + * and enumeration tokens are shape errors; token limits are rule 3; + * - token parse classes follow the qualified AT-0 codec: a denominator below 1 (including a + * negative one) is non-canonical, a scaled decimal with a sign is non-canonical. + * Every exact decision uses at1_bn.c (no fixed-width arithmetic can overflow). */ +#include "at1_model.h" +#include "sha256.h" + +#include +#include + +const char *const at1_failure_codes[AT1_FAILURE_CODE_COUNT] = { + "BOUND_KIND_INSUFFICIENT", "CONDITIONAL_UNDEFINED", "CONSTRAINT_RESIDUAL_EXCEEDED", + "INTERACTING_DEVIATION_EXCEEDED", "NONFINITE_VALUE", "ORACLE_DISAGREEMENT", + "POVM_NORMALIZATION_EXCEEDED", "PRECISION_INSUFFICIENT", "PROBABILITY_OUT_OF_RANGE", + "PROBABILITY_SUM_EXCEEDED", "SCHRODINGER_DEVIATION_EXCEEDED", "TRIVIAL_PHYSICAL_STATE" +}; + +const char *at1_status_name(at1_status s) +{ + switch (s) { + case AT1_OK: return "OK"; + case AT1_CASE_PARSE_ERROR: return "CASE_PARSE_ERROR"; + case AT1_CASE_NONCANONICAL: return "CASE_NONCANONICAL"; + case AT1_CASE_UNSUPPORTED_VERSION: return "CASE_UNSUPPORTED_VERSION"; + case AT1_CASE_INVALID_PARAMETER: return "CASE_INVALID_PARAMETER"; + case AT1_CASE_IRRATIONAL_SPECTRUM: return "CASE_IRRATIONAL_SPECTRUM"; + case AT1_CASE_ID_MISMATCH: return "CASE_ID_MISMATCH"; + case AT1_ERR_RESOURCE: return "RESOURCE_LIMIT"; + case AT1_ERR_INTERNAL: return "INTERNAL_ERROR"; + case AT1_ERR_ARGUMENT: return "ARGUMENT"; + } + return "UNKNOWN"; +} + +/* ---- digests ------------------------------------------------------------------------------- */ +static void hex32(const uint8_t d[32], char out[65]) +{ + static const char hx[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = hx[d[i] >> 4]; out[2 * i + 1] = hx[d[i] & 15]; } + out[64] = 0; +} +void at1_tagged_sha256(const char *tag, const char *data, size_t len, char out[65]) +{ + sha256_ctx ctx; uint8_t d[32]; uint8_t zero = 0; + sha256_init(&ctx); + sha256_update(&ctx, (const uint8_t *)tag, strlen(tag)); + sha256_update(&ctx, &zero, 1); + sha256_update(&ctx, (const uint8_t *)data, len); + sha256_final(&ctx, d); + hex32(d, out); +} +void at1_sha256_hex(const uint8_t *data, size_t len, char out[65]) +{ + uint8_t d[32]; + sha256_hash(data, len, d); + hex32(d, out); +} + +/* ---- line table ---------------------------------------------------------------------------- */ +typedef struct { char **line; size_t *off; int count, pos; char *copy; } lines_t; + +static at1_status split_lines(const uint8_t *b, size_t len, lines_t *L) +{ + L->line = NULL; L->off = NULL; L->count = 0; L->pos = 0; L->copy = NULL; + if (len == 0 || b[len - 1] != '\n') return AT1_CASE_PARSE_ERROR; + for (size_t i = 0; i < len; i++) if (b[i] != '\n' && (b[i] < 0x20 || b[i] > 0x7E)) return AT1_CASE_PARSE_ERROR; + int n = 0; + for (size_t i = 0; i < len; i++) if (b[i] == '\n') n++; + L->copy = at1_xmalloc(len + 1); + memcpy(L->copy, b, len); L->copy[len] = 0; + L->line = at1_xmalloc((size_t)n * sizeof(char *)); + L->off = at1_xmalloc((size_t)(n + 1) * sizeof(size_t)); + size_t start = 0; + for (size_t i = 0; i < len; i++) { + if (b[i] != '\n') continue; + size_t ln = i - start; + if (ln == 0) return AT1_CASE_PARSE_ERROR; /* blank line */ + if (b[start] == ' ' || b[i - 1] == ' ') return AT1_CASE_PARSE_ERROR; /* leading/trailing space */ + for (size_t j = start + 1; j < i; j++) if (b[j] == ' ' && b[j - 1] == ' ') return AT1_CASE_PARSE_ERROR; + L->copy[i] = 0; + L->line[L->count] = L->copy + start; L->off[L->count] = start; L->count++; + start = i + 1; + } + L->off[L->count] = len; + return AT1_OK; +} +static void lines_free(lines_t *L) { free(L->line); free(L->off); free(L->copy); } +static const char *peek(const lines_t *L) { return L->pos < L->count ? L->line[L->pos] : NULL; } +static const char *take(lines_t *L) { return L->pos < L->count ? L->line[L->pos++] : NULL; } + +/* line " " -> rest, or NULL when the key differs or the line has no value */ +static const char *key_rest(const char *line, const char *key) +{ + size_t k = strlen(key); + if (!line || strncmp(line, key, k) != 0 || line[k] != ' ') return NULL; + return line + k + 1; +} +static int line_key_is(const char *line, const char *key) { return key_rest(line, key) != NULL; } + +/* ---- token grammar ------------------------------------------------------------------------- */ +static int is_digit(char c) { return c >= '0' && c <= '9'; } + +typedef struct { + int shape; /* a shape failure was seen (PARSE_ERROR) */ + int noncanonical; /* a parsed, non-canonical token was seen */ + int resource; /* a token beyond the engine's digit limit was seen */ + int over_limit; /* a rational token outside the section 2 limits (rule 3) */ + int scaled_k_over; /* a scaled decimal with k > 40 (rule 3) */ +} flags_t; + +/* integer token "-?[0-9]+": returns 0 shape failure, 1 parsed. *canon, *val (bn, exact). */ +static int parse_int_tok(const char *s, size_t len, int *canon, bn *val, flags_t *f) +{ + size_t i = 0; int neg = 0; + if (len == 0) return 0; + if (s[0] == '-') { neg = 1; i = 1; } + if (i == len) return 0; + for (size_t j = i; j < len; j++) if (!is_digit(s[j])) return 0; + *canon = !(s[i] == '0' && (len - i > 1 || neg)); + size_t z = i; + while (z < len - 1 && s[z] == '0') z++; /* value of the significant digits */ + if (!bn_from_digits(val, s + z, len - z)) { f->resource = 1; bn_set_u64(val, 0); return 1; } + if (neg && val->n) val->neg = 1; + return 1; +} + +/* small integer for counts and indices; saturates far above every limit */ +static int parse_small_int(const char *s, size_t len, long *out, flags_t *f) +{ + int canon; bn v; bn_init(&v); + if (!parse_int_tok(s, len, &canon, &v, f)) { bn_free(&v); return 0; } + int64_t x; + if (!bn_fits_i64(&v, &x) || x > 1000000000 || x < -1000000000) x = v.neg ? -1000000001 : 1000000001; + *out = (long)x; + if (!canon) f->noncanonical = 1; + bn_free(&v); + return 1; +} + +static int bn_within(const bn *a, int64_t lim) +{ + bn l; bn_init(&l); bn_set_i64(&l, lim); + int ok = bn_cmp_abs(a, &l) <= 0; + bn_free(&l); + return ok; +} + +/* rational "n/d": 0 on shape failure; sets flags for non-canonical and over-limit tokens */ +static int parse_rat_tok(const char *s, size_t len, bq *out, flags_t *f) +{ + const char *slash = memchr(s, '/', len); + if (!slash) return 0; + size_t ln = (size_t)(slash - s), ld = len - ln - 1; + int cn, cd; bn n, d, g; bn_init(&n); bn_init(&d); bn_init(&g); + int ok = parse_int_tok(s, ln, &cn, &n, f) && parse_int_tok(slash + 1, ld, &cd, &d, f); + if (!ok) { bn_free(&n); bn_free(&d); bn_free(&g); return 0; } + int canonical = cn && cd && bn_sign(&d) > 0; + if (canonical) { bn_gcd(&g, &n, &d); if (!(g.n == 1 && g.d[0] == 1)) canonical = 0; } + if (!canonical) f->noncanonical = 1; + if (!bn_within(&n, AT1_TOKEN_LIMIT) || !bn_within(&d, AT1_TOKEN_LIMIT) || bn_sign(&d) <= 0) f->over_limit = 1; + if (bn_sign(&d) > 0) bq_set_bn(out, &n, &d); else bq_set_i64(out, 0, 1); + bn_free(&n); bn_free(&d); bn_free(&g); + return 1; +} + +static int parse_crat_tok(const char *s, size_t len, gq *out, flags_t *f) +{ + if (len < 2 || s[0] != '(' || s[len - 1] != ')') return 0; + const char *semi = memchr(s, ';', len); + if (!semi) return 0; + size_t la = (size_t)(semi - s - 1), lb = len - 2 - la - 1; + if (memchr(semi + 1, ';', lb)) return 0; + return parse_rat_tok(s + 1, la, &out->re, f) && parse_rat_tok(semi + 1, lb, &out->im, f); +} + +static int parse_scaled_tok(const char *s, size_t len, at1_scaled *out, flags_t *f) +{ + const char *at = memchr(s, '@', len); + if (!at) return 0; + size_t ln = (size_t)(at - s), lk = len - ln - 1; + int cn, ck; bn n, k; bn_init(&n); bn_init(&k); + int ok = parse_int_tok(s, ln, &cn, &n, f) && parse_int_tok(at + 1, lk, &ck, &k, f); + if (!ok) { bn_free(&n); bn_free(&k); return 0; } + int canonical = cn && ck && bn_sign(&n) >= 0 && bn_sign(&k) >= 0; + int64_t kv; + if (!bn_fits_i64(&k, &kv) || kv > 1000) kv = 1000; + if (kv < 0) kv = 0; + if (canonical && bn_is_zero(&n) && kv != 0) canonical = 0; + if (canonical && !bn_is_zero(&n) && kv != 0) { + bn ten, r; bn_init(&ten); bn_init(&r); bn_set_u64(&ten, 10); + bn_divmod(NULL, &r, &n, &ten); + if (bn_is_zero(&r)) canonical = 0; + bn_free(&ten); bn_free(&r); + } + if (!canonical) f->noncanonical = 1; + if (kv > AT1_SCALED_K_MAX) f->scaled_k_over = 1; + bn_abs(&out->n, &n); out->k = (unsigned)kv; + bn_free(&n); bn_free(&k); + return 1; +} + +static int valid_label(const char *s) +{ + size_t n = strlen(s); + if (n < 1 || n > AT1_LABEL_LEN || !(s[0] >= 'a' && s[0] <= 'z')) return 0; + for (size_t i = 1; i < n; i++) + if (!((s[i] >= 'a' && s[i] <= 'z') || is_digit(s[i]) || s[i] == '_')) return 0; + return 1; +} +static int is_alnum(char c) { return is_digit(c) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } +static int valid_name(const char *s) +{ + size_t n = strlen(s); + if (n < 1 || n > AT1_NAME_LEN || !is_alnum(s[0])) return 0; + for (size_t i = 1; i < n; i++) if (!(is_alnum(s[i]) || s[i] == '_' || s[i] == '.' || s[i] == '-')) return 0; + return 1; +} +static int valid_digest(const char *s) +{ + if (strlen(s) != 64) return 0; + for (int i = 0; i < 64; i++) if (!(is_digit(s[i]) || (s[i] >= 'a' && s[i] <= 'f'))) return 0; + return 1; +} + +/* split "a,b,c" (no empty items); returns item count or -1 on shape failure; "none" is 0 items */ +static int split_list(const char *s, const char ***items, size_t **lens) +{ + *items = NULL; *lens = NULL; + if (strcmp(s, "none") == 0) return 0; + size_t n = 1; + for (const char *p = s; *p; p++) if (*p == ',') n++; + *items = at1_xmalloc(n * sizeof(char *)); + *lens = at1_xmalloc(n * sizeof(size_t)); + const char *p = s; size_t i = 0; + for (;;) { + const char *c = strchr(p, ','); + size_t l = c ? (size_t)(c - p) : strlen(p); + if (l == 0) { free(*items); free(*lens); *items = NULL; *lens = NULL; return -1; } + (*items)[i] = p; (*lens)[i] = l; i++; + if (!c) break; + p = c + 1; + } + return (int)n; +} + +/* ---- raw parse state ----------------------------------------------------------------------- */ +typedef struct { + const char *header_v, *domain_v, *contract_v; + long clock_dim, label_count; + int n_energies; bq *energies; + int n_coupling; bq (*coupling)[3]; + int n_labels; char (*labels)[AT1_LABEL_LEN + 1]; + const char **codes; size_t *code_lens; int n_codes; + int sem_begin, sem_end, acc_begin, acc_end; /* line indices */ +} raw_t; + +static void raw_free(raw_t *r) +{ + if (r->energies) { for (int i = 0; i < r->n_energies; i++) bq_free(&r->energies[i]); free(r->energies); } + if (r->coupling) { for (int i = 0; i < r->n_coupling; i++) for (int a = 0; a < 3; a++) bq_free(&r->coupling[i][a]); free(r->coupling); } + free(r->labels); free(r->codes); free(r->code_lens); +} + +static void case_init(at1_case *c) +{ + memset(c, 0, sizeof *c); + for (int j = 0; j < AT1_CLOCK_DIM_MAX; j++) { bq_init(&c->energies[j]); for (int a = 0; a < 3; a++) bq_init(&c->v[j][a]); } + bq_init(&c->h0); for (int a = 0; a < 3; a++) bq_init(&c->h[a]); + gq_init(&c->psi0[0]); gq_init(&c->psi0[1]); + bq_init(&c->tau); bq_init(&c->weight); + at1_scaled *t[5] = { &c->tol_constraint, &c->tol_povm, &c->tol_probability, &c->tol_zero, &c->tol_schrodinger }; + for (int i = 0; i < 5; i++) { bn_init(&t[i]->n); t[i]->k = 0; } + c->initialized = 1; +} + +void at1_case_free(at1_case *c) +{ + if (!c || !c->initialized) return; + for (int j = 0; j < AT1_CLOCK_DIM_MAX; j++) { bq_free(&c->energies[j]); for (int a = 0; a < 3; a++) bq_free(&c->v[j][a]); } + bq_free(&c->h0); for (int a = 0; a < 3; a++) bq_free(&c->h[a]); + gq_free(&c->psi0[0]); gq_free(&c->psi0[1]); + bq_free(&c->tau); bq_free(&c->weight); + at1_scaled *t[5] = { &c->tol_constraint, &c->tol_povm, &c->tol_probability, &c->tol_zero, &c->tol_schrodinger }; + for (int i = 0; i < 5; i++) bn_free(&t[i]->n); + free(c->semantic_text); free(c->acceptance_text); + memset(c, 0, sizeof *c); +} + +#define SHAPE() do { return AT1_CASE_PARSE_ERROR; } while (0) +#define FIXED(text) do { const char *l_ = take(L); if (!l_ || strcmp(l_, (text)) != 0) SHAPE(); } while (0) +#define KEYED(key, rest) do { rest = key_rest(take(L), (key)); if (!rest) SHAPE(); } while (0) +#define ONE_TOKEN(rest) do { if (strchr((rest), ' ')) SHAPE(); } while (0) + +static at1_status parse_shape(lines_t *L, at1_case *c, raw_t *r, flags_t *f) +{ + const char *rest; + /* version-bearing lines: key and placement here, value in step 2 (reading d) */ + KEYED("OMEGA-AT1-CASE", rest); r->header_v = rest; + KEYED("domain", rest); r->domain_v = rest; + KEYED("contract", rest); r->contract_v = rest; + KEYED("case_name", rest); + if (!valid_name(rest)) SHAPE(); + strcpy(c->name, rest); + r->sem_begin = L->pos; + FIXED("begin semantic"); + FIXED("model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG"); + FIXED("energy_unit DIMENSIONLESS_HBAR_1"); + KEYED("clock_dim", rest); ONE_TOKEN(rest); + if (!parse_small_int(rest, strlen(rest), &r->clock_dim, f)) SHAPE(); + KEYED("clock_energies", rest); ONE_TOKEN(rest); + { + const char **it; size_t *ln; + int n = split_list(rest, &it, &ln); + if (n < 0 || n != r->clock_dim) { free(it); free(ln); SHAPE(); } + r->energies = at1_xmalloc((size_t)(n ? n : 1) * sizeof(bq)); + for (int i = 0; i < n; i++) bq_init(&r->energies[i]); + r->n_energies = n; + for (int i = 0; i < n; i++) if (!parse_rat_tok(it[i], ln[i], &r->energies[i], f)) { free(it); free(ln); SHAPE(); } + free(it); free(ln); + } + FIXED("system_dim 2"); + KEYED("system_hamiltonian_pauli", rest); ONE_TOKEN(rest); + { + const char **it; size_t *ln; + int n = split_list(rest, &it, &ln); + if (n != 4) { free(it); free(ln); SHAPE(); } + int ok = parse_rat_tok(it[0], ln[0], &c->h0, f) && parse_rat_tok(it[1], ln[1], &c->h[0], f) && + parse_rat_tok(it[2], ln[2], &c->h[1], f) && parse_rat_tok(it[3], ln[3], &c->h[2], f); + free(it); free(ln); + if (!ok) SHAPE(); + } + FIXED("interaction CLOCK_DIAGONAL_PAULI"); + { + /* repeated block; clock_dim is its count line (AT1_CASE_V1 section 1) */ + int start = L->pos, n = 0; + while (peek(L) && line_key_is(peek(L), "interaction_pauli")) { L->pos++; n++; } + if (n != r->clock_dim) SHAPE(); + L->pos = start; + r->coupling = at1_xmalloc((size_t)(n ? n : 1) * sizeof *r->coupling); + for (int i = 0; i < n; i++) for (int a = 0; a < 3; a++) bq_init(&r->coupling[i][a]); + r->n_coupling = n; + for (int j = 0; j < n; j++) { + KEYED("interaction_pauli", rest); + const char *sp = strchr(rest, ' '); + if (!sp || strchr(sp + 1, ' ')) SHAPE(); + long idx; + if (!parse_small_int(rest, (size_t)(sp - rest), &idx, f) || idx != j) SHAPE(); /* reading e */ + const char **it; size_t *ln; + int m = split_list(sp + 1, &it, &ln); + if (m != 3) { free(it); free(ln); SHAPE(); } + int ok = 1; + for (int a = 0; a < 3; a++) ok = ok && parse_rat_tok(it[a], ln[a], &r->coupling[j][a], f); + free(it); free(ln); + if (!ok) SHAPE(); + } + } + FIXED("constraint SUM_HC_HS_V"); + FIXED("physical_state NULLSPACE_PROJECTION"); + KEYED("reference_clock_label", rest); + if (!valid_label(rest)) SHAPE(); + strcpy(c->ref_label, rest); + KEYED("reference_system_state", rest); ONE_TOKEN(rest); + { + const char **it; size_t *ln; + int n = split_list(rest, &it, &ln); + int ok = n == 2 && parse_crat_tok(it[0], ln[0], &c->psi0[0], f) && parse_crat_tok(it[1], ln[1], &c->psi0[1], f); + free(it); free(ln); + if (!ok) SHAPE(); + } + FIXED("clock_povm COVARIANT_DISCRETE"); + KEYED("povm_tau_turns", rest); ONE_TOKEN(rest); + if (!parse_rat_tok(rest, strlen(rest), &c->tau, f)) SHAPE(); + KEYED("povm_weight", rest); ONE_TOKEN(rest); + if (!parse_rat_tok(rest, strlen(rest), &c->weight, f)) SHAPE(); + KEYED("clock_label_count", rest); ONE_TOKEN(rest); + if (!parse_small_int(rest, strlen(rest), &r->label_count, f)) SHAPE(); + { + int start = L->pos, n = 0; + while (peek(L) && line_key_is(peek(L), "clock_label")) { L->pos++; n++; } + if (n != r->label_count) SHAPE(); + L->pos = start; + r->labels = at1_xmalloc((size_t)(n ? n : 1) * sizeof *r->labels); + r->n_labels = n; + for (int k = 0; k < n; k++) { + KEYED("clock_label", rest); + const char *sp = strchr(rest, ' '); + if (!sp || strchr(sp + 1, ' ')) SHAPE(); + long idx; + if (!parse_small_int(rest, (size_t)(sp - rest), &idx, f) || idx != k) SHAPE(); + if (!valid_label(sp + 1)) SHAPE(); + strcpy(r->labels[k], sp + 1); + } + } + FIXED("observables PAULI_X,PAULI_Y,PAULI_Z"); + r->sem_end = L->pos; + FIXED("end semantic"); + r->acc_begin = L->pos; + FIXED("begin acceptance"); + KEYED("control_kind", rest); + if (strcmp(rest, "POSITIVE") == 0) c->control_positive = 1; + else if (strcmp(rest, "NEGATIVE") == 0) c->control_positive = 0; + else SHAPE(); + KEYED("prediction_target", rest); + if (strcmp(rest, "IDEAL") == 0) c->target = AT1_TARGET_IDEAL; + else if (strcmp(rest, "INTERACTING") == 0) c->target = AT1_TARGET_INTERACTING; + else SHAPE(); + KEYED("expected_outcome", rest); + if (strcmp(rest, "PASS") == 0) c->expected_outcome = AT1_EXPECT_PASS; + else if (strcmp(rest, "FAIL") == 0) c->expected_outcome = AT1_EXPECT_FAIL; + else SHAPE(); + KEYED("expected_failure_codes", rest); ONE_TOKEN(rest); + r->n_codes = split_list(rest, &r->codes, &r->code_lens); + if (r->n_codes < 0) SHAPE(); + KEYED("min_bound_kind", rest); + if (strcmp(rest, "RIGOROUS") == 0) c->min_bound_kind = AT1_BOUND_RIGOROUS; + else if (strcmp(rest, "ESTIMATED") == 0) c->min_bound_kind = AT1_BOUND_ESTIMATED; + else if (strcmp(rest, "NONE") == 0) c->min_bound_kind = AT1_BOUND_NONE; + else SHAPE(); + static const char *tol_keys[5] = { "tol_constraint_residual", "tol_povm_residual", "tol_probability", + "tol_zero_probability", "tol_schrodinger" }; + at1_scaled *tols[5] = { &c->tol_constraint, &c->tol_povm, &c->tol_probability, &c->tol_zero, &c->tol_schrodinger }; + for (int i = 0; i < 5; i++) { + KEYED(tol_keys[i], rest); ONE_TOKEN(rest); + if (!parse_scaled_tok(rest, strlen(rest), tols[i], f)) SHAPE(); + } + r->acc_end = L->pos; + FIXED("end acceptance"); + KEYED("case_id", rest); + if (!valid_digest(rest)) SHAPE(); + strcpy(c->case_id, rest); + KEYED("acceptance_id", rest); + if (!valid_digest(rest)) SHAPE(); + strcpy(c->acceptance_id, rest); + FIXED("end"); + if (L->pos != L->count) SHAPE(); /* trailing lines */ + return AT1_OK; +} + +static at1_status check_parameters(at1_case *c, raw_t *r, const flags_t *f) +{ + if (f->over_limit || f->scaled_k_over) return AT1_CASE_INVALID_PARAMETER; + if (r->clock_dim < AT1_CLOCK_DIM_MIN || r->clock_dim > AT1_CLOCK_DIM_MAX) return AT1_CASE_INVALID_PARAMETER; + int N = (int)r->clock_dim; + for (int j = 1; j < N; j++) if (bq_cmp(&r->energies[j - 1], &r->energies[j]) >= 0) return AT1_CASE_INVALID_PARAMETER; + if (gq_is_zero(&c->psi0[0]) && gq_is_zero(&c->psi0[1])) return AT1_CASE_INVALID_PARAMETER; + if (bq_sign(&c->weight) <= 0 || bq_sign(&c->tau) <= 0) return AT1_CASE_INVALID_PARAMETER; + if (r->label_count < 1 || r->label_count > AT1_LABEL_MAX) return AT1_CASE_INVALID_PARAMETER; + int M = (int)r->label_count; + c->ref_index = -1; + for (int k = 0; k < M; k++) { + for (int l = 0; l < k; l++) if (strcmp(r->labels[k], r->labels[l]) == 0) return AT1_CASE_INVALID_PARAMETER; + if (strcmp(r->labels[k], c->ref_label) == 0) c->ref_index = k; + } + if (c->ref_index < 0) return AT1_CASE_INVALID_PARAMETER; + c->clock_dim = N; c->label_count = M; + for (int j = 0; j < N; j++) { + bq_copy(&c->energies[j], &r->energies[j]); + for (int a = 0; a < 3; a++) bq_copy(&c->v[j][a], &r->coupling[j][a]); + } + for (int k = 0; k < M; k++) strcpy(c->labels[k], r->labels[k]); + return AT1_OK; +} + +/* rule 4: |h + v_j|^2 is the square of a rational for every level, decided exactly */ +static at1_status check_spectrum(const at1_case *c) +{ + at1_status st = AT1_OK; + bq s, t, comp; bn root; bq_init(&s); bq_init(&t); bq_init(&comp); bn_init(&root); + for (int j = 0; j < c->clock_dim && st == AT1_OK; j++) { + bq_set_i64(&s, 0, 1); + for (int a = 0; a < 3; a++) { + bq_add(&comp, &c->h[a], &c->v[j][a]); + bq_mul(&t, &comp, &comp); + bq_add(&s, &s, &t); + } + /* s is reduced with den > 0, so it is a rational square iff num and den are squares */ + if (!bn_isqrt_exact(&s.num, &root) || !bn_isqrt_exact(&s.den, &root)) st = AT1_CASE_IRRATIONAL_SPECTRUM; + } + bq_free(&s); bq_free(&t); bq_free(&comp); bn_free(&root); + return st; +} + +static at1_status check_acceptance(at1_case *c, const raw_t *r) +{ + c->expected_codes = 0; + if (c->expected_outcome == AT1_EXPECT_PASS) return r->n_codes == 0 ? AT1_OK : AT1_CASE_INVALID_PARAMETER; + if (r->n_codes == 0) return AT1_CASE_INVALID_PARAMETER; + int prev = -1; + for (int i = 0; i < r->n_codes; i++) { + int idx = -1; + for (int j = 0; j < AT1_FAILURE_CODE_COUNT; j++) + if (strlen(at1_failure_codes[j]) == r->code_lens[i] && memcmp(r->codes[i], at1_failure_codes[j], r->code_lens[i]) == 0) { idx = j; break; } + if (idx < 0 || idx <= prev) return AT1_CASE_INVALID_PARAMETER; /* unknown, duplicate or unsorted */ + c->expected_codes |= 1u << idx; prev = idx; + } + return AT1_OK; +} + +at1_status at1_case_parse(const uint8_t *bytes, size_t len, at1_case *c) +{ + lines_t L; raw_t r; flags_t f; + memset(&r, 0, sizeof r); memset(&f, 0, sizeof f); + case_init(c); + at1_status st; + if (len > AT1_FILE_MAX) { st = AT1_ERR_RESOURCE; L.line = NULL; L.off = NULL; L.copy = NULL; goto done; } + st = split_lines(bytes, len, &L); + if (st == AT1_OK) st = parse_shape(&L, c, &r, &f); + if (st == AT1_OK && f.resource) st = AT1_ERR_RESOURCE; + if (st == AT1_OK && f.noncanonical) st = AT1_CASE_NONCANONICAL; /* still step 1 */ + if (st == AT1_OK) { /* step 2 */ + if (strcmp(r.header_v, "v1") != 0 || strcmp(r.domain_v, "omega.at1.case.v1") != 0 || + strcmp(r.contract_v, "AT1_CASE_V1") != 0) st = AT1_CASE_UNSUPPORTED_VERSION; + } + if (st == AT1_OK) st = check_parameters(c, &r, &f); /* step 3 */ + if (st == AT1_OK) st = check_spectrum(c); /* step 4 */ + if (st == AT1_OK) { /* step 5 */ + size_t s0 = L.off[r.sem_begin], s1 = L.off[r.sem_end + 1]; + size_t a0 = L.off[r.acc_begin], a1 = L.off[r.acc_end + 1]; + char cid[65], aid[65]; + at1_tagged_sha256("omega.at1.case.v1", (const char *)bytes + s0, s1 - s0, cid); + at1_tagged_sha256("omega.at1.acceptance.v1", (const char *)bytes + a0, a1 - a0, aid); + if (strcmp(cid, c->case_id) != 0 || strcmp(aid, c->acceptance_id) != 0) st = AT1_CASE_ID_MISMATCH; + else { + c->semantic_len = s1 - s0; c->semantic_text = at1_xmalloc(c->semantic_len + 1); + memcpy(c->semantic_text, bytes + s0, c->semantic_len); c->semantic_text[c->semantic_len] = 0; + c->acceptance_len = a1 - a0; c->acceptance_text = at1_xmalloc(c->acceptance_len + 1); + memcpy(c->acceptance_text, bytes + a0, c->acceptance_len); c->acceptance_text[c->acceptance_len] = 0; + } + } + if (st == AT1_OK) st = check_acceptance(c, &r); /* step 6 */ + if (st == AT1_OK) at1_sha256_hex(bytes, len, c->case_file_sha256); +done: + raw_free(&r); + lines_free(&L); + if (st != AT1_OK) at1_case_free(c); + return st; +} diff --git a/research/atemporal/at1/model/at1_exact.c b/research/atemporal/at1/model/at1_exact.c new file mode 100644 index 000000000..bc1bd5751 --- /dev/null +++ b/research/atemporal/at1/model/at1_exact.c @@ -0,0 +1,291 @@ +/* Exact kernel of the literal constraint matrix. + * + * H_total = H_C (x) I_S + I_C (x) H_S + sum_j |E_j> (x) psi_0) = N^(-1/2) sum_j w_j y_j with + * |w_j| = 1 and y_j = P_0 (|E_j> (x) psi_0) exact. When the nonzero y_j have pairwise disjoint + * supports, Psi = 0 exactly iff every y_j = 0. Disjointness is checked, not assumed; it always + * holds for a clock-diagonal V, and its failure is reported as an internal error. */ +#include "at1_model.h" + +#include +#include +#include + +typedef struct { int r, c; gq **e; } mat; /* row major; NULL entry = exact zero */ + +static mat mat_new(int r, int c) +{ + mat m = { r, c, at1_xcalloc((size_t)r * (size_t)c, sizeof(gq *)) }; + return m; +} +static void ent_free(gq *x) { if (x) { gq_free(x); free(x); } } +static void mat_free(mat *m) +{ + if (!m->e) return; + for (int i = 0; i < m->r * m->c; i++) ent_free(m->e[i]); + free(m->e); m->e = NULL; +} +static gq **at(mat *m, int i, int j) { return &m->e[i * m->c + j]; } +static const gq *get(const mat *m, int i, int j) { return m->e[i * m->c + j]; } + +/* *slot += x (x exact); keeps exact zeros as NULL */ +static void ent_add(gq **slot, const gq *x) +{ + if (!x || gq_is_zero(x)) return; + if (!*slot) { *slot = at1_xmalloc(sizeof(gq)); gq_init(*slot); gq_copy(*slot, x); return; } + gq_add(*slot, *slot, x); + if (gq_is_zero(*slot)) { ent_free(*slot); *slot = NULL; } +} +static void ent_set(gq **slot, const gq *x) { ent_free(*slot); *slot = NULL; ent_add(slot, x); } + +static void gq_set_rat(gq *g, const bq *re, const bq *im) +{ + if (re) bq_copy(&g->re, re); else bq_set_i64(&g->re, 0, 1); + if (im) bq_copy(&g->im, im); else bq_set_i64(&g->im, 0, 1); +} +static void gq_set_int(gq *g, int64_t re, int64_t im) { bq_set_i64(&g->re, re, 1); bq_set_i64(&g->im, im, 1); } + +/* C = A (x) B */ +static mat kron(const mat *A, const mat *B) +{ + mat C = mat_new(A->r * B->r, A->c * B->c); + gq t; gq_init(&t); + for (int i = 0; i < A->r; i++) for (int j = 0; j < A->c; j++) { + const gq *a = get(A, i, j); + if (!a) continue; + for (int k = 0; k < B->r; k++) for (int l = 0; l < B->c; l++) { + const gq *b = get(B, k, l); + if (!b) continue; + gq_mul(&t, a, b); + ent_add(at(&C, i * B->r + k, j * B->c + l), &t); + } + } + gq_free(&t); + return C; +} +/* A += B */ +static void mat_addto(mat *A, const mat *B) +{ + for (int i = 0; i < A->r * A->c; i++) if (B->e[i]) ent_add(&A->e[i], B->e[i]); +} +/* A * s (exact scalar) into a new matrix */ +static mat mat_scale(const mat *A, const gq *s) +{ + mat C = mat_new(A->r, A->c); + gq t; gq_init(&t); + for (int i = 0; i < A->r * A->c; i++) if (A->e[i]) { gq_mul(&t, A->e[i], s); ent_set(&C.e[i], &t); } + gq_free(&t); + return C; +} +static mat mat_mul(const mat *A, const mat *B) +{ + mat C = mat_new(A->r, B->c); + gq t; gq_init(&t); + for (int i = 0; i < A->r; i++) for (int k = 0; k < A->c; k++) { + const gq *a = get(A, i, k); + if (!a) continue; + for (int j = 0; j < B->c; j++) { + const gq *b = get(B, k, j); + if (!b) continue; + gq_mul(&t, a, b); + ent_add(at(&C, i, j), &t); + } + } + gq_free(&t); + return C; +} +static mat mat_adjoint(const mat *A) +{ + mat C = mat_new(A->c, A->r); + gq t; gq_init(&t); + for (int i = 0; i < A->r; i++) for (int j = 0; j < A->c; j++) { + const gq *a = get(A, i, j); + if (a) { gq_conj(&t, a); ent_set(at(&C, j, i), &t); } + } + gq_free(&t); + return C; +} +static void mat_set_int(mat *m, int i, int j, int64_t re, int64_t im) +{ + gq t; gq_init(&t); gq_set_int(&t, re, im); ent_set(at(m, i, j), &t); gq_free(&t); +} + +/* Gauss-Jordan to reduced row echelon form, in place. pivcol[r] = pivot column of row r. + * Returns the rank. Exact: a pivot is any exactly nonzero entry. */ +static int rref(mat *A, int *pivcol) +{ + int rank = 0; + gq inv, t, one; gq_init(&inv); gq_init(&t); gq_init(&one); gq_set_int(&one, 1, 0); + for (int c = 0; c < A->c && rank < A->r; c++) { + int p = -1; + for (int i = rank; i < A->r; i++) if (get(A, i, c)) { p = i; break; } + if (p < 0) continue; + if (p != rank) for (int j = 0; j < A->c; j++) { gq *s = *at(A, p, j); *at(A, p, j) = *at(A, rank, j); *at(A, rank, j) = s; } + gq_div(&inv, &one, get(A, rank, c)); + for (int j = 0; j < A->c; j++) if (get(A, rank, j)) gq_mul(*at(A, rank, j), get(A, rank, j), &inv); + for (int i = 0; i < A->r; i++) { + if (i == rank || !get(A, i, c)) continue; + gq f; gq_init(&f); gq_copy(&f, get(A, i, c)); + for (int j = 0; j < A->c; j++) { + const gq *rj = get(A, rank, j); + if (!rj) continue; + gq_mul(&t, &f, rj); gq_neg(&t, &t); + ent_add(at(A, i, j), &t); + } + gq_free(&f); + } + pivcol[rank++] = c; + } + gq_free(&inv); gq_free(&t); gq_free(&one); + return rank; +} + + +void at1_kernel_free(at1_kernel *k) +{ + free(k->h_re); free(k->h_im); free(k->y_re); free(k->y_im); free(k->owner); + memset(k, 0, sizeof *k); +} + +at1_status at1_kernel_build(const at1_case *c, at1_kernel *k) +{ + memset(k, 0, sizeof *k); + const int N = c->clock_dim, D = 2 * N; + at1_status st = AT1_OK; + gq t; gq_init(&t); + + /* single-factor matrices */ + mat HC = mat_new(N, N), IN = mat_new(N, N), I2 = mat_new(2, 2); + mat X = mat_new(2, 2), Y = mat_new(2, 2), Z = mat_new(2, 2); + for (int j = 0; j < N; j++) { gq_set_rat(&t, &c->energies[j], NULL); ent_set(at(&HC, j, j), &t); mat_set_int(&IN, j, j, 1, 0); } + mat_set_int(&I2, 0, 0, 1, 0); mat_set_int(&I2, 1, 1, 1, 0); + mat_set_int(&X, 0, 1, 1, 0); mat_set_int(&X, 1, 0, 1, 0); + mat_set_int(&Y, 0, 1, 0, -1); mat_set_int(&Y, 1, 0, 0, 1); + mat_set_int(&Z, 0, 0, 1, 0); mat_set_int(&Z, 1, 1, -1, 0); + const mat *pauli[3] = { &X, &Y, &Z }; + + /* H_S = h0 I + hx X + hy Y + hz Z */ + mat HS = mat_new(2, 2); + { gq_set_rat(&t, &c->h0, NULL); mat s = mat_scale(&I2, &t); mat_addto(&HS, &s); mat_free(&s); } + for (int a = 0; a < 3; a++) { gq_set_rat(&t, &c->h[a], NULL); mat s = mat_scale(pauli[a], &t); mat_addto(&HS, &s); mat_free(&s); } + + /* H_total = H_C (x) I + I (x) H_S + sum_j |E_j>v[j][a], NULL); mat s = mat_scale(pauli[a], &t); mat_addto(&Vj, &s); mat_free(&s); } + mat s = kron(&Pj, &Vj); mat_addto(&H, &s); + mat_free(&s); mat_free(&Pj); mat_free(&Vj); + } + + /* exact nullspace */ + mat R = mat_new(D, D); + for (int i = 0; i < D * D; i++) if (H.e[i]) ent_set(&R.e[i], H.e[i]); + int *pivcol = at1_xmalloc((size_t)D * sizeof(int)); + int rank = rref(&R, pivcol); + int dk = D - rank; + k->dim = D; k->kernel_dim = dk; + int *is_piv = at1_xcalloc((size_t)D, sizeof(int)); + for (int r = 0; r < rank; r++) is_piv[pivcol[r]] = 1; + mat B = mat_new(D, dk > 0 ? dk : 1); + { + int col = 0; + for (int f = 0; f < D; f++) { + if (is_piv[f]) continue; + mat_set_int(&B, f, col, 1, 0); + for (int r = 0; r < rank; r++) { + const gq *x = get(&R, r, f); + if (x) { gq_neg(&t, x); ent_set(at(&B, pivcol[r], col), &t); } + } + col++; + } + } + mat P0 = mat_new(D, D); + if (dk > 0) { + /* re-check H_total B = 0 exactly */ + mat HB = mat_mul(&H, &B); + for (int i = 0; i < HB.r * HB.c; i++) if (HB.e[i]) st = AT1_ERR_INTERNAL; + mat_free(&HB); + /* P_0 = B (B^dagger B)^(-1) B^dagger */ + mat Bd = mat_adjoint(&B); + mat G = mat_mul(&Bd, &B); + mat Aug = mat_new(dk, 2 * dk); + for (int i = 0; i < dk; i++) { + for (int j = 0; j < dk; j++) if (get(&G, i, j)) ent_set(at(&Aug, i, j), get(&G, i, j)); + mat_set_int(&Aug, i, dk + i, 1, 0); + } + int *pc = at1_xmalloc((size_t)dk * sizeof(int)); + int gr = rref(&Aug, pc); + if (gr != dk) st = AT1_ERR_INTERNAL; /* Gram matrix of a basis is invertible */ + for (int r = 0; r < gr && st == AT1_OK; r++) if (pc[r] != r) st = AT1_ERR_INTERNAL; + free(pc); + mat Gi = mat_new(dk, dk); + for (int i = 0; i < dk; i++) for (int j = 0; j < dk; j++) if (get(&Aug, i, dk + j)) ent_set(at(&Gi, i, j), get(&Aug, i, dk + j)); + mat W = mat_mul(&B, &Gi); + mat_free(&P0); + P0 = mat_mul(&W, &Bd); + mat_free(&Bd); mat_free(&G); mat_free(&Aug); mat_free(&Gi); mat_free(&W); + } + + /* exact zero test and the number of clock levels carrying Psi */ + { + int *owner = at1_xmalloc((size_t)D * sizeof(int)); + for (int i = 0; i < D; i++) owner[i] = -1; + k->y_re = at1_xcalloc((size_t)D, sizeof(double)); k->y_im = at1_xcalloc((size_t)D, sizeof(double)); + int L = 0; + gq y, prod; gq_init(&y); gq_init(&prod); + for (int j = 0; j < N && st == AT1_OK; j++) { + int nonzero = 0; + for (int i = 0; i < D; i++) { + bq_set_i64(&y.re, 0, 1); bq_set_i64(&y.im, 0, 1); + for (int s = 0; s < 2; s++) { + const gq *p = get(&P0, i, 2 * j + s); + if (!p) continue; + gq_mul(&prod, p, &c->psi0[s]); + gq_add(&y, &y, &prod); + } + if (gq_is_zero(&y)) continue; + nonzero = 1; + if (owner[i] >= 0) st = AT1_ERR_INTERNAL; /* supports overlap: not clock-diagonal */ + owner[i] = j; + k->y_re[i] = bq_to_double(&y.re); k->y_im[i] = bq_to_double(&y.im); /* rounded once */ + } + L += nonzero; + } + gq_free(&y); gq_free(&prod); + k->owner = owner; + k->levels_in_psi = L; + k->psi_zero = (L == 0); + } + + /* binary64 copies, each entry correctly rounded from its exact value */ + k->h_re = at1_xcalloc((size_t)D * D, sizeof(double)); k->h_im = at1_xcalloc((size_t)D * D, sizeof(double)); + for (int i = 0; i < D * D; i++) { + if (H.e[i]) { k->h_re[i] = bq_to_double(&H.e[i]->re); k->h_im[i] = bq_to_double(&H.e[i]->im); } + } + /* hmax = max_i sum over columns l carrying Psi of |H_total[i,l]|: the row sums of |H| that act on + * Psi, which is what the rounding of H_total Psi_hat and the error of Psi are multiplied by */ + k->hmax = 0.0; + for (int i = 0; i < D; i++) { + double s = 0.0; + for (int l = 0; l < D; l++) if (k->owner[l] >= 0) s += hypot(k->h_re[i * D + l], k->h_im[i * D + l]); + if (s > k->hmax) k->hmax = s; + } + + free(pivcol); free(is_piv); + mat_free(&HC); mat_free(&IN); mat_free(&I2); mat_free(&X); mat_free(&Y); mat_free(&Z); + mat_free(&HS); mat_free(&H); mat_free(&R); mat_free(&B); mat_free(&P0); + gq_free(&t); + if (st != AT1_OK) at1_kernel_free(k); + return st; +} diff --git a/research/atemporal/at1/model/at1_io.c b/research/atemporal/at1/model/at1_io.c new file mode 100644 index 000000000..6a3a684ed --- /dev/null +++ b/research/atemporal/at1/model/at1_io.c @@ -0,0 +1,30 @@ +/* The only file-system access of the engine: read a whole file, up to AT1_FILE_MAX bytes. */ +#include "at1_model.h" + +#include +#include + +at1_status at1_read_file(const char *path, uint8_t **bytes, size_t *len) +{ + *bytes = NULL; *len = 0; + FILE *f = fopen(path, "rb"); + if (!f) return AT1_ERR_ARGUMENT; + size_t cap = 65536, n = 0; + uint8_t *b = at1_xmalloc(cap); + for (;;) { + if (n == cap) { + if (cap > AT1_FILE_MAX) break; + cap *= 2; + b = at1_xrealloc(b, cap); + } + size_t got = fread(b + n, 1, cap - n, f); + n += got; + if (got == 0) break; + } + int bad = ferror(f); + fclose(f); + if (bad) { free(b); return AT1_ERR_ARGUMENT; } + if (n > AT1_FILE_MAX) { free(b); return AT1_ERR_RESOURCE; } + *bytes = b; *len = n; + return AT1_OK; +} diff --git a/research/atemporal/at1/model/at1_main.c b/research/atemporal/at1/model/at1_main.c new file mode 100644 index 000000000..f7fb44aec --- /dev/null +++ b/research/atemporal/at1/model/at1_main.c @@ -0,0 +1,104 @@ +/* at1-model: command-line tool of the AT-1 candidate engine. + * + * at1-model result [--reversed] + * writes the complete AT1_RESULT_V1 file to standard output. The reference_* lines are + * spliced verbatim from the oracle record (charter reading c); "none", or an oracle record + * that cannot be read, writes an ERROR + * result with error_code ORACLE_UNAVAILABLE. The provenance file holds the provenance + * lines (source_repo .. run_finished_utc, then optional artifact lines) so that the + * engine itself never reads a clock. + * at1-model values [--reversed] + * writes the engine's own values lines only (component output, not a contract file). + * + * Exit status: 0 written; 2 case refused (one line "AT1_CASE_REFUSED " on stderr); + * 1 engine error (one line "AT1_ENGINE_ERROR " on stderr), nothing on stdout. */ +#include "at1_model.h" + +#include +#include +#include + +static int usage(void) +{ + fputs("usage: at1-model result [--reversed]\n" + " at1-model values [--reversed]\n", stderr); + return 1; +} + +static int engine_error(const char *what) +{ + fprintf(stderr, "AT1_ENGINE_ERROR %s\n", what); + return 1; +} + +static int emit(char *out, size_t len) +{ + size_t w = fwrite(out, 1, len, stdout); + free(out); + if (w != len || fflush(stdout) != 0) return engine_error("write failed"); + return 0; +} + +int main(int argc, char **argv) +{ + if (argc < 3) return usage(); + int result_mode = strcmp(argv[1], "result") == 0; + if (!result_mode && strcmp(argv[1], "values") != 0) return usage(); + int fixed = result_mode ? 5 : 3, reversed = 0; + if (argc == fixed + 1 && strcmp(argv[fixed], "--reversed") == 0) reversed = 1; + else if (argc != fixed) return usage(); + + uint8_t *case_bytes = NULL, *oracle = NULL, *prov = NULL; + size_t case_len = 0, oracle_len = 0, prov_len = 0; + at1_status st = at1_read_file(argv[2], &case_bytes, &case_len); + if (st == AT1_ERR_RESOURCE) return engine_error("RESOURCE_LIMIT case file larger than 1 MiB"); + if (st != AT1_OK) return engine_error("cannot read case file"); + /* the case is validated before any other input is read, so a refusal is never masked */ + at1_case c; + st = at1_case_parse(case_bytes, case_len, &c); + free(case_bytes); + if (st >= AT1_CASE_PARSE_ERROR && st <= AT1_CASE_ID_MISMATCH) { + fprintf(stderr, "AT1_CASE_REFUSED %s\n", at1_status_name(st)); + return 2; + } + if (st != AT1_OK) return engine_error(st == AT1_ERR_RESOURCE ? "RESOURCE_LIMIT engine limit in case file" : "INTERNAL_ERROR case parse"); + + /* an oracle record that cannot be read is a run error (ORACLE_UNAVAILABLE), not a tool failure; + * the provenance is required to write any result at all */ + if (result_mode) { + st = at1_read_file(argv[4], &prov, &prov_len); + if (st != AT1_OK) { at1_case_free(&c); return engine_error("cannot read provenance file"); } + if (strcmp(argv[3], "none") != 0 && at1_read_file(argv[3], &oracle, &oracle_len) != AT1_OK) { + free(oracle); oracle = NULL; oracle_len = 0; /* written as ERROR ORACLE_UNAVAILABLE */ + } + } + + at1_kernel k; + at1_values *v = at1_xcalloc(1, sizeof *v); + const char *run_error = NULL; + st = at1_kernel_build(&c, &k); + if (st == AT1_OK) { + st = at1_compute(&c, &k, reversed, v); + at1_kernel_free(&k); + } + if (st == AT1_ERR_RESOURCE) run_error = "RESOURCE_LIMIT"; + else if (st != AT1_OK) run_error = "INTERNAL_ERROR"; + + char *out = NULL; size_t out_len = 0; char err[256]; + int rc; + if (!result_mode) { + if (run_error) rc = engine_error(run_error); + else { at1_values_write(&c, v, &out, &out_len); rc = emit(out, out_len); } + } else { + if (run_error) + st = at1_result_write_error(&c, run_error, (const char *)prov, prov_len, &out, &out_len, err, sizeof err); + else + st = at1_result_write(&c, v, (const char *)oracle, oracle_len, (const char *)prov, prov_len, &out, &out_len, err, sizeof err); + if (st == AT1_OK) rc = emit(out, out_len); + else if (st == AT1_ERR_ARGUMENT) rc = engine_error(err); + else rc = engine_error("INTERNAL_ERROR result writer"); + } + free(v); free(oracle); free(prov); + at1_case_free(&c); + return rc; +} diff --git a/research/atemporal/at1/model/at1_model.h b/research/atemporal/at1/model/at1_model.h new file mode 100644 index 000000000..18e470c4f --- /dev/null +++ b/research/atemporal/at1/model/at1_model.h @@ -0,0 +1,231 @@ +/* AT-1 candidate engine (Agent 3, aien-dev/omega#371). Portable C11, libc + libm only. + * + * Contracts (frozen, aien-architecture cbe4c8e): AT1_CASE_V1 (sha256 e62018d8...), + * AT1_RESULT_V1 (sha256 3e6efd7e...), with AT0_RESULT_V2 sections 2, 4, 5, 7 normative by + * reference. Mathematics: AT1_SPEC.md at aien-architecture 81047f5. Contract readings (c), (d), + * (e) of AT1_CHARTER.md section 8 are applied. + * + * Layers, one file each: + * at1_bn.c arbitrary-precision integers, exact rationals, Gaussian rationals + * at1_case.c AT1_CASE_V1 parser and validator (rules 1 to 6 in contract order), identities + * at1_exact.c literal H_total as an exact Gaussian-rational matrix, exact nullspace by + * Gauss-Jordan elimination, exact orthogonal projector P_0, exact zero test + * at1_numeric.c binary64 physics: clock states, Psi = P_0 (|t_r> (x) psi_0) by linearity from the + * exact per-level vectors P_0 (|E_j> (x) psi_0), residuals,|t_r> (x) psi_0), residuals, + * phi_k, p(k), rho_k, Pauli outcomes, ESTIMATED bounds + * at1_result.c oracle reference splice, provenance, exact verdict (12 checks), AT1_RESULT_V1 + * writer, verdict_id and evidence_digest + * at1_io.c the only file-system access (read a whole file) + * at1_main.c command-line tool + * No global mutable state. No clock, timer, random source, thread or network call anywhere. */ +#ifndef AT1_MODEL_H +#define AT1_MODEL_H + +#include +#include + +/* ---- contract constants ---------------------------------------------------------------- */ +#define AT1_CLOCK_DIM_MIN 2 +#define AT1_CLOCK_DIM_MAX 64 +#define AT1_LABEL_MAX 256 +#define AT1_TOKEN_LIMIT 1048576 /* |n| <= 2^20, 1 <= d <= 2^20 */ +#define AT1_SCALED_K_MAX 40 +#define AT1_LABEL_LEN 32 +#define AT1_NAME_LEN 64 +#define AT1_FILE_MAX (1u << 20) /* engine limit: case and auxiliary files up to 1 MiB */ +#define AT1_TOKEN_DIGITS_MAX 4096 /* engine limit: numeric tokens up to 4096 digits */ + +typedef enum { + AT1_OK = 0, + /* refusal codes, AT1_RESULT_V1 section 5, in validation order */ + AT1_CASE_PARSE_ERROR, + AT1_CASE_NONCANONICAL, + AT1_CASE_UNSUPPORTED_VERSION, + AT1_CASE_INVALID_PARAMETER, + AT1_CASE_IRRATIONAL_SPECTRUM, + AT1_CASE_ID_MISMATCH, + /* engine errors (never a refusal) */ + AT1_ERR_RESOURCE, /* an engine limit (file size, token length) */ + AT1_ERR_INTERNAL, /* an internal consistency check failed */ + AT1_ERR_ARGUMENT /* bad tool input (oracle record, provenance) */ +} at1_status; + +const char *at1_status_name(at1_status s); + +/* ---- arbitrary-precision integers (at1_bn.c) --------------------------------------------- */ +/* Sign-magnitude, 32-bit limbs, little endian; zero has n = 0 and neg = 0. Every output may + * alias an input. Allocation failure prints AT1_ENGINE_ERROR RESOURCE_LIMIT and exits 1. */ +typedef struct { int neg; int n; int cap; uint32_t *d; } bn; + +void bn_init(bn *a); +void bn_free(bn *a); +void bn_copy(bn *r, const bn *a); +void bn_set_i64(bn *r, int64_t v); +void bn_set_u64(bn *r, uint64_t v); +int bn_is_zero(const bn *a); +int bn_sign(const bn *a); /* -1, 0, +1 */ +int bn_cmp(const bn *a, const bn *b); +int bn_cmp_abs(const bn *a, const bn *b); +void bn_add(bn *r, const bn *a, const bn *b); +void bn_sub(bn *r, const bn *a, const bn *b); +void bn_mul(bn *r, const bn *a, const bn *b); +void bn_neg(bn *r, const bn *a); +void bn_abs(bn *r, const bn *a); +void bn_divmod(bn *q, bn *rem, const bn *a, const bn *b); /* truncated; q or rem may be NULL */ +void bn_gcd(bn *r, const bn *a, const bn *b); /* r >= 0 */ +void bn_shl(bn *r, const bn *a, unsigned bits); +void bn_pow10(bn *r, unsigned k); +int bn_bitlen(const bn *a); +int bn_isqrt_exact(const bn *a, bn *root); /* 1 if a >= 0 is a perfect square */ +int bn_fits_i64(const bn *a, int64_t *out); +/* decimal digit string (no sign) into r; returns 0 if longer than AT1_TOKEN_DIGITS_MAX */ +int bn_from_digits(bn *r, const char *s, size_t len); + +/* ---- exact rationals (reduced, den > 0) --------------------------------------------------- */ +typedef struct { bn num, den; } bq; + +void bq_init(bq *a); +void bq_free(bq *a); +void bq_copy(bq *r, const bq *a); +void bq_set_i64(bq *r, int64_t n, int64_t d); /* d != 0 */ +void bq_set_bn(bq *r, const bn *n, const bn *d); /* d != 0 */ +int bq_is_zero(const bq *a); +int bq_sign(const bq *a); +int bq_cmp(const bq *a, const bq *b); +void bq_add(bq *r, const bq *a, const bq *b); +void bq_sub(bq *r, const bq *a, const bq *b); +void bq_mul(bq *r, const bq *a, const bq *b); +void bq_div(bq *r, const bq *a, const bq *b); /* b != 0 */ +void bq_neg(bq *r, const bq *a); +void bq_abs(bq *r, const bq *a); +double bq_to_double(const bq *a); /* correctly rounded (normal range) */ +void bq_from_double(bq *r, double x); /* exact; x finite */ +void bq_from_scaled(bq *r, const bn *n, unsigned k); /* n / 10^k */ + +/* ---- exact Gaussian rationals ------------------------------------------------------------- */ +typedef struct { bq re, im; } gq; + +void gq_init(gq *a); +void gq_free(gq *a); +void gq_copy(gq *r, const gq *a); +int gq_is_zero(const gq *a); +void gq_add(gq *r, const gq *a, const gq *b); +void gq_sub(gq *r, const gq *a, const gq *b); +void gq_mul(gq *r, const gq *a, const gq *b); +void gq_div(gq *r, const gq *a, const gq *b); /* b != 0 */ +void gq_conj(gq *r, const gq *a); +void gq_neg(gq *r, const gq *a); + +/* ---- parsed case (at1_case.c) -------------------------------------------------------------- */ +typedef enum { AT1_TARGET_IDEAL = 0, AT1_TARGET_INTERACTING = 1 } at1_target; +typedef enum { AT1_BOUND_NONE = 0, AT1_BOUND_ESTIMATED = 1, AT1_BOUND_RIGOROUS = 2 } at1_bound_kind; +typedef enum { AT1_EXPECT_PASS = 0, AT1_EXPECT_FAIL = 1 } at1_expect; + +#define AT1_FAILURE_CODE_COUNT 12 +extern const char *const at1_failure_codes[AT1_FAILURE_CODE_COUNT]; /* sorted bytewise */ + +/* a scaled decimal N@k, kept exactly */ +typedef struct { bn n; unsigned k; } at1_scaled; + +typedef struct { + /* exact semantic content */ + char name[AT1_NAME_LEN + 1]; + int clock_dim; /* N */ + bq energies[AT1_CLOCK_DIM_MAX]; + bq h0, h[3]; /* system_hamiltonian_pauli h0,hx,hy,hz */ + bq v[AT1_CLOCK_DIM_MAX][3]; /* interaction_pauli j vx,vy,vz */ + int ref_index; /* r */ + char ref_label[AT1_LABEL_LEN + 1]; + gq psi0[2]; + bq tau, weight; + int label_count; /* M */ + char labels[AT1_LABEL_MAX][AT1_LABEL_LEN + 1]; + /* acceptance */ + int control_positive; + at1_target target; + at1_expect expected_outcome; + unsigned expected_codes; /* bit i = at1_failure_codes[i] */ + at1_bound_kind min_bound_kind; + at1_scaled tol_constraint, tol_povm, tol_probability, tol_zero, tol_schrodinger; + /* identities (lowercase hex) and the copied text blocks */ + char case_id[65], acceptance_id[65], case_file_sha256[65]; + char *semantic_text; size_t semantic_len; /* "begin semantic\n" .. "end semantic\n" */ + char *acceptance_text; size_t acceptance_len; /* "begin acceptance\n" .. "end acceptance\n" */ + int initialized; +} at1_case; + +void at1_case_free(at1_case *c); +/* Parse and validate case bytes (AT1_CASE_V1 section 4, first failure in order). On a refusal + * the case is freed and the refusal status returned. AT1_ERR_RESOURCE for engine limits. */ +at1_status at1_case_parse(const uint8_t *bytes, size_t len, at1_case *c); +/* domain-tagged SHA-256 as lowercase hex (tag || 0x00 || data) */ +void at1_tagged_sha256(const char *tag, const char *data, size_t len, char out[65]); +void at1_sha256_hex(const uint8_t *data, size_t len, char out[65]); + +/* ---- exact kernel (at1_exact.c) ------------------------------------------------------------ */ +typedef struct { + int dim; /* D = 2N */ + int kernel_dim; /* D - rank(H_total), exact */ + int psi_zero; /* Psi exactly zero (exact decision) */ + int levels_in_psi; /* L: clock levels j with P_0 (e_j (x) psi_0) != 0 */ + double *h_re, *h_im; /* H_total rounded to binary64, D x D row major */ + double *y_re, *y_im; /* Y = sum_j P_0 (|E_j> (x) psi_0), exact, rounded once (D) */ + int *owner; /* clock level j whose y_j covers entry i, or -1 (D) */ + double hmax; /* max_i sum over l with owner[l] >= 0 of |H_total[i,l]| */ +} at1_kernel; + +void at1_kernel_free(at1_kernel *k); +at1_status at1_kernel_build(const at1_case *c, at1_kernel *k); + +/* ---- numerics (at1_numeric.c) --------------------------------------------------------------- */ +typedef enum { AT1_LABEL_DEFINED = 0, AT1_LABEL_UNDEFINED = 1, AT1_LABEL_INDETERMINATE = 2 } at1_label_status; + +typedef struct { + double value, bound; /* bound >= 0, ESTIMATED */ + int undefined; /* write "undefined 0@0" */ +} at1_val; + +typedef struct { + int kernel_dim; + int trivial; /* kernel_dim == 0 or Psi exactly zero */ + at1_val constraint, povm; + int M; + at1_label_status status[AT1_LABEL_MAX]; + at1_val clock[AT1_LABEL_MAX]; + at1_val pauli[AT1_LABEL_MAX][6]; /* X+, X-, Y+, Y-, Z+, Z- */ +} at1_values; + +/* reversed != 0 evaluates the labels in reverse order (test T8; values must be bit-identical) */ +at1_status at1_compute(const at1_case *c, const at1_kernel *k, int reversed, at1_values *out); +/* label status rule (AT1_RESULT_V1 section 3) decided exactly on the binary64 value and the + * scaled-decimal bound written for it */ +at1_label_status at1_status_rule(double p, double bound, const at1_scaled *tol_zero); +/* smallest scaled decimal >= x (x >= 0 finite), at most 7 significant digits; "0@0" for 0 */ +void at1_bound_format(double x, char *buf, size_t cap); +void at1_f64_format(double x, char *buf, size_t cap); + +/* ---- result (at1_result.c) ------------------------------------------------------------------- */ +/* Writes the complete AT1_RESULT_V1 file into a malloc'd buffer (*out, *out_len). + * oracle_text == NULL means the oracle is unavailable: outcome ERROR ORACLE_UNAVAILABLE. + * Returns AT1_ERR_ARGUMENT with a message in err (cap bytes) for a malformed oracle record + * or provenance file. */ +at1_status at1_result_write(const at1_case *c, const at1_values *v, + const char *oracle_text, size_t oracle_len, + const char *prov_text, size_t prov_len, + char **out, size_t *out_len, char *err, size_t cap); +/* an ERROR result with the given run error code (INTERNAL_ERROR, RESOURCE_LIMIT) */ +at1_status at1_result_write_error(const at1_case *c, const char *error_code, + const char *prov_text, size_t prov_len, + char **out, size_t *out_len, char *err, size_t cap); +/* engine-only values lines (component output for debugging; not an interface) */ +at1_status at1_values_write(const at1_case *c, const at1_values *v, char **out, size_t *out_len); + +/* ---- io (at1_io.c) ------------------------------------------------------------------------- */ +at1_status at1_read_file(const char *path, uint8_t **bytes, size_t *len); + +/* ---- allocation helpers (at1_bn.c) --------------------------------------------------------- */ +void *at1_xmalloc(size_t n); +void *at1_xcalloc(size_t n, size_t sz); +void *at1_xrealloc(void *p, size_t n); + +#endif diff --git a/research/atemporal/at1/model/at1_numeric.c b/research/atemporal/at1/model/at1_numeric.c new file mode 100644 index 000000000..70a044f1a --- /dev/null +++ b/research/atemporal/at1/model/at1_numeric.c @@ -0,0 +1,261 @@ +/* binary64 evaluation of the AT-1 quantities (AT1_RESULT_V1 section 3) from the exact kernel. + * + * |t_k> = N^(-1/2) sum_j exp(-2 pi i E_j k tau) |E_j> turn count E_j k tau reduced + * exactly modulo 1 (int64) first + * Psi = P_0 (|t_r> (x) psi_0) = sum_j y_j y_j = P_0 (|E_j> (x) psi_0) exact + * (at1_exact.c), rounded once + * constraint_residual = || H_total Psi_hat ||_2 literal D x D product, V included + * povm_residual = || sum_k w |t_k> +#include +#include +#include + +#define AT1_EPS 1.1102230246251565404e-16 /* 2^-53 */ +static const double TWO_PI = 6.283185307179586476925286766559005768; + +typedef struct { double re, im; } cplx; +static cplx c_mul(cplx a, cplx b) { cplx r = { a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re }; return r; } +static cplx c_add(cplx a, cplx b) { cplx r = { a.re + b.re, a.im + b.im }; return r; } +static cplx c_conj(cplx a) { cplx r = { a.re, -a.im }; return r; } +static double c_abs2(cplx a) { return a.re * a.re + a.im * a.im; } + +void at1_f64_format(double x, char *buf, size_t cap) +{ + if (!isfinite(x)) { snprintf(buf, cap, "nonfinite"); return; } + if (x == 0.0) x = 0.0; /* -0.0 is written as +0.0 */ + uint64_t bits; memcpy(&bits, &x, sizeof bits); + snprintf(buf, cap, "f64:%016llx", (unsigned long long)bits); +} + +/* smallest N@k >= x with at most 7 significant digits, verified exactly */ +static void bound_scaled(double x, uint64_t *N, unsigned *k) +{ + if (!(x > 0.0)) { *N = 0; *k = 0; return; } + int kk = (int)ceil(6.0 - log10(x)); + if (kk < 0) kk = 0; + if (kk > AT1_SCALED_K_MAX) kk = AT1_SCALED_K_MAX; + double y = floor(x * pow(10.0, kk)) - 2.0; /* start below, step up to the minimum */ + uint64_t n = y > 0.0 ? (uint64_t)y : 0; + bq ex, sc; bn nb; bq_init(&ex); bq_init(&sc); bn_init(&nb); + bq_from_double(&ex, x); + for (;;) { /* exact check N / 10^k >= x */ + bn_set_u64(&nb, n); bq_from_scaled(&sc, &nb, (unsigned)kk); + if (bq_cmp(&sc, &ex) >= 0) break; + n++; + } + bq_free(&ex); bq_free(&sc); bn_free(&nb); + while (kk > 0 && n % 10 == 0) { n /= 10; kk--; } + *N = n; *k = (unsigned)kk; +} + +void at1_bound_format(double x, char *buf, size_t cap) +{ + uint64_t n; unsigned k; + bound_scaled(x, &n, &k); + snprintf(buf, cap, "%llu@%u", (unsigned long long)n, k); +} + +at1_label_status at1_status_rule(double p, double bound, const at1_scaled *tol_zero) +{ + uint64_t n; unsigned k; + bound_scaled(bound, &n, &k); + bq P, B, T, s; bn nb; bq_init(&P); bq_init(&B); bq_init(&T); bq_init(&s); bn_init(&nb); + bq_from_double(&P, p); + bn_set_u64(&nb, n); bq_from_scaled(&B, &nb, k); + bq_from_scaled(&T, &tol_zero->n, tol_zero->k); + at1_label_status st; + bq_add(&s, &P, &B); + if (bq_cmp(&s, &T) <= 0) st = AT1_LABEL_UNDEFINED; + else { bq_sub(&s, &P, &B); st = bq_cmp(&s, &T) > 0 ? AT1_LABEL_DEFINED : AT1_LABEL_INDETERMINATE; } + bq_free(&P); bq_free(&B); bq_free(&T); bq_free(&s); bn_free(&nb); + return st; +} + +static int rat_i64(const bq *q, int64_t *n, int64_t *d) +{ + return bn_fits_i64(&q->num, n) && bn_fits_i64(&q->den, d); +} + +/* exp(-2 pi i E k tau) with the turn count reduced exactly to [-1/2, 1/2) */ +static int clock_phase(const bq *E, int k, const bq *tau, cplx *out) +{ + int64_t en, ed, tn, td; + if (!rat_i64(E, &en, &ed) || !rat_i64(tau, &tn, &td)) return 0; + /* in-limit tokens: |en|, ed, tn, td <= 2^20 and k <= 255, so |num| < 2^48, den <= 2^40 */ + int64_t num = en * (int64_t)k * tn, den = ed * td; + int64_t m = num % den; + if (m < 0) m += den; + if (2 * m >= den) m -= den; + double ang = TWO_PI * ((double)m / (double)den); + out->re = cos(ang); out->im = -sin(ang); + return 1; +} + +/* pairwise sum of a[lo..hi) (real), for the Frobenius norm over N^2 entries */ +static double pair_sum_r(const double *a, int lo, int hi) +{ + if (hi - lo == 1) return a[lo]; + if (hi - lo == 0) return 0.0; + int mid = lo + (hi - lo) / 2; + return pair_sum_r(a, lo, mid) + pair_sum_r(a, mid, hi); +} + +/* pairwise sum of a[lo..hi) (complex), for the POVM sum over labels */ +static cplx pair_sum(const cplx *a, int lo, int hi) +{ + if (hi - lo == 1) return a[lo]; + if (hi - lo == 0) { cplx z = { 0, 0 }; return z; } + int mid = lo + (hi - lo) / 2; + return c_add(pair_sum(a, lo, mid), pair_sum(a, mid, hi)); +} + +at1_status at1_compute(const at1_case *c, const at1_kernel *K, int reversed, at1_values *out) +{ + memset(out, 0, sizeof *out); + const int N = c->clock_dim, D = 2 * N, M = c->label_count, r = c->ref_index; + const double w = bq_to_double(&c->weight); + const double inv_sqrt_n = 1.0 / sqrt((double)N); + out->kernel_dim = K->kernel_dim; + out->M = M; + out->trivial = K->kernel_dim == 0 || K->psi_zero; + + /* clock states */ + cplx *tk = at1_xmalloc((size_t)M * (size_t)N * sizeof(cplx)); + for (int k = 0; k < M; k++) for (int j = 0; j < N; j++) { + cplx ph; + if (!clock_phase(&c->energies[j], k, &c->tau, &ph)) { free(tk); return AT1_ERR_INTERNAL; } + ph.re *= inv_sqrt_n; ph.im *= inv_sqrt_n; + tk[k * N + j] = ph; + } + + /* povm_residual (independent of Psi) */ + { + cplx *terms = at1_xmalloc((size_t)M * sizeof(cplx)); + double *sq = at1_xmalloc((size_t)N * (size_t)N * sizeof(double)); + for (int j = 0; j < N; j++) for (int l = 0; l < N; l++) { + for (int k = 0; k < M; k++) { + cplx t = c_mul(tk[k * N + j], c_conj(tk[k * N + l])); + terms[k].re = w * t.re; terms[k].im = w * t.im; + } + cplx s = pair_sum(terms, 0, M); + if (j == l) s.re -= 1.0; + sq[j * N + l] = c_abs2(s); + } + free(terms); + out->povm.value = sqrt(pair_sum_r(sq, 0, N * N)); /* pairwise: N^2 terms, log depth */ + free(sq); + int lg = 0; while ((1 << lg) < M) lg++; + int ln = 0; while ((1 << ln) < N) ln++; + out->povm.bound = 2.0 * ((lg + 8) * AT1_EPS * (M * w + 1.0) + (2 * ln + 4) * AT1_EPS * out->povm.value); + } + + if (out->trivial) { + out->constraint.undefined = 1; + for (int k = 0; k < M; k++) { + out->status[k] = AT1_LABEL_UNDEFINED; + out->clock[k].undefined = 1; + for (int s = 0; s < 6; s++) out->pauli[k][s].undefined = 1; + } + free(tk); + return AT1_OK; + } + + /* Psi = P_0 (|t_r> (x) psi_0) */ + cplx *Psi = at1_xmalloc((size_t)D * sizeof(cplx)); + /* Psi = P_0 (|t_r> (x) psi_0) = sum_j P_0 (|E_j> (x) psi_0) (linearity): entry i is the + * clock amplitude of its level times the exact Y_i rounded once. No sum, so no cancellation: + * every entry has relative error at most about 8 eps (Y_i, cos and sin, 1/sqrt(N), one complex + * product); delta = 16 eps bounds ||Psi_c - Psi|| / ||Psi|| with a safety factor 2. */ + double norm2 = 0.0; + for (int i = 0; i < D; i++) { + if (K->owner[i] < 0) { Psi[i].re = 0.0; Psi[i].im = 0.0; continue; } + cplx yi = { K->y_re[i], K->y_im[i] }; + Psi[i] = c_mul(tk[r * N + K->owner[i]], yi); + norm2 += c_abs2(Psi[i]); + } + const double delta = 16.0 * AT1_EPS; + + /* constraint_residual = || H_total Psi_hat || */ + { + double inv = 1.0 / sqrt(norm2), res2 = 0.0; + for (int i = 0; i < D; i++) { + cplx acc = { 0, 0 }; + for (int l = 0; l < D; l++) { + cplx h = { K->h_re[i * D + l], K->h_im[i * D + l] }; + if (h.re == 0.0 && h.im == 0.0) continue; + cplx ph = { Psi[l].re * inv, Psi[l].im * inv }; + acc = c_add(acc, c_mul(h, ph)); + } + res2 += c_abs2(acc); + } + out->constraint.value = sqrt(res2); + out->constraint.bound = 2.0 * (K->hmax * delta + 8.0 * AT1_EPS * (K->hmax + 1.0)) + 4.0 * AT1_EPS * out->constraint.value; + } + + /* per label: phi_k, p(k), status, Pauli outcomes */ + static const cplx proj[6][2][2] = { + { { { 0.5, 0 }, { 0.5, 0 } }, { { 0.5, 0 }, { 0.5, 0 } } }, /* X+ */ + { { { 0.5, 0 }, { -0.5, 0 } }, { { -0.5, 0 }, { 0.5, 0 } } }, /* X- */ + { { { 0.5, 0 }, { 0, -0.5 } }, { { 0, 0.5 }, { 0.5, 0 } } }, /* Y+ */ + { { { 0.5, 0 }, { 0, 0.5 } }, { { 0, -0.5 }, { 0.5, 0 } } }, /* Y- */ + { { { 1, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, /* Z+ */ + { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 1, 0 } } } /* Z- */ + }; + const double L = K->levels_in_psi > 0 ? K->levels_in_psi : 1; + const double cc = L + 12.0; + const double eta = sqrt(L / N) * (delta + cc * AT1_EPS); /* |Delta phi_k| / ||Psi|| */ + for (int step = 0; step < M; step++) { + int k = reversed ? M - 1 - step : step; + cplx phi[2]; + for (int s = 0; s < 2; s++) { + cplx acc = { 0, 0 }; + for (int j = 0; j < N; j++) { + cplx v = Psi[2 * j + s]; + if (v.re == 0.0 && v.im == 0.0) continue; + acc = c_add(acc, c_mul(c_conj(tk[k * N + j]), v)); + } + phi[s] = acc; + } + double n2 = c_abs2(phi[0]) + c_abs2(phi[1]); + double p = w * n2 / norm2; + double pp = p > 0.0 ? p : 0.0; + out->clock[k].value = p; + out->clock[k].bound = 2.0 * (2.0 * sqrt(w * pp) * eta + (2.0 * delta + (2.0 * L + 12.0) * AT1_EPS) * pp) + 4.0 * w * eta * eta; + out->status[k] = at1_status_rule(p, out->clock[k].bound, &c->tol_zero); + if (out->status[k] != AT1_LABEL_DEFINED) { + for (int s = 0; s < 6; s++) out->pauli[k][s].undefined = 1; + continue; + } + cplx rho[2][2]; + for (int a = 0; a < 2; a++) for (int b = 0; b < 2; b++) { + cplx t = c_mul(phi[a], c_conj(phi[b])); + rho[a][b].re = t.re / n2; rho[a][b].im = t.im / n2; + } + double bP = 2.0 * (2.0 * eta * sqrt(w / pp) + 16.0 * AT1_EPS); + for (int s = 0; s < 6; s++) { + cplx tr = { 0, 0 }; + for (int a = 0; a < 2; a++) for (int b = 0; b < 2; b++) tr = c_add(tr, c_mul(rho[a][b], proj[s][b][a])); + out->pauli[k][s].value = tr.re; + out->pauli[k][s].bound = bP; + } + } + free(tk); free(Psi); + return AT1_OK; +} diff --git a/research/atemporal/at1/model/at1_result.c b/research/atemporal/at1/model/at1_result.c new file mode 100644 index 000000000..60d91fe9d --- /dev/null +++ b/research/atemporal/at1/model/at1_result.c @@ -0,0 +1,673 @@ +/* AT1_RESULT_V1 writer: splices the oracle's four reference families (charter reading c), + * judges the twelve checks of AT1_RESULT_V1 section 4 in exact rational arithmetic on the + * written tokens (AT0_RESULT_V2 section 4 comparison forms), and writes the complete file with + * verdict_id and evidence_digest (AT1_RESULT_V1 section 6). + * + * Exactness: every f64 token and every scaled decimal is an exact rational (at1_bn.c); the exact + * rational w/N is the ideal clock marginal of check 10. No comparison here uses floating point. + * Aggregation inside a check: FAIL if any item fails, else INDETERMINATE if any item is, else + * PASS; NOT_EVALUATED when no input remains (per-input NOT_EVALUATED reading). Check 9 is FAIL + * exactly when some engine label is UNDEFINED (as the qualified AT-0 judge). */ +#include "at1_model.h" + +#include +#include +#include +#include + +/* ---- growable text buffer ----------------------------------------------------------------- */ +typedef struct { char *p; size_t n, cap; } buf_t; +static void put(buf_t *b, const char *s) +{ + size_t l = strlen(s); + if (b->n + l + 1 > b->cap) { + size_t cap = b->cap ? b->cap : 4096; + while (b->n + l + 1 > cap) cap *= 2; + b->p = at1_xrealloc(b->p, cap); b->cap = cap; + } + memcpy(b->p + b->n, s, l); b->n += l; b->p[b->n] = 0; +} +static void putn(buf_t *b, const char *s, size_t l) +{ + char *t = at1_xmalloc(l + 1); memcpy(t, s, l); t[l] = 0; put(b, t); free(t); +} + +/* ---- judged value ---------------------------------------------------------------------------- */ +enum { JV_VALUE = 0, JV_NONFINITE = 1, JV_UNDEFINED = 2 }; +typedef struct { int kind; double v; bn bN; unsigned bk; char btxt[400]; } jv; + +static void jv_init(jv *x) { x->kind = JV_UNDEFINED; x->v = 0; bn_init(&x->bN); x->bk = 0; strcpy(x->btxt, "0@0"); } +static void jv_free(jv *x) { bn_free(&x->bN); } +static void jv_from_val(jv *x, const at1_val *v) +{ + char t[400]; + if (v->undefined) { x->kind = JV_UNDEFINED; bn_set_u64(&x->bN, 0); x->bk = 0; return; } + /* a value whose bound overflowed is written nonfinite (it forces NONFINITE_VALUE) */ + x->kind = isfinite(v->value) && isfinite(v->bound) ? JV_VALUE : JV_NONFINITE; + x->v = v->value; + /* the bound exactly as it is written */ + at1_bound_format(x->kind == JV_VALUE ? v->bound : 0.0, x->btxt, sizeof x->btxt); + strcpy(t, x->btxt); + char *at = strchr(t, '@'); + bn_from_digits(&x->bN, t, (size_t)(at - t)); + x->bk = (unsigned)atoi(at + 1); +} +static void jv_text(const jv *x, char *out, size_t cap) +{ + if (x->kind == JV_UNDEFINED) { snprintf(out, cap, "undefined 0@0"); return; } + char v[64]; + if (x->kind == JV_NONFINITE) snprintf(v, sizeof v, "nonfinite"); else at1_f64_format(x->v, v, sizeof v); + snprintf(out, cap, "%s %s", v, x->btxt); /* the bound exactly as at1_bound_format wrote it */ +} +static void jv_exact(const jv *x, bq *val, bq *bound) +{ + bq_from_double(val, x->v); + bq_from_scaled(bound, &x->bN, x->bk); +} + +/* ---- oracle reference lines ----------------------------------------------------------------- */ +static const char *AXES[3] = { "X", "Y", "Z" }; +static const char *SIGNS[2] = { "PLUS", "MINUS" }; +static const char *STATUS_NAME[3] = { "DEFINED", "UNDEFINED", "INDETERMINATE" }; + +typedef struct { + int M; + char **lines; int nlines; /* the spliced lines, verbatim */ + at1_label_status *status; + jv *clock; /* M */ + jv (*ideal)[6], (*inter)[6]; /* M x 6 */ +} refs_t; + +static void refs_free(refs_t *R) +{ + for (int i = 0; i < R->nlines; i++) free(R->lines[i]); + free(R->lines); + if (R->clock) for (int k = 0; k < R->M; k++) jv_free(&R->clock[k]); + if (R->ideal) for (int k = 0; k < R->M; k++) for (int s = 0; s < 6; s++) { jv_free(&R->ideal[k][s]); jv_free(&R->inter[k][s]); } + free(R->status); free(R->clock); free(R->ideal); free(R->inter); +} + +static int is_hex_lower(const char *s, size_t n) +{ + for (size_t i = 0; i < n; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0; + return 1; +} +static int is_digits(const char *s, size_t n) +{ + if (n == 0) return 0; + for (size_t i = 0; i < n; i++) if (s[i] < '0' || s[i] > '9') return 0; + return 1; +} + +/* " " -> jv; 0 on a grammar failure. undefined only with 0@0. */ +static int parse_value_bound(const char *v, const char *b, jv *x) +{ + size_t lb = strlen(b); + const char *at = strchr(b, '@'); + if (!at) return 0; + size_t ln = (size_t)(at - b), lk = lb - ln - 1; + if (!is_digits(b, ln) || !is_digits(at + 1, lk) || lk > 2) return 0; + if ((ln > 1 && b[0] == '0') || (lk > 1 && at[1] == '0')) return 0; + unsigned k = (unsigned)atoi(at + 1); + if (k > AT1_SCALED_K_MAX) return 0; + if (ln == 1 && b[0] == '0' && k != 0) return 0; + if (k != 0 && b[ln - 1] == '0') return 0; + if (!bn_from_digits(&x->bN, b, ln)) return 0; + x->bk = k; + if (strcmp(v, "undefined") == 0) { x->kind = JV_UNDEFINED; return bn_is_zero(&x->bN) && k == 0; } + if (strcmp(v, "nonfinite") == 0) { x->kind = JV_NONFINITE; return 1; } + if (strlen(v) != 20 || strncmp(v, "f64:", 4) != 0 || !is_hex_lower(v + 4, 16)) return 0; + uint64_t bits = 0; + for (int i = 4; i < 20; i++) bits = (bits << 4) | (uint64_t)(v[i] <= '9' ? v[i] - '0' : v[i] - 'a' + 10); + double d; memcpy(&d, &bits, sizeof d); + if (!isfinite(d) || bits == 0x8000000000000000ull) return 0; /* -0.0 is never written */ + x->kind = JV_VALUE; x->v = d; + return 1; +} + +/* split a line into at most cap space-separated tokens (in a scratch copy) */ +static int tokens(char *s, char **t, int cap) +{ + int n = 0; + for (char *p = s; ; ) { + if (n == cap) return cap + 1; + t[n++] = p; + char *sp = strchr(p, ' '); + if (!sp) break; + *sp = 0; p = sp + 1; + } + return n; +} + +static int key_is(const char *line, size_t len, const char *key) +{ + size_t k = strlen(key); + return len > k && strncmp(line, key, k) == 0 && line[k] == ' '; +} + + +/* the status rule of section 3, exact, on a written value and its written bound */ +static at1_label_status jv_status(const jv *x, const at1_scaled *tol) +{ + bq P, B, T, s; bq_init(&P); bq_init(&B); bq_init(&T); bq_init(&s); + bq_from_double(&P, x->v); + bq_from_scaled(&B, &x->bN, x->bk); + bq_from_scaled(&T, &tol->n, tol->k); + at1_label_status st; + bq_add(&s, &P, &B); + if (bq_cmp(&s, &T) <= 0) st = AT1_LABEL_UNDEFINED; + else { bq_sub(&s, &P, &B); st = bq_cmp(&s, &T) > 0 ? AT1_LABEL_DEFINED : AT1_LABEL_INDETERMINATE; } + bq_free(&P); bq_free(&B); bq_free(&T); bq_free(&s); + return st; +} +static at1_status refs_parse(const at1_case *c, const char *text, size_t len, refs_t *R, char *err, size_t cap) +{ + const int M = c->label_count; + memset(R, 0, sizeof *R); + R->M = M; + R->status = at1_xcalloc((size_t)M, sizeof *R->status); + R->clock = at1_xmalloc((size_t)M * sizeof(jv)); + R->ideal = at1_xmalloc((size_t)M * sizeof *R->ideal); + R->inter = at1_xmalloc((size_t)M * sizeof *R->inter); + for (int k = 0; k < M; k++) { jv_init(&R->clock[k]); for (int s = 0; s < 6; s++) { jv_init(&R->ideal[k][s]); jv_init(&R->inter[k][s]); } } + R->lines = at1_xmalloc((size_t)(14 * M) * sizeof(char *)); + + if (len == 0 || text[len - 1] != '\n') { snprintf(err, cap, "oracle record: not LF-terminated"); return AT1_ERR_ARGUMENT; } + /* is there a values block? then take reference lines only from inside it */ + int has_values = 0; + for (size_t i = 0; i < len; ) { + const char *e = memchr(text + i, '\n', len - i); + size_t l = (size_t)(e - (text + i)); + if (l == 12 && strncmp(text + i, "begin values", 12) == 0) has_values = 1; + i += l + 1; + } + static const char *fam[4] = { "reference_label", "reference_clock_probability", "reference_ideal", "reference_interacting" }; + int expect_total = 14 * M, got = 0, inside = !has_values; + for (size_t i = 0; i < len; ) { + const char *ln = text + i; + const char *e = memchr(ln, '\n', len - i); + size_t l = (size_t)(e - ln); + i += l + 1; + if (l == 12 && strncmp(ln, "begin values", 12) == 0) { inside = 1; continue; } + if (l == 10 && strncmp(ln, "end values", 10) == 0) { inside = 0; continue; } + if (key_is(ln, l, "case_id") && (l != 8 + 64 || strncmp(ln + 8, c->case_id, 64) != 0)) { + snprintf(err, cap, "oracle record: case_id differs from the case"); return AT1_ERR_ARGUMENT; + } + if (key_is(ln, l, "acceptance_id") && (l != 14 + 64 || strncmp(ln + 14, c->acceptance_id, 64) != 0)) { + snprintf(err, cap, "oracle record: acceptance_id differs from the case"); return AT1_ERR_ARGUMENT; + } + if (!inside) continue; + int f = -1; + for (int q = 0; q < 4; q++) if (key_is(ln, l, fam[q])) f = q; + if (f < 0) continue; + if (got >= expect_total) { snprintf(err, cap, "oracle record: too many reference lines"); return AT1_ERR_ARGUMENT; } + /* expected position */ + int fam_expected, k, s; + if (got < M) { fam_expected = 0; k = got; s = 0; } + else if (got < 2 * M) { fam_expected = 1; k = got - M; s = 0; } + else if (got < 8 * M) { fam_expected = 2; k = (got - 2 * M) / 6; s = (got - 2 * M) % 6; } + else { fam_expected = 3; k = (got - 8 * M) / 6; s = (got - 8 * M) % 6; } + char *copy = at1_xmalloc(l + 1); memcpy(copy, ln, l); copy[l] = 0; + R->lines[R->nlines++] = copy; + char *scratch = at1_xmalloc(l + 1); memcpy(scratch, ln, l); scratch[l] = 0; + char *t[8]; int nt = tokens(scratch, t, 7); + char kbuf[16]; snprintf(kbuf, sizeof kbuf, "%d", k); + int ok = f == fam_expected && nt >= 2 && strcmp(t[1], kbuf) == 0; + if (ok && f == 0) { + ok = nt == 4 && strcmp(t[2], c->labels[k]) == 0; + int st = -1; + for (int q = 0; ok && q < 3; q++) if (strcmp(t[3], STATUS_NAME[q]) == 0) st = q; + ok = ok && st >= 0; + if (ok) R->status[k] = (at1_label_status)st; + } else if (ok && f == 1) { + ok = nt == 4 && parse_value_bound(t[2], t[3], &R->clock[k]); + } else if (ok) { + jv *dst = f == 2 ? &R->ideal[k][s] : &R->inter[k][s]; + ok = nt == 6 && strcmp(t[2], AXES[s / 2]) == 0 && strcmp(t[3], SIGNS[s % 2]) == 0 && parse_value_bound(t[4], t[5], dst); + } + free(scratch); + if (!ok) { snprintf(err, cap, "oracle record: malformed or out-of-order reference line %d", got + 1); return AT1_ERR_ARGUMENT; } + got++; + } + if (got != expect_total) { snprintf(err, cap, "oracle record: %d reference lines, expected %d", got, expect_total); return AT1_ERR_ARGUMENT; } + /* undefined placement (section 1): reference_ideal is always a value; reference_interacting + * is undefined exactly when that reference_label is not DEFINED; reference_clock_probability + * is undefined only in the trivial shape (all M undefined, every reference_label UNDEFINED); + * a written clock value must reproduce its reference_label under the status rule. */ + int n_undef_clock = 0; + for (int k = 0; k < M; k++) n_undef_clock += R->clock[k].kind == JV_UNDEFINED; + for (int k = 0; k < M; k++) { + const char *why = NULL; + for (int s = 0; s < 6 && !why; s++) { + if (R->ideal[k][s].kind == JV_UNDEFINED) why = "reference_ideal undefined"; + else if ((R->inter[k][s].kind == JV_UNDEFINED) != (R->status[k] != AT1_LABEL_DEFINED)) + why = "reference_interacting undefined does not match reference_label"; + } + if (!why && n_undef_clock != 0 && (n_undef_clock != M || R->status[k] != AT1_LABEL_UNDEFINED)) + why = "reference_clock_probability undefined outside the trivial shape"; + if (!why && R->clock[k].kind == JV_VALUE && jv_status(&R->clock[k], &c->tol_zero) != R->status[k]) + why = "reference_label does not follow the status rule on reference_clock_probability"; + if (why) { snprintf(err, cap, "oracle record: label %d: %s", k, why); return AT1_ERR_ARGUMENT; } + } + return AT1_OK; +} + +/* ---- provenance ------------------------------------------------------------------------------ */ +static const char *PROV_KEYS[13] = { "source_repo", "source_commit", "source_tree_clean", "contract_commit", + "engine_sha256", "oracle_repo", "oracle_commit", "oracle_sha256", "build_cc", "build_flags", "host", + "run_started_utc", "run_finished_utc" }; + +static int valid_repo(const char *s) +{ + const char *sl = strchr(s, '/'); + if (!sl || sl == s || !sl[1] || strchr(sl + 1, '/')) return 0; + for (const char *p = s; *p; p++) { + if (p == sl) continue; + char ch = *p; + if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '.' || ch == '-')) return 0; + } + return 1; +} +static int valid_text(const char *s) +{ + size_t n = strlen(s); + if (n < 1 || n > 200 || s[0] == ' ' || s[n - 1] == ' ') return 0; + for (size_t i = 0; i < n; i++) if (s[i] < 0x20 || s[i] > 0x7E) return 0; + return 1; +} +static int valid_utc(const char *s) +{ + if (strlen(s) != 20) return 0; + static const char pat[] = "dddd-dd-ddTdd:dd:ddZ"; + for (int i = 0; i < 20; i++) { + if (pat[i] == 'd') { if (s[i] < '0' || s[i] > '9') return 0; } + else if (s[i] != pat[i]) return 0; + } + int mo = (s[5] - '0') * 10 + s[6] - '0', d = (s[8] - '0') * 10 + s[9] - '0'; + int h = (s[11] - '0') * 10 + s[12] - '0', mi = (s[14] - '0') * 10 + s[15] - '0', se = (s[17] - '0') * 10 + s[18] - '0'; + return mo >= 1 && mo <= 12 && d >= 1 && d <= 31 && h <= 23 && mi <= 59 && se <= 59; +} +static int valid_path(const char *s, size_t n) +{ + if (n < 1 || n > 200) return 0; + for (size_t i = 0; i < n; i++) if (s[i] < 0x21 || s[i] > 0x7E) return 0; + return 1; +} + +/* Validates the provenance lines and returns them normalized in *out (each LF-terminated). + * oracle_none: the oracle fields are written as "none" (ERROR results). */ +static at1_status prov_parse(const char *text, size_t len, int oracle_none, buf_t *out, char *err, size_t cap) +{ + if (len == 0 || text[len - 1] != '\n') { snprintf(err, cap, "provenance: not LF-terminated"); return AT1_ERR_ARGUMENT; } + for (size_t i = 0; i < len; i++) if (text[i] != '\n' && (text[i] < 0x20 || text[i] > 0x7E)) { snprintf(err, cap, "provenance: byte outside 0x20..0x7E"); return AT1_ERR_ARGUMENT; } + char *copy = at1_xmalloc(len + 1); memcpy(copy, text, len); copy[len] = 0; + char *line = copy; int idx = 0; at1_status st = AT1_OK; + char engine_sha[65] = "", oracle_sha[65] = "", prev_path[256] = ""; int have_prev = 0; + while (*line && st == AT1_OK) { + char *nl = strchr(line, '\n'); *nl = 0; + if (idx < 13) { + const char *key = PROV_KEYS[idx]; + size_t kl = strlen(key); + if (strncmp(line, key, kl) != 0 || line[kl] != ' ') { snprintf(err, cap, "provenance: line %d must be %s", idx + 1, key); st = AT1_ERR_ARGUMENT; break; } + const char *v = line + kl + 1; + int ok; + int is_oracle_field = idx >= 5 && idx <= 7; + if (oracle_none && is_oracle_field) { v = "none"; ok = 1; } + else switch (idx) { + case 0: case 5: ok = valid_repo(v); break; + case 1: case 3: case 6: ok = strlen(v) == 40 && is_hex_lower(v, 40); break; + case 2: ok = strcmp(v, "YES") == 0 || strcmp(v, "NO") == 0; break; + case 4: case 7: ok = strlen(v) == 64 && is_hex_lower(v, 64); break; + case 8: case 9: case 10: ok = valid_text(v); break; + default: ok = valid_utc(v); break; + } + if (!ok) { snprintf(err, cap, "provenance: bad value for %s", key); st = AT1_ERR_ARGUMENT; break; } + if (idx == 4) strcpy(engine_sha, v); + if (idx == 7 && strcmp(v, "none") != 0) strcpy(oracle_sha, v); + if (idx == 8 && strncmp(v, "oracle ", 7) == 0) { snprintf(err, cap, "provenance: build_cc marks an oracle-written record; a candidate result is refused"); st = AT1_ERR_ARGUMENT; break; } + put(out, key); put(out, " "); put(out, v); put(out, "\n"); + } else { + /* artifact , sorted strictly by path */ + char *sp1 = strncmp(line, "artifact ", 9) == 0 ? line + 9 : NULL; + char *sp2 = sp1 ? strchr(sp1, ' ') : NULL; + if (!sp2 || !valid_path(sp1, (size_t)(sp2 - sp1)) || strlen(sp2 + 1) != 64 || !is_hex_lower(sp2 + 1, 64) || strchr(sp2 + 1, ' ')) { + snprintf(err, cap, "provenance: bad artifact line"); st = AT1_ERR_ARGUMENT; break; + } + *sp2 = 0; + if (have_prev && strcmp(prev_path, sp1) >= 0) { snprintf(err, cap, "provenance: artifact paths not strictly increasing"); st = AT1_ERR_ARGUMENT; break; } + strcpy(prev_path, sp1); have_prev = 1; + *sp2 = ' '; + put(out, line); put(out, "\n"); + } + idx++; + line = nl + 1; + } + if (st == AT1_OK && idx < 13) { snprintf(err, cap, "provenance: %d lines, expected at least 13", idx); st = AT1_ERR_ARGUMENT; } + if (st == AT1_OK && oracle_sha[0] && strcmp(engine_sha, oracle_sha) == 0) { + snprintf(err, cap, "provenance: engine_sha256 equals oracle_sha256 (oracle-written record); refused"); st = AT1_ERR_ARGUMENT; + } + free(copy); + return st; +} + +/* ---- exact checks ---------------------------------------------------------------------------- */ +enum { C_PASS = 0, C_FAIL = 1, C_INDET = 2, C_NE = 3 }; +static const char *CHECK_STATE[4] = { "PASS", "FAIL", "INDETERMINATE", "NOT_EVALUATED" }; +static const char *CHECK_NAME[12] = { "bound_kind_sufficient", "values_finite", "physical_state_nontrivial", + "constraint_residual", "povm_normalization", "clock_probability_sum", "probability_range", "pauli_pair_sum", + "conditional_defined", "target_agreement", "oracle_cross_check", "label_status_agreement" }; +/* failure code index (at1_failure_codes order) of each check; check 10 depends on the target */ +enum { K_BOUND = 0, K_COND = 1, K_CON = 2, K_INTER = 3, K_NONFIN = 4, K_ORACLE = 5, K_POVM = 6, K_PREC = 7, + K_RANGE = 8, K_SUM = 9, K_SCHRO = 10, K_TRIV = 11 }; + +typedef struct { int seen, fail, indet; } agg_t; +static void agg_add(agg_t *g, int r) { g->seen = 1; if (r == C_FAIL) g->fail = 1; else if (r == C_INDET) g->indet = 1; } +static int agg_res(const agg_t *g) { return !g->seen ? C_NE : g->fail ? C_FAIL : g->indet ? C_INDET : C_PASS; } + +/* absolute form: |v| + b <= tol PASS; |v| - b > tol FAIL; else INDETERMINATE */ +static int absform(const bq *v, const bq *b, const bq *tol) +{ + bq a, s; bq_init(&a); bq_init(&s); + bq_abs(&a, v); + bq_add(&s, &a, b); + int r; + if (bq_cmp(&s, tol) <= 0) r = C_PASS; + else { bq_sub(&s, &a, b); r = bq_cmp(&s, tol) > 0 ? C_FAIL : C_INDET; } + bq_free(&a); bq_free(&s); + return r; +} +static int signedform(const bq *v, const bq *b, const bq *tol) +{ + bq s; bq_init(&s); + bq_add(&s, v, b); + int r; + if (bq_cmp(&s, tol) <= 0) r = C_PASS; + else { bq_sub(&s, v, b); r = bq_cmp(&s, tol) > 0 ? C_FAIL : C_INDET; } + bq_free(&s); + return r; +} +/* compare a - b (bounds summed) */ +static int absdiff(const jv *a, const jv *b, const bq *tol) +{ + bq va, ba, vb, bb, d, s; bq_init(&va); bq_init(&ba); bq_init(&vb); bq_init(&bb); bq_init(&d); bq_init(&s); + jv_exact(a, &va, &ba); jv_exact(b, &vb, &bb); + bq_sub(&d, &va, &vb); bq_add(&s, &ba, &bb); + int r = absform(&d, &s, tol); + bq_free(&va); bq_free(&ba); bq_free(&vb); bq_free(&bb); bq_free(&d); bq_free(&s); + return r; +} + +typedef struct { + int M; + int trivial, kernel_dim; + jv constraint, povm; + at1_label_status *status; + jv *clock; + jv (*pauli)[6]; +} eng_t; + +static void judge(const at1_case *c, const eng_t *E, const refs_t *R, int res[12], unsigned *codes) +{ + const int M = E->M, triv = E->trivial; + bq tol_con, tol_povm, tol_p, tol_s, one, wn, v, b, s, t; + bq_init(&tol_con); bq_init(&tol_povm); bq_init(&tol_p); bq_init(&tol_s); bq_init(&one); bq_init(&wn); + bq_init(&v); bq_init(&b); bq_init(&s); bq_init(&t); + bq_from_scaled(&tol_con, &c->tol_constraint.n, c->tol_constraint.k); + bq_from_scaled(&tol_povm, &c->tol_povm.n, c->tol_povm.k); + bq_from_scaled(&tol_p, &c->tol_probability.n, c->tol_probability.k); + bq_from_scaled(&tol_s, &c->tol_schrodinger.n, c->tol_schrodinger.k); + bq_set_i64(&one, 1, 1); + { bq n; bq_init(&n); bq_set_i64(&n, c->clock_dim, 1); bq_div(&wn, &c->weight, &n); bq_free(&n); } + agg_t g; + + /* 1 */ + res[0] = AT1_BOUND_ESTIMATED >= c->min_bound_kind ? C_PASS : C_FAIL; + /* 2: no nonfinite token anywhere in the values block */ + int nonfin = E->constraint.kind == JV_NONFINITE || E->povm.kind == JV_NONFINITE; + for (int k = 0; k < M; k++) { + if (E->clock[k].kind == JV_NONFINITE || R->clock[k].kind == JV_NONFINITE) nonfin = 1; + for (int q = 0; q < 6; q++) + if (E->pauli[k][q].kind == JV_NONFINITE || R->ideal[k][q].kind == JV_NONFINITE || R->inter[k][q].kind == JV_NONFINITE) nonfin = 1; + } + res[1] = nonfin ? C_FAIL : C_PASS; + /* 3 */ + res[2] = triv ? C_FAIL : C_PASS; + /* 4 */ + memset(&g, 0, sizeof g); + if (!triv && E->constraint.kind == JV_VALUE) { jv_exact(&E->constraint, &v, &b); agg_add(&g, absform(&v, &b, &tol_con)); } + res[3] = triv ? C_NE : agg_res(&g); + /* 5 */ + memset(&g, 0, sizeof g); + if (E->povm.kind == JV_VALUE) { jv_exact(&E->povm, &v, &b); agg_add(&g, absform(&v, &b, &tol_povm)); } + res[4] = agg_res(&g); + /* 6 */ + memset(&g, 0, sizeof g); + if (!triv) { + int all = 1; + bq sv, sb; bq_init(&sv); bq_init(&sb); + for (int k = 0; k < M; k++) { + if (E->clock[k].kind != JV_VALUE) { all = 0; break; } + jv_exact(&E->clock[k], &v, &b); bq_add(&sv, &sv, &v); bq_add(&sb, &sb, &b); + } + if (all) { bq_sub(&sv, &sv, &one); agg_add(&g, absform(&sv, &sb, &tol_p)); } + bq_free(&sv); bq_free(&sb); + } + res[5] = triv ? C_NE : agg_res(&g); + /* 7: every clock_probability and pauli value, reference lines excluded */ + memset(&g, 0, sizeof g); + if (!triv) { + for (int k = 0; k < M; k++) for (int q = -1; q < 6; q++) { + const jv *x = q < 0 ? &E->clock[k] : &E->pauli[k][q]; + if (x->kind != JV_VALUE) continue; + jv_exact(x, &v, &b); + bq_neg(&t, &v); agg_add(&g, signedform(&t, &b, &tol_p)); + bq_sub(&t, &v, &one); agg_add(&g, signedform(&t, &b, &tol_p)); + } + } + res[6] = triv ? C_NE : agg_res(&g); + /* 8 */ + memset(&g, 0, sizeof g); + if (!triv) for (int k = 0; k < M; k++) { + if (E->status[k] != AT1_LABEL_DEFINED) continue; + for (int a = 0; a < 3; a++) { + const jv *pl = &E->pauli[k][2 * a], *mi = &E->pauli[k][2 * a + 1]; + if (pl->kind != JV_VALUE || mi->kind != JV_VALUE) continue; + bq v2, b2; bq_init(&v2); bq_init(&b2); + jv_exact(pl, &v, &b); jv_exact(mi, &v2, &b2); + bq_add(&s, &v, &v2); bq_sub(&s, &s, &one); bq_add(&b, &b, &b2); + agg_add(&g, absform(&s, &b, &tol_p)); + bq_free(&v2); bq_free(&b2); + } + } + res[7] = triv ? C_NE : agg_res(&g); + /* 9 */ + if (triv) res[8] = C_NE; + else { res[8] = C_PASS; for (int k = 0; k < M; k++) if (E->status[k] == AT1_LABEL_UNDEFINED) res[8] = C_FAIL; } + /* 10 and 11 */ + for (int chk = 0; chk < 2; chk++) { + memset(&g, 0, sizeof g); + int use_ideal = chk == 0 && c->target == AT1_TARGET_IDEAL; + if (!triv && !(chk == 1 && c->target == AT1_TARGET_INTERACTING)) { + for (int k = 0; k < M; k++) { + if (E->status[k] != AT1_LABEL_DEFINED || R->status[k] != AT1_LABEL_DEFINED) continue; + for (int q = 0; q < 6; q++) { + const jv *ref = use_ideal ? &R->ideal[k][q] : &R->inter[k][q]; + if (E->pauli[k][q].kind != JV_VALUE || ref->kind != JV_VALUE) continue; + agg_add(&g, absdiff(&E->pauli[k][q], ref, &tol_s)); + } + if (E->clock[k].kind != JV_VALUE) continue; + if (use_ideal) { + jv_exact(&E->clock[k], &v, &b); bq_sub(&s, &v, &wn); + agg_add(&g, absform(&s, &b, &tol_p)); + } else if (R->clock[k].kind == JV_VALUE) { + agg_add(&g, absdiff(&E->clock[k], &R->clock[k], &tol_p)); + } + } + } + res[9 + chk] = triv ? C_NE : agg_res(&g); + } + /* 12 */ + memset(&g, 0, sizeof g); + if (!triv) for (int k = 0; k < M; k++) { + at1_label_status a = E->status[k], r = R->status[k]; + if (a == AT1_LABEL_INDETERMINATE || r == AT1_LABEL_INDETERMINATE) agg_add(&g, C_INDET); + else agg_add(&g, a != r ? C_FAIL : C_PASS); + } + res[11] = triv ? C_NE : agg_res(&g); + + const int code_of[12] = { K_BOUND, K_NONFIN, K_TRIV, K_CON, K_POVM, K_SUM, K_RANGE, K_SUM, K_COND, + c->target == AT1_TARGET_IDEAL ? K_SCHRO : K_INTER, K_ORACLE, K_ORACLE }; + int indet = 0; + for (int k = 0; k < M; k++) if (E->status[k] == AT1_LABEL_INDETERMINATE || R->status[k] == AT1_LABEL_INDETERMINATE) indet = 1; + *codes = 0; + for (int i = 0; i < 12; i++) { if (res[i] == C_FAIL) *codes |= 1u << code_of[i]; if (res[i] == C_INDET) indet = 1; } + if (indet) *codes |= 1u << K_PREC; + bq_free(&tol_con); bq_free(&tol_povm); bq_free(&tol_p); bq_free(&tol_s); bq_free(&one); bq_free(&wn); + bq_free(&v); bq_free(&b); bq_free(&s); bq_free(&t); +} + +/* ---- writer ------------------------------------------------------------------------------------- */ +static void eng_from_values(eng_t *E, const at1_values *V) +{ + const int M = V->M; + E->M = M; E->trivial = V->trivial; E->kernel_dim = V->kernel_dim; + jv_init(&E->constraint); jv_init(&E->povm); + jv_from_val(&E->constraint, &V->constraint); jv_from_val(&E->povm, &V->povm); + E->status = at1_xmalloc((size_t)M * sizeof *E->status); + E->clock = at1_xmalloc((size_t)M * sizeof(jv)); + E->pauli = at1_xmalloc((size_t)M * sizeof *E->pauli); + for (int k = 0; k < M; k++) { + E->status[k] = V->status[k]; + jv_init(&E->clock[k]); jv_from_val(&E->clock[k], &V->clock[k]); + for (int q = 0; q < 6; q++) { jv_init(&E->pauli[k][q]); jv_from_val(&E->pauli[k][q], &V->pauli[k][q]); } + } +} +static void eng_free(eng_t *E) +{ + jv_free(&E->constraint); jv_free(&E->povm); + for (int k = 0; k < E->M; k++) { jv_free(&E->clock[k]); for (int q = 0; q < 6; q++) jv_free(&E->pauli[k][q]); } + free(E->status); free(E->clock); free(E->pauli); +} + +static void write_engine_values(buf_t *o, const at1_case *c, const eng_t *E) +{ + char t[640], vb[480]; + snprintf(t, sizeof t, "physical_state_kernel_dim %d\n", E->kernel_dim); put(o, t); + jv_text(&E->constraint, vb, sizeof vb); snprintf(t, sizeof t, "constraint_residual %s\n", vb); put(o, t); + jv_text(&E->povm, vb, sizeof vb); snprintf(t, sizeof t, "povm_residual %s\n", vb); put(o, t); + for (int k = 0; k < E->M; k++) { snprintf(t, sizeof t, "label %d %s %s\n", k, c->labels[k], STATUS_NAME[E->status[k]]); put(o, t); } + for (int k = 0; k < E->M; k++) { jv_text(&E->clock[k], vb, sizeof vb); snprintf(t, sizeof t, "clock_probability %d %s\n", k, vb); put(o, t); } + for (int k = 0; k < E->M; k++) for (int q = 0; q < 6; q++) { + jv_text(&E->pauli[k][q], vb, sizeof vb); + snprintf(t, sizeof t, "pauli %d %s %s %s\n", k, AXES[q / 2], SIGNS[q % 2], vb); put(o, t); + } +} + +static at1_status write_common_head(buf_t *o, const at1_case *c) +{ + char cid[65], aid[65], t[256]; + /* a writer refuses blocks that do not reproduce the copied identities */ + at1_tagged_sha256("omega.at1.case.v1", c->semantic_text, c->semantic_len, cid); + at1_tagged_sha256("omega.at1.acceptance.v1", c->acceptance_text, c->acceptance_len, aid); + if (strcmp(cid, c->case_id) != 0 || strcmp(aid, c->acceptance_id) != 0) return AT1_ERR_INTERNAL; + put(o, "OMEGA-AT1-RESULT v1\ndomain omega.at1.result.v1\ncontract AT1_RESULT_V1\ncase_contract AT1_CASE_V1\n"); + snprintf(t, sizeof t, "case_name %s\n", c->name); put(o, t); + putn(o, c->semantic_text, c->semantic_len); + putn(o, c->acceptance_text, c->acceptance_len); + snprintf(t, sizeof t, "case_id %s\nacceptance_id %s\ncase_file_sha256 %s\n", c->case_id, c->acceptance_id, c->case_file_sha256); put(o, t); + return AT1_OK; +} + +static void write_tail(buf_t *o, const at1_case *c, const char *verdict, const char *prov) +{ + char vid[65], ev[65]; + size_t pre_len = 8 + 64 + 1 + 14 + 64 + 1; + char *pre = at1_xmalloc(pre_len + strlen(verdict) + 1); + snprintf(pre, pre_len + strlen(verdict) + 1, "case_id %s\nacceptance_id %s\n%s", c->case_id, c->acceptance_id, verdict); + at1_tagged_sha256("omega.at1.verdict.v1", pre, strlen(pre), vid); + free(pre); + put(o, verdict); + put(o, "verdict_id "); put(o, vid); put(o, "\n"); + put(o, "begin provenance\n"); put(o, prov); put(o, "end provenance\n"); + at1_tagged_sha256("omega.at1.evidence.v1", o->p, o->n, ev); + put(o, "evidence_digest "); put(o, ev); put(o, "\nend\n"); +} + +at1_status at1_result_write(const at1_case *c, const at1_values *v, const char *oracle_text, size_t oracle_len, + const char *prov_text, size_t prov_len, char **out, size_t *out_len, char *err, size_t cap) +{ + *out = NULL; *out_len = 0; err[0] = 0; + if (!oracle_text) return at1_result_write_error(c, "ORACLE_UNAVAILABLE", prov_text, prov_len, out, out_len, err, cap); + refs_t R; buf_t prov = { 0 }, o = { 0 }, verdict = { 0 }; + at1_status st = refs_parse(c, oracle_text, oracle_len, &R, err, cap); + if (st == AT1_OK) st = prov_parse(prov_text, prov_len, 0, &prov, err, cap); + if (st == AT1_OK) st = write_common_head(&o, c); + if (st != AT1_OK) { refs_free(&R); free(prov.p); free(o.p); return st; } + eng_t E; eng_from_values(&E, v); + put(&o, "begin numerics\narithmetic BINARY64\nbound_kind ESTIMATED\nthreads 1\nend numerics\nbegin values\n"); + write_engine_values(&o, c, &E); + for (int i = 0; i < R.nlines; i++) { put(&o, R.lines[i]); put(&o, "\n"); } + put(&o, "end values\n"); + int res[12]; unsigned codes; + judge(c, &E, &R, res, &codes); + char t[256]; + put(&verdict, "begin verdict\n"); + for (int i = 0; i < 12; i++) { snprintf(t, sizeof t, "check %s %s\n", CHECK_NAME[i], CHECK_STATE[res[i]]); put(&verdict, t); } + int pass = codes == 0; + for (int i = 0; i < 12; i++) if (res[i] == C_FAIL || res[i] == C_INDET) pass = 0; + put(&verdict, pass ? "outcome PASS\n" : "outcome FAIL\n"); + put(&verdict, "failure_codes "); + if (codes == 0) put(&verdict, "none"); + for (int i = 0, first = 1; i < AT1_FAILURE_CODE_COUNT; i++) if (codes & (1u << i)) { if (!first) put(&verdict, ","); put(&verdict, at1_failure_codes[i]); first = 0; } + put(&verdict, "\nerror_code none\n"); + int met = (pass ? AT1_EXPECT_PASS : AT1_EXPECT_FAIL) == c->expected_outcome && codes == c->expected_codes; + put(&verdict, met ? "expectation_met YES\n" : "expectation_met NO\n"); + put(&verdict, "end verdict\n"); + write_tail(&o, c, verdict.p, prov.p); + eng_free(&E); refs_free(&R); free(prov.p); free(verdict.p); + *out = o.p; *out_len = o.n; + return AT1_OK; +} + +at1_status at1_result_write_error(const at1_case *c, const char *error_code, const char *prov_text, size_t prov_len, + char **out, size_t *out_len, char *err, size_t cap) +{ + *out = NULL; *out_len = 0; err[0] = 0; + buf_t prov = { 0 }, o = { 0 }, verdict = { 0 }; + int oracle_none = strcmp(error_code, "ORACLE_UNAVAILABLE") == 0; + at1_status st = prov_parse(prov_text, prov_len, oracle_none, &prov, err, cap); + if (st == AT1_OK) st = write_common_head(&o, c); + if (st != AT1_OK) { free(prov.p); free(o.p); return st; } + const int M = c->label_count; + char t[256]; + put(&o, "begin numerics\narithmetic BINARY64\nbound_kind ESTIMATED\nthreads 1\nend numerics\nbegin values\n"); + put(&o, "physical_state_kernel_dim 0\nconstraint_residual undefined 0@0\npovm_residual undefined 0@0\n"); + for (int k = 0; k < M; k++) { snprintf(t, sizeof t, "label %d %s UNDEFINED\n", k, c->labels[k]); put(&o, t); } + for (int k = 0; k < M; k++) { snprintf(t, sizeof t, "clock_probability %d undefined 0@0\n", k); put(&o, t); } + for (int k = 0; k < M; k++) for (int q = 0; q < 6; q++) { snprintf(t, sizeof t, "pauli %d %s %s undefined 0@0\n", k, AXES[q / 2], SIGNS[q % 2]); put(&o, t); } + for (int k = 0; k < M; k++) { snprintf(t, sizeof t, "reference_label %d %s UNDEFINED\n", k, c->labels[k]); put(&o, t); } + for (int k = 0; k < M; k++) { snprintf(t, sizeof t, "reference_clock_probability %d undefined 0@0\n", k); put(&o, t); } + for (int f = 0; f < 2; f++) for (int k = 0; k < M; k++) for (int q = 0; q < 6; q++) { + snprintf(t, sizeof t, "%s %d %s %s undefined 0@0\n", f == 0 ? "reference_ideal" : "reference_interacting", k, AXES[q / 2], SIGNS[q % 2]); + put(&o, t); + } + put(&o, "end values\n"); + put(&verdict, "begin verdict\n"); + for (int i = 0; i < 12; i++) { snprintf(t, sizeof t, "check %s NOT_EVALUATED\n", CHECK_NAME[i]); put(&verdict, t); } + snprintf(t, sizeof t, "outcome ERROR\nfailure_codes none\nerror_code %s\nexpectation_met NOT_APPLICABLE\nend verdict\n", error_code); + put(&verdict, t); + write_tail(&o, c, verdict.p, prov.p); + free(prov.p); free(verdict.p); + *out = o.p; *out_len = o.n; + return AT1_OK; +} + +at1_status at1_values_write(const at1_case *c, const at1_values *v, char **out, size_t *out_len) +{ + buf_t o = { 0 }; + eng_t E; eng_from_values(&E, v); + write_engine_values(&o, c, &E); + eng_free(&E); + *out = o.p; *out_len = o.n; + return AT1_OK; +} diff --git a/research/atemporal/at1/model/tests/cases/at1-kat-rotated-level-n4.case b/research/atemporal/at1/model/tests/cases/at1-kat-rotated-level-n4.case new file mode 100644 index 000000000..d92e2126e --- /dev/null +++ b/research/atemporal/at1/model/tests/cases/at1-kat-rotated-level-n4.case @@ -0,0 +1,45 @@ +OMEGA-AT1-CASE v1 +domain omega.at1.case.v1 +contract AT1_CASE_V1 +case_name at1-kat-rotated-level-n4 +begin semantic +model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG +energy_unit DIMENSIONLESS_HBAR_1 +clock_dim 4 +clock_energies -3/2,-1/2,1/2,3/2 +system_dim 2 +system_hamiltonian_pauli 0/1,0/1,0/1,1/2 +interaction CLOCK_DIAGONAL_PAULI +interaction_pauli 0 0/1,0/1,0/1 +interaction_pauli 1 0/1,0/1,0/1 +interaction_pauli 2 3/10,0/1,-1/10 +interaction_pauli 3 0/1,0/1,0/1 +constraint SUM_HC_HS_V +physical_state NULLSPACE_PROJECTION +reference_clock_label t0 +reference_system_state (1/1;0/1),(1/1;0/1) +clock_povm COVARIANT_DISCRETE +povm_tau_turns 1/4 +povm_weight 1/1 +clock_label_count 4 +clock_label 0 t0 +clock_label 1 t1 +clock_label 2 t2 +clock_label 3 t3 +observables PAULI_X,PAULI_Y,PAULI_Z +end semantic +begin acceptance +control_kind POSITIVE +prediction_target INTERACTING +expected_outcome PASS +expected_failure_codes none +min_bound_kind ESTIMATED +tol_constraint_residual 1@12 +tol_povm_residual 1@12 +tol_probability 1@12 +tol_zero_probability 1@9 +tol_schrodinger 1@12 +end acceptance +case_id 890980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1 +acceptance_id d63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f +end diff --git a/research/atemporal/at1/model/tests/test_model.c b/research/atemporal/at1/model/tests/test_model.c new file mode 100644 index 000000000..517543744 --- /dev/null +++ b/research/atemporal/at1/model/tests/test_model.c @@ -0,0 +1,1059 @@ +/* Tests of the AT-1 candidate engine (Agent 3). Portable C11 plus POSIX system() status macros. + * + * build/test_model + * + * 1. Contract worked example (AT1_CASE_V1 section 6): file digest, case_id, acceptance_id, and + * the generator reproduces the file byte for byte. + * 2. Every AT1_SPEC section 13 class: exact tables compared with the engine values in exact + * rational arithmetic (|value - exact| <= written bound), kernel dimension, label status, + * full AT1_RESULT_V1 written with an oracle record built from the exact tables, and the + * verdict (12 checks, outcome, failure codes, expectation_met) compared with section 13. + * 3. Refusals R0..R14 of section 13.5, the 42 inherited AT-0 rows, and charter readings d, e. + * 4. Invariance tests T4..T9 of AT1_SPEC section 9.1; a large N = 64, M = 256 case. + * 5. Tool behaviour: oracle record and provenance checks, ERROR results, CLI exit codes. + * Prints the measured worst error-to-bound ratios used in README.md. */ +#define _POSIX_C_SOURCE 200809L +#include "at1_model.h" + +#include +#include +#include +#include +#include +#include + +static int g_fail = 0, g_pass = 0; +static const char *g_cases, *g_tool; +#define CHECK(cond, ...) do { if (cond) g_pass++; else { g_fail++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0) + +/* measured worst cases over every exact comparison */ +static double g_ratio_p = 0, g_ratio_pauli = 0, g_max_err_p = 0, g_max_err_pauli = 0; +static double g_max_con = 0, g_max_con_bound_ratio = 0, g_max_povm = 0; + +/* ---- text helpers ------------------------------------------------------------------------- */ +typedef struct { char *p; size_t n, cap; } sb; +static void sb_put(sb *b, const char *s) +{ + size_t l = strlen(s); + if (b->n + l + 1 > b->cap) { b->cap = (b->n + l + 1) * 2 + 256; b->p = realloc(b->p, b->cap); if (!b->p) abort(); } + memcpy(b->p + b->n, s, l); b->n += l; b->p[b->n] = 0; +} +static void sb_printf(sb *b, const char *fmt, ...) +{ + char t[8192]; va_list ap; va_start(ap, fmt); vsnprintf(t, sizeof t, fmt, ap); va_end(ap); sb_put(b, t); +} + +static char *read_all(const char *path, size_t *len) +{ + uint8_t *b; size_t n; + if (at1_read_file(path, &b, &n) != AT1_OK) return NULL; + char *s = malloc(n + 1); memcpy(s, b, n); s[n] = 0; free(b); + if (len) *len = n; + return s; +} +static void write_all(const char *path, const char *s, size_t n) +{ + FILE *f = fopen(path, "wb"); if (!f) { printf("cannot write %s\n", path); exit(1); } + fwrite(s, 1, n, f); fclose(f); +} + +/* replace the first line equal to `old` (without LF) by `rep` (zero or more LF-terminated + * lines); returns a malloc'd string or NULL if not found */ +static char *replace_line(const char *text, const char *old, const char *rep) +{ + size_t lo = strlen(old); + for (const char *p = text; *p; ) { + const char *e = strchr(p, '\n'); if (!e) break; + if ((size_t)(e - p) == lo && strncmp(p, old, lo) == 0) { + size_t pre = (size_t)(p - text), rl = strlen(rep), post = strlen(e + 1); + char *r = malloc(pre + rl + post + 1); + memcpy(r, text, pre); memcpy(r + pre, rep, rl); memcpy(r + pre + rl, e + 1, post + 1); + return r; + } + p = e + 1; + } + return NULL; +} +/* the first line that starts with `prefix` */ +static char *line_with_prefix(const char *text, const char *prefix, char *out, size_t cap) +{ + size_t lp = strlen(prefix); + for (const char *p = text; *p; ) { + const char *e = strchr(p, '\n'); if (!e) break; + if (strncmp(p, prefix, lp) == 0) { size_t l = (size_t)(e - p); if (l >= cap) l = cap - 1; memcpy(out, p, l); out[l] = 0; return out; } + p = e + 1; + } + return NULL; +} + +/* recompute case_id and acceptance_id from the blocks present in the text (in place) */ +static void restamp(char *text) +{ + const char *bs = strstr(text, "begin semantic\n"), *es = strstr(text, "\nend semantic\n"); + const char *ba = strstr(text, "begin acceptance\n"), *ea = strstr(text, "\nend acceptance\n"); + char cid[65], aid[65]; + if (bs && es && es > bs) { + at1_tagged_sha256("omega.at1.case.v1", bs, (size_t)(es + 14 - bs), cid); + char *p = strstr(text, "\ncase_id "); if (p && strlen(p + 9) >= 64) memcpy(p + 9, cid, 64); + } + if (ba && ea && ea > ba) { + at1_tagged_sha256("omega.at1.acceptance.v1", ba, (size_t)(ea + 16 - ba), aid); + char *p = strstr(text, "\nacceptance_id "); if (p && strlen(p + 15) >= 64) memcpy(p + 15, aid, 64); + } +} + +/* ---- case generator ------------------------------------------------------------------------ */ +typedef struct { + const char *name; int N; const char *E; const char *h; const char *v[AT1_CLOCK_DIM_MAX]; + const char *ref; const char *psi; const char *tau; const char *w; int M; + const char *control, *target, *expected, *codes, *minbk, *tolz; +} spec; + +static void base_B(spec *s, const char *name) +{ + memset(s, 0, sizeof *s); + s->name = name; s->N = 4; s->E = "-3/2,-1/2,1/2,3/2"; s->h = "0/1,0/1,0/1,1/2"; + s->ref = "t0"; s->psi = "(1/1;0/1),(1/1;0/1)"; s->tau = "1/4"; s->w = "1/1"; s->M = 4; + s->control = "POSITIVE"; s->target = "INTERACTING"; s->expected = "PASS"; s->codes = "none"; + s->minbk = "ESTIMATED"; s->tolz = "1@9"; +} +static const char *RHO = "3/10,0/1,-1/10"; + +static char *gen_case(const spec *s) +{ + sb b = { 0 }; + sb_printf(&b, "OMEGA-AT1-CASE v1\ndomain omega.at1.case.v1\ncontract AT1_CASE_V1\ncase_name %s\n", s->name); + sb_printf(&b, "begin semantic\nmodel_family PAGE_WOOTTERS_FINITE_CLOCKDIAG\nenergy_unit DIMENSIONLESS_HBAR_1\n"); + sb_printf(&b, "clock_dim %d\nclock_energies %s\nsystem_dim 2\nsystem_hamiltonian_pauli %s\ninteraction CLOCK_DIAGONAL_PAULI\n", s->N, s->E, s->h); + for (int j = 0; j < s->N; j++) sb_printf(&b, "interaction_pauli %d %s\n", j, (j < AT1_CLOCK_DIM_MAX && s->v[j]) ? s->v[j] : "0/1,0/1,0/1"); + sb_printf(&b, "constraint SUM_HC_HS_V\nphysical_state NULLSPACE_PROJECTION\nreference_clock_label %s\nreference_system_state %s\n", s->ref, s->psi); + sb_printf(&b, "clock_povm COVARIANT_DISCRETE\npovm_tau_turns %s\npovm_weight %s\nclock_label_count %d\n", s->tau, s->w, s->M); + for (int k = 0; k < s->M; k++) sb_printf(&b, "clock_label %d t%d\n", k, k); + sb_printf(&b, "observables PAULI_X,PAULI_Y,PAULI_Z\nend semantic\nbegin acceptance\n"); + sb_printf(&b, "control_kind %s\nprediction_target %s\nexpected_outcome %s\nexpected_failure_codes %s\nmin_bound_kind %s\n", s->control, s->target, s->expected, s->codes, s->minbk); + sb_printf(&b, "tol_constraint_residual 1@12\ntol_povm_residual 1@12\ntol_probability 1@12\ntol_zero_probability %s\ntol_schrodinger 1@12\nend acceptance\n", s->tolz); + sb_printf(&b, "case_id %064d\nacceptance_id %064d\nend\n", 0, 0); + restamp(b.p); + return b.p; +} + +/* ---- exact table values ------------------------------------------------------------------- */ +/* "a/b", "a", or "~a" / "~b" for 1/2 +- 3 sqrt(3)/16 (N4b, irrational) */ +static int parse_rat(const char *s, bq *out, double *approx) +{ + if (s[0] == '~') { *approx = s[1] == 'a' ? 0.5 + 3.0 * sqrt(3.0) / 16.0 : 0.5 - 3.0 * sqrt(3.0) / 16.0; return 0; } + int neg = s[0] == '-'; if (neg) s++; + const char *sl = strchr(s, '/'); + bn n, d; bn_init(&n); bn_init(&d); + bn_from_digits(&n, s, sl ? (size_t)(sl - s) : strlen(s)); + if (sl) bn_from_digits(&d, sl + 1, strlen(sl + 1)); else bn_set_u64(&d, 1); + if (neg) bn_neg(&n, &n); + bq_set_bn(out, &n, &d); + bn_free(&n); bn_free(&d); + *approx = bq_to_double(out); + return 1; +} + +typedef struct { const char *p[4], *x[4], *y[4], *z[4]; } table4; +static const table4 T_P1 = { { "1/4", "1/4", "1/4", "1/4" }, { "1", "1/2", "0", "1/2" }, { "1/2", "1", "1/2", "0" }, { "1/2", "1/2", "1/2", "1/2" } }; +static const table4 T_P2 = { { "5/28", "1/4", "9/28", "1/4" }, { "49/50", "29/70", "1/10", "29/70" }, { "1/2", "13/14", "1/2", "1/14" }, { "16/25", "26/35", "4/5", "26/35" } }; +static const table4 T_P3 = { { "107/280", "53/280", "5/56", "19/56" }, { "98/107", "37/53", "8/25", "37/95" }, { "65/214", "101/106", "37/50", "17/190" }, { "65/214", "61/106", "9/10", "29/38" } }; +static const table4 T_P3b = { { "41/80", "19/80", "1/80", "19/80" }, { "29/82", "1/38", "1/2", "37/38" }, { "40/41", "10/19", "0", "10/19" }, { "45/82", "25/38", "1/2", "13/38" } }; +static const table4 I_P3b = { { 0 }, { "1/2", "1/2", "1/2", "1/2" }, { "1", "0", "1", "0" }, { "1/2", "1/2", "1/2", "1/2" } }; +static const table4 T_P4 = { { "29/164", "37/164", "53/164", "45/164" }, { "277/290", "197/370", "37/530", "13/50" }, { "17/58", "73/74", "65/106", "1/10" }, { "73/145", "113/185", "193/265", "17/25" } }; +static const table4 I_P4 = { { 0 }, { "9/10", "4/5", "1/10", "1/5" }, { "1/5", "9/10", "4/5", "1/10" }, { "1/2", "1/2", "1/2", "1/2" } }; +static const table4 T_P5 = { { "524181/2096716", "522731/2096716", "524177/2096716", "525627/2096716" }, + { "274763624041/549527248074", "274761527333/548007134774", "274759430625/549523054658", "274761527333/551043167958" }, + { "274004612845/549527248074", "274004612845/548007134774", "275520532729/549523054658", "275520532729/551043167958" }, + { "524180/524181", "522730/522731", "524176/524177", "525626/525627" } }; +static const table4 T_P6 = { { "5/28", "9/28", "5/28", "9/28" }, { "49/50", "1/10", "49/50", "1/10" }, { "1/2", "1/2", "1/2", "1/2" }, { "16/25", "4/5", "16/25", "4/5" } }; +static const table4 T_N3 = { { "1/2", "1/4", "0", "1/4" }, { "1/2", "1/2", NULL, "1/2" }, { "1/2", "1/2", NULL, "1/2" }, { "1", "1", NULL, "1" } }; +static const table4 T_N4a = { { "5/56", "1/8", "9/56", "1/8" }, { "49/50", "29/70", "1/10", "29/70" }, { "1/2", "13/14", "1/2", "1/14" }, { "16/25", "26/35", "4/5", "26/35" } }; +static const table4 T_N4b = { { "5/28", "2/7", "2/7", "5/28" }, { "49/50", "19/80", "19/80", "49/50" }, { "1/2", "~a", "~b", "1/2" }, { "16/25", "31/40", "31/40", "16/25" } }; +static const table4 I_N6 = { { 0 }, { "4/5", "1/2", "1/5", "1/2" }, { "1/2", "4/5", "1/2", "1/5" }, { "9/10", "9/10", "9/10", "9/10" } }; +/* conditioning control (not a section 13 row): one kernel level, psi_0 nearly orthogonal to its vector */ +static const table4 T_C1 = { { "1/4", "1/4", "1/4", "1/4" }, { "1/5", "1/5", "1/5", "1/5" }, { "1/2", "1/2", "1/2", "1/2" }, { "1/10", "1/10", "1/10", "1/10" } }; + +/* |value - exact| <= bound (exact rationals); returns the error and the error/bound ratio */ +static int within(double value, double bound, const char *exact, double *err, double *ratio) +{ + bq e, v, b, d; bq_init(&e); bq_init(&v); bq_init(&b); bq_init(&d); + double approx; int rational = parse_rat(exact, &e, &approx); + char t[400]; at1_bound_format(bound, t, sizeof t); + char *at = strchr(t, '@'); bn bN; bn_init(&bN); bn_from_digits(&bN, t, (size_t)(at - t)); + bq_from_scaled(&b, &bN, (unsigned)atoi(at + 1)); bn_free(&bN); + if (!rational) { /* irrational entry: allow the reference double's own rounding */ + bq_from_double(&e, approx); + bq u; bq_init(&u); bq_from_double(&u, 4 * 1.1102230246251565e-16 * fabs(approx)); bq_add(&b, &b, &u); bq_free(&u); + } + bq_from_double(&v, value); bq_sub(&d, &v, &e); bq_abs(&d, &d); + int ok = bq_cmp(&d, &b) <= 0; + *err = bq_to_double(&d); + *ratio = bound > 0 ? *err / bound : (*err == 0 ? 0 : INFINITY); + bq_free(&e); bq_free(&v); bq_free(&b); bq_free(&d); + return ok; +} +/* 1 - x for a table string, as a string */ +static void one_minus(const char *x, char *out, size_t cap) +{ + if (x[0] == '~') { snprintf(out, cap, "~%c", x[1] == 'a' ? 'b' : 'a'); return; } + bq e, one; bq_init(&e); bq_init(&one); double a; parse_rat(x, &e, &a); bq_set_i64(&one, 1, 1); bq_sub(&e, &one, &e); + /* print as num/den */ + sb b = { 0 }; + bn ten, q, r, cur; bn_init(&ten); bn_init(&q); bn_init(&r); bn_init(&cur); bn_set_u64(&ten, 10); + for (int part = 0; part < 2; part++) { + bn_abs(&cur, part ? &e.den : &e.num); + char dg[128]; int nd = 0; + if (bn_is_zero(&cur)) dg[nd++] = '0'; + while (!bn_is_zero(&cur)) { bn_divmod(&q, &r, &cur, &ten); dg[nd++] = (char)('0' + (r.n ? r.d[0] : 0)); bn_copy(&cur, &q); } + char rev[128]; for (int i = 0; i < nd; i++) rev[i] = dg[nd - 1 - i]; rev[nd] = 0; + if (part == 0 && bn_sign(&e.num) < 0) sb_put(&b, "-"); + sb_put(&b, rev); if (part == 0) sb_put(&b, "/"); + } + snprintf(out, cap, "%s", b.p); free(b.p); + bn_free(&ten); bn_free(&q); bn_free(&r); bn_free(&cur); bq_free(&e); bq_free(&one); +} +static const char *tab_entry(const table4 *t, int k, int q, char *buf, size_t cap) +{ + const char *const *col = q / 2 == 0 ? t->x : q / 2 == 1 ? t->y : t->z; + if (!col[k]) return NULL; + if (q % 2 == 0) return col[k]; + one_minus(col[k], buf, cap); return buf; +} + +/* ---- oracle record and provenance --------------------------------------------------------------- */ +static const char *AX[3] = { "X", "Y", "Z" }, *SG[2] = { "PLUS", "MINUS" }; +static void f64_of(const char *exact, char *out, size_t cap) +{ + bq e; bq_init(&e); double a; parse_rat(exact, &e, &a); bq_free(&e); + at1_f64_format(a, out, cap); +} +/* reference lines from exact tables; status from the exact interacting marginal (0 -> UNDEFINED) */ +static char *oracle_record(const at1_case *c, const table4 *inter, const table4 *ideal, int trivial) +{ + sb b = { 0 }; char v[64], buf[128]; + sb_printf(&b, "case_id %s\nacceptance_id %s\n", c->case_id, c->acceptance_id); + int M = c->label_count, def[AT1_LABEL_MAX]; + for (int k = 0; k < M; k++) { + def[k] = !trivial && strcmp(inter->p[k], "0") != 0; + sb_printf(&b, "reference_label %d %s %s\n", k, c->labels[k], def[k] ? "DEFINED" : "UNDEFINED"); + } + for (int k = 0; k < M; k++) { + if (trivial) { sb_printf(&b, "reference_clock_probability %d undefined 0@0\n", k); continue; } + f64_of(inter->p[k], v, sizeof v); sb_printf(&b, "reference_clock_probability %d %s 1@15\n", k, v); + } + for (int f = 0; f < 2; f++) for (int k = 0; k < M; k++) for (int q = 0; q < 6; q++) { + const char *key = f == 0 ? "reference_ideal" : "reference_interacting"; + const char *e = tab_entry(f == 0 ? ideal : inter, k, q, buf, sizeof buf); + if (f == 1 && (!def[k] || !e)) { sb_printf(&b, "%s %d %s %s undefined 0@0\n", key, k, AX[q / 2], SG[q % 2]); continue; } + f64_of(e, v, sizeof v); sb_printf(&b, "%s %d %s %s %s 1@15\n", key, k, AX[q / 2], SG[q % 2], v); + } + return b.p; +} +static const char *PROV = + "source_repo aien-dev/omega\n" + "source_commit 0123456789abcdef0123456789abcdef01234567\n" + "source_tree_clean YES\n" + "contract_commit ea91d7c0000000000000000000000000000000aa\n" + "engine_sha256 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" + "oracle_repo aien-dev/omega\n" + "oracle_commit cccccccccccccccccccccccccccccccccccccccc\n" + "oracle_sha256 dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\n" + "build_cc cc test harness\n" + "build_flags -std=c11 -O2\n" + "host test host\n" + "run_started_utc 2026-10-09T00:00:00Z\n" + "run_finished_utc 2026-10-09T00:00:01Z\n" + "artifact a/one 1111111111111111111111111111111111111111111111111111111111111111\n" + "artifact b/two 2222222222222222222222222222222222222222222222222222222222222222\n"; + +/* ---- verdict inspection --------------------------------------------------------------------- */ +static void copy_str(char *dst, size_t cap, const char *src) { size_t l = strlen(src); if (l >= cap) l = cap - 1; memcpy(dst, src, l); dst[l] = 0; } +static void verdict_of(const char *res, char checks[13], char *outcome, size_t ocap, char *codes, size_t ccap, char *met, size_t mcap) +{ + int n = 0; char line[1024]; + for (const char *p = strstr(res, "begin verdict\n"); p && *p; ) { + const char *e = strchr(p, '\n'); size_t l = (size_t)(e - p); if (l >= sizeof line) l = sizeof line - 1; + memcpy(line, p, l); line[l] = 0; p = e + 1; + if (strncmp(line, "check ", 6) == 0 && n < 12) { + const char *st = strrchr(line, ' ') + 1; + checks[n++] = st[0] == 'P' ? 'P' : st[0] == 'F' ? 'F' : st[0] == 'I' ? 'I' : 'N'; + } + if (strncmp(line, "outcome ", 8) == 0) copy_str(outcome, ocap, line + 8); + if (strncmp(line, "failure_codes ", 14) == 0) copy_str(codes, ccap, line + 14); + if (strncmp(line, "expectation_met ", 16) == 0) copy_str(met, mcap, line + 16); + if (strcmp(line, "end verdict") == 0) break; + } + checks[n] = 0; +} +/* structure: line count, verdict_id and evidence_digest recomputed */ +static void check_structure(const char *name, const at1_case *c, const char *res, size_t len) +{ + int M = c->label_count, lines = 0; + for (size_t i = 0; i < len; i++) lines += res[i] == '\n'; + int sem = 0, acc = 0; + for (size_t i = 0; i < c->semantic_len; i++) sem += c->semantic_text[i] == '\n'; + for (size_t i = 0; i < c->acceptance_len; i++) acc += c->acceptance_text[i] == '\n'; + int expect = 5 + sem + acc + 3 + 5 + (2 + 3 + 8 * M + 14 * M) + (2 + 12 + 4) + 1 + (2 + 13 + 2) + 2; + CHECK(lines == expect, "%s: %d result lines, expected %d", name, lines, expect); + CHECK(res[len - 1] == '\n' && strstr(res, "\nend\n") == res + len - 5, "%s: result does not end with end", name); + const char *bv = strstr(res, "begin verdict\n"), *ev = strstr(res, "end verdict\n"); + char vid[65], ev2[65], line[200]; + size_t vlen = (size_t)(ev + 12 - bv); + sb pre = { 0 }; sb_printf(&pre, "case_id %s\nacceptance_id %s\n", c->case_id, c->acceptance_id); + char *tmp = malloc(vlen + 1); memcpy(tmp, bv, vlen); tmp[vlen] = 0; sb_put(&pre, tmp); free(tmp); + at1_tagged_sha256("omega.at1.verdict.v1", pre.p, pre.n, vid); free(pre.p); + CHECK(line_with_prefix(res, "verdict_id ", line, sizeof line) && strcmp(line + 11, vid) == 0, "%s: verdict_id", name); + const char *ed = strstr(res, "evidence_digest "); + at1_tagged_sha256("omega.at1.evidence.v1", res, (size_t)(ed - res), ev2); + CHECK(strncmp(ed + 16, ev2, 64) == 0, "%s: evidence_digest", name); + size_t badbyte = len; + for (size_t i = 0; i < len && badbyte == len; i++) if (!(res[i] == '\n' || (res[i] >= 0x20 && res[i] <= 0x7e))) badbyte = i; + CHECK(badbyte == len, "%s: byte outside 0x20..0x7E at offset %zu", name, badbyte); +} + +/* ---- one section-13 case end to end ------------------------------------------------------------ */ +typedef struct { + const char *id; spec s; const table4 *inter, *ideal; int kdim; int trivial; + const char *checks, *outcome, *codes; +} kase; + +static void run_case(const kase *K) +{ + char *text = gen_case(&K->s); + at1_case c; at1_kernel k; at1_values *v = calloc(1, sizeof *v); + at1_status st = at1_case_parse((const uint8_t *)text, strlen(text), &c); + CHECK(st == AT1_OK, "%s: case refused %s", K->id, at1_status_name(st)); + if (st != AT1_OK) { free(text); free(v); return; } + st = at1_kernel_build(&c, &k); + CHECK(st == AT1_OK, "%s: kernel build %d", K->id, st); + if (st != AT1_OK) { at1_case_free(&c); free(text); free(v); return; } + CHECK(k.kernel_dim == K->kdim, "%s: kernel_dim %d expected %d", K->id, k.kernel_dim, K->kdim); + st = at1_compute(&c, &k, 0, v); + CHECK(st == AT1_OK, "%s: compute %d", K->id, st); + CHECK(v->trivial == K->trivial, "%s: trivial %d", K->id, v->trivial); + double err, ratio; char buf[128]; + CHECK(!v->povm.undefined && v->povm.value >= 0, "%s: povm residual written", K->id); + if (v->povm.value < 0.5 && v->povm.value > g_max_povm) g_max_povm = v->povm.value; + if (!K->trivial) { + if (v->constraint.value > g_max_con) g_max_con = v->constraint.value; + if (v->constraint.value / v->constraint.bound > g_max_con_bound_ratio) g_max_con_bound_ratio = v->constraint.value / v->constraint.bound; + CHECK(v->constraint.value <= v->constraint.bound, "%s: constraint residual %.3g above its bound %.3g", K->id, v->constraint.value, v->constraint.bound); + for (int q = 0; q < c.label_count; q++) { + const char *pe = K->inter->p[q]; + int ok = within(v->clock[q].value, v->clock[q].bound, pe, &err, &ratio); + CHECK(ok, "%s: p(%d) = %.17g, exact %s, err %.3g, bound %.3g", K->id, q, v->clock[q].value, pe, err, v->clock[q].bound); + if (ratio > g_ratio_p) g_ratio_p = ratio; + if (err > g_max_err_p) g_max_err_p = err; + at1_label_status want = strcmp(pe, "0") == 0 ? AT1_LABEL_UNDEFINED : AT1_LABEL_DEFINED; + CHECK(v->status[q] == want, "%s: label %d status %d", K->id, q, v->status[q]); + if (want != AT1_LABEL_DEFINED) { + for (int s = 0; s < 6; s++) CHECK(v->pauli[q][s].undefined, "%s: pauli of undefined label %d written", K->id, q); + continue; + } + for (int s = 0; s < 6; s++) { + const char *e = tab_entry(K->inter, q, s, buf, sizeof buf); + ok = within(v->pauli[q][s].value, v->pauli[q][s].bound, e, &err, &ratio); + CHECK(ok, "%s: pauli %d %s %s = %.17g, exact %s, err %.3g, bound %.3g", K->id, q, AX[s / 2], SG[s % 2], v->pauli[q][s].value, e, err, v->pauli[q][s].bound); + if (ratio > g_ratio_pauli) g_ratio_pauli = ratio; + if (err > g_max_err_pauli) g_max_err_pauli = err; + } + } + } else { + CHECK(v->constraint.undefined, "%s: trivial constraint_residual not undefined", K->id); + for (int q = 0; q < c.label_count; q++) CHECK(v->status[q] == AT1_LABEL_UNDEFINED && v->clock[q].undefined, "%s: trivial label %d", K->id, q); + } + char *orec = oracle_record(&c, K->inter, K->ideal, K->trivial); + char *res = NULL; size_t rlen = 0; char errs[256]; + st = at1_result_write(&c, v, orec, strlen(orec), PROV, strlen(PROV), &res, &rlen, errs, sizeof errs); + CHECK(st == AT1_OK, "%s: result write: %s", K->id, errs); + if (st == AT1_OK) { + char checks[13], outcome[64] = "", codes[512] = "", met[32] = ""; + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, K->checks) == 0, "%s: checks %s expected %s", K->id, checks, K->checks); + CHECK(strcmp(outcome, K->outcome) == 0, "%s: outcome %s", K->id, outcome); + CHECK(strcmp(codes, K->codes) == 0, "%s: failure_codes %s expected %s", K->id, codes, K->codes); + CHECK(strcmp(met, "YES") == 0, "%s: expectation_met %s", K->id, met); + check_structure(K->id, &c, res, rlen); + printf("case %-6s kernel_dim %d checks %s outcome %s codes %s expectation_met %s constraint %.3g (bound %.3g)\n", K->id, k.kernel_dim, checks, outcome, codes, met, v->constraint.undefined ? 0.0 : v->constraint.value, v->constraint.undefined ? 0.0 : v->constraint.bound); + } + free(res); free(orec); at1_kernel_free(&k); at1_case_free(&c); free(text); free(v); +} + +static void section13(void) +{ + kase L[32]; int n = 0; +#define NEW(idv, nm) (memset(&L[n], 0, sizeof L[n]), L[n].id = idv, base_B(&L[n].s, nm), &L[n]) + kase *K; + K = NEW("P1a", "at1-p1a-zero-coupling"); K->inter = &T_P1; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P1b", "at1-p1b-zero-coupling-ideal"); K->s.target = "IDEAL"; K->inter = &T_P1; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPPP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P1c", "at1-p1c-spectator"); K->s.target = "IDEAL"; K->s.v[0] = "0/1,0/1,1/2"; K->s.v[3] = RHO; K->inter = &T_P1; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPPP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P2", "at1-kat-rotated-level-n4"); K->s.v[2] = RHO; K->inter = &T_P2; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P3", "at1-p3-every-level"); K->s.N = 3; K->s.E = "-1/2,1/2,3/2"; K->s.v[0] = RHO; K->s.v[1] = "0/1,3/10,-1/10"; K->s.v[2] = "6/5,0/1,2/5"; K->s.w = "3/4"; + K->inter = &T_P3; K->ideal = &T_P1; K->kdim = 3; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P3b", "at1-p3b-degenerate"); K->s.N = 3; K->s.E = "-1/2,0/1,1/2"; K->s.v[1] = "0/1,0/1,-1/2"; K->s.v[2] = RHO; K->s.psi = "(1/1;0/1),(0/1;1/1)"; K->s.tau = "1/2"; K->s.w = "3/4"; + K->inter = &T_P3b; K->ideal = &I_P3b; K->kdim = 4; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P4", "at1-p4-complex-psi-r1"); K->s.v[2] = RHO; K->s.psi = "(1/1;0/1),(3/5;4/5)"; K->s.ref = "t1"; + K->inter = &T_P4; K->ideal = &I_P4; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P5", "at1-p5-large-rationals"); K->s.N = 2; K->s.E = "-524289/1048574,524285/1048574"; K->s.h = "1/524287,0/1,0/1,1/2"; K->s.v[1] = "524175/1048354,724/524177,-1/2"; K->s.w = "1/2"; + K->inter = &T_P5; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + K = NEW("P6", "at1-p6-near-miss"); K->s.v[0] = "0/1,0/1,1/1"; K->s.v[1] = "0/1,0/1,1/1048576"; K->s.v[2] = RHO; + K->inter = &T_P6; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + /* N1 family: the positive cases above with target IDEAL */ + static const char *n1id[6] = { "N1", "N1b", "N1c", "N1d", "N1e", "N1f" }; + static const char *n1nm[6] = { "at1-n1-p2-ideal", "at1-n1b-p3-ideal", "at1-n1c-p3b-ideal", "at1-n1d-p4-ideal", "at1-n1e-p5-ideal", "at1-n1f-p6-ideal" }; + for (int i = 0; i < 6; i++) { + L[n] = L[3 + i]; L[n].id = n1id[i]; L[n].s.name = n1nm[i]; L[n].s.target = "IDEAL"; L[n].s.control = "NEGATIVE"; L[n].s.expected = "FAIL"; + L[n].s.codes = "SCHRODINGER_DEVIATION_EXCEEDED"; L[n].checks = "PPPPPPPPPFPP"; L[n].outcome = "FAIL"; L[n].codes = "SCHRODINGER_DEVIATION_EXCEEDED"; n++; + } + const char *TRIV = "PPFNPNNNNNNN"; + K = NEW("N2", "at1-n2-all-out"); K->s.v[1] = "0/1,0/1,1/2"; K->s.v[2] = "0/1,0/1,1/2"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "TRIVIAL_PHYSICAL_STATE"; + K->inter = &T_P1; K->ideal = &T_P1; K->kdim = 0; K->trivial = 1; K->checks = TRIV; K->outcome = "FAIL"; K->codes = "TRIVIAL_PHYSICAL_STATE"; n++; + K = NEW("N3", "at1-n3-zero-marginal"); K->s.v[2] = "0/1,0/1,-1/1"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "CONDITIONAL_UNDEFINED"; + K->inter = &T_N3; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPFPNP"; K->outcome = "FAIL"; K->codes = "CONDITIONAL_UNDEFINED"; n++; + K = NEW("N4a", "at1-n4a-wrong-weight"); K->s.v[2] = RHO; K->s.w = "1/2"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "POVM_NORMALIZATION_EXCEEDED,PROBABILITY_SUM_EXCEEDED"; + K->inter = &T_N4a; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPFFPPPPNP"; K->outcome = "FAIL"; K->codes = "POVM_NORMALIZATION_EXCEEDED,PROBABILITY_SUM_EXCEEDED"; n++; + /* N4b: target INTERACTING, so reference_ideal does not enter the verdict (P1's column is written) */ + K = NEW("N4b", "at1-n4b-broken-clock"); K->s.v[2] = RHO; K->s.tau = "1/3"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "POVM_NORMALIZATION_EXCEEDED,PROBABILITY_SUM_EXCEEDED"; + K->inter = &T_N4b; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPFFPPPPNP"; K->outcome = "FAIL"; K->codes = "POVM_NORMALIZATION_EXCEEDED,PROBABILITY_SUM_EXCEEDED"; n++; + K = NEW("N5", "at1-n5-precision-demand"); K->s.v[2] = RHO; K->s.minbk = "RIGOROUS"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "BOUND_KIND_INSUFFICIENT"; + K->inter = &T_P2; K->ideal = &T_P1; K->kdim = 2; K->checks = "FPPPPPPPPPNP"; K->outcome = "FAIL"; K->codes = "BOUND_KIND_INSUFFICIENT"; n++; + K = NEW("N6", "at1-n6-zero-projection"); K->s.v[1] = "0/1,0/1,1/2"; K->s.v[2] = RHO; K->s.psi = "(3/1;0/1),(1/1;0/1)"; K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "TRIVIAL_PHYSICAL_STATE"; + K->inter = &T_P1; K->ideal = &I_N6; K->kdim = 1; K->trivial = 1; K->checks = TRIV; K->outcome = "FAIL"; K->codes = "TRIVIAL_PHYSICAL_STATE"; n++; + /* f^dagger psi_0 = 3/1048575: Psi is 1e-6 of psi_0, a cancellation trap for P_0 applied in binary64 */ + K = NEW("C1", "at1-c1-near-orthogonal-psi"); K->s.v[1] = "0/1,0/1,1/2"; K->s.v[2] = RHO; K->s.psi = "(3/1;0/1),(1048576/1048575;0/1)"; + K->inter = &T_C1; K->ideal = &T_P1; K->kdim = 1; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + /* energy shift +1000 cancelled by h0 = -1000: the matrix entries stay small, so P2 must still PASS */ + K = NEW("C2", "at1-c2-shifted-energies"); K->s.E = "1997/2,1999/2,2001/2,2003/2"; K->s.h = "-1000/1,0/1,0/1,1/2"; K->s.v[2] = RHO; + K->inter = &T_P2; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPPPPPPPPNP"; K->outcome = "PASS"; K->codes = "none"; n++; + /* declared limit: a kernel level with |E_j + h0| = R_j = 1025/2 on the rotated axis (3/5, 0, 4/5), so + * |H_total| acting on Psi has row sums near 1230 and the binary64 residual bound (about 48 eps times + * that) exceeds tol_constraint_residual: check 4 is INDETERMINATE. Same chi_k as P2, same table. */ + K = NEW("C3", "at1-c3-large-level-norm"); K->s.N = 2; K->s.E = "-1/2,1025/2"; K->s.v[1] = "615/2,0/1,819/2"; K->s.w = "1/2"; + K->s.control = "NEGATIVE"; K->s.expected = "FAIL"; K->s.codes = "PRECISION_INSUFFICIENT"; + K->inter = &T_P2; K->ideal = &T_P1; K->kdim = 2; K->checks = "PPPIPPPPPPNP"; K->outcome = "FAIL"; K->codes = "PRECISION_INSUFFICIENT"; n++; +#undef NEW + for (int i = 0; i < n; i++) run_case(&L[i]); + /* N4b povm_residual = sqrt(42)/4, N4a = 1 */ + for (int i = 0; i < n; i++) { + if (strcmp(L[i].id, "N4a") && strcmp(L[i].id, "N4b")) continue; + char *t = gen_case(&L[i].s); at1_case c; at1_kernel k; at1_values v; + at1_case_parse((const uint8_t *)t, strlen(t), &c); at1_kernel_build(&c, &k); at1_compute(&c, &k, 0, &v); + double want = L[i].id[2] == 'a' ? 1.0 : sqrt(42.0) / 4.0; + CHECK(fabs(v.povm.value - want) <= v.povm.bound + 4e-16 * want, "%s: povm_residual %.17g expected %.17g", L[i].id, v.povm.value, want); + at1_kernel_free(&k); at1_case_free(&c); free(t); + } +} + +/* ---- worked example ------------------------------------------------------------------------- */ +static char *g_kat; +static void kat(void) +{ + char path[1024]; size_t len; + snprintf(path, sizeof path, "%s/at1-kat-rotated-level-n4.case", g_cases); + g_kat = read_all(path, &len); + CHECK(g_kat != NULL, "cannot read %s", path); + if (!g_kat) exit(1); + char h[65]; at1_sha256_hex((const uint8_t *)g_kat, len, h); + CHECK(strcmp(h, "76e282fecf21025c9dd675378244e90ff192822a4c49d6cb812c9fe84b3f9ba4") == 0, "KAT file sha256 %s", h); + at1_case c; + at1_status st = at1_case_parse((const uint8_t *)g_kat, len, &c); + CHECK(st == AT1_OK, "KAT refused %s", at1_status_name(st)); + CHECK(strcmp(c.case_id, "890980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1") == 0, "KAT case_id"); + CHECK(strcmp(c.acceptance_id, "d63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f") == 0, "KAT acceptance_id"); + CHECK(strcmp(c.case_file_sha256, h) == 0, "KAT case_file_sha256"); + at1_case_free(&c); + spec s; base_B(&s, "at1-kat-rotated-level-n4"); s.v[2] = RHO; + char *g = gen_case(&s); + CHECK(strcmp(g, g_kat) == 0, "generator does not reproduce the contract example byte for byte"); + free(g); +} + +/* ---- refusals ----------------------------------------------------------------------------- */ +typedef struct { const char *id; const char *old[3]; const char *rep[3]; int no_restamp; at1_status code; } refusal; + +static void expect_refusal(const char *id, const char *text, size_t len, at1_status code) +{ + at1_case c; + at1_status st = at1_case_parse((const uint8_t *)text, len, &c); + CHECK(st == code, "%s: got %s expected %s", id, at1_status_name(st), at1_status_name(code)); + if (st == AT1_OK) at1_case_free(&c); +} + +static int refusals(void) +{ + const at1_status P = AT1_CASE_PARSE_ERROR, NC = AT1_CASE_NONCANONICAL, UV = AT1_CASE_UNSUPPORTED_VERSION, + IP = AT1_CASE_INVALID_PARAMETER, IR = AT1_CASE_IRRATIONAL_SPECTRUM, ID = AT1_CASE_ID_MISMATCH; + const char *L2 = "interaction_pauli 2 3/10,0/1,-1/10", *L1 = "interaction_pauli 1 0/1,0/1,0/1"; + const char *CID = "case_id 890980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1"; + const char *AID = "acceptance_id d63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f"; + const refusal R[] = { + /* AT1_SPEC section 13.5 */ + { "R0", { "system_dim 2" }, { "" }, 0, P }, + { "R1", { "povm_tau_turns 1/4" }, { "povm_tau_turns 2/8\n" }, 0, NC }, + { "R2", { "OMEGA-AT1-CASE v1" }, { "OMEGA-AT1-CASE v2\n" }, 0, UV }, + { "R2b", { "domain omega.at1.case.v1" }, { "domain omega.at1.case.v2\n" }, 0, UV }, + { "R2c", { "contract AT1_CASE_V1" }, { "contract AT1_CASE_V2\n" }, 0, UV }, + { "R4", { L2 }, { "interaction_pauli 2 1/2,0/1,-1/10\n" }, 0, IR }, + { "R5", { CID }, { "case_id 990980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1\n" }, 1, ID }, + { "R5b", { AID }, { "acceptance_id e63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f\n" }, 1, ID }, + { "R6", { "expected_outcome PASS" }, { "expected_outcome FAIL\n" }, 0, IP }, + { "R6b", { "expected_outcome PASS", "control_kind POSITIVE", "expected_failure_codes none" }, { "expected_outcome FAIL\n", "control_kind NEGATIVE\n", "expected_failure_codes FOO_BAR\n" }, 0, IP }, + { "R7", { "interaction_pauli 3 0/1,0/1,0/1" }, { "" }, 0, P }, + { "R8", { L2, L1, "XX" }, { "XX\n", "interaction_pauli 2 3/10,0/1,-1/10\n", "interaction_pauli 1 0/1,0/1,0/1\n" }, 0, P }, + { "R9", { "interaction CLOCK_DIAGONAL_PAULI" }, { "interaction NONE\n" }, 0, P }, + { "R10", { "model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG" }, { "model_family PAGE_WOOTTERS_FINITE_IDEAL\n" }, 0, P }, + { "R11", { "constraint SUM_HC_HS_V" }, { "constraint SUM_HC_HS\n" }, 0, P }, + { "R12", { "prediction_target INTERACTING" }, { "prediction_target BOTH\n" }, 0, P }, + { "R12b", { "prediction_target INTERACTING" }, { "" }, 0, P }, + { "R13", { "interaction_pauli 0 0/1,0/1,0/1" }, { "interaction_pauli 0 2/10,0/1,0/1\n" }, 0, NC }, + { "R14", { "interaction_pauli 0 0/1,0/1,0/1" }, { "interaction_pauli 0 1048577/1,0/1,0/1\n" }, 0, IP }, + /* charter readings d and e */ + { "d-at0-header", { "OMEGA-AT1-CASE v1" }, { "OMEGA-AT0-CASE v1\n" }, 0, P }, + { "d-at0-domain", { "domain omega.at1.case.v1" }, { "domain omega.at0.case.v1\n" }, 0, UV }, + { "e-index-01", { L1 }, { "interaction_pauli 01 0/1,0/1,0/1\n" }, 0, NC }, + { "e-index-x", { L1 }, { "interaction_pauli x 0/1,0/1,0/1\n" }, 0, P }, + { "e-index-5", { L1 }, { "interaction_pauli 5 0/1,0/1,0/1\n" }, 0, P }, + { "e-label-01", { "clock_label 1 t1" }, { "clock_label 01 t1\n" }, 0, NC }, + /* inherited AT-0 rows (omega bacc4b6 MANIFEST.tsv), re-expressed on P2 */ + { "R08-tab", { "clock_dim 4" }, { "clock_dim\t4\n" }, 0, P }, + { "R09-blank-line", { "begin semantic" }, { "begin semantic\n\n" }, 0, P }, + { "R10-trailing-space", { "system_dim 2" }, { "system_dim 2 \n" }, 0, P }, + { "R11-double-space", { "system_dim 2" }, { "system_dim 2\n" }, 0, P }, + { "R12-missing-key", { "interaction CLOCK_DIAGONAL_PAULI" }, { "" }, 0, P }, + { "R13-unknown-key", { "interaction CLOCK_DIAGONAL_PAULI" }, { "interaction CLOCK_DIAGONAL_PAULI\nfoo bar\n" }, 0, P }, + { "R14-duplicate-key", { "interaction CLOCK_DIAGONAL_PAULI" }, { "interaction CLOCK_DIAGONAL_PAULI\ninteraction CLOCK_DIAGONAL_PAULI\n" }, 0, P }, + { "R15-out-of-order", { "interaction CLOCK_DIAGONAL_PAULI", "constraint SUM_HC_HS_V" }, { "", "constraint SUM_HC_HS_V\ninteraction CLOCK_DIAGONAL_PAULI\n" }, 0, P }, + { "R16-float-text", { "povm_tau_turns 1/4" }, { "povm_tau_turns 0.25\n" }, 0, P }, + { "R19-label-uppercase", { "clock_label 0 t0", "reference_clock_label t0" }, { "clock_label 0 T0\n", "reference_clock_label T0\n" }, 0, P }, + { "R31-control-kind-bad", { "control_kind POSITIVE" }, { "control_kind MAYBE\n" }, 0, P }, + { "R32-case-name-two-tokens", { "case_name at1-kat-rotated-level-n4" }, { "case_name at1 kat\n" }, 0, P }, + { "R35-trailing-line", { "end" }, { "end\nextra\n" }, 0, P }, + { "R36-label-count-mismatch", { "clock_label_count 4" }, { "clock_label_count 5\n" }, 0, P }, + { "R37-model-family-bad", { "model_family PAGE_WOOTTERS_FINITE_CLOCKDIAG" }, { "model_family PAGE_WOOTTERS_INTERACTING\n" }, 0, P }, + { "R01-noncanonical-rational", { "povm_weight 1/1" }, { "povm_weight 2/2\n" }, 0, NC }, + { "R17-noncanonical-integer", { "clock_dim 4" }, { "clock_dim 04\n" }, 0, NC }, + { "R18-noncanonical-scaled", { "tol_probability 1@12" }, { "tol_probability 10@13\n" }, 0, NC }, + { "R30-negative-zero", { "system_hamiltonian_pauli 0/1,0/1,0/1,1/2" }, { "system_hamiltonian_pauli -0/1,0/1,0/1,1/2\n" }, 0, NC }, + { "R02-header-v2", { "OMEGA-AT1-CASE v1" }, { "OMEGA-AT1-CASE v2\n" }, 0, UV }, + { "R24-wrong-domain", { "domain omega.at1.case.v1" }, { "domain omega.at1.case.v2\n" }, 0, UV }, + { "R25-wrong-contract", { "contract AT1_CASE_V1" }, { "contract AT1_CASE_V2\n" }, 0, UV }, + { "R20-energies-not-increasing", { "clock_energies -3/2,-1/2,1/2,3/2" }, { "clock_energies -1/2,-3/2,1/2,3/2\n" }, 0, IP }, + { "R21-psi-zero", { "reference_system_state (1/1;0/1),(1/1;0/1)" }, { "reference_system_state (0/1;0/1),(0/1;0/1)\n" }, 0, IP }, + { "R22-tau-zero", { "povm_tau_turns 1/4" }, { "povm_tau_turns 0/1\n" }, 0, IP }, + { "R23-weight-negative", { "povm_weight 1/1" }, { "povm_weight -1/1\n" }, 0, IP }, + { "R27-rational-over-limit", { "clock_energies -3/2,-1/2,1/2,3/2" }, { "clock_energies -1048577/1,-1/2,1/2,3/2\n" }, 0, IP }, + { "R28-duplicate-label", { "clock_label 2 t2" }, { "clock_label 2 t1\n" }, 0, IP }, + { "R29-ref-label-missing", { "reference_clock_label t0" }, { "reference_clock_label t9\n" }, 0, IP }, + { "R39-huge-digits-tau", { "povm_tau_turns 1/4" }, { "povm_tau_turns 340282366920938463463374607431768211457/4\n" }, 0, IP }, + { "R06-codes-with-pass", { "expected_failure_codes none" }, { "expected_failure_codes TRIVIAL_PHYSICAL_STATE\n" }, 0, IP }, + { "R06b-codes-unsorted", { "expected_outcome PASS", "control_kind POSITIVE", "expected_failure_codes none" }, { "expected_outcome FAIL\n", "control_kind NEGATIVE\n", "expected_failure_codes PROBABILITY_SUM_EXCEEDED,POVM_NORMALIZATION_EXCEEDED\n" }, 0, IP }, + { "R06c-codes-unknown", { "expected_outcome PASS", "control_kind POSITIVE", "expected_failure_codes none" }, { "expected_outcome FAIL\n", "control_kind NEGATIVE\n", "expected_failure_codes FOO_BAR\n" }, 0, IP }, + { "R06d-fail-without-codes", { "expected_outcome PASS", "control_kind POSITIVE" }, { "expected_outcome FAIL\n", "control_kind NEGATIVE\n" }, 0, IP }, + { "R04-irrational-spectrum", { "system_hamiltonian_pauli 0/1,0/1,0/1,1/2" }, { "system_hamiltonian_pauli 0/1,1/1,0/1,1/1\n" }, 0, IR }, + { "R05-wrong-case-id", { CID }, { "case_id 790980a43bd189494c2c922d2bf0049cbffb07f1090f578e04e1142aee7525f1\n" }, 1, ID }, + { "R38-acceptance-id-wrong", { AID }, { "acceptance_id c63246c391296c6cd381f1b654cc625be9f453c77c27c68d9eac240efd5b4d8f\n" }, 1, ID }, + }; + int count = 0; + for (size_t i = 0; i < sizeof R / sizeof R[0]; i++) { + char *t = strdup(g_kat); + for (int e = 0; e < 3 && R[i].old[e]; e++) { + char *u = replace_line(t, R[i].old[e], R[i].rep[e]); + CHECK(u != NULL, "%s: edit %d did not apply", R[i].id, e); + if (u) { free(t); t = u; } + } + if (!R[i].no_restamp) restamp(t); + expect_refusal(R[i].id, t, strlen(t), R[i].code); + free(t); count++; + } + /* byte-level rows */ + size_t n = strlen(g_kat); + sb crlf = { 0 }; + for (size_t i = 0; i < n; i++) { if (g_kat[i] == '\n') sb_put(&crlf, "\r\n"); else { char ch[2] = { g_kat[i], 0 }; sb_put(&crlf, ch); } } + expect_refusal("R07-crlf", crlf.p, crlf.n, P); free(crlf.p); count++; + expect_refusal("R33-missing-final-lf", g_kat, n - 1, P); count++; + expect_refusal("R34-empty", "", 0, P); count++; + /* R3, R3b, R26, R03: clock_dim 65 and 1 with matching energy and coupling lines */ + spec s; base_B(&s, "at1-kat-rotated-level-n4"); s.v[2] = RHO; + sb e65 = { 0 }; + for (int j = 0; j < 65; j++) sb_printf(&e65, "%s%d/1", j ? "," : "", j - 32); + s.N = 65; s.E = e65.p; s.v[2] = NULL; + { char *g = gen_case(&s); expect_refusal("R3-clock-dim-65", g, strlen(g), IP); free(g); count++; } + free(e65.p); + base_B(&s, "at1-kat-rotated-level-n4"); s.N = 1; s.E = "-1/2"; + { char *g = gen_case(&s); expect_refusal("R3b-clock-dim-1", g, strlen(g), IP); free(g); count++; } + /* a token over the engine's digit limit is an engine error, not a refusal */ + { + sb big = { 0 }; sb_put(&big, "povm_tau_turns 1"); + for (int i = 0; i < 4999; i++) sb_put(&big, "0"); + sb_put(&big, "1"); + sb_put(&big, "/4\n"); + char *t = replace_line(g_kat, "povm_tau_turns 1/4", big.p); restamp(t); + expect_refusal("engine-limit-digits", t, strlen(t), AT1_ERR_RESOURCE); free(t); free(big.p); + } + return count; +} + +/* ---- invariance tests (AT1_SPEC section 9.1) ---------------------------------------------------- */ +static int values_of(const spec *s, int reversed, at1_values *v, at1_case *c_out) +{ + char *t = gen_case(s); at1_case c; at1_kernel k; + at1_status st = at1_case_parse((const uint8_t *)t, strlen(t), &c); free(t); + if (st != AT1_OK) return 0; + if (at1_kernel_build(&c, &k) != AT1_OK) { at1_case_free(&c); return 0; } + memset(v, 0, sizeof *v); + st = at1_compute(&c, &k, reversed, v); + at1_kernel_free(&k); + if (c_out) *c_out = c; else at1_case_free(&c); + return st == AT1_OK; +} +static int close_val(const at1_val *a, const at1_val *b) +{ + if (a->undefined || b->undefined) return a->undefined == b->undefined; + return fabs(a->value - b->value) <= a->bound + b->bound; +} +/* every value of a equals the value of b at label k + shift, within the summed bounds */ +static int same_values(const at1_values *a, const at1_values *b, int shift, int from, int to) +{ + for (int k = from; k < to; k++) { + if (a->status[k] != b->status[k + shift] || !close_val(&a->clock[k], &b->clock[k + shift])) return 0; + for (int q = 0; q < 6; q++) if (!close_val(&a->pauli[k][q], &b->pauli[k + shift][q])) return 0; + } + return 1; +} +static void invariance(void) +{ + at1_values *a = calloc(1, sizeof *a), *b = calloc(1, sizeof *b); + spec p2; base_B(&p2, "at1-t-p2"); p2.v[2] = RHO; + spec p4 = p2; p4.psi = "(1/1;0/1),(3/5;4/5)"; p4.ref = "t1"; + const spec *base[2] = { &p2, &p4 }; + for (int i = 0; i < 2; i++) { + CHECK(values_of(base[i], 0, a, NULL), "T: base %d", i); + /* T4: psi_0 -> i psi_0 */ + spec s = *base[i]; s.psi = i == 0 ? "(0/1;1/1),(0/1;1/1)" : "(0/1;1/1),(-4/5;3/5)"; + CHECK(values_of(&s, 0, b, NULL) && same_values(a, b, 0, 0, 4), "T4 phase invariance (base %d)", i); + /* T5: psi_0 -> 2 psi_0 */ + s = *base[i]; s.psi = i == 0 ? "(2/1;0/1),(2/1;0/1)" : "(2/1;0/1),(6/5;8/5)"; + CHECK(values_of(&s, 0, b, NULL) && same_values(a, b, 0, 0, 4), "T5 scale invariance (base %d)", i); + /* T6: purity of each rho_k: |Bloch|^2 = 1 */ + for (int k = 0; k < 4; k++) { + double x = 2 * a->pauli[k][0].value - 1, y = 2 * a->pauli[k][2].value - 1, z = 2 * a->pauli[k][4].value - 1; + double tol = 6 * (a->pauli[k][0].bound + a->pauli[k][2].bound + a->pauli[k][4].bound); + CHECK(fabs(x * x + y * y + z * z - 1) <= tol, "T6 purity k=%d (base %d): %.3g", k, i, x * x + y * y + z * z - 1); + } + /* T8: reversed label order, bit-identical */ + CHECK(values_of(base[i], 1, b, NULL) && memcmp(a, b, sizeof *a) == 0, "T8 reversed order not bit-identical (base %d)", i); + /* T9: run twice, bit-identical */ + CHECK(values_of(base[i], 0, b, NULL) && memcmp(a, b, sizeof *a) == 0, "T9 second run not bit-identical (base %d)", i); + } + /* T7: shifting r by one shifts the labels by one (values depend on k - r) */ + spec r1 = p2; r1.ref = "t1"; + CHECK(values_of(&p2, 0, a, NULL) && values_of(&r1, 0, b, NULL) && same_values(a, b, 1, 0, 3), "T7 reference shift"); + free(a); free(b); +} + +/* ---- large case: N = 64, M = 256 ------------------------------------------------------------- */ +static void large(void) +{ + spec s; base_B(&s, "at1-large-n64-m256"); + sb e = { 0 }; + for (int j = 0; j < 64; j++) { + int num = j - 32; /* E_j = (j - 32)/2 */ + if (num % 2 == 0) sb_printf(&e, "%s%d/1", j ? "," : "", num / 2); else sb_printf(&e, "%s%d/2", j ? "," : "", num); + } + s.N = 64; s.E = e.p; s.v[33] = RHO; s.v[40] = "0/1,0/1,1/2"; s.tau = "1/128"; s.w = "1/4"; s.M = 256; + at1_values *v = calloc(1, sizeof *v); at1_case c; + int ok = values_of(&s, 0, v, &c); + CHECK(ok, "large case did not run"); + if (!ok) { free(e.p); free(v); return; } + CHECK(v->kernel_dim == 2 && !v->trivial, "large: kernel_dim %d", v->kernel_dim); + double sum = 0; for (int k = 0; k < 256; k++) sum += v->clock[k].value; + /* oracle record mirroring the engine's own values: exercises the writer and judge at M = 256 */ + sb o = { 0 }; char f[64]; + sb_printf(&o, "case_id %s\n", c.case_id); + for (int k = 0; k < 256; k++) sb_printf(&o, "reference_label %d t%d %s\n", k, k, v->status[k] == AT1_LABEL_DEFINED ? "DEFINED" : "UNDEFINED"); + for (int k = 0; k < 256; k++) { at1_f64_format(v->clock[k].value, f, sizeof f); sb_printf(&o, "reference_clock_probability %d %s 1@15\n", k, f); } + for (int fam = 0; fam < 2; fam++) for (int k = 0; k < 256; k++) for (int q = 0; q < 6; q++) { + if (v->pauli[k][q].undefined) { sb_printf(&o, "%s %d %s %s undefined 0@0\n", fam ? "reference_interacting" : "reference_ideal", k, AX[q / 2], SG[q % 2]); continue; } + at1_f64_format(v->pauli[k][q].value, f, sizeof f); + sb_printf(&o, "%s %d %s %s %s 1@15\n", fam ? "reference_interacting" : "reference_ideal", k, AX[q / 2], SG[q % 2], f); + } + char *res; size_t rl; char err[256]; + at1_status st = at1_result_write(&c, v, o.p, o.n, PROV, strlen(PROV), &res, &rl, err, sizeof err); + CHECK(st == AT1_OK, "large: result write %s", err); + if (st == AT1_OK) { + char checks[13], outcome[64], codes[512], met[32]; + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, "PPPPPPPPPPNP") == 0 && strcmp(outcome, "PASS") == 0, "large: checks %s outcome %s codes %s", checks, outcome, codes); + check_structure("large", &c, res, rl); + printf("case large N=64 M=256 kernel_dim %d sum p - 1 = %.3g constraint %.3g (bound %.3g) povm %.3g (bound %.3g) checks %s\n", + v->kernel_dim, sum - 1, v->constraint.value, v->constraint.bound, v->povm.value, v->povm.bound, checks); + free(res); + } + free(o.p); free(e.p); free(v); at1_case_free(&c); +} + +/* ---- oracle record, provenance, ERROR results ------------------------------------------------- */ +/* rewrite label k of an oracle record consistently: its status, its clock line and its six + * reference_interacting lines (undefined unless the new status is DEFINED) */ +static char *label_edit(const char *o, int k, const char *status, const char *clock) +{ + char pre[96], old[256], rep[256], *cur = strdup(o), *u; + snprintf(pre, sizeof pre, "reference_label %d ", k); + if (line_with_prefix(cur, pre, old, sizeof old)) { snprintf(rep, sizeof rep, "reference_label %d t%d %s\n", k, k, status); u = replace_line(cur, old, rep); free(cur); cur = u; } + snprintf(pre, sizeof pre, "reference_clock_probability %d ", k); + if (line_with_prefix(cur, pre, old, sizeof old)) { snprintf(rep, sizeof rep, "reference_clock_probability %d %s\n", k, clock); u = replace_line(cur, old, rep); free(cur); cur = u; } + for (int q = 0; q < 6 && strcmp(status, "DEFINED") != 0; q++) { + snprintf(pre, sizeof pre, "reference_interacting %d %s %s ", k, AX[q / 2], SG[q % 2]); + if (line_with_prefix(cur, pre, old, sizeof old)) { snprintf(rep, sizeof rep, "%sundefined 0@0\n", pre); u = replace_line(cur, old, rep); free(cur); cur = u; } + } + return cur; +} +static char *(*g_mut)(const char *) = NULL; /* optional whole-record edit inside verdict_with */ +static void verdict_with(const char *id, const spec *s, const table4 *inter, const table4 *ideal, const char *old, const char *rep, + const char *prov, const char *want_checks, const char *want_codes, const char *want_met, at1_status want_st) +{ + at1_values *v = calloc(1, sizeof *v); at1_case c; + if (!values_of(s, 0, v, &c)) { CHECK(0, "%s: did not run", id); free(v); return; } + char *o = oracle_record(&c, inter, ideal, 0); + if (g_mut) { char *u = g_mut(o); free(o); o = u; } + if (old) { char *u = replace_line(o, old, rep); CHECK(u != NULL, "%s: edit did not apply", id); if (u) { free(o); o = u; } } + char *res = NULL; size_t rl = 0; char err[256] = ""; + at1_status st = at1_result_write(&c, v, o, strlen(o), prov, strlen(prov), &res, &rl, err, sizeof err); + CHECK(st == want_st, "%s: status %d (%s)", id, st, err); + if (st == AT1_OK && want_checks) { + char checks[13], outcome[64], codes[512], met[32]; + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, want_checks) == 0 && strcmp(codes, want_codes) == 0 && strcmp(met, want_met) == 0, + "%s: checks %s codes %s met %s", id, checks, codes, met); + } + free(res); free(o); free(v); at1_case_free(&c); +} + +static char *mut_label1_undefined(const char *o) { return label_edit(o, 1, "UNDEFINED", "f64:0000000000000000 1@15"); } +static char *mut_label1_indeterminate(const char *o) +{ + char f[64], cl[96]; at1_f64_format(1e-9, f, sizeof f); snprintf(cl, sizeof cl, "%s 1@15", f); + return label_edit(o, 1, "INDETERMINATE", cl); +} +static char *mut_oracle_trivial(const char *o) +{ + char *cur = strdup(o), *u; + for (int k = 0; k < 4; k++) { u = label_edit(cur, k, "UNDEFINED", "undefined 0@0"); free(cur); cur = u; } + return cur; +} +static char *mut_one_clock_undefined(const char *o) { return label_edit(o, 1, "UNDEFINED", "undefined 0@0"); } +static char *mut_status_rule_broken(const char *o) +{ + char f[64], cl[96]; f64_of("1/4", f, sizeof f); snprintf(cl, sizeof cl, "%s 1@15", f); + return label_edit(o, 1, "UNDEFINED", cl); /* clock 1/4 says DEFINED */ +} +static char *mut_all_undefined(const char *o) +{ + /* every value line undefined, every label DEFINED (the review's PASS reproducer) */ + sb b = { 0 }; char line[512]; + for (const char *p = o; *p; ) { + const char *e = strchr(p, '\n'); size_t l = (size_t)(e - p); + if (l >= sizeof line) l = sizeof line - 1; + memcpy(line, p, l); line[l] = 0; p = e + 1; + int nt = 0; for (char *q = line; *q; q++) nt += *q == ' '; + if (strncmp(line, "reference_clock_probability ", 28) == 0 || strncmp(line, "reference_ideal ", 16) == 0 + || strncmp(line, "reference_interacting ", 22) == 0) { + char *sp = line; for (int s = 0; s < nt - 1; s++) sp = strchr(sp, ' ') + 1; + strcpy(sp, "undefined 0@0"); + } + sb_printf(&b, "%s\n", line); + } + return b.p; +} +static void tool_rules(void) +{ + spec p2; base_B(&p2, "at1-kat-rotated-level-n4"); p2.v[2] = RHO; + spec n1 = p2; n1.target = "IDEAL"; n1.control = "NEGATIVE"; n1.expected = "FAIL"; n1.codes = "SCHRODINGER_DEVIATION_EXCEEDED"; + char f[64], line[256]; + /* label status disagreement: check 12 FAIL */ + g_mut = mut_label1_undefined; + verdict_with("oracle-status-disagree", &p2, &T_P2, &T_P1, NULL, NULL, PROV, "PPPPPPPPPPNF", "ORACLE_DISAGREEMENT", "NO", AT1_OK); + g_mut = mut_label1_indeterminate; + verdict_with("oracle-status-indeterminate", &p2, &T_P2, &T_P1, NULL, NULL, PROV, "PPPPPPPPPPNI", "PRECISION_INSUFFICIENT", "NO", AT1_OK); + /* a consistent trivial-shape oracle record against a nontrivial engine: every label disagrees */ + g_mut = mut_oracle_trivial; + verdict_with("oracle-trivial-shape", &p2, &T_P2, &T_P1, NULL, NULL, PROV, "PPPPPPPPPNNF", "ORACLE_DISAGREEMENT", "NO", AT1_OK); + /* undefined placement and the status rule are enforced on the oracle record (review finding 1) */ + g_mut = mut_one_clock_undefined; + verdict_with("oracle-one-clock-undefined", &p2, &T_P2, &T_P1, NULL, NULL, PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + g_mut = mut_status_rule_broken; + verdict_with("oracle-status-rule-broken", &p2, &T_P2, &T_P1, NULL, NULL, PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + g_mut = mut_all_undefined; + verdict_with("oracle-all-undefined", &p2, &T_P2, &T_P1, NULL, NULL, PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + g_mut = NULL; + verdict_with("oracle-status-without-lines", &p2, &T_P2, &T_P1, "reference_label 1 t1 DEFINED", "reference_label 1 t1 UNDEFINED\n", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + { + char a[64], l1[160], l2[160]; + f64_of("1", a, sizeof a); snprintf(l1, sizeof l1, "reference_ideal 0 X PLUS %s 1@15", a); + verdict_with("oracle-ideal-undefined", &p2, &T_P2, &T_P1, l1, "reference_ideal 0 X PLUS undefined 0@0\n", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + f64_of("49/50", a, sizeof a); snprintf(l2, sizeof l2, "reference_interacting 0 X PLUS %s 1@15", a); + verdict_with("oracle-interacting-undefined", &p2, &T_P2, &T_P1, l2, "reference_interacting 0 X PLUS undefined 0@0\n", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + } + /* INTERACTING target, wrong oracle clock marginal: check 10 FAIL with INTERACTING_DEVIATION_EXCEEDED */ + f64_of("1/4", f, sizeof f); snprintf(line, sizeof line, "reference_clock_probability 0 %s 1@15", (f64_of("5/28", f, sizeof f), f)); + char rep[256]; char f2[64]; f64_of("1/4", f2, sizeof f2); snprintf(rep, sizeof rep, "reference_clock_probability 0 %s 1@15\n", f2); + verdict_with("interacting-deviation", &p2, &T_P2, &T_P1, line, rep, PROV, "PPPPPPPPPFNP", "INTERACTING_DEVIATION_EXCEEDED", "NO", AT1_OK); + /* IDEAL target, wrong reference_interacting: check 11 FAIL in addition to check 10 */ + f64_of("49/50", f, sizeof f); snprintf(line, sizeof line, "reference_interacting 0 X PLUS %s 1@15", f); + f64_of("48/50", f2, sizeof f2); snprintf(rep, sizeof rep, "reference_interacting 0 X PLUS %s 1@15\n", f2); + verdict_with("oracle-cross-check", &n1, &T_P2, &T_P1, line, rep, PROV, "PPPPPPPPPFFP", "ORACLE_DISAGREEMENT,SCHRODINGER_DEVIATION_EXCEEDED", "NO", AT1_OK); + /* a nonfinite reference value: check 2 FAIL */ + snprintf(line, sizeof line, "reference_ideal 0 X PLUS %s 1@15", (f64_of("1", f, sizeof f), f)); + verdict_with("nonfinite-reference", &p2, &T_P2, &T_P1, line, "reference_ideal 0 X PLUS nonfinite 0@0\n", PROV, "PFPPPPPPPPNP", "NONFINITE_VALUE", "NO", AT1_OK); + /* malformed oracle records and refused provenance */ + verdict_with("oracle-missing-line", &p2, &T_P2, &T_P1, "reference_label 3 t3 DEFINED", "", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + verdict_with("oracle-wrong-label", &p2, &T_P2, &T_P1, "reference_label 3 t3 DEFINED", "reference_label 3 t2 DEFINED\n", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + verdict_with("oracle-negative-zero", &p2, &T_P2, &T_P1, line, "reference_ideal 0 X PLUS f64:8000000000000000 1@15\n", PROV, NULL, NULL, NULL, AT1_ERR_ARGUMENT); + { + at1_values *v = calloc(1, sizeof *v); at1_case c; values_of(&p2, 0, v, &c); + char *o = oracle_record(&c, &T_P2, &T_P1, 0); + char *bad = replace_line(o, line_with_prefix(o, "case_id ", line, sizeof line), "case_id 0000000000000000000000000000000000000000000000000000000000000000\n"); + char *res; size_t rl; char err[256]; + CHECK(at1_result_write(&c, v, bad, strlen(bad), PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_ERR_ARGUMENT, "oracle case_id mismatch accepted"); + char *p1 = replace_line(PROV, "build_cc cc test harness", "build_cc oracle cargo\n"); + CHECK(at1_result_write(&c, v, o, strlen(o), p1, strlen(p1), &res, &rl, err, sizeof err) == AT1_ERR_ARGUMENT, "oracle build_cc accepted"); + char *p2s = replace_line(PROV, "oracle_sha256 dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", + "oracle_sha256 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"); + CHECK(at1_result_write(&c, v, o, strlen(o), p2s, strlen(p2s), &res, &rl, err, sizeof err) == AT1_ERR_ARGUMENT, "engine_sha256 == oracle_sha256 accepted"); + char *p3 = replace_line(PROV, "artifact b/two 2222222222222222222222222222222222222222222222222222222222222222", "artifact a/one 2222222222222222222222222222222222222222222222222222222222222222\n"); + CHECK(at1_result_write(&c, v, o, strlen(o), p3, strlen(p3), &res, &rl, err, sizeof err) == AT1_ERR_ARGUMENT, "duplicate artifact path accepted"); + char *p4 = replace_line(PROV, "run_started_utc 2026-10-09T00:00:00Z", "run_started_utc 2026-10-09 00:00:00\n"); + CHECK(at1_result_write(&c, v, o, strlen(o), p4, strlen(p4), &res, &rl, err, sizeof err) == AT1_ERR_ARGUMENT, "bad timestamp accepted"); + /* ORACLE_UNAVAILABLE: ERROR shape */ + CHECK(at1_result_write(&c, v, NULL, 0, PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_OK, "oracle unavailable: %s", err); + char checks[13], outcome[64], codes[512], met[32]; + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, "NNNNNNNNNNNN") == 0 && strcmp(outcome, "ERROR") == 0 && strcmp(codes, "none") == 0 && strcmp(met, "NOT_APPLICABLE") == 0, + "oracle unavailable verdict %s %s %s %s", checks, outcome, codes, met); + CHECK(strstr(res, "\nerror_code ORACLE_UNAVAILABLE\n") && strstr(res, "\noracle_repo none\noracle_commit none\noracle_sha256 none\n") + && strstr(res, "\nphysical_state_kernel_dim 0\nconstraint_residual undefined 0@0\npovm_residual undefined 0@0\n"), "oracle unavailable shape"); + check_structure("oracle-unavailable", &c, res, rl); + free(res); + CHECK(at1_result_write_error(&c, "INTERNAL_ERROR", PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_OK && strstr(res, "\nerror_code INTERNAL_ERROR\n") + && strstr(res, "\noracle_sha256 dddd"), "INTERNAL_ERROR result"); + free(res); + free(o); free(bad); free(p1); free(p2s); free(p3); free(p4); free(v); at1_case_free(&c); + } +} + +/* ---- review findings: values block, POVM accumulation, bound formatting, boundaries ---------- */ +static void scaled_of(const char *t, bq *out) +{ + const char *at = strchr(t, '@'); bn n; bn_init(&n); bn_from_digits(&n, t, (size_t)(at - t)); + bq_from_scaled(out, &n, (unsigned)atoi(at + 1)); bn_free(&n); +} +static void bound_minimal(double x) +{ + char t[400]; at1_bound_format(x, t, sizeof t); + const char *at = strchr(t, '@'); size_t d = (size_t)(at - t); unsigned k = (unsigned)atoi(at + 1); + bq X, B, Bm; bq_init(&X); bq_init(&B); bq_init(&Bm); + bq_from_double(&X, x); scaled_of(t, &B); + int ok = d <= 7 || k == 0; + ok = ok && bq_cmp(&B, &X) >= 0; + /* one unit less in the seventh significant digit (or in the last digit when k is clamped) is below x */ + unsigned s = d < 7 ? (unsigned)(7 - d) : 0; + if (k + s > AT1_SCALED_K_MAX) s = AT1_SCALED_K_MAX - k; + bn n, p, one; bn_init(&n); bn_init(&p); bn_init(&one); + bn_from_digits(&n, t, d); bn_pow10(&p, s); bn_mul(&n, &n, &p); bn_set_u64(&one, 1); bn_sub(&n, &n, &one); + bq_from_scaled(&Bm, &n, k + s); + ok = ok && bq_cmp(&Bm, &X) < 0; + CHECK(ok, "bound %.17g written %s is not the smallest 7-digit scaled decimal >= x", x, t); + bn_free(&n); bn_free(&p); bn_free(&one); bq_free(&X); bq_free(&B); bq_free(&Bm); +} +static void review(void) +{ + char t[400]; + /* finding 5: minimal bound tokens */ + at1_bound_format(1.0, t, sizeof t); CHECK(strcmp(t, "1@0") == 0, "bound 1 written %s", t); + at1_bound_format(0.25, t, sizeof t); CHECK(strcmp(t, "25@2") == 0, "bound 0.25 written %s", t); + at1_bound_format(3.0, t, sizeof t); CHECK(strcmp(t, "3@0") == 0, "bound 3 written %s", t); + at1_bound_format(0.0, t, sizeof t); CHECK(strcmp(t, "0@0") == 0, "bound 0 written %s", t); + at1_bound_format(1e-300, t, sizeof t); CHECK(strcmp(t, "1@40") == 0, "bound 1e-300 written %s", t); + const double xs[] = { 1.0, 0.25, 1.0 / 3.0, 1e-15, 8.17e-15, 2.31e-13, 7.0e-17, 6.56e-12, 123456789.0, 9999999.5, 1e-40, 3e-41 }; + for (size_t i = 0; i < sizeof xs / sizeof xs[0]; i++) bound_minimal(xs[i]); + + /* label status rule at its exact boundaries, tol_zero = 1/2 */ + at1_scaled tz; bn_init(&tz.n); bn_set_u64(&tz.n, 5); tz.k = 1; + CHECK(at1_status_rule(0.25, 0.25, &tz) == AT1_LABEL_UNDEFINED, "status: p + b == tol must be UNDEFINED"); + CHECK(at1_status_rule(0.5, 0.0, &tz) == AT1_LABEL_UNDEFINED, "status: p == tol, b = 0 must be UNDEFINED"); + CHECK(at1_status_rule(nextafter(0.5, 1.0), 0.0, &tz) == AT1_LABEL_DEFINED, "status: p one ulp above tol must be DEFINED"); + CHECK(at1_status_rule(0.75, 0.25, &tz) == AT1_LABEL_INDETERMINATE, "status: p - b == tol must be INDETERMINATE"); + CHECK(at1_status_rule(0.75, 0.125, &tz) == AT1_LABEL_DEFINED, "status: p - b > tol must be DEFINED"); + bn_free(&tz.n); + + /* finding 2: POVM accumulation, N = 64, M = 1, w = 1/3: exact value sqrt(571)/3 */ + { + spec s; base_B(&s, "at1-review-povm-n64"); sb e = { 0 }; + for (int j = 0; j < 64; j++) sb_printf(&e, "%s%d/1", j ? "," : "", j); + s.N = 64; s.E = e.p; s.h = "0/1,0/1,0/1,0/1"; s.tau = "1/1"; s.w = "1/3"; s.M = 1; + at1_values *v = calloc(1, sizeof *v); + int ok = values_of(&s, 0, v, NULL); + CHECK(ok, "povm reproducer did not run"); + if (ok) { + char bt[400]; at1_bound_format(v->povm.bound, bt, sizeof bt); + bq V, B, lo, hi, ex; bq_init(&V); bq_init(&B); bq_init(&lo); bq_init(&hi); bq_init(&ex); + bq_from_double(&V, v->povm.value); scaled_of(bt, &B); bq_set_i64(&ex, 571, 9); + bq_sub(&lo, &V, &B); bq_add(&hi, &V, &B); + int in = bq_sign(&lo) >= 0; bq_mul(&lo, &lo, &lo); bq_mul(&hi, &hi, &hi); + in = in && bq_cmp(&lo, &ex) <= 0 && bq_cmp(&ex, &hi) <= 0; + double err = fabs(v->povm.value - sqrt(571.0) / 3.0); + CHECK(in, "povm reproducer: value outside [exact - bound, exact + bound], error about %.3g bound %s", err, bt); + printf("review povm N=64 M=1 w=1/3: value %.17g, |value - sqrt(571)/3| about %.3g, bound %s (ratio %.3g)\n", + v->povm.value, err, bt, err / v->povm.bound); + bq_free(&V); bq_free(&B); bq_free(&lo); bq_free(&hi); bq_free(&ex); + } + free(e.p); free(v); + } + + spec p2; base_B(&p2, "at1-kat-rotated-level-n4"); p2.v[2] = RHO; + at1_values *v = calloc(1, sizeof *v); at1_case c; + if (!values_of(&p2, 0, v, &c)) { CHECK(0, "review: P2 did not run"); free(v); return; } + char *o = oracle_record(&c, &T_P2, &T_P1, 0), *res = NULL, err[256], checks[13], outcome[64], codes[512], met[32]; + size_t rl; + + /* finding 3: an oracle record that is a full result file; lines outside its values block are ignored */ + { + const char *first = strstr(o, "reference_label "); + sb b = { 0 }; + sb_printf(&b, "%.*s", (int)(first - o), o); + sb_printf(&b, "reference_label 0 t0 BOGUS\nbegin values\n%send values\nend\n", first); + at1_status st = at1_result_write(&c, v, b.p, b.n, PROV, strlen(PROV), &res, &rl, err, sizeof err); + CHECK(st == AT1_OK, "values-block record refused: %s", err); + if (st == AT1_OK) { + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, "PPPPPPPPPPNP") == 0 && strcmp(outcome, "PASS") == 0, "values-block record: %s %s", checks, outcome); + free(res); + } + free(b.p); + } + + /* finding 6: absolute-form comparison boundary on check 10 (|d| + b == tol is PASS, one ulp more is INDETERMINATE) */ + { + CHECK(at1_result_write(&c, v, o, strlen(o), PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_OK, "boundary base: %s", err); + char line[256], vt[64], bt[64]; + line_with_prefix(res, "pauli 0 X PLUS ", line, sizeof line); + sscanf(line + 15, "%63s %63s", vt, bt); + free(res); + const char *at = strchr(bt, '@'); unsigned k = (unsigned)atoi(at + 1); + uint64_t nb = strtoull(bt, NULL, 10), p = 1; + CHECK(k >= 12 && k - 12 <= 19, "boundary: engine bound %s out of the test's range", bt); + for (unsigned i = 12; i < k; i++) p *= 10; + uint64_t ob = p - nb; unsigned okk = k; + while (okk > 0 && ob % 10 == 0) { ob /= 10; okk--; } + char old[160], rep[200], a[64]; + f64_of("49/50", a, sizeof a); snprintf(old, sizeof old, "reference_interacting 0 X PLUS %s 1@15", a); + snprintf(rep, sizeof rep, "reference_interacting 0 X PLUS %s %llu@%u\n", vt, (unsigned long long)ob, okk); + char *o2 = replace_line(o, old, rep); + CHECK(o2 && at1_result_write(&c, v, o2, strlen(o2), PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_OK, "boundary equal: %s", err); + if (o2) { + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, "PPPPPPPPPPNP") == 0 && strcmp(codes, "none") == 0, "boundary equal: %s %s", checks, codes); + free(res); free(o2); + } + uint64_t bits = 0; for (int i = 4; i < 20; i++) bits = (bits << 4) | (uint64_t)(vt[i] <= '9' ? vt[i] - '0' : vt[i] - 'a' + 10); + double dv; memcpy(&dv, &bits, sizeof dv); at1_f64_format(nextafter(dv, 2.0), a, sizeof a); + snprintf(rep, sizeof rep, "reference_interacting 0 X PLUS %s %llu@%u\n", a, (unsigned long long)ob, okk); + o2 = replace_line(o, old, rep); + CHECK(o2 && at1_result_write(&c, v, o2, strlen(o2), PROV, strlen(PROV), &res, &rl, err, sizeof err) == AT1_OK, "boundary ulp: %s", err); + if (o2) { + verdict_of(res, checks, outcome, sizeof outcome, codes, sizeof codes, met, sizeof met); + CHECK(strcmp(checks, "PPPPPPPPPINP") == 0 && strcmp(codes, "PRECISION_INSUFFICIENT") == 0, "boundary ulp: %s %s", checks, codes); + free(res); free(o2); + } + } + free(o); free(v); at1_case_free(&c); +} + +/* ---- the command-line tool -------------------------------------------------------------------- */ +static int run(const char *cmd) +{ + int st = system(cmd); + return st == -1 ? -1 : WIFEXITED(st) ? WEXITSTATUS(st) : -1; +} +static void cli(void) +{ + spec p2; base_B(&p2, "at1-kat-rotated-level-n4"); p2.v[2] = RHO; + at1_values *v = calloc(1, sizeof *v); at1_case c; values_of(&p2, 0, v, &c); + char *o = oracle_record(&c, &T_P2, &T_P1, 0); + write_all("build/t.case", g_kat, strlen(g_kat)); + write_all("build/t.oracle", o, strlen(o)); + write_all("build/t.prov", PROV, strlen(PROV)); + char *lib; size_t ll; char err[256]; + at1_result_write(&c, v, o, strlen(o), PROV, strlen(PROV), &lib, &ll, err, sizeof err); + char cmd[2048]; + snprintf(cmd, sizeof cmd, "%s result build/t.case build/t.oracle build/t.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 0, "cli result exit status"); + size_t n; char *out = read_all("build/t.out", &n); + CHECK(out && n == ll && memcmp(out, lib, n) == 0, "cli output differs from the library output"); + snprintf(cmd, sizeof cmd, "%s result build/t.case build/t.oracle build/t.prov --reversed > build/t.out2 2> build/t.err", g_tool); + CHECK(run(cmd) == 0, "cli reversed exit status"); + char *out2 = read_all("build/t.out2", NULL); + CHECK(out && out2 && strcmp(out, out2) == 0, "cli --reversed output differs"); + char line[256]; + printf("KAT verdict_id %s\n", line_with_prefix(out, "verdict_id ", line, sizeof line) ? line + 11 : "?"); + free(out); free(out2); + snprintf(cmd, sizeof cmd, "%s result build/t.case none build/t.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 0, "cli oracle none exit status"); + out = read_all("build/t.out", NULL); + CHECK(out && strstr(out, "\noutcome ERROR\nfailure_codes none\nerror_code ORACLE_UNAVAILABLE\n"), "cli oracle none result"); + free(out); + char *r1 = replace_line(g_kat, "povm_tau_turns 1/4", "povm_tau_turns 2/8\n"); restamp(r1); + write_all("build/t-r1.case", r1, strlen(r1)); free(r1); + snprintf(cmd, sizeof cmd, "%s result build/t-r1.case build/t.oracle build/t.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 2, "cli refusal exit status"); + out = read_all("build/t.err", NULL); char *so = read_all("build/t.out", &n); + CHECK(out && strcmp(out, "AT1_CASE_REFUSED CASE_NONCANONICAL\n") == 0 && n == 0, "cli refusal stderr/stdout"); + free(out); free(so); + /* finding 4: an unreadable oracle record is an ERROR ORACLE_UNAVAILABLE result, and a refused + * case is reported before any other input is read */ + snprintf(cmd, sizeof cmd, "%s result build/t.case build/no-such.oracle build/t.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 0, "cli unreadable oracle exit status"); + out = read_all("build/t.out", NULL); + CHECK(out && strstr(out, "\noutcome ERROR\nfailure_codes none\nerror_code ORACLE_UNAVAILABLE\n"), "cli unreadable oracle result"); + free(out); + snprintf(cmd, sizeof cmd, "%s result build/t-r1.case build/no-such.oracle build/no-such.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 2, "cli refusal with unreadable inputs exit status"); + out = read_all("build/t.err", NULL); + CHECK(out && strcmp(out, "AT1_CASE_REFUSED CASE_NONCANONICAL\n") == 0, "cli refusal masked by unreadable inputs"); + free(out); + snprintf(cmd, sizeof cmd, "%s result build/t.case build/t.oracle build/no-such.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 1, "cli unreadable provenance exit status"); + char *bp = replace_line(PROV, "source_tree_clean YES", "source_tree_clean MAYBE\n"); + write_all("build/t-bad.prov", bp, strlen(bp)); free(bp); + snprintf(cmd, sizeof cmd, "%s result build/t.case build/t.oracle build/t-bad.prov > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 1, "cli bad provenance exit status"); + so = read_all("build/t.out", &n); out = read_all("build/t.err", NULL); + CHECK(n == 0 && out && strncmp(out, "AT1_ENGINE_ERROR ", 17) == 0, "cli bad provenance output"); + free(so); free(out); + snprintf(cmd, sizeof cmd, "%s values build/t.case > build/t.out 2> build/t.err", g_tool); + CHECK(run(cmd) == 0, "cli values exit status"); + free(lib); free(o); free(v); at1_case_free(&c); +} + +int main(int argc, char **argv) +{ + if (argc != 3) { fprintf(stderr, "usage: test_model \n"); return 2; } + g_cases = argv[1]; g_tool = argv[2]; + kat(); + section13(); + int nref = refusals(); + invariance(); + large(); + tool_rules(); + review(); + cli(); + printf("refusal files: %d\n", nref); + printf("measured: max |p - exact| %.3g, max ratio to its bound %.3g; max |pauli - exact| %.3g, max ratio %.3g\n", + g_max_err_p, g_ratio_p, g_max_err_pauli, g_ratio_pauli); + printf("measured: max constraint_residual %.3g (max ratio to its bound %.3g); max povm_residual on complete clocks %.3g\n", + g_max_con, g_max_con_bound_ratio, g_max_povm); + printf("%d passed, %d failed\n", g_pass, g_fail); + free(g_kat); + return g_fail ? 1 : 0; +} ```