Irfanuruchi commited on
Commit
d424561
·
verified ·
1 Parent(s): ca64be4

Stage noncommercial V1.0.0: scripts/ce_v1_build_rc1.py

Browse files
Files changed (1) hide show
  1. scripts/ce_v1_build_rc1.py +553 -0
scripts/ce_v1_build_rc1.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a fail-closed, traceable V1.0.0-rc1 dataset candidate.
3
+
4
+ Local only; NEVER changes frozen V5, historical V1, model artifacts, or Hugging Face.
5
+ Requires existing V3 two-family audit with exactly 17 specification warnings and
6
+ 0 hard failures. Adjusts 9 below-minimum IPv6 MTU problems to MTU=1280, and
7
+ clarifies 8 impossible ISR utilization examples as demanded CPU capacity.
8
+
9
+ Usage:
10
+ python ce_v1_build_rc1.py --self-test
11
+ python ce_v1_build_rc1.py
12
+
13
+ No public upload or license assertion. Inspect the ledger before approval.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ from collections import Counter
19
+ from copy import deepcopy
20
+ from decimal import Decimal
21
+ import hashlib
22
+ import json
23
+ import os
24
+ from pathlib import Path
25
+ import re
26
+ import shutil
27
+ import tempfile
28
+
29
+ HOME = Path.home()
30
+ EXP = HOME / 'Projects/qwen3-ce-training/EXP-009-1P7B/cleanroom/EXP-010'
31
+ QUAL = EXP / 'data/exp010-full-data-BQSFdT/v5-qual-8100'
32
+ V1 = HOME / 'qwen3-ce-dataset-v1.0.0-release'
33
+ RC1 = HOME / 'qwen3-ce-dataset-v1.0.0-rc1'
34
+ AUDIT_V3 = HOME / 'qwen3-ce-v1-audit-local/family-risk-audit-v3.json'
35
+ FROZEN_ALL_SHA = 'ac7f3071f9724dad72811fd4264e3780c35d44907cce10c176056afc32bd9729'
36
+ COPY_MAP = {
37
+ 'qwen/train.jsonl': 'data/train.jsonl',
38
+ 'qwen/valid.jsonl': 'data/validation.jsonl',
39
+ 'structured/all.jsonl': 'source/all.jsonl',
40
+ 'structured/train.jsonl': 'source/train.jsonl',
41
+ 'structured/valid.jsonl': 'source/validation.jsonl',
42
+ }
43
+ ORIGINAL_RELEASE_FILES = set(COPY_MAP.values()) | {
44
+ 'README.md', 'RELEASE_MANIFEST.json', 'QUALIFICATION_EVIDENCE.json', 'RESEARCH_AUDIT.json'
45
+ }
46
+ 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\.$')
47
+ MSS_ANSWER = re.compile(r'=\s*(\d+)\s*-\s*(\d+)\s*-\s*(\d+)\s*=\s*(-?\d+)\s*bytes\b')
48
+ 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\.$')
49
+ NUM = r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?'
50
+ ISR_ANSWER = re.compile(r'=\s*(' + NUM + r')\s*=\s*(' + NUM + r')\s*%')
51
+
52
+
53
+ def sha_bytes(b: bytes) -> str:
54
+ return hashlib.sha256(b).hexdigest()
55
+
56
+
57
+ def sha(path: Path) -> str:
58
+ h = hashlib.sha256()
59
+ with path.open('rb') as f:
60
+ for chunk in iter(lambda: f.read(1 << 20), b''):
61
+ h.update(chunk)
62
+ return h.hexdigest()
63
+
64
+
65
+ def json_bytes(obj) -> bytes:
66
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True,
67
+ separators=(',', ':')).encode('utf-8')
68
+
69
+
70
+ def json_canon(row) -> str:
71
+ return json_bytes(row).decode('utf-8')
72
+
73
+
74
+ def require(cond, message):
75
+ if not cond:
76
+ raise ValueError(message)
77
+
78
+
79
+ def load_lines(path: Path):
80
+ lines = path.read_text(encoding='utf-8').splitlines(keepends=True)
81
+ require(lines and all(line.strip() for line in lines), f'Blank/empty JSONL: {path}')
82
+ rows = [json.loads(line) for line in lines]
83
+ require(all(isinstance(r, dict) for r in rows), f'Nonobject JSONL: {path}')
84
+ return lines, rows
85
+
86
+
87
+ def write_once(path: Path, value):
88
+ # Only used in an isolated temporary candidate directory.
89
+ require(not path.exists(), f'Unexpected output file exists: {path}')
90
+ path.parent.mkdir(parents=True, exist_ok=True)
91
+ path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + '\n', encoding='utf-8')
92
+
93
+
94
+ def set_metadata_identity(row: dict, old_row: dict, source_line: int, category: str) -> None:
95
+ old_meta = old_row.get('metadata', {})
96
+ meta = row.get('metadata')
97
+ require(isinstance(meta, dict) and isinstance(old_meta, dict), 'Missing metadata')
98
+ original_prompt_sha = old_meta.get('prompt_sha1')
99
+ computed_old_sha = hashlib.sha1(old_row['input'].encode('utf-8')).hexdigest()
100
+ require(original_prompt_sha in (None, computed_old_sha),
101
+ f'Original prompt hash not canonical, line {source_line}')
102
+ if original_prompt_sha:
103
+ meta['historical_prompt_sha1'] = original_prompt_sha
104
+ meta['prompt_sha1'] = hashlib.sha1(row['input'].encode('utf-8')).hexdigest()
105
+ # Old identity must NOT be passed off as the current text's content hash.
106
+ if 'content_sha256' in meta:
107
+ meta['historical_content_sha256'] = meta.pop('content_sha256')
108
+ meta['content_sha256_scheme'] = 'rc1-v1:sha256(canonical-json:{generator_id,input,output})'
109
+ meta['content_sha256'] = sha_bytes(json_bytes({
110
+ 'generator_id': meta['generator_id'], 'input': row['input'], 'output': row['output']
111
+ }))
112
+ meta['release_correction'] = {
113
+ 'kind': category,
114
+ 'from_frozen_v5_sha256': FROZEN_ALL_SHA,
115
+ 'source_line': source_line,
116
+ 'original_row_sha256': sha_bytes(json_bytes(old_row)),
117
+ 'version': 'v1.0.0-rc1',
118
+ }
119
+
120
+
121
+ def rewrite_mss_metadata(container, old_mtu: int, old_mss: int, new_mtu: int, new_mss: int, loc='metadata'):
122
+ """Replace only numeric old MTU/MSS values in relevant metadata areas.
123
+
124
+ All other numeric values remain byte-for-byte conceptually identical. A numeric
125
+ reference inside an unrecognized string refuses automation rather than guessing.
126
+ """
127
+ if isinstance(container, dict):
128
+ out = {}
129
+ for k, v in container.items():
130
+ out[k] = rewrite_mss_metadata(v, old_mtu, old_mss, new_mtu, new_mss, f'{loc}.{k}')
131
+ return out
132
+ if isinstance(container, list):
133
+ return [rewrite_mss_metadata(v, old_mtu, old_mss, new_mtu, new_mss, f'{loc}[{n}]')
134
+ for n, v in enumerate(container)]
135
+ if isinstance(container, bool):
136
+ return container
137
+ if isinstance(container, (int, float)):
138
+ if container == old_mtu:
139
+ return type(container)(new_mtu)
140
+ if container == old_mss:
141
+ return type(container)(new_mss)
142
+ return container
143
+ if isinstance(container, str):
144
+ # JSON metadata occasionally stores numeric values as decimal strings.
145
+ if container == str(old_mtu):
146
+ return str(new_mtu)
147
+ if container == str(old_mss):
148
+ return str(new_mss)
149
+ # Explicitly block old numbers embedded in descriptions or expressions.
150
+ # Hashes are not part of the metadata subtrees processed here.
151
+ if re.search(rf'(?<!\d)(?:{old_mtu}|{old_mss})(?!\d)', container):
152
+ raise ValueError(f'Stale or ambiguous MSS numeric metadata at {loc}: {container[:120]}')
153
+ return container
154
+
155
+
156
+ def transform_mss(old: dict, source_line: int, replacement_mtu: int = 1280) -> dict:
157
+ prompt, answer = old['input'], old['output']
158
+ m = MSS_PROMPT.fullmatch(prompt)
159
+ a = MSS_ANSWER.search(answer)
160
+ require(m is not None and a is not None, f'MSS format mismatch at {source_line}')
161
+ version, mtu_s, ip_s, tcp_s = m.groups()
162
+ mtu, ip, tcp = int(mtu_s), int(ip_s), int(tcp_s)
163
+ ref_mtu, ref_ip, ref_tcp, ref_mss = map(int, a.groups())
164
+ require(version == 'IPv6' and mtu < 1280, f'Not an IPv6 MTU warning at {source_line}')
165
+ require((ref_mtu, ref_ip, ref_tcp, ref_mss) == (mtu, ip, tcp, mtu-ip-tcp),
166
+ f'Original MSS answer mismatch at {source_line}')
167
+ require(ip == 40 and 20 <= tcp <= 60 and tcp % 4 == 0, f'Invalid header at {source_line}')
168
+ result = deepcopy(old)
169
+ require(1280 <= replacement_mtu <= 9216, f'Out of range MTU {replacement_mtu}')
170
+ new_mtu, new_mss = replacement_mtu, replacement_mtu-ip-tcp
171
+ result['input'] = prompt.replace(f'IPv6 MTU {mtu} bytes', f'IPv6 MTU {new_mtu} bytes', 1)
172
+ # Replace exactly the arithmetic clause found by independently anchored parser.
173
+ result['output'] = (answer[:a.start()] + f'= {new_mtu}-{ip}-{tcp} = {new_mss} bytes' + answer[a.end():])
174
+ meta = result['metadata']
175
+ for field in ('parameters', 'verification'):
176
+ if field in meta:
177
+ meta[field] = rewrite_mss_metadata(meta[field], mtu, mtu-ip-tcp, new_mtu, new_mss, field)
178
+ for field in ('output_contract',):
179
+ if field in meta:
180
+ # Contracts should specify format, not a particular old numerical answer.
181
+ s = json.dumps(meta[field], ensure_ascii=False)
182
+ require(not re.search(rf'(?<!\d)(?:{mtu}|{mtu-ip-tcp})(?!\d)', s),
183
+ f'Contract contains old MSS value at {source_line}')
184
+ set_metadata_identity(result, old, source_line, 'ipv6_mtu_minimum')
185
+ require(str(new_mss) in result['output'], f'New reference missing MSS at {source_line}')
186
+ return result
187
+
188
+
189
+ def transform_isr(old: dict, source_line: int) -> dict:
190
+ prompt, answer = old['input'], old['output']
191
+ m, a = ISR_PROMPT.fullmatch(prompt), ISR_ANSWER.search(answer)
192
+ require(m is not None and a is not None, f'ISR format mismatch at {source_line}')
193
+ mhz, freq, cycles = Decimal(m.group(1)), Decimal(m.group(2)), Decimal(m.group(3))
194
+ demand = freq*cycles/(mhz*Decimal(1000000))
195
+ require(demand > 1, f'Expected overload scenario at {source_line}')
196
+ stated = Decimal(a.group(2))
197
+ # Printed answer may be rounded; relative tolerance 1e-5 of the percentage.
198
+ require(abs(stated-demand*100) <= max(Decimal('0.00001'), demand*Decimal('0.001')),
199
+ f'ISR numeric answer mismatch at {source_line}')
200
+ require(answer.startswith('Utilization ='), f'Unexpected ISR answer prefix at {source_line}')
201
+ result = deepcopy(old)
202
+ result['input'] = prompt.replace(
203
+ 'Assuming no overlap, compute CPU utilization caused by the ISR.',
204
+ 'Ignoring queuing and interrupt interference, compute the idealized CPU-time demand '
205
+ 'as a percentage of one processor. If the demand exceeds 100%, identify the '
206
+ 'workload as overloaded rather than claiming achievable sustained CPU utilization.'
207
+ )
208
+ require(result['input'] != prompt, 'ISR prompt did not change')
209
+ result['output'] = answer.replace('Utilization =', 'Idealized CPU-time demand =', 1).rstrip()
210
+ result['output'] += (' This exceeds 100% of one processor: the workload is overloaded, '
211
+ 'and this is demanded capacity, not attainable sustained CPU utilization.')
212
+ set_metadata_identity(result, old, source_line, 'isr_overload_terminology')
213
+ return result
214
+
215
+
216
+ def edit_record(old: dict, warning: dict, source_line: int, replacement_mtu: int | None = None) -> dict:
217
+ require(warning['source_line'] == source_line, f'Wrong line for {source_line}')
218
+ require(warning['prompt'] == old['input'], f'Original prompt mismatch at {source_line}')
219
+ require(warning['reference_answer'] == old['output'], f'Original reference mismatch at {source_line}')
220
+ kind, gid = warning['type'], old['metadata']['generator_id']
221
+ if kind == 'IPV6_MTU_BELOW_1280':
222
+ require(gid == 'mss_from_mtu', f'Wrong generator for {kind}')
223
+ require(replacement_mtu is not None, 'Missing deterministic IPv6 replacement MTU')
224
+ return transform_mss(old, source_line, replacement_mtu)
225
+ if kind == 'ISR_DEMAND_ABOVE_100_PERCENT':
226
+ require(gid == 'interrupt_cpu_load', f'Wrong generator for {kind}')
227
+ return transform_isr(old, source_line)
228
+ raise ValueError(f'Unrecognized risk category: {kind}')
229
+
230
+
231
+ def apply_file(stage_file: Path, changes_by_prompt: dict):
232
+ old_lines, rows = load_lines(stage_file)
233
+ output_lines = []
234
+ touched = set()
235
+ for line, row in zip(old_lines, rows):
236
+ old_prompt = row['input'] if 'input' in row else row['messages'][1]['content']
237
+ if old_prompt not in changes_by_prompt:
238
+ output_lines.append(line)
239
+ continue
240
+ require(old_prompt not in touched, f'Duplicate prompt in {stage_file}: {old_prompt[:100]}')
241
+ old_row, corrected = changes_by_prompt[old_prompt]
242
+ if 'input' in row:
243
+ require(json_canon(row) == json_canon(old_row),
244
+ f'Split record differs from full original: {stage_file}')
245
+ new_row = corrected
246
+ else:
247
+ msgs = row['messages']
248
+ require([m.get('role') for m in msgs] == ['system', 'user', 'assistant'],
249
+ f'Invalid Qwen roles {stage_file}')
250
+ require(msgs[2]['content'] == old_row['output'],
251
+ f'Qwen assistant differs from source at {stage_file}')
252
+ new_row = deepcopy(row)
253
+ new_row['messages'][1]['content'] = corrected['input']
254
+ new_row['messages'][2]['content'] = corrected['output']
255
+ output_lines.append(json.dumps(new_row, ensure_ascii=False) + '\n')
256
+ touched.add(old_prompt)
257
+ stage_file.write_text(''.join(output_lines), encoding='utf-8')
258
+ return touched
259
+
260
+
261
+ def canonical_rows(rows):
262
+ return Counter(json_canon(r) for r in rows)
263
+
264
+
265
+ def verify_stage(stage: Path, old: Path, originals: dict, edited: dict, ledger: list):
266
+ all_lines, all_rows = load_lines(stage / 'source/all.jsonl')
267
+ _, tr_rows = load_lines(stage / 'source/train.jsonl')
268
+ _, va_rows = load_lines(stage / 'source/validation.jsonl')
269
+ require((len(all_rows), len(tr_rows), len(va_rows)) == (8100, 7695, 405), 'RC1 wrong row counts')
270
+ require(canonical_rows(tr_rows) + canonical_rows(va_rows) == canonical_rows(all_rows),
271
+ 'RC1 train+validation does not equal full')
272
+ require(len({r['input'] for r in all_rows}) == 8100, 'RC1 prompts not unique')
273
+ require(not {r['input'] for r in tr_rows} & {r['input'] for r in va_rows},
274
+ 'RC1 exact train/valid prompt leakage')
275
+ generators = Counter(r['metadata']['generator_id'] for r in all_rows)
276
+ require(len(generators) == 81 and set(generators.values()) == {100}, 'RC1 generator distribution')
277
+ require(Counter(r['metadata']['generator_id'] for r in tr_rows) == Counter({g: 95 for g in generators}),
278
+ 'RC1 train distribution')
279
+ require(Counter(r['metadata']['generator_id'] for r in va_rows) == Counter({g: 5 for g in generators}),
280
+ 'RC1 validation distribution')
281
+ for split, rows in [('train', tr_rows), ('validation', va_rows)]:
282
+ _, q_rows = load_lines(stage / f'data/{split}.jsonl')
283
+ require(len(q_rows) == len(rows), f'Wrong Qwen {split} row count')
284
+ source_pairs = Counter((r['input'], r['output']) for r in rows)
285
+ q_pairs = Counter((r['messages'][1]['content'], r['messages'][2]['content']) for r in q_rows)
286
+ require(source_pairs == q_pairs, f'RC1 Qwen/source {split} misalignment')
287
+ require(all([m.get('role') for m in q['messages']] == ['system', 'user', 'assistant']
288
+ for q in q_rows), f'Invalid Qwen message roles in {split}')
289
+ require(len(ledger) == 17 and len(edited) == 17, 'Must change exactly 17 source records')
290
+ orig_by_prompt = {r['input']: r for r in originals['all']}
291
+ changed_count = 0
292
+ for i, (old_row, new_row) in enumerate(zip(originals['all'], all_rows), 1):
293
+ if old_row == new_row:
294
+ continue
295
+ changed_count += 1
296
+ require(old_row['input'] in edited, f'Unexpected changed row at {i}')
297
+ require(new_row == edited[old_row['input']][1], f'Wrong replacement at {i}')
298
+ require(new_row['metadata']['prompt_sha1'] == hashlib.sha1(new_row['input'].encode()).hexdigest(),
299
+ f'Stale prompt_sha1 at {i}')
300
+ require(changed_count == 17, f'Wrong changed structured record count: {changed_count}')
301
+ # Every untouched structured row must be identical in content to frozen V5.
302
+ source_line_map = {r['input']: r for r in all_rows}
303
+ for prompt, original in orig_by_prompt.items():
304
+ if prompt not in edited:
305
+ require(source_line_map.get(prompt) == original, 'Unexpected change to unaffected row')
306
+ # Each corrected category has the intended new interpretation.
307
+ counts = Counter()
308
+ for item in ledger:
309
+ row = edited[item['old_prompt']][1]
310
+ if item['kind'] == 'IPV6_MTU_BELOW_1280':
311
+ m = MSS_PROMPT.fullmatch(row['input'])
312
+ a = MSS_ANSWER.search(row['output'])
313
+ require(m is not None and a is not None, 'Bad corrected MSS format')
314
+ ipver, mtu, ip, tcp = m.groups()
315
+ require(ipver == 'IPv6' and int(mtu) >= 1280, 'Still below IPv6 minimum')
316
+ require(tuple(map(int, a.groups())) == (int(mtu), int(ip), int(tcp), int(mtu)-int(ip)-int(tcp)),
317
+ 'Corrected MSS arithmetic mismatch')
318
+ counts['ipv6_mtu'] += 1
319
+ else:
320
+ require('idealized CPU-time demand' in row['input']
321
+ and 'overloaded' in row['output'], 'ISR correction missing explanatory language')
322
+ counts['isr_overload'] += 1
323
+ require(counts == Counter({'ipv6_mtu': 9, 'isr_overload': 8}), 'Wrong correction category distribution')
324
+ # Minimal leakage check across candidate release files.
325
+ patterns = [r'/(?:home|Users)/[A-Za-z0-9._-]+/', r'\bhf_[A-Za-z0-9]{20,}\b',
326
+ r'\bgh[pousr]_[A-Za-z0-9]{30,}\b', r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----']
327
+ flags = []
328
+ for file in stage.rglob('*'):
329
+ if not file.is_file():
330
+ continue
331
+ text = file.read_text(encoding='utf-8')
332
+ for pat in patterns:
333
+ if re.search(pat, text):
334
+ flags.append((str(file.relative_to(stage)), pat))
335
+ require(not flags, f'RC1 private-path/token flags: {flags}')
336
+ return {'train': 7695, 'validation': 405, 'total': 8100, 'edited_records': changed_count,
337
+ 'unchanged_records': 8083, 'families': 81, 'qwen_structured_pair_matches': 8100,
338
+ 'corrections': dict(counts), 'exact_cross_split_prompt_overlap': 0,
339
+ 'privacy_pattern_flags': 0}
340
+
341
+
342
+ def build():
343
+ require(not RC1.exists(), f'RC1 already exists, refusing to overwrite: {RC1}')
344
+ require(V1.is_dir(), 'Original V1 release directory missing')
345
+ require(sha(QUAL / 'structured/all.jsonl') == FROZEN_ALL_SHA, 'Frozen V5 SHA mismatch')
346
+ historical = json.loads((QUAL / 'reports/qualification-v5.json').read_text())
347
+ require(historical.get('qualification_complete') is True, 'Historical qualification not complete')
348
+ require(historical.get('protected_eval_used') is False, 'Historical protected eval flag')
349
+ for name, expected in historical['artifact_sha256'].items():
350
+ require(sha(QUAL / name) == expected, f'Frozen artifact hash mismatch: {name}')
351
+ for name, expected in historical['code_sha256'].items():
352
+ require(sha(EXP / name) == expected, f'Original code hash mismatch: {name}')
353
+ origin_manifest = json.loads((V1 / 'RELEASE_MANIFEST.json').read_text())
354
+ for src, dest in COPY_MAP.items():
355
+ require(sha(V1 / dest) == sha(QUAL / src), f'Original V1 release not an exact copy: {dest}')
356
+ require(sha(V1 / dest) == origin_manifest['files_sha256'][dest],
357
+ f'Original V1 release manifest mismatch: {dest}')
358
+ origin_actual = {str(p.relative_to(V1)) for p in V1.rglob('*') if p.is_file()}
359
+ require(origin_actual == ORIGINAL_RELEASE_FILES, f'Unexpected original release files: {origin_actual ^ ORIGINAL_RELEASE_FILES}')
360
+ audit = json.loads(AUDIT_V3.read_text())
361
+ require(audit['dataset_sha256'] == FROZEN_ALL_SHA, 'V3 audit refers to different dataset')
362
+ require(not audit.get('hard_failures'), 'V3 audit has hard failures')
363
+ counts = audit['counts']
364
+ require(counts.get('mss_calculation_correct') == 100 and counts.get('isr_calculation_correct') == 100,
365
+ 'V3 audit has incomplete mathematical checks')
366
+ warnings = audit['specification_warnings']
367
+ require(len(warnings) == 17, f'Expected 17 V3 warnings, got {len(warnings)}')
368
+ require(Counter(w['type'] for w in warnings) == Counter({'IPV6_MTU_BELOW_1280': 9,
369
+ 'ISR_DEMAND_ABOVE_100_PERCENT': 8}), 'Unexpected V3 warning types')
370
+ require(len({w['source_line'] for w in warnings}) == 17, 'Duplicate warning line')
371
+
372
+ _, frozen = load_lines(QUAL / 'structured/all.jsonl')
373
+ _, source_train = load_lines(QUAL / 'structured/train.jsonl')
374
+ _, source_valid = load_lines(QUAL / 'structured/valid.jsonl')
375
+ require(len(frozen) == 8100, 'Unexpected frozen source rows')
376
+ original_split = {r['input']: 'train' for r in source_train}
377
+ original_split.update({r['input']: 'validation' for r in source_valid})
378
+ require(len(original_split) == 8100, 'Original prompt split mapping duplicates')
379
+ by_warning = {w['source_line']: w for w in warnings}
380
+ edited = {}
381
+ ledger = []
382
+ used_prompts = {r['input'] for r in frozen}
383
+ require(len(used_prompts) == 8100, 'Original dataset contains duplicate prompts')
384
+ for line, row in enumerate(frozen, 1):
385
+ warning = by_warning.get(line)
386
+ if warning is None:
387
+ continue
388
+ replacement_mtu = None
389
+ if warning['type'] == 'IPV6_MTU_BELOW_1280':
390
+ # Preserve uniqueness across the entire original corpus AND all new RC1 prompts.
391
+ # Prefer byte-aligned, valid MTUs. The first viable candidate is deterministic.
392
+ mss = MSS_PROMPT.fullmatch(row['input'])
393
+ require(mss is not None, f'MSS prompt unparsable at {line}')
394
+ version, old_mtu, ip, tcp = mss.groups()
395
+ require(version == 'IPv6', f'Wrong protocol at {line}')
396
+ for candidate in range(1280, 9217, 8):
397
+ proposed = row['input'].replace(f'IPv6 MTU {old_mtu} bytes',
398
+ f'IPv6 MTU {candidate} bytes', 1)
399
+ if proposed not in used_prompts:
400
+ replacement_mtu = candidate
401
+ break
402
+ require(replacement_mtu is not None, f'No collision-free valid MTU at {line}')
403
+ corrected = edit_record(row, warning, line, replacement_mtu)
404
+ require(corrected['input'] not in used_prompts,
405
+ f'Corrected prompt would collide at {line}')
406
+ used_prompts.add(corrected['input'])
407
+ require(corrected['input'] != row['input'] and corrected['output'] != row['output'],
408
+ f'Both prompt and reference must change at {line}')
409
+ require(row['input'] not in edited, 'Duplicate corrected prompt')
410
+ edited[row['input']] = (row, corrected)
411
+ ledger.append({
412
+ 'source_line': line, 'split': original_split[row['input']],
413
+ 'generator_id': row['metadata']['generator_id'], 'kind': warning['type'],
414
+ 'old_prompt': row['input'], 'new_prompt': corrected['input'],
415
+ 'old_answer': row['output'], 'new_answer': corrected['output'],
416
+ 'chosen_replacement_ipv6_mtu': replacement_mtu,
417
+ 'old_record_sha256': sha_bytes(json_bytes(row)),
418
+ 'new_record_sha256': sha_bytes(json_bytes(corrected)),
419
+ 'reason': warning['detail'],
420
+ })
421
+ require(len(edited) == 17, 'Not exactly 17 corrected records')
422
+ tmp = Path(tempfile.mkdtemp(prefix='.ce-v1-rc1-build-', dir=HOME))
423
+ try:
424
+ for file in V1.rglob('*'):
425
+ if file.is_file():
426
+ relative = file.relative_to(V1)
427
+ target = tmp / relative
428
+ target.parent.mkdir(parents=True, exist_ok=True)
429
+ shutil.copyfile(file, target)
430
+ (tmp / 'scripts').mkdir(exist_ok=True)
431
+ shutil.copyfile(Path(__file__).resolve(), tmp / 'scripts/ce_v1_build_rc1.py')
432
+ (tmp / 'audits').mkdir(exist_ok=True)
433
+ shutil.copyfile(AUDIT_V3, tmp / 'audits/family-risk-audit-v3.json')
434
+ touched = {}
435
+ for file in ('source/all.jsonl', 'source/train.jsonl', 'source/validation.jsonl',
436
+ 'data/train.jsonl', 'data/validation.jsonl'):
437
+ touched[file] = apply_file(tmp / file, edited)
438
+ require(touched['source/all.jsonl'] == set(edited), 'Not all 17 corrections found in full source')
439
+ require(touched['source/train.jsonl'] | touched['source/validation.jsonl'] == set(edited),
440
+ 'Split corrections incomplete')
441
+ require(not touched['source/train.jsonl'] & touched['source/validation.jsonl'],
442
+ 'Correction appears in both splits')
443
+ require(touched['data/train.jsonl'] == touched['source/train.jsonl'],
444
+ 'Train Qwen corrections mismatch')
445
+ require(touched['data/validation.jsonl'] == touched['source/validation.jsonl'],
446
+ 'Validation Qwen corrections mismatch')
447
+ audit_result = verify_stage(tmp, V1, {'all': frozen}, edited, ledger)
448
+ # Keep historical audit and qualification evidence as explicitly historical.
449
+ readme = (tmp / 'README.md').read_text(encoding='utf-8')
450
+ readme = readme.replace('Dataset V1', 'Dataset V1 RC1')
451
+ readme = readme.replace('— V1.0.0', '— V1.0.0-rc1')
452
+ readme += """
453
+ ## RC1 corrections and verification scope
454
+
455
+ This release candidate corrects 17 specification issues identified by
456
+ an independent targeted family audit: nine below-minimum IPv6 MTU
457
+ scenarios and eight ISR overload terminology issues. Replacement MTUs
458
+ are chosen deterministically at or above 1280 bytes, without duplicate prompts. The complete
459
+ before/after record-level ledger is in `RC1_CORRECTIONS.json`.
460
+ The original risk audit and the exact RC1 build script are included under
461
+ `audits/` and `scripts/` for release reproducibility.
462
+
463
+ The `QUALIFICATION_EVIDENCE.json` and earlier `RESEARCH_AUDIT.json`
464
+ describe the **original immutable V5 corpus**, not a fresh full
465
+ 8,100-record semantic certification of RC1. Targeted V3 arithmetic
466
+ checks covered the original 200 MSS/ISR examples. Original RTL
467
+ qualification reports remain historical; RTL was not rerun here.
468
+ Cross-split template similarity remains a significant limitation.
469
+ The protected holdout was not accessed. This candidate is not yet
470
+ publicly released; license and semantic review are still pending.
471
+ """
472
+ (tmp / 'README.md').write_text(readme, encoding='utf-8')
473
+ write_once(tmp / 'RC1_CORRECTIONS.json', {
474
+ 'release': 'v1.0.0-rc1', 'frozen_all_sha256': FROZEN_ALL_SHA,
475
+ 'v3_audit_sha256': sha(AUDIT_V3), 'changes': ledger,
476
+ 'counts': {'ipv6_mtu_minimum': 9, 'isr_overload_terminology': 8},
477
+ 'note': 'Original V5 and private Hugging Face V1 staging are unchanged.',
478
+ })
479
+ write_once(tmp / 'RC1_AUDIT.json', {
480
+ 'release': 'v1.0.0-rc1', 'scope': 'structural, paired-message alignment, 17 targeted corrections',
481
+ 'derived_from_frozen_v5_all_sha256': FROZEN_ALL_SHA,
482
+ 'original_release_manifest_sha256': sha(V1 / 'RELEASE_MANIFEST.json'),
483
+ 'original_v3_audit_sha256': sha(AUDIT_V3),
484
+ 'checks': audit_result,
485
+ 'limitations': [
486
+ 'This audit does not establish independent semantic correctness of all 8100 examples.',
487
+ '17 edited records are independently checked by category; 8083 are preserved without text edits.',
488
+ 'The 1700 reported RTL behavioral passes belong to original V5, not newly rerun RC1 tests.',
489
+ 'Original dataset has high train/validation prompt-template overlap.',
490
+ 'RC1 hash scheme is explicitly identified for edited records; original metadata hashes are historical.',
491
+ 'No protected holdout was used; no model training or Hugging Face upload performed.',
492
+ 'Human license, provenance and paper review remain necessary before public release.',
493
+ ],
494
+ })
495
+ # RC1 manifest is new, not the copied original file. Always created last.
496
+ (tmp / 'RELEASE_MANIFEST.json').unlink()
497
+ output_files = {str(p.relative_to(tmp)): sha(p) for p in tmp.rglob('*') if p.is_file()}
498
+ write_once(tmp / 'RELEASE_MANIFEST.json', {
499
+ 'version': 'v1.0.0-rc1', 'examples': 8100, 'train': 7695,
500
+ 'validation': 405, 'generator_count': 81, 'modified_examples': 17,
501
+ 'unchanged_examples': 8083,
502
+ 'frozen_source_all_sha256': FROZEN_ALL_SHA,
503
+ 'frozen_qualification_manifest_sha256': sha(QUAL / 'manifest.json'),
504
+ 'original_private_v1_manifest_sha256': sha(V1 / 'RELEASE_MANIFEST.json'),
505
+ 'file_sha256': output_files,
506
+ })
507
+ require(not RC1.exists(), f'RC1 destination appeared while building: {RC1}')
508
+ os.replace(tmp, RC1)
509
+ except Exception:
510
+ shutil.rmtree(tmp, ignore_errors=True)
511
+ raise
512
+ print('=== EXP-010 V1.0.0-rc1 BUILT (LOCAL ONLY) ===')
513
+ print('Candidate:', RC1)
514
+ print('Frozen V5 SHA256:', FROZEN_ALL_SHA, 'PASS')
515
+ print('Changed structured records: 17 (9 IPv6 MTU, 8 ISR overload language)')
516
+ print('Unchanged source records: 8083')
517
+ print('Qwen train/validation matches: 8100 / 8100')
518
+ print('No exact split overlap; 81 families retained')
519
+ print('Ledger:', RC1 / 'RC1_CORRECTIONS.json')
520
+ print('Audit:', RC1 / 'RC1_AUDIT.json')
521
+ print('Original V5: UNCHANGED | Original V1: UNCHANGED | Hub: UNCHANGED')
522
+ print('PUBLIC RELEASE: BLOCKED pending human review of correction ledger and license.')
523
+
524
+
525
+ def self_test():
526
+ metadata = {'generator_id': 'mss_from_mtu', 'prompt_sha1': '',
527
+ 'parameters': {'mtu': 1000}, 'verification': {'mtu': 1000, 'mss': 932}}
528
+ old = {'input': 'For IPv6 MTU 1000 bytes, IP header 40 bytes, and TCP header 28 bytes, compute TCP MSS assuming no other encapsulation.',
529
+ 'output': 'MSS = MTU - IP header - TCP header = 1000-40-28 = 932 bytes.', 'metadata': metadata}
530
+ old['metadata']['prompt_sha1'] = hashlib.sha1(old['input'].encode()).hexdigest()
531
+ new = transform_mss(old, 518)
532
+ require(new['metadata']['verification']['mss'] == 1212, 'MSS metadata test')
533
+ require(new['metadata']['parameters']['mtu'] == 1280, 'MTU metadata test')
534
+ require('1280-40-28 = 1212 bytes' in new['output'], 'MSS answer test')
535
+ require(old['metadata']['parameters']['mtu'] == 1000, 'Original mutated')
536
+ 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.',
537
+ 'output': 'Utilization = 50000×1811/(8×10^6) = 11.31875 = 1131.875000%.',
538
+ 'metadata': {'generator_id': 'interrupt_cpu_load'}}
539
+ new2 = transform_isr(old2, 797)
540
+ require('idealized CPU-time demand' in new2['input'], 'ISR revised prompt')
541
+ require('overloaded' in new2['output'], 'ISR revised answer')
542
+ require(old2['output'].startswith('Utilization ='), 'Original ISR mutated')
543
+ print('SELF-TEST PASS: IPv6 arithmetic, metadata, ISR overload wording, source immutability')
544
+
545
+
546
+ if __name__ == '__main__':
547
+ parser = argparse.ArgumentParser()
548
+ parser.add_argument('--self-test', action='store_true', help='Test transformations without touching user files')
549
+ args = parser.parse_args()
550
+ if args.self_test:
551
+ self_test()
552
+ else:
553
+ build()