"""Independent full-row label reconstruction and split audit against pinned originals.""" import json,gzip,hashlib,re,math from pathlib import Path from collections import Counter import pyarrow.parquet as pq R=Path('/home/ubuntu/openjudgment/v4');S=R/'sources';cache={};checks=Counter();ids=set();groups={};states={} def load(repo,config,split): key=(repo,config,split) if key in cache:return cache[key] p=S/repo.replace('/','--') if repo=='nvidia/HelpSteer3': with gzip.open(p/config/(split+'.jsonl.gz'),'rt') as f:data=[json.loads(l) for l in f] elif repo=='nvidia/Aegis-AI-Content-Safety-Dataset-2.0':data=json.loads((p/(split+'.json')).read_text()) elif repo=='rabuahmad/climatecheck':data=pq.read_table(p/'data'/(split+'-00000-of-00001.parquet')).to_pylist() elif repo=='openai/coval':data=[json.loads(l) for l in (p/'comparisons.jsonl').read_text().splitlines()] else:data=[json.loads(l) for l in (p/'benchmark_v1_splits.jsonl').read_text().splitlines()] cache[key]=data;return data for path in sorted((R/'corpus').glob('*.parquet')): for batch in pq.ParquetFile(path).iter_batches(batch_size=1024): for row in batch.to_pylist(): checks['rows']+=1;m=json.loads(row['metadata']);repo=row['source'];cfg=m['source_config'];raw=load(repo,cfg,row['source_split'])[m['source_row_index']] assert row['id'] not in ids;ids.add(row['id']) for label,seen in [('group_hash',groups),('state_hash',states)]: assert row[label] not in seen or seen[row[label]]==path.stem seen[row[label]]=path.stem assert row['split']==path.stem if path.stem=='train':assert row['source_split']=='train' for t in row['target']:assert math.isfinite(t) and 0<=t<=1 if row['kind']!='noul':assert abs(sum(row['target'])-1)<1e-7 expected={} if repo=='nvidia/HelpSteer3': state=json.loads(row['state']);context=[dict(role=x['role'],content=x['content'].replace('\r\n','\n').replace('\r','\n')) for x in raw['context']] assert state['context']==context if cfg=='preference': assert set(state)=={'context','response1','response2'} and state['response1']==raw['response1'] and state['response2']==raw['response2'] votes=[x['score'] for x in raw['individual_preference']];assert len(votes)>=2 expected={k:sum((v<0 if k=='response1' else v==0 if k=='tie' else v>0) for v in votes)/len(votes) for k in ['response1','tie','response2']} else: assert set(state)=={'context','response'};number=m['source_response'][-1];assert state['response']==raw['response'+number] feedback=raw['feedback'+number];assert len(feedback)>=2 votes=[] for f in feedback: match=re.match(r'^\s*The response is (not|slightly|partially|mostly|perfectly) helpful\.',f,re.I);assert match votes.append(['not','slightly','partially','mostly','perfectly'].index(match.group(1).lower())) expected={str(i):votes.count(i)/len(votes) for i in range(5)} elif repo=='nvidia/Aegis-AI-Content-Safety-Dataset-2.0': assert raw['prompt_label_source']=='human' and row['state']==raw['prompt'] and not raw.get('reconstruction_id_if_redacted') expected={'true':float(raw['prompt_label']=='unsafe')} elif repo=='rabuahmad/climatecheck': assert json.loads(row['state'])=={'claim':raw['claim'],'evidence':raw['abstract']} mapping={'Supports':'supported','Refutes':'refuted','Not Enough Information':'insufficient'} expected={k:float(k==mapping[raw['annotation']]) for k in ['supported','insufficient','refuted']} elif repo=='KSE-RESEARCH-Group/UAReviews': assert row['source_split']==raw['split'] and row['state']==raw['content'].replace('\r\n','\n').replace('\r','\n') expected={k:float(c==raw['final_category']) for k,c in zip(row['keys'],row['candidates'])} elif repo=='openai/coval': state=json.loads(row['state']);assert state=={'conversation':raw['prompt']['messages'],'responses':{r['response_index']:r['messages'] for r in raw['responses']}} counts=Counter();n=0 for assessment in raw['metadata']['assessments']: blocks=assessment.get('ranking_blocks',{}).get('world',[]) if len(blocks)!=1:continue ranking=''.join(blocks[0].get('ranking','').split());parts=re.split('[>=]',ranking) if len(parts)!=4 or set(parts)!=set('ABCD') or not all(p in 'ABCD' and len(p)==1 for p in parts):continue winners=ranking.split('>')[0].split('=');n+=1 for w in winners:counts[w]+=1/len(winners) assert n>=3;expected={k:counts[k]/n for k in 'ABCD'} else:raise AssertionError(repo) assert all(abs(expected[k]-v)<1e-7 for k,v in zip(row['keys'],row['target'])),row['id'] checks[repo]+=1 print('AUDITED',path.stem,checks['rows'],flush=True) manifest=json.loads((R/'corpus/manifest.json').read_text());assert checks['rows']==manifest['total_rows'] report={'passed':True,'rows':checks['rows'],'by_source':dict(checks),'unique_ids':len(ids),'unique_prompt_groups':len(groups),'cross_split_groups':0,'cross_split_states':0,'target_reconstruction_failures':0,'state_label_leakage_failures':0,'official_evaluation_rows_in_training':0,'scope':'Every emitted target and model-visible state reconstructed independently against pinned original source row. This verifies faithful adaptation, not human annotation truth or semantic near-duplicate freedom.'} (R/'reports/audit.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True)