Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/rh-count-to-find.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: RH-CRYPTO-26 count-to-find exact control

on:
push:
paths:
- "src/spiral_ln/rh_count_to_find.py"
- "tests/test_rh_count_to_find.py"
- "scripts/verify_rh_count_to_find.py"
- "paper/rh_count_to_find_2026_11_22.md"
- ".github/workflows/rh-count-to-find.yml"
pull_request:
paths:
- "src/spiral_ln/rh_count_to_find.py"
- "tests/test_rh_count_to_find.py"
- "scripts/verify_rh_count_to_find.py"
- "paper/rh_count_to_find_2026_11_22.md"
- ".github/workflows/rh-count-to-find.yml"
workflow_dispatch:

jobs:
exact-control:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install EvalMath test requirements
run: python -m pip install -e ".[test]"
- name: Exact finite domain tests
run: python -m pytest -q tests/test_rh_count_to_find.py
- name: Generate development-only receipt
run: PYTHONPATH=src python scripts/verify_rh_count_to_find.py --phase dev --output output/rh_count_to_find/dev.json
- uses: actions/upload-artifact@v4
with:
name: rh-count-to-find-development
path: output/rh_count_to_find/dev.json
if-no-files-found: error
Comment on lines +22 to +39
41 changes: 41 additions & 0 deletions paper/rh_count_to_find_2026_11_22.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# RH-CRYPTO-26 / RH-05: what a point-count theorem does and does not buy

**Evidence class:** exact finite-domain synthetic control. **Scientific aim:** distinguish existence/counting theorems from constructive algorithms in the finite-field settings relevant to cryptographic polynomial systems.

