"""Freeze individual reference-fact coverage of existing full511 reader outputs. This diagnostic is neither task accuracy nor evidence entailment. No generation, new acceptance labels, source-identity injection or selected-question filtering. """ import hashlib,json,sys from pathlib import Path from validate_openqa_grader import JUDGE from prepare_openqa_dev161_equal_budget import freeze ROOT=Path(__file__).resolve().parent BASE=ROOT/'miriad_public/openqa_human511_readers' OUT=ROOT/'miriad_public/openqa_human511_individual_reference_coverage_v1' sys.path.insert(0,str(ROOT.parent/'MeningiomaBench-v1/code')) from response_parsing import normalize_prediction PROMPT=JUDGE.split('\nEvaluate EVERY supplied')[0]+'''\nThis call evaluates one candidate only. All supplied reference facts are automatic silver propositions. Some are compound, examples or ancillary details, so full reference coverage is a diagnostic, NOT task accuracy, source entailment or medical correctness. Do not declare a medically reasonable alternative wrong just because it does not cover this reference. For this metric, however, partial coverage of a compound proposition is false or uncertain, never true. No source passage, other answers, explanations, model or method identities are supplied. Return ONLY JSON {"fact_coverage":[{"index":0,"covered":true,"candidate_quote":"exact contiguous candidate span or null"}]}. covered is true,false,or"uncertain". Include every supplied fact index exactly once. No reasons or extra fields.''' def read(p):return [json.loads(x) for x in p.read_text().splitlines()] def sha(b):return hashlib.sha256(b).hexdigest() def dump(x):return json.dumps(x,ensure_ascii=False) def main(): OUT.mkdir(exist_ok=True);items={x['id']:x for x in read(BASE/'selected_items.jsonl')};orig={(x['id'],x['method']):x for x in read(BASE/'requests2555.jsonl')};assert len(items)==511 and len(orig)==2555 facts={};sets={} for ident,item in items.items(): pool=[];indices={} for author,propositions in sorted(item['reference_fact_candidates'].items()): assert isinstance(propositions,list) and propositions and all(isinstance(f,str) and f.strip() for f in propositions) found=[] for fact in propositions: if fact not in pool:pool.append(fact) found.append(pool.index(fact)) indices[author]=found facts[ident]=pool;sets[ident]=indices paths={'luna':BASE/'luna_predictions.jsonl','deepseek':BASE/'deepseek_predictions.jsonl','qwen25_7b':BASE/'qwen25_7b_human511/predictions.jsonl','llama31_8b':BASE/'llama31_8b_human511/predictions.jsonl'} expectedmodels={'luna':'gpt-6-luna','deepseek':'deepseek-v4.1-flash','qwen25_7b':'Qwen/Qwen2.5-7B-Instruct','llama31_8b':'unsloth/Llama-3.1-8B-Instruct'} frame=[];requests={};invalid={};hashes={} for model,path in paths.items(): rows=read(path);preds={} for r in rows: if r.get('error'):continue # Historical failed attempts retained in original file; use unique completed response. key=r['id'],r['method'];assert key not in preds and key in orig assert r['context_sha256']==orig[key]['context_sha256'] and r['model_returned']==expectedmodels[model] preds[key]=r assert set(preds)==set(orig);hashes[model]=sha(path.read_bytes());req=[];bad=0 for key,r in preds.items(): ident,method=key;parsed=normalize_prediction(r);answer=parsed.get('answer');primary=isinstance(answer,str) and bool(answer.strip()) final=answer if primary else (r.get('output') or '').strip();bad+=not primary # Preserve both declared-answer primary and explicitly labeled whole-final-text sensitivity. data={'question':items[ident]['question'],'fixed_reference_facts':[{'fact':f} for f in facts[ident]],'candidate_answer':final,'evidence':''} row={'id':ident,'method':method,'track':'human511_exploratory_reference_coverage_not_accuracy','option_letters':[],'response_protocol':'individual_reference_fact_coverage_v1', 'messages':[{'role':'system','content':PROMPT},{'role':'user','content':dump(data)}],'context_sha256':sha(b''),'context_tokens_unified':0} req.append(row);frame.append({'id':ident,'reader':model,'method':method,'source_family_id':items[ident]['source_family_id'], 'reader_context_sha256':r['context_sha256'],'declared_answer_primary_valid':primary,'graded_candidate_serialization':'declared_answer' if primary else 'whole_final_response_sensitivity_only', 'candidate_answer_sha256':sha(final.encode()),'request_messages_sha256':sha(dump(row['messages']).encode()),'reference_fact_sets':sets[ident], 'reference_fact_count':len(facts[ident]),'source_metadata_not_injected_into_reader_query':True}) requests[model]=req;invalid[model]=bad freeze(OUT/(model+'_requests2555_local_only.jsonl'),''.join(dump(r)+'\n' for r in req)) freeze(OUT/'reader_frame10220_local_only.jsonl',''.join(dump(r)+'\n' for r in frame)) protocol={'scope':'All historical511human OpenQA/196sourcefamilies/4readers/5methods; source-conditioned exploratory evaluation, NOT untouchedtest/clinicalaccuracy. Original questions/answers/readercontexts unchanged.', 'questions':511,'readers':4,'logical_answer_records':10220,'requests_per_reader':2555,'declared_answer_invalid_by_reader':invalid, 'reference_sets':'Both existing source auditors fact lists; exact string union for shared grading, each original set reported separately. No new target proposals accepted; compounds/examples/ancillary facts retained explicitly as diagnostic limitation.', 'primary':'Declared valid candidate answer only, per-reference-fact coverage + uncertainty. Invalid declared answers missing primary, whole-final-response scores sensitivity only; no answer repair.', 'missingness':'Invalid/truncated judgment or missing positive anchor is missing, never true/false by repair. Report complete/invalid denominators and missingness bounds, not complete-case-only victories.', 'full_frame_retained':True,'judge_and_reader_identity_hidden_in_messages':True,'batching_used':False,'batch_protocol_failed_development_check':True, 'judge':'official gpt-6-luna first; independent DeepSeek after observed quota reset. No independent full-frame agreement inferred.', 'reasoning_effort':'low','temperature':'provider_default','max_completion_tokens':2000,'no_medical_truth_or_full_task_accuracy_claim':True,'expert_reviews':0, 'reader_prediction_sha256':hashes,'source_items_sha256':sha((BASE/'selected_items.jsonl').read_bytes()),'original_requests_sha256':sha((BASE/'requests2555.jsonl').read_bytes()), 'grader_requests_sha256':{m:sha((OUT/(m+'_requests2555_local_only.jsonl')).read_bytes()) for m in paths},'code_sha256':sha(Path(__file__).read_bytes()), 'next':'Separate reference coverage from source-claim entailment/citation precision. Grader disagreements and expert-pending status remain; source citation-pointers are not entailment. No inference that negativeRAG has been solved.'} freeze(OUT/'protocol_before_grading_calls.json',json.dumps(protocol,indent=2)+'\n');freeze(OUT/'code_snapshot.py',Path(__file__).read_text()) print(json.dumps({'frozen_reader_records':len(frame),'questions':511,'requests_per_reader':2555,'invalid_primary_answers':invalid,'new_reader_generations':0,'new_judge_calls':0})) if __name__=='__main__':main()