"""Materialize the pre-frozen inline verifier on source18 reader contexts.""" import json import argparse from collections import Counter from pathlib import Path import re import sys import tiktoken from prepare_confirmation_source_cohort import OUT, read, digest from prepare_openqa_dev161_equal_budget import freeze, sha from study_population_witness_gate import counts from inline_population_verification_development import annotate, PROMPT BASE=OUT/'source18_verifier_validation_prospective_v1' DEST=BASE/'inline_verifier_v1' def main(): DEST.mkdir(exist_ok=True);parent=json.loads((BASE/'protocol_before_candidate_construction.json').read_text()) for name in ['inline_population_verification_development.py','study_population_witness_gate.py','frame_choice_syntax_projection.py']: assert digest(Path(__file__).with_name(name))==parent['method_code_sha256'][name],name corpus={r['source_id']:r for r in read(OUT/'numeric_rag_development_smoke_v2/corpus_source_only_local.jsonl')} encoder=tiktoken.encoding_for_model('gpt-4o');requests={};catalogs={};selectors=[] for grid in ['primary','matched_length']: folder=BASE/('reader_'+grid+'_v1');protocol=json.loads((folder/'protocol.json').read_text());path=folder/'requests48_local_only.jsonl' assert digest(path)==protocol['requests_sha256'] for row in read(path): payload=json.loads(row['messages'][1]['content']);requested=counts(payload['question'],True) record={'id':row['id'],'method':row['method'],'grid':grid,'baseline_context_sha256':row['context_sha256'],'baseline_evidence_tokens':row['context_tokens_unified']} if not requested or not payload['evidence']: selectors.append({**record,'state':'not_applicable' if not requested else 'no_evidence','request_id':None});continue assert len(requested)==1;q=requested[0];pattern=r'\b'+str(q['value'])+r'\b';assert len(re.findall(pattern,payload['question']))==1 evidence,frames,stats=annotate(payload['evidence'],row['context_tokens_unified'],encoder,corpus) messages=[{'role':'system','content':PROMPT},{'role':'user','content':json.dumps({'study':payload['study'],'question':re.sub(pattern,'[POPULATION_COUNT]',payload['question']),'evidence':evidence},ensure_ascii=False)}] ident='S18INLINE:'+sha(json.dumps(messages,sort_keys=True).encode())[:24] if frames: if ident not in requests: requests[ident]={'id':ident,'method':'inline_cohort_frame_select','track':'source18_prefrozen_inline_verifier', 'option_letters':[],'response_protocol':'inline_population_frame_id_v1','context_sha256':sha(evidence.encode()), 'context_tokens_unified':stats['verifier_tokens'],'messages':messages} catalogs[ident]={'id':ident,'frames':frames,'study_pmid':str(payload['study']['pmid'])} else:assert requests[ident]['messages']==messages and catalogs[ident]['frames']==frames selectors.append({**record,'state':'verifier_requested' if frames else 'no_visible_count_frame', 'request_id':ident if frames else None,'proposed_count':q['value'],'entity_family':q['family'], 'annotation_stats':stats}) assert len(selectors)==96 freeze(DEST/'selectors96_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in selectors)) freeze(DEST/'catalogs_local_only.jsonl',''.join(json.dumps(r)+'\n' for r in catalogs.values())) path=DEST/'verifier_requests_local_only.jsonl';freeze(path,''.join(json.dumps(r)+'\n' for r in requests.values())) freeze(DEST/'protocol_before_verifier_calls.json',json.dumps({'scope':'Prefrozen method applied to source18prospectivesourcevalidation,not a new method tuned on readeroutputs.', 'parent_method_protocol_sha256':digest(BASE/'protocol_before_candidate_construction.json'), 'evaluation_plan_sha256':digest(BASE/'evaluation_plan_frozen_before_readers.json'), 'requests_sha256':digest(path),'selectors_sha256':digest(DEST/'selectors96_local_only.jsonl'), 'unique_verifier_requests':len(requests),'source_only_method_code_sha256':parent['method_code_sha256'], 'materialization_timing':'Baseline readerinputs/evaluationplan and methodcode were frozen beforebaselinecalls. Verifierbytefilesmaterialized afterbaselinejoblaunch, BEFOREverifiercalls, withoutreadingbaselinepredictions; entirelydeterministicfromprefrozenmethod+contexts.', 'preparation_uses_reader_outputs':False,'primary':'frame_idobjectschema','secondary':'alreadyfrozennarrowsyntaxprojection', 'gate':'Validcompletevisibleframe mustmatchesstudy/entity;countmismatch=>abstain;unknown=>nooverride. Actualextraevidencereadingcostseparate. Oraclecontroloriginalpositivesourcecontext upperbound separate.', 'luna_reasoning_effort':'low','luna_temperature':'provider_default','local_temperature':0, 'max_completion_tokens_or_local_max_tokens':1000,'expert_reviews':0,'new_accepted_main_benchmark_questions':0},indent=2)+'\n') print('Frozen',len(requests),'uniqueverifierrequests representing',sum(bool(r['request_id']) for r in selectors),'logicalchecks/96contexts;noansweroutputsread') def audit(): sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'publication_candidate_20261120/code')) from identified_numeric_scoring import parse_json_output from frame_choice_syntax_projection import project protocol=json.loads((DEST/'protocol_before_verifier_calls.json').read_text()) assert digest(DEST/'verifier_requests_local_only.jsonl')==protocol['requests_sha256'] assert digest(DEST/'selectors96_local_only.jsonl')==protocol['selectors_sha256'] plan=json.loads((BASE/'evaluation_plan_frozen_before_readers.json').read_text()) assert digest(BASE/'reader_items8_local_only.jsonl')==plan['items_sha256'] items={r['id']:r for r in read(BASE/'reader_items8_local_only.jsonl')} requests={r['id']:r for r in read(DEST/'verifier_requests_local_only.jsonl')} catalogs={r['id']:r for r in read(DEST/'catalogs_local_only.jsonl')};selectors=read(DEST/'selectors96_local_only.jsonl') models={} for model in ['luna','qwen3_4b','qwen25_7b']: vp=DEST/('luna_predictions.jsonl' if model=='luna' else model+'/predictions.jsonl') gp=vp.with_suffix('.protocol.json') if model=='luna' else DEST/model/'protocol.json';gen=json.loads(gp.read_text()) assert gen.get('request_sha256',gen.get('input_sha256'))==protocol['requests_sha256'] if model!='luna':assert json.loads((DEST/model/'complete.json').read_text())['complete'] outputs=read(vp);verifiers={r['id']:r for r in outputs};assert len(outputs)==len(requests) and verifiers.keys()==requests.keys() for r in outputs: assert not r.get('error') and r['model_requested']==r['model_returned']==gen['model'] assert all(r[k]==requests[r['id']][k] for k in ['context_sha256','context_tokens_unified','response_protocol']) baselines={};basecases={};basehashes={} for grid in ['primary','matched_length']: folder=BASE/('reader_'+grid+'_v1');rp=folder/'requests48_local_only.jsonl';req={(r['id'],r['method']):r for r in read(rp)} path=folder/('luna_predictions.jsonl' if model=='luna' else model+'/predictions.jsonl');g=json.loads((path.with_suffix('.protocol.json') if model=='luna' else folder/model/'protocol.json').read_text()) assert g.get('request_sha256',g.get('input_sha256'))==digest(rp) and g['model']==gen['model'] for row in read(path): key=row['id'],row['method'];assert not row.get('error') and row['model_requested']==row['model_returned']==gen['model'] assert all(row[k]==req[key][k] for k in ['context_sha256','context_tokens_unified','response_protocol']);baselines[(grid,*key)]=row audit_report=json.loads((folder/'reader_audit.json').read_text()) for row in audit_report['models'][model]['cases']:basecases[grid,row['id'],row['method']]=row basehashes[grid]=digest(path) counters={};cases=[];pipeline=[] for grid in ['primary','matched_length']: counters[grid]={mode:{m:Counter() for m in plan['methods']} for mode in ['strict_schema','prefrozen_narrow_syntax']} for s in selectors: key=s['grid'],s['id'],s['method'];item=items[s['id']];original=baselines[key];prior=basecases[key];control=item['is_constructed_unanswerable_control'] origin=items[item['original_positive_id']] if control else item expected_counts=origin['population_count_mentions'] expected_count=expected_counts[0]['value'] if len(expected_counts)==1 else None for mode in ['strict_schema','prefrozen_narrow_syntax']: frame=None;state=s['state'] if s['request_id']: row=verifiers[s['request_id']];cat=catalogs[s['request_id']];allowed={f['frame_id'] for f in cat['frames']};parsed=parse_json_output(row['output']) if mode=='strict_schema':ident=parsed['frame_id'] if isinstance(parsed,dict) and set(parsed)=={'frame_id'} and isinstance(parsed['frame_id'],str) else None else:ident=project(row['output'],allowed)['frame_id'] frame=next((f for f in cat['frames'] if f['frame_id']==ident),None);state='validated_count_frame' if frame else 'unknown_frame_selection' if frame and (frame['paper_id']!=cat['study_pmid'] or frame['entity_family']!=s['entity_family']):frame=None;state='wrong_paper_or_entity_family' if row.get('finish_reason')!='stop':frame=None;state='truncated_verifier' reject=bool(frame and frame['count']!=s['proposed_count']) numeric=bool(prior['strict_requested_numeric'] and not reject) refusal=bool(control and (reject or prior['strict_control_rejection'])) c=counters[s['grid']][mode][s['method']] c.update(cases=1,verifier_requested=int(bool(s['request_id'])),validated_count=int(frame is not None), source_role_count_matches_reference=int(frame is not None and frame['count']==expected_count),gate_rejects=int(reject)) if control:c.update(controls=1,baseline_control_reject=int(prior['strict_control_rejection']),pipeline_control_reject=int(refusal)) else:c.update(positives=1,baseline_numeric=int(prior['strict_requested_numeric']),pipeline_numeric=int(numeric), positive_gate_abstentions=int(reject),previously_numeric_pass_now_abstain=int(reject and prior['strict_requested_numeric'])) cases.append({'id':s['id'],'method':s['method'],'grid':s['grid'],'mode':mode,'control':control,'source_scope':item['source_scope'], 'state':state,'requested_count':s.get('proposed_count'),'selected_count':frame['count'] if frame else None, 'evaluator_only_expected_source_count':expected_count,'gate_reject':reject,'baseline_numeric':prior['strict_requested_numeric'], 'pipeline_numeric':numeric,'baseline_control_reject':prior.get('strict_control_rejection',False),'pipeline_control_reject':refusal}) pipeline.append({'id':s['id'],'method':s['method'],'grid':s['grid'],'mode':mode, 'output':'{"answer":"unanswerable","citations":[]}' if reject else original['output'], 'gate_reject':reject,'cached_answer_predictions_sha256':basehashes[s['grid']],'verifier_request_id':s['request_id'], 'output_kind':'derived_pipeline_from_actual_verifier_and_exact_cached_answer_not_new_generation'}) folder=DEST/model;folder.mkdir(exist_ok=True);(folder/'composed_pipeline_outputs192.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in pipeline)) models[model]={'generation_protocol':gen,'verifier_predictions_sha256':digest(vp),'cached_reader_predictions_sha256':basehashes, 'counts':counters,'cases':cases,'new_verifier_provider_logged_tokens':sum((r.get('usage') or {}).get('total_tokens',0) for r in outputs) if model=='luna' else 0} report={'scope':'Source18prospective-source validation ofprefrozeninlineverifier;6silverpositives/4families+2syntheticcohortcontrols/onefamily. Notclinicalaccuracy.', 'protocol':protocol,'models':models,'new_verifier_model_outputs':len(requests)*3,'cached_answer_grid_records':288, 'derived_pipeline_records':576,'new_answer_generations_for_composition':0,'expert_reviews':0, 'limits':'Only1/6positivequestionsactivatescurrentcountparser;2controls are fromsamepositivefamily. Unknownisnotverifiedcompatibility. Additionalverifierpasscostscompute;source-roletruth remainsassistant-readingsilver.'} (DEST/'reader_pipeline_audit.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({m:v['counts'] for m,v in models.items()},indent=2)) if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('--audit',action='store_true');args=ap.parse_args() audit() if args.audit else main()