The negative-control family is an affine equation \`a*x+b*y=c\` over \`F_p\` for nonzero \`(a,b)\`. Every instance has exactly \`p\` solutions in a domain of \`p^2\` points. Because the coefficients are explicit, a one-query witness can be constructed using a modular inverse. This is deliberately easy.

The lexicographic first-witness search cost can nevertheless range from **1** to **\`p^2-p+1\`** queries while the solution count stays exactly \`p\`. The late vertical instance \`x=p-1\` attains the worst-case bound. For uniformly random sampling without replacement, the expected first hit is \`(p^2+1)/(p+1)\`, as an exact rational number. A solution-count theorem alone provides no guarantee that a specific algorithm will find a witness quickly. This demonstration concerns the chosen black-box query order, not the intrinsic complexity of affine systems.

## Protocol

- Development primes: 17 and 31, with four linked tasks per prime.
- Confirmation primes: 43 and 53, reserved for a later independent execution.
- Each task records exact affine coefficients, exhaustive count, first lexicographic hit, a constructive witness checked by the same field equation, the extremal \`N-M+1\` bound, and the random-order expectation.
- Grading accepts only explicit field-point query sequences and reports the first verified hit. It charges the number of witness queries. Algebraic preprocessing and arithmetic cost are **outside** this pedagogical score.
- Independent unit for any empirical extrapolation is the prime/instance generator family, not all repeated point queries. Here \`n_units=2\` per phase, with eight correlated cases. No statistical generalization or causal mechanism claim is made.
- The exact count is verified by enumerating every point. The underlying combinatorial first-hit inequality follows from placing \`M\` marked items as late as possible among \`N\` slots. The rational expectation is the negative-hypergeometric minimum-order-statistic identity.

## Execution

\`\`\`bash
PYTHONPATH=src python -m spiral_ln.rh_count_to_find --phase dev --output output/rh_count_to_find_dev.json
PYTHONPATH=src pytest -q tests/test_rh_count_to_find.py
\`\`\`

An external solver can submit a JSONL line such as:

\`\`\`json
{"id":"RHCF-dev-p17-late_vertical","queries":[[16,0]]}
\`\`\`

and grade it with \`--submissions /path/to/queries.jsonl\`. The grader does not execute submitted programs or accept an unsupported proof string.

## Transfer research gate

To extend beyond affine controls, select explicit nonlinear finite-field varieties with certified cardinalities, record uniformity and degree/dimension of any point-count theorem, and add solver baselines (enumeration, random search, Gröbner/SAT or other exact algebra). Measure full field arithmetic, memory, witness verification and preprocessing. Use the independent confirmation family only after the task generator and algorithm-selection policy are frozen.

For Semaev relation search, the key question is whether a theorem about point count or prime-character cancellation yields a *constructive, lower-cost* relation acquisition algorithm. An existence theorem has to be paired with an effective extraction procedure to become a cryptanalytic improvement.

**Statistical preflight:** EvalMath's \`evalmath-mechinterp-power\` procedure was reviewed. This module is an exact synthetic math control with no neural intervention, effect threshold, sham causal measurement, or inference target. Sample power and model-specific mechanistic resolution are inapplicable. Future trained-model comparisons would need independent family-level pilot roots and the standard preflight protocol before allocating confirmation data.

Mathematical assumption ledger: [MathCan RH-CRYPTO-26](https://github.com/patrickdugan/MathCan/tree/research/rh-crypto26-assumptions-20261122/research/rh_crypto26).
22 changes: 22 additions & 0 deletions scripts/verify_rh_count_to_find.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
"""Regenerate source-pinned RH-05 exact finite-domain receipts."""
import argparse
import json
from pathlib import Path

from spiral_ln.rh_count_to_find import audit


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--phase", choices=("dev", "confirm"), default="dev")
parser.add_argument("--output", type=Path, default=Path("output/rh_count_to_find/dev.json"))
args = parser.parse_args()
result = audit(args.phase)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n", encoding="utf-8")
print(f"exact RH-05 receipt: {args.output}; {result['cases']} tasks")


if __name__ == "__main__":
main()
182 changes: 182 additions & 0 deletions src/spiral_ln/rh_count_to_find.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
"""RH-CRYPTO-26 / RH-05: exact finite-field count-to-find negative-control gym.

This is an *exact finite-domain synthetic task*, not a model-power study or a
theorem that a hard polynomial system is easy/hard. All systems here are affine
with an explicit one-query constructive solver.

Run: PYTHONPATH=src python -m spiral_ln.rh_count_to_find --phase dev
Optional grading: ... --submissions /path/to/queries.jsonl
Each submission is {"id": "...", "queries": [[x,y], ...]}.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
from dataclasses import dataclass
from fractions import Fraction
from pathlib import Path

PHASE_PRIMES = {"dev": (17, 31), "confirm": (43, 53)}
FORMS = ("early_vertical", "late_vertical", "late_horizontal", "scrambled")


def is_prime_trial(n: int) -> bool:
return n >= 2 and all(n % d for d in range(2, math.isqrt(n) + 1))


@dataclass(frozen=True)
class Instance:
p: int
a: int
b: int
c: int
id: str

def __post_init__(self):
if not is_prime_trial(self.p):
raise ValueError("p must be prime")
if self.a % self.p == 0 and self.b % self.p == 0:
raise ValueError("nonzero affine coefficient required")

def accepts(self, x: int, y: int) -> bool:
return (self.a * x + self.b * y - self.c) % self.p == 0

def construct(self):
"""Explicit affine solver; cost of inversion is outside query-count score."""
if self.b % self.p:
return (0, self.c * pow(self.b, -1, self.p) % self.p)
return (self.c * pow(self.a, -1, self.p) % self.p, 0)

def verify_by_enumeration(self):
first = None
count = 0
checks = 0
for x in range(self.p):
for y in range(self.p):
checks += 1
if self.accepts(x, y):
count += 1
if first is None:
first = checks
if count != self.p:
raise AssertionError("affine counting invariant violated")
candidate = self.construct()
if not self.accepts(*candidate):
raise AssertionError("explicit witness failed")
return {"solution_count": count, "first_lexicographic_query": first,
"enumeration_queries": checks, "constructed_witness": list(candidate),
"constructive_witness_queries": 1}


def make_instances(phase="dev"):
if phase not in PHASE_PRIMES:
raise ValueError("unknown phase")
cases = []
for p in PHASE_PRIMES[phase]:
parameters = (
(1, 0, 0),
(1, 0, p - 1),
(0, 1, p - 1),
(3, 7, p - 1),
)
for name, (a, b, c) in zip(FORMS, parameters):
cases.append(Instance(p, a, b, c, f"RHCF-{phase}-p{p}-{name}"))
return cases


def combinatorial_first_hit_bound(N: int, M: int):
"""For exactly M marked states among N, worst first hit is N-M+1."""
if not (1 <= M <= N):
raise ValueError("require 1 <= M <= N")
return N - M + 1


def uniform_without_replacement_expectation(N: int, M: int) -> Fraction:
if not (1 <= M <= N):
raise ValueError("require 1 <= M <= N")
return Fraction(N + 1, M + 1)


def exact_first_hit_distribution(N: int, M: int):
"""Probability of earliest of M uniformly sampled marked locations."""
if not (1 <= M <= N):
raise ValueError("require 1 <= M <= N")
denom = math.comb(N, M)
return [Fraction(math.comb(N - t, M - 1), denom)
for t in range(1, N - M + 2)]


def grade_queries(case: Instance, queries):
if not isinstance(queries, list):
raise ValueError("queries must be a list")
limit = case.p * case.p
if len(queries) > limit:
raise ValueError("query budget exceeds full enumeration")
for j, point in enumerate(queries, 1):
if (not isinstance(point, list) or len(point) != 2
or any(type(x) is not int or not (0 <= x < case.p) for x in point)):
raise ValueError("each query must be an in-field integer pair")
if case.accepts(*point):
return {"solved": True, "first_hit_queries": j}
return {"solved": False, "first_hit_queries": None}


def audit(phase="dev", submissions=None):
cases = make_instances(phase)
by_id = {c.id: c for c in cases}
rows = []
for c in cases:
checked = c.verify_by_enumeration()
N, M = c.p ** 2, c.p
bound = combinatorial_first_hit_bound(N, M)
if checked["first_lexicographic_query"] > bound:
raise AssertionError("combinatorial worst-case bound violated")
rows.append({
"id": c.id, "p": c.p, "a": c.a, "b": c.b, "c": c.c,
"domain_size": N, "worst_case_first_hit_bound": bound,
"uniform_random_expected_first_hit": str(
uniform_without_replacement_expectation(N, M)),
**checked,
})
grades = {}
if submissions:
for raw in Path(submissions).read_text(encoding="utf-8").splitlines():
if not raw.strip():
continue
item = json.loads(raw)
key = item["id"]
if key not in by_id or key in grades:
raise ValueError("invalid or duplicated submission id")
grades[key] = grade_queries(by_id[key], item["queries"])
return {
"campaign": "RH-CRYPTO-26", "experiment": "RH-05",
"phase": phase, "evidence": "exact finite-domain synthetic control",
"independent_units": len(PHASE_PRIMES[phase]),
"cases": len(cases), "model_intervention": None,
"physical_dose": None, "effect_floor": None,
"matched_sham_floor": None, "planned_causal_comparisons": 0,
"power": "not applicable to finite arithmetic truth checks",
"warning": "exact affine point count and a known one-query solver; no hardness/GRH claim",
"source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"rows": rows, "grades": grades,
}


def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--phase", choices=tuple(PHASE_PRIMES), default="dev")
parser.add_argument("--submissions", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args(argv)
data = json.dumps(audit(args.phase, args.submissions), indent=2, sort_keys=True) + "\n"
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(data, encoding="utf-8")
print(data, end="")
return 0


if __name__ == "__main__":
raise SystemExit(main())
57 changes: 57 additions & 0 deletions tests/test_rh_count_to_find.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Finite-domain counterexamples and exact grader gates for RH-05."""
from fractions import Fraction

import pytest

from spiral_ln.rh_count_to_find import (
Instance, audit, combinatorial_first_hit_bound,
exact_first_hit_distribution, grade_queries, make_instances,
uniform_without_replacement_expectation,
)


def test_count_constant_search_cost_changes():
p = 17
early = Instance(p, 1, 0, 0, "early").verify_by_enumeration()
late = Instance(p, 1, 0, p - 1, "late").verify_by_enumeration()
assert early["solution_count"] == late["solution_count"] == p
assert early["first_lexicographic_query"] == 1
assert late["first_lexicographic_query"] == p * p - p + 1
assert late["first_lexicographic_query"] == combinatorial_first_hit_bound(p*p, p)


def test_exact_distribution_and_mean():
N, M = 9, 3
dist = exact_first_hit_distribution(N, M)
assert sum(dist) == 1
assert sum(Fraction(t + 1) * prob for t, prob in enumerate(dist)) == (
uniform_without_replacement_expectation(N, M))
assert uniform_without_replacement_expectation(289, 17) == Fraction(145, 9)


def test_constructive_witnesses_and_all_domains():
for case in make_instances("dev"):
checked = case.verify_by_enumeration()
assert checked["solution_count"] == case.p
assert case.accepts(*case.construct())
assert checked["first_lexicographic_query"] <= case.p**2-case.p+1


def test_grading_verifies_finite_points():
case = Instance(17, 1, 0, 16, "late")
assert grade_queries(case, [[0, 0], [16, 0]]) == (
{"solved": True, "first_hit_queries": 2})
assert grade_queries(case, [[0, 0]])["solved"] is False
with pytest.raises(ValueError):
grade_queries(case, [[17, 0]])
with pytest.raises(ValueError):
grade_queries(case, [[True, 0]])


def test_receipt_exposes_evidence_boundary():
receipt = audit("dev")
assert receipt["independent_units"] == 2
assert receipt["cases"] == 8
assert receipt["model_intervention"] is None
assert receipt["power"] == "not applicable to finite arithmetic truth checks"
assert len(receipt["source_sha256"]) == 64
Loading