"""Register frozen candidates and apply the fixed engineering rule, no field labels.""" from pathlib import Path import argparse,hashlib,json,os,resource,time import numpy as np from g1_registration_cost import register from g1_candidate_fingerprints import check_contract from s2_e1_supervisor import save ROOT=Path(os.environ.get('MELTMIND_G1_REGISTRATION_ROOT','artifacts/s2-g1-registration-2026-11-14')) def engineering_rule(routes,rga,rgb,thresholds): ratio=max(rga,rgb)/min(rga,rgb);mean=(rga+rgb)/2;report={};scores=[] for name in ['physical','scale_free']: rows=[r for r in routes if r['route']==name] if len(rows)!=2 or {r['parity'] for r in rows}!={-1,1}:raise ValueError('Missing det branch') branches={str(r['parity']):r['residual_max_two_way_area_pps_p95']/(mean if name=='physical' else 1.) for r in rows} best=min(branches,key=lambda k:(branches[k],k));other='-1' if best=='1' else '1';value=branches[best] if not np.isfinite(value) or value<0 or thresholds[name]<=0:raise ValueError('Invalid residual/threshold') eligible=name=='scale_free' or ratio<=1.05;score=value/thresholds[name] label=('det'+('+' if best=='1' else '-')+' preferred') if eligible and value2*value else 'branch-ambiguous (near-symmetric)' report[name]={'best_residual':value,'size_gate_pass':eligible,'threshold':thresholds[name],'normalized_score':score, 'branch_residuals':branches,'branch_label':label} if eligible:scores.append(score) score=min(scores) return {'routes':report,'rg_ratio':ratio,'combined_score':score, 'engineering_status':'LINK_UNDER_FIXED_RULE' if score<=1 else 'BAND_REVIEW_REQUIRED' if score<=2 else 'OUTSIDE_FIXED_RULE', 'not_a_relatedness_or_recall_certificate':True} def main(): ap=argparse.ArgumentParser();ap.add_argument('index',type=int);args=ap.parse_args();c=check_contract(ROOT) plan=json.loads((ROOT/'custodian/plan.json').read_text());pair=plan['jobs'][args.index];start=time.monotonic();g=[] for case in [pair['a'],pair['b']]: cache=plan['geometry_cache'][case];p=Path(cache['path']) if hashlib.sha256(p.read_bytes()).hexdigest()!=cache['sha256']:raise ValueError('Frozen geometry cache changed') with np.load(p,allow_pickle=False) as z: if set(z.files)!={'points','boundary','center','rg'}:raise ValueError('Unexpected non-geometry cache member') g.append({k:z[k] for k in z.files}) loaded=time.monotonic()-start;registration_start=time.monotonic() routes=register(g[0],g[1],int(pair['a'].split('_')[0]),int(pair['b'].split('_')[0])) decision=engineering_rule(routes,float(g[0]['rg']),float(g[1]['rg']),c['thresholds']) dest=ROOT/'custodian/results'/f'pair-{args.index:04d}.json' if dest.exists():raise FileExistsError('Result already exists; no retry') save(dest,{'index':args.index,'pair':pair,'routes':routes,'engineering_rule':decision, 'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start, 'geometry_load_wall_seconds':loaded,'registration_wall_seconds':time.monotonic()-registration_start, 'max_starts_per_branch':max(len(r['starts']) for r in routes), 'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024,'simulation_fields_read':False, 'geometric_relationship':'UNREVIEWED','components_frozen':False}) print(json.dumps({'index':args.index,'status':'REGISTRATION_COMPLETE','engineering_status':decision['engineering_status']}),flush=True) if __name__=='__main__':main()