"""Independent raw-record oracle. Does not import/reference the witness program.""" from copy import deepcopy as cp from datetime import datetime from fractions import Fraction import math def same(a,b): if isinstance(a,bool) or isinstance(b,bool):return type(a)==type(b) and a==b if isinstance(a,(int,float)) and isinstance(b,(int,float)):return math.isfinite(a) and math.isfinite(b) and a==b if type(a)!=type(b):return False if isinstance(a,dict):return a.keys()==b.keys() and all(same(a[k],b[k]) for k in a) if isinstance(a,list):return len(a)==len(b) and all(same(x,y) for x,y in zip(a,b)) return a==b def instant(value):return datetime.fromisoformat(value.replace('Z','+00:00')) def fields(row,keys):return {k:cp(row[k]) for k in keys.split()} def equivalent_report(number,actual,gold,context): """Normalize only explicitly permitted representations, never missing fields.""" candidate=cp(actual) if number==1 and gold['report'] is not None and isinstance(candidate.get('report'),dict): for key in ('window_start','window_end'): value=instant(candidate['report'][key]);target=instant(gold['report'][key]) if value.tzinfo is None or value!=target:return False candidate['report'][key]=gold['report'][key] if number==4 and gold['report'] is not None and isinstance(candidate.get('report'),dict): for public,field in [('mean_sleep_minutes','total_sleep_minutes'),('mean_efficiency_percent','efficiency_percent'),('mean_rem_share_percent','rem_share_percent')]: exact=float(sum(Fraction(str(row[field])) for row in gold['report']['nights'])/7) value=candidate['report'][public] if type(value) not in (float,int) or not math.isfinite(value):return False permitted=[exact]+[round(exact,digits) for digits in range(1,13)] if not any(math.isclose(value,x,rel_tol=0,abs_tol=1e-10) for x in permitted):return False candidate['report'][public]=gold['report'][public] if number in (1,2) and gold['limitations']: peers={'routes/'+context['route_id'],'dispatch_notes/'+context['route_id']} if number==1 else {'appointments/'+context['event_id'],'provider_messages/'+context['confirmation_id']} limits=candidate['limitations'] if all(x['reason']=='CONFLICTING_RECORDS' for x in gold['limitations']): if not limits or len({x['resource'] for x in limits})!=len(limits):return False if any(set(x)!={'resource','reason'} or x['reason']!='CONFLICTING_RECORDS' or x['resource'] not in peers for x in limits):return False candidate['limitations']=cp(gold['limitations']) # Any observed decisive ownership/audience failure prevents this deliverable. if number in (5,6) and candidate.get('report') is None: reasons={'OWNER_MISMATCH'} if number==5 else {'AUDIENCE_NOT_AUTHORIZED'} limits=candidate.get('limitations',[]) if limits and len({(x['resource'],x['reason']) for x in limits})==len(limits) and all(x in gold['limitations'] and x['reason'] in reasons for x in limits): candidate['limitations']=cp(gold['limitations']) return same(candidate,gold) def expected(number,state,context): sources={k:{r['id']:r for r in g['records']} for k,g in state['collections'].items()} needed=set() def get(group,ident): ident=str(ident);needed.add(group+'/'+ident);return cp(sources[group][ident]['payload']) def all_rows(group):return [get(group,i) for i in sources[group]] result=None;changes=cp(state);semantic=[] if number==1: r=get('routes',context['route_id']);note=get('dispatch_notes',context['route_id']) if instant(r['time_window_start'])!=instant(note['start']) or instant(r['time_window_end'])!=instant(note['end']):semantic=[{'resource':'routes/'+context['route_id'],'reason':'CONFLICTING_RECORDS'}] result={'route_id':context['route_id'],'window_start':note['start'],'window_end':note['end']} elif number==2: e=get('appointments',context['event_id']);p=get('provider_messages',context['confirmation_id']) if e['location']!=p['location'] or e['date']!=p['date'] or e['start_time']!=p['start_time']:semantic=[{'resource':'appointments/'+context['event_id'],'reason':'CONFLICTING_RECORDS'}] result={'event':e,'clinician':p['clinician'],'confirmation_id':context['confirmation_id']} elif number in (3,50): ss=[get('sessions',i) for i,r in sources['sessions'].items() if r['index']['start_time'][:10]==context['date'] and int(r['index']['start_time'][11:13])>=context['start_hour']];ns=all_rows('journal_notes') ss=[s for s in ss if s['start_time'][:10]==context['date'] and int(s['start_time'][11:13])>=context['start_hour']] kinds={s['content_type'] for s in ss};applicable=[n for n in ns if n['late_night_relevance'] is True and kinds.intersection(n['supported_content_types'])] applicable.sort(key=lambda n:n['evidence_id']) if number==3: categories=[] for k in context['content_types']: members=[s for s in ss if s['content_type']==k] categories.append({'content_type':k,'minutes':float(sum(Fraction(str(s['duration_minutes'])) for s in members)), 'usage_ids':sorted(s['usage_id'] for s in members),'factor_ids':sorted(n['evidence_id'] for n in applicable if k in n['supported_content_types']) if members else []}) result={'date':context['date'],'categories':categories,'notes':applicable} else:result={'sessions':sorted(ss,key=lambda s:(s['start_time'],s['usage_id'])),'factors':applicable} elif number==4: groups={} for ident,r in sources['sleep_records'].items(): v=r['index'] if context['from']<=v['night']<=context['through']:groups.setdefault(v['origin_night_id'],[]).append(r) chosen=[sorted(v,key=lambda r:(r['index']['source']=='oura',instant(r['index']['imported_at'])))[-1]['id'] for v in groups.values()] selected=[get('sleep_records',ident) for ident in chosen] selected.sort(key=lambda r:r['night']) if len(selected)!=7:raise ValueError('Seven-night cohort is not defined') result={'nights':selected,'below_target_nights':len([s for s in selected if s['efficiency_percent']instant(r['time_window_start']) or instant(d['available_until'])