"""Twenty bounded executable demonstrations; no product benchmark or security exploit. Run locally with Python 3 and NumPy. Assertions are intentional acceptance checks. """ from pathlib import Path from itertools import combinations,permutations,product from collections import Counter from bisect import bisect_left import json,math import numpy as np ROOT=Path(__file__).resolve().parents[1] TOPICS=json.loads((ROOT/"topics.json").read_text(encoding="utf-8")) RESULTS=[];ASSERTIONS=0 def ck(condition,message): global ASSERTIONS ASSERTIONS+=1 if not condition:raise AssertionError(message) def finish(n,label,witness,scope,start): RESULTS.append(dict(article=n,slug=TOPICS[n-1][0],check=label,assertions=ASSERTIONS-start, witness=witness,scope=scope,status="PASS")) def run(): start=ASSERTIONS;pairs=0 for n in range(3,10): q=n//2+1;sets=[set(v) for v in combinations(range(n),q)] smallest=n for a,b in product(sets,repeat=2): v=len(a&b);ck(v>=2*q-n,"quorum intersection");smallest=min(v,smallest);pairs+=1 ck(smallest==2*q-n,"tight lower bound") ck(not({0,1}&{2,3}),"minorities can be disjoint") votes=[({"A","B"},"x"),({"B","C"},"y")] ck(bool(votes[0][0]&votes[1][0]) and votes[0][1]!=votes[1][1],"intersection without persistent voting rules is insufficient") finish(1,"Enumerated quorum intersection and an agreement counterexample",dict(quorum_pairs=pairs,unsafe_witness="B votes x then y without a persistence rule"),"Subset arithmetic and a deliberately invalid voting rule; not a Raft or Paxos proof.",start) start=ASSERTIONS snapshot=[1,1];decisions=[sum(snapshot)-snapshot[i]>=1 for i in range(2)] final=[0 if decisions[i] else 1 for i in range(2)] ck(final==[0,0],"snapshot write skew") serial=[] for order in permutations(range(2)): state=[1,1] for i in order: if sum(state)-state[i]>=1:state[i]=0 ck(sum(state)>=1,"serial invariant");serial.append(state) finish(2,"Snapshot write skew versus both serial orders",dict(snapshot_final=final,serial_finals=serial),"Two disjoint-row transactions in a toy state machine; no database engine executed.",start) start=ASSERTIONS def invoke(state,kind,cut=None): effect,receipt=state if receipt:return state ops=["effect","receipt"] if kind=="effect-first" else ["receipt","effect"] if kind=="receipt-first" else ["atomic"] for step,op in enumerate(ops): if cut==step:return effect,receipt if op=="effect":effect+=1 elif op=="receipt":receipt=True else:effect+=1;receipt=True return effect,receipt outcomes={} for kind in ["effect-first","receipt-first","atomic"]: vals=[] for cut in range(3): crashed=invoke((0,False),kind,cut);recovered=invoke(crashed,kind) vals.append(recovered[0]) if kind=="atomic":ck(recovered==(1,True),"atomic receipt and effect") outcomes[kind]=vals ck(2 in outcomes["effect-first"],"duplicate effect witness") ck(0 in outcomes["receipt-first"],"lost effect witness") finish(3,"Crashes between effect and receipt writes",outcomes,"Sequential one-operation crash positions, no concurrent transactions or external side effects.",start) start=ASSERTIONS states=[frozenset(i for i in range(4) if mask&(1<1,"capacity invariant not merge-closed") finish(4,"All grow-only-set merge laws on a four-element universe",dict(states=16,capacity_counterexample=[list(a),list(b),list(a|b)]),"Finite grow-only sets; not a collaborative editor implementation or proof of intention preservation.",start) start=ASSERTIONS;bounds={} for b in range(2,9): impl=spec=0;first=None for k in range(1,2**b+1): spec+=1;impl=(impl+1)%(2**b) ck(impl==spec%(2**b),"correct modular specification") if impl!=spec and first is None:first=k ck(first==2**b,"first refinement mismatch");bounds[str(b)]=first finish(5,"Finite-width counter and a mismatched specification",bounds,"Exhaustive increment traces for 2-8 bits, not verification of seL4, CertiKOS or IronFleet.",start) start=ASSERTIONS sc=set();sc_count=0 for order in permutations(["Wx","Ry","Wy","Rx"]): pos={x:order.index(x) for x in order} if not(pos["Wx"]x if not pred:bad.append(x) ck((2*x)%256==(x<<1)%256,"bit-vector shift identity") ck(bad==[255],"invalid constant-true rewrite") a=1e16;left=(a-a)+1;right=a+(-a+1) ck(left==1 and right==0,"floating-point non-associativity") finish(7,"Exhaustive 8-bit rewrite and binary64 counterexample",dict(bad_inputs=bad,float_results=[left,right]),"Declared arithmetic expressions; no compiler binary or source-language undefined-behavior model.",start) start=ASSERTIONS def spatial(p,length):return 0<=p and length>0 and p+length<=16 def valid(p,length,access,capgen,livegen):return spatial(p,length) and access=="read" and capgen==livegen ck(valid(0,16,"read",1,1),"valid access") ck(not valid(16,1,"read",1,1) and not valid(-1,1,"read",1,1),"spatial rejection") ck(not valid(0,1,"write",1,1),"permission rejection") ck(spatial(4,4) and not valid(4,4,"read",1,2),"reuse temporal counterexample") finish(8,"Bounds, permissions and ideal generation lifetime",dict(reused_address=4,old_generation=1,live_generation=2),"Mathematical integers and an ideal generation model, not a CHERI emulator.",start) start=ASSERTIONS;majority={} for n in [3,5,7]: p=.1;prob=0 for bits in product([0,1],repeat=n): if sum(bits)>n//2:prob+=p**sum(bits)*(1-p)**(n-sum(bits)) closed=sum(math.comb(n,k)*p**k*(1-p)**(n-k) for k in range(n//2+1,n+1)) ck(math.isclose(prob,closed,rel_tol=1e-12),"majority enumeration") majority[str(n)]=prob ck(math.isclose(majority["3"],.028),"three-observation error") finish(9,"Enumerated independent binary-channel majority errors",majority,"A hypothetical noisy-bit channel; no processor attack, exploit or secret collection.",start) start=ASSERTIONS;bounds=[] for k,sigma in [(1,4),(10,8),(100,16),(1000,8)]: a=k/(2*sigma*sigma);L=math.log(1e6);closed=a+2*math.sqrt(a*L) orders=1+np.logspace(-4,4,200001) numerical=float(np.min(a*orders+L/(orders-1))) ck(math.isclose(numerical,closed,rel_tol=1e-7),"RDP continuous-order optimization") bounds.append(dict(k=k,sigma=sigma,closed=closed,grid=numerical)) for r in [1,2,10,100]: covariance=np.eye(r)*64;w=np.ones(r)/r ck(math.isclose(float(w@covariance@w),64/r,rel_tol=1e-12),"noise-average variance") finish(10,"Numerical RDP minimization and independent-noise variance",bounds,"Unsampled Gaussian mechanism accounting; not an empirical privacy audit or optimal analytic calibration.",start) start=ASSERTIONS roots=[x for x in range(101) if (x*x-9)%101==0] ck(roots==[3,98],"finite-field roots") ck([x for x in roots if 0<=x<=10]==[3],"range constraint") ck(len(roots)<=2,"degree root count") finish(11,"Finite-field relation versus intended integer range",dict(field_roots=roots,range_roots=[3]),"One polynomial relation over a tiny field; not a cryptographic proof system or security parameter.",start) start=ASSERTIONS;hashes=[lambda x:x%4,lambda x:(3*x+1)%4] def sketch(updates): c=np.zeros((2,4),dtype=np.int64) for key,delta in updates: for row,h in enumerate(hashes):c[row,h(key)]+=delta return c stream=[(0,3),(1,2),(4,5),(2,7),(7,1)] c=sketch(stream);truth=Counter() for key,delta in stream:truth[key]+=delta for key in range(10):ck(min(c[row,h(key)] for row,h in enumerate(hashes))>=truth[key],"nonnegative lower bound") ck(np.array_equal(c,sketch(stream[:2])+sketch(stream[2:])),"additive merge") ck(np.array_equal(sketch(stream+stream),2*c),"duplicate updates change counters") negative=sketch([(0,3),(4,-5)]) ck(min(negative[row,h(0)] for row,h in enumerate(hashes))<3,"signed frequency breaks nonunderestimate") finish(12,"Toy Count-Min insertion, merge and signed-stream counterexample",dict(positive_updates=stream,signed_estimate=int(negative[0,0]),true_frequency=3),"Fixed explicit hashes; no probabilistic hash guarantee or HyperLogLog implementation is claimed.",start) start=ASSERTIONS keys=[(i/1024)**2 for i in range(1025)] def local(a,q): pred=max(0,min(len(a),int((len(a)-1)*q))) lo=max(0,pred-4);hi=min(len(a),pred+5) return bisect_left(a,q,lo,hi) def validated(a,q): j=local(a,q) if (j>0 and a[j-1]>=q) or (jfreq[cache[0]]:cache.pop(0);cache.append(key) return hits warm=[0,1,2,3]*5;scan=list(range(100,120));tail=[0,1,2,3] lru=sum(cache_trace(warm+scan+tail)[-4:]);gate=sum(cache_trace(warm+scan+tail,True)[-4:]) ck(lru==0 and gate==4,"scan pollution witness") changed=cache_trace(warm+scan+[200,201,202,203]*20,True) ck(sum(changed[-4:])==4,"new frequent keys eventually admitted") finish(14,"LRU scan pollution and an exact-frequency admission toy",dict(post_scan_hits={"LRU":lru,"toy_gate":gate},new_hot_tail_hits=sum(changed[-4:])),"Exact unbounded counts and strict admission comparison; not an implementation of TinyLFU, ARC or LeCaR.",start) start=ASSERTIONS for n in range(1,9): p=.1 enumeration=sum(p**sum(v)*(1-p)**(n-sum(v)) for v in product([0,1],repeat=n) if any(v)) ck(math.isclose(enumeration,1-(1-p)**n,rel_tol=1e-12),"fanout probability") p100=1-.99**100;ck(math.isclose(p100,.6339676587267709),"100-branch tail") ck((1+.25)*.8==1,"queue stability boundary") finish(15,"Independent fan-out enumeration and an overload boundary",dict(hundred_branch_probability=p100,unstable_utilization=1.0),"Independent binary branch events and M/M/1 load accounting; no service trace.",start) start=ASSERTIONS;prime=101;coeff=[7,11,3] def f(x):return sum(c*pow(x,i,prime) for i,c in enumerate(coeff))%prime def interpolate(points,x): total=0 for i,(xi,yi) in enumerate(points): num=den=1 for j,(xj,yj) in enumerate(points): if i!=j:num=num*(x-xj)%prime;den=den*(xi-xj)%prime total=(total+yi*num*pow(den,-1,prime))%prime return total nodes=[(x,f(x)) for x in range(1,6)] for selected in combinations(nodes,3): for x in range(6):ck(interpolate(selected,x)==f(x),"three fragments reconstruct") def alternate(x):return (f(x)+(x-1)*(x-2))%prime ck(alternate(1)==f(1) and alternate(2)==f(2) and alternate(0)!=f(0),"two-fragment ambiguity") finish(16,"All ten three-of-five finite-field reconstructions",dict(field=prime,fragments=nodes,constant_terms=[f(0),alternate(0)]),"Tiny Reed-Solomon-style interpolation; no storage device, repair codec or durability estimate.",start) start=ASSERTIONS;C=1_000_000;q=0;trace=[] for rate in [1.5*C]*20+[.5*C]*20: q=max(0,q+(rate-C)*.0001);trace.append(q) ck(math.isclose(trace[19],1000),"burst queue mass") ck(math.isclose(trace[-1],0,abs_tol=1e-9),"queue drains") def jain(a):return sum(a)**2/(len(a)*sum(v*v for v in a)) for a in [[8,2],[1,1],[0,10],[1,2,3,4]]: v=jain(a);ck(1/len(a)<=v<=1,"Jain bounds") ck(math.isclose(v,jain(list(reversed(a)))) and math.isclose(v,jain([x*13 for x in a])),"Jain invariance") finish(17,"Fluid queue conservation and rate-equality invariants",dict(peak_bytes=max(trace),final_bytes=trace[-1],eight_two_Jain=jain([8,2])),"Piecewise fluid arrivals and equal-weight rate fairness; no transport protocol executed.",start) start=ASSERTIONS regular=[10]*100;bursty=[1]*90+[91]*10 ck(sum(regular)==sum(bursty)==1000,"same average gap") cold=lambda seq:sum(g>20 for g in seq)/len(seq) ck(cold(regular)==0 and cold(bursty)==.1,"different gap tails") finish(18,"Equal average arrival rates with different cold fractions",dict(mean_gap=10,timeout=20,regular_cold=cold(regular),bursty_cold=cold(bursty),Poisson_prediction=math.exp(-2)),"One environment, negligible service and declared interarrival gaps; initial arrival excluded.",start) start=ASSERTIONS pertoken=2*32*8*128*2 ck(pertoken==131072 and pertoken*4096==2**29,"KV accounting") lengths=[1,15,16,17,31,32];waste=sum(16*math.ceil(t/16)-t for t in lengths) ck(waste==32 and waste<=len(lengths)*15,"page tails") for B in [4,8,16,32,64]: mean=sum(B*math.ceil(t/B)-t for t in range(1,513))/512 ck(mean==(B-1)/2,"uniform tail average") def dense(Q,K,V): scores=Q@K.T/math.sqrt(Q.shape[1]);scores-=scores.max(axis=1,keepdims=True) P=np.exp(scores);P/=P.sum(axis=1,keepdims=True);return P@V def online(Q,K,V,block): out=[] for query in Q: m=-math.inf;l=0.;acc=np.zeros(V.shape[1]) for start in range(0,len(K),block): scores=K[start:start+block]@query/math.sqrt(Q.shape[1]);new=max(m,float(scores.max())) scale=math.exp(m-new);weights=np.exp(scores-new) acc=acc*scale+weights@V[start:start+block];l=l*scale+weights.sum();m=new out.append(acc/l) return np.array(out) rng=np.random.default_rng(20261022);Q=rng.normal(size=(7,4));K=rng.normal(size=(7,4));V=rng.normal(size=(7,3)) errors=[] for multiplier in [1,1000]: target=dense(Q*multiplier,K*multiplier,V) for block in [1,2,3,7]: actual=online(Q*multiplier,K*multiplier,V,block);err=float(np.max(np.abs(target-actual)));errors.append(err) ck(np.allclose(actual,target,atol=1e-12,rtol=1e-12),"online softmax versus dense") finish(19,"KV and page accounting plus online-softmax numerical comparison",dict(bytes_per_token=pertoken,page_tail_slots=waste,largest_absolute_error=max(errors),attention_cases=len(errors)),"Small binary64 NumPy arrays; not a FlashAttention GPU kernel, serving engine or throughput benchmark.",start) start=ASSERTIONS;variance=[] for R,J in [(2,3),(5,4),(10,2)]: covariance=np.eye(R*J)*100 for r in range(R):covariance[r*J:(r+1)*J,r*J:(r+1)*J]+=4 weights=np.ones(R*J)/(R*J);direct=float(weights@covariance@weights);formula=4/R+100/(R*J) ck(math.isclose(direct,formula,rel_tol=1e-12),"hierarchical covariance mean") variance.append(dict(runs=R,iterations=J,direct=direct,formula=formula)) A=[1,10];B=[2,12] ck(all(amixedB,"mixture reversal") def geom(a,b):return math.exp(sum(math.log(y/x) for x,y in zip(a,b))/len(a)) ck(math.isclose(geom(A,B),geom([x*1000 for x in A],[x*1000 for x in B])),"unit-invariant speedup") finish(20,"Covariance calculation, workload reversal and unit invariance",dict(variance=variance,unmatched_means=[mixedA,mixedB],matched_means=[sum(A)/2,sum(B)/2]),"Constructed statistics; no empirical confidence interval or product performance comparison.",start) if __name__=="__main__": run();assert len(RESULTS)==20 result=dict(status="PASS",groups=20,assertions=ASSERTIONS,results=RESULTS, scope="Finite models, mathematical counterexamples and deterministic numerical checks only; not independent peer review, product verification, or empirical system benchmarks.") (ROOT/"analysis/example-results.json").write_text(json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False)+"\n",encoding="utf-8") print(json.dumps({k:result[k] for k in ["status","groups","assertions"]}))