"""Full small Grams, independent modular ranks, and implicit recipe integrity.""" import json import os from pathlib import Path import numpy as np import pytest from theory.code import block_bootstrap as block ROOT=Path(os.environ.get('BUTSON_TOWERS_ROOT',Path(__file__).resolve().parents[2])) INPUTS=ROOT/'search/code/williamson_inputs.json' CERTIFICATE=ROOT/'certificates/scalar-lift/known-order-paley-comparison.json' @pytest.fixture(scope='module') def seeds(): return block.small_seed_pair(INPUTS) def test_full_H72_H144_Grams_and_direct_rank_distinctions(seeds): a,b=seeds assert block.rank_mod3(a.array())==16 and block.rank_mod3(b.array())==18 for exponent in (1,2): m=2**exponent;found=[] for k in range(m+1): recipe=block.two_seed_recipe(a,b,exponent,k) literal=recipe.dense().astype(np.int64) assert set(np.unique(literal))=={-1,1} assert np.array_equal(literal@literal.T,36*m*np.eye(36*m,dtype=np.int64)) # Rank is computed from every literal output entry, independently # of the conditional sum-of-seed-ranks prediction. rank=block.rank_mod3(literal) assert rank==recipe.conditional_rank_mod3((16,18))==16*m+2*k found.append(rank) assert len(set(found))==m+1 def test_generic_selector_row_and_factorization_are_literal(seeds): a,b=seeds choices=(1,0,1,1) recipe=block.SylvesterBlocks((a,b),2,lambda v:choices[v]) h=36;m=4 outer=np.array([[(-1)**((u&v).bit_count()%2)for v in range(m)]for u in range(m)],dtype=np.int64) diagonal=np.zeros((h*m,h*m),dtype=np.int64) for v,choice in enumerate(choices): diagonal[v*h:(v+1)*h,v*h:(v+1)*h]=(a,b)[choice].array() explicit=np.kron(outer,np.eye(h,dtype=np.int64))@diagonal assert np.array_equal(recipe.dense(),explicit) assert np.array_equal(recipe.row(50),explicit[50]) assert recipe.conditional_rank_mod3((16,18))==70 assert recipe.entry(np.int64(50),np.int64(100))==explicit[50,100] def test_corrupt_seed_is_rejected_and_verified_literal_cannot_alias_input(seeds): original=seeds[0].array();checked=block.ArrayHadamard(original) original[0,0]*=-1 assert checked.entry(0,0)!=original[0,0] with pytest.raises(ValueError,match='complete integer Gram'): block.ArrayHadamard(original) with pytest.raises(ValueError,match='integer signs'): block.ArrayHadamard(seeds[0].array().astype(float)) with pytest.raises(ValueError,match='square'): block.ArrayHadamard(np.ones((2,3),dtype=int)) def test_allocation_budgets_and_types_fail_before_calling_any_seed(): class ForbiddenSeed: order=36 def entry(self,i,j):raise AssertionError('forbidden allocation reached source') recipe=block.two_seed_recipe(ForbiddenSeed(),ForbiddenSeed(),20,3) with pytest.raises(ValueError,match='allocation budget'):recipe.row(0,maximum_entries=100) with pytest.raises(ValueError,match='allocation budget'):recipe.dense(maximum_order=100) for t,k in ((True,0),(1.0,0),(-1,0),(1,True),(1,3),(block.MAX_EXPONENT+1,0)): with pytest.raises(ValueError):block.two_seed_recipe(ForbiddenSeed(),ForbiddenSeed(),t,k) for i,j in ((True,0),(0,False),(0,1.0),(-1,0),(recipe.order,0)): with pytest.raises(ValueError):recipe.entry(i,j) def test_bad_selector_or_sign_and_rank_metadata_cannot_create_a_claim(seeds): a,b=seeds for selector in (lambda v:2,lambda v:True,lambda v:0.0): recipe=block.SylvesterBlocks((a,b),1,selector) with pytest.raises(ValueError):recipe.entry(0,0) with pytest.raises(ValueError,match='same order'): block.two_seed_recipe(a,block.ArrayHadamard(np.array([[1]],dtype=int)),1,1) class BadSeed: order=36 def entry(self,i,j):return 0 with pytest.raises(ValueError,match='non-sign'): block.two_seed_recipe(BadSeed(),b,1,0).entry(0,0) for ranks in ((16,),(-1,18),(16,37),(True,18)): with pytest.raises(ValueError):block.two_seed_recipe(a,b,1,1).conditional_rank_mod3(ranks) with pytest.raises(ValueError,match='census'): block.SylvesterBlocks((a,b),20,lambda v:v%2).conditional_rank_mod3((16,18),maximum_blocks=10) def test_retained_large_rank_input_is_digest_bound_without_dense_allocation(tmp_path): result=block.known_rank_family_report(CERTIFICATE,exponents=(0,1,2)) assert result['source_ranks_mod3']==[246090,442962] assert [r['order']for r in result['families']]==[885924,1771848,3543696] assert [r['pairwise_inequivalent_representatives']for r in result['families']]==[2,3,5] assert result['large_dense_matrix_allocated'] is False changed=json.loads(CERTIFICATE.read_text());changed['endpoint_rank']+=1 bad=tmp_path/'changed.json';bad.write_text(json.dumps(changed)) with pytest.raises(ValueError,match='certificate hash mismatch'):block.known_rank_family_report(bad) changed_input=tmp_path/'changed-input.json';changed_input.write_bytes(INPUTS.read_bytes()+b' ') with pytest.raises(ValueError,match='input hash mismatch'):block.small_seed_pair(changed_input) def test_uint64_rank_reduction_does_not_overflow_before_modulus(): # 2^64-1 is divisible by3; casting to signed64 before reduction changes it. assert block.rank_mod3(np.array([[2**64-1]],dtype=np.uint64))==0 assert block.rank_mod3(np.array([[2**64-2]],dtype=np.uint64))==1 def test_retained_adapters_are_lazy_and_Paley_entries_need_no_scalar_initialization(monkeypatch,tmp_path): import sys sys.path.insert(0,str(ROOT)) from search.code import tripled_unreal_scalar_endpoints as existing def forbidden(order):raise AssertionError('large seed initialized before an explicit scalar entry') monkeypatch.setattr(existing,'endpoint',forbidden) a,b=block.retained_seed_recipes(CERTIFICATE) assert a.order==b.order==885924 # Only B is selected in the first block; these entries must not build A. recipe=block.two_seed_recipe(a,b,1,1) assert recipe.entry(0,0)==1 assert recipe.entry(100,104)==1 assert recipe.entry(104,100)==-1 assert recipe.entry(100,0)==-1 for i in (1,2,100,885923): assert b.entry(0,i)==1 and b.entry(i,0)==-1 and b.entry(i,i)==1 for i,j in ((1,2),(100,104),(17,883),(885923,1)): assert b.entry(i,j)+b.entry(j,i)==0 with pytest.raises(ValueError):a.entry(True,0) # Even a complete default report must avoid the old expensive entry factory. block.main(['--williamson-inputs',str(INPUTS),'--rank-certificate',str(CERTIFICATE), '--output',str(tmp_path/'report.json')]) calls=[] class MockEndpoint: order=885924 def entry(self,i,j):return 1 if (i+j)%2==0 else -1 def factory(order): calls.append(order) return MockEndpoint() monkeypatch.setattr(existing,'endpoint',factory) assert a.entry(7,8)==-1 assert a.entry(9,9)==1 assert calls==[351] changed=tmp_path/'bad-seed-certificate.json' changed.write_bytes(CERTIFICATE.read_bytes()+b' ') with pytest.raises(ValueError,match='certificate hash mismatch'): block.retained_seed_recipes(changed)