Datasets:
File size: 21,007 Bytes
cc4d2ad | 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 | #!/usr/bin/env python3
"""Validate component transport, provenance, leakage controls and packed tokens."""
from __future__ import annotations
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path
import re
CORE = ('id', 'text', 'group', 'license', 'paper_id', 'split', 'record_type', 'source_url')
MODEL = 'deepseek-v4.1-flash'
COMMIT = '4eaee87548250b2682affda7d05d947c05554bae'
SPLITS = ('train', 'dev', 'test')
def ensure(condition, message):
if not condition:
raise ValueError(message)
def canonical(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
def sha(path):
h = hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def read_jsonl(path):
path = Path(path)
opener = gzip.open if path.suffix == '.gz' else open
with opener(path, 'rt', encoding='utf-8') as f:
return [json.loads(line) for line in f if line.strip()]
def read_json(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def safe_path(root, relative):
ensure(not Path(relative).is_absolute(), 'Absolute manifest/provenance path')
p = (root / relative).resolve()
ensure(p.is_relative_to(root.resolve()), 'Path escapes component root')
return p
def check_parquet(path, expected):
import pyarrow.parquet as pq
table = pq.read_table(path)
ensure(table.column_names == [*CORE, 'metadata_json'], f'Parquet columns: {path}')
ensure(table.num_rows == len(expected), f'Parquet row count: {path}')
for index, (row, original) in enumerate(zip(table.to_pylist(), expected)):
metadata = json.loads(row.pop('metadata_json'))
reconstructed = {**row, **metadata}
ensure(reconstructed == original, f'Parquet mismatch {path}:{index}')
def final_worker_message(log):
final = None
for line in log.read_text(encoding='utf-8', errors='replace').splitlines():
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if event.get('type') in {'message_end', 'turn_end'} and event.get('message', {}).get('role') == 'assistant':
final = event['message']
ensure(final is not None, f'No final worker response: {log}')
ensure(final.get('model') == MODEL and final.get('provider') == 'damn-grok', 'Worker log model/provider')
ensure(final.get('stopReason') in {'stop', 'end_turn'}, 'Worker log did not finish normally')
content = final.get('content', [])
text = content if isinstance(content, str) else ''.join(x.get('text', '') for x in content if x.get('type') == 'text')
text = text.strip()
fence = chr(96) * 3
if text.startswith(fence) and text.endswith(fence):
text = text[len(fence):-len(fence)].strip()
if text.startswith('json'):
text = text[4:].strip()
result = json.loads(text)
return result['papers']
def validate_packed(root, split_records):
import numpy as np
import sentencepiece as spm
packed = root / 'packed'
manifest = read_json(packed / 'manifest.json')
ensure(manifest['format'] == 'mmla-type2-packed-v1', 'Packed format')
ensure(manifest['seq_len'] == 2048, 'Packed sequence length')
tokenizer = (packed / manifest['tokenizer']['path']).resolve()
ensure(tokenizer.is_relative_to(root), 'Tokenizer path escapes component')
ensure(sha(tokenizer) == manifest['tokenizer']['sha256'], 'Tokenizer hash')
sp = spm.SentencePieceProcessor(model_file=str(tokenizer))
ensure((sp.pad_id(), sp.bos_id(), sp.eos_id(), sp.unk_id(), sp.vocab_size()) == (0, 1, 2, 3, 32768), 'Tokenizer IDs')
result = {}
for split in SPLITS:
records = split_records[split]
token_catalog = read_jsonl(packed / f'{split}-records.jsonl')
rows = read_jsonl(packed / f'{split}-rows.jsonl')
ensure([r['id'] for r in records] == [r['id'] for r in token_catalog], f'{split} packed source ordering')
arrays, doc_offsets, stream_start = [], [], 0
for r, entry in zip(records, token_catalog):
tokens = np.asarray([1] + sp.encode(r['text'], out_type=int) + [2], dtype='<i4')
ensure(len(tokens) == entry['tokens'], f'{split} record token count')
ensure(hashlib.sha256(tokens.tobytes()).hexdigest() == entry['token_sha256'], f'{split} record token hash')
ensure(r['paper_id'] == entry['paper_id'], f'{split} record paper ID')
doc_offsets.append((stream_start, stream_start + len(tokens), r['id'], r['paper_id']))
stream_start += len(tokens)
arrays.append(tokens)
stream = np.concatenate(arrays)
del arrays
cursor, doc_index, row_number, labels_count = 0, 0, 0, 0
for shard_index, shard in enumerate(manifest['splits'][split]):
loaded = {}
for name in ('input_ids', 'labels', 'role_ids'):
field = shard['fields'][name]
path = safe_path(packed, field['path'])
ensure(path.stat().st_size == field['bytes'] and sha(path) == field['sha256'], f'Packed file hash/size: {path}')
array = np.load(path, mmap_mode='r', allow_pickle=False)
ensure(array.dtype == np.dtype('int32'), 'Packed dtype')
ensure(list(array.shape) == field['shape'] == [shard['count'], 2048], 'Packed shape')
loaded[name] = array
ensure(np.all(loaded['role_ids'] == 0), 'Nonzero plain-text role')
for shard_row in range(shard['count']):
ensure(row_number < len(rows), 'Missing row attribution')
attribution = rows[row_number]
n = min(2048, len(stream) - cursor)
ensure(n > 0, 'Unexpected all-padding row')
expect_input = np.zeros(2048, dtype=np.int32)
expect_input[:n] = stream[cursor:cursor+n]
expect_labels = np.full(2048, -100, dtype=np.int32)
available = min(n, len(stream) - cursor - 1)
if available > 0:
expect_labels[:available] = stream[cursor+1:cursor+1+available]
expect_labels[expect_labels == 1] = -100
ensure(np.array_equal(loaded['input_ids'][shard_row], expect_input), f'{split} source token mismatch at row {row_number}')
ensure(np.array_equal(loaded['labels'][shard_row], expect_labels), f'{split} label shift/mask mismatch at row {row_number}')
ensure(attribution['row'] == row_number and attribution['shard'] == shard_index and attribution['shard_row'] == shard_row, 'Row location attribution')
ensure(attribution['stream_start'] == cursor and attribution['length'] == n, 'Row stream attribution')
while doc_index < len(doc_offsets) and doc_offsets[doc_index][1] <= cursor:
doc_index += 1
spans = []
k = doc_index
while k < len(doc_offsets) and doc_offsets[k][0] < cursor + n:
start, end, rid, pid = doc_offsets[k]
lo, hi = max(cursor, start), min(cursor+n, end)
if lo < hi:
spans.append({'record_id': rid, 'paper_id': pid,
'row_start': lo-cursor, 'row_end': hi-cursor,
'record_start': lo-start, 'record_end': hi-start})
k += 1
ensure(attribution['segments'] == spans, 'Token source attribution mismatch')
labels_count += int(np.count_nonzero(expect_labels != -100))
cursor += n
row_number += 1
ensure(cursor == len(stream), f'{split} token stream not fully consumed')
ensure(row_number == len(rows), f'{split} extra row attribution')
actual = {'rows': row_number, 'tokens': len(stream), 'loss_bearing_labels': labels_count}
ensure(actual == manifest['statistics'][split], f'{split} packed statistics mismatch')
result[split] = actual
print(f'Validated packed {split}: {row_number} rows, {len(stream)} tokens', flush=True)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--component', type=Path, default=Path('work/staging/openai-math'))
parser.add_argument('--expected-papers', type=int, default=721)
parser.add_argument('--source-root', type=Path, default=Path('/Users/zxy/math'))
parser.add_argument('--skip-source-files', action='store_true', help='Validate transport without local upstream source checkout')
args = parser.parse_args()
root = args.component.resolve()
checks = []
manifest = read_json(root / 'manifest.json')
expected_files = {x['path'] for x in manifest['files']}
actual_files = {p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and p.relative_to(root).as_posix() not in {'manifest.json', 'validation.json'}}
ensure(expected_files == actual_files, f'File manifest coverage mismatch: missing={expected_files-actual_files}, extra={actual_files-expected_files}')
for item in manifest['files']:
path = safe_path(root, item['path'])
ensure(path.stat().st_size == item['bytes'], f'Byte count: {path}')
ensure(sha(path) == item['sha256'], f'File digest: {path}')
checks.append('all_delivered_file_hashes_and_sizes')
inputs = read_jsonl(root / 'worker-inputs.jsonl')
input_by_id = {r['paper_id']: r for r in inputs}
expected = set(input_by_id)
ensure(len(expected) == len(inputs) == args.expected_papers, 'Current paper expected count')
manuscripts = read_jsonl(root / 'audit/manuscripts.jsonl')
status = Counter(x['status'] for x in manuscripts)
ensure(status == {'current': args.expected_papers, 'previous': 27, 'withdrawn': 3}, f'Manuscript status coverage: {status}')
ensure({x['paper_id'] for x in manuscripts if x['status'] == 'current'} == expected, 'Current inventory identity')
checks.append('721_current_27_previous_3_withdrawn_inventory')
workers = read_jsonl(root / 'audit/worker-results.jsonl')
ensure(len(workers) == len({w['paper_id'] for w in workers}) == args.expected_papers, 'Worker unique coverage')
ensure({w['paper_id'] for w in workers} == expected, 'Worker input coverage')
log_results = {}
batch_inputs_cache = {}
for w in workers:
ensure(w.get('model') == MODEL and w.get('provider') == 'damn-grok' and w.get('runner') == 'oh-my-pi', 'Worker identity')
ensure(w['review_scope'] == 'abstract_headings_excerpt', 'Worker review scope')
ensure(w['recommended_action'] in {'keep_source', 'needs_review'}, 'Worker recommendation')
ensure({'not_independently_verified', 'excerpt_review_only'} <= set(w['quality_flags']), 'Worker caveats')
ensure(80 <= len(w['summary'].split()) <= 150, 'Worker summary length')
ensure(hashlib.sha256(canonical(input_by_id[w['paper_id']]).encode()).hexdigest() == w['source_input_sha256'], 'Worker individual input hash')
log = safe_path(root / 'audit/worker-runs', w['log_path'])
ensure(sha(log) == w['log_sha256'], 'Worker log digest')
if str(log) not in log_results:
raw_papers = final_worker_message(log)
ensure(len(raw_papers) == len({p['paper_id'] for p in raw_papers}), 'Worker raw response duplicate IDs')
log_results[str(log)] = {p['paper_id']: p for p in raw_papers}
batch_inputs = read_json(log.parent / 'input.json')
ensure([p['paper_id'] for p in raw_papers] == [p['paper_id'] for p in batch_inputs], 'Worker batch raw response ID order')
ensure(all(p == input_by_id[p['paper_id']] for p in batch_inputs), 'Worker batch input differs from source inputs')
ensure(hashlib.sha256(canonical(batch_inputs).encode()).hexdigest() == w['input_sha256'], 'Worker batch input digest')
batch_inputs_cache[str(log)] = w['input_sha256']
ensure(batch_inputs_cache[str(log)] == w['input_sha256'], 'Worker batch inconsistent digest')
prompt_path = log.parent / f"attempt-{w['attempt']:02d}.prompt.md"
ensure(sha(prompt_path) == w['prompt_sha256'], 'Worker prompt digest')
raw_result = log_results[str(log)][w['paper_id']]
ensure(all(w[k] == raw_result[k] for k in ('paper_id', 'summary', 'topics', 'quality_flags', 'recommended_action', 'review_scope')), 'Worker log/result mismatch')
checks.append('all_721_real_omp_deepseek_responses_and_input_hashes')
source_records = read_jsonl(root / 'data/source-records.jsonl')
source_by_id = {r['id']: r for r in source_records}
ensure(len(source_by_id) == len(source_records), 'Source extraction duplicate IDs')
ensure({r['paper_id'] for r in source_records} == expected, 'Full source paper coverage')
macros = read_jsonl(root / 'data/macro-contexts.jsonl')
macro_ids = {r.get('id') or r.get('macro_context_id') for r in macros}
checked_source_files = {}
for r in source_records:
ensure(r['source_commit'] == COMMIT and COMMIT in r['source_url'], 'Source pinned commit')
ensure(r['license'] == 'Apache-2.0', 'Source license')
ensure(r['verification_status'] == 'unverified_source_claim' and r['lean_verified'] is False, 'Source verification status')
ensure(r['macro_context_id'] in macro_ids, 'Source macro context dangling link')
spans = r['source_spans']
ensure(spans, 'Source record has no source spans')
if not args.skip_source_files:
for span in spans:
path = safe_path(args.source_root, span['path'])
if str(path) not in checked_source_files:
checked_source_files[str(path)] = sha(path)
ensure(checked_source_files[str(path)] == span['sha256'], f'Source span hash: {path}')
ensure(span['start_line'] > 0 and span['end_line'] >= span['start_line'], 'Source line span invalid')
if not args.skip_source_files:
for macro in macros:
for context in macro['contexts']:
path = safe_path(args.source_root, context['source_path'])
if str(path) not in checked_source_files:
checked_source_files[str(path)] = sha(path)
ensure(checked_source_files[str(path)] == context['source_sha256'], 'Macro source file digest')
ensure(context['start_line'] > 0 and context['end_line'] >= context['start_line'], 'Macro context source lines')
for file in read_jsonl(root / 'audit/source-files.jsonl'):
path = safe_path(args.source_root, file['path'])
if str(path) not in checked_source_files:
checked_source_files[str(path)] = sha(path)
ensure(checked_source_files[str(path)] == file['sha256'], 'Source file inventory digest')
ensure(path.stat().st_size == file['bytes'], 'Source file inventory size')
checks.append('source_and_macro_provenance' + ('_local_files' if not args.skip_source_files else '_metadata_only'))
group_splits = read_json(root / 'audit/group-splits.json')
split_records, ids, hashes, paper_groups, seen_groups, family_splits = {}, set(), set(), {}, {}, {}
workers_by_id = {r['paper_id']: r for r in workers}
current_manuscripts = {r['paper_id']: r for r in manuscripts if r['status'] == 'current'}
for split in SPLITS:
rows = read_jsonl(root / f'data/{split}.jsonl.gz')
ensure(rows, f'Empty split {split}')
check_parquet(root / f'data/{split}.parquet', rows)
for r in rows:
ensure(r['split'] == split and group_splits[r['group']] == split, 'Family split assignment')
ensure(r['id'] not in ids, 'Cross-split duplicate ID')
ids.add(r['id'])
digest = hashlib.sha256(r['text'].encode('utf-8')).hexdigest()
ensure(r['text_sha256'] == digest and digest not in hashes, 'Exact text duplicate or digest mismatch')
hashes.add(digest)
original = source_by_id[r['id']]
ensure(all(r[k] == v for k, v in original.items()), 'Source text/provenance changed during packaging')
ensure(r['content_origin'] == 'source_extraction' and r['mathematical_verification'] == 'not_performed', 'Source/AI distinction')
ensure(r['worker_model'] == MODEL, 'Source worker model')
current_flags = current_manuscripts[r['paper_id']].get('extraction_flags', [])
observed_flags = input_by_id[r['paper_id']].get('extraction_flags', [])
ensure(r['current_extraction_flags'] == current_flags, 'Current extraction flags differ from final manuscript audit')
ensure(r['worker_observed_extraction_flags'] == observed_flags, 'Worker-observed extraction flags differ from frozen input')
ensure(r['worker_input_snapshot_differs_from_current'] is (current_flags != observed_flags), 'Worker snapshot flag comparison differs')
ensure(isinstance(r.get('worker_snapshot_note'), str) and bool(r['worker_snapshot_note']), 'Missing worker snapshot scope note')
ensure(all(r['worker_metadata'][k] == workers_by_id[r['paper_id']][k] for k in ('topics', 'quality_flags', 'recommended_action', 'review_scope')), 'Source worker metadata mismatch')
ensure(r['paper_id'] in expected, 'Training includes excluded manuscript')
if r['group'] in seen_groups:
ensure(seen_groups[r['group']] == split, 'Family cross-split leakage')
seen_groups[r['group']] = split
for family in r['family_ids']:
if family in family_splits:
ensure(family_splits[family] == split, 'Catalog family crosses split groups')
family_splits[family] = split
if r['paper_id'] in paper_groups:
ensure(paper_groups[r['paper_id']] == r['group'], 'Paper has multiple split groups')
paper_groups[r['paper_id']] = r['group']
split_records[split] = rows
ensure(set(paper_groups) == expected, 'All 721 papers present after deduplication')
duplicates = read_jsonl(root / 'audit/excluded-duplicates.jsonl')
ensure(ids | {d['excluded_id'] for d in duplicates} == set(source_by_id), 'Dedup audit coverage')
for d in duplicates:
ensure(d['kept_id'] in ids, 'Dedup kept ID absent')
ensure(source_by_id[d['excluded_id']]['text'] == source_by_id[d['kept_id']]['text'], 'Dedup text differs')
checks.append('lossless_jsonl_parquet_and_exact_dedup_audit')
checks.append('connected_family_group_and_paper_split_separation')
checks.append('frozen_worker_observed_flags_and_final_extraction_flags_distinguished')
summaries = read_jsonl(root / 'data/worker-summaries.jsonl')
check_parquet(root / 'data/worker-summaries.parquet', summaries)
ensure({r['paper_id'] for r in summaries} == expected and len(summaries) == args.expected_papers, 'Summary coverage')
for r in summaries:
ensure(r['text'] == workers_by_id[r['paper_id']]['summary'], 'Summary differs from worker')
ensure(r['record_type'] == 'ai_metadata_summary' and r['content_origin'] == 'deepseek_metadata_summary', 'Summary labeling')
ensure(r['split'] == group_splits[r['group']], 'Summary split')
checks.append('separate_ai_metadata_summary_transport')
packed = validate_packed(root, split_records) if (root / 'packed/manifest.json').exists() else {}
if packed:
checks.append('all_packed_tokens_reencoded_source_shift_padding_masks_and_attribution')
stats = read_json(root / 'statistics.json')
ensure(stats['current_papers'] == stats['worker_papers'] == args.expected_papers, 'Statistics coverage')
ensure(stats['source_records'] == sum(len(x) for x in split_records.values()), 'Statistics record count')
ensure(stats['packed'] == packed, 'Statistics packed counts')
report = {'status': 'passed', 'source_commit': COMMIT, 'current_papers': args.expected_papers,
'source_records': stats['source_records'], 'source_files_hashed': len(checked_source_files),
'worker_model': MODEL, 'worker_batches': len(log_results), 'checks': checks, 'packed': packed,
'mathematical_verification': 'not_performed',
'limitations': ['Worker metadata review uses abstracts, headings and bounded excerpts.',
'No theorem correctness assessment or Lean/Comparator compilation.',
'No near-duplicate or Phase 1 overlap assessment.']}
(root / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
|