File size: 30,410 Bytes
d424561
4271c52
 
 
 
d424561
4271c52
 
d424561
4271c52
 
d424561
4271c52
d424561
4271c52
d424561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#!/usr/bin/env python3
"""
Build the V1.0.0-rc1 dataset from the frozen V5 corpus.

Requires the completed V3 audit.

Corrects nine IPv6 MSS examples with valid MTUs and clarifies
eight interrupt-load examples where demand exceeds CPU capacity.

Writes a separate release candidate, records the changes, and
checks dataset integrity and train/validation consistency.

The original corpus is not modified.
"""

from __future__ import annotations

import argparse
from collections import Counter
from copy import deepcopy
from decimal import Decimal
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import tempfile

HOME = Path.home()
EXP = HOME / 'Projects/qwen3-ce-training/EXP-009-1P7B/cleanroom/EXP-010'
QUAL = EXP / 'data/exp010-full-data-BQSFdT/v5-qual-8100'
V1 = HOME / 'qwen3-ce-dataset-v1.0.0-release'
RC1 = HOME / 'qwen3-ce-dataset-v1.0.0-rc1'
AUDIT_V3 = HOME / 'qwen3-ce-v1-audit-local/family-risk-audit-v3.json'
FROZEN_ALL_SHA = 'ac7f3071f9724dad72811fd4264e3780c35d44907cce10c176056afc32bd9729'
COPY_MAP = {
    'qwen/train.jsonl': 'data/train.jsonl',
    'qwen/valid.jsonl': 'data/validation.jsonl',
    'structured/all.jsonl': 'source/all.jsonl',
    'structured/train.jsonl': 'source/train.jsonl',
    'structured/valid.jsonl': 'source/validation.jsonl',
}
ORIGINAL_RELEASE_FILES = set(COPY_MAP.values()) | {
    'README.md', 'RELEASE_MANIFEST.json', 'QUALIFICATION_EVIDENCE.json', 'RESEARCH_AUDIT.json'
}
MSS_PROMPT = re.compile(r'^For (IPv4|IPv6) MTU (\d+) bytes, IP header (\d+) bytes, and TCP header (\d+) bytes, compute TCP MSS assuming no other encapsulation\.$')
MSS_ANSWER = re.compile(r'=\s*(\d+)\s*-\s*(\d+)\s*-\s*(\d+)\s*=\s*(-?\d+)\s*bytes\b')
ISR_PROMPT = re.compile(r'^A ([\d.]+) MHz CPU services an interrupt at ([\d.]+) Hz\. Each ISR consumes (\d+) CPU cycles\. Assuming no overlap, compute CPU utilization caused by the ISR\.$')
NUM = r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?'
ISR_ANSWER = re.compile(r'=\s*(' + NUM + r')\s*=\s*(' + NUM + r')\s*%')


