File size: 9,689 Bytes
248ea7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python3
"""Export recorded research results to deterministic Hugging Face JSON Lines tables.

This script transforms saved evidence only. It does not rerun or alter experiments.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
import statistics
from pathlib import Path

METHODS = ('frozen_syntax', 'one_shot', 'recursive', 'semantic_bfs')

def read_json(path):
    return json.loads(path.read_text(encoding='utf-8'))

def scalar_fields(value, prefix=''):
    """Retain named scalar leaves, never variable-length arrays."""
    result = {}
    for key, item in value.items():
        name = prefix + key
        if isinstance(item, dict):
            result.update(scalar_fields(item, name + '_'))
        elif item is None or isinstance(item, (str, bool, int, float)):
            result[name] = item
    return result

def ratio(a, b):
    return a / b if b else None

def canonical_json(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)

def write_rows(path, rows):
    path.write_text(''.join(canonical_json(row) + '\n' for row in rows), encoding='utf-8')

def close(actual, expected):
    if isinstance(expected, float):
        assert math.isclose(actual, expected, rel_tol=1e-12, abs_tol=1e-12), (actual, expected)
    else:
        assert actual == expected, (actual, expected)

def export(source: Path, output: Path):
    summary = read_json(source / 'results/SUMMARY.json')
    tests = read_json(source / 'results/TEST_RESULTS.json')
    paths = sorted((source / 'results').glob('case_*.json'))
    paths.sort(key=lambda p: tuple(map(int, re.fullmatch(r'case_(\d+)_(\d+)\.json', p.name).groups())))
    cases, generations, source_cases = [], [], []
    expected_snapshots = set()
    case_keys = set()
    for path in paths:
        case = read_json(path)
        width, seed = case['width'], case['seed']
        assert (width, seed) not in case_keys, 'Duplicate case key'
        case_keys.add((width, seed))
        assert path.name == f'case_{width}_{seed}.json'
        history = case['history']
        assert [h['generation'] for h in history] == list(range(1, len(history)+1))
        targets = read_json(source / f'results/targets_{width}_{seed}.json')
        row = {
            'case_id': f'n{width}_seed{seed}',
            'width': width,
            'seed': seed,
            'source_case_path': path.relative_to(source).as_posix(),
            'source_case_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
            'scheduled_generations': len(history),
            'nonempty_updates': sum(h['upgrade']['accepted'] > 0 for h in history),
            'final_rules': case['final_rules'],
            'final_automaton_states': case['final_automaton_states'],
            'training_wall_seconds': case['training_wall_seconds'],
            'targets_total': len(targets),
        }
        row.update(scalar_fields(case['final_receipt'], 'final_receipt_'))
        row.update(scalar_fields(case['final_stats'], 'final_stats_'))
        for method in METHODS:
            data = case['methods'][method]
            for budget in ('fixed_products', 'fixed_prefix'):
                row.update(scalar_fields(data[budget], f'{method}_{budget}_'))
            row[f'{method}_median_prefix_seconds'] = data['median_prefix_seconds']
            for metric in ('known_semantics', 'targets_solved', 'wall_seconds', 'semantic_products'):
                row[f'{method}_wall_probe_median_{metric}'] = statistics.median(p[metric] for p in data['wall_probes'])
        for branch in ('continue_self_updates', 'freeze_meta_only'):
            row.update(scalar_fields(case['causal_fork'][branch], 'causal_' + branch + '_'))
        for base in ('frozen_syntax', 'one_shot', 'semantic_bfs'):
            row[f'ratio_recursive_to_{base}_fixed_products_semantics'] = ratio(
                case['methods']['recursive']['fixed_products']['known_semantics'],
                case['methods'][base]['fixed_products']['known_semantics'])
            row[f'speedup_recursive_vs_{base}_prefix'] = ratio(
                case['methods'][base]['median_prefix_seconds'],
                case['methods']['recursive']['median_prefix_seconds'])
        row['ratio_causal_continue_to_freeze_additional_semantics'] = ratio(
            case['causal_fork']['continue_self_updates']['additional_semantics'],
            case['causal_fork']['freeze_meta_only']['additional_semantics'])
        cases.append(row)
        source_cases.append(case)
        prior_rule_count = 0
        for item in history:
            generation = item['generation']
            snapshot_path = source / f'snapshots/n{width}_seed{seed}_g{generation}.json'
            expected_snapshots.add(snapshot_path.name)
            snapshot = read_json(snapshot_path)
            guard = snapshot['guard']
            assert all(len(g) == width for g in snapshot['generators'])
            assert snapshot['known_semantics'] == item['growth']['known_semantics']
            assert len(snapshot['rules']) == item['upgrade']['rules_total']
            assert len(snapshot['rules']) - prior_rule_count == item['upgrade']['accepted']
            assert len(guard['prefixes']) == item['upgrade']['automaton_states']
            assert guard['sha256'] == item['upgrade']['after_hash']
            assert snapshot['stats'] == item['stats']
            prior_rule_count = len(snapshot['rules'])
            gen = {
                'case_id': row['case_id'], 'width': width, 'seed': seed,
                'generation': generation,
                'source_snapshot_path': snapshot_path.relative_to(source).as_posix(),
                'source_snapshot_sha256': hashlib.sha256(snapshot_path.read_bytes()).hexdigest(),
                'known_semantics': snapshot['known_semantics'],
                'rules_total': len(snapshot['rules']),
                'automaton_states': len(guard['prefixes']),
                'generator_count': len(snapshot['generators']),
                'accepted_new_rules': item['upgrade']['accepted'],
                'nonempty_update': item['upgrade']['accepted'] > 0,
                'guard_sha256': guard['sha256'],
                'before_guard_sha256': item['upgrade']['before_hash'],
                'upgrade_wall_seconds': item['upgrade']['wall_seconds'],
            }
            gen.update(scalar_fields(item['growth'], 'growth_'))
            gen.update(scalar_fields(item['stats'], 'stats_'))
            generations.append(gen)
        assert prior_rule_count == row['final_rules']
    assert set(p.name for p in (source/'snapshots').glob('*.json')) == expected_snapshots
    assert len(cases) == summary['case_count'] == 24
    assert len(generations) == tests['accepted_snapshots'] == 192
    assert len({(g['width'],g['seed'],g['generation']) for g in generations}) == len(generations)
    close(sum(c['final_rules'] for c in cases), summary['total_final_rules'])
    close(sum(c['nonempty_updates'] for c in cases), summary['total_nonempty_updates'])
    for method in METHODS:
        recorded = summary['methods'][method]
        close(statistics.mean(c[f'{method}_fixed_products_known_semantics'] for c in cases), recorded['mean_semantics_fixed_products'])
        close(sum(c[f'{method}_fixed_products_targets_solved'] for c in cases), recorded['total_targets_solved'])
        close(sum(c['targets_total'] for c in cases), recorded['targets_total'])
        close(statistics.mean(c[f'{method}_fixed_prefix_semantic_products'] for c in cases), recorded['mean_products_fixed_prefix'])
        close(statistics.median(c[f'{method}_median_prefix_seconds'] for c in cases), recorded['median_prefix_seconds'])
    for base in ('frozen_syntax', 'one_shot', 'semantic_bfs'):
        close(statistics.mean(c[f'ratio_recursive_to_{base}_fixed_products_semantics'] for c in cases), summary['paired'][base]['mean_discovery_ratio'])
        close(statistics.median(c[f'speedup_recursive_vs_{base}_prefix'] for c in cases), summary['paired'][base]['median_prefix_speedup'])
    close(statistics.mean(c['ratio_causal_continue_to_freeze_additional_semantics'] for c in cases), summary['causal_additional_discovery_mean_ratio'])
    output.mkdir(parents=True, exist_ok=True)
    write_rows(output/'cases.jsonl', cases)
    write_rows(output/'generations.jsonl', generations)
    report = {
        'cases':len(cases), 'generations':len(generations),
        'nonempty_updates':sum(g['nonempty_update'] for g in generations),
        'final_rules_summed_across_cases':sum(c['final_rules'] for c in cases),
        'causal_continue_additional_semantics':sum(c['causal_continue_self_updates_additional_semantics'] for c in cases),
        'causal_freeze_additional_semantics':sum(c['causal_freeze_meta_only_additional_semantics'] for c in cases),
        'all_recorded_aggregate_checks_passed':True,
        'source_files_unchanged':True,
        'tables':{name:{'rows':len(rows),'columns':len(rows[0]),'sha256':hashlib.sha256((output/name).read_bytes()).hexdigest()} for name,rows in [('cases.jsonl',cases),('generations.jsonl',generations)]},
    }
    (output/'EXPORT_VALIDATION.json').write_text(json.dumps(report,indent=2,sort_keys=True)+'\n',encoding='utf-8')
    return report

def main():
    root=Path(__file__).resolve().parent
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source',type=Path,default=root/'research')
    parser.add_argument('--output',type=Path,default=root/'data')
    args=parser.parse_args()
    print(json.dumps(export(args.source.resolve(),args.output.resolve()),indent=2,sort_keys=True))

if __name__=='__main__':
    main()