diff --git a/.github/workflows/h3-solver-pilot.yml b/.github/workflows/h3-solver-pilot.yml new file mode 100644 index 000000000..0dc5f2d20 --- /dev/null +++ b/.github/workflows/h3-solver-pilot.yml @@ -0,0 +1,26 @@ +name: h3-search-and-certify-pilot +on: + push: + pull_request: +permissions: + contents: read +jobs: + scalar-replay: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Exact arithmetic and adversarial controls + run: | + python3 -m unittest discover -s tests -p test_h3_solver_pilot.py -v + python3 -O -m unittest discover -s tests -p test_h3_solver_pilot.py -v + - name: Cold candidate reproduction (not scientific acceptance) + run: | + expected=$(python3 -c "import json; print(json.load(open('engine/solver_pilots/h3_20260921/CERTIFICATE_IDENTITY.json'))['canonical_sha256'])") + python3 engine/solver_pilots/h3_20260921/h3_solver.py \ + --source-archive research/campaigns/h3_rn_n6_20260920_v1.zip \ + --context engine/solver_pilots/h3_20260921/CONTEXT.json \ + --expected-certificate-sha "$expected" \ + --out "${RUNNER_TEMP}/h3-scalar-${GITHUB_RUN_ID}.json" --search --cold diff --git a/engine/solver_pilots/h3_20260921/CERTIFICATE.json b/engine/solver_pilots/h3_20260921/CERTIFICATE.json new file mode 100644 index 000000000..5ee227fbe --- /dev/null +++ b/engine/solver_pilots/h3_20260921/CERTIFICATE.json @@ -0,0 +1,149 @@ +{ + "conclusion": { + "coefficient": "1747/1000", + "endpoint_at_rmax": "1747/400000", + "fixed_geometry": "2D normalized SIDE24; x axis; b=6/5; gap=r^3/6; canonical six-pin Gaussian law", + "statement": "Z(r) >= coefficient * r^2 for every 00. The new +selection is epsilon=103/500 and d=9/100. These are event cutoffs, not changes to +the field, pins, conditioning measure or radius domain. + +Set m_(2j)=(-1)^j k^(2j)(0), sigma_e^2=m4-m2^2 and beta=m4*m2/4. Retain the source's +cancellation-free pin vector + +\[ +V=(f_M,f_{x,M},f_{y,M},(f_{x,S}-f_{x,M})/r, +(f_{y,S}-f_{y,M})/r, +(f_S-f_M)/r^3-(f_{x,S}+f_{x,M})/(2r^2)). +\] + +Its conditioned value is v=(6/5,0,0,0,0,-1/6). The limiting vector is +(f,fx,fy,fxx,fxy,-fxxx/12). Its only nonsingleton covariance blocks are +[[1,-m2],[-m2,m4]] and [[m2,m4/12],[m4/12,m6/144]]. The other variances are m2,m2^2. +Exact positive shifted pivots establish G(0)>(3/80)I. Mean-square integral +identities give + +\[ +\|c\cdot(V(r)-V(0))\|_2^2\le r^2\|c\|_2^2 +\left(m_2/4+m_4/4+m_2^2/4+m_6/16+m_4m_2/16+m_8/4096\right). +\] + +For example the first three coordinate differences use endpoint displacement +r/2; the next two use average derivatives with mean |t|=1/4; the last uses +kernel (1/2)(1/4-t^2), whose absolute first moment is 1/64. Squared L2 bounds +sum by Cauchy-Schwarz. The displayed coefficient is below (31/20)^2. +Since (193/1000)^2<3/80, reverse triangle and Loewner inversion imply + +\[ +Q(r)=v^TG(r)^{-1}v\le Q_*=\frac{17/6}{[1-(31/20)R/(193/1000)]^2} +=\frac{1266466}{160083}<8. +\] + +Here Q(0)=36m4/[25(m4-m2^2)]+4m2/(m2*m6-m4^2)<17/6, also recomputed. Thus every +positive radius in the band has a nonsingular regression law. No finite-radius +matrix grid is being used as a substitute for this transport argument. + +## 2. Sector decomposition and axial event + +As in the source, the complete line processes X=f(x,0), Y=fy(x,0), and +E=fyy(x,0)+m2*f(x,0) are mutually independent: separability and parity make all +cross-covariances zero. The pins condition X and Y separately and leave E +unchanged, with covariance sigma_e^2*k(x-z). + +Put A_M=fxx(M)/r and A_S=fxx(S)/r. Integration by parts after subtracting the pins +gives residuals R_M=A_M+1 and R_S=A_S-1 with Peano kernels +(1/2-t)^2(1/2+t) and (1/2+t)^2(1/2-t), respectively, integrated over [-1/2,1/2] +against r*X''''(rt). Both are nonnegative with mass 1/12. Hence each unconditional +residual variance is at most s(r)^2=r^2*m8/144. Regression bounds the conditional +mean magnitude by sqrt(Q_*)s(r), and the conditional variance by s(r)^2. + +For the event A={A_M<=-a,A_S>=a}, a union bound therefore gives + +\[ +P(A)\ge p_A=1-2\overline\Phi\left(\frac{\epsilon}{R\sqrt{m_8}/12}-\sqrt{Q_*}\right). +\] + +The standardized argument is positive. A smaller r improves the bound; a +zero conditional variance is covered by the deterministic mean bound. The two +residuals are not assumed independent. Unlike the old fixed 14/15 floor, this +uses the full certified probability bound and the sharper Q_* rather than 8. + +The centered mixed derivative B_M=fxy(M)/r belongs to the independent Y sector. +The pin-subtracted second-derivative kernel has mass 1/2, and conditioning on +zero Y values cannot increase variance, so E B_M^2<=beta. No B_S bound is needed. + +## 3. Transverse event and moments + +Let q_M=fyy(M), q_S=fyy(S), Qbar=(q_M+q_S)/2 and Delta=q_S-q_M. Then + +\[ +E Qbar=-m_2(6/5-r^3/12),\quad Var(Qbar)=\sigma_e^2(1+k(r))/2, +\] +\[ +E Delta=m_2r^3/6,\quad Var(Delta)=2\sigma_e^2(1-k(r)). +\] + +Stationarity gives zero covariance between midpoint and difference, hence their +Gaussian independence. Both are independent of X and Y. The mean-square +fundamental theorem gives 2(1-k(r))<=m2*r^2. Consequently + +\[ +Var(Qbar)\in[\sigma_e^2(1-m_2R^2/4),\sigma_e^2], +\quad sd(Delta)\le R\sqrt{\sigma_e^2m_2}. +\] + +For D={|Delta|<=2d}, retain both tails and the positive nonzero mean: + +\[ +P(D)\ge p_D=1-2\overline\Phi\left( +\frac{2d-m_2R^3/6}{R\sqrt{\sigma_e^2m_2}}\right). +\] + +Let T=(-Qbar-d)_+. Its underlying normal mean mu=m2*(6/5-r^3/12)-d and variance +sigma^2=Var(Qbar) lie in explicit whole-band intervals. With t=mu/sigma, + +\[ +M_1=E T=\sigma\phi(t)+\mu\Phi(t),\qquad +M_2=E T^2=(\sigma^2+\mu^2)\Phi(t)+\mu\sigma\phi(t). +\] + +The program interval-evaluates both quantities over their entire parameter +ranges, including overestimation of correlated intervals. The approximation +used in parameter search is not used to certify these moments. + +## 4. Typed determinant bound + +Write H_i=[[rA_i,rB_i],[rB_i,q_i]], det(H_i)=rD_i with +D_i=A_i*q_i-rB_i^2. On A and D, whenever T>0, both transverse entries are at most +-T. Thus D_M>=aT-rB_M^2 and D_S<=-aT. A positive first expression ensures M is a +maximum and S a saddle. Pointwise, the rescaled typed integrand is at least +1_A*1_D*aT*(aT-rB_M^2)_+. The zero positive-part cases cause no difficulty. +Using x_+>=x and the established independence gives + +\[ +Z(r)/r^2\ge P(A)P(D)[a^2M_2-ar\beta M_1]. +\] + +First verify the bracket is positive; only then replace probabilities by lower +bounds and r by R in the negative term. The sufficient lower-bound expression +is enclosed by exact rational arithmetic, with outward decimal display + +\[ +[1.747106129274,\ 1.747994749902]. +\] + +**This interval encloses the sufficient-bound formula, not the true value of +Z(r)/r^2.** Its lower endpoint exceeds 1747/1000. All r dependence was bounded +uniformly before this scalar evaluation, proving the displayed candidate for +every 0100000. Hence e^-288<10^-120, +e^-1152<10^-480 and e^-1440<10^-600. For n<=8, writing C_n as the sum of absolute +Hermite coefficients, the |j|>=2 image tail is bounded by + +\[ +2C_n48^n10^{-480}/[1-(3/2)^n10^{-600}]. +\] + +The j=+/-1 contribution is bounded by 2|H_n(24)|10^-120. Keeping normalization, +the resulting moments differ from (1,3,15,105) by less than 10^-100. These are +rationally checked bounds, not deletion of small image terms. Rounding error is +then enclosed independently. Source hashes select the declared source, not an +extraction transform chosen to fit a desired hash. + +The tests include both-tail omissions, understated moments, scope expansion, +wrong-quantity refutations, cache corruption and actual candidate recomputation. +The optional mpmath comparison is diagnostic only. Arb was not executed. +Nonauthor mathematical review, a second rigorous implementation, and any wider +research application remain separate tasks. diff --git a/engine/solver_pilots/h3_20260921/PROPOSAL_ASSESSMENT.md b/engine/solver_pilots/h3_20260921/PROPOSAL_ASSESSMENT.md new file mode 100644 index 000000000..dcde7aa26 --- /dev/null +++ b/engine/solver_pilots/h3_20260921/PROPOSAL_ASSESSMENT.md @@ -0,0 +1,38 @@ +# Six suggested mechanisms: disposition after source inspection + +Owner authorization supplies permission to act, not a mathematical result. This +experiment advances a concrete H3 estimate instead of installing all six ideas +as workspace-wide rules. The suggestions are useful engineering patterns, not +established novel mathematical primitives. + +| Suggestion | Decision and actual scope | +|---|---| +| Bitemporal/Merkle claims | Defer global migration. Valid time means the applicability interval of an assertion, review or operational status; it is not when a timeless theorem became true. Recursive hashes are implemented only for this experiment's declared formula DAG. They prove integrity under a trusted root, not logical soundness. Cyclic logical dependencies need an explicit treatment before any forest conversion. | +| Prover/falsifier lanes | Implement bounded parameter proposal -> rigorous scalar certification and adversarial negative controls. Actual result improves the source's band lower coefficient. No failure-count-to-proof or 10k-sample budget rule. The full-law Z counterexample evaluator remains unimplemented. | +| Execution cache | Implement local content-addressed scalar reuse with source/code/context/runtime keys, immutable outputs, hash checks and optional mandatory cold replay. It is not a hermetic distributed build and never becomes source of scientific authority. Shared cache authentication and Nix/Guix pinning are deferred. | +| Dual arithmetic | Optional mpmath cross-checks are diagnostic, not certified. Arb was inspected in primary documentation but not executed in this runtime. Agreement/overlap does not validate shared formulas, conditioning, tails or scope. A disagreement identifies a consistency problem, not automatically which backend is wrong. | +| Formula-cell lineage | Trace the actual mathematical formula dependencies here, with no invented Sheets ancestry. Full formula-cell lineage needs a source census, parser, named-range/INDIRECT/volatile/external/cycle handling and changed-cell impact tests. The supplied counts were not verified and are not adopted. | +| Proof market/energy | Record actual wall time, process CPU time and achieved bound improvement. Energy is unmeasured. No hypothetical 12h/200h cost estimates, spend, token market or automatic resource grants. Prioritization must consider all unresolved AND premises and alternative OR routes, not naive descendant count. | + +## Highest-value next scientific actions + +A nonauthor reviewer can check the general epsilon,d adaptation and the alternate +rational kernel using the exact source and new certificate. A genuinely second +rigorous backend can then reproduce the scalar inequalities; an independent +expectation oracle would be required for the proposed full-Z falsifier. Broader +all-angle or RN work must retain its own hypotheses and gates. No automatic +replacement of the existing stronger fixed-radius consumer is justified. + +## Primary sources inspected + +- MariaDB Bitemporal Tables: system-time and application-time versioning are distinct. + https://mariadb.com/docs/server/reference/sql-structure/temporal-tables/bitemporal-tables +- RFC 9162, section 2.1: Merkle inclusion and consistency concern authenticated data. + https://www.rfc-editor.org/rfc/rfc9162.html +- Bazel Remote Caching: action metadata and content-addressed output storage; + undeclared environment/input changes matter. https://bazel.build/remote/caching +- python-flint 0.9.0 arb documentation: ball representations and error tracking. + https://python-flint.readthedocs.io/en/latest/arb.html + +These sources support the engineering distinctions, not the H3 theorem. The +mathematical argument and exact scalar computations are explicitly supplied here. diff --git a/engine/solver_pilots/h3_20260921/README.md b/engine/solver_pilots/h3_20260921/README.md new file mode 100644 index 000000000..5d04ed850 --- /dev/null +++ b/engine/solver_pilots/h3_20260921/README.md @@ -0,0 +1,91 @@ +# H3 search-and-certify pilot + +A bounded executable research experiment, not a new global governance layer. +It turns a 30,351-case NONCERTIFYING parameter search into a separately certified +scalar result supporting the fixed-axis whole-band candidate +`Z(r) >= (1747/1000) r^2`, for `0self.hi: raise ValueError('empty interval') + @classmethod + def bound(cls, lo, hi): + return cls(floor_grid(lo), ceil_grid(hi)) + @staticmethod + def of(x): return x if isinstance(x,I) else I(x) + def __add__(self,b): + b=I.of(b); return I.bound(self.lo+b.lo,self.hi+b.hi) + __radd__=__add__ + def __neg__(self): return I(-self.hi,-self.lo) + def __sub__(self,b): return self+-I.of(b) + def __rsub__(self,b): return I.of(b)+-self + def __mul__(self,b): + b=I.of(b); v=[self.lo*b.lo,self.lo*b.hi,self.hi*b.lo,self.hi*b.hi] + return I.bound(min(v),max(v)) + __rmul__=__mul__ + def __truediv__(self,b): + b=I.of(b) + if b.lo<=0<=b.hi: raise ZeroDivisionError('denominator includes zero') + return self*I.bound(1/b.hi,1/b.lo) + def __rtruediv__(self,b): return I.of(b)/self + def __pow__(self,n): + if type(n) is not int or n<0: raise ValueError('nonnegative integer power required') + if n==0: return I(1) + if n%2: + return I.bound(self.lo**n,self.hi**n) + lo=0 if self.lo<=0<=self.hi else min(self.lo**n,self.hi**n) + return I.bound(lo,max(self.lo**n,self.hi**n)) + def encode(self): return {'lo':str(self.lo),'hi':str(self.hi)} + def __repr__(self): return str(self.encode()) + + +def sqrt(x): + x=I.of(x) + if x.lo<0: raise ValueError('negative square root') + def bounds(y): + k=isqrt((y.numerator*SCALE*SCALE)//y.denominator) + a=F(k,SCALE) + return a, a if a*a==y else F(k+1,SCALE) + return I(bounds(x.lo)[0],bounds(x.hi)[1]) + + +def atan_reciprocal(n,terms=160): + """Alternating series, 0<1/n<=1/2, tail <= first omitted term.""" + if type(n) is not int or n<2 or type(terms) is not int or terms<1: + raise ValueError('bad arctan parameters') + x=F(1,n); total=F(0) + for k in range(terms): total+=(-1)**k*x**(2*k+1)/(2*k+1) + nxt=(-1)**terms*x**(2*terms+1)/(2*terms+1) + return I.bound(min(total,total+nxt),max(total,total+nxt)) + + +@lru_cache(None) +def pi(): + # Machin's identity, principal arctangents: pi=16 atan(1/5)-4 atan(1/239). + return 16*atan_reciprocal(5)-4*atan_reciprocal(239) + + +def exp_negative_point(x,terms=240): + """exp(-x), 0<=x<=50. Alternating tail decreases from the omitted term.""" + x=q(x) + if not 0<=x<=50 or type(terms) is not int or terms=32. Using terms>=40 proves the + remainder between zero and the first omitted term. Endpoint rounding + is enclosed separately and pi is also an enclosure. + """ + x=q(x) + if not -8<=x<=8 or type(terms) is not int or terms<40: + raise ValueError('outside certified CDF series domain') + if x<0: return 1-cdf_point(-x,terms) + term=x; total=term + for k in range(terms-1): + term*= -x*x*F(2*k+1,2*(k+1)*(2*k+3)); total+=term + nxt=term*(-x*x)*F(2*terms-1,2*terms*(2*terms+1)) + area=I.bound(min(total,total+nxt),max(total,total+nxt)) + return F(1,2)+area/sqrt(2*pi()) + + +def cdf(x): + x=I.of(x) + return I(cdf_point(x.lo).lo,cdf_point(x.hi).hi) + + +def sf(x): return 1-cdf(x) + + +def pdf(x): + x=I.of(x) + return exp_negative(x*x/2)/sqrt(2*pi()) if x.lo>=0 else exp_negative((x**2)/2)/sqrt(2*pi()) + + +def outward_decimal(x,places=12): + """Decimal enclosure generated by rational floor/ceiling, never floats.""" + x=I.of(x); scale=10**places + def dec(v,upper): + n=v.numerator*scale; d=v.denominator + k=-((-n)//d) if upper else n//d + sign='-' if k<0 else ''; digits=str(abs(k)).rjust(places+1,'0') + return sign+(digits[:-places]+'.'+digits[-places:] if places else digits) + return {'lo':dec(x.lo,False),'hi':dec(x.hi,True)} diff --git a/engine/solver_pilots/h3_20260921/h3_scalar_certificate.py b/engine/solver_pilots/h3_20260921/h3_scalar_certificate.py new file mode 100644 index 000000000..c2d496765 --- /dev/null +++ b/engine/solver_pilots/h3_20260921/h3_scalar_certificate.py @@ -0,0 +1,133 @@ +"""Exact scalar continuation of the frozen fixed-axis H3 analytic proof. + +All-small-r conclusion depends on the explicitly cited analytic sector, +regression, transport and determinant arguments, not on a sampled r grid. +This file certifies their numerical sufficient conditions by a separate +rational construction; it does not replay the original repository wrapper. +""" +from fractions import Fraction as F +from pathlib import Path +import hashlib +import json +import sys +sys.path.insert(0,str(Path(__file__).resolve().parent)) +from h3_scalar_arithmetic import I, sqrt, sf, cdf, pdf, outward_decimal + + +def need(condition,message): + if not condition: raise ValueError(message) + + +def canonical(obj): + return json.dumps(obj,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode() + + +def digest(obj): return hashlib.sha256(canonical(obj)).hexdigest() + + +def hermite(n): + p=[1]; q=[0,1] + if n==0:return p + for k in range(1,n): + a=[0]+q + for j,v in enumerate(p): a[j]-=k*v + p,q=q,a + return q + + +def moments(): + # e^12 > 100000 by its positive Taylor partial sum; hence e^-288<10^-120. + term=F(1); partial=term + for k in range(1,40): term*=F(12,k); partial+=term + need(partial>100000,'elementary exponential comparison') + eps=F(1,10**100) + errors={} + for n in (0,2,4,6,8): + coeff=hermite(n); c=sum(abs(a) for a in coeff) + h24=sum(a*24**k for k,a in enumerate(coeff)) + # |H_n(24j)| <= c |24j|^n, j>=2. + # Successive envelope ratio <= (3/2)^n exp(-1440)<(3/2)^n 10^-600. + ratio=F(3,2)**n/F(10**600) + tail=2*c*48**n*F(1,10**480)/(1-ratio) + errors[n]=2*abs(h24)*F(1,10**120)+tail + z=I(1,1+errors[0]) + m={} + for n,central in ((2,1),(4,3),(6,15),(8,105)): + exact_range=I(central-errors[n],central+errors[n])/z + # Arithmetic rounds at 2^-256, so use direct rational comparison for + # the much smaller analytic 1e-100 kernel perturbation first. + need((F(central)-errors[n])/(1+errors[0]) >= F(central)-eps,'normalized lower tail') + need(F(central)+errors[n] <= F(central)+eps,'normalized upper tail') + m[n]=I(F(central)-eps,F(central)+eps) + return m,{'exp12_partial_gt_100000':True,'kernel_normalizer':z.encode(), + 'normalized_moment_error':str(eps),'raw_derivative_errors':{str(n):str(v) for n,v in errors.items()}} + + +def gram_and_energy(m,R): + shift=F(3,80) + # Shifted two nontrivial limiting covariance blocks and two singleton blocks. + p0=I(1)-shift; p1=m[4]-shift-(m[2]**2)/p0 + p2=m[2]-shift; p3=m[6]/144-shift-(m[4]/12)**2/p2 + pivots=[p0,p1,p2,p3,m[2]-shift,m[2]**2-shift] + need(all(x.lo>0 for x in pivots),'strict limiting Gram eigenfloor') + transport2=m[2]/4+m[4]/4+m[2]**2/4+m[6]/16+m[4]*m[2]/16+m[8]/4096 + need(transport2.hi0,'uniform covariance gap') + Q=F(17,6)/(gap*gap) + return Q,{'shifted_gram_pivots':[x.encode() for x in pivots], + 'transport_squared':transport2.encode(),'limiting_pin_energy':q0.encode(), + 'uniform_energy_upper':str(Q),'radius_max':str(R)} + + +def prove(epsilon=F(103,500),gap_half=F(9,100),radius=F(1,20),target=F(1747,1000), + axial_tails=F(2),difference_tails=F(2),variance_loss=F(1,4),beta_scale=F(1,4)): + for x in (epsilon,gap_half,radius,target,axial_tails,difference_tails,variance_loss,beta_scale): need(type(x) is F,'exact Fraction parameters required') + need(00,'invalid optimization parameters') + need(axial_tails>=2 and difference_tails>=2,'both event unions retain two tails') + need(variance_loss>=F(1,4) and beta_scale>=F(1,4),'variance majorants cannot be understated') + m,tail= moments(); Q,energy=gram_and_energy(m,radius) + axial_argument=epsilon/(radius*sqrt(m[8])/12)-sqrt(I(Q)) + need(axial_argument.lo>0,'axial threshold exceeds conditional mean') + pA=1-axial_tails*sf(axial_argument) + sigma2=m[4]-m[2]**2 + variance=sigma2*I(1-variance_loss*m[2].hi*radius**2,1) + mu=I(m[2].lo*(F(6,5)-radius**3/12)-gap_half,m[2].hi*F(6,5)-gap_half) + need(variance.lo>0 and mu.lo>0,'positive midpoint parameters') + sd=sqrt(variance); t=mu/sd; phi=pdf(t); Phi=cdf(t) + M1=sd*phi+mu*Phi + M2=(variance+mu**2)*Phi+mu*sd*phi + delta_mean=m[2]*radius**3/6 + delta_sd=radius*sqrt(sigma2*m[2]) + delta_argument=(2*gap_half-delta_mean)/delta_sd + need(delta_argument.lo>0,'two-sided difference threshold exceeds its mean') + pD=1-difference_tails*sf(delta_argument) + need(pA.lo>0 and pD.lo>0,'positive event probability floors') + a=1-epsilon; beta=beta_scale*m[4]*m[2] + bracket=a*a*M2-a*radius*beta*M1 + need(bracket.lo>0,'positive budget BEFORE lower probability multiplication') + lower=pA*pD*bracket + need(lower.lo>=target,'requested target not certified by this sufficient estimate') + values={'moments':{str(k):v.encode() for k,v in m.items()},'tail':tail,'energy':energy, + 'axial_argument':axial_argument.encode(),'p_axial':pA.encode(), + 'midpoint_variance':variance.encode(),'midpoint_mean':mu.encode(), + 'positive_first_moment':M1.encode(),'positive_second_moment':M2.encode(), + 'difference_argument':delta_argument.encode(),'p_difference':pD.encode(), + 'beta':beta.encode(),'positive_bracket':bracket.encode(), + 'derived_lower_coefficient':lower.encode(),'derived_outward_decimal':outward_decimal(lower)} + return {'schema':'h3-scalar-candidate-v1','status':'AUTHOR_SIDE_PROVED_CANDIDATE', + 'parameters':{'epsilon':str(epsilon),'gap_half':str(gap_half),'radius_max':str(radius),'axial_tails':str(axial_tails),'difference_tails':str(difference_tails), + 'variance_loss':str(variance_loss),'beta_scale':str(beta_scale)}, + 'conclusion':{'coefficient':str(target),'statement':'Z(r) >= coefficient * r^2 for every 0 exact scalar certification -> traceable candidate. + +No network calls or scientific-register writes. Local trusted cache only; +--cold or --verify-result recomputes instead of trusting cached arithmetic. +Code/runtime/source/context identities are part of the key. This is NOT a +hermetic Nix build, authenticated cache, full-law falsifier, or proof assistant. +""" +from pathlib import Path +from fractions import Fraction as F +from datetime import datetime, timezone +import argparse +import hashlib +import importlib.util +import json +import platform +import sys +import time +import zipfile +sys.dont_write_bytecode=True +HERE=Path(__file__).resolve().parent +sys.path.insert(0,str(HERE)) +from h3_scalar_certificate import prove, digest, canonical, need +from h3_scalar_arithmetic import I, BITS +import h3_source_admission as admission + +ARCHIVE_SHA='73b9e63800f77c677c504f3097fe0bb2459ff6c94cdee5772b56062320aefc21' +MANIFEST_SHA='81770e26ec654d3b462f06cebaa20d0dd282cfd4df10ac593c7887ea0d292b40' +FORMULA_SPEC=[ + ('parameters','exact epsilon,d,R,target',[]), + ('kernel','normalized image-sum Hermite moments with full geometric tails',[]), + ('energy','shifted Gram blocks + L2 transport -> uniform Q', ['kernel','parameters']), + ('axial','1-2*sf(epsilon/(R*sqrt(m8)/12)-sqrt(Q))',['kernel','energy','parameters']), + ('midpoint','Gaussian positive-part M1,M2 with mean/variance intervals',['kernel','parameters']), + ('difference','1-2*sf((2*d-m2*R^3/6)/(R*sqrt((m4-m2^2)*m2)))',['kernel','parameters']), + ('determinant','positive a^2*M2-a*R*(m4*m2/4)*M1; a=1-epsilon',['kernel','parameters','midpoint']), + ('coefficient','pA*pD*positive_bracket',['axial','difference','determinant']), +] + + +def strict_json(text): + def pairs(items): + out={} + for key,value in items: + need(key not in out,'duplicate JSON key') + out[key]=value + return out + def reject(value):raise ValueError('nonfinite JSON token') + return json.loads(text,object_pairs_hook=pairs,parse_constant=reject) + + +def file_hash(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +source_check = admission.source_check + +def recipe(source,context,params): + admission.validate_context(context) + need(context['source_archive_sha256']==source.get('archive_sha256'),'context/source identity mismatch') + return {'schema':'local-h3-recipe-v2','source':source, + 'code':{name:file_hash(HERE/name) for name in ('h3_scalar_arithmetic.py','h3_scalar_certificate.py','h3_solver.py','h3_source_admission.py')}, + 'runtime':{'python':sys.version,'implementation':platform.python_implementation(), + 'platform':platform.platform(),'bits':BITS}, + 'context_sha256':digest(context),'parameters':params, + 'hermetic':False,'context_authentication':'caller-supplied deny-only filter; source admission is separate'} + + +def formula_lineage(result,source): + v=result['values']; values={ + 'parameters':{'parameters':result['parameters'],'conclusion':result['conclusion']},'kernel':{'moments':v['moments'],'tail':v['tail']}, + 'energy':v['energy'],'axial':{'argument':v['axial_argument'],'p':v['p_axial']}, + 'midpoint':{k:v[k] for k in ('midpoint_mean','midpoint_variance','positive_first_moment','positive_second_moment')}, + 'difference':{'argument':v['difference_argument'],'p':v['p_difference']}, + 'determinant':{'beta':v['beta'],'positive_bracket':v['positive_bracket']}, + 'coefficient':v['derived_lower_coefficient']} + nodes={} + for nid,expr,deps in FORMULA_SPEC: + payload={'id':nid,'expression':expr,'dependencies':{d:nodes[d]['hash'] for d in deps}, + 'value':values[nid],'source_archive_sha256':source['archive_sha256']} + nodes[nid]={'hash':digest(payload),'payload':payload} + return {'schema':'h3-formula-lineage-v1','root':nodes['coefficient']['hash'],'nodes':nodes, + 'spreadsheet_cells_used':[],'lineage_completeness':'declared formula-level dependencies; not a general Python or Sheets tracer', + 'scope':'Declared mathematical formula DAG, not whole-workspace or Google Sheets formula lineage', + 'hash_meaning':'content/dependency integrity only; not a mathematical proof'} + + +def affected_nodes(changed): + known={x[0] for x in FORMULA_SPEC} + need(set(changed)<=known,'unknown formula node') + out=set(changed) + for nid,_,deps in FORMULA_SPEC: + if out.intersection(deps):out.add(nid) + return sorted(out) + + +def classify_enclosure(lo,hi,lower,upper,quantity_kind): + """For a certified enclosure of THE TARGET only, never a lower estimator.""" + lo,hi,lower,upper=map(F,(lo,hi,lower,upper)) + need(lo<=hi and lower<=upper,'malformed enclosure or target') + if quantity_kind!='TARGET_QUANTITY_ENCLOSURE':return 'WRONG_QUANTITY_FOR_REFUTATION' + if hiupper:return 'CONTRADICTION_REQUIRES_SCOPE_AND_INDEPENDENT_REVIEW' + if lower<=lo and hi<=upper:return 'COMPATIBLE_ON_THIS_ENCLOSED_DOMAIN_ONLY' + return 'INCONCLUSIVE_REFINE_ENCLOSURE' + + +def search(): + """Finite double-precision proposal search; never decides truth.""" + import math + R=.05; Q=1266466/160083; s=R*math.sqrt(105)/12 + best=(-1,None); evaluated=0; rejected=0 + for ei in range(100,301): + eps=ei/1000; pa=1-math.erfc((eps/s-math.sqrt(Q))/math.sqrt(2)) + for di in range(50,201): + evaluated+=1; d=di/1000 + pd=1-math.erfc((2*d-R**3/6)/(R*math.sqrt(2))/math.sqrt(2)) + if pa<=0 or pd<=0: rejected+=1;continue + mu=1.2-R**3/12-d; sd=math.sqrt(2*(1-R*R/4)); t=mu/sd + ph=math.exp(-t*t/2)/math.sqrt(2*math.pi); c=.5*(1+math.erf(t/math.sqrt(2))) + M1=sd*ph+mu*c; M2=(sd*sd+mu*mu)*c+mu*sd*ph + b=pa*pd*((1-eps)**2*M2-(1-eps)*R*.75*M1) + if b>best[0]:best=(b,(ei,di)) + return {'status':'NONCERTIFYING_PARAMETER_SEARCH','evaluated':evaluated,'rejected_nonpositive_probability':rejected, + 'best_diagnostic_estimate':best[0],'epsilon':str(F(best[1][0],1000)), + 'gap_half':str(F(best[1][1],1000)), + 'limitation':'Optimizes a Gaussian-limit sufficient formula, not actual Z or a rigorous global optimum. Re-certify exact selected parameters.'} + + +def cached(recipe_obj,cache,compute,cold=False): + key=digest(recipe_obj) + if cache is None:return compute(),'DISABLED',key + cache=Path(cache);cache.mkdir(parents=True,exist_ok=True) + path=cache/(key+'.json') + if path.exists(): + old=strict_json(path.read_text()) + need(old.get('recipe')==recipe_obj and old.get('payload_sha256')==digest(old.get('payload')),'cache corruption/key mismatch') + if not cold:return old['payload'],'LOCAL_TRUSTED_HIT_NOT_NEW_EVIDENCE',key + fresh=compute() + need(fresh==old['payload'],'cold recomputation disagrees with cache') + return fresh,'COLD_RECOMPUTE_MATCH',key + result=compute(); envelope={'recipe':recipe_obj,'payload':result,'payload_sha256':digest(result)} + try: + with path.open('x') as f:f.write(json.dumps(envelope,sort_keys=True,indent=2)+'\n') + except FileExistsError: + other=strict_json(path.read_text());need(other==envelope,'conflicting cache publication') + return result,'MISS_COMPUTED',key + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--source-archive',type=Path,required=True) + p.add_argument('--context',type=Path,required=True) + p.add_argument('--out',type=Path,required=True) + p.add_argument('--cache',type=Path) + p.add_argument('--cold',action='store_true') + p.add_argument('--search',action='store_true') + p.add_argument('--verify-result',type=Path) + p.add_argument('--expected-certificate-sha') + p.add_argument('--epsilon',type=F) + p.add_argument('--gap-half',type=F) + p.add_argument('--target',type=F,default=F(1747,1000)) + args=p.parse_args() + start=time.perf_counter();cpu=time.process_time() + context=admission.strict_json(admission.read_bounded(args.context,admission.MAX_METADATA)) + source=source_check(args.source_archive,context) + diagnostic=search() if args.search else None + epsilon=args.epsilon if args.epsilon is not None else F(diagnostic['epsilon']) if diagnostic else F(103,500) + gap_half=args.gap_half if args.gap_half is not None else F(diagnostic['gap_half']) if diagnostic else F(9,100) + params={'epsilon':str(epsilon),'gap_half':str(gap_half),'target':str(args.target),'radius':'1/20'} + rec=recipe(source,context,params) + result,cache_state,key=cached(rec,args.cache, + lambda:prove(epsilon=epsilon,gap_half=gap_half,target=args.target),args.cold or args.verify_result is not None or args.expected_certificate_sha is not None) + if args.expected_certificate_sha: + need(digest(result)==args.expected_certificate_sha,'exact candidate digest mismatch') + if args.verify_result: + expected=strict_json(args.verify_result.read_text()) + need(expected.get('certificate',expected)==result,'candidate differs from exact recomputation') + final_context=admission.strict_json(admission.read_bounded(args.context,admission.MAX_METADATA)) + need(source_check(args.source_archive,final_context)==source and recipe(source,final_context,params)==rec, + 'source/context/code changed during run') + output={'certificate':result,'formula_lineage':formula_lineage(result,source),'recipe':rec,'recipe_sha256':key, + 'cache':cache_state,'parameter_search':diagnostic, + 'recorded_at':datetime.now(timezone.utc).isoformat(), + 'timing':{'wall_seconds':time.perf_counter()-start,'cpu_seconds':time.process_time()-cpu, + 'energy_joules':None,'energy_measurement':'NOT_MEASURED'}, + 'arb_backend':'NOT_EXECUTED; no second rigorous backend claimed', + 'source_admissibility':'pinned authored provenance and current local exclusions/upstream eligibility rechecked; caller context is deny-only; no live permission or canonical acceptance service', + 'automatic_promotion':False,'scheduled_execution':False} + args.out.parent.mkdir(parents=True,exist_ok=True) + with args.out.open('x') as f:f.write(json.dumps(output,sort_keys=True,indent=2)+'\n') + print(json.dumps({'result':'CANDIDATE_WRITTEN','cache':cache_state,'coefficient':result['conclusion']['coefficient'], + 'formula_bound':result['values']['derived_outward_decimal'],'seconds':output['timing']['wall_seconds']})) + + +if __name__=='__main__': + try:main() + except (ValueError,TypeError,KeyError,OSError,zipfile.BadZipFile) as e: + print('PILOT REFUSAL: '+str(e),file=sys.stderr);sys.exit(2) diff --git a/engine/solver_pilots/h3_20260921/h3_source_admission.py b/engine/solver_pilots/h3_20260921/h3_source_admission.py new file mode 100644 index 000000000..219c136f1 --- /dev/null +++ b/engine/solver_pilots/h3_20260921/h3_source_admission.py @@ -0,0 +1,232 @@ +"""Local, candidate-only H3 source admission; no live authority or status moves. + +A pinned numbered provenance record links the authored source to its registered +parent delivery. Current repository exclusions remain a separate, fresh deny +input. Only the manifest metadata and one declared proof body are materialized; +no archived program is imported and unrelated leaves are never opened. +""" +from pathlib import Path, PurePosixPath +import csv +import hashlib +import io +import json +import stat +import zipfile +from urllib.parse import urlsplit + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +ADMISSION = HERE / 'sources/H3_AUTHORED_NESTED_SOURCE_V1.json' +ADMISSION_SHA256 = '104cb5d72f06ac74979a976f43492226145182a141f382fc8eae7b7b59d84df0' +ARCHIVE = 'research/campaigns/h3_rn_n6_20260920_v1.zip' +ARCHIVE_ID = {'bytes': 571735, 'sha256': '73b9e63800f77c677c504f3097fe0bb2459ff6c94cdee5772b56062320aefc21'} +MANIFEST_ID = {'bytes': 12008, 'sha256': '81770e26ec654d3b462f06cebaa20d0dd282cfd4df10ac593c7887ea0d292b40'} +BODY_ALLOWLIST = {'h3_floor/PROOF.md': {'bytes': 10423, 'sha256': 'b48d8baa39b80be9a15af9833234d9339ea0afa4cdff2e1c60ae9ef79f5cb4fa'}} +ANCESTOR_ID = '1ni4q7t4a6rIpDkxapmc9yU4Xt1wv3983' +FORBIDDEN_IDS = {'1VTiBaRlBvHGptiXqoEli4E5630nO7mNb', '1hnd7jbFwcCQIuOcbrzilMQoymsOzFQZb'} +FORBIDDEN_SHA = {'579ef6cd88d543ec14db45558e5e7c1899078095e0df295c7d46fd1810273831'} +CONTEXT_KEYS = {'context_id', 'scientific_use', 'source_usable_for_candidate', 'basis', 'scope', + 'source_archive_sha256', 'current_use_requires_revalidation', 'organizational_independence_credit'} +MAX_METADATA = 1_000_000 +MAX_SOURCE_MAP = 8_000_000 + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def identity(raw): + return {'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()} + + +def read_bounded(path, limit): + path = Path(path).absolute() + need(path == path.resolve() and not path.is_symlink(), 'noncanonical or symlink source input') + need(stat.S_ISREG(path.stat().st_mode), 'regular source input required') + with path.open('rb') as handle: + raw = handle.read(limit + 1) + need(len(raw) <= limit, 'source input exceeds size limit') + return raw + + +def strict_json(raw): + need(len(raw) <= MAX_METADATA, 'source metadata size limit') + def pairs(items): + result = {} + for key, value in items: + need(key not in result, 'duplicate source metadata key') + result[key] = value + return result + def inexact(_): + raise ValueError('noninteger source metadata number') + return json.loads(raw, object_pairs_hook=pairs, parse_float=inexact, parse_constant=inexact) + + +def validate_context(context): + """The caller can restrict use; it cannot supply the provenance warrant.""" + need(type(context) is dict and set(context) == CONTEXT_KEYS, 'unsupported or missing context fields') + need(all(type(context[key]) is str and context[key] for key in ('context_id','basis','scope')), + 'context identity, basis and scope must be nonempty strings') + need(context.get('scientific_use') == 'REQUIRES_REVIEW', 'context does not permit candidate-only use') + need(context.get('source_usable_for_candidate') is True, 'source use denied or unknown') + need(context.get('source_archive_sha256') == ARCHIVE_ID['sha256'], 'context/source identity mismatch') + need(type(context.get('organizational_independence_credit')) is int + and context['organizational_independence_credit'] == 0, 'no independence credit may be imported') + need(context.get('current_use_requires_revalidation') is True, 'current revalidation required') + + +def safe_name(name): + need(type(name) is str and name and '\\' not in name, 'invalid archive name') + path = PurePosixPath(name) + need(not path.is_absolute() and str(path) == name and '..' not in path.parts, 'unsafe archive name') + return name + + +def check_exclusions(record, rows): + need(type(rows) is list, 'exclusions must be a list') + upstream = record['upstream'] + carriers = {ANCESTOR_ID, upstream['carrier']['drive_id']} + hashes = {record['ancestor']['sha256'], ARCHIVE_ID['sha256'], MANIFEST_ID['sha256'], + record['ancestor_manifest']['sha256'], upstream['carrier']['sha256']} + hashes |= {v['sha256'] for v in BODY_ALLOWLIST.values()} + hashes |= {v['sha256'] for v in upstream['members'].values()} + paths = {record['ancestor']['name'], ARCHIVE, 'MANIFEST.json', 'DELIVERY_MANIFEST.json'} + paths |= set(BODY_ALLOWLIST) | set(upstream['members']) + need(not hashes.intersection(FORBIDDEN_SHA) and not carriers.intersection(FORBIDDEN_IDS), 'permanent source exclusion') + for row in rows: + need(type(row) is dict and row.get('kind') in ('drive_object', 'archive_member'), 'unknown exclusion record') + need(type(row.get('carrier_id')) is str and row['carrier_id'], 'missing exclusion carrier') + need(type(row.get('member_path')) is str and row['member_path'], 'missing exclusion path') + sha = row.get('payload_sha256') + need(sha is None or (type(sha) is str and len(sha) == 64 + and all(ch in '0123456789abcdef' for ch in sha)), 'invalid excluded payload digest') + need(sha not in hashes, 'excluded source payload') + if row['kind'] == 'drive_object': + need(row['carrier_id'] not in carriers, 'excluded source ancestor') + else: + # An unrelated held leaf in the same container does not deny this leaf. + name = row['member_path'].replace('!/', '/') + matches = any(name == path or name.endswith('/' + path) for path in paths) + relevant = row['carrier_id'] in carriers or row.get('carrier_sha256') in hashes + need(not (matches and relevant), 'excluded source member') + + +def upstream_gate(record): + """Authenticate two declared upstream identities from current metadata only.""" + raw_inventory = read_bounded(ROOT / 'drive/inventory.jsonl', MAX_SOURCE_MAP) + raw_payloads = read_bounded(ROOT / 'drive/source_map/Payloads.csv', MAX_SOURCE_MAP) + inventory = [strict_json(line) for line in raw_inventory.splitlines() if line.strip()] + need(all(type(row) is dict for row in inventory), 'invalid inventory row') + carrier = record['upstream']['carrier'] + matches = [row for row in inventory if row.get('id') == carrier['drive_id']] + need(len(matches) == 1, 'missing or ambiguous upstream carrier mapping') + source = matches[0] + need(type(source.get('bytes')) is int and source['bytes'] == carrier['bytes'] + and source.get('sha256') == carrier['sha256'], 'upstream carrier identity mismatch') + need(source.get('context') == 'RESEARCH_SOURCE_CHECK_STATUS' + and source.get('access_status') == 'ARCHIVE_INDEXED', 'upstream carrier unavailable') + name = source.get('path', '') + need(type(name) is str and name.startswith('01_ACTIVE_RESEARCH_PACKAGES/') + and not any(word in name.lower() for word in ('quarantine', 'legacy', '99_do_not_open')), + 'upstream carrier outside eligible active source path') + def drive_link(link): + need(type(link) is str, 'missing source link') + url = urlsplit(link) + need(url.scheme == 'https' and url.netloc == 'drive.google.com' + and url.path == '/file/d/' + carrier['drive_id'] + '/view' and url.query in ('', 'usp=drivesdk') and not url.fragment, + 'upstream source link mismatch') + drive_link(source.get('link')) + try: + rows = list(csv.reader(io.StringIO(raw_payloads.decode('utf-8')), strict=True)) + except csv.Error as error: + raise ValueError('malformed source-map CSV') from error + need(rows and len(rows[0]) == len(set(rows[0])), 'missing or duplicate source-map headers') + required = {'Source name', 'SHA-256', 'Bytes', 'Conversion', 'Context', 'Scope holds', 'Original source link'} + need(required <= set(rows[0]) and all(len(row) == len(rows[0]) for row in rows[1:]), 'malformed source-map shape') + payloads = [dict(zip(rows[0], row)) for row in rows[1:]] + for name, expected in record['upstream']['members'].items(): + matches = [row for row in payloads if row['SHA-256'] == expected['sha256'] or row['Source name'] == name] + need(len(matches) == 1, 'missing or ambiguous upstream member mapping') + row = matches[0] + need(row['Source name'] == name and row['SHA-256'] == expected['sha256'] + and row['Bytes'] == str(expected['bytes']), 'upstream member identity mismatch') + need(row['Conversion'] == 'TEXT_READING_COPY' and row['Context'] == 'RESEARCH_SOURCE_CHECK_STATUS' + and strict_json(row['Scope holds']) == [], 'upstream member unavailable or held') + drive_link(row['Original source link']) + return {'drive/inventory.jsonl': identity(raw_inventory), + 'drive/source_map/Payloads.csv': identity(raw_payloads)} + + +def metadata_gate(context): + """Read only local policy/provenance metadata, before opening any ZIP.""" + validate_context(context) + raw = read_bounded(ADMISSION, MAX_METADATA) + record = strict_json(raw) + need(identity(raw)['sha256'] == ADMISSION_SHA256, 'missing, changed or unreviewed source admission record') + need(record['schema'] == 'h3-authored-nested-source-v1' + and record['candidate_use'] == 'REQUIRES_REVIEW' + and record['eligibility'] == 'CANDIDATE_READING' + and record['scope'] == context.get('scope'), 'ineligible or mismatched source scope') + need(record['archive'] == dict(path=ARCHIVE, **ARCHIVE_ID) + and record['manifest'] == dict(path='MANIFEST.json', **MANIFEST_ID) + and record['body_allowlist'] == BODY_ALLOWLIST + and record['ancestor']['drive_id'] == ANCESTOR_ID, 'source admission identity mismatch') + custody_raw = read_bounded(HERE / record['current_custody']['path'], MAX_METADATA) + need(identity(custody_raw) == {key: record['current_custody'][key] for key in ('bytes','sha256')}, + 'current custody receipt identity mismatch') + custody = strict_json(custody_raw) + need(custody['schema'] == 'C11_SOURCE_CUSTODY_V1' + and custody['source_kind'] == 'AUTHORED_ARCHIVE_MEMBER' + and custody['ancestor'] == {key: record['ancestor'][key] for key in ('drive_id','bytes','sha256')} | {'exact_fresh_raw_readback': True} + and custody['member'] == record['archive'] + and custody['receipt_utc'] == record['current_custody']['observed_receipt_utc'] + and record['implementation_claim'] in custody['current_claim_ids'] + and custody['scientific_acceptance'] is False + and type(custody['organizational_independence_credit']) is int + and custody['organizational_independence_credit'] == 0, 'custody/admission scope mismatch') + exclusions_raw = read_bounded(ROOT / 'quarantine/EXCLUSIONS.json', MAX_METADATA) + exclusions = strict_json(exclusions_raw) + need(type(exclusions) is dict and 'exclusions' in exclusions, 'missing current exclusions') + check_exclusions(record, exclusions['exclusions']) + upstream = upstream_gate(record) + return {'schema': 'h3-local-source-gate-v1', + 'admission_record': identity(raw), 'custody_receipt': identity(custody_raw), + 'exclusions': identity(exclusions_raw), + 'upstream_metadata': upstream, + 'ancestor_drive_id': ANCESTOR_ID, 'candidate_use': 'REQUIRES_REVIEW', + 'body_allowlist': BODY_ALLOWLIST, + 'authority': 'Pinned local provenance snapshot plus current repository exclusions; not live Drive permissions or canonical scientific admission'} + + +def source_check(path, context): + gate = metadata_gate(context) # Must precede even opaque archive reads. + raw = read_bounded(path, ARCHIVE_ID['bytes']) + need(identity(raw) == ARCHIVE_ID, 'original H3 archive identity mismatch') + with zipfile.ZipFile(io.BytesIO(raw)) as archive: + infos = archive.infolist() + names = {item.filename for item in infos} + need(len(infos) == len(names) == 71, 'archive member set mismatch') + need(sum(item.file_size for item in infos) <= 5_000_000, 'expanded archive size limit') + for item in infos: + safe_name(item.filename) + need(stat.S_IFMT(item.external_attr >> 16) in (0, stat.S_IFREG), 'nonregular archive member') + need(0 <= item.file_size <= 2_000_000 and not item.flag_bits & 1, 'oversized or encrypted archive member') + need(item.compress_type in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED), 'unsupported compression') + manifest_raw = archive.read('MANIFEST.json') + need(identity(manifest_raw) == MANIFEST_ID, 'source manifest mismatch') + rows = strict_json(manifest_raw)['files'] + need(type(rows) is list and len(rows) == 70, 'source manifest cardinality mismatch') + records = {row['path']: {'bytes': row['bytes'], 'sha256': row['sha256']} for row in rows} + need(len(records) == 70 and set(records) | {'MANIFEST.json'} == names, 'duplicate or incomplete manifest mapping') + for name, expected in BODY_ALLOWLIST.items(): + need(records.get(name) == expected, 'selected body manifest identity mismatch') + # Recheck current policy after archive metadata and before analytic bodies. + need(metadata_gate(context) == gate, 'source metadata changed before body read') + bodies = {name: identity(archive.read(name)) for name in BODY_ALLOWLIST} + need(bodies == BODY_ALLOWLIST, 'selected source body identity mismatch') + need(metadata_gate(context) == gate, 'source metadata changed during body read') + return {'archive_sha256': ARCHIVE_ID['sha256'], 'manifest_sha256': MANIFEST_ID['sha256'], + 'archive_entries': len(infos), 'manifest_entries_checked_as_metadata': len(rows), + 'analytic_bodies_read': bodies, 'analytic_proof_sha256': bodies['h3_floor/PROOF.md']['sha256'], + 'admission': gate, 'scope': 'Candidate-only source byte custody and local eligibility; not acceptance'} diff --git a/engine/solver_pilots/h3_20260921/sources/H3_AUTHORED_NESTED_SOURCE_V1.json b/engine/solver_pilots/h3_20260921/sources/H3_AUTHORED_NESTED_SOURCE_V1.json new file mode 100644 index 000000000..5e460fb4a --- /dev/null +++ b/engine/solver_pilots/h3_20260921/sources/H3_AUTHORED_NESTED_SOURCE_V1.json @@ -0,0 +1,82 @@ +{ + "ancestor": { + "bytes": 2972608, + "drive_id": "1ni4q7t4a6rIpDkxapmc9yU4Xt1wv3983", + "name": "H3_RN_N6_DELIVERY_20260920_v1.zip", + "sha256": "891d0b63bb686bf43742a33edd458c48e86d1dea70253b0fd91f6cdf517f0fdc" + }, + "ancestor_manifest": { + "bytes": 29179, + "entry_path": "research/campaigns/h3_rn_n6_20260920_v1.zip", + "path": "DELIVERY_MANIFEST.json", + "sha256": "6fa3e295c3ad5f3a3f4753c597e7cd76f20e143c0bb6a991a9fc88db915782b9" + }, + "archive": { + "bytes": 571735, + "path": "research/campaigns/h3_rn_n6_20260920_v1.zip", + "sha256": "73b9e63800f77c677c504f3097fe0bb2459ff6c94cdee5772b56062320aefc21" + }, + "archived_programs_executed": false, + "authority": "Local retained provenance snapshot for this candidate-reading scope; not a live Drive permission check, source-map export, new scientific warrant, or canonical source admission.", + "body_allowlist": { + "h3_floor/PROOF.md": { + "bytes": 10423, + "sha256": "b48d8baa39b80be9a15af9833234d9339ea0afa4cdff2e1c60ae9ef79f5cb4fa" + } + }, + "candidate_use": "REQUIRES_REVIEW", + "compatibility": "Original SOURCES.json is historical declared exposure. Its delivery_drive_id names the outer delivery, not the raw archive or the archived proof. This numbered record supplies the exact nested relationship without rewriting that file.", + "current_custody": { + "bytes": 1746, + "observed_receipt_utc": "2026-09-21T23:52:30.286501+00:00", + "path": "sources/H3_CURRENT_SOURCE_CUSTODY_V1.json", + "sha256": "d5db9aab9360f092478906c4d462d35a15cc6f159ca4a507e7fdbf9e32100ac7" + }, + "eligibility": "CANDIDATE_READING", + "fresh_ancestor_readback": { + "bytes": 190, + "record": "h3-ancestor-readback.json", + "sha256": "86b00f6f32cd6a19ec8c73edae0aaee5bbe8a0a85699b566ea85dbf563a1059e" + }, + "implementation_claim": "6a1e1fe6-2042-44b3-8b03-9b378d2adc8e", + "manifest": { + "bytes": 12008, + "path": "MANIFEST.json", + "sha256": "81770e26ec654d3b462f06cebaa20d0dd282cfd4df10ac593c7887ea0d292b40" + }, + "organizational_independence_credit": 0, + "provenance_review": { + "bytes": 9548, + "record": "h3-provenance.md", + "sha256": "95eb92aa3a16e5d8424b28577355e36d8893d6e16ce657a7564686bd5d6fff91" + }, + "record_id": "H3-AUTHORED-NESTED-SOURCE-20260921-v1", + "registration_reference": { + "artifact_index_row": 805, + "status": "registered candidate; scoped scientific review open", + "target": "DG-H3-RN-N6-20260920-v1" + }, + "schema": "h3-authored-nested-source-v1", + "scientific_acceptance": false, + "scientific_status_changed": false, + "scope": "2D SIDE24 fixed x axis; canonical six-pin law; b=6/5; gap=r^3/6; 00 for x in report['shifted_gram_pivots'])) + + +class ScientificDirection(unittest.TestCase): + def test_wide_crossing_not_counterexample(self): + self.assertEqual(r.classify_enclosure('1','4','1.7','3.49','TARGET_QUANTITY_ENCLOSURE'),'INCONCLUSIVE_REFINE_ENCLOSURE') + def test_upper_below_floor_is_conflict(self): + self.assertIn('CONTRADICTION',r.classify_enclosure('1','1.6','1.7','3.49','TARGET_QUANTITY_ENCLOSURE')) + def test_lower_above_ceiling_is_conflict(self): + self.assertIn('CONTRADICTION',r.classify_enclosure('3.5','4','1.7','3.49','TARGET_QUANTITY_ENCLOSURE')) + def test_lower_formula_cannot_refute_true_quantity(self): + self.assertEqual(r.classify_enclosure('0','1','1.7','3.49','SUFFICIENT_LOWER_BOUND'),'WRONG_QUANTITY_FOR_REFUTATION') + def test_equal_endpoint_not_strict_violation(self): + self.assertEqual(r.classify_enclosure('1','1.7','1.7','3.49','TARGET_QUANTITY_ENCLOSURE'),'INCONCLUSIVE_REFINE_ENCLOSURE') + def test_compatible_point_not_universal_proof(self): + self.assertIn('DOMAIN_ONLY',r.classify_enclosure('2','3','1.7','3.49','TARGET_QUANTITY_ENCLOSURE')) + def test_no_float_parameter_in_proof(self): + with self.assertRaises(ValueError):c.prove(epsilon=.206) + def test_two_axial_tails_required(self): + with self.assertRaises(ValueError):c.prove(axial_tails=F(1)) + def test_two_difference_tails_required(self): + with self.assertRaises(ValueError):c.prove(difference_tails=F(1)) + def test_no_understated_beta(self): + with self.assertRaises(ValueError):c.prove(beta_scale=F(1,8)) + def test_no_understated_variance_loss(self): + with self.assertRaises(ValueError):c.prove(variance_loss=F(1,8)) + def test_radius_scope_refusal(self): + with self.assertRaises(ValueError):c.prove(radius=F(1,10)) + def test_zero_radius_not_endpoint_claim(self): + with self.assertRaises(ValueError):c.prove(radius=F(0)) + def test_invalid_parameter_refusal(self): + with self.assertRaises(ValueError):c.prove(epsilon=F(1)) + def test_search_is_diagnostic(self): + x=r.search();self.assertEqual(x['evaluated'],30351) + self.assertEqual(x['status'],'NONCERTIFYING_PARAMETER_SEARCH') + self.assertEqual((x['epsilon'],x['gap_half']),('103/500','9/100')) + def test_malformed_interval_refused(self): + with self.assertRaises(ValueError):r.classify_enclosure('2','1','0','3','TARGET_QUANTITY_ENCLOSURE') + + +class Provenance(unittest.TestCase): + def sample_context(self):return json.loads((HERE/'CONTEXT.json').read_text()) + def test_context_denial_before_cache(self): + x=self.sample_context();x['source_usable_for_candidate']=False + with self.assertRaises(ValueError):r.recipe({'archive_sha256':r.ARCHIVE_SHA},x,{}) + def test_context_new_hash_new_key(self): + x=self.sample_context();y=dict(x,basis='same candidate; additional observation') + self.assertNotEqual(c.digest(r.recipe({'archive_sha256':r.ARCHIVE_SHA},x,{})),c.digest(r.recipe({'archive_sha256':r.ARCHIVE_SHA},y,{}))) + def test_context_source_mismatch(self): + with self.assertRaises(ValueError):r.recipe({'archive_sha256':'0'*64},self.sample_context(),{}) + def test_independence_cannot_be_imported(self): + x=self.sample_context();x['organizational_independence_credit']=1 + with self.assertRaises(ValueError):r.recipe({'archive_sha256':r.ARCHIVE_SHA},x,{}) + def test_local_cache_hit_no_recompute(self): + with tempfile.TemporaryDirectory() as d: + x,tag,_=r.cached({'input':1},d,lambda:{'answer':2}) + y,tag2,_=r.cached({'input':1},d,lambda:self.fail('must hit')) + self.assertEqual(x,y);self.assertIn('NOT_NEW_EVIDENCE',tag2) + def test_cache_tampering_detected(self): + with tempfile.TemporaryDirectory() as d: + _,_,key=r.cached({'input':1},d,lambda:{'answer':2}) + p=Path(d)/(key+'.json');v=json.loads(p.read_text());v['payload']['answer']=3;p.write_text(json.dumps(v)) + with self.assertRaises(ValueError):r.cached({'input':1},d,lambda:{'answer':2}) + def test_cold_cache_disagreement_detected(self): + with tempfile.TemporaryDirectory() as d: + r.cached({'input':1},d,lambda:{'answer':2}) + with self.assertRaises(ValueError):r.cached({'input':1},d,lambda:{'answer':3},cold=True) + def test_changed_inputs_recompute(self): + with tempfile.TemporaryDirectory() as d: + r.cached({'input':1},d,lambda:2) + y,tag,_=r.cached({'input':2},d,lambda:3) + self.assertEqual((y,tag),(3,'MISS_COMPUTED')) + def test_dependency_propagation(self): + self.assertEqual(r.affected_nodes(['midpoint']),['coefficient','determinant','midpoint']) + def test_unknown_lineage_node_rejected(self): + with self.assertRaises(ValueError):r.affected_nodes(['fake']) + def test_archive_mutation_refused(self): + with tempfile.TemporaryDirectory() as d: + p=Path(d)/'bad.zip';p.write_bytes(b'not the source') + with self.assertRaises(ValueError):r.source_check(p,self.sample_context()) + + +class ExactCandidate(unittest.TestCase): + @classmethod + def setUpClass(cls):cls.result=c.prove() + def test_new_floor(self): + v=self.result['values']['derived_lower_coefficient'] + self.assertGreater(F(v['lo']),F(1747,1000)) + self.assertLess(F(v['hi']),F(7,4)) + def test_scope_is_preserved(self): + self.assertEqual(self.result['conclusion']['endpoint_at_rmax'],'1747/400000') + self.assertFalse(self.result['scientific_status_changed']) + self.assertEqual(self.result['organizational_independence_credit'],0) + def test_positive_budget_before_product(self): + for key in ('positive_bracket','p_axial','p_difference'): + self.assertGreater(F(self.result['values'][key]['lo']),0) + def test_formula_root_changes_with_upstream_data(self): + x=copy.deepcopy(self.result);x['parameters']['epsilon']='1/5' + a=r.formula_lineage(self.result,{'archive_sha256':r.ARCHIVE_SHA});b=r.formula_lineage(x,{'archive_sha256':r.ARCHIVE_SHA}) + self.assertNotEqual(a['root'],b['root']);self.assertEqual(a['spreadsheet_cells_used'],[]) + def test_unattainable_target_rejected(self): + with self.assertRaises(ValueError):c.prove(target=F(7,4)) + def test_original_parameters_still_clear_original_target(self): + x=c.prove(epsilon=F(1,5),gap_half=F(3,25),target=F(17,10)) + self.assertGreater(F(x['values']['derived_lower_coefficient']['lo']),F(17,10)) + + +class SourceAdmission(unittest.TestCase): + """Synthetic metadata controls, never a second admission authority.""" + @classmethod + def setUpClass(cls): + cls.certificate = c.prove() + cls.original_root = r.admission.ROOT + cls.original_record = r.admission.ADMISSION + cls.record_bytes = cls.original_record.read_bytes() + cls.record = json.loads(cls.record_bytes) + cls.archive_bytes = (cls.original_root/r.admission.ARCHIVE).read_bytes() + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.ad = r.admission + self.context = json.loads((HERE/'CONTEXT.json').read_text()) + self.record_path = self.root/'admission.json' + self.record_path.write_bytes(self.record_bytes) + (self.root/'sources').mkdir() + self.custody_path=self.root/'sources/H3_CURRENT_SOURCE_CUSTODY_V1.json' + self.custody_path.write_bytes((HERE/'sources/H3_CURRENT_SOURCE_CUSTODY_V1.json').read_bytes()) + self.exclusions_path = self.root/'quarantine/EXCLUSIONS.json' + self.exclusions_path.parent.mkdir() + self.write_exclusions([]) + (self.root/'drive/source_map').mkdir(parents=True) + carrier = self.record['upstream']['carrier'] + link = 'https://drive.google.com/file/d/'+carrier['drive_id']+'/view' + self.inventory = [dict(id=carrier['drive_id'], bytes=carrier['bytes'], sha256=carrier['sha256'], + context='RESEARCH_SOURCE_CHECK_STATUS', access_status='ARCHIVE_INDEXED', + path='01_ACTIVE_RESEARCH_PACKAGES/current/source.zip', link=link)] + self.payloads = [{'Source name':name, 'SHA-256':value['sha256'], 'Bytes':str(value['bytes']), + 'Conversion':'TEXT_READING_COPY', 'Context':'RESEARCH_SOURCE_CHECK_STATUS', + 'Scope holds':'[]', 'Original source link':link} + for name,value in self.record['upstream']['members'].items()] + self.write_inventory(); self.write_payloads() + self.archive = self.root/'source.zip'; self.archive.write_bytes(self.archive_bytes) + self.context_path = self.root/'context.json'; self.context_path.write_text(json.dumps(self.context)) + self.enterContext(mock.patch.object(self.ad,'ROOT',self.root)) + self.enterContext(mock.patch.object(self.ad,'HERE',self.root)) + self.enterContext(mock.patch.object(self.ad,'ADMISSION',self.record_path)) + self.ad.metadata_gate(self.context) # Each negative starts from an admitted fixture. + + def write_exclusions(self,rows): + self.exclusions_path.write_text(json.dumps({'exclusions':rows})) + + def write_inventory(self): + (self.root/'drive/inventory.jsonl').write_text(''.join(json.dumps(row)+'\n' for row in self.inventory)) + + def write_payloads(self): + with (self.root/'drive/source_map/Payloads.csv').open('w',newline='') as f: + writer=csv.DictWriter(f,fieldnames=list(self.payloads[0]));writer.writeheader();writer.writerows(self.payloads) + + def denial(self,context=None): + # Fails if a denial opens even ZIP metadata or reads the opaque archive. + original=self.ad.read_bounded + def read(path,limit): + self.assertNotEqual(Path(path),self.archive,'denied archive bytes were read') + return original(path,limit) + with mock.patch.object(self.ad,'read_bounded',side_effect=read), mock.patch.object(zipfile.ZipFile,'open') as opened: + with self.assertRaises((ValueError,OSError)): + self.ad.source_check(self.archive,self.context if context is None else context) + opened.assert_not_called() + + def exclusion(self,**changes): + row={'kind':'archive_member','carrier_id':self.ad.ANCESTOR_ID,'member_path':'h3_floor/PROOF.md'} + row.update(changes);self.write_exclusions([row]) + + def main(self,out,**kwargs): + argv=['h3_solver.py','--source-archive',str(self.archive),'--context',str(self.context_path),'--out',str(out), + '--cache',str(self.root/'cache')] + with mock.patch.object(sys,'argv',argv), mock.patch.object(r,'prove',**kwargs) as compute, mock.patch('builtins.print'): + r.main() + return compute + + def test_only_manifest_and_allowlisted_body_opened(self): + seen=[];original=zipfile.ZipFile.open + def opened(z,name,*args,**kwargs): + seen.append(name.filename if isinstance(name,zipfile.ZipInfo) else name) + return original(z,name,*args,**kwargs) + with mock.patch.object(zipfile.ZipFile,'open',opened): + result=self.ad.source_check(self.archive,self.context) + self.assertEqual(seen,['MANIFEST.json','h3_floor/PROOF.md']) + self.assertEqual(result['analytic_bodies_read'],self.ad.BODY_ALLOWLIST) + self.assertNotIn('verified_manifest_leaves',result) + + def test_caller_denial_precedes_every_metadata_read(self): + self.context['source_usable_for_candidate']=False + with mock.patch.object(self.ad,'read_bounded') as read: + with self.assertRaises(ValueError):self.ad.source_check(self.archive,self.context) + read.assert_not_called() + + def test_unknown_context_hold_field_refused_before_metadata(self): + self.context['new_hold']=True + with mock.patch.object(self.ad,'read_bounded') as read: + with self.assertRaises(ValueError):self.ad.source_check(self.archive,self.context) + read.assert_not_called() + def test_missing_context_basis_refused(self): + del self.context['basis'];self.denial() + def test_missing_custody_receipt_refused(self): + self.custody_path.unlink();self.denial() + def test_changed_custody_receipt_refused(self): + self.custody_path.write_text('{}');self.denial() + def test_unsupported_source_url_query_refused(self): + self.payloads[0]['Original source link']+='?id=other';self.write_payloads();self.denial() + def test_source_url_fragment_refused(self): + self.payloads[0]['Original source link']+='#other';self.write_payloads();self.denial() + def test_supported_drivesdk_query_keeps_same_identity(self): + self.payloads[0]['Original source link']+='?usp=drivesdk';self.write_payloads() + self.ad.source_check(self.archive,self.context) + + def test_context_false_scope_refused(self): + self.context['scope']='all angles; promoted theorem';self.denial() + def test_context_cannot_import_independence_bool(self): + self.context['organizational_independence_credit']=False;self.denial() + def test_context_revalidation_cannot_be_disabled(self): + self.context['current_use_requires_revalidation']=False;self.denial() + def test_missing_admission_refused_before_archive(self): + self.record_path.unlink();self.denial() + def test_changed_admission_refused_before_archive(self): + obj=json.loads(self.record_bytes);obj['eligibility']='HELD';self.record_path.write_text(json.dumps(obj));self.denial() + def test_extra_allowlisted_body_cannot_be_asserted(self): + obj=json.loads(self.record_bytes);obj['body_allowlist']['rn_n6/PROOF.md']=dict(bytes=1,sha256='0'*64) + self.record_path.write_text(json.dumps(obj));self.denial() + def test_duplicate_admission_key_refused(self): + self.record_path.write_bytes(b'{"schema":"first","schema":"second"}');self.denial() + def test_symlink_admission_refused(self): + other=self.root/'other.json';self.record_path.rename(other);self.record_path.symlink_to(other);self.denial() + def test_missing_exclusions_refused(self): + self.exclusions_path.unlink();self.denial() + def test_duplicate_exclusion_key_refused(self): + self.exclusions_path.write_text('{"exclusions":[],"exclusions":[]}');self.denial() + def test_unknown_exclusion_kind_refused(self): + self.exclusion(kind='unrecognized');self.denial() + def test_ancestor_drive_hold_refused(self): + self.exclusion(kind='drive_object',member_path='delivery');self.denial() + def test_ancestor_hash_hold_refused(self): + self.exclusion(payload_sha256=self.record['ancestor']['sha256'],member_path='alias');self.denial() + def test_raw_archive_hash_hold_refused(self): + self.exclusion(payload_sha256=self.ad.ARCHIVE_ID['sha256'],member_path='alias');self.denial() + def test_nested_member_path_hold_refused(self): + self.exclusion(member_path=self.ad.ARCHIVE+'!/h3_floor/PROOF.md');self.denial() + def test_proof_hash_hold_cannot_be_hidden_by_other_carrier(self): + self.exclusion(payload_sha256=self.ad.BODY_ALLOWLIST['h3_floor/PROOF.md']['sha256'],carrier_id='other');self.denial() + def test_upstream_carrier_hold_refused(self): + self.exclusion(kind='drive_object',carrier_id=self.inventory[0]['id']);self.denial() + def test_upstream_member_hold_refused(self): + self.exclusion(carrier_id=self.inventory[0]['id'],member_path=self.payloads[0]['Source name']);self.denial() + def test_unrelated_held_leaf_is_not_opened_or_an_overbroad_denial(self): + self.exclusion(member_path='rn_n6/unrelated.py',payload_sha256='0'*64) + result=self.ad.source_check(self.archive,self.context) + self.assertEqual(list(result['analytic_bodies_read']),['h3_floor/PROOF.md']) + def test_missing_upstream_carrier_refused(self): + self.inventory=[];self.write_inventory();self.denial() + def test_ambiguous_upstream_carrier_refused(self): + self.inventory.append(dict(self.inventory[0]));self.write_inventory();self.denial() + def test_upstream_access_denial_refused(self): + self.inventory[0]['access_status']='NO_ACCESS';self.write_inventory();self.denial() + def test_upstream_legacy_path_refused(self): + self.inventory[0]['path']='02_LEGACY_Q0_ARCHIVE/source.zip';self.write_inventory();self.denial() + def test_upstream_context_denial_refused(self): + self.inventory[0]['context']='QUARANTINE_OR_HISTORY';self.write_inventory();self.denial() + def test_upstream_carrier_identity_drift_refused(self): + self.inventory[0]['sha256']='0'*64;self.write_inventory();self.denial() + def test_upstream_member_identity_drift_refused(self): + self.payloads[0]['Bytes']='16700';self.write_payloads();self.denial() + def test_upstream_scope_hold_refused(self): + self.payloads[0]['Scope holds']='[{"key":"NEW_HOLD"}]';self.write_payloads();self.denial() + def test_upstream_ambiguous_member_refused(self): + self.payloads.append(dict(self.payloads[0]));self.write_payloads();self.denial() + def test_upstream_missing_member_refused(self): + self.payloads.pop();self.write_payloads();self.denial() + def test_upstream_context_multiplicity_refused(self): + self.payloads[0]['Context']='MULTIPLE_CONTEXTS';self.write_payloads();self.denial() + def test_upstream_wrong_source_link_refused(self): + self.payloads[0]['Original source link']='https://drive.google.com/file/d/other/view';self.write_payloads();self.denial() + def test_duplicate_csv_header_refused(self): + p=self.root/'drive/source_map/Payloads.csv';p.write_text('SHA-256,SHA-256\na,a\n');self.denial() + def test_duplicate_inventory_key_refused(self): + (self.root/'drive/inventory.jsonl').write_text('{"id":"a","id":"b"}\n');self.denial() + def test_csv_short_row_refused(self): + p=self.root/'drive/source_map/Payloads.csv';p.write_text(p.read_text()+'a,b\n');self.denial() + def test_metadata_size_bound_precedes_archive(self): + self.exclusions_path.write_bytes(b' '*(self.ad.MAX_METADATA+1));self.denial() + def test_archive_mutation_after_valid_gate_refused(self): + self.archive.write_bytes(b'not the source') + with mock.patch.object(zipfile.ZipFile,'open') as opened: + with self.assertRaises(ValueError):self.ad.source_check(self.archive,self.context) + opened.assert_not_called() + + def test_policy_drift_after_manifest_prevents_proof_read(self): + original=zipfile.ZipFile.read;seen=[] + def read(z,name,*args,**kwargs): + seen.append(name);value=original(z,name,*args,**kwargs) + if name=='MANIFEST.json':self.exclusion() + return value + with mock.patch.object(zipfile.ZipFile,'read',read): + with self.assertRaises(ValueError):self.ad.source_check(self.archive,self.context) + self.assertEqual(seen,['MANIFEST.json']) + + def test_current_metadata_in_recipe_changes_key(self): + first=self.ad.source_check(self.archive,self.context) + self.inventory[0]['observation']='fresh metadata snapshot';self.write_inventory() + second=self.ad.source_check(self.archive,self.context) + self.assertNotEqual(c.digest(r.recipe(first,self.context,{})),c.digest(r.recipe(second,self.context,{}))) + + def test_warm_cache_rechecks_eligibility(self): + first=self.root/'first.json';self.main(first,return_value=self.certificate) + self.exclusion() + with mock.patch.object(zipfile.ZipFile,'open') as opened: + with self.assertRaises(ValueError):self.main(self.root/'denied.json',side_effect=AssertionError('must not compute')) + opened.assert_not_called() + self.assertFalse((self.root/'denied.json').exists()) + + def test_eligible_warm_hit_retains_trusted_local_label(self): + self.main(self.root/'first.json',return_value=self.certificate) + compute=self.main(self.root/'second.json',side_effect=AssertionError('must not compute')) + compute.assert_not_called() + result=json.loads((self.root/'second.json').read_text()) + self.assertEqual(result['cache'],'LOCAL_TRUSTED_HIT_NOT_NEW_EVIDENCE') + self.assertFalse(result['automatic_promotion']) + + def test_drift_during_compute_never_publishes(self): + def compute(**kwargs):self.exclusion();return self.certificate + with self.assertRaises(ValueError):self.main(self.root/'denied.json',side_effect=compute) + self.assertFalse((self.root/'denied.json').exists()) + + def test_cli_real_cold_run_and_denied_retry(self): + # Relocated minimal checkout: fixture metadata, unchanged canonical ZIP, + # and the actual CLI. No system checkout or native source export is edited. + destination=self.root/'engine/solver_pilots/h3_20260921';destination.mkdir(parents=True) + for name in ('h3_solver.py','h3_source_admission.py','h3_scalar_arithmetic.py','h3_scalar_certificate.py'): + (destination/name).write_bytes((HERE/name).read_bytes()) + (destination/'sources').mkdir() + (destination/'sources/H3_AUTHORED_NESTED_SOURCE_V1.json').write_bytes(self.record_bytes) + (destination/'sources/H3_CURRENT_SOURCE_CUSTODY_V1.json').write_bytes( + (HERE/'sources/H3_CURRENT_SOURCE_CUSTODY_V1.json').read_bytes()) + cmd=[sys.executable]+(['-O'] if sys.flags.optimize else [])+[str(destination/'h3_solver.py'), + '--source-archive',str(self.archive),'--context',str(self.context_path), + '--out',str(self.root/'cli.json'),'--cold','--expected-certificate-sha',c.digest(self.certificate)] + done=subprocess.run(cmd,capture_output=True,text=True,timeout=30,env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1')) + self.assertEqual(done.returncode,0,done.stderr) + self.assertEqual(json.loads((self.root/'cli.json').read_text())['certificate'],self.certificate) + self.exclusion();cmd[cmd.index('--out')+1]=str(self.root/'cli-denied.json') + denied=subprocess.run(cmd,capture_output=True,text=True,timeout=30,env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1')) + self.assertEqual(denied.returncode,2,denied.stderr) + self.assertFalse((self.root/'cli-denied.json').exists()) + + +class ActualSourceAdmission(unittest.TestCase): + def test_current_repository_metadata_and_exact_source(self): + context=json.loads((HERE/'CONTEXT.json').read_text()) + result=r.source_check(r.admission.ROOT/r.admission.ARCHIVE,context) + self.assertEqual(result['analytic_bodies_read'],r.admission.BODY_ALLOWLIST) + self.assertIn('upstream_metadata',result['admission']) + + +if __name__=='__main__':unittest.main() diff --git a/tests/test_workflows.py b/tests/test_workflows.py index eb40dd97d..a91155ab5 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -17,7 +17,9 @@ ROOT = pathlib.Path(__file__).resolve().parents[1] WORKFLOWS = sorted((ROOT / ".github" / "workflows").glob("*.yml")) -CHECKER = re.compile(r"python3?\s+(tools/\S+\.py|-m\s+pytest)") +CHECKER = re.compile( + r"\bpython3?(?:\s+-O)?\s+(tools/\S+\.py|engine/solver_pilots/\S+\.py|-m\s+(?:pytest|unittest)\b)" +) MASK = re.compile(r"\|\|\s*(?:echo|true|:)(?:\s|$)") @@ -38,24 +40,29 @@ def run_blocks(text: str) -> list[str]: while i < len(lines) and (not lines[i].strip() or len(lines[i]) - len(lines[i].lstrip()) > len(indent)): body.append(lines[i]) i += 1 - blocks.append("\n".join(body)) + blocks.append(" ".join(line.strip() for line in body) if rest.strip().startswith(">") else "\n".join(body)) else: blocks.append(rest) i += 1 return blocks +def logical_lines(block: str) -> list[str]: + # A mask after a continued CLI argument still masks the checker process. + return re.sub(r"\\\s*\n\s*", " ", block).splitlines() + + def masked_checker_lines(text: str) -> list[str]: bad = [] for block in run_blocks(text): - for line in block.splitlines(): + for line in logical_lines(block): if CHECKER.search(line) and MASK.search(line): bad.append(line.strip()) return bad def test_workflow_files_exist(): - assert [p.name for p in WORKFLOWS] == ["ci.yml", "research.yml"] + assert [p.name for p in WORKFLOWS] == ["ci.yml", "h3-solver-pilot.yml", "research.yml", "withdrawal-governance.yml"] @pytest.mark.parametrize("path", WORKFLOWS, ids=lambda p: p.name) @@ -67,7 +74,7 @@ def test_no_checker_step_masks_its_failure(path): def test_every_repository_checker_step_is_seen(path): # The scanner must actually find the checker invocations, or the test # above passes vacuously. - seen = [l for b in run_blocks(path.read_text()) for l in b.splitlines() if CHECKER.search(l)] + seen = [l for b in run_blocks(path.read_text()) for l in logical_lines(b) if CHECKER.search(l)] assert len(seen) >= 3, seen @@ -88,3 +95,27 @@ def test_negative_control_the_pre_2026_09_19_line_is_refused(): def test_unmasked_checker_passes(): assert masked_checker_lines(" - run: python tools/lanes_check.py\n") == [] + + +@pytest.mark.parametrize("command", [ + "python3 -m unittest discover -s tests -p test_h3_solver_pilot.py -v", + "python3 -O -m unittest discover -s tests -p test_h3_solver_pilot.py -v", + "python3 -O tools/withdrawal_check.py check", + "python3 engine/solver_pilots/h3_20260921/h3_solver.py --cold", +]) +def test_new_workflow_checker_mask_is_refused(command): + assert masked_checker_lines(" - run: " + command + " || true\n") == [command + " || true"] + assert masked_checker_lines(" - run: " + command + "\n") == [] + + +def test_wrapped_h3_cli_mask_is_refused(): + text = (" - run: |\n" + " python3 engine/solver_pilots/h3_20260921/h3_solver.py \\\n" + " --out result.json --cold || echo skipped\n") + bad = masked_checker_lines(text) + assert len(bad) == 1 and "h3_solver.py" in bad[0] and "|| echo skipped" in bad[0] + + +def test_folded_checker_mask_is_refused(): + text = " - run: >-\n python3 tools/withdrawal_check.py check\n || true\n" + assert masked_checker_lines(text) == ["python3 tools/withdrawal_check.py check || true"]