report.py

benches/crypto/private-los/report.py

report.py607 lines← Benchmarks
1#!/usr/bin/env python32"""Render private-LOS evidence without mutating measured sources or raw receipts.34Final mode requires the independent audit, both image roles, all actual rows5and unchanged 91-population regression. Preview mode visibly marks incomplete6qualification. Original raw inputs are required; compact archived snapshots are7not a substitute for the complete run directories.8"""9import argparse10import base6411from decimal import Decimal12import gzip13import hashlib14import json15import os16from pathlib import Path17import shutil1819PROGRAMS = ('los0', 'los4', 'los16', 'los64', 'equality8', 'selector256')20STAGES = ('randomness', 'garble', 'evaluate', 'serialize', 'parse')21FIELDS = ('raw_cost', 'whole_message_cost', 'postcheck_cost', 'page_fee_cost', 'prelude_cost')22FEATURES = {'aes-narrow', 'aes-simd', 'prg-simd', 'prg-xof4', 'prg-query-batch'}23PIC = '6a9a75ad9b4551d2b0f4a0d954ffb8bd5bbd0ebc44ac00290679b06ad0b2f8e6'24LABELS = {'los0':'LOS 0', 'los4':'LOS 4', 'los16':'LOS 16', 'los64':'LOS 64', 'equality8':'Equality8', 'selector256':'Synthetic selector'}252627def need(condition, message):28    if not condition:29        raise ValueError(message)303132def read(path):33    return json.loads(Path(path).read_text())343536def sha(path):37    return hashlib.sha256(Path(path).read_bytes()).hexdigest()383940def save(path, value):41    Path(path).write_text(json.dumps(value, indent=2) + '\n')424344def table(headers, rows):45    return ['| ' + ' | '.join(headers) + ' |', '| ' + ' | '.join('---' for _ in headers) + ' |',46            *('| ' + ' | '.join(map(str, row)) + ' |' for row in rows)]474849def fmt(value):50    return 'pending' if value is None else f'{Decimal(value):,.1f}'515253def per(row, field):54    if row is None or row.get(field) is None:55        return None56    return Decimal(row[field]) / row['batch']575859def median(values):60    a = sorted(map(int, values))61    return str(a[len(a)//2] if len(a)%2 else (a[len(a)//2-1]+a[len(a)//2])//2)626364def normalized_wall(w):65    return list(w) if isinstance(w, list) else [w[str(i)] for i in range(4)]666768def check_maps(catalog):69    need([p['name'] for p in catalog] == list(PROGRAMS), 'Different static programs')70    walls=[]71    for t in range(64):72        i=((t & 1)<<2)|((t & 4)>>1)|((t & 16)>>4)73        j=((t & 2)<<1)|((t & 8)>>2)|((t & 32)>>5)74        x,y=2*i+1,2*j+175        parity=(i ^ (i>>1) ^ (i>>2) ^ j ^ (j>>1) ^ (j>>2)) & 176        walls.append([x,y,x+(parity==0),y+(parity==1)])77    for p,n in zip(catalog[:4],(0,4,16,64)):78        actual=[normalized_wall(w) for w in p['walls']]79        need(actual == walls[:n], 'Measured map differs from reproducible prefix')80        need(len({tuple(w) for w in actual}) == n, 'Duplicate wall')81    need(len({p['suite_id'] for p in catalog}) == 6, 'Program framing identities overlap')82    need([(p['and_count'],p['xor_count'],p['and_depth']) for p in catalog] ==83         [(0,0,0),(276,533,18),(703,1234,20),(2265,3527,22),(7,8,3),(255,510,8)], 'Different compiled program')84    return {'position_encoding':'x=byte&15; y=byte>>4; centre=(2*x+1,2*y+1)',85            'walls_are':'closed integer-grid segments; endpoint touch blocks; identical positions visible',86            'prefix_counts':[0,4,16,64], 'walls_64':walls,87            'programs':[{**p,'walls':[normalized_wall(w) for w in p['walls']]} for p in catalog]}888990def draw_maps(path,maps):91    import matplotlib92    matplotlib.use('Agg')93    matplotlib.rcParams['svg.hashsalt']='private-los-map-v1'94    import matplotlib.pyplot as plt95    figure,axes=plt.subplots(1,4,figsize=(12,3.3),constrained_layout=True)96    for axis,n in zip(axes,(0,4,16,64)):97        axis.set_xlim(0,16);axis.set_ylim(0,16);axis.set_aspect('equal')98        axis.set_xticks((0,4,8,12,16));axis.set_yticks((0,4,8,12,16))99        axis.set_xticks(range(17),minor=True);axis.set_yticks(range(17),minor=True)100        axis.grid(which='both',color='#e3e8ed',linewidth=.5)101        for x1,y1,x2,y2 in maps['walls_64'][:n]:102            axis.plot((x1,x2),(y1,y2),color='#163c63',linewidth=2.4,103                      marker='o',markersize=2.5,zorder=3)104        axis.set_title(f'{n} public segments',fontsize=11)105        axis.tick_params(which='both',labelsize=8,length=0)106        for spine in axis.spines.values():spine.set_color('#c7ced5')107    figure.savefig(path,format='svg',metadata={'Date':None,'Creator':'private-los report generator'})108    plt.close(figure)109110111class Run:112    def __init__(self, path, preview=False, structural=False):113        self.path=Path(path)114        self.artifact=read(self.path/'artifact.json')115        self.host=read(self.path/'host-receipt.json')116        self.catalog=read(self.path/'catalog.json')117        self.checks=read(self.path/'correctness.json')118        self.maps=check_maps(self.catalog)119        need(read(self.path/'session/receipt.json')['binarySha256'] == PIC, 'Different PocketIC binary')120        need(set(self.artifact['features']) == FEATURES | ({'instrumentation'} if structural else set()), 'Different image feature set')121        need(self.checks['status'] == 'PASS' and self.checks['full_byte_records'] == 48, 'Full-byte target qualification incomplete')122        self.complete=(self.path/'results.json').exists()123        if self.complete:124            self.data=read(self.path/'results.json')125            need(self.data['status'] == 'PASS', 'Run did not pass')126            rows=self.data.get('rows',[])127            if structural:128                need(self.data['performance_rows'] == [], 'Counter image emitted cost rows')129        else:130            need(preview and not structural, 'Run not complete')131            rows=[json.loads(line) for line in (self.path/'rows.jsonl').read_text().splitlines()]132            self.data={'status':'PREVIEW','rows':rows}133        self.rows={}134        controls=[]135        blocked=[]136        for row in rows:137            if row['status'] == 'BLOCKED':138                blocked.append(row)139                need(all(row.get(k) is None for k in ('actual_ot_cost','raw_cost','whole_message_cost','generated_ot_count','check_ot_count','base_ot_count','sent_payload_bytes','received_payload_bytes','rounds')), 'Invented actual IC OT cost')140                continue141            need(row['status']=='MEASURED' and row['sample_count']==len(row['samples'])==2, 'Failed or different sample population')142            need(row['artifact_hash']==self.artifact['wasmSha256'], 'Mixed row artifact')143            need(set(row['artifact_features'])==set(self.artifact['features']), 'Mixed row features')144            for sample in row['samples']:145                need(sample['ok'] and sample['reply']['ok'] and sample['endpoint']['memoryDetailsAvailable'], 'Incomplete successful sample')146            for field,source in [('raw_cost',('reply','body_instructions')),('postcheck_cost',('reply','check_instructions')),('prelude_cost',('reply','prelude_instructions')),('whole_message_cost',('endpoint','instructions')),('page_fee_cost',('endpoint','pageAccessInstructions'))]:147                need(row[field]==median(s[source[0]][source[1]] for s in row['samples']), 'Changed sample median')148            if row['stage']=='empty-harness':149                controls.append(row)150            else:151                key=(row['program'],row['stage'],row['batch'])152                need(key not in self.rows, 'Duplicate population')153                self.rows[key]=row154        self.counts={'body_rows':len(self.rows),'harness_rows':len(controls),'blocked_rows':len(blocked),155                     'body_samples':sum(r['sample_count'] for r in self.rows.values())}156        if self.complete and not structural:157            need(self.counts=={'body_rows':90,'harness_rows':90,'blocked_rows':36,'body_samples':180}, 'Wrong primary matrix')158            need(set(self.rows)=={(p,s,n) for p in PROGRAMS for s in STAGES for n in (1,10,100)}, 'Different actual sizes')159        for key,row in self.rows.items():160            p=self.catalog[PROGRAMS.index(key[0])]161            need(row['suite_id']==p['suite_id'] and row['logical_ot_count']==p['live_bob_bits']*row['batch'], 'Changed circuit/OT metadata')162            for field in ('request_payload_bytes','reply_payload_bytes','request_framing_bytes','reply_framing_bytes'):163                need(row[field]==int(p[field])*row['batch'], 'Payload byte count differs from constructed program')164        for p in PROGRAMS:165            for n in (1,10,100):166                rows=[self.rows[p,s,n] for s in STAGES if (p,s,n) in self.rows]167                if rows:168                    need(all([q['reply']['checksums'] for q in row['samples']]==[q['reply']['checksums'] for q in rows[0]['samples']] for row in rows), 'Stage outputs differ')169170    def row(self,p,s,n=100):171        return self.rows.get((p,s,n))172173174def regression(path,baseline):175    current=read(Path(path)/'results.json')176    prior=read(baseline)177    need(current['status']=='PASS' and prior['status']=='PASS','GC regression incomplete')178    def rows(data):179        return {(r['benchmark'],r['batch'],r['prg_bytes']):r for r in data['rows'] if r['status']=='MEASURED' and not r['benchmark'].endswith('.empty-harness')}180    a,b=rows(current),rows(prior)181    need(a.keys()==b.keys() and len(a)==91,'Changed original GC matrix')182    for key,row in a.items():183        need(all(row[f]==b[key][f] for f in ('raw_cost','whole_message_cost','page_fee_cost')),'Changed original GC costs')184        need([s['reply']['checksums'] for s in row['samples']]==[s['reply']['checksums'] for s in b[key]['samples']],'Changed original GC output')185    return {'status':'PASS','actual_populations':91,'fields_identical':['raw_cost','whole_message_cost','page_fee_cost'],186            'artifact':read(Path(path)/'artifact.json'),'results_sha256':sha(Path(path)/'results.json'),'baseline_results_sha256':sha(baseline)}187188189def ot_reference(path):190    out=[]191    for label,n in [('chosen-8',8),('chosen-80',80),('chosen-800',800),('chosen-8000',8000),('base128',None),('noop',None)]:192        directory=Path(path)/label193        r=read(directory/'receipt.json')194        records=[json.loads(line) for line in (directory/'stdout.jsonl').read_text().splitlines()]195        need(r['passed'] and r['error'] is None and r['ic_instruction_count'] is None,'WASI OT reference failed or mislabeled')196        need(len(records)==1 and records[0]['ok'],'OT reference output check failed')197        if n is not None:need(records[0]['logical_ots']==n and r['selected_logical_count']==n,'Different OT reference population')198        else:need(r['selected_control']==label,'Different OT control')199        out.append({'label':label,'count':n,'receipt_sha256':sha(directory/'receipt.json'),'receipt':r,'record':records[0],200                    'scope':'Whole Wasmtime fuel; both parties cold setup/checks/stdout; no subtraction or IC conversion',201                    'qualification':'Independent audit plus receipted execution' if n in (8,80,800) else 'Additional receipted reproduction/control; outside initial three-cell independent audit'})202    return out203204205def verify_audit(path,primary,counter,native):206    a=read(path)207    need(a['status']=='PASS','Independent IC audit incomplete')208    need(a['primary']['results_sha256']==sha(primary.path/'results.json'),'Audit references different primary result')209    for key in ('wasm_sha256','manifest_sha256'):210        name={'wasm_sha256':'wasmSha256','manifest_sha256':'manifestSha256'}[key]211        need(a['primary']['artifact'][key]==primary.artifact[name], 'Primary audit artifact differs')212        need(a['structural']['artifact'][key]==counter.artifact[name], 'Structural audit artifact differs')213    need(a['structural']['role']=='instrumented-correctness-only' and a['structural']['performance_rows']==0,'Wrong counter audit role')214    need(a['native']['reference_sha256']==sha(native),'Native audit reference differs')215    need(a['native']['independent_full_byte_records']==48 and a['native']['independent_full_bytes_compared']==943360,'Independent byte proof incomplete')216    need(a['primary']['traces']['trace_count']==770 and a['structural']['traces']['trace_count']==48,'Incomplete trace populations')217    return a218219220def link(path,output):221    return os.path.relpath(path,Path(output).parent).replace(os.sep,'/')222223224def selector_comparison(primary,n=100):225    data={'actual_n':n,'reference':'synthetic-selector256; LOS preprocessing unmeasured','programs':{}}226    for name in ('los4','los16','los64'):227        data['programs'][name]={}228        for stage in ('garble','evaluate'):229            row=primary.row(name,stage,n);reference=primary.row('selector256',stage,n)230            if row is None or reference is None:return None231            ratio=Decimal(row['raw_cost'])/Decimal(reference['raw_cost'])232            data['programs'][name][stage]={'numerator':row['raw_cost'],'denominator':reference['raw_cost'],233                'ratio':str(ratio),'percent_higher':str((ratio-1)*100)}234    four=primary.row('los4','randomness',n);selector=primary.row('selector256','randomness',n)235    if four is None or selector is None:return None236    data['four_wall_randomness_body']={'numerator':four['raw_cost'],'denominator':str(n)}237    data['selector_randomness_body']={'numerator':selector['raw_cost'],'denominator':str(n)}238    for name in ('los4','selector256'):239        p=primary.catalog[PROGRAMS.index(name)]240        data['programs'].setdefault(name,{})['request_payload_bytes']=int(p['request_payload_bytes'])241        data['programs'][name]['random_material_bytes']=16*(1+p['live_alice_bits']+p['live_bob_bits']+int(p['needs_constant']))242    return data243244245def evidence_index(args,primary,counter,audit,comparison=None):246    root=args.curate247    output=root/'README.md'248    dated=args.report or Path('research/crypto/benchmarks/2026-10-31-private-los.md')249    initial_data=' and [initial results](initial-baseline/selected-results/results.json.gz)' if comparison else ''250    initial_audit=', [initial audit](review/actual-audit.json)' if comparison else ''251    initial_counter=' and [initial counter proof](initial-baseline/counter-checks/correctness.json.gz)' if comparison else ''252    return '\n'.join([253        '# Private LOS evidence index','',254        'The [dated report]('+link(dated,output)+') owns the measurement tables and conclusions. '255        'This archive retains the selected shared-workspace run, the initial per-query-workspace baseline, independent proofs and separate reference controls.','',256        '- [Exact costs and comparison numerators](cost-summary.json); [selected results](selected-results/results.json.gz)'+initial_data+'.',257        '- [Map endpoints and program contracts](maps.json), [map drawing](maps.svg) and [generated circuit](source/generated/programs.rs).',258        '- [Selected independent audit](review/'+args.audit.name+')'+initial_audit+', [geometry/source review](review/independent-review.md) and [publication checks](publication-checks.json).',259        '- [Selected counter proof](counter-checks/correctness.json.gz)'+initial_counter+'; counter images supply no performance rows.',260        '- [Original 91-case execution repeat](algorithm-regression/results.json.gz); [separate WASI OT receipts](ot-reference-repeat/) and [exact reproduction module](ot-reference-repeat/reproduction.wasm.gz).',261        '- [Native-reference receipt](native-reference-receipt.json), [original/selected binary mappings](native/binary-mappings.json) and [frozen compiler proof](compiler.md).',262        '- [Measured source snapshots](source/measured/), [host snapshot](source/host/), [complete source hash index](source/source-archive-index.json.gz) and [debug/source path index](source/debug-sources-index.json.gz).',263        '- [Full trace hash indexes](all-trace-hashes.json.gz), representative captures under each run directory and [retained-file hashes](file-index.json).',264        '- [Frozen report and curation generator](report_private_los.py).','',265        'Selected primary/counter qualification covers 90 actual N1/10/100 populations and 818 complete traces. '266        'Actual IC OT and the full private protocol remain blocked. WASI fuel covers the standalone reference fixture and is never translated into IC instructions or combined with circuit stages.','',267        'This is a compact, partial repository reproduction snapshot. Full SDK/debug/source archives and most raw captures remain at `'+str(args.run.resolve())+'`; the indexes retain their exact hashes and original paths. '268        'Replaying complete raw audits requires those local originals. Rebuilding elsewhere requires the pinned SDK/compiler/dependencies and fresh canonical artifacts. '269        'The compact snapshots do not form a standalone full build closure, and recorded absolute paths are historical mappings, not fresh build receipts.','',270        'Current guide changes postdate measurement. Native/reference generation, canonical builds and host-runner commands were qualified separately; no new end-to-end packaging-script execution is claimed.',''])271272273def render(args,primary,counter,audit,reg,ot,output=None,comparison=None):274    output=output or args.out/'private-los-report.md'275    src=args.run276    def evidence(raw):277        raw=Path(raw)278        if not args.curate:279            return raw280        if raw==args.native:return args.curate/'native-reference.json.gz'281        if raw==args.native_receipt:return args.curate/'native-reference-receipt.json'282        mappings=[(primary.path,Path('selected-results')),(args.audit.parent,Path('review'))]283        if counter:mappings.append((counter.path,Path('counter-checks')))284        if args.comparison:mappings.append((args.comparison,Path('initial-baseline/selected-results')))285        mappings.append((args.run,Path()))286        target=None287        for source,prefix in mappings:288            try:target=args.curate/prefix/raw.relative_to(source);break289            except ValueError:pass290        if target is None:return raw291        if target.exists():292            return target293        if target.with_name(target.name+'.gz').exists():294            return target.with_name(target.name+'.gz')295        return raw296    data_root=args.curate if args.curate else args.out297    lines=['# Private two-dimensional LOS — static circuit costs','',f'Fixture: {args.label}.','']298    if args.preview:299        lines+=['PREVIEW — qualification is incomplete; pending cells are unmeasured. This is a scratch draft, not a published result.','']300    los64g=primary.row('los64','garble');los64e=primary.row('los64','evaluate')301    lines+=[f"The four public maps compile to 0/276/703/2,265 ANDs. At actual N100, the 64-wall circuit uses {fmt(per(los64g,'raw_cost'))} garbling and {fmt(per(los64e,'raw_cost'))} evaluation body instructions per query. "302            'These are separate circuit stages through one generic runtime; actual IC OT and the full private protocol remain blocked.', '',303            'Cost tables use actual IC instructions per query, obtained by dividing the measured cohort by its actual N. N1 is a separate measurement; N10 and N100 are actual bulk cohorts. '304            'Each body and independent empty harness has two freshly reconstructed deterministic samples. Values are rounded to 0.1; exact integer numerators, denominators and every sample remain in '305            f'[cost-summary.json]({link(data_root/"cost-summary.json",output)}) and raw results. No harness subtraction, component-summed total, page-fee addition or extrapolation is used. N1000 was not measured.', '',306            'Position bits 0..3 encode x and 4..7 encode y. Tile centres are (2x+1,2y+1); wall vertices are doubled integer grid points. Walls are closed, endpoint touch blocks, and identical positions are visible. '307            'The maps contain exact 0/4/16/64 prefixes of one nonduplicate distributed unit-segment set. [maps.json]('+link(data_root/'maps.json',output)+') preserves every endpoint and program descriptor.', '']308    lines += ['![Exact public wall maps]('+link(data_root/'maps.svg',output)+')', '', 'Coordinate axes and pale grid lines are guides; only dark segments are walls.', '']309    measured=selector_comparison(primary)310    if measured:311        p=measured['programs'];g=lambda name:Decimal(p[name]['garble']['ratio']);e=lambda name:Decimal(p[name]['evaluate']['ratio'])312        higher=lambda name,stage:f"{Decimal(p[name][stage]['percent_higher']):.2f}%"313        four_random=Decimal(measured['four_wall_randomness_body']['numerator'])/measured['actual_n']314        selector_random=Decimal(measured['selector_randomness_body']['numerator'])/measured['actual_n']315        lines += [f"At actual N100, the four-wall direct circuit has nearly the selector's gate-stage cost: garbling is {higher('los4','garble')} higher and evaluation {higher('los4','evaluate')} higher. "316            f"The 16-/64-wall circuits use {g('los16'):.2f}×/{g('los64'):.2f}× its garbling body and {e('los16'):.2f}×/{e('los64'):.2f}× its evaluation body. "317            f"Direct four-wall LOS needs {p['los4']['request_payload_bytes']:,} rather than {p['selector256']['request_payload_bytes']:,} request payload bytes and {fmt(four_random)} rather than {fmt(selector_random)} measured randomness body instructions per query "318            f"({p['los4']['random_material_bytes']:,} versus {p['selector256']['random_material_bytes']:,} PRG material bytes). "319            'Thus the four-wall circuit is close in garble/evaluate cost with smaller requests and randomness work; larger maps require substantially more gate work. '320            'The selector excludes LOS preprocessing and is only an arbitrary-input comparator. These stage measurements establish no overall protocol winner.','']321    lines+=table(['Program','Walls','AND','XOR','AND depth','Declared A/B','Live A/B'],[322        [LABELS[p['name']],len(p['walls']),f"{p['and_count']:,}",f"{p['xor_count']:,}",p['and_depth'],f"{p['alice_bits']}/{p['bob_bits']}",f"{p['live_alice_bits']}/{p['live_bob_bits']}"] for p in primary.catalog])323    lines+=['','The empty map folds to constant true: zero gates and zero logical OT, with one random active false-wire label whose output meaning is complemented. This does not expose the delta. '324            'Equality8 and the 255-AND/510-XOR selector use the identical generic runtime. The selector receives arbitrary synthetic 256-bit Alice data; it is not a LOS implementation, does not construct a visibility mask, and excludes preprocessing.','',325            'Payloads are exact constructed circuit adapter bytes per query. The request contains live Alice labels, optional constant label and 32 bytes per AND. The reply is one 16-byte label. '326            'Each direction adds an actual 84-byte header. No party transport is executed; sent/received network bytes and rounds stay null.','']327    lines+=table(['Program','Request payload','Request frame','Reply payload/frame','Logical OT N1/N10/N100'],[328        [LABELS[p['name']],f"{int(p['request_payload_bytes']):,}",f"{int(p['request_payload_bytes'])+84:,}",'16 / 100',f"{p['live_bob_bits']} / {10*p['live_bob_bits']} / {100*p['live_bob_bits']}"] for p in primary.catalog])329    lines+=['','All programs declare eight Bob bits. Only the empty map has zero live Bob inputs. Actual OT cost, generated/check/base OT counts and private-protocol communication are null, including when logical OT is zero. '330            'A distinct BLAKE3 application descriptor binds each exact program, map, liveness and positional request contract in the unchanged header; the underlying GC construction suite remains separate.','',331            'Inputs, output buffers, workspaces, AES schedules, shared session prefix and public descriptor preparation precede body timers. Randomness measures per-query stream construction and actual fill into prepared material. '332            'Garbling consumes previously filled material and includes scratch wiping. Evaluation uses staged garblings and fixture-only locally selected Bob labels, without OT. Serialization writes both actual frames; parsing borrows both frames and validates routes and lengths.','',333            'Postcheck costs depend on the staged phase: they complete remaining stages, evaluate the parsed frame, check complete returned-label bytes, decode through Alice and run independent ordinary i64 geometry. '334            'They are neither a pure Alice/Bob phase nor a second protocol. Whole checked-update costs include wrappers, postchecks, reply serialization and page fees. Page columns are already included in whole; Counter 0 also includes any charges between its probes. '335            'Whole costs below belong to these checked fixture endpoints, not the full private protocol.','']336    if comparison:337        lines += ['The selected sequential fixture reuses one cleared Alice workspace and one cleared Bob workspace for the cohort. Every query still retains fresh material, its own private output map, garbling and output buffers. The initial fixture retained two workspaces per query. Circuit gates, fresh query domains, bytes, outputs and logical work are identical; differences include scratch layout and actual page admissions.', '',338                  'Matched initial → selected fixture, actual N100:', '']339        values=[]340        for p in PROGRAMS:341            for stage in ('garble','evaluate'):342                before=comparison.row(p,stage);after=primary.row(p,stage)343                pair=lambda f:fmt(per(before,f))+' → '+fmt(per(after,f))344                values.append([LABELS[p],stage,pair('raw_cost'),pair('whole_message_cost'),pair('page_fee_cost')])345        lines += table(['Program','Stage','Body/query','Whole/query','Page/query'],values)+['',346            'Observed committed capacity after each actual N100 garble call (initial → selected):', '']347        lines += table(['Program','Committed 64KiB pages','Committed capacity bytes'],[348            [LABELS[p],str(comparison.row(p,'garble')['wasm_pages'])+' → '+str(primary.row(p,'garble')['wasm_pages']),349             f"{int(comparison.row(p,'garble')['heap_capacity_bytes']):,} → {int(primary.row(p,'garble')['heap_capacity_bytes']):,}"] for p in PROGRAMS])+['',350            'These are page-authority committed capacities observed outside timing, including preceding allocations and runtime/Store/control ownership. They are not peak live heap. The reuse improvement changes scratch allocation/layout and page admission; it does not introduce a new gate kernel.', '']351    titles={'randomness':'Fresh query randomness','garble':'Garbling from prepared material','evaluate':'Evaluation from prepared garbling','serialize':'Serialize request and reply frames','parse':'Parse request and reply frames'}352    for stage in STAGES:353        lines+=[titles[stage]+':','']354        values=[]355        for p in PROGRAMS:356            for n in (1,10,100):357                row=primary.row(p,stage,n)358                values.append([LABELS[p],n,*(fmt(per(row,f)) for f in FIELDS)])359        lines+=table(['Program','Actual N','Body/query','Whole/query','Postcheck/query','Page/query','Prelude/query'],values)+['']360    lines+=['The same-runtime Equality8 rows above are the phase comparison. The retained specialized Equality8 reference reports 65,817.3 garble and 29,043.1 evaluate body instructions per query at actual N1000. '361            'That older garble body includes fresh per-query PRG construction/fill; this garble phase uses staged RandomMaterial. The specialized evaluator also uses a different fixed circuit adapter. '362            'Those older values are source-scope context, not a matched direct speed ratio or a combined LOS cost.','',363            'Qualification: native tests pass six runtime tests, eight independent integration tests including all 262,144 plaintext position pairs across the four maps, and three benchmark tests. '364            'The optimized installed image checks all 48 complete request/reply frame records against portable native bytes and independent geometry. A separate instrumented image checks exact compiled gates and four Alice/two Bob hashes per AND; it produces no performance rows. '365            'The ordinary native/target differential shares runtime source. The independent audit separately reconstructs all 48 records (943,360 bytes) with Python integer Half-Gates, OpenSSL AES and Node noble BLAKE3. It reconciles 770 primary and 48 counter traces. The optional narrow AES constant-time claim retains its supported-engine hardware register-swizzle assumption; no universal-host timing guarantee is added.','']366    if audit:367        lines+=['The [independent actual-IC audit]('+link(evidence(args.audit),output)+') passes for the exact primary/counter images and native-reference hashes. The only sample difference is 45 whole-update instructions when a fixture-ID Wire varint grows by one byte; bodies, postchecks, preludes and page fees remain identical.','']368    elif args.preview:369        lines+=['Independent primary/counter audit: pending.','']370    if reg:371        lines+=['The original 91-population GC matrix was rerun using its unchanged prepared artifact. All outputs and raw-body/whole/page cost fields match the frozen baseline exactly. '372                'This is a fresh execution regression, not a rebuild of a different original benchmark.','']373    if ot:374        lines+=['The pinned malicious-OT reference was also repeated at actual 8/80/800/8000 logical OTs, plus separate base128 and no-op controls, under wasm32 WASI. These are Wasmtime fuel for the entire standalone fixture, including setup, tests, output checks and stdout. '375                'Fuel includes both parties cold setup and checks; it is not IC instructions and is never subtracted or added to these circuit-stage costs. All six runs pass; IC integration remains blocked. The repeated WASI module has SHA256 `61025a9915de9e562bb269d028970a461c74513fba1143ed93a8aae429dd0f9f`; this is a fresh reproduction, distinct from the original `a47b57b2` module and its frozen fuel receipts.','']376        values=[]377        for r in ot:378            record=r['record']379            transport=record.get('total_transport_bytes',record.get('transport_bytes'))380            mask=record.get('chosen_mask_payload_bytes')381            values.append([r['label'],f"{r['receipt']['wasmtime_fuel_consumed']:,}",f"{transport:,}" if transport is not None else 'unreported',382                f"{mask:,}" if mask is not None else 'unreported',str(record.get('base_ots','—'))+' / '+str(record.get('internal_ots','—'))])383        lines+=table(['Standalone population','Whole WASI fuel','Fixture transport bytes','Chosen-mask payload','Base/internal OTs'],values)+['',384            'The original audit covered chosen 8/80/800; the selected-run audit also checks all six receipts separately. Chosen 8000, base128 and noop are additive WASI reproductions/controls and do not qualify an IC OT adapter.','']385    manifest=read(primary.artifact['manifestPath'])386    wasm=next(r for r in manifest['outputs'] if r['path'].endswith('.wasm') and not r['path'].endswith('.raw.wasm'))387    lines+=['Frozen image identity:','']388    lines+=table(['Image','Prepared Wasm SHA256','Bytes','Features'],[389        ['Primary',f"`{primary.artifact['wasmSha256']}`",f"{wasm['bytes']:,}",', '.join(primary.artifact['features'])],390        *([['Counter',f"`{counter.artifact['wasmSha256']}`",'separate image',', '.join(counter.artifact['features'])]] if counter else [])])+['',391        f"SDK `{primary.host['source']['sdk_commit']}`; factory parent `{primary.host['source']['factory_commit']}`. Exact archived source receipts identify local additions beyond the parent commit. "392        f"PocketIC normal13 SHA256 `{PIC}`. The primary image has no instrumentation. Host invocation durations are diagnostics; runtime wall median/p95, peak live heap, IC OT costs and network metrics remain unmeasured. "393        'Out-of-window committed page capacity is not peak live heap.','',394        'The curated archive retains all results, byte proofs, exact introduced-source/generated-circuit snapshots, prepared modules, representative captures and full trace/source hash indexes. Raw evidence remains at `'+str(src.resolve())+'`, with complete canonical artifacts/source archives, native-reference receipts, setup/body/control/noop traces, cycle snapshots and owned-session receipts. '395        'Canonical receipt absolute paths preserve their original build meaning; curation does not reinterpret them as fresh builds. '+396        ('[Native binary mappings]('+link(data_root/'native/binary-mappings.json',output)+') distinguish the saved original binary from the later binary at its reused absolute path.'397         if args.curate else 'The native receipt identifies the selected reference binary; this report-only replay creates no binary archive.'),'',398        'This is a partial repository reproduction snapshot: full SDK/debug/source archives and most raw captures remain local at the indexed original paths. Compact source snapshots are not a standalone full build closure. Replaying those complete raw audits requires the local originals; rebuilding elsewhere requires the pinned SDK/compiler/dependencies and fresh canonical artifacts. Current API/documentation edits postdate measurement and do not constitute a rerun of an end-to-end packaging script.', '',399        'Evidence: [primary results]('+link(evidence(primary.path/'results.json'),output)+'), [catalog]('+link(evidence(primary.path/'catalog.json'),output)+'), [correctness]('+link(evidence(primary.path/'correctness.json'),output)+'), '400        '[native receipt]('+link(evidence(args.native_receipt),output)+'), [source review]('+link(evidence(src/'review/independent-review.md'),output)+').','']401    return '\n'.join(lines)402403404def curate(args,primary,counter,comparison=None):405    dest=args.curate406    need(not dest.exists(),'Curation directory must be fresh')407    dest.mkdir(parents=True)408    index=[]409    def keep_bytes(data,target,source=None,encoding=None,original_sha=None):410        target=dest/target;target.parent.mkdir(parents=True,exist_ok=True)411        need(not target.exists(),'Repeated curated file: '+str(target))412        target.write_bytes(data)413        entry={'source':str(source.resolve()) if source else None,'target':str(target.relative_to(dest)),414               'bytes':len(data),'sha256':sha(target)}415        if encoding:entry.update(encoding=encoding,uncompressed_sha256=original_sha)416        index.append(entry)417    def copy(source,target):keep_bytes(source.read_bytes(),target,source)418    def compressed(source,target):419        keep_bytes(gzip.compress(source.read_bytes(),mtime=0),target,source,'gzip; original bytes unchanged',sha(source))420    def compact_json(value,target):421        raw=(json.dumps(value,indent=2)+'\n').encode()422        keep_bytes(gzip.compress(raw,mtime=0),target,encoding='gzip; generated index',original_sha=hashlib.sha256(raw).hexdigest())423    selected_captures={424        'los0-garble-n1-s0-body','los4-garble-n100-s0-body','los16-garble-n100-s0-body',425        'los64-randomness-n100-s0-body','los64-garble-n100-s0-body','los64-evaluate-n100-s0-body',426        'los64-serialize-n100-s0-body','los64-parse-n100-s0-body',427        'equality8-garble-n100-s0-body','equality8-evaluate-n100-s0-body',428        'selector256-garble-n100-s0-body','selector256-evaluate-n100-s0-body',429        'los64-garble-n100-s0-harness','los64-garble-n100-s0-body-setup',430        'byte-probe-24','byte-probe-25','noop-s0'}431    all_hashes={}432    original_counter=Run(args.run/'counter-checks',structural=True) if comparison else None433    run_inputs=[('selected-results',primary.path,selected_captures),434            ('counter-checks',counter.path,{'byte-probe-24','byte-probe-25'}),435            ('algorithm-regression',args.run/'algorithm-regression',{'g045-s0-body','g045-s0-body-setup','g049-s0-body'})]436    if comparison:437        run_inputs.append(('initial-baseline/selected-results',comparison.path,{'los64-garble-n100-s0-body','los64-evaluate-n100-s0-body'}))438        run_inputs.append(('initial-baseline/counter-checks',original_counter.path,{'byte-probe-24'}))439    for label,run_path,captures in run_inputs:440        hashes=[]441        for source in sorted(run_path.rglob('*')):442            if not source.is_file() or '.generated' in source.parts or source.name=='pocket-ic':continue443            rel=source.relative_to(run_path)444            if rel.parts[0]=='traces':445                hashes.append({'path':str(rel),'bytes':source.stat().st_size,'sha256':sha(source)})446                if rel.parts[1] not in captures:continue447            if source.suffix in ('.json','.jsonl','.csv') and source.stat().st_size>200000:448                compressed(source,Path(label)/(str(rel)+'.gz'))449            else:copy(source,Path(label)/rel)450        all_hashes[label]={'raw_directory':str(run_path.resolve()),'files':hashes,451                           'trace_count':sum(row['path'].endswith('/trace.json.gz') for row in hashes)}452    compact_json(all_hashes,'all-trace-hashes.json.gz')453    artifact_inputs=[('selected-artifact',primary.artifact),('counter-artifact',counter.artifact)]454    if comparison:455        artifact_inputs.append(('initial-baseline/selected-artifact',comparison.artifact))456        artifact_inputs.append(('initial-baseline/counter-artifact',original_counter.artifact))457    for label,artifact in artifact_inputs:458        directory=Path(artifact['manifestPath']).parent459        for source in sorted(directory.iterdir()):460            if not source.is_file() or source.name.endswith(('.raw.wasm','.stripped.raw.wasm','.wasm-tool','.source-before.json','.source-archive.json.gz','.debug-sources.json.gz')):continue461            if source.suffix in ('.json','.mjs','.mts','.ts','.txt','.wasm','.gz') or source.name.endswith('SHA256SUMS'):462                if source.stat().st_size>200000 and source.suffix=='.json':compressed(source,Path(label)/(source.name+'.gz'))463                else:copy(source,Path(label)/source.name)464    # Keep the exact small source closure introduced by this task, and full465    # source hash indexes. Full SDK/debug archives remain at their recorded raw466    # paths instead of duplicating roughly 180 MiB of existing dependencies.467    artifact_dir=Path(primary.artifact['manifestPath']).parent468    stem=Path(primary.artifact['manifestPath']).name.removesuffix('.manifest.json')469    for suffix in ('source-archive','debug-sources'):470        archive_path=artifact_dir/(stem+'.'+suffix+'.json.gz')471        archive=json.loads(gzip.decompress(archive_path.read_bytes()))472        records=archive['files']473        compact_json({'original_archive':str(archive_path.resolve()),'archive_sha256':sha(archive_path),474            'files':[{k:v for k,v in record.items() if k!='contents_base64'} for record in records]},475            'source/'+suffix+'-index.json.gz')476        for record in records:477            path=record['path']478            wanted=(suffix=='source-archive' and (path.startswith('crypto/algo/private-los/') or path.startswith('crypto/bench/private-los/') or path in ('crypto/Cargo.toml','crypto/Cargo.lock')))479            generated=(suffix=='debug-sources' and path.endswith('/out/programs.rs') and '/cdk-rsx-crypto-private-los/' in path)480            if not wanted and not generated:continue481            data=base64.b64decode(record['contents_base64'])482            need(len(data)==record['bytes'] and hashlib.sha256(data).hexdigest()==record['sha256'],'Invalid source archive record')483            target=Path('source/generated/programs.rs') if generated else Path('source/measured')/path484            keep_bytes(data,target,source=archive_path)485    if comparison:486        original=Path(comparison.artifact['manifestPath'])487        archive_path=original.with_name(original.name.removesuffix('.manifest.json')+'.source-archive.json.gz')488        archive=json.loads(gzip.decompress(archive_path.read_bytes()))489        record=next(row for row in archive['files'] if row['path']=='crypto/bench/private-los/canister/src/fixture.rs')490        data=base64.b64decode(record['contents_base64'])491        need(hashlib.sha256(data).hexdigest()==record['sha256'],'Initial fixture source snapshot differs')492        keep_bytes(data,'initial-baseline/source/fixture.rs',source=archive_path)493        if args.comparison_audit:494            prior=read(args.comparison_audit)495            need(prior['status']=='PASS' and prior['primary']['results_sha256']==sha(comparison.path/'results.json'),'Wrong initial independent audit')496            copy(args.comparison_audit,'initial-baseline/review/actual-audit.json')497    for record in primary.host['source']['files']:498499        source=Path(record['path'])500        need(sha(source)==record['sha256'],'Measured host source changed before curation: '+str(source))501        copy(source,Path('source/host')/source.relative_to(args.run.resolve().parents[1]))502    for source,name in [(args.native,'native-reference.json'),(args.native_receipt,'native-reference-receipt.json'),*[(args.run/name,name) for name in ('compiler.md','runtime.md','bench.md')]]:503        if source.stat().st_size>200000:compressed(source,name+'.gz')504        else:copy(source,name)505    for source in sorted(args.run.glob('*.log')):copy(source,Path('logs')/source.name)506    for root,label in [(args.audit.parent,'review'),(args.run/'ot-reference-repeat','ot-reference-repeat')]:507        for source in sorted(root.rglob('*')):508            if source.is_file() and '__pycache__' not in source.parts:copy(source,Path(label)/source.relative_to(root))509    for name in ('independent-review.md','arithmetic-bounds.json'):510        if not (dest/'review'/name).exists():copy(args.run/'review'/name,Path('review')/name)511    if primary.path.parent != args.run:512        for source in sorted(primary.path.parent.glob('*.log')):copy(source,Path('chosen-logs')/source.name)513    old=read(args.run/'algorithm-regression/artifact.json')514    copy(Path(old['wasmPath']),'algorithm-artifact/original-gc-prepared.wasm')515    if args.ot_wasm:516        expected=read(args.run/'ot-reference-repeat/chosen-8/receipt.json')['wasm_sha256']517        need(sha(args.ot_wasm)==expected,'Different WASI OT reproduction module')518        compressed(args.ot_wasm,'ot-reference-repeat/reproduction.wasm.gz')519    binaries=[]520    current=read(args.native_receipt)521    binary=Path(current['binary'])522    need(sha(binary)==current['binary_sha256'],'Selected native reference binary changed')523    compressed(binary,'native/selected-reference-binary.gz')524    binaries.append({'role':'selected','declared_receipt_binary_path':str(binary),525        'binary_sha256':current['binary_sha256'],'stored':'native/selected-reference-binary.gz'})526    if comparison:527        receipt=args.run/'native-reference-receipt.json'528        original=read(receipt)529        preserved=args.run/'original-native-reference-binary.gz'530        need(hashlib.sha256(gzip.decompress(preserved.read_bytes())).hexdigest()==original['binary_sha256'],'Preserved initial native binary differs')531        copy(receipt,'initial-baseline/native-reference-receipt.json')532        copy(preserved,'native/original-reference-binary.gz')533        binaries.append({'role':'initial','declared_receipt_binary_path':original['binary'],534            'binary_sha256':original['binary_sha256'],'stored':'native/original-reference-binary.gz',535            'mapping':'Original absolute binary path was subsequently reused; preserved gzip bytes independently restore the original receipt hash.'})536    keep_bytes((json.dumps({'reference_json_sha256':sha(args.native),'binary_mappings':binaries},indent=2)+'\n').encode(),'native/binary-mappings.json')537    for name in ['maps.json','maps.svg','cost-summary.json']:copy(args.out/name,name)538    copy(Path(__file__),'report_private_los.py')539    save(dest/'file-index.json',{'schema':'private-los-curated-evidence-v1','raw_root':str(args.run.resolve()),540        'scope':'Exact compact source/data/independent models/prepared modules and representative captures. Full original trace/source archives stay at their recorded raw paths; complete indexes preserve every hash.',541        'files':index})542543544def main():545    parser=argparse.ArgumentParser(description=__doc__)546    parser.add_argument('--run',type=Path,default=Path('playground/private-los-20261031'))547    parser.add_argument('--primary',type=Path)548    parser.add_argument('--native',type=Path)549    parser.add_argument('--native-receipt',type=Path)550    parser.add_argument('--label',default='initial independent query workspaces')551    parser.add_argument('--comparison',type=Path,help='Complete matched initial fixture result directory')552    parser.add_argument('--comparison-audit',type=Path)553    parser.add_argument('--out',type=Path,required=True)554    parser.add_argument('--audit',type=Path)555    parser.add_argument('--counter',type=Path)556    parser.add_argument('--gc-baseline',type=Path,default=Path('playground/gc-20261031/round5-four-aes-001/selected-results/results.json'))557    parser.add_argument('--preview',action='store_true')558    parser.add_argument('--curate',type=Path)559    parser.add_argument('--report',type=Path,help='Explicit final report destination; requires --curate and full qualification')560    parser.add_argument('--ot-wasm',type=Path)561    args=parser.parse_args()562    if args.audit is None:args.audit=args.run/'review/actual-audit.json'563    if args.counter is None:args.counter=args.run/'counter-checks'564    primary=Run(args.primary or args.run/'selected-results',args.preview)565    if args.native is None:args.native=primary.path.parent/'native-reference.json'566    if args.native_receipt is None:args.native_receipt=primary.path.parent/'native-reference-receipt.json'567    comparison=Run(args.comparison) if args.comparison else None568    if comparison:569        need(primary.maps==comparison.maps,'Workspace comparison changed program/map contracts')570        need(primary.rows.keys()<=comparison.rows.keys() if args.preview else primary.rows.keys()==comparison.rows.keys(),'Workspace comparison changed populations')571        for key,row in primary.rows.items():572            need([s['reply']['checksums'] for s in row['samples']]==[s['reply']['checksums'] for s in comparison.rows[key]['samples']],'Workspace comparison changed output bytes')573    counter=Run(args.counter,structural=True) if (args.counter/'results.json').exists() else None574    if not args.preview:need(counter is not None,'Structural image not qualified')575    audit=verify_audit(args.audit,primary,counter,args.native) if args.audit.exists() and counter and primary.complete else None576    if not args.preview:need(audit is not None,'Independent actual-IC audit required')577    reg=regression(args.run/'algorithm-regression',args.gc_baseline)578    ot=ot_reference(args.run/'ot-reference-repeat')579    args.out.mkdir(parents=True,exist_ok=False)580    save(args.out/'maps.json',primary.maps)581    draw_maps(args.out/'maps.svg',primary.maps)582    costs=[{'program':p,'stage':s,'actual_n':n,'denominator':str(n),'status':r['status'],583            **{f:r[f] for f in FIELDS},'harness_cost':r['harness_cost'],'adjusted_cost':r['adjusted_cost'],584            'suite_id':r['suite_id'],'logical_ot_count':r['logical_ot_count'],585            **{f:r[f] for f in ('request_payload_bytes','reply_payload_bytes','request_framing_bytes','reply_framing_bytes')},586            'endpoint_wire_bytes':[{'request':a['endpoint_wire_request_bytes'],'reply':a['endpoint_wire_reply_bytes']} for a in r['samples']]}587           for (p,s,n),r in primary.rows.items()]588    save(args.out/'cost-summary.json',{'schema':'private-los-cost-summary-v1','status':'PREVIEW' if args.preview else 'PASS',589        'primary_artifact':primary.artifact,'counter_artifact':counter.artifact if counter else None,590        'counts':primary.counts,'inputs':{'primary_results_sha256':sha(primary.path/'results.json') if primary.complete else None,591        'audit_sha256':sha(args.audit) if audit else None,'native_reference_sha256':sha(args.native)},592        'costs':costs,'regression':reg,'ot_reference':ot,'selector_comparison':selector_comparison(primary),593        'comparison':{'artifact':comparison.artifact,'costs':[{594            'program':p,'stage':s,'actual_n':n,**{f:r[f] for f in FIELDS}} for (p,s,n),r in comparison.rows.items()]} if comparison else None})595    (args.out/'private-los-report.md').write_text(render(args,primary,counter,audit,reg,ot,comparison=comparison))596    if args.curate:597        need(not args.preview and audit,'Only fully qualified evidence may be curated')598        curate(args,primary,counter,comparison)599        (args.curate/'README.md').write_text(evidence_index(args,primary,counter,audit,comparison))600    if args.report:601        need(not args.preview and args.curate,'Final report requires fully qualified curation')602        args.report.parent.mkdir(parents=True,exist_ok=True)603        with args.report.open('x') as output:604            output.write(render(args,primary,counter,audit,reg,ot,args.report,comparison))605    print(json.dumps({'status':'PREVIEW' if args.preview else 'PASS','body_rows':len(costs),'out':str(args.out),'curated':str(args.curate) if args.curate else None}))606607if __name__=='__main__':main()