def sha_bytes(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def sha(path: Path) -> str:
    h = hashlib.sha256()
    with path.open('rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


def json_bytes(obj) -> bytes:
    return json.dumps(obj, ensure_ascii=False, sort_keys=True,
                      separators=(',', ':')).encode('utf-8')


def json_canon(row) -> str:
    return json_bytes(row).decode('utf-8')


def require(cond, message):
    if not cond:
        raise ValueError(message)


def load_lines(path: Path):
    lines = path.read_text(encoding='utf-8').splitlines(keepends=True)
    require(lines and all(line.strip() for line in lines), f'Blank/empty JSONL: {path}')
    rows = [json.loads(line) for line in lines]
    require(all(isinstance(r, dict) for r in rows), f'Nonobject JSONL: {path}')
    return lines, rows


def write_once(path: Path, value):
    # Only used in an isolated temporary candidate directory.
    require(not path.exists(), f'Unexpected output file exists: {path}')
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + '\n', encoding='utf-8')


def set_metadata_identity(row: dict, old_row: dict, source_line: int, category: str) -> None:
    old_meta = old_row.get('metadata', {})
    meta = row.get('metadata')
    require(isinstance(meta, dict) and isinstance(old_meta, dict), 'Missing metadata')
    original_prompt_sha = old_meta.get('prompt_sha1')
    computed_old_sha = hashlib.sha1(old_row['input'].encode('utf-8')).hexdigest()
    require(original_prompt_sha in (None, computed_old_sha),
            f'Original prompt hash not canonical, line {source_line}')
    if original_prompt_sha:
        meta['historical_prompt_sha1'] = original_prompt_sha
    meta['prompt_sha1'] = hashlib.sha1(row['input'].encode('utf-8')).hexdigest()
    # Old identity must NOT be passed off as the current text's content hash.
    if 'content_sha256' in meta:
        meta['historical_content_sha256'] = meta.pop('content_sha256')
    meta['content_sha256_scheme'] = 'rc1-v1:sha256(canonical-json:{generator_id,input,output})'
    meta['content_sha256'] = sha_bytes(json_bytes({
        'generator_id': meta['generator_id'], 'input': row['input'], 'output': row['output']
    }))
    meta['release_correction'] = {
        'kind': category,
        'from_frozen_v5_sha256': FROZEN_ALL_SHA,
        'source_line': source_line,
        'original_row_sha256': sha_bytes(json_bytes(old_row)),
        'version': 'v1.0.0-rc1',
    }


def rewrite_mss_metadata(container, old_mtu: int, old_mss: int, new_mtu: int, new_mss: int, loc='metadata'):
    """Replace only numeric old MTU/MSS values in relevant metadata areas.

    All other numeric values remain byte-for-byte conceptually identical. A numeric
    reference inside an unrecognized string refuses automation rather than guessing.
    """
    if isinstance(container, dict):
        out = {}
        for k, v in container.items():
            out[k] = rewrite_mss_metadata(v, old_mtu, old_mss, new_mtu, new_mss, f'{loc}.{k}')
        return out
    if isinstance(container, list):
        return [rewrite_mss_metadata(v, old_mtu, old_mss, new_mtu, new_mss, f'{loc}[{n}]')
                for n, v in enumerate(container)]
    if isinstance(container, bool):
        return container
    if isinstance(container, (int, float)):
        if container == old_mtu:
            return type(container)(new_mtu)
        if container == old_mss:
            return type(container)(new_mss)
        return container
    if isinstance(container, str):
        # JSON metadata occasionally stores numeric values as decimal strings.
        if container == str(old_mtu):
            return str(new_mtu)
        if container == str(old_mss):
            return str(new_mss)
        # Explicitly block old numbers embedded in descriptions or expressions.
        # Hashes are not part of the metadata subtrees processed here.
        if re.search(rf'(?<!\d)(?:{old_mtu}|{old_mss})(?!\d)', container):
            raise ValueError(f'Stale or ambiguous MSS numeric metadata at {loc}: {container[:120]}')
    return container


def transform_mss(old: dict, source_line: int, replacement_mtu: int = 1280) -> dict:
    prompt, answer = old['input'], old['output']
    m = MSS_PROMPT.fullmatch(prompt)
    a = MSS_ANSWER.search(answer)
    require(m is not None and a is not None, f'MSS format mismatch at {source_line}')
    version, mtu_s, ip_s, tcp_s = m.groups()
    mtu, ip, tcp = int(mtu_s), int(ip_s), int(tcp_s)
    ref_mtu, ref_ip, ref_tcp, ref_mss = map(int, a.groups())
    require(version == 'IPv6' and mtu < 1280, f'Not an IPv6 MTU warning at {source_line}')
    require((ref_mtu, ref_ip, ref_tcp, ref_mss) == (mtu, ip, tcp, mtu-ip-tcp),
            f'Original MSS answer mismatch at {source_line}')
    require(ip == 40 and 20 <= tcp <= 60 and tcp % 4 == 0, f'Invalid header at {source_line}')
    result = deepcopy(old)
    require(1280 <= replacement_mtu <= 9216, f'Out of range MTU {replacement_mtu}')
    new_mtu, new_mss = replacement_mtu, replacement_mtu-ip-tcp
    result['input'] = prompt.replace(f'IPv6 MTU {mtu} bytes', f'IPv6 MTU {new_mtu} bytes', 1)
    # Replace exactly the arithmetic clause found by independently anchored parser.
    result['output'] = (answer[:a.start()] + f'= {new_mtu}-{ip}-{tcp} = {new_mss} bytes' + answer[a.end():])
    meta = result['metadata']
    for field in ('parameters', 'verification'):
        if field in meta:
            meta[field] = rewrite_mss_metadata(meta[field], mtu, mtu-ip-tcp, new_mtu, new_mss, field)
    for field in ('output_contract',):
        if field in meta:
            # Contracts should specify format, not a particular old numerical answer.
            s = json.dumps(meta[field], ensure_ascii=False)
            require(not re.search(rf'(?<!\d)(?:{mtu}|{mtu-ip-tcp})(?!\d)', s),
                    f'Contract contains old MSS value at {source_line}')
    set_metadata_identity(result, old, source_line, 'ipv6_mtu_minimum')
    require(str(new_mss) in result['output'], f'New reference missing MSS at {source_line}')
    return result


def transform_isr(old: dict, source_line: int) -> dict:
    prompt, answer = old['input'], old['output']
    m, a = ISR_PROMPT.fullmatch(prompt), ISR_ANSWER.search(answer)
    require(m is not None and a is not None, f'ISR format mismatch at {source_line}')
    mhz, freq, cycles = Decimal(m.group(1)), Decimal(m.group(2)), Decimal(m.group(3))
    demand = freq*cycles/(mhz*Decimal(1000000))
    require(demand > 1, f'Expected overload scenario at {source_line}')
    stated = Decimal(a.group(2))
    # Printed answer may be rounded; relative tolerance 1e-5 of the percentage.
    require(abs(stated-demand*100) <= max(Decimal('0.00001'), demand*Decimal('0.001')),
            f'ISR numeric answer mismatch at {source_line}')
    require(answer.startswith('Utilization ='), f'Unexpected ISR answer prefix at {source_line}')
    result = deepcopy(old)
    result['input'] = prompt.replace(
        'Assuming no overlap, compute CPU utilization caused by the ISR.',
        'Ignoring queuing and interrupt interference, compute the idealized CPU-time demand '
        'as a percentage of one processor. If the demand exceeds 100%, identify the '
        'workload as overloaded rather than claiming achievable sustained CPU utilization.'
    )
    require(result['input'] != prompt, 'ISR prompt did not change')
    result['output'] = answer.replace('Utilization =', 'Idealized CPU-time demand =', 1).rstrip()
    result['output'] += (' This exceeds 100% of one processor: the workload is overloaded, '
                          'and this is demanded capacity, not attainable sustained CPU utilization.')
    set_metadata_identity(result, old, source_line, 'isr_overload_terminology')
    return result


def edit_record(old: dict, warning: dict, source_line: int, replacement_mtu: int | None = None) -> dict:
    require(warning['source_line'] == source_line, f'Wrong line for {source_line}')
    require(warning['prompt'] == old['input'], f'Original prompt mismatch at {source_line}')
    require(warning['reference_answer'] == old['output'], f'Original reference mismatch at {source_line}')
    kind, gid = warning['type'], old['metadata']['generator_id']
    if kind == 'IPV6_MTU_BELOW_1280':
        require(gid == 'mss_from_mtu', f'Wrong generator for {kind}')
        require(replacement_mtu is not None, 'Missing deterministic IPv6 replacement MTU')
        return transform_mss(old, source_line, replacement_mtu)
    if kind == 'ISR_DEMAND_ABOVE_100_PERCENT':
        require(gid == 'interrupt_cpu_load', f'Wrong generator for {kind}')
        return transform_isr(old, source_line)
    raise ValueError(f'Unrecognized risk category: {kind}')


def apply_file(stage_file: Path, changes_by_prompt: dict):
    old_lines, rows = load_lines(stage_file)
    output_lines = []
    touched = set()
    for line, row in zip(old_lines, rows):
        old_prompt = row['input'] if 'input' in row else row['messages'][1]['content']
        if old_prompt not in changes_by_prompt:
            output_lines.append(line)
            continue
        require(old_prompt not in touched, f'Duplicate prompt in {stage_file}: {old_prompt[:100]}')
        old_row, corrected = changes_by_prompt[old_prompt]
        if 'input' in row:
            require(json_canon(row) == json_canon(old_row),
                    f'Split record differs from full original: {stage_file}')
            new_row = corrected
        else:
            msgs = row['messages']
            require([m.get('role') for m in msgs] == ['system', 'user', 'assistant'],
                    f'Invalid Qwen roles {stage_file}')
            require(msgs[2]['content'] == old_row['output'],
                    f'Qwen assistant differs from source at {stage_file}')
            new_row = deepcopy(row)
            new_row['messages'][1]['content'] = corrected['input']
            new_row['messages'][2]['content'] = corrected['output']
        output_lines.append(json.dumps(new_row, ensure_ascii=False) + '\n')
        touched.add(old_prompt)
    stage_file.write_text(''.join(output_lines), encoding='utf-8')
    return touched


def canonical_rows(rows):
    return Counter(json_canon(r) for r in rows)


def verify_stage(stage: Path, old: Path, originals: dict, edited: dict, ledger: list):
    all_lines, all_rows = load_lines(stage / 'source/all.jsonl')
    _, tr_rows = load_lines(stage / 'source/train.jsonl')
    _, va_rows = load_lines(stage / 'source/validation.jsonl')
    require((len(all_rows), len(tr_rows), len(va_rows)) == (8100, 7695, 405), 'RC1 wrong row counts')
    require(canonical_rows(tr_rows) + canonical_rows(va_rows) == canonical_rows(all_rows),
            'RC1 train+validation does not equal full')
    require(len({r['input'] for r in all_rows}) == 8100, 'RC1 prompts not unique')
    require(not {r['input'] for r in tr_rows} & {r['input'] for r in va_rows},
            'RC1 exact train/valid prompt leakage')
    generators = Counter(r['metadata']['generator_id'] for r in all_rows)
    require(len(generators) == 81 and set(generators.values()) == {100}, 'RC1 generator distribution')
    require(Counter(r['metadata']['generator_id'] for r in tr_rows) == Counter({g: 95 for g in generators}),
            'RC1 train distribution')
    require(Counter(r['metadata']['generator_id'] for r in va_rows) == Counter({g: 5 for g in generators}),
            'RC1 validation distribution')
    for split, rows in [('train', tr_rows), ('validation', va_rows)]:
        _, q_rows = load_lines(stage / f'data/{split}.jsonl')
        require(len(q_rows) == len(rows), f'Wrong Qwen {split} row count')
        source_pairs = Counter((r['input'], r['output']) for r in rows)
        q_pairs = Counter((r['messages'][1]['content'], r['messages'][2]['content']) for r in q_rows)
        require(source_pairs == q_pairs, f'RC1 Qwen/source {split} misalignment')
        require(all([m.get('role') for m in q['messages']] == ['system', 'user', 'assistant']
                    for q in q_rows), f'Invalid Qwen message roles in {split}')
    require(len(ledger) == 17 and len(edited) == 17, 'Must change exactly 17 source records')
    orig_by_prompt = {r['input']: r for r in originals['all']}
    changed_count = 0
    for i, (old_row, new_row) in enumerate(zip(originals['all'], all_rows), 1):
        if old_row == new_row:
            continue
        changed_count += 1
        require(old_row['input'] in edited, f'Unexpected changed row at {i}')
        require(new_row == edited[old_row['input']][1], f'Wrong replacement at {i}')
        require(new_row['metadata']['prompt_sha1'] == hashlib.sha1(new_row['input'].encode()).hexdigest(),
                f'Stale prompt_sha1 at {i}')
    require(changed_count == 17, f'Wrong changed structured record count: {changed_count}')
    # Every untouched structured row must be identical in content to frozen V5.
    source_line_map = {r['input']: r for r in all_rows}
    for prompt, original in orig_by_prompt.items():
        if prompt not in edited:
            require(source_line_map.get(prompt) == original, 'Unexpected change to unaffected row')
    # Each corrected category has the intended new interpretation.
    counts = Counter()
    for item in ledger:
        row = edited[item['old_prompt']][1]
        if item['kind'] == 'IPV6_MTU_BELOW_1280':
            m = MSS_PROMPT.fullmatch(row['input'])
            a = MSS_ANSWER.search(row['output'])
            require(m is not None and a is not None, 'Bad corrected MSS format')
            ipver, mtu, ip, tcp = m.groups()
            require(ipver == 'IPv6' and int(mtu) >= 1280, 'Still below IPv6 minimum')
            require(tuple(map(int, a.groups())) == (int(mtu), int(ip), int(tcp), int(mtu)-int(ip)-int(tcp)),
                    'Corrected MSS arithmetic mismatch')
            counts['ipv6_mtu'] += 1
        else:
            require('idealized CPU-time demand' in row['input']
                    and 'overloaded' in row['output'], 'ISR correction missing explanatory language')
            counts['isr_overload'] += 1
    require(counts == Counter({'ipv6_mtu': 9, 'isr_overload': 8}), 'Wrong correction category distribution')
    # Minimal leakage check across candidate release files.
    patterns = [r'/(?:home|Users)/[A-Za-z0-9._-]+/', r'\bhf_[A-Za-z0-9]{20,}\b',
                r'\bgh[pousr]_[A-Za-z0-9]{30,}\b', r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----']
    flags = []
    for file in stage.rglob('*'):
        if not file.is_file():
            continue
        text = file.read_text(encoding='utf-8')
        for pat in patterns:
            if re.search(pat, text):
                flags.append((str(file.relative_to(stage)), pat))
    require(not flags, f'RC1 private-path/token flags: {flags}')
    return {'train': 7695, 'validation': 405, 'total': 8100, 'edited_records': changed_count,
            'unchanged_records': 8083, 'families': 81, 'qwen_structured_pair_matches': 8100,
            'corrections': dict(counts), 'exact_cross_split_prompt_overlap': 0,
            'privacy_pattern_flags': 0}


def build():
    require(not RC1.exists(), f'RC1 already exists, refusing to overwrite: {RC1}')
    require(V1.is_dir(), 'Original V1 release directory missing')
    require(sha(QUAL / 'structured/all.jsonl') == FROZEN_ALL_SHA, 'Frozen V5 SHA mismatch')
    historical = json.loads((QUAL / 'reports/qualification-v5.json').read_text())
    require(historical.get('qualification_complete') is True, 'Historical qualification not complete')
    require(historical.get('protected_eval_used') is False, 'Historical protected eval flag')
    for name, expected in historical['artifact_sha256'].items():
        require(sha(QUAL / name) == expected, f'Frozen artifact hash mismatch: {name}')
    for name, expected in historical['code_sha256'].items():
        require(sha(EXP / name) == expected, f'Original code hash mismatch: {name}')
    origin_manifest = json.loads((V1 / 'RELEASE_MANIFEST.json').read_text())
    for src, dest in COPY_MAP.items():
        require(sha(V1 / dest) == sha(QUAL / src), f'Original V1 release not an exact copy: {dest}')
        require(sha(V1 / dest) == origin_manifest['files_sha256'][dest],
                f'Original V1 release manifest mismatch: {dest}')
    origin_actual = {str(p.relative_to(V1)) for p in V1.rglob('*') if p.is_file()}
    require(origin_actual == ORIGINAL_RELEASE_FILES, f'Unexpected original release files: {origin_actual ^ ORIGINAL_RELEASE_FILES}')
    audit = json.loads(AUDIT_V3.read_text())
    require(audit['dataset_sha256'] == FROZEN_ALL_SHA, 'V3 audit refers to different dataset')
    require(not audit.get('hard_failures'), 'V3 audit has hard failures')
    counts = audit['counts']
    require(counts.get('mss_calculation_correct') == 100 and counts.get('isr_calculation_correct') == 100,
            'V3 audit has incomplete mathematical checks')
    warnings = audit['specification_warnings']
    require(len(warnings) == 17, f'Expected 17 V3 warnings, got {len(warnings)}')
    require(Counter(w['type'] for w in warnings) == Counter({'IPV6_MTU_BELOW_1280': 9,
            'ISR_DEMAND_ABOVE_100_PERCENT': 8}), 'Unexpected V3 warning types')
    require(len({w['source_line'] for w in warnings}) == 17, 'Duplicate warning line')

    _, frozen = load_lines(QUAL / 'structured/all.jsonl')
    _, source_train = load_lines(QUAL / 'structured/train.jsonl')
    _, source_valid = load_lines(QUAL / 'structured/valid.jsonl')
    require(len(frozen) == 8100, 'Unexpected frozen source rows')
    original_split = {r['input']: 'train' for r in source_train}
    original_split.update({r['input']: 'validation' for r in source_valid})
    require(len(original_split) == 8100, 'Original prompt split mapping duplicates')
    by_warning = {w['source_line']: w for w in warnings}
    edited = {}
    ledger = []
    used_prompts = {r['input'] for r in frozen}
    require(len(used_prompts) == 8100, 'Original dataset contains duplicate prompts')
    for line, row in enumerate(frozen, 1):
        warning = by_warning.get(line)
        if warning is None:
            continue
        replacement_mtu = None
        if warning['type'] == 'IPV6_MTU_BELOW_1280':
            # Preserve uniqueness across the entire original corpus AND all new RC1 prompts.
            # Prefer byte-aligned, valid MTUs. The first viable candidate is deterministic.
            mss = MSS_PROMPT.fullmatch(row['input'])
            require(mss is not None, f'MSS prompt unparsable at {line}')
            version, old_mtu, ip, tcp = mss.groups()
            require(version == 'IPv6', f'Wrong protocol at {line}')
            for candidate in range(1280, 9217, 8):
                proposed = row['input'].replace(f'IPv6 MTU {old_mtu} bytes',
                                                f'IPv6 MTU {candidate} bytes', 1)
                if proposed not in used_prompts:
                    replacement_mtu = candidate
                    break
            require(replacement_mtu is not None, f'No collision-free valid MTU at {line}')
        corrected = edit_record(row, warning, line, replacement_mtu)
        require(corrected['input'] not in used_prompts,
                f'Corrected prompt would collide at {line}')
        used_prompts.add(corrected['input'])
        require(corrected['input'] != row['input'] and corrected['output'] != row['output'],
                f'Both prompt and reference must change at {line}')
        require(row['input'] not in edited, 'Duplicate corrected prompt')
        edited[row['input']] = (row, corrected)
        ledger.append({
            'source_line': line, 'split': original_split[row['input']],
            'generator_id': row['metadata']['generator_id'], 'kind': warning['type'],
            'old_prompt': row['input'], 'new_prompt': corrected['input'],
            'old_answer': row['output'], 'new_answer': corrected['output'],
            'chosen_replacement_ipv6_mtu': replacement_mtu,
            'old_record_sha256': sha_bytes(json_bytes(row)),
            'new_record_sha256': sha_bytes(json_bytes(corrected)),
            'reason': warning['detail'],
        })
    require(len(edited) == 17, 'Not exactly 17 corrected records')
    tmp = Path(tempfile.mkdtemp(prefix='.ce-v1-rc1-build-', dir=HOME))
    try:
        for file in V1.rglob('*'):
            if file.is_file():
                relative = file.relative_to(V1)
                target = tmp / relative
                target.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(file, target)
        (tmp / 'scripts').mkdir(exist_ok=True)
        shutil.copyfile(Path(__file__).resolve(), tmp / 'scripts/ce_v1_build_rc1.py')
        (tmp / 'audits').mkdir(exist_ok=True)
        shutil.copyfile(AUDIT_V3, tmp / 'audits/family-risk-audit-v3.json')
        touched = {}
        for file in ('source/all.jsonl', 'source/train.jsonl', 'source/validation.jsonl',
                     'data/train.jsonl', 'data/validation.jsonl'):
            touched[file] = apply_file(tmp / file, edited)
        require(touched['source/all.jsonl'] == set(edited), 'Not all 17 corrections found in full source')
        require(touched['source/train.jsonl'] | touched['source/validation.jsonl'] == set(edited),
                'Split corrections incomplete')
        require(not touched['source/train.jsonl'] & touched['source/validation.jsonl'],
                'Correction appears in both splits')
        require(touched['data/train.jsonl'] == touched['source/train.jsonl'],
                'Train Qwen corrections mismatch')
        require(touched['data/validation.jsonl'] == touched['source/validation.jsonl'],
                'Validation Qwen corrections mismatch')
        audit_result = verify_stage(tmp, V1, {'all': frozen}, edited, ledger)
        # Keep historical audit and qualification evidence as explicitly historical.
        readme = (tmp / 'README.md').read_text(encoding='utf-8')
        readme = readme.replace('Dataset V1', 'Dataset V1 RC1')
        readme = readme.replace('— V1.0.0', '— V1.0.0-rc1')
        readme += """
## RC1 corrections and verification scope

This release candidate corrects 17 specification issues identified by
an independent targeted family audit: nine below-minimum IPv6 MTU
scenarios and eight ISR overload terminology issues. Replacement MTUs
are chosen deterministically at or above 1280 bytes, without duplicate prompts. The complete
before/after record-level ledger is in `RC1_CORRECTIONS.json`.
The original risk audit and the exact RC1 build script are included under
`audits/` and `scripts/` for release reproducibility.

The `QUALIFICATION_EVIDENCE.json` and earlier `RESEARCH_AUDIT.json`
describe the **original immutable V5 corpus**, not a fresh full
8,100-record semantic certification of RC1. Targeted V3 arithmetic
checks covered the original 200 MSS/ISR examples. Original RTL
qualification reports remain historical; RTL was not rerun here.
Cross-split template similarity remains a significant limitation.
The protected holdout was not accessed. This candidate is not yet
publicly released; license and semantic review are still pending.
"""
        (tmp / 'README.md').write_text(readme, encoding='utf-8')
        write_once(tmp / 'RC1_CORRECTIONS.json', {
            'release': 'v1.0.0-rc1', 'frozen_all_sha256': FROZEN_ALL_SHA,
            'v3_audit_sha256': sha(AUDIT_V3), 'changes': ledger,
            'counts': {'ipv6_mtu_minimum': 9, 'isr_overload_terminology': 8},
            'note': 'Original V5 and private Hugging Face V1 staging are unchanged.',
        })
        write_once(tmp / 'RC1_AUDIT.json', {
            'release': 'v1.0.0-rc1', 'scope': 'structural, paired-message alignment, 17 targeted corrections',
            'derived_from_frozen_v5_all_sha256': FROZEN_ALL_SHA,
            'original_release_manifest_sha256': sha(V1 / 'RELEASE_MANIFEST.json'),
            'original_v3_audit_sha256': sha(AUDIT_V3),
            'checks': audit_result,
            'limitations': [
                'This audit does not establish independent semantic correctness of all 8100 examples.',
                '17 edited records are independently checked by category; 8083 are preserved without text edits.',
                'The 1700 reported RTL behavioral passes belong to original V5, not newly rerun RC1 tests.',
                'Original dataset has high train/validation prompt-template overlap.',
                'RC1 hash scheme is explicitly identified for edited records; original metadata hashes are historical.',
                'No protected holdout was used; no model training or Hugging Face upload performed.',
                'Human license, provenance and paper review remain necessary before public release.',
            ],
        })
        # RC1 manifest is new, not the copied original file. Always created last.
        (tmp / 'RELEASE_MANIFEST.json').unlink()
        output_files = {str(p.relative_to(tmp)): sha(p) for p in tmp.rglob('*') if p.is_file()}
        write_once(tmp / 'RELEASE_MANIFEST.json', {
            'version': 'v1.0.0-rc1', 'examples': 8100, 'train': 7695,
            'validation': 405, 'generator_count': 81, 'modified_examples': 17,
            'unchanged_examples': 8083,
            'frozen_source_all_sha256': FROZEN_ALL_SHA,
            'frozen_qualification_manifest_sha256': sha(QUAL / 'manifest.json'),
            'original_private_v1_manifest_sha256': sha(V1 / 'RELEASE_MANIFEST.json'),
            'file_sha256': output_files,
        })
        require(not RC1.exists(), f'RC1 destination appeared while building: {RC1}')
        os.replace(tmp, RC1)
    except Exception:
        shutil.rmtree(tmp, ignore_errors=True)
        raise
    print('=== EXP-010 V1.0.0-rc1 BUILT (LOCAL ONLY) ===')
    print('Candidate:', RC1)
    print('Frozen V5 SHA256:', FROZEN_ALL_SHA, 'PASS')
    print('Changed structured records: 17 (9 IPv6 MTU, 8 ISR overload language)')
    print('Unchanged source records: 8083')
    print('Qwen train/validation matches: 8100 / 8100')
    print('No exact split overlap; 81 families retained')
    print('Ledger:', RC1 / 'RC1_CORRECTIONS.json')
    print('Audit:', RC1 / 'RC1_AUDIT.json')
    print('Original V5: UNCHANGED | Original V1: UNCHANGED | Hub: UNCHANGED')
    print('PUBLIC RELEASE: BLOCKED pending human review of correction ledger and license.')


def self_test():
    metadata = {'generator_id': 'mss_from_mtu', 'prompt_sha1': '',
                'parameters': {'mtu': 1000}, 'verification': {'mtu': 1000, 'mss': 932}}
    old = {'input': 'For IPv6 MTU 1000 bytes, IP header 40 bytes, and TCP header 28 bytes, compute TCP MSS assuming no other encapsulation.',
           'output': 'MSS = MTU - IP header - TCP header = 1000-40-28 = 932 bytes.', 'metadata': metadata}
    old['metadata']['prompt_sha1'] = hashlib.sha1(old['input'].encode()).hexdigest()
    new = transform_mss(old, 518)
    require(new['metadata']['verification']['mss'] == 1212, 'MSS metadata test')
    require(new['metadata']['parameters']['mtu'] == 1280, 'MTU metadata test')
    require('1280-40-28 = 1212 bytes' in new['output'], 'MSS answer test')
    require(old['metadata']['parameters']['mtu'] == 1000, 'Original mutated')
    old2 = {'input': 'A 8 MHz CPU services an interrupt at 50000 Hz. Each ISR consumes 1811 CPU cycles. Assuming no overlap, compute CPU utilization caused by the ISR.',
            'output': 'Utilization = 50000×1811/(8×10^6) = 11.31875 = 1131.875000%.',
            'metadata': {'generator_id': 'interrupt_cpu_load'}}
    new2 = transform_isr(old2, 797)
    require('idealized CPU-time demand' in new2['input'], 'ISR revised prompt')
    require('overloaded' in new2['output'], 'ISR revised answer')
    require(old2['output'].startswith('Utilization ='), 'Original ISR mutated')
    print('SELF-TEST PASS: IPv6 arithmetic, metadata, ISR overload wording, source immutability')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--self-test', action='store_true', help='Test transformations without touching user files')
    args = parser.parse_args()
    if args.self_test:
        self_test()
    else:
        build()