report_round5.py

benches/crypto/garbled-circuit/report_round5.py

report_round5.py283 lines← Benchmarks
1#!/usr/bin/env python32"""Generate round5 narrow-AES/cutoff findings only from complete paired evidence."""3import argparse4from decimal import Decimal5import hashlib6import json7import os8from pathlib import Path910FEATURES = {'aes-simd', 'game-prg-simd', 'prg-simd', 'prg-xof4', 'prg-query-batch'}11FIELDS = ('raw_cost', 'whole_message_cost', 'page_fee_cost')12SUITE = 'c93cec6c2f3fd4e73d9928f5a2634786706b6691feddc055e990e1a6e00f0daf'13PIC = '6a9a75ad9b4551d2b0f4a0d954ffb8bd5bbd0ebc44ac00290679b06ad0b2f8e6'14GC_CASES = ('aes-block', 'gate-hash', 'and-garble', 'and-evaluate',15            'eq8-garble-gate-only', 'eq8-evaluate-gate-only')161718def need(value, message):19    if not value:20        raise ValueError(message)212223def read(path):24    return json.loads(path.read_text())252627def sha(path):28    return hashlib.sha256(path.read_bytes()).hexdigest()293031def transcript(row):32    return [s['reply']['checksums'] for s in row['samples']]333435def table(headers, rows):36    return ['| ' + ' | '.join(headers) + ' |', '| ' + ' | '.join('---' for _ in headers) + ' |',37            *('| ' + ' | '.join(map(str, row)) + ' |' for row in rows)]383940def per(row, field, count=1000):41    return Decimal(row[field]) / count424344def fmt(value):45    return f'{value:,.1f}'464748class Run:49    def __init__(self, path, required, counter=False):50        self.path = path51        self.artifact = read(path / 'artifact.json')52        self.host = read(path / 'host-receipt.json')53        self.checks = read(path / 'correctness.json')54        self.data = read(path / 'results.json')55        need(self.data['status'] == 'PASS' and set(self.artifact['features']) == set(required), f'Incomplete/different image: {path}')56        need(read(path / 'session/receipt.json')['binarySha256'] == PIC, f'Different runtime: {path}')57        need(('instrumentation' in required) == counter, f'Wrong cost/counter role: {path}')58        self.rows, controls, blocked = {}, 0, 059        for row in self.data['rows']:60            if row['status'] == 'BLOCKED':61                blocked += 162                need(all(row.get(k) is None for k in (*FIELDS, 'harness_cost', 'adjusted_cost', 'cost_per_query')), 'Invented OT cost')63                continue64            need(row['status'] == 'MEASURED' and row['sample_count'] == len(row['samples']) == 2, 'Unmeasured sample')65            need(all(s['ok'] and s['reply']['ok'] and s['endpoint']['memoryDetailsAvailable'] for s in row['samples']), 'Failed sample')66            need(all(row[k] is None for k in ('wall_time_median_ns', 'wall_time_p95_ns', 'peak_heap_bytes',67                'sent_payload_bytes', 'received_payload_bytes', 'sent_framing_bytes', 'received_framing_bytes', 'rounds')), 'Unqualified metric')68            need(row['artifact_hash'] == self.artifact['wasmSha256'] and row['source_commit'] == self.artifact['commit']69                and set(row['artifact_features']) == set(required), 'Row/source identity differs')70            if row['benchmark'].endswith('.empty-harness'):71                controls += 172            else:73                key = (row['benchmark'], row['batch'], row['prg_bytes'])74                need(key not in self.rows, 'Repeated population')75                self.rows[key] = row76        need((len(self.rows), controls, blocked) == ((0, 0, 0) if counter else (91, 91, 52)), 'Wrong population counts')77        for key, n in {'native_exhaustive_pairs': 65536, 'wasm_bounded_pairs': 1024, 'xof_bytewise_cases': 64,78                       'game_prg_bytewise_cases': 50, 'aes32_bytewise_cases': 32, 'secret_batch_bytewise_cases': 68}.items():79            need(self.checks[key] == n, f'Missing correctness scope: {key}')8081    def row(self, case, n=1000):82        row = self.rows[(case, n, 0)]83        need(row['suite_id'] == SUITE, 'Changed GC contract')84        return row858687def audited(name, data, directory, counter=False):88    audit = read(directory / (name + '-ic-audit.json'))89    need(audit['status'] == 'PASS' and audit['artifact']['wasm_sha256'] == data.artifact['wasmSha256']90         and audit['artifact']['manifest_sha256'] == data.artifact['manifestSha256']91         and audit['result_sha256'] == sha(data.path / 'results.json'), f'Different audited image: {name}')92    need(audit['traces']['trace_count'] == (7 if counter else 737), f'Incomplete traces: {name}')93    expected = {'secret_batch_cases': 68, 'secret_batch_bytes_compared': 28928, 'secret_batch_rejections': 12}94    if not counter:95        expected.update(body_rows=91, harness_rows=91, blocked_rows=52, body_samples=182, harness_samples=182,96                        setup_samples=364, native_checksum_items_compared=50726)97    for key, n in expected.items():98        need(audit['populations'][key] == n, f'Incomplete audit: {name}/{key}')99    return audit100101102def generate(args):103    old = Run(args.round4 / 'selected-results', FEATURES)104    control = Run(args.control, FEATURES)105    # CLI explicitly records selected features; no implicit feature is invented in metadata.106    selected = Run(args.selected, set(args.selected_features.split(',')))107    need('aes-narrow' in selected.artifact['features'], 'No narrow AES feature selected')108    counter = Run(args.counter, set(selected.artifact['features']) | {'instrumentation'}, counter=True)109    need(old.rows.keys() == control.rows.keys() == selected.rows.keys(), 'Matrix changed')110    for key, row in old.rows.items():111        need(transcript(row) == transcript(control.rows[key]) == transcript(selected.rows[key]), f'Frozen output changed: {key}')112        need(all(row.get(k) == selected.rows[key].get(k) == control.rows[key].get(k)113             for k in ('suite_id', 'profile_id', 'key_context', 'gc_suite_compatible')), f'Profile changed: {key}')114    for data in (control, selected):115        for n in (1, 100, 1000):116            need(transcript(data.row('prg-secret32', n)) == transcript(data.row('prg-batch-secret32', n)), 'Secret bytes changed')117    native, prior = read(args.native), read(args.round4 / 'native-reference.json')118    need(native['rows'] == prior['rows'] and native['secret_batch_probe'] == prior['secret_batch_probe'], 'Native91/68 corpus changed')119    need(all(data.checks['native_reference_sha256'] == sha(args.native) for data in (control, selected, counter)), 'Different native inputs')120    audits = {name: audited(name, data, args.review, name == 'counter')121              for name, data in [('control', control), ('selected', selected), ('counter', counter)]}122    need(len({d.host['source']['sdk_commit'] for d in (old, control, selected, counter)}) == 1, 'SDK pin changed')123    need(all(a['artifact']['archive_gc_source_hashes'] == audits['selected']['artifact']['archive_gc_source_hashes']124             for a in audits.values()), 'Paired compiled sources differ')125    kernel_pins = {'1,2': '2e5dbd7e9648bbe91e4be9ce46729f277f4ce04e536ba5050b0f38e93f79a184',126                   '1,2,4': 'cbd43ac4f54f1b6829060dfc563e4f5dcea22d85f0ba5c165ea93abd573bcc9b'}127    need(audits['selected']['artifact']['archive_gc_source_hashes']['crypto/algo/aes/src/simd128.rs'] ==128         kernel_pins[args.narrow_widths], 'Declared narrow widths differ from exact audited kernel')129    oldaudit = read(args.round4 / 'review/selected-ic-audit.json')130    need(all(a['artifact']['sdk_source_closure_sha256'] == oldaudit['artifact']['sdk_source_closure_sha256']131             for a in audits.values()), 'SDK source closure changed')132    counts = counter.checks['probe']['reply']['structural_counts']['some']133    need(int(counts['alice_hashes']) == 28672 and int(counts['bob_hashes']) == 14336, 'Changed structural counts')134    relative = lambda p: os.path.relpath(p, args.output.parent).replace(os.sep, '/')135    link = relative(args.evidence / 'round5/narrow-aes')136    narrow_description = ('one/two-block AES methods; four/eight-block methods retain their prior implementation'137                          if args.narrow_widths == '1,2' else138                          'one/two/four-block AES methods; eight-block methods retain their prior implementation')139    checked_results = 1280 if args.narrow_widths == '1,2' else 1792140    lines = ['# Narrow AES and small BLAKE3 batches — round 5', '',141        'Two fresh matched images pass all 91 populations. Both include the measured BLAKE3 cutoff: lengths 1..6 use the original single-query readers, '142        'and lengths 7 or greater use the independent-query SIMD path. The selected image enables `aes-narrow` for ' + narrow_description + '. '143        'All GC/PRG output contracts and the 68-case batch corpus remain unchanged.', '',144        'Costs are actual IC instructions per operation/query at N=1000. Each body and separate empty harness has two fresh samples. '145        'Counter 0 body and authoritative whole checked update remain separate; page fees are included in whole cost. Values are rounded to 0.1; '146        'exact numerators and denominators remain in the cost summary. No harness subtraction or N=1 projection is used.', '']147    rows, exact = [], []148    for case in GC_CASES:149        a, b = control.row(case), selected.row(case)150        rows.append([case, fmt(per(a, 'raw_cost')) + ' → ' + fmt(per(b, 'raw_cost')),151                     fmt(per(a, 'whole_message_cost')) + ' → ' + fmt(per(b, 'whole_message_cost')),152                     fmt(per(b, 'page_fee_cost'))])153        exact.append({'benchmark': case, 'actual_n': 1000, 'control': {f: a[f] for f in FIELDS},154                      'selected': {f: b[f] for f in FIELDS}, 'denominator': '1000'})155    lines += table(['GC operation', 'Control→narrow body', 'Control→narrow whole', 'Selected page fees'], rows)156    if args.screen:157        screen = Run(args.screen / 'selected-results', set(selected.artifact['features']))158        audited('selected', screen, args.screen / 'review')159        screen_rows = []160        for case in GC_CASES:161            before, after = screen.row(case), selected.row(case)162            need(transcript(before) == transcript(after), 'Earlier same-round checkpoint changed bytes')163            screen_rows.append([case, fmt(per(before, 'raw_cost')) + ' → ' + fmt(per(after, 'raw_cost')),164                                fmt(per(before, 'whole_message_cost')) + ' → ' + fmt(per(after, 'whole_message_cost'))])165        lines += ['', 'Earlier frozen 1/2 checkpoint → chosen-width image, actual N1000:', '',166                  *table(['GC operation', 'Body', 'Whole checked update'], screen_rows), '',167                  'This compares complete checkpoint artifacts and their layouts. Source scopes and independent audits remain separate.']168    lines += ['', 'These AES rows use the fixed public-zero key for the GC construction. They do not measure generic secret-key narrow API costs. '169        'The direct AES32 reference remains separately named with real-block denominators. Public-zero setup retains a zero-sized owner; '170        'its setup row does not represent general secret-key expansion. Garbler whole updates also evaluate/check outputs after timing: '171        'whole savings with unchanged garbling bodies come from that evaluator/checking work, not a faster pure Alice kernel.', '',172        'Actual BLAKE3 short-secret populations, per real secret:', '']173    secret_rows = []174    for n in (1, 100, 1000):175        for name, data, case in [('round4 SIMD batch', old, 'prg-batch-secret32'), ('round5 control batch', control, 'prg-batch-secret32'),176                                 ('round5 selected batch', selected, 'prg-batch-secret32'), ('round5 selected stream', selected, 'prg-secret32')]:177            row = data.row(case, n)178            secret_rows.append([str(n), name, *(fmt(per(row, field, n)) for field in FIELDS)])179            exact.append({'benchmark': case, 'image': name, 'actual_n': n, 'denominator': str(n), **{f: row[f] for f in FIELDS}})180    lines += table(['Actual N', 'Path/image', 'Body/secret', 'Whole/secret', 'Page fees/secret'], secret_rows)181    lines += ['', 'One batch API call writes N independent 32-byte secrets; the stream path constructs, fills and retires N stream owners. '182        'The cutoff was chosen from the preceding [actual small-batch sweep](' + relative(args.round4 / 'small-batch-sweep/README.md') + '), '183        'where N6 favored sequential readers and N7 favored four-query SIMD scheduling. The new N1/100/1000 figures above are fresh binary measurements; no new crossover is inferred '184        'for unmeasured populations. Session preparation precedes timing, batch scratch cleanup stays inside the body, and cold-output verification, '185        'checksums, replies and retained-owner cleanup remain in whole updates. '186        'Single-query readers can themselves use Wasm SIMD compression; the cutoff changes independent-query scheduling, not SIMD versus non-SIMD arithmetic.', '',187        'The fresh pair isolates the narrow-feature choice within this round. Comparisons with [round4](' + relative(args.round4 / 'README.md') + ') '188        'also include the changed cutoff and complete compiler/layout effects; they do not isolate each source edit. The previous archive and '189        'report remain unchanged.', '',190        'Qualification scope:', '',191        '- The shared native reference preserves all 91 output populations and 68 batch cases. Each installed image passes 1,024 equality pairs, '192        '64 BLAKE3 cases, 50 standalone PRG cases, 32 AES cases and 68 batch cases; native exhaustive equality covers 65,536 pairs. '193        'Each primary independent audit checks 737 traces and 50,726 per-output checksum items. Separate instrumented proof confirms 28/14 hashes '194        'per equality, with no primary cost rows.',195        '- Generic AES target checks retain eight-lane results and exercise borrowed/in-place narrow-width methods within the same 32-case '196        f'endpoint schema: {checked_results:,} checked block results across 256 distinct key/input lane pairs per image. These include repeated '197        'cross-API comparisons, not that many unique vectors. Hardware-lowering qualification remains scoped by the independent source/target review; '198        'these correctness probes are distinct from GC public-zero performance rows.',199        '- The optional byte-vector AES path uses secret-index register swizzles. Its constant-time claim depends on hardware register-swizzle '200        'lowering; source equivalence or native emulation does not establish a universal-host guarantee. Read the exact measured-host review before '201        'using that claim outside the qualified runtime.',202        '- Frozen GC suite `' + SUITE + '` and all existing PRG domains remain unchanged. Standalone ChaCha profiles retain null GC suite IDs. '203        'Wasm64 IC OT integration/full IC protocol remain blocked, with no fresh OT costs; pinned portable/WASI OT evidence is separate. '204        'Network measurements, wall-time statistics and peak live heap remain null.', '', 'Frozen identities:', '']205    lines += table(['Image', 'Prepared Wasm SHA256', 'Actual features'],206                   [[name, '`' + data.artifact['wasmSha256'] + '`', ', '.join(data.artifact['features'])]207                    for name, data in [('Control', control), ('Selected', selected)]])208    sizes = [['Round4 selected', f"{oldaudit['artifact']['wasm_bytes']:,}"]]209    if args.screen:210        screen_audit = read(args.screen / 'review/selected-ic-audit.json')211        sizes.append(['Earlier round5 narrow1/2', f"{screen_audit['artifact']['wasm_bytes']:,}"])212    sizes += [[name, f"{audits[key]['artifact']['wasm_bytes']:,}"] for name, key in213              [('Fresh round5 control', 'control'), ('Chosen narrow widths', 'selected')]]214    lines += ['', *table(['Prepared image', 'Actual Wasm bytes'], sizes), '',215              'These sizes belong to complete prepared images, including their correctness probe code; they are not isolated kernel byte estimates.']216    diagnostic = read(args.evidence / 'round5/narrow-aes/selected-profile/summary.json')217    profile_root = args.evidence / 'round5/narrow-aes/selected-profile'218    profile_review = read(profile_root / 'review/source-profile-audit.json')219    cohort_review = read(profile_root / 'review/cohort-audit.json')220    need(profile_review['status'] == cohort_review['status'] == 'PASS'221         and profile_review['prepared_image'] == selected.artifact['wasmSha256']222         and profile_review['cohort_audit_sha256'] == sha(profile_root / 'review/cohort-audit.json')223         and cohort_review['result_sha256'] == sha(profile_root / 'results.json')224         and cohort_review['traces']['trace_count'] == 41, 'Incomplete separate diagnostic audit')225    need(diagnostic['runner_status'] == 'PASS' and diagnostic['installed_sha256'] == selected.artifact['wasmSha256']226         and diagnostic['complete_charge_ledger'] is True and diagnostic['stack_attribution'] == 'partial',227         'Different or incorrectly scoped diagnostic profile')228    population = diagnostic['profiled_population']229    need(population['body_instructions'] == selected.row('eq8-evaluate-gate-only')['raw_cost'],230         'Profiled body differs from primary population')231    coverage = diagnostic['source_coverage']232    lines += ['', 'A separately audited [evaluator diagnostic](' + link + '/selected-profile/summary.json) uses actual N=1/10/100/1000, '233        'with one N1000 source profile. Its charge ledger is complete, while stack details are truncated/partial: '234        f"{diagnostic['captured_stacks']} captured stacks, {diagnostic['captured_stack_charges']} captured stack charges and "235        f"{diagnostic['retained_boundary_rows']} retained boundary rows. Source locations cover "236        f"{coverage['points_with_archived_source']}/{coverage['queried_points']} queried points. "237        f"The filtered N1000 call has body {int(population['body_instructions']):,} / whole {int(population['whole_update_instructions']):,}; "238        f"the complete primary whole is {int(selected.row('eq8-evaluate-gate-only')['whole_message_cost']):,}. "239        'Boundary/stack attribution does not provide exact line or component costs, and these diagnostic calls do not replace primary samples.']240    lines += ['', 'Exact archived source inputs, not parent commits alone, identify these builds. SDK commit `' + selected.host['source']['sdk_commit']241        + '` and the frozen SDK/runtime/allocator closure match round4. PocketIC normal13 executable SHA256 is `' + PIC + '`. '242        'Primary instrumentation is disabled.', '',243        'Evidence: [control JSON](' + link + '/control-results/results.json), [selected JSON](' + link + '/selected-results/results.json), '244        '[CSV](' + link + '/selected-results/results.csv), [source/artifact manifest](' + link + '/manifest.json), '245        '[independent review](' + link + '/review/IC-REVIEW.txt) and [proof scope](' + link + '/README.md). Full raw originals remain at '246        '`/srv/shared/code/newstack/playground/gc-20261031/round5-four-aes-001`; the earlier checkpoint remains at '247        '`/srv/shared/code/newstack/playground/gc-20261031/round5-narrow-aes-001`. Curated gzip files are storage encodings; '248        'installation receipts retain original transport identities.', '', '```sh',249        'python3 benches/crypto/garbled-circuit/report_round5.py', '```', '']250    return '\n'.join(lines), {'format': 'gc-round5-report-v1', 'rows': exact,251        'inputs': {name: {'results_sha256': sha(data.path / 'results.json'), 'artifact': data.artifact}252                   for name, data in [('control', control), ('selected', selected), ('counter', counter)]}}253254255def main():256    p = argparse.ArgumentParser(description=__doc__)257    p.add_argument('--repo-root', type=Path, default=Path(__file__).resolve().parents[3])258    for name in ('evidence', 'round4', 'control', 'selected', 'counter', 'native', 'review', 'screen', 'output', 'json'):259        p.add_argument('--' + name, type=Path)260    p.add_argument('--selected-features', default=','.join(sorted(FEATURES | {'aes-narrow'})))261    p.add_argument('--narrow-widths', choices=('1,2', '1,2,4'), default='1,2,4')262    args = p.parse_args()263    if args.evidence is None:264        args.evidence = args.repo_root / 'research/crypto/experiments/2026-10-31-garbled-circuit'265    defaults = {'round4': args.evidence / 'round4/query-batch', 'control': args.evidence / 'round5/narrow-aes/control-results',266                'selected': args.evidence / 'round5/narrow-aes/selected-results', 'counter': args.evidence / 'round5/narrow-aes/counter-checks',267                'native': args.evidence / 'round4/query-batch/native-reference.json', 'review': args.evidence / 'round5/narrow-aes/review',268                'screen': args.evidence / 'round5/narrow-aes-screen',269                'output': args.repo_root / 'research/crypto/benchmarks/2026-10-31-garbled-circuit-round5.md'}270    for name, value in defaults.items():271        if getattr(args, name) is None:272            setattr(args, name, value)273    report, exact = generate(args)274    args.output.parent.mkdir(parents=True, exist_ok=True)275    args.output.write_text(report)276    if args.json:277        args.json.parent.mkdir(parents=True, exist_ok=True)278        args.json.write_text(json.dumps(exact, indent=2) + '\n')279    print(args.output)280281282if __name__ == '__main__':283    main()