Download private/controller/native_reference.py from sxcn/HERA-Bench: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/sxcn/HERA-Bench/resolve/main/private/controller/native_reference.py
- Command line
-
hf download hf://datasets/sxcn/HERA-Bench/private/controller/native_reference.py
-
curl -L -o native_reference.py https://huggingface.co/datasets/sxcn/HERA-Bench/resolve/main/private/controller/native_reference.py
12.1 kB
| """Controller-only deterministic witness. Receives public tools/context, no state/oracle.""" | |
| from datetime import datetime | |
| from decimal import Decimal | |
| from copy import deepcopy | |
| def solve(number,call,context): | |
| limitations=[] | |
| def load(collection,predicate=None): | |
| directory=call('list_'+collection,{})['result']['items'] | |
| ids=[r['id'] for r in directory if predicate is None or predicate(r)] | |
| if not ids:return [] | |
| response=call('read_'+collection,{'ids':ids})['result'] | |
| limitations.extend({'resource':collection+'/'+r['id'],'reason':r['code']} for r in response['unavailable']) | |
| return [deepcopy(r['data']) for r in response['items']] | |
| def stopped():return {'report':None,'limitations':sorted(limitations,key=lambda x:(x['resource'],x['reason']))} | |
| if number==1: | |
| r=load('routes',lambda h:h['id']==context['route_id']);d=load('dispatch_notes',lambda h:h['id']==context['route_id']) | |
| if limitations:return stopped() | |
| parse=lambda s:datetime.fromisoformat(s.replace('Z','+00:00')) | |
| if tuple(parse(r[0][k]) for k in ('time_window_start','time_window_end'))!=tuple(parse(d[0][k]) for k in ('start','end')): | |
| limitations.append({'resource':'routes/'+context['route_id'],'reason':'CONFLICTING_RECORDS'});return stopped() | |
| result={'route_id':context['route_id'],'window_start':d[0]['start'],'window_end':d[0]['end']} | |
| elif number==2: | |
| event=load('appointments',lambda h:h['id']==context['event_id']);confirmation=load('provider_messages',lambda h:h['id']==context['confirmation_id']) | |
| if limitations:return stopped() | |
| e,c=event[0],confirmation[0] | |
| if any(e[k]!=c[k] for k in ('date','start_time','location')): | |
| limitations.append({'resource':'appointments/'+context['event_id'],'reason':'CONFLICTING_RECORDS'});return stopped() | |
| result={'event':e,'clinician':c['clinician'],'confirmation_id':context['confirmation_id']} | |
| elif number in (3,50): | |
| sessions=load('sessions',lambda h:h['index']['start_time'][:10]==context['date'] and int(h['index']['start_time'][11:13])>=context['start_hour']);notes=load('journal_notes') | |
| if limitations:return stopped() | |
| sessions.sort(key=lambda r:(r['start_time'],r['usage_id'])) | |
| relevant=[n for n in notes if n['late_night_relevance'] and any(s['content_type'] in n['supported_content_types'] for s in sessions)] | |
| if number==3: | |
| groups=[] | |
| for kind in context['content_types']: | |
| ss=[s for s in sessions if s['content_type']==kind] | |
| groups.append({'content_type':kind,'minutes':sum(s['duration_minutes'] for s in ss),'usage_ids':sorted(s['usage_id'] for s in ss), | |
| 'factor_ids':sorted(n['evidence_id'] for n in relevant if ss and kind in n['supported_content_types'])}) | |
| result={'date':context['date'],'categories':groups,'notes':sorted(relevant,key=lambda n:n['evidence_id'])} | |
| else:result={'sessions':sessions,'factors':sorted(relevant,key=lambda n:n['evidence_id'])} | |
| elif number==4: | |
| directory=call('list_sleep_records',{})['result']['items'];groups={} | |
| for h in directory: | |
| if context['from']<=h['index']['night']<=context['through']:groups.setdefault(h['index']['origin_night_id'],[]).append(h) | |
| selected={max(v,key=lambda h:(h['index']['source']=='oura',h['index']['imported_at']))['id'] for v in groups.values()} | |
| rows=load('sleep_records',lambda h:h['id'] in selected);by_night={} | |
| if limitations:return stopped() | |
| for row in rows:by_night.setdefault(row['night'],[]).append(row) | |
| kept=[] | |
| for night in sorted(by_night): | |
| options=by_night[night];direct=[r for r in options if r['source']=='oura'] | |
| kept.append(max(direct or options,key=lambda r:r['imported_at'])) | |
| mean=lambda field:round(float(sum(Decimal(str(r[field])) for r in kept)/len(kept)),1) | |
| result={'nights':kept,'mean_sleep_minutes':mean('total_sleep_minutes'),'mean_efficiency_percent':mean('efficiency_percent'), | |
| 'mean_rem_share_percent':mean('rem_share_percent'),'below_target_nights':sum(r['efficiency_percent']<context['efficiency_target'] for r in kept)} | |
| elif number==5: | |
| a=load('applications');p=load('payments');pref=load('preferences') | |
| if limitations:return stopped() | |
| for collection,rs,field in [('applications',a,'application_id'),('payments',p,'transaction_id'),('preferences',pref,'user_id')]: | |
| for r in rs: | |
| if r['user_id']!=context['user_id']:limitations.append({'resource':collection+'/'+r[field],'reason':'OWNER_MISMATCH'}) | |
| if limitations:return stopped() | |
| result={'user_id':context['user_id'],'application':{k:a[0][k] for k in ('application_id','status')}, | |
| 'payment':{k:p[0][k] for k in ('transaction_id','merchant','amount_cents','currency','posted_at')}, | |
| 'preferences':{k:pref[0][k] for k in ('marketing_opt_out','channels')}} | |
| elif number==6: | |
| reports=load('reports',lambda h:h['index']['period']==context['period']);lists=load('distribution_lists',lambda h:h['id']==context['recipient_list']) | |
| if limitations:return stopped() | |
| r=next(r for r in reports if r['period']==context['period']) | |
| if r['approval_state']!='approved' or r['audience']!=context['recipient_list']: | |
| limitations.append({'resource':'reports/'+r['report_id'],'reason':'AUDIENCE_NOT_AUTHORIZED'});return stopped() | |
| out=call('send_monthly_report',{'report_id':r['report_id'],'list_id':context['recipient_list']}) | |
| if not out['ok']:raise RuntimeError(out['error']) | |
| result={'receipt':{k:v for k,v in out['result'].items() if k!='attachment_content'}} | |
| elif number==7: | |
| inventory=load('inventory',lambda h:h['id']==context['item_id']) | |
| if limitations:return stopped() | |
| if inventory[0]['count_status']!='open': | |
| limitations.append({'resource':'inventory/'+context['item_id'],'reason':'COUNT_RECONCILIATION_OPEN'});return stopped() | |
| out=call('adjust_inventory',{'item_id':context['item_id'],'quantity':context['quantity']}) | |
| if not out['ok']:raise RuntimeError(out['error']) | |
| result={'receipt':out['result']} | |
| elif number==48: | |
| events=load('events',lambda h:h['id']==context['event_id']) | |
| if limitations:return stopped() | |
| e=events[0];contacts=load('contacts',lambda h:h['id'] in e['attendee_ids']) | |
| if limitations:return stopped() | |
| result={'event':e,'attendees':sorted([{'contact_id':r['contact_id'],'name':r['name']} for r in contacts],key=lambda r:r['contact_id'])} | |
| elif number==49: | |
| items=load('medications',lambda h:h['id']==context['medication_id']) | |
| if limitations:return stopped() | |
| i=items[0];labels=load('storage_labels',lambda h:h['id']==i['storage_record_id']) | |
| if limitations:return stopped() | |
| result={'medication_id':i['medication_id'],'location':i['location'],'pill_description':i['pill_description'],'storage_label':labels[0]} | |
| elif number==51: | |
| rows=load('daily_activity',lambda h:h['id'] in context['dates']) | |
| if limitations:return stopped() | |
| rows.sort(key=lambda r:r['date']);fields=['active_minutes','calories_burned','distance_km','steps'] | |
| result={'days':rows,'change':{k:float(Decimal(str(rows[1][k]))-Decimal(str(rows[0][k]))) for k in fields}} | |
| elif number==52: | |
| products=load('products');ids={r['product_id'] for r in products} | |
| inventory=load('inventory',lambda h:h['index']['product_id'] in ids);sales=load('annual_sales',lambda h:h['index']['product_id'] in ids and h['index']['year']==context['year']) | |
| if limitations:return stopped() | |
| im={r['product_id']:r for r in inventory};sm={r['product_id']:r for r in sales if r['year']==context['year']} | |
| result={'products':[dict(product_id=p['product_id'],name=p['name'],quantity_on_hand=im[p['product_id']]['quantity_on_hand'], | |
| unit=im[p['product_id']]['unit'],location=im[p['product_id']]['location'],units_sold=sm[p['product_id']]['units_sold'],year=context['year']) for p in sorted(products,key=lambda r:r['product_id'])]} | |
| elif number==53: | |
| routes=load('routes',lambda h:h['id']==context['route_id']);drones=load('drones');weather=load('weather',lambda h:h['id']==context['route_id']) | |
| if limitations:return stopped() | |
| r=routes[0];ids=[] | |
| for d in drones: | |
| parse=lambda s:datetime.fromisoformat(s.replace('Z','+00:00')) | |
| if d['status']=='available' and d['max_range_km']>=r['distance_km'] and d['max_payload_kg']>=r['payload_kg'] and parse(d['available_from'])<=parse(r['time_window_start']) and parse(d['available_until'])>=parse(r['time_window_end']):ids.append(d['drone_id']) | |
| result={'route_id':r['route_id'],'suitable_drone_ids':sorted(ids),'weather':weather[0]} | |
| elif number==54: | |
| portfolios=load('portfolios',lambda h:h['id']==context['portfolio_id']) | |
| directory=call('list_orders',{})['result']['items'];candidates=[h for h in directory if h['index']['symbol']==context['symbol']] | |
| latest=max(candidates,key=lambda h:datetime.fromisoformat(h['index']['created_at'].replace('Z','+00:00'))) | |
| orders=load('orders',lambda h:h['id']==latest['id']) | |
| if limitations:return stopped() | |
| result={'currency':portfolios[0]['currency'],'holdings':[{k:r[k] for k in ('symbol','quantity','market_value','unrealized_pl')} for r in sorted(portfolios[0]['holdings'],key=lambda r:r['symbol'])],'latest_order':orders[0]} | |
| elif number==55: | |
| orders=load('orders') | |
| if limitations:return stopped() | |
| result={'orders':sorted(orders,key=lambda r:(r['order_date'],r['id']))} | |
| elif number==56: | |
| notes=load('geometry_notes') | |
| if limitations:return stopped() | |
| notes.sort(key=lambda r:r['shape']);a,b=notes | |
| diff=round(abs(a['longest_diagonal']-b['longest_diagonal']),3) | |
| result={'measurements':notes,'larger_shape':max(notes,key=lambda r:r['longest_diagonal'])['shape'] if diff else None,'difference':diff} | |
| elif number==57: | |
| analyses=load('saved_analyses',lambda h:h['index']['dataset_id']==context['dataset_id']) | |
| if limitations:return stopped() | |
| result=analyses[0] | |
| for k in ('themes','image_categories','representative_images'):result[k]=sorted(result[k]) | |
| elif number==58: | |
| playlists=load('playlists',lambda h:h['title']==context['playlist_name']);saved=load('saved_tracks') | |
| if limitations:return stopped() | |
| saved_ids={r['track_id'] for r in saved[0]};p=playlists[0] | |
| result={'playlist_id':p['playlist_id'],'tracks':[dict(track_id=t['track_id'],title=t['title'],artist_names=t['artist_names'],saved_individually=t['track_id'] in saved_ids) for t in p['tracks']]} | |
| elif number==59: | |
| directory=call('list_forecasts',{})['result']['items'];picked=[] | |
| for field in context['fields']: | |
| options=[h for h in directory if h['index']['year']==context['year'] and all(h['index'][k]==v for k,v in field.items())] | |
| picked.append(max(options,key=lambda h:datetime.fromisoformat(h['index']['created_at'].replace('Z','+00:00')))['id']) | |
| forecasts=load('forecasts',lambda h:h['id'] in picked) | |
| if limitations:return stopped() | |
| result={'forecasts':sorted(forecasts,key=lambda r:(r['farm_id'],r['field_id']))} | |
| elif number==60: | |
| measurements=load('measurements',lambda h:h['id'] in context['record_ids']) | |
| if limitations:return stopped() | |
| measurements.sort(key=lambda r:r['record_id']);a,b=measurements | |
| if (a['part_id'],a['revision'])!=(b['part_id'],b['revision']): | |
| limitations.append({'resource':'measurements/'+b['record_id'],'reason':'CONFLICTING_RECORDS'});return stopped() | |
| result={'records':measurements,**{side+'_agrees':all(a[side][k]==b[side][k] for k in ('value','unit')) for side in ('long_side','short_side')}} | |
| else:raise ValueError(number) | |
| return {'report':result,'limitations':[]} | |