File size: 16,694 Bytes
a3a7873 | 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 | """Independent V3 validator. Does not import build.py or transformation functions."""
import json,re,html,hashlib,sys,copy,importlib.util
from pathlib import Path
from collections import Counter,defaultdict
from html.parser import HTMLParser
from jsonschema import Draft202012Validator
from huggingface_hub import hf_hub_download
def encoded(x):return json.dumps(x,sort_keys=True,ensure_ascii=False,separators=(',',':'),allow_nan=False)
def digest(x):return hashlib.sha256((x if isinstance(x,str) else encoded(x)).encode()).hexdigest()
def strict(s):
def pairs(xs):
d={}
for k,v in xs:
if k in d:raise ValueError('duplicate JSON key')
d[k]=v
return d
return json.loads(s,object_pairs_hook=pairs,parse_constant=lambda s:(_ for _ in ()).throw(ValueError('nonfinite number')))
def readrows(p):return [strict(s) for s in p.read_text('utf-8').splitlines() if s.strip()]
def require(v,message):
if not v:raise ValueError(message)
def module(path,name):
spec=importlib.util.spec_from_file_location(name,path);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
def originals(folder):
result={};lock=json.loads((folder/'SOURCE_LOCK.json').read_text())
wanted=defaultdict(set)
for r in readrows(folder/'dataset.jsonl'):wanted[r['provenance']['source_dataset']].add(r['provenance']['source_record_id'])
for s in lock:
repo=s['repo_id']
if repo:
p=Path(hf_hub_download(repo,s['data_file'],repo_type='dataset',revision=s['commit']))
expected=s['files']['dataset.jsonl']['sha256'];require(hashlib.sha256(p.read_bytes()).hexdigest()==expected,'source snapshot hash mismatch')
else:p=folder/s['data_file'];repo='RegalFire/'+s['name']
for line in p.open(encoding='utf-8'):
r=strict(line);key=str(r.get('id',r.get('record_id',r.get('thread_id'))))
if key in wanted[repo]:result[(repo,key)]=r
return result
def thread(s):return s.get('thread',s)
def question(s):t=thread(s);return t.get('question_text'),t.get('question_html'),t.get('source_url',t.get('thread_url'))
class Links(HTMLParser):
def __init__(self):super().__init__(convert_charrefs=True);self.urls=[]
def handle_starttag(self,tag,attrs):
if tag=='a':
self.urls.extend(v for k,v in attrs if k=='href' and v and v.startswith(('http://','https://')))
def literal_blocks(body):
result=[]
for raw in re.findall(r'<pre\b[^>]*>(.*?)</pre\s*>',body,re.S|re.I):
raw=re.sub(r'<br\s*/?>','\n',raw,flags=re.I)
result.append(html.unescape(re.sub(r'<[^>]+>','',raw)))
return result
def scientific(r,s):
t=thread(s);text,body,url=question(s);aa=t['answers'];require(r['provenance']['source_url']==url,'thread URL mismatch')
require(r['provenance']['original_provenance']==t['provenance'],'original provenance changed')
require(r['provenance']['revision_attribution']==t['revision_attribution'],'revision contributors changed')
require(r['content_license']==t['question_license']=='CC BY-SA 4.0','question license mismatch')
require(all(a['content_license']=='CC BY-SA 4.0' for a in aa),'answer license not approved')
if r['id'].startswith('SCT'):
require(r['problem_text']==text and r['question_html']==body and r['question_title']==t['title'],'question content changed')
require(bool(r['code_blocks']),'no code')
posts={str(t.get('question_id',t.get('thread_id'))):body,**{str(a['answer_id']):a['answer_html'] for a in aa}}
for b in r['code_blocks']:
source=posts.get(str(b['post_id']),body)
blocks=literal_blocks(source);require(b['block_index']<len(blocks) and b['code_text']==blocks[b['block_index']],'code extraction mismatch')
require(digest(b['code_text'])==b['sha256'],'code hash mismatch')
expected_error=[line.strip() for line in text.splitlines() if re.match(r'^\s*(?:[A-Za-z]+Error:|Error(?: in .*?)?:|Warning:|Traceback \(most recent call last\):)',line)] or None
require(r['error_text_if_explicit']==expected_error,'fabricated error')
if r['attempted_method_if_explicit'] is not None:require(r['attempted_method_if_explicit'] in text and r['attempted_method_if_explicit'].startswith(('I tried ','I attempted ')),'fabricated attempt')
require(r['answer_scores']==[{'answer_id':a['answer_id'],'score':a['score']} for a in aa],'answer scores mismatch')
require(r['author_attribution']['question_author']==t['question_author'] and r['author_attribution']['question_author_url']==t['question_author_url'],'question attribution changed')
answers=r['answers'];accepted=r['accepted_answer']
else:
require(r['query']==t['title']+'\n'+text,'query changed')
expected=[text]+[a['answer_text'] for a in aa]
require([c['text'] for c in r['contexts']]==expected,'context changed')
require(len(r['context_sources'])==len(expected),'missing context attribution')
for c in r['context_sources']:require(c['content_license']=='CC BY-SA 4.0' and c['author'] is not None and 'revision_attribution' in c,'missing attribution')
accepted=next((a for a in aa if a['is_accepted']),None);families=[]
parser=Links();parser.feed(body)
for a in aa:parser.feed(a['answer_html'])
citations=sorted(set(parser.urls));require(r['external_citations']==citations,'citations invented or dropped')
if not accepted:families.append('no_accepted_answer')
if accepted and max(a['score'] for a in aa)>accepted['score']:families.append('accepted_vs_highest_score_disagreement')
if len(citations)>=2:families.append('multiple_sources')
if len(citations)>=5:families.append('citation_heavy')
if len(aa)>=2:families.append('multiple_answer_candidates')
if int(t['question_created_at'][:4])<=2021:families.append('old_thread_metadata')
require(r['hard_case_family']==families,'unsupported family')
require(r['accepted_status']['accepted_answer_id']==(accepted['answer_id'] if accepted else None),'acceptance mismatch')
require(r['ground_truth_type']=='metadata_grounded' and r['oracle']['canonical_answer'] is None and r['accepted_status']['scientific_correctness_verified'] is False,'unsupported scientific truth')
require(r['scores']==[{'answer_id':a['answer_id'],'score':a['score']} for a in aa],'scores mismatch')
answers=r['candidate_answers']
require(len(answers)==len(aa),'answer count mismatch')
for a,b in zip(answers,aa):
for key in ['answer_id','question_id','answer_text','answer_html','content_license','answer_url','score','is_accepted','revision_attribution','provenance']:
require(a[key]==b[key],'answer field mismatch: '+key)
require(a['author']==b.get('author',b.get('author_display_name')) and a['author_url']==b.get('author_url',b.get('author_profile_url')),'answer attribution mismatch')
if r['id'].startswith('SCT'):
expected=next((a for a in answers if a['is_accepted']),None);require(accepted==expected,'accepted answer invented')
def agent(r,s,nav,physics,horizon):
domain=r['domain'];available=True
if domain=='navigation':
nav.nav(s['input'],s['expected']);i=s['input'];before=s['expected']['before'];after=s['expected']['after'];grid=list(i['grid']);y,x=i['edit'];line=list(grid[y]);line[x]='#';grid[y]=''.join(line)
require(i['grid'][y][x]=='.' and i['edit'] in before['path'],'no explicit invalid legacy path')
require(r['initial_state']=={'grid':i['grid'],'costs':i['costs'],'position':i['start']},'initial state mismatch')
failed={'grid':grid,'costs':i['costs'],'position':i['start']};require(r['failure_state']==failed,'failure state mismatch')
require(r['action_history']==[{'action':'submit_path','path':before['path'],'result':'rejected_atomically_blocked_cell','state_unchanged':True}],'history mismatch')
available=after['path'] is not None;seq=after['path'][1:] if available else [];action={'action':'follow_path','path':after['path']} if available else None;final={**failed,'position':i['goal']} if available else failed;cost={'cost':after['cost'],'steps':len(seq) if available else None};failure='legacy_path_blocked_by_critical_edit';goal={'position':i['goal']}
elif domain=='multi_agent':
nav.coord(s['input'],s['expected']);i=s['input'];plan=s['expected']['plan'];available=plan is not None
initial={'grid':i['grid'],'positions':i['starts']};require(r['initial_state']==initial and r['failure_state']==initial,'joint state mismatch')
require(i['starts']!=i['goals'],'stop was not a failure')
require(r['action_history']==[{'action':'stop','result':'rejected_goals_unsatisfied','state_unchanged':True}],'joint history mismatch')
seq=plan[1:] if plan else [];action={'action':'execute_joint_plan','plan':plan} if plan else None;final={'grid':i['grid'],'positions':i['goals']} if plan else initial;cost={'cost':s['expected']['optimal_makespan'],'steps':len(seq) if plan else None};failure='premature_stop_goals_unsatisfied';goal={'positions':i['goals'],'vertex_collision_forbidden':True,'edge_swap_forbidden':True,'absorbing_goals':True}
elif domain=='counterfactual':
truth=physics.truth(s);require(physics.compare(truth,s['expected_state_t1']) and not physics.compare(truth,s['counterfactual_state_t1']),'physics source labels invalid')
require(r['initial_state']=={'state_t0':s['state_t0'],'action':s['action'],'dt':s['dt']},'physics initial mismatch')
require(r['failure_state']=={'predicted_state_t1':s['counterfactual_state_t1']},'physics failure mismatch')
require(r['action_history']==[{'action':'submit_prediction','prediction':s['counterfactual_state_t1'],'result':'rejected_analytical_inconsistency'}],'physics history mismatch')
action={'action':'replace_prediction','prediction':s['expected_state_t1']};seq=[action];final={'predicted_state_t1':s['expected_state_t1']};cost={'cost':1,'steps':1};failure='analytically_inconsistent_'+s['counterfactual_changed_field'];goal={'prediction_matches_analytical_transition':True}
elif domain=='planning':
correct,final=horizon.oracle(s);require(correct==s['optimal_action'] and final==s['expected_state_t1'],'planning source oracle mismatch')
require(r['initial_state']==s['observation']['state'] and r['failure_state']==s['observation']['state'],'planning initial/failure mismatch')
h=r['action_history'];require(len(h)==1 and h[0]['action'] in s['available_actions'] and h[0]['action']!=correct and h[0]['result']=='rejected_policy_mismatch' and h[0]['state_unchanged'] is True,'failure action not a wrong policy action')
action={'action':correct};seq=[action];cost={'cost':1,'steps':1};failure='next_step_policy_mismatch';goal={'short_horizon':s['success_condition'],'full_long_horizon_goal_claimed':False}
else:raise ValueError('unknown agent domain')
require(r['goal']==goal and r['failure_type']==failure,'failure/goal labels mismatch')
require(r['recovery_available'] is available and r['success'] is available,'success/availability mismatch')
require(r['recovery_action']==action and r['recovery_sequence']==seq and r['final_state']==final and r['cost_or_steps']==cost,'recovery trajectory mismatch')
require(r['oracle']['source_family']==s['family'] and r['oracle']['source_input']==s.get('input') and r['oracle']['source_expected']==s.get('expected'),'oracle metadata mismatch')
def validate(folder,records=None):
folder=Path(folder);data=readrows(folder/'dataset.jsonl') if records is None else records
sources=originals(folder);schema=Draft202012Validator(json.loads((folder/'schema.json').read_text()))
vendor=folder/'validator'/'vendor';sys.path.insert(0,str(vendor))
nav=module(vendor/'nav_check.py','nav_check') if (vendor/'nav_check.py').exists() else None
physics=module(vendor/'physics.py','physics') if (vendor/'physics.py').exists() else None
horizon=module(vendor/'horizon.py','horizon') if (vendor/'horizon.py').exists() else None
gcc=module(vendor/'gcc.py','gcc') if (vendor/'gcc.py').exists() else None
ids=set();semantic=set();groups={};templates={};procedural={};textsplits={};errors=[];question_grams=[]
for index,r in enumerate(data):
try:
schema.validate(r);require(r['id'] not in ids,'duplicate id');ids.add(r['id'])
body={k:v for k,v in r.items() if k not in ['id','provenance','group_id','split']};h=digest(body);require(h not in semantic,'exact semantic duplicate');semantic.add(h)
p=r['provenance'];key=(p['source_dataset'],p['source_record_id']);require(key in sources,'missing source relation');s=sources[key];require(digest(s)==p['source_record_sha256'],'source record hash mismatch')
require(r['content_license']==p['source_license'],'license mismatch')
require(groups.setdefault(r['group_id'],r['split'])==r['split'],'group leakage')
if r['id'].startswith('AFR'):
require(templates.setdefault((r['domain'],r['task_type']),r['split'])==r['split'],'template leakage')
if p.get('procedural_group_id'):require(procedural.setdefault(p['procedural_group_id'],r['split'])==r['split'],'procedural grid leakage')
agent(r,s,nav,physics,horizon)
elif p['source_dataset'].endswith('GCC-RAG-HardCases'):
truth=gcc.oracle(s)
require(all(s['expected'][k]==v for k,v in truth.items()),'independent GCC oracle mismatch')
require(r['query']==s['query'] and r['oracle']==s['expected'],'GCC source oracle/query mismatch')
require(r['hard_case_family']==['gcc_'+s['family']] and r['ground_truth_type']=='deterministic_source_grounded','GCC family/truth mismatch')
require([c['text'] for c in r['contexts']]==[d['content'] for d in s['documents']],'GCC context mismatch')
require(r['candidate_answers']==([{'answer_text':s['expected']['answer']}] if s['expected']['answerable'] else []),'GCC answer mismatch')
require(r['external_citations']==[] and len(r['context_sources'])==len(s['documents']) and all(c['synthetic'] and c['content_license']=='MIT' for c in r['context_sources']),'GCC sources/citations invalid')
require(templates.setdefault(s['family'],r['split'])==r['split'],'GCC template leakage')
else:
scientific(r,s)
t=thread(s)
words=re.sub(r'[^\w]+',' ',t['question_text'].lower()).split();grams={tuple(words[j:j+5]) for j in range(len(words)-4)}
for prior,split in question_grams:
if prior and grams and len(prior&grams)/len(prior|grams)>=.85:require(split==r['split'],'near-duplicate question split leakage')
question_grams.append((grams,r['split']))
for text in [t['question_text']]+[a['answer_text'] for a in t['answers']]:
normal=re.sub(r'[^\w]+',' ',text.lower()).strip()
if len(normal)>=50:require(textsplits.setdefault(digest(normal),r['split'])==r['split'],'shared text leakage')
except Exception as e:errors.append({'id':r.get('id'),'line':index+1,'reason':str(e)})
if records is None:
splitrows=[r for name in ['train','validation','test','holdout'] for r in readrows(folder/(name+'.jsonl'))]
require(Counter(encoded(r) for r in splitrows)==Counter(encoded(r) for r in data),'split files do not partition dataset exactly')
return {'status':'PASS' if not errors else 'FAIL','records':len(data),'independently_checked':len(data)-len(errors),'unique_ids':len(ids),'semantic_duplicates':len(data)-len(semantic),'group_count':len(groups),'splits':dict(Counter(r['split'] for r in data)),'errors':errors,'validation_scope':'Schema, strict UTF-8/JSON, identities, exact semantic duplicates, source hashes/relationships, attribution, labels, independent computational oracles, recovery replay and grouped split leakage','near_duplicate_policy':'Scientific normalized text and question 5-shingle grouping; synthetic whole-template groups plus source symmetry-grid grouping. No claim of exhaustive semantic deduplication.'}
if __name__=='__main__':
folder=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parents[1]
report=validate(folder);(folder/'validation_report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8');print(json.dumps({k:v for k,v in report.items() if k!='errors'}));sys.exit(0 if report['status']=='PASS' else 1)
|