diff --git a/.github/workflows/nor24-adaptive-audits.yml b/.github/workflows/nor24-adaptive-audits.yml new file mode 100644 index 000000000..a739edab6 --- /dev/null +++ b/.github/workflows/nor24-adaptive-audits.yml @@ -0,0 +1,134 @@ +name: NOR-24 preregistered trained posterior coordinate audit + +on: + push: + paths: + - 'research/nor24_adaptive_audits/**' + - '.github/workflows/nor24-adaptive-audits.yml' + pull_request: + paths: + - 'research/nor24_adaptive_audits/**' + - '.github/workflows/nor24-adaptive-audits.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + original-source-locked-first-run-independent-replay: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: SHA-pin and independently replay all original 24 sources and 2,764,800 heldout decisions + run: python research/nor24_adaptive_audits/original_archive_audit.py + + exact-controls-and-source-isolation: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Exhaustive finite binomial, sequential scheduling, true-witness and split tests + run: python -m unittest research.nor24_adaptive_audits.test_experiment -v + + first-source-locked-training-and-test: + needs: exact-controls-and-source-isolation + runs-on: ubuntu-24.04 + timeout-minutes: 40 + env: + PYTHONHASHSEED: '0' + OMP_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Materialize 24 fresh public-only source identities and disjoint train-test split + run: | + python research/nor24_adaptive_audits/experiment.py \ + --make-fixture /tmp/nor24_fixture.json + - name: Freeze public source identities before training attack labels + run: | + python - <<'PY' + import json + from pathlib import Path + from hashlib import sha256 + from collections import Counter + raw=Path('/tmp/nor24_fixture.json').read_bytes() + o=json.loads(raw) + assert o['schema']=='nor24.public_source_only_24_disjoint_train_test.v1' + assert o['new_source_offset']==94324000 + assert o['public_only'] and o['private_program_and_target_absent'] + assert o['heldout_attack_locations_absent'] + assert o['train_replicates']==[0,1] and o['test_replicates']==[2,3] + assert len(o['cases'])==24 + assert len({x['full_public_input_sha256'] for x in o['cases']})==24 + assert Counter(x['split'] for x in o['cases'])=={'TRAIN':12,'TEST':12} + assert all('future' not in x and 'program' not in x and 'attack' not in x for x in o['cases']) + print('NOR24 FROZEN PUBLIC SOURCE SHA256',len(raw),sha256(raw).hexdigest()) + PY + - name: Fit only on TRAIN attack families and evaluate frozen posterior versus heldout controls + run: | + python research/nor24_adaptive_audits/experiment.py \ + --check-parity --fixture /tmp/nor24_fixture.json \ + --out /tmp/nor24_full.json + - name: Independent original-source target and policy replay + run: | + python research/nor24_adaptive_audits/receipt_audit.py --check \ + --fixture /tmp/nor24_fixture.json --full /tmp/nor24_full.json + - name: Verify full frozen outcome roster and report PASS or FAIL + run: | + python - <<'PY' + from pathlib import Path + from hashlib import sha256 + import json + a=Path('/tmp/nor24_fixture.json').read_bytes() + b=Path('/tmp/nor24_full.json').read_bytes() + z=json.loads(b) + assert z['schema']=='nor24.train_only_sequential_structured_coordinate_audit.v1' + assert z['fixture_sha256']==sha256(a).hexdigest() + assert len(z['source_records'])==12 + assert len(z['primary_by_source'])==12 + assert all(len(x['observations'])==225 for x in z['source_records']) + assert all(c['detected']+c['missed']==1024 and + c['informed_false_accept']==1024 and + c['informed_detected']==0 + for x in z['source_records'] for c in x['observations']) + print('NOR24 ORIGINAL FIXTURE BYTES SHA256',len(a),sha256(a).hexdigest()) + print('NOR24 ORIGINAL RESULT BYTES SHA256',len(b),sha256(b).hexdigest()) + print('NOR24 REGISTERED PRIMARY PASS',z['registered_primary_pass']) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: nor24_original_24_public_sources_and_12_heldout_audits + path: | + /tmp/nor24_fixture.json + /tmp/nor24_full.json + if-no-files-found: warn + retention-days: 90 + + separate-process-replay: + needs: first-source-locked-training-and-test + runs-on: ubuntu-24.04 + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/download-artifact@v4 + with: + name: nor24_original_24_public_sources_and_12_heldout_audits + path: /tmp/nor24_original + - name: Independently regenerate all hidden-world and heldout audit decisions + run: | + python research/nor24_adaptive_audits/receipt_audit.py --check \ + --fixture /tmp/nor24_original/nor24_fixture.json \ + --full /tmp/nor24_original/nor24_full.json diff --git a/research/nor24_adaptive_audits/README.md b/research/nor24_adaptive_audits/README.md new file mode 100644 index 000000000..cc70d8ed6 --- /dev/null +++ b/research/nor24_adaptive_audits/README.md @@ -0,0 +1,66 @@ +# NOR-24: train-only sequential coordinate auditing under structured hidden-future attacks + +**Protocol frozen before the new data** in commit 780c822, with complete design at [REGISTRATION.md](REGISTRATION.md). Continues merged NOR-23 and the companion kernel-proved [MathCan NOR-24 PR #113](https://github.com/patrickdugan/MathCan/pull/113). + +## What is being tested + +NOR-23 proved and experimentally illustrated that an external honest exact-coefficient witness detects a hidden output alteration if a sampled coordinate intersects the changed set. NOR-24 asks whether public source structure and a train-only learned prior improve *where* a limited witness budget is spent. It retains the same exact sixteen-candidate RRC25 grammar and the existing NOR-21 streamed public verifier. The witness still supplies genuinely target-dependent information; all full-target-soundness claims remain scoped to those assumptions. + +Four disclosed synthetic attack-location supports are defined entirely from public candidate output and header: the last 96 coefficients, the 96 largest absolute forecast coefficients, the 96 positions from delay+spacing, and all output coordinates as a uniform background. The policy learns the **four mixing weights**, not the attack templates themselves. Its fitted weights from 768 TRAIN labels were: tail 0.38212435, magnitude 0.31865285, lag 0.19818653, uniform 0.10103627. + +## First prospective hosted outcome + +[Original successful GitHub Actions run #43870686549](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43870686549) used **24 genuinely distinct public sources**, split into 12 TRAIN and 12 TEST, at observation degrees 512/1024 with three source families per degree per replicate. Query output lengths were 769 and 1537. All source-only fixtures excluded generating programs, hidden true outputs and target-derived witness values. Every public streamed mask was checked against the original native 16-template interpreter and every in-family full prediction matched native sealed truth. + +There were exactly **1,024 challenge ordinals per TEST source and policy**, with k=4,16,64 nested audit budgets; r=1,4,16 altered-coordinate worlds; integer changes +1 and +4294049777; blind supports fixed before the challenge. A separate informed attacker observes the inspection set before changing output coordinates. Five policies are run on matched source/trial worlds: uniform, static learned prior, sequential Bayesian no-hit posterior, shuffled static ranking, and privileged support-informed oracle. The randomized controls share exact audit budgets. + +The registered primary comparison was k=16,r=4,δ=1, with fixed family evaluation weights tail .4, magnitude .3, lag .2, uniform .1. + +| Policy | Mean weighted detection / source | +| --- | ---: | +| Uniform | 6.145833% | +| Shuffled learned-risk ranking | 6.197103% | +| Static learned-risk ranking | 34.867350% | +| **Sequential posterior** | **34.969889%** | +| Privileged support oracle | 47.443034% | + +**PASS:** posterior exceeded uniform on **11/12 TEST sources**, shuffled on **11/12**, and had a **+0.2882405599 absolute** source-mean weighted gain over uniform. Registered thresholds were 9/12 and +0.10. One degree-1024 source produced a negative paired posterior-minus-uniform difference (-0.0121). The **increment over static risk ranking was only +0.001025391**, or about **0.10 percentage points**. The result supports source-risk localization under the specified templates, with little evidence of incremental value from after-check Bayesian updates. + +### Required negative controls + +At the same k=16,r=4,δ=1, detections by attack family were: + +| Attack location | Uniform | Static prior | Posterior | Support oracle | +| --- | ---: | ---: | ---: | ---: | +| Tail window | 5.92% | 51.52% | 52.29% | 52.22% | +| Largest forecast coefficients | 6.38% | 37.83% | 37.13% | 51.76% | +| Delay+spacing window | 6.27% | 13.53% | 13.56% | 52.13% | +| Uniform background | 6.07% | 2.03% | 2.03% | 6.01% | +| **Off-template** | **6.47%** | **0.00%** | **0.00%** | **7.93%** | + +The off-template stressor alters only positions outside all three structured regions and is **excluded from the preregistered mixture**. Its zero posterior detection is a concrete assumption-break counterexample. For the informed adversary, all tests under k≤64 permit r≤16 unchecked positions inside each family support, yielding **0% detections** across every policy. Exact witness decisions were invariant to changing δ from 1 to 4,294,049,777. + +## Original source-locked evidence + +First source-only fixture: **4,300,923 bytes**, SHA-256: + + 88285e2400566c633d211071ace59784987d6458d743db478321dc90f33ef001 + +Original complete first-run JSON: **737,700 bytes**, SHA-256: + + ed54eabd70637a42c34caf66d04bcadd50f890a1ced46cea0132f8767b476807 + +The exact byte streams are committed in [results/nor24_original_hosted.zip](results/nor24_original_hosted.zip), with the [frozen receipt](results/nor24_first_frozen_receipt.json). The separate independent replayer reconstructs all 24 original exact programs and hypothetical output masks, all **768** supervised family episodes, and **12,288** heldout 64-query clean-path schedules. It independently checks **2,764,800** paired TEST policy/family/radius/budget decisions using an implementation separate from the new evaluator. All three original CI jobs passed, including the separate-process audit. + +The study is **conditional on the synthetic attack template family and the assumed authenticity of an exogenous exact target witness**. The policy's seed is deterministic for evidence replay and does not claim cryptographic unpredictability. Multiple challenge draws and counterfactual worlds share only 12 held-out source identities. A source-level transfer or adversarial guarantee in a real Lean theorem prover is outside these measurements. + +The original execution separately recorded aggregate schedule generation cost (approximately 2.1–2.2 seconds per 1024 planned schedules at degree 512 and 3.9–4.0 seconds at degree 1024, including all policy arms). The preregistered separate CPU timing of witness comparisons was **not captured as its own field**. CPU comparisons between audit policies should not be inferred from this original receipt. The correctness and detection criteria were independently replayed and are reported without substituting a performance estimate. + +## Reproduction + + python -m unittest research.nor24_adaptive_audits.test_experiment -v + python research/nor24_adaptive_audits/experiment.py --make-fixture /tmp/nor24_fixture.json + python research/nor24_adaptive_audits/experiment.py --check-parity --fixture /tmp/nor24_fixture.json --out /tmp/nor24_full.json + python research/nor24_adaptive_audits/receipt_audit.py --check --fixture /tmp/nor24_fixture.json --full /tmp/nor24_full.json + +The permanent read-only archive audit also checks both first-run byte hashes and replays the fixed program and decision grid. diff --git a/research/nor24_adaptive_audits/REGISTRATION.md b/research/nor24_adaptive_audits/REGISTRATION.md new file mode 100644 index 000000000..34f7f9d0a --- /dev/null +++ b/research/nor24_adaptive_audits/REGISTRATION.md @@ -0,0 +1,33 @@ +# NOR-24 prospective registration: trained sequential witness auditing + +**Frozen on 2026-11-16 before generating any NOR-24 training or held-out sources, attack labels, audit challenge schedules or results.** Continues merged NOR-23 (Compactification-Theory PR #191; MathCan #112). + +## Sources and information + +- Preserve original exact sixteen-program RRC25 and NOR-21 stream16 full-degree public verifier. 24 distinct source inputs: replicates 0,1 TRAIN and 2,3 TEST; each degree D=512 or 1024 and each of three NOR-21 families. Query OUTPUT length m=3D/2+1 (769 or 1537). Seed: original corpus.SEED + **94324000** + 1000003*rep + 100009*degree_index + 10007*family_index. First source within 100 attempts with unique public header, nonempty accepted mask and unanimous full query prediction. Distinct public hashes across train and test. +- Public fixture contains only two observed D-degree demos, query INPUT, inferred header, original exact acceptance mask, attempt/seed and public digest. There are NO private planted programs, true future outputs, altered coordinates, witness values or test attack labels. Freeze one exact public predicted query OUTPUT before regenerating the true program and native target in a postchoice grader. +- Four predeclared attack supports visible from the frozen candidate output and public header: tail = last 96 coordinates, magnitude = 96 largest abs(candidate coefficient) coordinates with ties at smaller indices, lag = 96 consecutive coordinates starting at header.delay + header.spacing, uniform = all m indices. An off_template stress attacker selects outside the union of the first three supports; exclude it from the primary mixture and require at least 16 eligible positions. The model is explicitly supplied these four templates. It learns mixture weights only, so results are conditional on correct support-template assumptions. + +## Registered learning, policies, attacks + +- Fit only on 64 labeled synthetic attack episodes per TRAIN source (768 episodes). Each training attack family drawn at weights tail .40, magnitude .30, lag .20, uniform .10, and four distinct attack positions sampled uniformly from that support. Draw using SHA256-derived seeds **202611240071**, public digest and episode number. Add one pseudocount to each of four family counts; fitted priors are frozen before TEST auditing. Family labels are supervised data, never inferred from test targets. +- TEST attacks: kinds tail, magnitude, lag, uniform and off_template; changed coordinate counts r={1,4,16}; integer deltas δ={1,4294049777}. For each TEST source/kind/r, fix the blind set with SHA256 seed **202611240072**, public digest, kind and r, INDEPENDENT of later audit draws. Both magnitudes reuse that set. +- Audit budgets k={4,16,64}, **1024** trial ordinals per TEST source/arm. Each policy draws an ordered 64-coordinate clean-witness-path schedule using SHA256 seed **202611240073**, digest, arm, and ordinal. Budget checks use nested prefixes so source/world/trial comparisons are paired. +- Arms: + 1. uniform: independently shuffled range(m). + 2. static_prior: rank coordinates by sum_f pi_f * 1{index in support_f}/|support_f|; seeded randomized ties. + 3. posterior: sequentially select highest conditional probability of an attack at next index, given all previous authentic audit checks matched. Calibration radius rho=4. For each family f, after t_f matched checks in S_f: likelihood L_f=choose(|S_f|-t_f,rho)/choose(|S_f|,rho); posterior family weight pi_f*L_f normalized; next-index score sum_f posterior_f * rho*1{i in S_f}/(|S_f|-t_f). Select maximum among unchecked, break equal scores using independent seeded tie randomness. The clean-path schedule is extensionally the actual sequential policy until first mismatch; stop at mismatch. + 4. shuffled_prior: uniform random permutation of the full static_prior coordinate order, retaining the rank distribution but destroying its localization. + 5. oracle_support: privileged upper bound given the true attack family, selecting a seeded random order inside its support. Never give the other arms this family label. +- A separately labeled informed adversary sees each policy's realized k-coordinate schedule and chooses all r changes in unchecked positions of its declared support, which is always feasible since k+r<=80 and |S|>=96. Expected exact detection zero. + +## Frozen scoring and control + +- On each test source, each kind×radius×arm×k calculate blind detection counts /1024, informed-evasion counts, exact original public mask parity and valid-target acceptance. Reuse both δ values to verify exact magnitude invariance. Report source-level deltas versus uniform, shuffled and static. +- Primary evaluated at k=16,r=4,δ=1: weighted detection over four in-template kinds using weights tail .4, magnitude .3, lag .2, uniform .1. **PASS only if posterior exceeds uniform on >=9/12 held-out sources, exceeds shuffled on >=9/12, and gains >=0.10 absolute in pooled source-weighted mean over uniform.** Failure retained as FAIL with all observations. No predefined advantage requirement for posterior versus static. +- Off-template attacks are a separate stress readout and excluded from the primary weighted mean; do not upgrade passes on k= 0 and lag_start + SUPPORT_SIZE <= m + top = sorted(range(m), key=lambda i: (-abs(predicted[i]), i))[:SUPPORT_SIZE] + regions = { + "tail": frozenset(range(m-SUPPORT_SIZE, m)), + "magnitude": frozenset(top), + "lag": frozenset(range(lag_start, lag_start+SUPPORT_SIZE)), + "uniform": frozenset(range(m)), + } + region_union = regions["tail"] | regions["magnitude"] | regions["lag"] + regions[STRESS] = frozenset(range(m)) - region_union + assert all(len(regions[f]) == SUPPORT_SIZE for f in KINDS[:3]) + assert len(regions["uniform"]) == m + assert len(regions[STRESS]) >= max(RADII) + return regions + + +def training_counts(rows, source_proposals): + counts = Counter({f: 0 for f in KINDS}) + selected = [] + for row in rows: + assert row["split"] == "TRAIN" + digest = row["full_public_input_sha256"] + proposal = source_proposals[digest] + regs = supports(proposal["predicted"], proposal["header"]) + for episode in range(TRAIN_EPISODES): + rng = random.Random(stream_seed(TRAIN_STREAM, digest, episode)) + draw = rng.random() + acc = 0.0 + kind = KINDS[-1] + for candidate_kind, weight in zip(KINDS, PRIOR_WEIGHTS): + acc += weight + if draw < acc: + kind = candidate_kind + break + positions = tuple(sorted(rng.sample(sorted(regs[kind]), TRAIN_RADIUS))) + counts[kind] += 1 + selected.append([digest, episode, kind, positions]) + assert sum(counts.values()) == 12 * TRAIN_EPISODES + pi = {kind: (counts[kind] + 1) / (12 * TRAIN_EPISODES + len(KINDS)) + for kind in KINDS} + assert abs(sum(pi.values()) - 1) < 1e-12 + receipt_sha = sha256(json.dumps(selected, separators=(",", ":")).encode()).hexdigest() + return counts, pi, receipt_sha + + +def blind_attack(digest, kind, radius, reg): + if kind not in ALL_KINDS or radius not in RADII: + raise ValueError("attack outside frozen grid") + rng = random.Random(stream_seed(ATTACK_STREAM, digest, kind, radius)) + return frozenset(rng.sample(sorted(reg[kind]), radius)) + + +def conditional_nohit_count(s, already, radius=CALIBRATION_RADIUS): + if s - already < radius: + return 0 + return comb(s-already, radius) + + +def risk_scores(regions, prior, m): + scores = [0.0] * m + for kind in KINDS: + part = prior[kind] / len(regions[kind]) + for j in regions[kind]: + scores[j] += part + return scores + + +def static_schedule(regions, prior, digest, trial): + scores = risk_scores(regions, prior, len(regions["uniform"])) + rng = random.Random(stream_seed(CHALLENGE_STREAM, digest, "static_prior", trial)) + return tuple(sorted(range(len(scores)), key=lambda i: (-scores[i], rng.random()))[:64]) + + +def sequential_nohit_schedule(regions, prior, digest, trial): + """Exact sequential posterior update along the authentic all-matched path. + + Every altered-world run follows the same path UNTIL it hits a changed + coefficient, where it rejects. Grouping coordinates by support-membership + signature reduces complexity without changing the greedy policy. + """ + rng = random.Random(stream_seed(CHALLENGE_STREAM, digest, "posterior", trial)) + groups = {} + for i in range(len(regions["uniform"])): + key = tuple(f for f in KINDS if i in regions[f]) + groups.setdefault(key, []).append(i) + for pool in groups.values(): + rng.shuffle(pool) + taken = {f: 0 for f in KINDS} + denom = {f: comb(len(regions[f]), CALIBRATION_RADIUS) for f in KINDS} + chosen = [] + for step in range(64): + weights = {} + for f in KINDS: + s = len(regions[f]) + weights[f] = (prior[f] * conditional_nohit_count(s, taken[f]) / + denom[f]) + norm = sum(weights.values()) + assert norm > 0 + best = None + best_score = -1.0 + ties = [] + for key, pool in groups.items(): + if not pool: + continue + val = sum(weights[f] * CALIBRATION_RADIUS / + (len(regions[f]) - taken[f]) + for f in key) / norm + if val > best_score + 1e-15: + best_score = val + ties = [key] + elif abs(val - best_score) <= 1e-15: + ties.append(key) + assert ties + best = rng.choice(ties) + index = groups[best].pop() + chosen.append(index) + for f in best: + taken[f] += 1 + assert len(chosen) == len(set(chosen)) == 64 + return tuple(chosen) + + +def policy_schedules(regions, prior, digest, trial): + m = len(regions["uniform"]) + rng = random.Random(stream_seed(CHALLENGE_STREAM, digest, "uniform", trial)) + seq = list(range(m)) + rng.shuffle(seq) + uniform = tuple(seq[:64]) + static = static_schedule(regions, prior, digest, trial) + posterior = sequential_nohit_schedule(regions, prior, digest, trial) + shuffle_rng = random.Random( + stream_seed(CHALLENGE_STREAM, digest, "shuffled_prior", trial)) + permutation = list(range(m)) + shuffle_rng.shuffle(permutation) + shuffled = tuple(permutation[i] for i in static) + result = {"uniform": uniform, "static_prior": static, + "posterior": posterior, "shuffled_prior": shuffled} + for kind in ALL_KINDS: + oracle_rng = random.Random(stream_seed( + CHALLENGE_STREAM, digest, "oracle_support", kind, trial)) + pool = list(sorted(regions[kind])) + oracle_rng.shuffle(pool) + result[("oracle_support", kind)] = tuple(pool[:64]) + assert all(len(v) == len(set(v)) == 64 for v in result.values()) + return result + + +def exact_witness_accepts(proposed, true, checked, attacked, delta): + if len(proposed) != len(true) or delta == 0: + raise ValueError("misconfigured trusted witness") + return all(proposed[i] == true[i] + (delta if i in attacked else 0) + for i in checked) + + +def informed_attack(checked, support, radius): + used = set(checked) + unseen = support.difference(used) + if len(unseen) < radius: + raise ValueError("informed attack needs uninspected support") + return frozenset(islice(iter(unseen), radius)) + + +def private_truth_only_after_proposal(row, predicted): + rep, d, family = row["replicate"], row["observation_degree"], row["family"] + rng = random.Random(source_seed(rep, d, family)) + prog = query = demos = None + for _ in range(row["selected_attempt"] + 1): + prog = nor21.new_header_program(rng) + demos = tuple((src := nor21.public_source(rng, family, 3*d//2), + corpus.execute(src, prog)) 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(s[:d+1]), list(y[:d+1])] for s, y in demos] + assert row["public_query_input"] == list(query) + actual = corpus.execute(query, prog) + assert predicted == actual + return actual + + +def evaluate(fixture_path): + fixture, fixture_sha = load_fixture(fixture_path) + train_rows = [r for r in fixture["cases"] if r["split"] == "TRAIN"] + test_rows = [r for r in fixture["cases"] if r["split"] == "TEST"] + proposals = {r["full_public_input_sha256"]: public_proposal(r) + for r in fixture["cases"]} + counts, prior, train_sha = training_counts(train_rows, proposals) + source_records = [] + for row in test_rows: + digest = row["full_public_input_sha256"] + proposal = proposals[digest] + target = private_truth_only_after_proposal(row, proposal["predicted"]) + regions = supports(proposal["predicted"], proposal["header"]) + attacks = {(kind, r): blind_attack(digest, kind, r, regions) + for kind in ALL_KINDS for r in RADII} + cells = {(kind, r, k, arm): {"detected": 0, "missed": 0, + "informed_detected": 0, + "informed_false_accept": 0} + for kind in ALL_KINDS for r in RADII + for k in BUDGETS for arm in ARMS} + clock_ns = Counter({arm: 0 for arm in ARMS}) + for trial in range(TRIALS): + start = time.perf_counter_ns() + schedules = policy_schedules(regions, prior, digest, trial) + total_ns = time.perf_counter_ns() - start + # Timed separately in a subsequent pass; aggregate as proposal + # scheduling CPU for all non-oracle policies together. + clock_ns["all_schedule_generation"] += total_ns + for kind in ALL_KINDS: + for arm in ARMS: + plan = schedules[arm] if arm != "oracle_support" else schedules[(arm,kind)] + for k in BUDGETS: + checked = plan[:k] + assert len(checked) == len(set(checked)) == k + assert exact_witness_accepts( + proposal["predicted"], target, checked, + frozenset(), DELTAS[0]) + for radius in RADII: + attack = attacks[(kind, radius)] + # A strict truthful witness returns exact target + # values; pair two nonzero magnitudes and ensure + # that their decisions coincide, without labels + # entering any public audit scheduling function. + baseline = exact_witness_accepts( + proposal["predicted"], target, + checked, attack, DELTAS[0]) + larger = exact_witness_accepts( + proposal["predicted"], target, + checked, attack, DELTAS[1]) + assert baseline == larger + cell = cells[(kind, radius, k, arm)] + cell["missed" if baseline else "detected"] += 1 + changed_after = informed_attack( + checked, regions[kind], radius) + # The informed attacker must evade every + # inspected coordinate, even for oracle policy. + assert exact_witness_accepts( + proposal["predicted"], target, checked, + changed_after, DELTAS[0]) + assert exact_witness_accepts( + proposal["predicted"], target, checked, + changed_after, DELTAS[1]) + cell["informed_false_accept"] += 1 + for cell in cells.values(): + assert cell["detected"] + cell["missed"] == TRIALS + assert cell["informed_detected"] == 0 + assert cell["informed_false_accept"] == TRIALS + source_records.append({ + "split": "TEST", "replicate": row["replicate"], + "observation_degree": row["observation_degree"], + "family": row["family"], "public_sha256": digest, + "chosen_class": proposal["chosen_class"], + "public_mask": proposal["mask"], + "public_prediction_sha256": proposal["sha256"], + "sealed_true_future_sha256_postchoice": sha_target(target), + "support_sizes": {k: len(regions[k]) for k in ALL_KINDS}, + "attack_positions": { + f"{kind}|{r}": sorted(attacks[(kind, r)]) + for kind in ALL_KINDS for r in RADII}, + "schedule_generation_ns_total": clock_ns["all_schedule_generation"], + "observations": [ + {"kind": kind, "radius": r, "budget": k, "policy": arm, + **cells[(kind, r, k, arm)]} + for kind in ALL_KINDS for r in RADII + for k in BUDGETS for arm in ARMS + ], + }) + primary_by_source = [] + for rec in source_records: + rates = {} + for arm in ARMS: + cells = {(z["kind"], z["radius"], z["budget"], z["policy"]): z + for z in rec["observations"]} + rates[arm] = sum( + PRIOR_WEIGHTS[i] * cells[(kind, 4, 16, arm)]["detected"] / TRIALS + for i, kind in enumerate(KINDS)) + primary_by_source.append({ + "public_sha256": rec["public_sha256"], + "degree": rec["observation_degree"], + "family": rec["family"], "rates": rates, + "posterior_minus_uniform": rates["posterior"]-rates["uniform"], + "posterior_minus_shuffled": rates["posterior"]-rates["shuffled_prior"], + "posterior_minus_static": rates["posterior"]-rates["static_prior"], + }) + wins_uniform = sum(v["posterior_minus_uniform"] > 0 for v in primary_by_source) + wins_shuffle = sum(v["posterior_minus_shuffled"] > 0 for v in primary_by_source) + mean_gain = statistics.mean(v["posterior_minus_uniform"] for v in primary_by_source) + registered_pass = wins_uniform >= 9 and wins_shuffle >= 9 and mean_gain >= .10 + return { + "schema": SCHEMA, "fixture_sha256": fixture_sha, + "public_source_count": SOURCE_COUNT, "train_source_count": 12, + "heldout_source_count": TEST_COUNT, "trial_count": TRIALS, + "blind_attack_fixed_before_challenges": True, + "all_public_proposals_frozen_before_private_target_access": True, + "learned_prior_from_train_only": True, + "trusted_witness_values_are_new_external_information": True, + "family_support_templates_are_declared_model_prior": True, + "train_family_counts": dict(counts), + "fitted_prior": prior, "train_attack_position_receipt_sha256": train_sha, + "weighted_evaluation_mixture": dict(zip(KINDS, PRIOR_WEIGHTS)), + "source_records": source_records, "primary_by_source": primary_by_source, + "primary_wins_vs_uniform": wins_uniform, + "primary_wins_vs_shuffle": wins_shuffle, + "primary_weighted_mean_gain_vs_uniform": mean_gain, + "registered_primary_pass": registered_pass, + "scope": ("Finite synthetic RRC25 and assumed authentic exact target witness. " + "Test attack support templates are disclosed to the policy, " + "only labeled prior probabilities fitted on training sources. " + "Blind and informed adversary protocols differ. " + "1024 challenge replicates do not create new source cases."), + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--make-fixture", type=Path) + parser.add_argument("--fixture", type=Path) + parser.add_argument("--out", type=Path) + parser.add_argument("--check-parity", action="store_true") + args = parser.parse_args() + if args.make_fixture: + if args.fixture or args.out: + parser.error("fixture registration and heldout evaluation are separate") + raw = canonical(make_fixture()) + args.make_fixture.parent.mkdir(parents=True, exist_ok=True) + args.make_fixture.write_bytes(raw) + print("NOR24 PUBLIC 24-SOURCE FIXTURE", len(raw), sha256(raw).hexdigest()) + return + if not args.fixture: + parser.error("--fixture required") + result = evaluate(args.fixture) + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_bytes(canonical(result)) + print("NOR24 TRAIN FAMILY COUNTS", result["train_family_counts"]) + print("NOR24 FITTED TRAIN PRIOR", result["fitted_prior"]) + print("NOR24 TEST SOURCE PAIRED", [(z["degree"], + round(z["posterior_minus_uniform"],4), + round(z["posterior_minus_shuffled"],4), + round(z["posterior_minus_static"],4)) + for z in result["primary_by_source"]]) + print("NOR24 PRIMARY", result["registered_primary_pass"], + result["primary_wins_vs_uniform"], + result["primary_wins_vs_shuffle"], + round(result["primary_weighted_mean_gain_vs_uniform"],6)) + if args.check_parity: + assert result["public_source_count"] == 24 + assert all(z["sealed_true_future_sha256_postchoice"] == + z["public_prediction_sha256"] for z in result["source_records"]) + assert all(c["informed_detected"] == 0 and c["informed_false_accept"] == TRIALS + for z in result["source_records"] for c in z["observations"]) + + +if __name__ == "__main__": + main() diff --git a/research/nor24_adaptive_audits/original_archive_audit.py b/research/nor24_adaptive_audits/original_archive_audit.py new file mode 100644 index 000000000..79f4660f9 --- /dev/null +++ b/research/nor24_adaptive_audits/original_archive_audit.py @@ -0,0 +1,44 @@ +"""NOR-24 immutable original source and heldout result byte audit.""" +from __future__ import annotations +from hashlib import sha256 +import json +from pathlib import Path +from zipfile import ZipFile +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.receipt_audit import audit + +def audit_archived_original(): + receipt=json.loads((HERE/"results/nor24_first_frozen_receipt.json").read_text()) + assert receipt["schema"]=="nor24.first_preregistered_train_only_posterior_audits.v1" + assert receipt["preregistered_source_commit"]==( + "780c822c34314c0dead2cd1331280ca2f8978332") + assert receipt["registered_primary_pass"] and receipt["independent_replay_pass"] + with ZipFile(HERE/"results/nor24_original_hosted.zip") as z: + assert sorted(z.namelist())==["nor24_fixture.json","nor24_full.json"] + assert z.testzip() is None + fixture=z.read("nor24_fixture.json") + full=z.read("nor24_full.json") + assert len(fixture)==receipt["fixture_bytes"]==4300923 + assert len(full)==receipt["result_bytes"]==737700 + assert sha256(fixture).hexdigest()==receipt["fixture_sha256"] + assert sha256(full).hexdigest()==receipt["result_sha256"] + assert receipt["fixture_sha256"]==( + "88285e2400566c633d211071ace59784987d6458d743db478321dc90f33ef001") + assert receipt["result_sha256"]==( + "ed54eabd70637a42c34caf66d04bcadd50f890a1ced46cea0132f8767b476807") + result=audit(fixture,full) + assert result["original_sources_replayed"]==24 + assert result["train_episodes"]==768 + assert result["test_clean_schedules_replayed"]==12288 + assert result["independent_policy_world_budget_checks"]==2764800 + assert result["registered_primary_pass"] + return result + +if __name__=="__main__": + print("NOR24 ORIGINAL FIRST RECEIPT VERIFIED",audit_archived_original()) diff --git a/research/nor24_adaptive_audits/receipt_audit.py b/research/nor24_adaptive_audits/receipt_audit.py new file mode 100644 index 000000000..1b443b7bb --- /dev/null +++ b/research/nor24_adaptive_audits/receipt_audit.py @@ -0,0 +1,192 @@ +"""NOR-24 independent original-interpreter and full trial replay. + +The grader imports original RRC25 semantics and a separately written +challenge planner, never the NOR-24 experiment/heldout policy implementation. +""" +from __future__ import annotations +import argparse,json,random,statistics,sys +from collections import Counter +from hashlib import sha256 +from pathlib import Path +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT)) +from research.rrc_compactification import compound25 as base +from research.nor21_degree_scaling import receipt_audit as original +from research.nor24_adaptive_audits import replay_schedules as independent + +KINDS=independent.F +ALL=independent.K +ARMS=independent.A +WEIGHTS=(.40,.30,.20,.10) +RADII=(1,4,16) +BUDGETS=(4,16,64) +N=1024 + +def hash_future(y): + return sha256(json.dumps(y,separators=(",",":")).encode()).hexdigest() + +def regenerate(row): + rep,d,family=row["replicate"],row["observation_degree"],row["family"] + assert rep in range(4) and d in (512,1024) + seed=(base.SEED+94324000+1000003*rep+ + 100009*(0 if d==512 else 1)+10007*( + ("wide_dense_small","wide_sparse_small","wide_rational_short").index(family))) + assert seed==row["source_seed"] + rng=random.Random(seed) + planted=demos=query=None + for _ in range(row["selected_attempt"]+1): + planted=(rng.choice(base.OPS),rng.choice(base.DELAYS), + rng.choice(base.SPACINGS),rng.choice(base.AMPLITUDES), + rng.choice(base.OPS),rng.choice(base.OPS)) + demos=tuple((src:=original.independent_source(rng,family,3*d//2), + base.execute(src,planted)) for _ in range(2)) + query=original.independent_source(rng,family,3*d//2) + assert planted is not None + assert row["demos"]==[[list(s[:d+1]),list(y[:d+1])] for s,y in demos] + assert row["public_query_input"]==list(query) + h=row["public_header"] + header=base.Header(h["base"],h["delay"],h["spacing"],h["amplitude"]) + assert planted[:4]==(header.base,header.delay,header.spacing,header.amplitude) + public=base.Case("nor24-independent",family, + tuple((tuple(s),tuple(y)) for s,y in row["demos"]),tuple(query),(),None) + assert public.program is None and public.future==() + assert original.public_source_hash(public,d)==row["full_public_input_sha256"] + mask=original.independent_native_mask(public,header,d) + assert mask==row["original_public_accept_mask"] and mask>0 + chosen=next(j for j in range(16) if mask&(1<=radius + assert record["schedule_generation_ns_total"]>0 + entries={(z["kind"],z["radius"],z["budget"],z["policy"]):z + for z in record["observations"]} + assert len(entries)==5*3*3*5 + for index,z in entries.items(): + n=count[index] + assert z["detected"]==n,(key,index) + assert z["missed"]==N-n + assert z["informed_detected"]==0 + assert z["informed_false_accept"]==N + rates={arm:sum(WEIGHTS[j]*count[(f,4,16,arm)]/N + for j,f in enumerate(KINDS)) for arm in ARMS} + primary.append({ + "public_sha256":key,"degree":row["observation_degree"], + "family":row["family"],"rates":rates, + "posterior_minus_uniform":rates["posterior"]-rates["uniform"], + "posterior_minus_shuffled":rates["posterior"]-rates["shuffled_prior"], + "posterior_minus_static":rates["posterior"]-rates["static_prior"], + }) + assert result["primary_by_source"]==primary + wins_u=sum(x["posterior_minus_uniform"]>0 for x in primary) + wins_s=sum(x["posterior_minus_shuffled"]>0 for x in primary) + mean=statistics.mean(x["posterior_minus_uniform"] for x in primary) + assert result["primary_wins_vs_uniform"]==wins_u + assert result["primary_wins_vs_shuffle"]==wins_s + assert abs(result["primary_weighted_mean_gain_vs_uniform"]-mean)<1e-15 + assert result["registered_primary_pass"]==( + wins_u>=9 and wins_s>=9 and mean>=.10) + return {"original_sources_replayed":24,"train_episodes":768, + "test_clean_schedules_replayed":number, + "independent_policy_world_budget_checks":number*5*5*3*3, + "registered_primary_pass":result["registered_primary_pass"]} + +def main(): + p=argparse.ArgumentParser() + p.add_argument("--fixture",type=Path) + p.add_argument("--full",type=Path) + p.add_argument("--check",action="store_true") + a=p.parse_args() + if not a.fixture or not a.full:p.error("both source and grade paths required") + receipt=audit(a.fixture.read_bytes(),a.full.read_bytes()) + print("NOR24 INDEPENDENT ORIGINAL INTERPRETER REPLAY",receipt) + if a.check:assert receipt["test_clean_schedules_replayed"]==12*1024 + +if __name__=="__main__":main() diff --git a/research/nor24_adaptive_audits/replay_schedules.py b/research/nor24_adaptive_audits/replay_schedules.py new file mode 100644 index 000000000..c009ad519 --- /dev/null +++ b/research/nor24_adaptive_audits/replay_schedules.py @@ -0,0 +1,77 @@ +"""Independent NOR-24 challenge plans, without importing experiment.py.""" +from __future__ import annotations +from collections import Counter +from hashlib import sha256 +from math import comb +import random + +F=("tail","magnitude","lag","uniform") +K=F+("off_template",) +A=("uniform","static_prior","posterior","shuffled_prior","oracle_support") + +def seed(*fields): + return int.from_bytes(sha256("|".join(str(x) for x in fields).encode("ascii")).digest(),"big") + +def regions(y,header): + m=len(y) + t=set(range(m-96,m)) + mag=set(sorted(range(m),key=lambda i:(-abs(y[i]),i))[:96]) + lag=set(range(header.delay+header.spacing,header.delay+header.spacing+96)) + out=dict(tail=t,magnitude=mag,lag=lag,uniform=set(range(m))) + out["off_template"]=set(range(m))-(t|mag|lag) + assert len(out["off_template"])>=16 + return out + +def attack(digest,kind,r,regions): + rng=random.Random(seed(202611240072,digest,kind,r)) + return set(rng.sample(sorted(regions[kind]),r)) + +def plan(regions,prior,digest,trial): + m=len(regions["uniform"]) + rng=random.Random(seed(202611240073,digest,"uniform",trial)) + q=list(range(m));rng.shuffle(q) + uniform=tuple(q[:64]) + + weight=[0.0]*m + for kind in F: + w=prior[kind]/len(regions[kind]) + for i in regions[kind]:weight[i]+=w + rng=random.Random(seed(202611240073,digest,"static_prior",trial)) + static=tuple(sorted(range(m),key=lambda i:(-weight[i],rng.random()))[:64]) + + rng=random.Random(seed(202611240073,digest,"shuffled_prior",trial)) + permutation=list(range(m));rng.shuffle(permutation) + shuffled=tuple(permutation[i] for i in static) + + rng=random.Random(seed(202611240073,digest,"posterior",trial)) + groups={} + for i in range(m): + member=tuple(f for f in F if i in regions[f]) + groups.setdefault(member,[]).append(i) + for pool in groups.values():rng.shuffle(pool) + used=Counter({f:0 for f in F}) + denominators={f:comb(len(regions[f]),4) for f in F} + posterior=[] + for _ in range(64): + likelihood={f:prior[f]*comb(len(regions[f])-used[f],4)/denominators[f] + for f in F} + total=sum(likelihood.values()) + best=-1. + choices=[] + for member,pool in groups.items(): + if not pool:continue + s=sum(likelihood[f]*4/(len(regions[f])-used[f]) for f in member)/total + if s>best+1e-15: + best=s;choices=[member] + elif abs(s-best)<=1e-15: + choices.append(member) + selected=rng.choice(choices) + posterior.append(groups[selected].pop()) + for f in selected:used[f]+=1 + out=dict(uniform=uniform,static_prior=static, + posterior=tuple(posterior),shuffled_prior=shuffled) + for kind in K: + rng=random.Random(seed(202611240073,digest,"oracle_support",kind,trial)) + q=sorted(regions[kind]);rng.shuffle(q) + out[("oracle_support",kind)]=tuple(q[:64]) + return out diff --git a/research/nor24_adaptive_audits/results/nor24_first_frozen_receipt.json b/research/nor24_adaptive_audits/results/nor24_first_frozen_receipt.json new file mode 100644 index 000000000..f6ea8b270 --- /dev/null +++ b/research/nor24_adaptive_audits/results/nor24_first_frozen_receipt.json @@ -0,0 +1,24 @@ +{ + "date_utc": "2026-11-16", + "first_completed_run": "https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43870686549", + "fixture_bytes": 4300923, + "fixture_sha256": "88285e2400566c633d211071ace59784987d6458d743db478321dc90f33ef001", + "heldout_clean_challenge_schedules_replayed": 12288, + "heldout_trials_per_source_policy": 1024, + "heldout_world_policy_budget_decisions_replayed": 2764800, + "independent_replay_pass": true, + "original_artifact_id": 14227198490, + "original_artifact_name": "nor24_original_24_public_sources_and_12_heldout_audits", + "preregistered_source_commit": "780c822c34314c0dead2cd1331280ca2f8978332", + "primary_mean_weighted_absolute_gain": 0.28824055989583336, + "primary_posterior_wins_over_shuffled": 11, + "primary_posterior_wins_over_uniform": 11, + "registered_primary_pass": true, + "result_bytes": 737700, + "result_sha256": "ed54eabd70637a42c34caf66d04bcadd50f890a1ced46cea0132f8767b476807", + "schema": "nor24.first_preregistered_train_only_posterior_audits.v1", + "scope": "Known attack-support templates and assumed truthful extra target witness. Off-template counterexample and informed attacker remain blind spots.", + "test_sources": 12, + "train_episodes": 768, + "train_sources": 12 +} diff --git a/research/nor24_adaptive_audits/results/nor24_original_hosted.zip b/research/nor24_adaptive_audits/results/nor24_original_hosted.zip new file mode 100644 index 000000000..09d6d6806 Binary files /dev/null and b/research/nor24_adaptive_audits/results/nor24_original_hosted.zip differ diff --git a/research/nor24_adaptive_audits/test_experiment.py b/research/nor24_adaptive_audits/test_experiment.py new file mode 100644 index 000000000..1edbdc137 --- /dev/null +++ b/research/nor24_adaptive_audits/test_experiment.py @@ -0,0 +1,104 @@ +"""NOR-24 exact source isolation, bounded Bayesian update and blind controls.""" +from __future__ import annotations + +from itertools import combinations +from math import comb +import unittest + +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 + + +class NOR24SequentialAuditTests(unittest.TestCase): + def test_conditional_nohit_counts_exhaustive(self): + for s in range(2, 9): + universe = tuple(range(s)) + for r in range(s+1): + for t in range(s+1): + remaining = set(range(t, s)) + direct = sum(set(attack) <= remaining + for attack in combinations(universe, r)) + self.assertEqual(direct, n.conditional_nohit_count(s, t, r)) + self.assertEqual(n.conditional_nohit_count(96, 0, 4), comb(96, 4)) + + def test_true_witness_rejects_exact_nonzero_shifts(self): + pred = (12, -7, 19, 47, 5, 3) + for shift in n.DELTAS: + self.assertTrue(n.exact_witness_accepts( + pred, pred, (0, 1), {4}, shift)) + self.assertFalse(n.exact_witness_accepts( + pred, pred, (0, 4), {4}, shift)) + self.assertTrue(n.exact_witness_accepts( + pred, pred, (), {4}, shift)) + self.assertFalse(n.exact_witness_accepts( + pred, pred, (4,), {4}, n.DELTAS[1])) + + def test_preregistration_params_and_disjoint_seeds(self): + self.assertEqual(n.OFFSET, 94324000) + self.assertEqual(n.TRAIN_REPS, (0,1)) + self.assertEqual(n.TEST_REPS, (2,3)) + self.assertEqual(n.TRIALS, 1024) + self.assertEqual(n.BUDGETS, (4,16,64)) + self.assertEqual(len(set( + n.source_seed(rep,deg,f) for rep in range(4) + for deg in n.DEGREES for f in n.FAMILIES)), 24) + + def test_support_sizes_schedules_and_privileged_label(self): + pred = (1,) + tuple(i*i if i%7 == 0 else -i for i in range(1, 769)) + h = corpus.Header("I", 80, 32, 1) + support = n.supports(pred, h) + self.assertEqual({k:len(support[k]) for k in n.KINDS[:3]}, + {k:96 for k in n.KINDS[:3]}) + self.assertGreater(len(support[n.STRESS]), 16) + prior = dict(zip(n.KINDS, n.PRIOR_WEIGHTS)) + plans = n.policy_schedules(support, prior, "f"*64, 0) + self.assertEqual(plans, n.policy_schedules(support, prior, "f"*64, 0)) + self.assertEqual(len(plans), len(n.ARMS)-1+len(n.ALL_KINDS)) + for arm in n.ARMS[:-1]: + self.assertEqual(len(set(plans[arm])), 64) + self.assertTrue(all(0<=i<769 for i in plans[arm])) + for kind in n.ALL_KINDS: + self.assertTrue(set(plans[("oracle_support",kind)])<=support[kind]) + self.assertEqual(len(set(plans["posterior"][:16])),16) + + def test_informed_evasion_for_each_frozen_policy(self): + pred = (1,) + tuple(0 if i%13 else i for i in range(1, 769)) + h = corpus.Header("N", 96, 24, 1) + regs = n.supports(pred, h) + plans = n.policy_schedules(regs, dict(zip(n.KINDS,n.PRIOR_WEIGHTS)), + "b"*64,2) + for kind in n.ALL_KINDS: + for arm in n.ARMS: + plan = plans[arm] if arm != "oracle_support" else plans[(arm,kind)] + for k in n.BUDGETS: + for r in n.RADII: + unchecked = n.informed_attack(plan[:k],regs[kind],r) + self.assertEqual(len(unchecked),r) + self.assertFalse(set(plan[:k])&unchecked) + self.assertTrue(n.exact_witness_accepts( + pred,pred,plan[:k],unchecked,1)) + + def test_small_real_public_source_only_and_native_mask(self): + source = n.generate_source(2,512,n.FAMILIES[0],set()) + self.assertEqual(source["split"],"TEST") + self.assertNotIn("program",source) + self.assertNotIn("future",source) + self.assertNotIn("attack",source) + c,h=n.public_only_case(source) + self.assertIsNone(c.program) + self.assertEqual(c.future,()) + proposal=n.public_proposal(source) + self.assertEqual(proposal["mask"],source["original_public_accept_mask"]) + self.assertEqual(nor21.native_mask(c,h,512),proposal["mask"]) + self.assertEqual(n.private_truth_only_after_proposal( + source,proposal["predicted"]), proposal["predicted"]) + for kind,r in ((k,16) for k in n.ALL_KINDS): + support=n.supports(proposal["predicted"],h) + attacked=n.blind_attack(source["full_public_input_sha256"], + kind,r,support) + self.assertEqual(len(attacked),16) + + +if __name__=="__main__": + unittest.main()