File size: 13,166 Bytes
4a0c408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Independent source + product verifier. Never imports the product builder."""
import argparse,hashlib,importlib.util,json,re
from collections import Counter
from datetime import datetime
from html.parser import HTMLParser
from pathlib import Path
from jsonschema import Draft202012Validator
ROOT=Path(__file__).resolve().parents[1]
KINDS={'Scientific-Statistics-QA':'statistics_qa','Scientific-Code-and-Analysis-QA':'code_qa','Scientific-Answer-Ranking':'ranking','Scientific-Citation-Graph':'citations','Scientific-RAG-HardCases':'rag'}
CACHE={}
def read(p):return json.loads(p.read_text('utf-8'))
def rows(p):return [json.loads(x) for x in p.read_text('utf-8').splitlines() if x.strip()]
def h(s):return hashlib.sha256(s.encode()).hexdigest()
def normal(s):return re.sub(r'[^\w]+',' ',s.lower()).strip()
class CodeOracle(HTMLParser):
    def __init__(self):super().__init__(convert_charrefs=True);self.inside=False;self.parts=[];self.blocks=[]
    def handle_starttag(self,tag,attrs):
        if tag=='pre':self.inside=True;self.parts=[]
        elif self.inside and tag=='br':self.parts.append('\n')
    def handle_endtag(self,tag):
        if tag=='pre' and self.inside:self.blocks.append(''.join(self.parts));self.inside=False
    def handle_data(self,s):
        if self.inside:self.parts.append(s)
def sources(root):
    if str(root) in CACHE:return CACHE[str(root)]
    result={};reports={};edges={}
    for site in ['stats','scicomp','biology']:
        source=root/'sources'/site;file=source/'codex'/'validate_scientific_forum_dataset.py'
        spec=importlib.util.spec_from_file_location('independent_source_'+site,file);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
        report=module.validate(source/'release'/'source-corpus',source)
        if report['status']!='PASS':raise ValueError('Source validator failed: '+site+' '+str(report['errors'][:5]))
        reports[site]=report;result[site]={r['thread_id']:r for r in rows(source/'release'/'source-corpus'/'dataset.jsonl')};edges[site]=rows(source/'release'/'source-corpus'/'citation_graph.jsonl')
    CACHE[str(root)]=(result,reports,edges);return result,reports,edges
def validate(folder,root=ROOT,name=None):
    name=name or folder.name;kind=KINDS[name];source,source_reports,edges=sources(root)
    errors=[];assertions=0
    def check(ok,msg):
        nonlocal assertions
        assertions+=1
        if not ok:errors.append(msg)
    data=rows(folder/'dataset.jsonl');schema=Draft202012Validator(read(folder/'schema.json'));ids=set();threads={};primary={};code_total=0
    corpus={t['thread_id']:t for t in rows(root/'normalized'/'corpus.jsonl')}
    qaeligible=set();rankeligible=set();rageligible={};codeeligible={};citeseligible={}
    def selected(t):
        accepted=[a for a in t['answers'] if a['is_accepted']]
        if accepted:return accepted[0]
        scored=sorted([a for a in t['answers'] if a['score']>=1],key=lambda a:(-a['score'],a['answer_id']));return scored[0] if scored else None
    def signals(t):
        answers=t['answers'];sc=[a['score'] for a in answers];ac=next((a for a in answers if a['is_accepted']),None);ss=[]
        if len(answers)>1:ss.append('multiple_answers')
        if len(t['external_links'])>1:ss.append('multiple_external_references')
        if ac is None:ss.append('no_accepted_answer')
        if ac and max(sc)>ac['score']:ss.append('accepted_not_highest_score')
        if len(sc)>1 and max(sc)-min(sc)>=5:ss.append('community_score_spread_ge_5')
        if len(answers)>1:
            dates=[datetime.fromisoformat(a['created_at']) for a in answers]
            if (max(dates)-min(dates)).days>=365:ss.append('answer_age_span_ge_365_days')
        return ss
    def code(t):
        pp=[(t['question_id'],t['question_html'],t['source_url'])]+[(a['answer_id'],a['answer_html'],a['answer_url']) for a in t['answers']];rr=[]
        for pid,body,url in pp:
            oracle=CodeOracle();oracle.feed(body)
            for i,block in enumerate(oracle.blocks):
                if len(block.strip())<20:continue
                if not re.search(r'\b(import|def|return|while|function|library|numpy|printf|NDSolve|Table|Plot|double|void)\b|<-|np\.|\bfor\s|print\(|lm\(',block):continue
                rr.append((pid,i,block,url,h(block)))
        return rr
    for tid,t in corpus.items():
        if t['source_site']=='stats' and selected(t):qaeligible.add(tid)
        if len(t['answers'])>=2:rankeligible.add(tid)
        if signals(t):rageligible[tid]=signals(t)
        cb=code(t)
        if cb and selected(t):codeeligible[tid]=cb
        cc=[c for c in edges[t['source_site']] if c['thread_id']==t['question_id']]
        if cc:citeseligible[tid]=cc
    seen_citations=set()
    for r in data:
        se=list(schema.iter_errors(r));check(not se,'schema '+r.get('record_id','?')+': '+str([e.message for e in se[:2]]))
        if se:continue
        rid=r['record_id'];check(rid not in ids,'duplicate primary ID '+rid);ids.add(rid)
        t=r['thread'];tid=t['thread_id'];threads[tid]=t;site=t['source_site'];q=source[site].get(t['question_id']);check(q is not None,'orphan source thread '+tid)
        if q is None:continue
        check(tid==site+':'+str(t['question_id']),'qualified thread identity')
        check(t['source_url']==q['thread_url'] and t['domain']=={'stats':'statistics','scicomp':'computational_science','biology':'biology'}[site],'source URL/domain')
        for key in ['title','question_text','question_html','question_author','question_author_url','question_author_user_type','question_created_at','question_score','tags','question_license','accepted_answer_id','provenance','revision_attribution','medical_sensitive']:
            check(t[key]==q[key],'source question field '+tid+'/'+key)
        check(tid in corpus and t==corpus.get(tid),'canonical membership/equality '+tid)
        check(r['split']==t['split'],'record/thread split consistency')
        bucket=int(t['split_group'][:8],16)%100;expected='train' if bucket<70 else 'validation' if bucket<80 else 'test' if bucket<90 else 'holdout';check(t['split']==expected,'deterministic split bucket')
        rawanswers={a['answer_id']:a for a in q['answers']};seen_answers=set()
        for a in t['answers']:
            aid=a['answer_id'];check(aid not in seen_answers,'duplicate answer');seen_answers.add(aid);original=rawanswers.get(aid);check(bool(original),'orphan answer')
            if not original:continue
            check(a['question_id']==t['question_id'],'answer question relationship')
            for key in ['answer_text','answer_html','created_at','updated_at','score','is_accepted','content_license','answer_url','provenance','revision_attribution']:
                check(a[key]==original[key],'source answer field '+tid+'/'+str(aid)+'/'+key)
            check(a['author']==original['author_display_name'] and a['author_url']==original['author_profile_url'],'answer attribution')
        check(seen_answers==set(rawanswers),'complete source answer coverage')
        accepted=[a['answer_id'] for a in t['answers'] if a['is_accepted']];check(accepted==([t['accepted_answer_id']] if t['accepted_answer_id'] else []),'accepted consistency')
        content='\n'.join([t['question_text']]+[a['answer_text'] for a in t['answers']]);check(not re.search(r'[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}',content),'identifiable email heuristic')
        check(not re.search(r'\b(my|I have|I am|my friend|my mother|my father)\b.{0,100}\b(symptom\w*|diagnos\w*|medication|disease|infection|pain|sick)\b',content,re.I|re.S),'patient history heuristic')
        check(not re.search(r'\b(should I take|what (?:drug|medicine|treatment) should|how (?:can|should) I treat)\b',content,re.I),'clinical request heuristic')
        if kind in ('statistics_qa','code_qa'):
            s=selected(t);check(s is not None and r['selected_answer']==s and r['question']==t['question_text'],'QA selected answer')
            check(r['accepted_answer']==(s if s and s['is_accepted'] else None),'QA accepted vs score fallback')
            check(r['other_answers']==[a for a in t['answers'] if s and a['answer_id']!=s['answer_id']],'QA other candidates')
            if kind=='code_qa':
                actual=[(b['post_id'],b['block_index'],b['code_text'],b['source_url'],b['sha256']) for b in r['code_blocks']];check(actual==codeeligible.get(tid),'exact code extraction');code_total+=len(actual)
        if kind=='ranking':check(r['candidate_answers']==t['answers'] and r['scores']==[a['score'] for a in t['answers']] and r['accepted_status']==[a['is_accepted'] for a in t['answers']] and r['question']==t['question_text'],'ranking source arrays')
        if kind=='rag':check(r['hardness_signals']==signals(t),'deterministic hardness signals')
        if kind=='citations':
            key=(tid,r['post_id'],r['external_url'],r['doi']);check(key not in seen_citations,'duplicate citation');seen_citations.add(key)
            allowed=citeseligible.get(tid,[]);c=next((c for c in allowed if (c['post_id'],c['target_url'],c['doi'])==key[1:]),None);check(c is not None,'literal source citation')
            if c:
                check(r['post_url']==c['source_post_url'] and r['kind']==c['kind'] and r['content_license']==c['content_license'] and r['correctness_verified'] is False,'citation metadata')
                plain=t['question_text'] if r['post_id']==t['question_id'] else next(a['answer_text'] for a in t['answers'] if a['answer_id']==r['post_id']);needle=r['external_url'] or r['doi'];at=plain.find(needle);context=plain[max(0,at-100):at+len(needle)+100] if at>=0 else None;check(r['citation_context']==context,'citation literal context')
    expected={'statistics_qa':qaeligible,'code_qa':set(codeeligible),'ranking':rankeligible,'rag':set(rageligible),'citations':set(citeseligible)}[kind];check(set(threads)==expected,'product eligible thread coverage')
    if kind!='citations':check(len(data)==len(threads),'one record per thread')
    else:check(seen_citations=={(tid,c['post_id'],c['target_url'],c['doi']) for tid,cc in citeseligible.items() for c in cc},'citation complete edge coverage')
    allsplit=[]
    for split in ['train','validation','test','holdout']:
        ss=rows(folder/(split+'.jsonl'));check(ss==[r for r in data if r['split']==split],'exact '+split+' split');allsplit+=ss
    check(len(allsplit)==len(data),'split coverage')
    textmap={};near=0;normalized_duplicates=0;tts=list(threads.values());grams=[]
    for t in tts:
        for value in [normal(t['title']),normal(t['question_text'])]+[normal(a['answer_text']) for a in t['answers']]:
            if value in textmap:
                normalized_duplicates+=1;check(textmap[value]==t['split'],'exact question/title/answer leakage')
            else:textmap[value]=t['split']
        w=normal(t['question_text']).split();grams.append(set(tuple(w[j:j+3]) for j in range(len(w)-2)))
    for i,a in enumerate(grams):
        for j in range(i):
            b=grams[j]
            if len(a)>=5 and len(b)>=5 and min(len(a),len(b))>=.8*max(len(a),len(b)) and len(a&b)/len(a|b)>=.8:near+=1;check(tts[i]['split']==tts[j]['split'],'near duplicate leakage')
    stats=read(folder/'stats.json');check(stats['records']==len(data) and stats['unique_threads']==len(threads) and stats['answers']==sum(len(t['answers']) for t in threads.values()),'stats counts')
    check(stats['splits']==dict(Counter(r['split'] for r in data)),'split counts')
    rejected=rows(folder/'rejected.jsonl');check(len(rejected)==stats['rejected_records'] and all(r['reasons'] and r['thread_id'] not in threads for r in rejected),'rejections disjoint/reasoned')
    check(len(data)>0 and all(any(r['split']==s for r in data) for s in ['train','validation','test','holdout']),'nonempty data and four splits')
    report={'status':'PASS' if not errors else 'FAIL','name':name,'records':len(data),'unique_threads':len(threads),'answers':sum(len(t['answers']) for t in threads.values()),'assertions':assertions,'near_duplicate_pairs':near,'duplicate_text_occurrences':normalized_duplicates,'code_blocks_verified':code_total,'source_validation':{s:{'status':v['status'],'assertions':v['assertions'],'raw_files_verified':v['raw_files_verified']} for s,v in source_reports.items()},'errors':errors,'independent':'No import of builder; independent per-source raw/HTML/revision verifiers plus product selection and split checks. Same engine is used by five product-specific entry points.','holdout_note':'Source-thread lexical group holdout; public, not a contamination-free private test set.'}
    (folder/'validation_report.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8');return report
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--source-root',type=Path,default=ROOT);p.add_argument('--release',type=Path);p.add_argument('--product',choices=KINDS);a=p.parse_args()
    names=[a.product] if a.product else list(KINDS);result={name:validate(a.release or a.source_root/'release'/name,a.source_root,name) for name in names}
    print(json.dumps(result,indent=2));raise SystemExit(0 if all(r['status']=='PASS' for r in result.values()) else 1)