report.py

benches/crypto/private-proximity/report.py

report.py403 lines← Benchmarks
1#!/usr/bin/env python32"""Render completed private-proximity IC runs into explicit fresh destinations.34Reads the existing host results and receipts; never measures, extrapolates,5curates source archives, or writes into a measured run. Frozen LOS rows are6separate-contract references. Instrumented images supply correctness only.7"""89import argparse10import csv11from datetime import date12from decimal import Decimal13import hashlib14import json15import os16from pathlib import Path171819PROGRAMS = ('proximity1', 'proximity2', 'proximity4', 'equality8')20REFERENCES = ('los4', 'los16', 'los64', 'selector256')21STAGES = ('randomness', 'garble', 'evaluate', 'serialize', 'parse')22BATCHES = (1, 100)23PARTIES = {'randomness': 'Alice', 'garble': 'Alice', 'evaluate': 'Bob',24           'serialize': 'local', 'parse': 'local'}25FIELDS = {'raw_cost': ('reply', 'body_instructions'),26          'whole_message_cost': ('endpoint', 'instructions'),27          'page_fee_cost': ('endpoint', 'pageAccessInstructions'),28          'prelude_cost': ('reply', 'prelude_instructions'),29          'postcheck_cost': ('reply', 'check_instructions')}30BYTES = ('request_payload_bytes', 'reply_payload_bytes',31         'request_framing_bytes', 'reply_framing_bytes')32UNMEASURED = ('actual_ot_cost', 'generated_ot_count', 'check_ot_count',33              'base_ot_count', 'sent_payload_bytes', 'received_payload_bytes', 'rounds')34LABELS = {'proximity1': 'Proximity R1', 'proximity2': 'Proximity R2',35          'proximity4': 'Proximity R4', 'equality8': 'Generic Equality8',36          'los4': 'LOS 4', 'los16': 'LOS 16', 'los64': 'LOS 64',37          'selector256': 'Synthetic 256:1 selector'}383940def need(condition, message):41    if not condition:42        raise ValueError(message)434445def read(path):46    return json.loads(Path(path).read_text())474849def sha(path):50    return hashlib.sha256(Path(path).read_bytes()).hexdigest()515253def median(values):54    values = sorted(map(int, values))55    n = len(values)56    need(n > 0, 'Empty successful sample population')57    return str(values[n // 2] if n % 2 else (values[n // 2 - 1] + values[n // 2]) // 2)585960def per(value, n):61    return str(Decimal(value) / n)626364def fmt(value):65    return f'{Decimal(value):,.2f}'.rstrip('0').rstrip('.')666768def table(headers, rows):69    return ['| ' + ' | '.join(headers) + ' |',70            '| ' + ' | '.join('---' for _ in headers) + ' |',71            *('| ' + ' | '.join(map(str, row)) + ' |' for row in rows)]727374def link(path, output):75    return os.path.relpath(path, Path(output).parent).replace(os.sep, '/')767778class Run:79    def __init__(self, path, structural=False):80        self.path = Path(path).resolve()81        self.artifact = read(self.path / 'artifact.json')82        self.host = read(self.path / 'host-receipt.json')83        self.data = read(self.path / 'results.json')84        self.catalog = read(self.path / 'catalog.json')85        self.checks = read(self.path / 'correctness.json')86        self.session = read(self.path / 'session/receipt.json')87        self.programs = {p['name']: p for p in self.catalog}88        need(len(self.programs) == len(self.catalog), 'Duplicate catalog program')89        need(len({p['suite_id'] for p in self.catalog}) == len(self.catalog),90             'Overlapping program frame identities')91        need(self.data['status'] == self.checks['status'] == 'PASS',92             f'Incomplete result or correctness qualification: {self.path}')93        need(('instrumentation' in self.artifact['features']) == structural,94             'Instrumented correctness and performance image roles differ')95        need(self.host['pocket_ic_sha256'] == self.session['binarySha256'],96             'Host/session PocketIC identity differs')97        for key, hashkey in (('wasmPath', 'wasmSha256'), ('manifestPath', 'manifestSha256'),98                             ('interfacePath', 'interfaceSha256')):99            need(sha(self.artifact[key]) == self.artifact[hashkey],100                 f'Artifact bytes differ: {key}')101        reference = self.host['reference']102        need(reference['receipt']['portable_aes'] and103             reference['sha256'] == reference['receipt']['reference_sha256'],104             'Native reference receipt differs or portable AES is unqualified')105        need(sha(reference['path']) == reference['sha256'], 'Native reference bytes differ')106        probes = self.checks['probes']107        need(self.checks['full_byte_records'] == len(probes) > 0,108             'Missing complete-frame target probes')109        coverage = set()110        for probe in probes:111            capture = probe['capture']112            need(capture['ok'] and capture['reply']['ok'], 'Failed correctness probe')113            program = self.catalog[probe['case']['program']]114            coverage.add(program['name'])115            records = capture['reply']['records']116            need(len(records) == 1, 'Unexpected probe record count')117            if structural:118                counts = records[0]['counts']['some']119                for party in ('alice', 'bob'):120                    need(int(counts[party + '_ands']) == program['and_count'] and121                         int(counts[party + '_xors']) == program['xor_count'] and122                         int(counts[party + '_hashes']) ==123                         program['and_count'] * (4 if party == 'alice' else 2),124                         'Structural gate/hash count differs from compiled program')125        self.probe_programs = coverage126        if structural:127            need(self.data['performance_rows'] == [] and not self.data.get('rows'),128                 'Instrumented image supplied performance rows')129        self.rows = {}130        self.harnesses = {}131        self.blocked = []132        for index, row in enumerate(self.data.get('rows', [])):133            if row['status'] == 'BLOCKED':134                need(all(row.get(field) is None for field in (*UNMEASURED, 'raw_cost',135                     'whole_message_cost')), 'Invented actual IC OT/protocol measurement')136                self.blocked.append(row)137                continue138            need(row['status'] == 'MEASURED', 'Failed row in passing run')139            need(row['artifact_hash'] == self.artifact['wasmSha256'] and140                 set(row['artifact_features']) == set(self.artifact['features']),141                 'Mixed row artifact or features')142            samples = row['samples']143            need(row['sample_count'] == len(samples) > 0, 'Incomplete sample population')144            for sample in samples:145                need(sample['ok'] and sample['reply']['ok'] and146                     sample['endpoint']['memoryDetailsAvailable'], 'Incomplete successful sample')147                need(Path(sample['endpoint']['tracePath']).is_file(), 'Missing raw endpoint trace')148                need(sample['reply']['batch'] == row['batch'], 'Different actual sample batch')149            for field, (owner, source) in FIELDS.items():150                need(row[field] == median(s[owner][source] for s in samples),151                     f'Changed sample median: {field}')152            need(all(row.get(field) is None for field in UNMEASURED),153                 'Circuit-function row claims unmeasured OT/transport work')154            control = row['stage'] == 'empty-harness'155            stage = row['case_id'].split('.')[-1] if control else row['stage']156            need(stage in STAGES and row['party'] == PARTIES[stage], 'Unknown stage/party scope')157            key = (row['program'], stage, row['batch'])158            target = self.harnesses if control else self.rows159            need(key not in target, 'Duplicate population')160            target[key] = (index, row)161            if control:162                need(row['query_count'] == 0 and163                     all(s['reply']['control'] for s in samples), 'Invalid empty harness')164                continue165            program = self.programs[row['program']]166            need(row['query_count'] == row['batch'] and167                 all(s['reply']['checked_outputs'] == row['batch'] and168                     not s['reply']['control'] for s in samples), 'Incomplete actual query count')169            need(row['suite_id'] == program['suite_id'] and170                 row['logical_ot_count'] == program['live_bob_bits'] * row['batch'],171                 'Circuit identity or logical OT metadata differs')172            need(row['and_count_per_query'] == program['and_count'] and173                 row['xor_count_per_query'] == program['xor_count'], 'Compiled gate metadata differs')174            for field in BYTES:175                need(row[field] == int(program[field]) * row['batch'],176                     f'Constructed frame size differs: {field}')177            for prefix in ('request', 'reply'):178                need(row[prefix + '_frame_bytes'] ==179                     row[prefix + '_payload_bytes'] + row[prefix + '_framing_bytes'],180                     'Constructed frame omits framing bytes')181        need(self.rows.keys() == self.harnesses.keys(), 'Unmatched stage/harness populations')182        for (program, _, n), (_, row) in self.rows.items():183            peers = [self.rows[program, stage, n][1] for stage in STAGES184                     if (program, stage, n) in self.rows]185            need(all([s['reply']['checksums'] for s in p['samples']] ==186                     [s['reply']['checksums'] for s in row['samples']] for p in peers),187                 'Stage output checksums differ')188189    def row(self, program, stage, n):190        return self.rows[program, stage, n][1]191192    def receipts(self):193        return {name: {'path': str(self.path / name), 'sha256': sha(self.path / name)}194                for name in ('results.json', 'rows.jsonl', 'artifact.json', 'catalog.json',195                             'correctness.json', 'host-receipt.json', 'session/receipt.json')196                if (self.path / name).is_file()}197198199def costs(run, programs, role):200    rows = []201    for program in programs:202        for n in BATCHES:203            for stage in STAGES:204                index, row = run.rows[program, stage, n]205                rows.append({'role': role, 'program': program, 'stage': stage,206                    'party': row['party'], 'actual_n': n, 'sample_count': row['sample_count'],207                    **{field: row[field] for field in FIELDS},208                    **{field + '_per_query': per(row[field], n) for field in FIELDS},209                    **{field: row[field] for field in (*BYTES, 'request_frame_bytes',210                       'reply_frame_bytes', 'logical_ot_count', *UNMEASURED)},211                    'suite_id': row['suite_id'], 'artifact_sha256': row['artifact_hash'],212                    'raw_results': str(run.path / 'results.json'), 'raw_row_index': index,213                    'endpoint_wire_bytes': [{'request': s['endpoint_wire_request_bytes'],214                        'reply': s['endpoint_wire_reply_bytes']} for s in row['samples']],215                    'sample_traces': [s['endpoint']['tracePath'] for s in row['samples']]})216    return rows217218219def render(args, primary, counter, reference, output):220    lines = [f'# Private 2D proximity IC circuit stages — {args.date}', '',221        '`private_proximity_2d` returns `abs(ax-bx) <= R && abs(ay-by) <= R`. '222        'Each 8-bit position stores x in the low nibble and y in the high nibble, '223        'with coordinates 0–15 and ordinary integer distances without wrapping.', '',224        'Actual N1 and N100 calls measure R1/R2/R4 and generic Equality8 in one image. '225        'Each body value below is the recorded integer sample median divided by the actual '226        'query count. N100/query is a bulk amortized value, not an unbatched measurement.', '',227        'Randomness and garbling belong to Alice; evaluation belongs to Bob. Serialization '228        'and parsing are local combined intervals over both request and reply frames. '229        'They do not provide independent Alice/Bob costs. Inputs, buffers, AES/session owners '230        'and reusable workspaces are staged before the body counter. Garbling uses staged '231        'randomness; evaluation uses locally selected fixture labels. That selection is not OT.', '',232        '## Compiled circuits and constructed bytes', '',233        'Byte counts are per query and include the actual encoded circuit frames. These '234        'are neither network traffic nor full-protocol sizes. Logical OTs are live Bob '235        'input bits per query; generated/check/base OT counts, actual IC OT, rounds and '236        'sent/received transport bytes remain unmeasured (`null`).', '']237    for run, programs, caption in ((primary, PROGRAMS, 'Selected image'),238                                  (reference, REFERENCES, 'Frozen reference image')):239        if run is None:240            continue241        lines += [f'**{caption}.**', '']242        lines += table(['Program', 'AND', 'XOR', 'AND depth', 'Live Alice/Bob bits',243            'Logical OT/query', 'Request payload + framing = bytes', 'Reply payload + framing = bytes'],244            [[LABELS[p], c['and_count'], c['xor_count'], c['and_depth'],245              f"{c['live_alice_bits']}/{c['live_bob_bits']}", c['live_bob_bits'],246              *[f"{c[s + '_payload_bytes']} + {c[s + '_framing_bytes']} = "247                f"{int(c[s + '_payload_bytes']) + int(c[s + '_framing_bytes'])}"248                for s in ('request', 'reply')]] for p in programs for c in [run.programs[p]]])249        lines += ['']250    lines += ['## Body instructions per actual query', '',251        'All five stages execute separately. Their body intervals retain loop/control work, '252        'writes and page faults inside the counter. Their sum is not a measured composition '253        'or protocol total. No harness or page charge is subtracted.', '']254    lines += table(['Program', 'Actual N', 'Alice randomness', 'Alice garble', 'Bob evaluate',255                    'Local serialize both frames', 'Local parse both frames'],256        [[LABELS[p], n, *[fmt(per(primary.row(p, s, n)['raw_cost'], n)) for s in STAGES]]257         for p in PROGRAMS for n in BATCHES])258    lines += ['', '## Complete checked updates and page charges', '',259        'Whole-update instructions include wrappers, preparation inside the endpoint, '260        'prelude, postchecks and reply serialization. Page charges are already included '261        'where charged; do not add them to or subtract them from body/whole values. '262        'Earlier setup calls are separate. Whole and page columns below are totals for '263        'the actual update, not per-query figures. The JSON/CSV also retain prelude, '264        'postcheck, exact per-query quotients and benchmark endpoint Wire bytes.', '']265    lines += table(['Program', 'Actual N', 'Stage', 'Body total', 'Whole-update total',266                    'Included page charge', 'Samples'],267        [[LABELS[p], n, s, *[fmt(primary.row(p, s, n)[f]) for f in268          ('raw_cost', 'whole_message_cost', 'page_fee_cost')], primary.row(p, s, n)['sample_count']]269         for p in PROGRAMS for n in BATCHES for s in STAGES])270    lines += ['', '## Comparison scopes', '',271        'Generic Equality8 above uses the same image, generic runtime, staged inputs and '272        'stage boundaries as proximity. Its Boolean function is different. The older '273        'specialized Equality8 benchmark included per-query randomness in garbling and '274        'is outside this comparison.', '']275    if reference:276        lines += ['The frozen LOS 4/16/64 and synthetic selector below come from a different '277            'artifact and implement different functions. They are reference costs, not '278            'matched before/after proximity speedups. The 255-AND selector consumes an '279            'arbitrary staged 256-bit Alice mask and an 8-bit Bob index. Visibility-mask '280            'construction/preprocessing is unmeasured; it is not a measured LOS protocol.', '']281        lines += table(['Frozen reference', 'Actual N', 'Alice randomness/query',282                        'Alice garble/query', 'Bob evaluate/query', 'Local serialize/query',283                        'Local parse/query'],284            [[LABELS[p], n, *[fmt(per(reference.row(p, s, n)['raw_cost'], n)) for s in STAGES]]285             for p in REFERENCES for n in BATCHES])286        lines += ['']287    else:288        lines += ['Frozen LOS and synthetic-selector numerical references were not supplied. '289                  'No cross-contract cost comparison is inferred.', '']290    lines += ['## Qualification and raw evidence', '',291        f"The primary image passed {primary.checks['full_byte_records']} complete-frame target/native "292        f"probes. The separate instrumented image passed {counter.checks['full_byte_records']} probes "293        'and checked compiled AND/XOR counts plus four Alice/two Bob hashes per AND. '294        'The native differential shares circuit runtime code; independent function/oracle '295        'tests and source review remain separate evidence. Instrumented images supply no '296        'performance rows. Host invocation duration is diagnostic; wall-time median/p95 '297        'and peak live heap remain unmeasured.', '',298        f"Primary Wasm SHA-256: `{primary.artifact['wasmSha256']}`.  ",299        f"Structural Wasm SHA-256: `{counter.artifact['wasmSha256']}`.  ",300        f"PocketIC SHA-256: `{primary.host['pocket_ic_sha256']}`.", '']301    for label, run in (('Primary', primary), ('Structural correctness', counter),302                       ('Frozen LOS/selector reference', reference)):303        if run is None:304            continue305        lines += [f'**{label}:** ' + '; '.join(306            f'[{name}]({link(run.path / name, output)}) SHA-256 `{receipt["sha256"]}`'307            for name, receipt in run.receipts().items()), '']308    lines += [f'[Machine-readable summary]({link(args.out.resolve() / "cost-summary.json", output)}) '309              'retains original receipt paths, hashes, raw row indexes and trace links. '310              f'[CSV]({link(args.out.resolve() / "costs.csv", output)}) retains all selected '311              'and frozen-reference stage ledgers. This report-only replay is not a new '312              'measurement or source-archive curation.', '']313    return '\n'.join(lines)314315316def main():317    parser = argparse.ArgumentParser(description=__doc__)318    parser.add_argument('--run', type=Path, required=True, help='Completed primary result directory')319    parser.add_argument('--counter', type=Path, required=True, help='Completed structural result directory')320    parser.add_argument('--los-reference', type=Path, help='Frozen complete LOS result directory')321    parser.add_argument('--date', type=date.fromisoformat, required=True)322    parser.add_argument('--out', type=Path, required=True, help='Fresh directory for README, JSON and CSV')323    parser.add_argument('--report', type=Path, help='Optional fresh standalone Markdown destination')324    args = parser.parse_args()325    need(not args.out.exists(), 'Output directory already exists')326    need(not args.report or not args.report.exists(), 'Standalone report already exists')327    for source in (args.run, args.counter, args.los_reference):328        if source:329            need(not args.out.resolve().is_relative_to(source.resolve()) and330                 (not args.report or not args.report.resolve().is_relative_to(source.resolve())),331                 'Report outputs cannot be inside a measured run')332    need(not args.report or args.report.resolve() not in333         {args.out.resolve() / name for name in ('README.md', 'cost-summary.json', 'costs.csv')},334         'Standalone report collides with a generated output')335    primary, counter = Run(args.run), Run(args.counter, structural=True)336    need(primary.catalog == counter.catalog, 'Primary/structural compiled catalogs differ')337    need(set(counter.artifact['features']) == set(primary.artifact['features']) | {'instrumentation'},338         'Primary/structural feature sets differ')339    need(primary.host['pocket_ic_sha256'] == counter.host['pocket_ic_sha256'],340         'Primary/structural PocketIC binaries differ')341    need(primary.host['reference']['sha256'] == counter.host['reference']['sha256'],342         'Primary/structural native references differ')343    need([p['case'] for p in primary.checks['probes']] ==344         [p['case'] for p in counter.checks['probes']], 'Primary/structural probe cases differ')345    for a, b in zip(primary.checks['probes'], counter.checks['probes']):346        x, y = (p['capture']['reply']['records'][0] for p in (a, b))347        need(all(x[k] == y[k] for k in ('request', 'reply', 'answer')),348             'Instrumented and primary complete-frame bytes differ')349    for name, radius in zip(PROGRAMS[:3], (1, 2, 4)):350        program = primary.programs[name]351        need(program['predicate'] == 'private_proximity_2d' and program['radius'] == radius and352             program['alice_bits'] == program['bob_bits'] == 8 and program['walls'] == [],353             'Different selected proximity function contract')354    equality = primary.programs['equality8']355    need(equality['predicate'] == 'equality8' and356         (equality['and_count'], equality['xor_count']) == (7, 8),357         'Different generic Equality8 comparator')358    expected = {(p, s, n) for p in PROGRAMS for s in STAGES for n in BATCHES}359    need(primary.rows.keys() == expected, 'Primary must contain exactly R1/R2/R4/Equality8 at actual N1/N100')360    need(set(PROGRAMS) <= primary.probe_programs & counter.probe_programs,361         'Selected program lacks complete-frame or structural probes')362    need({(p, n, party) for p in PROGRAMS for n in BATCHES for party in ('Alice', 'Bob')} <=363         {(r['program'], r['query_count'], r['party']) for r in primary.blocked},364         'Missing explicit blocked IC OT/protocol populations')365    reference = Run(args.los_reference) if args.los_reference else None366    if reference:367        need(all((p, s, n) in reference.rows for p in REFERENCES for s in STAGES for n in BATCHES),368             'Frozen reference lacks requested actual populations')369        need(reference.programs['selector256']['and_count'] == 255, 'Different selector reference')370    rows = costs(primary, PROGRAMS, 'selected')371    if reference:372        rows += costs(reference, REFERENCES, 'frozen-separate-contract-reference')373    summary = {'schema': 'private-proximity-cost-summary-v1', 'status': 'PASS',374        'date': str(args.date), 'scope': 'Circuit stages only; no actual IC OT or full protocol.',375        'report_generator': {'path': str(Path(__file__).resolve()), 'sha256': sha(__file__)},376        'aggregation': 'Integer median of actual samples; per-query values divide by actual N.',377        'primary_artifact': primary.artifact, 'counter_artifact': counter.artifact,378        'reference_artifact': reference.artifact if reference else None,379        'inputs': {'primary': primary.receipts(), 'structural': counter.receipts(),380                   'frozen_reference': reference.receipts() if reference else None},381        'primary_host_source': primary.host['source'], 'counter_host_source': counter.host['source'],382        'catalog': primary.catalog, 'reference_catalog': reference.catalog if reference else None,383        'costs': rows, 'blocked_rows': primary.blocked,384        'qualification': {'primary_full_byte_records': primary.checks['full_byte_records'],385                          'structural_full_byte_records': counter.checks['full_byte_records']}}386    args.out.mkdir(parents=True, exist_ok=False)387    (args.out / 'cost-summary.json').write_text(json.dumps(summary, indent=2) + '\n')388    with (args.out / 'costs.csv').open('w', newline='') as output:389        writer = csv.DictWriter(output, fieldnames=list(rows[0]))390        writer.writeheader()391        writer.writerows({key: json.dumps(value) if isinstance(value, (list, dict)) else value392                         for key, value in row.items()} for row in rows)393    (args.out / 'README.md').write_text(render(args, primary, counter, reference, args.out / 'README.md'))394    if args.report:395        args.report.parent.mkdir(parents=True, exist_ok=True)396        with args.report.open('x') as output:397            output.write(render(args, primary, counter, reference, args.report))398    print(json.dumps({'status': 'PASS', 'selected_rows': len(expected),399                      'reference_rows': len(rows) - len(expected), 'out': str(args.out)}))400401402if __name__ == '__main__':403    main()