diff --git a/.github/workflows/nor25-robust-witness-audits.yml b/.github/workflows/nor25-robust-witness-audits.yml new file mode 100644 index 000000000..18cd95a46 --- /dev/null +++ b/.github/workflows/nor25-robust-witness-audits.yml @@ -0,0 +1,133 @@ +name: NOR-25 preregistered robust uniform-reserve coefficient audits + +on: + push: + paths: + - 'research/nor25_robust_audits/**' + - '.github/workflows/nor25-robust-witness-audits.yml' + pull_request: + paths: + - 'research/nor25_robust_audits/**' + - '.github/workflows/nor25-robust-witness-audits.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + frozen-registration-and-finite-controls: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Verify preregistration is ancestral to implementation + run: | + git merge-base --is-ancestor da075255e2d5e188d5a84f3febbcc7b162d08b79 HEAD + test -s research/nor25_robust_audits/REGISTRATION.md + - name: Compile source and independently enumerate small-universe audit subsets + run: | + python -m compileall -q research/nor25_robust_audits + python -m unittest research.nor25_robust_audits.test_experiment -v + + first-heldout-12-source-audit: + needs: frozen-registration-and-finite-controls + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + PYTHONHASHSEED: '0' + OMP_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Materialize new public-only source fixture + run: | + python research/nor25_robust_audits/experiment.py \ + --make-fixture /tmp/nor25_fixture.json + - name: Freeze and audit public-only source fixture before any attack outcomes + run: | + python - <<'PY' + from pathlib import Path + from hashlib import sha256 + import json + raw=Path('/tmp/nor25_fixture.json').read_bytes() + z=json.loads(raw) + assert z["schema"]=="nor25.source_only_12_fresh_test.v1" + assert z["source_offset"]==99325000 + assert z["replicates"]==[4,5] + assert z["source_only"] and z["private_truth_absent"] and z["attack_sets_absent"] + assert len(z["cases"])==12 + assert len({r["full_public_input_sha256"] for r in z["cases"]})==12 + assert all(not any(k in r for k in ("future","program","attack","witness")) + for r in z["cases"]) + print("NOR25 FIRST PUBLIC FIXTURE BYTES",len(raw),"SHA256",sha256(raw).hexdigest()) + PY + - name: Execute predeclared blind and informed adversary tests + run: | + python research/nor25_robust_audits/experiment.py \ + --fixture /tmp/nor25_fixture.json --out /tmp/nor25_full.json + - name: Record raw full receipt and all source scores even if registered FAIL + run: | + python - <<'PY' + from pathlib import Path + from hashlib import sha256 + import json + a=Path('/tmp/nor25_fixture.json').read_bytes() + b=Path('/tmp/nor25_full.json').read_bytes() + z=json.loads(b) + assert z["fixture_sha256"]==sha256(a).hexdigest() + assert len(z["source_records"])==12 + assert all(len(r["observations"])==360 for r in z["source_records"]) + assert all(c["detected"]+c["missed"]==1024 + for r in z["source_records"] for c in r["observations"]) + assert all(r["valid_target_failures"]==0 and + r["informed_attack_detected"]==0 and + r["delta_invariance_failures"]==0 + for r in z["source_records"]) + print("NOR25 ORIGINAL FIXTURE BYTES SHA256",len(a),sha256(a).hexdigest()) + print("NOR25 ORIGINAL RESULT BYTES SHA256",len(b),sha256(b).hexdigest()) + print("NOR25 REGISTERED PASS",z["registered_primary_pass"]) + PY + - name: Compare original full hosted bytes to immutable first-run SHA256 receipt + run: | + python research/nor25_robust_audits/original_lock_audit.py \ + --fixture /tmp/nor25_fixture.json --full /tmp/nor25_full.json + - uses: actions/upload-artifact@v4 + if: always() + with: + name: nor25-original-fresh-source-only-and-robust-audit-results + path: | + /tmp/nor25_fixture.json + /tmp/nor25_full.json + if-no-files-found: warn + retention-days: 90 + + independent-separate-process-replay: + needs: first-heldout-12-source-audit + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/download-artifact@v4 + with: + name: nor25-original-fresh-source-only-and-robust-audit-results + path: /tmp/nor25 + - name: Independently reconstruct every source, schedule and detection decision + run: | + python research/nor25_robust_audits/receipt_audit.py \ + --fixture /tmp/nor25/nor25_fixture.json \ + --full /tmp/nor25/nor25_full.json + - name: Independently check the frozen first original file hashes + run: | + python research/nor25_robust_audits/original_lock_audit.py \ + --fixture /tmp/nor25/nor25_fixture.json \ + --full /tmp/nor25/nor25_full.json diff --git a/research/nor25_robust_audits/README.md b/research/nor25_robust_audits/README.md new file mode 100644 index 000000000..a09acd19e --- /dev/null +++ b/research/nor25_robust_audits/README.md @@ -0,0 +1,54 @@ +# NOR-25: a uniform reserve for source-risk coordinate audits + +**Registered prior to data:** [REGISTRATION.md](REGISTRATION.md), frozen in the first commit of the branch. Continues the exact finite RRC25 verifier and NOR-24 source-conditional audit study ([merged PR #192](https://github.com/MoralityLabAI/Compactification-Theory/pull/192)). + +## Scientific question + +NOR-24's trained static risk ranking and sequential Bayesian auditor differed by approximately **0.10 percentage points** on the in-template primary readout. Both detected **0%** of its deliberately off-template attacks with 16 inspections. The core question for NOR-25 is whether allocating eight of sixteen authenticated coefficient probes to uniformly randomized unseen coordinates can achieve nonzero worst-case blind-attack coverage while retaining useful template localization. + +The prospective primary policy, **hybrid_50**, selects the first eight coordinates of NOR-24's public trained-risk ordering, then samples eight positions uniformly without replacement from the complement of those selected eight. Risk ordering uses NOR-24's **TRAIN-only** prior 295:246:153:78 over four disclosed attack templates. No NOR-25 labels update that prior. + +The alternate allocation policies hybrid_25 and hybrid_75 reserve respectively four and twelve of sixteen probes for uniform exploration. Controls preserve NOR-24's source-only uniform, static-risk, shuffled-prior, posterior and privileged true-support oracle policies. An informed adversary seeing the realized schedule is scored as a separate zero-detection control. + +## Exact finite blind-attack guarantee + +Write m for the number of coefficient positions, k for total probes, u for uniform reserve, t=k-u for the public-risk fixed prefix, and r for the size of the fixed blind attack set. Conditional on the attack set avoiding the prefix, the number of exploration subsets missing every altered coordinate is + + C(m-t-r,u) + +out of the total + + C(m-t,u). + +If the attack intersects the targeted prefix, detection is certain. Therefore for any blind radius-r attack selected before audit randomization, its chance of detection is at least + + 1 - C(m-t-r,u)/C(m-t,u). + +The minimum is attained by attack sets disjoint from the targeted prefix, assuming r<=m-t. This is an exact combinatorial floor, not a confidence interval. The implementation stores it as exact reduced integer numerator/denominator per source, radius, budget and hybrid policy. All feasible small universes are exhaustively tested. + +The probability model assumes independent idealized secret audit randomness and an attack fixed before sampling. The reproducible SHA256-based test stream is a controlled scientific experiment, not a claimed production secrecy mechanism. An adversary selecting altered coordinates *after* seeing the realized probes avoids all inspected positions whenever r unchecked positions exist. + +## Prospective protocol + +Twelve new source-distinct RRC25 public inputs (replicates 4 and 5; degrees 512 and 1024; each of the three NOR-21 source families), frozen observed demos, public query, header and native acceptance mask. Source generation attempts are deterministic under the new NOR-25 source offset 99325000. Each public source has m=769 or 1537 true query coefficients. + +The blind attack sets are held fixed per source, attack kind, and radius before generating any challenge schedule. 1024 random challenge ordinals per source, budgets 4/16/64, altered-coordinate radii 1/4/16, both exact nonzero shift magnitudes. Independent runs compare all policies on the same attack sets, while random audit schedules are separately salted. Budget levels for hybrid policies are sampled separately to maintain the exact two-stage uniform-reserve rule, rather than artificially imposing a nested schedule. + +**Predeclared primary criterion, k=16, r=4:** hybrid_50 must beat uniform in at least nine of twelve source pairs and yield at least +0.10 absolute source-mean in-template weighted detection gain. It must also detect more off-template attacks than static ranking on at least ten of twelve sources, and reach at least 2% source-mean off-template detection. We will retain and report a FAIL outcome if any threshold is missed. In-template mixture weights are tail .4, magnitude .3, lag .2, background .1, preserving NOR-24's prior test mixture. + +## Reproduce + +From repo root on Python 3.12 (no third-party packages): + + python -m unittest research.nor25_robust_audits.test_experiment -v + python research/nor25_robust_audits/experiment.py --make-fixture /tmp/nor25_fixture.json + python research/nor25_robust_audits/experiment.py --fixture /tmp/nor25_fixture.json --out /tmp/nor25_full.json + python research/nor25_robust_audits/receipt_audit.py --fixture /tmp/nor25_fixture.json --full /tmp/nor25_full.json + +The first CI job verifies source-only isolation and exhaustive finite combinatorics. A second job generates the 12 new source identities and freezes the public-only JSON bytes before any attack or audit grading. An independent third job restores the CI artifacts and separately reconstructs every source, blind attack, hybrid schedule, observation count, theoretical floor and primary pass/fail computation, without importing NOR-25's evaluator. + +## Scope and receipt status + +The NOR-25 registration and source preceded all held-out outcomes. The [first prospective held-out experiment](RESULTS.md) PASSED all four registered primary gates in [GitHub Actions #43885131079](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43885131079). An independent replay reproduced 4,423,680 audited decisions. The [immutable first-run receipt](results/nor25_original_first_receipt.json) pins the original fixture and full result byte hashes. The [original_lock_audit.py](original_lock_audit.py) independently checks the exact original bytes, and can deterministically regenerate them after the Actions artifact retention period. + +The honest coefficient witness remains an external target-dependent oracle. The evaluation is restricted to finite synthetic algebraic programs, declared attack families, reproducible blind challenges and the stated support-shift stressor. It does not establish an unconditional full-output verifier or robustness to an attacker with schedule visibility. diff --git a/research/nor25_robust_audits/REGISTRATION.md b/research/nor25_robust_audits/REGISTRATION.md new file mode 100644 index 000000000..c83e91253 --- /dev/null +++ b/research/nor25_robust_audits/REGISTRATION.md @@ -0,0 +1,40 @@ +# NOR-25 prospective registration: uniform-reserve robust coefficient auditing + +**Registered 2026-11-16, before generating any NOR-25 source fixture, challenge schedules, attack positions, or outcomes.** Base: merged NOR-24 PR #192 at `f28edf3b65fb4b834b661ead28d23b290e6f88e3`. This is a new source experiment and preserves the NOR-24 archive and registered result. If a correction is needed, append a dated amendment; preserve the first registration commit. + +## Fixed hypothesis and threat model + +NOR-24's sequential posterior achieved 34.9699% primary weighted detection against 34.8674% for static prior and 6.1458% for uniform, but its off-template 16-query detection was zero. NOR-25 tests whether **eight learned-risk inspections followed by eight uniform inspections over the remaining coordinates** retain a positive source-level template advantage while recovering an explicit worst-case blind-attack detection floor. + +The adversary fixes a set of exactly r altered coefficients BEFORE the audit samples its secret random schedule. Alterations use an honest exogenous exact target witness, integer deltas 1 and 4294049777, and are judged by intersection between the inspected positions and changed set. For an informed adversary that sees the realized schedule and can choose alterations afterward, the fixed-blind lower bound DOES NOT APPLY: all partial audits can be evaded when r unchecked coordinates exist. This negative control is mandatory. + +## Pinned priors, new sources, and isolation + +- Reuse the original RRC25 exact sixteen-template family, NOR-21 streamed public verifier, and NOR-24 public-only proposal interface without modifying their source code. +- Source generation: independently seeded **12 new held-out source identities**, replicates **4 and 5**, degrees **512 and 1024**, all three original NOR-21 families at each degree. Local source seed `corpus.SEED + 99325000 + 1000003*replicate + 100009*degree_index + 10007*family_index`; accept first attempt among 100 with unique public digest, unique public header, nonzero native mask and unanimous full-output prediction. Output lengths m=769 or 1537. These sources were absent from NOR-24 training and evaluation. No model training occurs in NOR-25. +- Source-only fixture holds two observed degree-D examples, the public query input, original native public acceptance mask, inferred header, seed, replicate, and public SHA; it excludes the planted program, true future, witness values, and attack positions. Save its bytes and SHA-256 BEFORE evaluating attack labels. +- Freeze the NOR-24 TRAIN-only fitted prior as exact fractions: tail 295/772, magnitude 246/772, lag 153/772, full-uniform background 78/772. Do not refit on NOR-25 test identities or outcomes. The 96-element tail, highest-absolute-coefficient, and delay+spacing supports remain public and predeclared. The off-template stress support is the complement of the union of those three structural regions. + +## Policies, randomization, and primary decision + +- Audit budgets k=(4,16,64), changed-coordinate radii r=(1,4,16), two exact nonzero deltas, 1024 independently salted trial ordinals per held-out public source and policy. Test kinds: tail, magnitude, lag, uniform background, and separate off_template. Each source/kind/r attack set is sampled ONCE, from public-only support with SHA-256 seed stream **202611250072**, before generating audit schedules; it is held fixed across all challenge ordinals, policies and deltas. +- Seven nonprivileged policies: uniform random without replacement; frozen static trained-prior rank; original clean-path sequential posterior; shuffled-prior ranking; hybrid_25 (25% exploration), **hybrid_50 (primary, 50% exploration)**, hybrid_75 (75% exploration). Include a privileged known-support oracle separately, never in the primary comparison. +- For each hybrid policy and budget k, first choose the top `t=k-u` ranked static-prior coordinates, then draw exactly `u=floor(f*k)` unseen positions uniformly without replacement from their complement using a distinct SHA-256 audit stream **202611250073**, source digest, policy, k, and trial. At k=4/16/64 the reserve sizes are (1,4,16), (2,8,32), (3,12,48). Schedules for different k are separately salted, and need NOT be nested. Baseline static and sequential policies retain their original top-k prefix. No audit selector reads private truth, blind altered positions, attack kind, or test results. +- Primary grid k=16, r=4, delta=1. Source-weighted in-template mixture fixed at (tail .4, magnitude .3, lag .2, uniform background .1), as in NOR-24. **PASS** iff hybrid_50 beats uniform on at least 9/12 independent sources, yields mean in-template detection gain >= +0.10 absolute vs uniform, exceeds static ranking on the off-template fixed attack on at least 10/12 independent sources, AND attains >= 0.02 source-mean off-template detection. Record failure without adapting the protocol. Additional static-retention ratio, source-specific changes against posterior, and alternative reserve allocations are descriptive only; no second primary gate is picked after data. +- Verify exact magnitude invariance, legitimate-target full acceptance, and informed-adversary evasion in every source/attack/policy/budget cell. Report individual source differences and pooled numbers; challenge replicas share 12 source units. + +## Mathematical guarantee, independent of source distribution + +Let U be the m possible output coordinates, let T be any fixed size-t set of risk-ranked coordinates, let A be any **fixed** size-r attack subset selected before the exploration randomness, and let R be a uniform size-u subset of U\\T, independent of A. The exact blind detection probability is 1 if A meets T; otherwise it is + + 1 - C(m-t-r,u)/C(m-t,u). + +Thus the minimum over all fixed size-r attacked sets (where m-t>=r and m-t>=u) equals this same hypergeometric value. For u=0 and a feasible disjoint attack the worst-case detection is zero. The finite combinatorial formula gives no computational randomness-security guarantee: a pseudorandom SHA256 seed in public CI is a reproducibility device rather than hidden production entropy. + +## Receipt and review gates + +- Commit this registration before producing any fixture or experimental result. +- Independent fixture generator parity checks versus the original RRC25 native 16-template public mask; reconstruct sealed true targets only AFTER freezing public proposals and policy schedules. +- Exhaustive small-m combinatorial oracle for hybrid blind detection probability and adversary-first/eavesdropping counterexample. Per-source SHA256 summaries of attack positions, schedule sampling and observation rows; independent second-process replay on the committed source-only fixture. +- GitHub Actions Python 3.12 CPU; tests and heldout run are separate jobs. Commit source only in first pass; attach unaltered fixture and complete outcome as CI artifact. If and only if the first run succeeds, preserve exact original bytes in a committed immutable archive and audit their SHA256 hashes. +- Interpretation is conditional on a synthetic finite attack model, authentic external target values, fixed blind attacks, disclosed support templates and the independent audit-randomness assumption. No complete-target soundness or live-verifier security claim is implied. diff --git a/research/nor25_robust_audits/RESULTS.md b/research/nor25_robust_audits/RESULTS.md new file mode 100644 index 000000000..2810d475c --- /dev/null +++ b/research/nor25_robust_audits/RESULTS.md @@ -0,0 +1,67 @@ +# NOR-25 first prospective outcome: registered PASS, with measured robustness cost + +**First held-out run:** [GitHub Actions #43885131079](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43885131079). Its source-only fixture was written and SHA-locked before constructing NOR-25 attack sets or audit schedules. The first preregistration commit is [da075255](https://github.com/MoralityLabAI/Compactification-Theory/commit/da075255e2d5e188d5a84f3febbcc7b162d08b79). See [registration](REGISTRATION.md) for all four fixed primary gates. + +The first full calculation and separate-process independent replay both passed. The replay reconstructed 12 original source identities, 15 fixed blind attack sets per source, all pseudorandom hybrid plans, theoretical worst-case floors and **4,423,680** paired detection decisions. The original output was preserved with exact raw file hashes in [results/nor25_original_first_receipt.json](results/nor25_original_first_receipt.json); its [original CI artifact, ID 14233747860](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43885131079), stores the source-only fixture and complete outcome JSON. + +## Primary registered k=16, radius=4 + +| Policy | In-template weighted detection | Off-template fixed blind attack | +| --- | ---: | ---: | +| Uniform | 6.22% | 6.15% | +| Shuffled prior | 5.99% | 6.00% | +| Static trained prior | 38.92% | 0.00% | +| Sequential posterior | 39.11% | 0.00% | +| Hybrid, 4 uniform / 12 targeted | 33.82% | 1.56% | +| **Hybrid, 8 uniform / 8 targeted** | **27.03%** | **3.17%** | +| Hybrid, 12 uniform / 4 targeted | 17.90% | 4.32% | +| Privileged support oracle | 47.97% | 8.39% | + +The registered hybrid_50 policy improved on uniform for **11/12 source pairs**, with +0.208194986979 absolute mean in-template gain. Off-template it beat static ranking for **12/12 source pairs**, with 0.0316569 mean detection versus static's zero. All four registered primary gates passed. + +Measured cost: hybrid_50 retained approximately **69.5%** of static prior's weighted in-template detection (27.03% versus 38.92%). Its off-template detection was roughly half uniform's 6.15%. This is a tradeoff under a fixed witness budget, and the sampling stream is public for reproducibility. + +## Source-level paired primary effects + +The source represents the independent unit. The 1,024 audit challenge ordinals within a source share that source's fixed blind attack positions. + +| Replicate | Degree | Source family | Hybrid_50 minus uniform, pp | Hybrid_50 minus static, pp | Off-template hybrid_50 | +| --- | ---: | --- | ---: | ---: | ---: | +| 4 | 512 | dense | -3.69 | +4.07 | 3.32% | +| 4 | 512 | sparse | +15.63 | -12.59 | 4.79% | +| 4 | 512 | rational | +20.99 | -16.01 | 4.49% | +| 4 | 1024 | dense | +18.01 | -15.55 | 1.27% | +| 4 | 1024 | sparse | +17.74 | -13.13 | 1.76% | +| 4 | 1024 | rational | +19.13 | -13.91 | 2.54% | +| 5 | 512 | dense | +16.64 | -11.04 | 3.81% | +| 5 | 512 | sparse | +14.77 | -13.79 | 4.39% | +| 5 | 512 | rational | +16.06 | -13.67 | 3.42% | +| 5 | 1024 | dense | +77.47 | -8.44 | 2.93% | +| 5 | 1024 | sparse | +18.45 | -15.16 | 3.13% | +| 5 | 1024 | rational | +18.64 | -13.43 | 2.15% | + +One unusually large +77.47 pp source effect contributes to the mean. The median source gain is **+17.88 pp**. Excluding that single maximum source as a retrospective sensitivity check gives about **+15.67 pp** over the remaining eleven; their paired win count is ten of eleven. The registration retained all twelve sources. + +## Per-family observation + +At k=16, radius=4, hybrid_50 detected 36.91% of tail attacks, 33.19% of magnitude attacks, 9.94% of lag-window attacks, and 3.21% of uniform-background attacks. The static prior detected 54.59%, 51.39%, 8.33% and **0.00%**, respectively, on these same source-world constructions. Hybrid allocation therefore restores some coverage against both the explicitly off-template attack and the declared uniform background family. + +## Exact worst-case blind floor + +For a fixed radius-four attack chosen before the audit seed, the hybrid_50 two-stage sampling design guarantees at least + +| Query output length | Exact minimum detection probability | +| ---: | ---: | +| 769 coefficients | 4.147204% | +| 1537 coefficients | 2.078527% | + +These are theoretical probabilities for idealized independent uniform sampling, not guaranteed minimum frequencies over 1,024 trials. Each source's finite empirical off-template frequency can fall below its exact probability floor by sampling fluctuation. A realized-schedule-informed adversary again evaded every partial audit, as preregistered. + +## Original exact byte receipts + +- 12-source public-only JSON: **2,187,225 bytes**, SHA-256 \`39f69654ed17b970088f405d8b8db171b5042459307d923fb3c7cc32b1b3b6bf\`. +- Full original outcome: **859,176 bytes**, SHA-256 \`901bd3b8ac9ac3335fc5e26cd69ee8d0ea9c81d7ba8fae3a508c7e9bcc14958f\`. +- Evidence archive: Actions #43885131079, artifact ID **14233747860**. The two full original files remain obtainable as the CI artifact until retention expiry and are deterministically regenerable by the source-pinned experiment. +- The separate-process auditor passed on the original artifact independently of the first evaluator, with exact source and attack replay. + +**Scope.** Synthetic fixed blind attacks, an independent source-only prior, and an authentic target-dependent exact-coefficient witness. Reported challenge averages are correlated within twelve source units. The fully informed adversary is a separate threat model with a zero-detection counterexample. A higher posterior in-template mean was observed, and the incremental adaptation effect remains small relative to the cost of global exploration. diff --git a/research/nor25_robust_audits/experiment.py b/research/nor25_robust_audits/experiment.py new file mode 100644 index 000000000..45644b7df --- /dev/null +++ b/research/nor25_robust_audits/experiment.py @@ -0,0 +1,379 @@ +"""NOR-25 source-locked robustness test. Registration precedes this implementation. + +The NOR-24 frozen prior is an input. All NOR-25 source identities are fresh. +The external witness is exact; SHA256-seeded trials are reproducible and +not claimed to supply cryptographic unpredictability. +""" +from __future__ import annotations + +import argparse +from collections import Counter +from fractions import Fraction +from hashlib import sha256 +from itertools import islice +from math import comb +from pathlib import Path +import random +import statistics +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from research.nor24_adaptive_audits import experiment as prior24 +from research.nor21_degree_scaling import experiment as nor21 +from research.rrc_compactification import compound25 as corpus + +SCHEMA = "nor25.frozen_prior_robust_blind_coordinate_audit.v1" +FIXTURE_SCHEMA = "nor25.source_only_12_fresh_test.v1" +SOURCE_OFFSET = 99325000 +REPLICATES = (4, 5) +DEGREES = prior24.DEGREES +FAMILIES = nor21.FAMILIES +SOURCE_COUNT = len(REPLICATES) * len(DEGREES) * len(FAMILIES) +KINDS = prior24.KINDS +ALL_KINDS = prior24.ALL_KINDS +PRIOR_NUMERATORS = (295, 246, 153, 78) +PRIOR_DENOMINATOR = 772 +PRIOR = {kind: num / PRIOR_DENOMINATOR + for kind, num in zip(KINDS, PRIOR_NUMERATORS)} +EVAL_WEIGHTS = prior24.PRIOR_WEIGHTS +RADIUS = (1, 4, 16) +BUDGETS = (4, 16, 64) +TRIALS = 1024 +DELTAS = (1, 4294049777) +ATTACK_STREAM = 202611250072 +AUDIT_STREAM = 202611250073 +MIXED_FRACTIONS = {"hybrid_25": 1, "hybrid_50": 2, "hybrid_75": 3} +ARMS = ("uniform", "static_prior", "posterior", "shuffled_prior", + "hybrid_25", "hybrid_50", "hybrid_75", "oracle_support") + + +def source_seed(rep, degree, family): + if rep not in REPLICATES or degree not in DEGREES or family not in FAMILIES: + raise ValueError("source outside NOR-25 registration") + return (corpus.SEED + SOURCE_OFFSET + 1000003 * rep + + 100009 * DEGREES.index(degree) + + 10007 * FAMILIES.index(family)) + + +def generate_source(rep, degree, family, seen): + q = 3 * degree // 2 + rng = random.Random(source_seed(rep, degree, family)) + for attempt in range(100): + planted = nor21.new_header_program(rng) + demos = tuple((f := nor21.public_source(rng, family, q), + corpus.execute(f, planted)) for _ in range(2)) + query = nor21.public_source(rng, family, q) + public = corpus.Case("nor25-public-source", family, demos, query, (), None) + headers = corpus.possible_headers(public) + if len(headers) != 1: + continue + header = headers[0] + if (header.base, header.delay, header.spacing, header.amplitude) != planted[:4]: + continue + digest = nor21.public_digest(public, degree) + if digest in seen: + continue + mask = nor21.native_mask(public, header, degree) + if mask == 0: + continue + preds = nor21.candidate_predictions(query, header, q) + if len({preds[j] for j in range(16) if mask & (1 << j)}) != 1: + continue + planted_j = corpus.OPS.index(planted[4]) * 4 + corpus.OPS.index(planted[5]) + assert mask & (1 << planted_j) + seen.add(digest) + return { + "split": "TEST", "replicate": rep, + "observation_degree": degree, "query_degree": q, + "family": family, "source_seed": source_seed(rep, degree, family), + "selected_attempt": attempt, "full_public_input_sha256": digest, + "public_header": {"base": header.base, "delay": header.delay, + "spacing": header.spacing, "amplitude": header.amplitude}, + "demos": [[list(x[:degree+1]), list(y[:degree+1])] + for x, y in demos], + "public_query_input": list(query), + "original_public_accept_mask": mask, + } + raise RuntimeError("NOR25 exhausted first-100 deterministic source candidates") + + +def make_fixture(): + seen = set() + rows = [generate_source(rep, degree, family, seen) + for rep in REPLICATES for degree in DEGREES for family in FAMILIES] + assert len(seen) == len(rows) == SOURCE_COUNT == 12 + return { + "schema": FIXTURE_SCHEMA, "source_offset": SOURCE_OFFSET, + "replicates": list(REPLICATES), "source_only": True, + "private_truth_absent": True, "attack_sets_absent": True, + "frozen_prior_numerators": list(PRIOR_NUMERATORS), + "frozen_prior_denominator": PRIOR_DENOMINATOR, + "challenge_trials": TRIALS, "cases": rows, + } + + +def load_fixture(path): + data = Path(path).read_bytes() + fixture = __import__("json").loads(data) + assert fixture["schema"] == FIXTURE_SCHEMA + assert fixture["source_offset"] == SOURCE_OFFSET + assert fixture["replicates"] == list(REPLICATES) + assert fixture["source_only"] and fixture["private_truth_absent"] + assert fixture["attack_sets_absent"] + assert fixture["frozen_prior_numerators"] == list(PRIOR_NUMERATORS) + assert fixture["frozen_prior_denominator"] == PRIOR_DENOMINATOR + assert fixture["challenge_trials"] == TRIALS + rows = fixture["cases"] + assert len(rows) == SOURCE_COUNT + assert len({r["full_public_input_sha256"] for r in rows}) == SOURCE_COUNT + assert {(r["replicate"], r["observation_degree"], r["family"]) for r in rows} == { + (rep, degree, family) for rep in REPLICATES + for degree in DEGREES for family in FAMILIES} + assert all(r["split"] == "TEST" and + not any(w in r for w in ("program", "future", "attack", "witness")) + for r in rows) + return fixture, sha256(data).hexdigest() + + +def sealed_truth_after_public_proposal(row, predicted): + """Reconstruct private original program after the public proposal is fixed.""" + rep, d, family = row["replicate"], row["observation_degree"], row["family"] + rng = random.Random(source_seed(rep, d, family)) + program = demos = query = None + for _ in range(row["selected_attempt"] + 1): + program = nor21.new_header_program(rng) + demos = tuple((x := nor21.public_source(rng, family, 3*d//2), + corpus.execute(x, program)) for _ in range(2)) + query = nor21.public_source(rng, family, 3*d//2) + assert row["source_seed"] == source_seed(rep, d, family) + assert row["demos"] == [[list(x[:d+1]), list(y[:d+1])] for x, y in demos] + assert row["public_query_input"] == list(query) + truth = corpus.execute(query, program) + assert tuple(predicted) == tuple(truth) + return truth + + +def blind_attack(digest, kind, radius, regions): + if kind not in ALL_KINDS or radius not in RADIUS: + raise ValueError("unregistered blind attack") + rng = random.Random(prior24.stream_seed(ATTACK_STREAM, digest, kind, radius)) + return frozenset(rng.sample(sorted(regions[kind]), radius)) + + +def reserve_size(policy, budget): + if policy not in MIXED_FRACTIONS or budget not in BUDGETS: + raise ValueError("unregistered NOR25 allocation") + return budget * MIXED_FRACTIONS[policy] // 4 + + +def hybrid_schedule(static_order, m, digest, policy, budget, trial): + """Fixed risk prefix T, then uniform size-u sample from U minus T.""" + u = reserve_size(policy, budget) + t = budget-u + top = tuple(static_order[:t]) + assert len(set(top)) == t + chosen = set(top) + remaining = [i for i in range(m) if i not in chosen] + rng = random.Random(prior24.stream_seed( + AUDIT_STREAM, digest, policy, budget, trial)) + tail = tuple(rng.sample(remaining, u)) + plan = top + tail + assert len(plan) == len(set(plan)) == budget + return plan + + +def policy_schedules(regions, digest, trial): + """Baseline controls preserve NOR24 policies; hybrids are independent.""" + baseline = prior24.policy_schedules(regions, PRIOR, digest, trial) + m = len(regions["uniform"]) + results = {} + for budget in BUDGETS: + for arm in ARMS: + if arm in MIXED_FRACTIONS: + plan = hybrid_schedule(baseline["static_prior"], m, digest, + arm, budget, trial) + elif arm == "oracle_support": + for kind in ALL_KINDS: + results[(arm, kind, budget)] = baseline[(arm, kind)][:budget] + continue + else: + plan = baseline[arm][:budget] + assert len(plan) == len(set(plan)) == budget + results[(arm, budget)] = plan + return results + + +def blind_floor(m, budget, reserve, radius): + """The exact minimax blind detection probability for a fixed risk prefix.""" + t = budget-reserve + if not (0 <= t < m and 0 <= reserve <= m-t and 1 <= radius <= m-t): + raise ValueError("out-of-domain blind guarantee") + return Fraction(1) - Fraction(comb(m-t-radius, reserve), comb(m-t, reserve)) + + +def exact_detection(proposed, true, inspected, changed, delta): + return not prior24.exact_witness_accepts( + proposed, true, inspected, changed, delta) + + +def evaluate(path): + fixture, fixture_hash = load_fixture(path) + # Freeze ALL source-only proposals before restoring any private targets. + proposals = {row["full_public_input_sha256"]: prior24.public_proposal(row) + for row in fixture["cases"]} + assert len(proposals) == SOURCE_COUNT + records = [] + for row in fixture["cases"]: + digest = row["full_public_input_sha256"] + proposal = proposals[digest] + true = sealed_truth_after_public_proposal(row, proposal["predicted"]) + predicted = proposal["predicted"] + regions = prior24.supports(predicted, proposal["header"]) + # Fix blind attacks for this public source BEFORE any audit plans. + attacks = {(kind, radius): blind_attack(digest, kind, radius, regions) + for kind in ALL_KINDS for radius in RADIUS} + cells = {(kind, radius, budget, arm): 0 + for kind in ALL_KINDS for radius in RADIUS + for budget in BUDGETS for arm in ARMS} + informed_fails = 0 + valid_target_fails = 0 + magnitude_disagreements = 0 + for trial in range(TRIALS): + plans = policy_schedules(regions, digest, trial) + for kind in ALL_KINDS: + for budget in BUDGETS: + for arm in ARMS: + checked = plans[(arm, kind, budget)] if arm == "oracle_support" \ + else plans[(arm, budget)] + if not prior24.exact_witness_accepts( + predicted, true, checked, frozenset(), DELTAS[0]): + valid_target_fails += 1 + # Adaptive attacker sees the exact realized schedule. + for radius in RADIUS: + attack = attacks[(kind, radius)] + d1 = exact_detection(predicted, true, checked, attack, DELTAS[0]) + d2 = exact_detection(predicted, true, checked, attack, DELTAS[1]) + magnitude_disagreements += d1 != d2 + cells[(kind, radius, budget, arm)] += int(d1) + informed = prior24.informed_attack( + checked, regions[kind], radius) + informed_fails += exact_detection( + predicted, true, checked, informed, DELTAS[0]) + assert valid_target_fails == informed_fails == magnitude_disagreements == 0 + observations = [ + {"kind": kind, "radius": radius, "budget": budget, + "policy": arm, "detected": cells[(kind, radius, budget, arm)], + "missed": TRIALS - cells[(kind, radius, budget, arm)]} + for kind in ALL_KINDS for radius in RADIUS + for budget in BUDGETS for arm in ARMS + ] + floors = {} + for arm in MIXED_FRACTIONS: + for budget in BUDGETS: + for radius in RADIUS: + u = reserve_size(arm, budget) + bound = blind_floor(len(predicted), budget, u, radius) + floors[f"{arm}|{budget}|{radius}"] = [ + bound.numerator, bound.denominator] + records.append({ + "public_sha256": digest, "replicate": row["replicate"], + "observation_degree": row["observation_degree"], + "family": row["family"], "public_mask": proposal["mask"], + "chosen_class": proposal["chosen_class"], + "public_prediction_sha256": proposal["sha256"], + "sealed_true_future_sha256_postchoice": prior24.sha_target(true), + "support_sizes": {kind: len(regions[kind]) for kind in ALL_KINDS}, + "blind_attack_positions": { + f"{kind}|{radius}": sorted(attacks[(kind, radius)]) + for kind in ALL_KINDS for radius in RADIUS}, + "theoretical_blind_floors": floors, + "valid_target_failures": valid_target_fails, + "informed_attack_detected": informed_fails, + "delta_invariance_failures": magnitude_disagreements, + "observations": observations, + }) + primary = [] + for rec in records: + d = {(x["kind"], x["radius"], x["budget"], x["policy"]): x + for x in rec["observations"]} + weighted = { + arm: sum(weight*d[(kind,4,16,arm)]["detected"]/TRIALS + for kind, weight in zip(KINDS, EVAL_WEIGHTS)) + for arm in ARMS + } + off = {arm: d[(prior24.STRESS,4,16,arm)]["detected"]/TRIALS + for arm in ARMS} + primary.append({ + "public_sha256": rec["public_sha256"], + "degree": rec["observation_degree"], "family": rec["family"], + "weighted_in_template_rates": weighted, + "off_template_rates": off, + "hybrid50_minus_uniform": weighted["hybrid_50"]-weighted["uniform"], + "hybrid50_minus_static": weighted["hybrid_50"]-weighted["static_prior"], + "hybrid50_off_minus_static": off["hybrid_50"]-off["static_prior"], + }) + wins_uniform = sum(x["hybrid50_minus_uniform"] > 0 for x in primary) + wins_off = sum(x["hybrid50_off_minus_static"] > 0 for x in primary) + mean_gain = statistics.mean(x["hybrid50_minus_uniform"] for x in primary) + mean_off = statistics.mean(x["off_template_rates"]["hybrid_50"] for x in primary) + primary_pass = (wins_uniform >= 9 and mean_gain >= .10 and + wins_off >= 10 and mean_off >= .02) + return { + "schema": SCHEMA, "registration_precedes_all_nor25_data": True, + "fixture_sha256": fixture_hash, "source_count": SOURCE_COUNT, + "challenge_trials_per_source_policy": TRIALS, + "frozen_prior": PRIOR, + "frozen_prior_numerators": list(PRIOR_NUMERATORS), + "frozen_prior_denominator": PRIOR_DENOMINATOR, + "blind_attacks_fixed_before_policy_challenges": True, + "public_proposals_frozen_before_private_truth": True, + "source_records": records, "primary_by_source": primary, + "wins_hybrid50_vs_uniform": wins_uniform, + "offtemplate_wins_hybrid50_vs_static": wins_off, + "source_mean_weighted_gain_vs_uniform": mean_gain, + "source_mean_offtemplate_hybrid50": mean_off, + "registered_primary_pass": primary_pass, + "scope": ("Synthetic fixed blind attacks with exact exogenous target witnesses; " + "seeded experimental reproducibility is not production unpredictability; " + "fully informed adversaries evade any partial inspection."), + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--make-fixture", type=Path) + parser.add_argument("--fixture", type=Path) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + if args.make_fixture: + if args.fixture or args.out: + parser.error("source generation and private assessment are separate stages") + raw = prior24.canonical(make_fixture()) + args.make_fixture.parent.mkdir(parents=True, exist_ok=True) + args.make_fixture.write_bytes(raw) + print("NOR25 FROZEN SOURCE-ONLY FIXTURE", len(raw), sha256(raw).hexdigest()) + return + if args.fixture is None: + parser.error("--fixture required") + outcome = evaluate(args.fixture) + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_bytes(prior24.canonical(outcome)) + print("NOR25 IN-TEMPLATE BY SOURCE", [ + (x["degree"], x["family"], round(x["hybrid50_minus_uniform"], 6), + round(x["hybrid50_minus_static"], 6), + round(x["hybrid50_off_minus_static"], 6)) + for x in outcome["primary_by_source"]]) + print("NOR25 PRIMARY", outcome["registered_primary_pass"], + outcome["wins_hybrid50_vs_uniform"], + outcome["offtemplate_wins_hybrid50_vs_static"], + round(outcome["source_mean_weighted_gain_vs_uniform"],6), + round(outcome["source_mean_offtemplate_hybrid50"],6)) + + +if __name__ == "__main__": + main() diff --git a/research/nor25_robust_audits/original_lock_audit.py b/research/nor25_robust_audits/original_lock_audit.py new file mode 100644 index 000000000..fca787b89 --- /dev/null +++ b/research/nor25_robust_audits/original_lock_audit.py @@ -0,0 +1,78 @@ +"""NOR-25 immutable first raw-byte receipt auditor. + +Checks the original hosted source-only fixture and complete outcome against +the SHA-locked public first-run receipt. Optional --regenerate regenerates +both files deterministically if the short-lived Actions artifact has expired. +The separate-process decision replay remains a different script. +""" +from __future__ import annotations + +import argparse +from hashlib import sha256 +import json +from math import isclose +from pathlib import Path +import sys +import tempfile + +ROOT=Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0,str(ROOT)) +HERE=Path(__file__).resolve().parent +RECEIPT=HERE/"results"/"nor25_original_first_receipt.json" + + +def check(fixture_file, outcome_file): + ref=json.loads(RECEIPT.read_text()) + raw_source=Path(fixture_file).read_bytes() + raw_outcome=Path(outcome_file).read_bytes() + for name,data in (("fixture",raw_source),("outcome",raw_outcome)): + expected=ref[name] + digest=sha256(data).hexdigest() + assert len(data)==expected["bytes"],(name,"bytes",len(data)) + assert digest==expected["sha256"],(name,"sha256",digest) + src=json.loads(raw_source) + out=json.loads(raw_outcome) + assert src["source_only"] and src["private_truth_absent"] and src["attack_sets_absent"] + assert len(src["cases"])==12 + source_order=[x["full_public_input_sha256"] for x in src["cases"]] + assert source_order==ref["source_public_sha256_order"] + assert [x["public_sha256"] for x in out["source_records"]]==source_order + assert len(out["primary_by_source"])==12 + assert out["registered_primary_pass"]==ref["primary"]["registered_pass"] + assert out["wins_hybrid50_vs_uniform"]==ref["primary"]["wins_hybrid50_vs_uniform"] + assert out["offtemplate_wins_hybrid50_vs_static"]==ref["primary"]["offtemplate_wins_hybrid50_vs_static"] + assert isclose(out["source_mean_weighted_gain_vs_uniform"], + ref["primary"]["weighted_source_mean_hybrid50_minus_uniform"], + rel_tol=0,abs_tol=1e-15) + assert isclose(out["source_mean_offtemplate_hybrid50"], + ref["primary"]["source_mean_offtemplate_hybrid50"], + rel_tol=0,abs_tol=1e-15) + assert all(len(x["observations"])==360 and x["informed_attack_detected"]==0 + and x["delta_invariance_failures"]==0 and x["valid_target_failures"]==0 + for x in out["source_records"]) + print("NOR25 IMMUTABLE FIRST SOURCE AND OUTCOME PASS", + len(raw_source),sha256(raw_source).hexdigest(), + len(raw_outcome),sha256(raw_outcome).hexdigest()) + + +if __name__=="__main__": + ap=argparse.ArgumentParser() + ap.add_argument("--fixture",type=Path) + ap.add_argument("--full",type=Path) + ap.add_argument("--regenerate",action="store_true") + args=ap.parse_args() + if args.regenerate: + if args.fixture or args.full: + ap.error("regenerate is separate from checking supplied original files") + from research.nor25_robust_audits import experiment as e + with tempfile.TemporaryDirectory(prefix="nor25_locked_") as t: + a=Path(t)/"nor25_fixture.json" + b=Path(t)/"nor25_full.json" + a.write_bytes(e.prior24.canonical(e.make_fixture())) + b.write_bytes(e.prior24.canonical(e.evaluate(a))) + check(a,b) + elif args.fixture and args.full: + check(args.fixture,args.full) + else: + ap.error("supply --fixture and --full, or --regenerate") diff --git a/research/nor25_robust_audits/receipt_audit.py b/research/nor25_robust_audits/receipt_audit.py new file mode 100644 index 000000000..04c4b52b7 --- /dev/null +++ b/research/nor25_robust_audits/receipt_audit.py @@ -0,0 +1,211 @@ +"""NOR-25 independent second-process deterministic source and decision replay. + +This auditor deliberately never imports research.nor25_robust_audits.experiment. +It independently reproduces NOR-25's hybrid allocation, fixed blind attacks, +combinatorial detection floor and primary source-level scores. +""" +from __future__ import annotations + +import argparse +from collections import Counter +from fractions import Fraction +from hashlib import sha256 +import json +from math import comb, isclose +from pathlib import Path +import random +import sys + +ROOT=Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0,str(ROOT)) + +from research.nor24_adaptive_audits import experiment as n +from research.nor21_degree_scaling import experiment as nor21 +from research.rrc_compactification import compound25 as corpus + +REPS=(4,5) +DEGREES=(512,1024) +FAMILIES=n.FAMILIES +KINDS=n.KINDS +ALL_KINDS=n.ALL_KINDS +RADII=(1,4,16) +BUDGETS=(4,16,64) +ARMS=("uniform","static_prior","posterior","shuffled_prior", + "hybrid_25","hybrid_50","hybrid_75","oracle_support") +FRACTIONS={"hybrid_25":1,"hybrid_50":2,"hybrid_75":3} +PRIOR=dict(zip(KINDS,(295/772,246/772,153/772,78/772))) +TRIALS=1024 + + +def seed(*fields): + return int.from_bytes(sha256("|".join(str(x) for x in fields).encode("ascii")).digest(),"big") + + +def source_seed(rep,d,family): + return (corpus.SEED + 99325000 + 1000003*rep + + 100009*DEGREES.index(d) + 10007*FAMILIES.index(family)) + + +def restore_sealed_truth(row, expected): + d=row["observation_degree"] + rep=row["replicate"] + family=row["family"] + s=source_seed(rep,d,family) + assert row["source_seed"]==s + rng=random.Random(s) + for _ in range(row["selected_attempt"]+1): + prog=nor21.new_header_program(rng) + demos=tuple((x := nor21.public_source(rng,family,3*d//2), + corpus.execute(x,prog)) for _ in range(2)) + query=nor21.public_source(rng,family,3*d//2) + assert row["demos"]==[[list(x[:d+1]),list(y[:d+1])] for x,y in demos] + assert row["public_query_input"]==list(query) + truth=corpus.execute(query,prog) + assert tuple(expected)==tuple(truth) + return truth + + +def independent_hybrid(static,m,digest,arm,k,trial): + u=k*FRACTIONS[arm]//4 + t=k-u + targeted=tuple(static[:t]) + remaining=sorted(set(range(m))-set(targeted)) + rng=random.Random(seed(202611250073,digest,arm,k,trial)) + return targeted+tuple(rng.sample(remaining,u)) + + +def replay(fixture_path,result_path): + fixture_bytes=Path(fixture_path).read_bytes() + result_bytes=Path(result_path).read_bytes() + source=json.loads(fixture_bytes) + record=json.loads(result_bytes) + assert source["schema"]=="nor25.source_only_12_fresh_test.v1" + assert source["source_only"] and source["private_truth_absent"] + assert source["attack_sets_absent"] and len(source["cases"])==12 + assert record["schema"]=="nor25.frozen_prior_robust_blind_coordinate_audit.v1" + assert record["fixture_sha256"]==sha256(fixture_bytes).hexdigest() + assert record["frozen_prior_numerators"]==[295,246,153,78] + assert record["frozen_prior_denominator"]==772 + assert record["source_count"]==12 + assert record["challenge_trials_per_source_policy"]==1024 + assert record["blind_attacks_fixed_before_policy_challenges"] + assert record["public_proposals_frozen_before_private_truth"] + assert {(r["replicate"],r["observation_degree"],r["family"]) + for r in source["cases"]} == { + (rep,d,f) for rep in REPS for d in DEGREES for f in FAMILIES} + mapped={r["public_sha256"]:r for r in record["source_records"]} + assert len(mapped)==12 + primary=[] + total_checked=0 + for row in source["cases"]: + digest=row["full_public_input_sha256"] + observed=mapped[digest] + public,header=n.public_only_case(row) + assert nor21.native_mask(public,header,row["observation_degree"]) == \ + row["original_public_accept_mask"] + proposal=n.public_proposal(row) + truth=restore_sealed_truth(row,proposal["predicted"]) + assert observed["public_mask"]==proposal["mask"] + assert observed["chosen_class"]==proposal["chosen_class"] + assert observed["public_prediction_sha256"]==proposal["sha256"] + assert observed["sealed_true_future_sha256_postchoice"]==n.sha_target(truth) + regions=n.supports(proposal["predicted"],header) + m=len(proposal["predicted"]) + assert observed["support_sizes"]=={kind:len(regions[kind]) for kind in ALL_KINDS} + attacks={} + for kind in ALL_KINDS: + for r in RADII: + rng=random.Random(seed(202611250072,digest,kind,r)) + attacks[(kind,r)]=set(rng.sample(sorted(regions[kind]),r)) + assert observed["blind_attack_positions"][f"{kind}|{r}"] == \ + sorted(attacks[(kind,r)]) + for arm in FRACTIONS: + for k in BUDGETS: + for r in RADII: + u=k*FRACTIONS[arm]//4 + t=k-u + p=Fraction(1)-Fraction(comb(m-t-r,u),comb(m-t,u)) + assert observed["theoretical_blind_floors"][f"{arm}|{k}|{r}"] == \ + [p.numerator,p.denominator] + counts=Counter() + for trial in range(TRIALS): + baselines=n.policy_schedules(regions,PRIOR,digest,trial) + hybrids={(arm,k):independent_hybrid( + baselines["static_prior"],m,digest,arm,k,trial) + for arm in FRACTIONS for k in BUDGETS} + for kind in ALL_KINDS: + for k in BUDGETS: + for arm in ARMS: + if arm in FRACTIONS: + checked=hybrids[(arm,k)] + elif arm=="oracle_support": + checked=baselines[(arm,kind)][:k] + else: + checked=baselines[arm][:k] + assert len(checked)==len(set(checked))==k + assert all(i>=0 and i=max(RADII) + for r in RADII: + # Independent exact rejection oracle: an authentic + # target that equals the public proposal differs + # after nonzero tampering precisely on attack set. + counts[(kind,r,k,arm)] += bool( + checked_set & attacks[(kind,r)]) + total_checked+=1 + assert len(observed["observations"])==len(ALL_KINDS)*len(RADII)*len(BUDGETS)*len(ARMS) + for cell in observed["observations"]: + key=(cell["kind"],cell["radius"],cell["budget"],cell["policy"]) + assert cell["detected"]==counts[key],(digest,key,cell["detected"],counts[key]) + assert cell["missed"]==TRIALS-counts[key] + assert observed["valid_target_failures"]==0 + assert observed["informed_attack_detected"]==0 + assert observed["delta_invariance_failures"]==0 + weighted={ + arm:sum(w*counts[(kind,4,16,arm)]/TRIALS + for kind,w in zip(KINDS,(.4,.3,.2,.1))) + for arm in ARMS} + off={arm:counts[(n.STRESS,4,16,arm)]/TRIALS for arm in ARMS} + primary.append({ + "public_sha256":digest,"degree":row["observation_degree"], + "family":row["family"],"weighted_in_template_rates":weighted, + "off_template_rates":off, + "hybrid50_minus_uniform":weighted["hybrid_50"]-weighted["uniform"], + "hybrid50_minus_static":weighted["hybrid_50"]-weighted["static_prior"], + "hybrid50_off_minus_static":off["hybrid_50"]-off["static_prior"], + }) + assert len(primary)==12 + observed_primary={x["public_sha256"]:x for x in record["primary_by_source"]} + for x in primary: + y=observed_primary[x["public_sha256"]] + assert x.keys()==y.keys() + for key in x: + if isinstance(x[key],dict): + for arm in x[key]: + assert isclose(x[key][arm],y[key][arm],abs_tol=1e-13) + elif isinstance(x[key],float): + assert isclose(x[key],y[key],abs_tol=1e-13) + else: + assert x[key]==y[key] + win=sum(x["hybrid50_minus_uniform"]>0 for x in primary) + offwin=sum(x["hybrid50_off_minus_static"]>0 for x in primary) + gain=sum(x["hybrid50_minus_uniform"] for x in primary)/12 + off=sum(x["off_template_rates"]["hybrid_50"] for x in primary)/12 + assert record["wins_hybrid50_vs_uniform"]==win + assert record["offtemplate_wins_hybrid50_vs_static"]==offwin + assert isclose(record["source_mean_weighted_gain_vs_uniform"],gain,abs_tol=1e-13) + assert isclose(record["source_mean_offtemplate_hybrid50"],off,abs_tol=1e-13) + assert record["registered_primary_pass"]==(win>=9 and gain>=.10 and offwin>=10 and off>=.02) + print("NOR25 independent replay OK",len(primary),"sources", + total_checked,"decisions","PASS",record["registered_primary_pass"]) + print("fixture",len(fixture_bytes),sha256(fixture_bytes).hexdigest()) + print("outcome",len(result_bytes),sha256(result_bytes).hexdigest()) + + +if __name__=="__main__": + ap=argparse.ArgumentParser() + ap.add_argument("--fixture",type=Path,required=True) + ap.add_argument("--full",type=Path,required=True) + args=ap.parse_args() + replay(args.fixture,args.full) diff --git a/research/nor25_robust_audits/results/nor25_original_first_receipt.json b/research/nor25_robust_audits/results/nor25_original_first_receipt.json new file mode 100644 index 000000000..13c9ca59e --- /dev/null +++ b/research/nor25_robust_audits/results/nor25_original_first_receipt.json @@ -0,0 +1,63 @@ +{ + "schema": "nor25.first_sha_locked_original_receipt.v1", + "registered_before_data_commit": "da075255e2d5e188d5a84f3febbcc7b162d08b79", + "first_hosted_run_id": 43885131079, + "independent_replay_job_id": 133362682358, + "original_ci_artifact_id": 14233747860, + "fixture": { + "name": "nor25_fixture.json", + "bytes": 2187225, + "sha256": "39f69654ed17b970088f405d8b8db171b5042459307d923fb3c7cc32b1b3b6bf", + "public_only": true, + "sources": 12 + }, + "outcome": { + "name": "nor25_full.json", + "bytes": 859176, + "sha256": "901bd3b8ac9ac3335fc5e26cd69ee8d0ea9c81d7ba8fae3a508c7e9bcc14958f", + "trial_count": 1024, + "source_count": 12, + "independent_replayed_decisions": 4423680 + }, + "primary": { + "registered_pass": true, + "wins_hybrid50_vs_uniform": 11, + "offtemplate_wins_hybrid50_vs_static": 12, + "weighted_source_mean_hybrid50_minus_uniform": 0.20819498697916666, + "source_mean_offtemplate_hybrid50": 0.031656901041666664 + }, + "weighted_in_template_source_means": { + "uniform": 0.06215, + "shuffled_prior": 0.059945, + "static_prior": 0.389201, + "posterior": 0.391056, + "hybrid_25": 0.338232, + "hybrid_50": 0.270345, + "hybrid_75": 0.179028, + "oracle_support": 0.47972 + }, + "off_template_source_means": { + "uniform": 0.061523, + "static_prior": 0, + "posterior": 0, + "hybrid_25": 0.015625, + "hybrid_50": 0.031657, + "hybrid_75": 0.043213, + "oracle_support": 0.083903 + }, + "source_public_sha256_order": [ + "bbcb64dd80f6ed096d1e46901e7237e57e0c5ec0dc5b702e2f6cff6f4ca3c734", + "2693be532a26894d1aab7648478846d25e1b94e9232d6383462f97a009bdf47d", + "862385ae26662719cedbfa98e6ed4aa27aeb96184404575c81adad5aae57b446", + "708c8813ade524dbbb4ad65ad07e07155f1262fbea3e3d36f93e626d78de38a1", + "d343975bb825ab55f01c16c752faf9c429a82b5962e59d5a77f8697fe18fb1d4", + "55b2af19c1489ed1cf028564793faeb932ef0fec562caf3e6e491c4720916c80", + "4643c02c7f6fa642090bdbd7890c7440b59e2011b77a6175dc0d15da6ab4591f", + "ce70fbd1bb17fa7316907472ff8e934788ccadaf766a7a921184bf8358fccd14", + "94593a85372bad444f5cc5badbfa476684f26537e0310bbc734346e299ff8489", + "9cd92deab0d747ebdcae45d78d7b29005463b062162caba430ec631e89a74d79", + "6a9e198a523983989cc2f5e179ce0e91364c84cc54740941ca48c2c1e6b30bd9", + "bdcbbfacfa977fdc3b92d8c1988d2e6c1824e12cd0cf2bb61058a1939cdd3269" + ], + "interpretation": "Source-level synthetic fixed blind attacks under honest external target witness; pseudorandom seeds provide replay not production unpredictability." +} diff --git a/research/nor25_robust_audits/test_experiment.py b/research/nor25_robust_audits/test_experiment.py new file mode 100644 index 000000000..f5f975c3f --- /dev/null +++ b/research/nor25_robust_audits/test_experiment.py @@ -0,0 +1,113 @@ +"""NOR-25 source split, audit support, deterministic policies and exact blind bound.""" +from __future__ import annotations + +from fractions import Fraction +from itertools import combinations +from math import comb +import unittest + +from research.nor25_robust_audits import experiment as e +from research.nor24_adaptive_audits import experiment as n +from research.rrc_compactification import compound25 as corpus +from research.nor21_degree_scaling import experiment as nor21 + + +class NOR25RobustAuditTests(unittest.TestCase): + def test_frozen_params_prior_and_source_disjointness(self): + self.assertEqual(e.SOURCE_OFFSET, 99325000) + self.assertEqual(e.REPLICATES, (4, 5)) + self.assertEqual(e.SOURCE_COUNT, 12) + self.assertEqual(e.TRIALS, 1024) + self.assertEqual(e.PRIOR_NUMERATORS, (295, 246, 153, 78)) + self.assertEqual(sum(e.PRIOR_NUMERATORS), e.PRIOR_DENOMINATOR) + self.assertEqual(e.reserve_size("hybrid_25",16),4) + self.assertEqual(e.reserve_size("hybrid_50",16),8) + self.assertEqual(e.reserve_size("hybrid_75",16),12) + self.assertEqual(len(set(e.source_seed(r,d,f) for r in e.REPLICATES + for d in e.DEGREES for f in e.FAMILIES)),12) + original = {n.source_seed(r,d,f) + for r in n.TRAIN_REPS+n.TEST_REPS + for d in n.DEGREES for f in n.FAMILIES} + fresh = {e.source_seed(r,d,f) for r in e.REPLICATES + for d in e.DEGREES for f in e.FAMILIES} + self.assertTrue(fresh.isdisjoint(original)) + + def test_hypergeometric_minimax_exact_small_universe(self): + for m in range(4, 9): + for k in range(1, min(5,m)+1): + for u in range(k+1): + t = k-u + for radius in range(1,min(3,m-t)+1): + T = set(range(t)) + remaining = tuple(range(t,m)) + samples = tuple(combinations(remaining,u)) + assert len(samples) == comb(m-t,u) + worst = Fraction(1) + for A in combinations(range(m),radius): + attack = set(A) + hits = sum(bool((T|set(R))&attack) for R in samples) + rate = Fraction(hits,len(samples)) + worst = min(worst,rate) + if not (attack&T): + self.assertEqual(rate,e.blind_floor(m,k,u,radius)) + else: + self.assertEqual(rate,1) + self.assertEqual(worst,e.blind_floor(m,k,u,radius)) + + def test_hybrid_uniform_reserve_independent_seed_and_exact_sizes(self): + m=769 + static_order=tuple(range(64)) + for policy in e.MIXED_FRACTIONS: + for budget in e.BUDGETS: + x=e.hybrid_schedule(static_order,m,"c"*64,policy,budget,17) + y=e.hybrid_schedule(static_order,m,"c"*64,policy,budget,17) + self.assertEqual(x,y) + self.assertEqual(len(x),budget) + self.assertEqual(len(set(x)),budget) + t=budget-e.reserve_size(policy,budget) + self.assertEqual(x[:t], static_order[:t]) + self.assertTrue(set(x[t:]).isdisjoint(x[:t])) + self.assertGreater(e.blind_floor(769,16,8,4),Fraction(2,100)) + self.assertGreater(e.blind_floor(1537,16,8,4),Fraction(2,100)) + self.assertEqual(e.blind_floor(769,16,0,4),0) + self.assertEqual(e.blind_floor(769,16,16,4), + Fraction(1)-Fraction(comb(769-4,16),comb(769,16))) + + def test_all_equal_budget_arms_and_informed_evasion(self): + y=tuple(i*i if i%7 == 0 else -i for i in range(769)) + h=corpus.Header("I",80,32,1) + supports=n.supports(y,h) + allplans=e.policy_schedules(supports,"f"*64,12) + self.assertEqual(allplans,e.policy_schedules(supports,"f"*64,12)) + for budget in e.BUDGETS: + for arm in e.ARMS: + for kind in e.ALL_KINDS: + p=allplans[(arm,kind,budget)] if arm=="oracle_support" \ + else allplans[(arm,budget)] + self.assertEqual(len(set(p)),budget) + self.assertTrue(all(0<=i<769 for i in p)) + for radius in e.RADIUS: + attack=n.informed_attack(p,supports[kind],radius) + self.assertEqual(len(attack),radius) + self.assertTrue(set(p).isdisjoint(attack)) + self.assertFalse(e.exact_detection(y,y,p,attack,1)) + self.assertFalse(e.exact_detection(y,y,p,attack,4294049777)) + + def test_original_native_verifier_on_one_new_public_source(self): + seen=set() + row=e.generate_source(4,512,e.FAMILIES[0],seen) + self.assertEqual(row["split"],"TEST") + self.assertEqual(len(seen),1) + self.assertTrue(all(s not in row for s in ("program","future","attack"))) + c,h=n.public_only_case(row) + self.assertIsNone(c.program) + self.assertEqual(c.future,()) + self.assertEqual(nor21.native_mask(c,h,512), + row["original_public_accept_mask"]) + prop=n.public_proposal(row) + self.assertEqual(prop["mask"],row["original_public_accept_mask"]) + self.assertEqual(len(prop["predicted"]),769) + + +if __name__=="__main__": + unittest.main()