cds-bench-pr-2-traces / validator.py
eczech's picture
Add Snowball one-shot tool-use follow-up traces to PR #2 archive
1d616e7 verified
Raw History Blame Contribute Delete
7.41 kB
"""Append one audited collection; reuse hash-verified, previously scanned content."""
import hashlib
import importlib.util
import json
import os
import re
import shutil
import tarfile
from collections import Counter
from pathlib import Path
import pyarrow.parquet as pq
HERE=Path(__file__).resolve().parent
ROOT=HERE.parents[1]
BASE=ROOT/'build/hf-traces-pr2'
DELTA=ROOT/'build/hf-traces-pr2-oneshot-delta'
OUT=ROOT/'build/hf-traces-pr2-oneshot-final'
SOURCE=ROOT/'scratch/snowball-v01-oneshot-pilot-20261031-01'
ACCESS=[Path('/Users/eczech/tmp/snowball-serving-20261031-092234/access.json'),Path('/Users/eczech/tmp/snowball-v01-serving-20261031-105439/access.json')]
def read(path):return json.loads(path.read_text())
def digest(path):
with path.open('rb') as file:return hashlib.file_digest(file,'sha256').hexdigest()
assert read(SOURCE/'audit.json')['passed'] and read(SOURCE/'summary.json')['state']=='complete'
assert not OUT.exists() and not DELTA.exists(),'Use a fresh staging directory'
spec=importlib.util.spec_from_file_location('exporter',HERE/'export.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
module.collections=lambda root:[SOURCE]
export=module.Export(ROOT,DELTA,ACCESS)
export.build()
base,delta=read(BASE/'manifest.json'),read(DELTA/'manifest.json')
prior=read(BASE/'validation.json')
assert prior['passed'] and prior['all_exported_text_scanned']
assert set(base['collections']).isdisjoint(delta['collections'])
base_checks=read(BASE/'payload-checksums.json')
for name,check in base_checks.items():
assert digest(BASE/name)==check['sha256'],name
print(json.dumps({'phase':'base-verified','files':len(base_checks)}),flush=True)
OUT.mkdir()
for name in base_checks:
if name.startswith(('data/','archives/')):
target=OUT/name;target.parent.mkdir(parents=True,exist_ok=True);os.link(BASE/name,target)
for file in (DELTA/'data').rglob('*.parquet'):
target=OUT/file.relative_to(DELTA).parent/('oneshot-20261031-'+file.name)
target.parent.mkdir(parents=True,exist_ok=True);os.link(file,target)
for file in (DELTA/'archives').glob('*.tar.gz'):
target=OUT/'archives'/file.name;assert not target.exists();os.link(file,target)
manifest=dict(base)
manifest.update(source_commit=read(SOURCE/'config.json')['source_commit'],snapshot_at=delta['snapshot_at'],
collections=base['collections']+delta['collections'],archives=base['archives']+delta['archives'])
for field in ['row_counts','request_counts_by_model','coverage','redactions']:
manifest[field]=dict(Counter(base[field])+Counter(delta[field]))
manifest['incremental_update']={'base_revision':read(ROOT/'scratch/hf-trace-export-pr2-20261031/publication.json')['revision'],
'base_validation_sha256':digest(BASE/'validation.json'),'all_base_payload_hashes_verified':True,
'new_collection':SOURCE.name,'base_source_text_was_previously_scanned':True}
(OUT/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
export.output,export.report=OUT,manifest
export.card()
with (OUT/'README.md').open('a') as file:
file.write('\nThe latest snapshot adds a separately labeled `one_shot_tool_followup`: 58 fresh Snowball v0.1 pilot attempts with a generic arithmetic tool-use demonstration, plus one unscored preflight. These attempts are excluded from the original full comparison and original pilot ranking. The demonstration, exact API requests and source script are preserved in that collection.\n')
for source,target in [(HERE/'export.py','exporter.py'),(HERE/'incremental.py','incremental-exporter.py'),(HERE/'incremental.py','validator.py')]:
shutil.copyfile(source,OUT/target)
# Independently inspect every new table value and all cross-table IDs.
redactor=module.Redactor(ROOT,ACCESS)
escaped=re.compile(module.PRIVATE_LOCATION.pattern.replace('/',r'\\?/'))
new_tables={}
for name,schema in module.SCHEMAS.items():
rows=[]
for file in (DELTA/'data'/name).glob('*.parquet'):
assert pq.ParquetFile(file).schema_arrow==schema
rows.extend(pq.read_table(file).to_pylist())
for row in rows:
for value in row.values():
if isinstance(value,str):redactor.check(value);assert not escaped.search(value)
assert len(rows)==delta['row_counts'][name]
new_tables[name]=rows
id_column={'requests':'request_id','attempts':'attempt_id','tools':'tool_id','runs':'run_id','artifacts':'artifact_id'}[name]
new_ids=[r[id_column] for r in rows]
assert len(new_ids)==len(set(new_ids))
old_ids=set()
for file in (BASE/'data'/name).glob('*.parquet'):
old_ids.update(pq.read_table(file,columns=[id_column]).column(0).to_pylist())
assert old_ids.isdisjoint(new_ids)
total=sum(pq.ParquetFile(f).metadata.num_rows for f in (OUT/'data'/name).glob('*.parquet'))
assert total==manifest['row_counts'][name]
assert len(new_tables['attempts'])==59
assert len(new_tables['requests'])==73 and len(new_tables['tools'])==14
assert not any(r['included_in_main_comparison'] or r['included_in_pilot'] for r in new_tables['attempts'])
artifacts={r['artifact_id']:r for r in new_tables['artifacts']}
attempts={r['attempt_id'] for r in new_tables['attempts']}
runs={r['run_id'] for r in new_tables['runs']}
for row in new_tables['requests']+new_tables['tools']:
assert row['attempt_id'] in attempts and row['run_id'] in runs
for key in ['request_artifact','response_artifact','sse_artifact','wire_response_artifact','artifact']:
if row.get(key):assert row[key] in artifacts
assert set(artifacts)=={p.relative_to(ROOT).as_posix() for p in SOURCE.rglob('*') if module.allowed(p)}
seen=set();bytes_scanned=0
for archive in delta['archives']:
path=OUT/archive['path'];assert digest(path)==archive['sha256']
with tarfile.open(path,'r:gz') as tar:
for member in tar:
assert member.isfile() and member.name in artifacts
data=tar.extractfile(member).read();row=artifacts[member.name]
assert hashlib.sha256(data).hexdigest()==row['export_sha256']
assert digest(ROOT/member.name)==row['source_sha256']
text=data.decode();redactor.check(text);assert not escaped.search(text)
assert redactor.text((ROOT/member.name).read_text())==text
seen.add(member.name);bytes_scanned+=len(data)
assert seen==set(artifacts)
validation={'passed':True,'all_exported_text_scanned':True,'known_credentials_found':0,
'credential_patterns_found':0,'private_locations_found':0,'row_counts':manifest['row_counts'],
'validation_method':'Every new Parquet value and archive member independently scanned; all new joins, unique IDs, source/export hashes and raw core-file coverage verified. Every reused base payload content hash matches its previously fully scanned validation. No old rows or artifacts are replaced.',
'new_source_text_bytes_scanned':bytes_scanned,'new_rows':delta['row_counts'],
'base_validation_sha256':digest(BASE/'validation.json'),'base_revision':manifest['incremental_update']['base_revision'],
'main_comparison_attempts_unchanged':13040,'new_scored_attempts':58,'new_unscored_preflights':1}
(OUT/'validation.json').write_text(json.dumps(validation,indent=2)+'\n')
(HERE/'incremental-validation.json').write_text(json.dumps(validation,indent=2)+'\n')
print(json.dumps({'phase':'incremental-validated','rows':manifest['row_counts'],'new_rows':delta['row_counts']}),flush=True)