Upload folder using huggingface_hub
Browse filesFiles changed (3)
1234567891011121314151617181920212223242526272829303132333435363738"""Stable result protocol; candidate failures and evaluator errors stay distinct."""from pathlib import Pathimport contextlib,io,json,runpy,sysfrom auto_policy import install,finalizeHERE=Path(__file__).resolve().parent
def main(): captured=io.StringIO() try: install() with contextlib.redirect_stdout(captured): try:runpy.run_path(str(HERE/'autograde_task_check.py'),run_name='__main__') except SystemExit as error: if error.code not in(None,0):raise RuntimeError('Trusted checker exited '+str(error.code)) body=None for line in reversed(captured.getvalue().splitlines()): try:value=json.loads(line) except(ValueError,TypeError):continue if isinstance(value,dict)and isinstance(value.get('checks'),list):body=value;break if body is None:raise RuntimeError('Trusted checker did not emit its result schema') if body.get('status')=='evaluation_error'or body.get('protocol_valid')is False:raise RuntimeError('Trusted checker reports evaluator failure: '+str(body.get('error',''))) cfgfile=HERE/'auto_policy.json' if cfgfile.is_file(): cfg=json.loads(cfgfile.read_text());owners=cfg.get('runtime_owner_ids',cfg.get('owner_ids',[])) if owners:body=finalize(body,owners,require_execution=cfg.get('require_execution',True)) checks=body['checks'] if not checks or any(not isinstance(c,dict)or type(c.get('passed'))is not bool or not isinstance(c.get('id'),(int,str))or isinstance(c.get('id'),bool)for c in checks):raise RuntimeError('Trusted checker contains an unresolved or malformed criterion; no model score assigned') ids=[str(c['id'])for c in checks] if len(ids)!=len(set(ids)):raise RuntimeError('Duplicate criterion ID') contract=json.loads((HERE/'auto_contract.json').read_text());expected=contract['expected_check_ids'] if '--view'not in sys.argv and set(ids)!=set(expected):raise RuntimeError('Criterion IDs differ from fixed public contract') weights=contract['criterion_weights'] body.update(status='scored',scoreable=True,protocol_valid=True,score=sum(weights[str(c['id'])]for c in checks if c['passed'])/sum(weights[str(c['id'])]for c in checks),passed_checks=sum(c['passed']for c in checks),total_checks=len(checks),all_passed=all(c['passed']for c in checks)) print(json.dumps(body,ensure_ascii=True));return 0 except Exception as error: print(json.dumps(dict(status='evaluation_error',score=None,scoreable=False,protocol_valid=False,checks=[],error=type(error).__name__+': '+str(error),error_category='trusted_evaluator_or_environment',candidate_scored=False),ensure_ascii=True));return 2
if __name__=='__main__':raise SystemExit(main())123version https://git-lfs.github.com/spec/v1oid sha256:de36882a90b5542e5c3a0c2c6d154e51021531ab3befae4345f812bcc88f7911size 376123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Trusted bounded-invocation policy; never infer whole-program properties."""from pathlib import Pathimport hashlib,json,os,subprocess,sys,tempfile,time,uuid
HERE=Path(__file__).resolve().parentENV='MYBENCH_AUTO_POLICY_RECEIPTS'DEADLINE='MYBENCH_AUTO_POLICY_DEADLINE'class PolicyInfrastructureError(RuntimeError): pass_installed=False_original_popen=subprocess.Popen_original_run=subprocess.run
def _config(): p=HERE/'auto_policy.json' if not p.is_file():return None value=json.loads(p.read_text()) if not isinstance(value,dict):raise PolicyInfrastructureError('Invalid trusted runtime policy') return value
def _folder(): if ENV not in os.environ: os.environ[ENV]=tempfile.mkdtemp(prefix='autograde-policy-',dir='/tmp') p=Path(os.environ[ENV]);p.mkdir(parents=True,exist_ok=True);return p
def _python_target(command,cwd): if not isinstance(command,(list,tuple))or not command:return None argv=[os.fspath(x)for x in command] if 'python'not in Path(argv[0]).name.lower():return None i=1;flags=[] while i<len(argv)and argv[i].startswith('-'): flag=argv[i] if flag=='-m': if i+1>=len(argv):return None name=argv[i+1];p=Path(cwd)/name.replace('.','/') if not p.with_suffix('.py').is_file()and not(p/'__main__.py').is_file():return None return argv[0],flags,'module',name,argv[i+2:] if flag in ['-c','-']:return None flags.append(flag);i+=1 if flag in ['-W','-X']and i<len(argv):flags.append(argv[i]);i+=1 if i>=len(argv)or not argv[i].endswith('.py'):return None path=Path(argv[i]);path=path if path.is_absolute()else Path(cwd)/path path=path.resolve() if path==HERE or HERE in path.parents: if path.name in ['auto_policy.py','auto_policy_guard.py']:return None for value in argv[i+1:]: if not value.endswith('.py')or value.startswith('-'):continue subject=Path(value);subject=subject if subject.is_absolute()else Path(cwd)/subject subject=subject.resolve() if HERE not in subject.parents: return argv[0],flags,'probe',str(path),[str(subject),*argv[i+1:]] return None return argv[0],flags,'script',str(path),argv[i+1:]
def install(): global _installed if _installed:return _installed=True cfg=_config() if cfg is None:return _folder() os.environ.setdefault(DEADLINE,str(time.monotonic()+cfg.get('total_evaluation_budget_seconds',420))) class GuardedPopen(_original_popen): def __init__(self,args,*pos,**kwargs): cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(args,cwd) receipt=None if target: executable,flags,kind,value,tail=target;receipt=_folder()/(uuid.uuid4().hex+'.json') receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='launching',target=value))) if cfg.get('stdlib_only')and'-S'not in flags:flags=flags+['-S'] args=[executable,*flags,str(HERE/'auto_policy_guard.py'),str(receipt),str(HERE/'auto_policy.json'),kind,value,*tail] env=dict(kwargs.get('env')or os.environ);env[ENV]=str(_folder());kwargs['env']=env if target:kwargs['env'][DEADLINE]=os.environ[DEADLINE] try:super().__init__(args,*pos,**kwargs) except OSError as error: if receipt: receipt.write_text(json.dumps(dict(schema='bounded-policy-v1',state='infrastructure_error',error=repr(error)))) raise subprocess.Popen=GuardedPopen def bounded_run(*pos,**kwargs): command=pos[0]if pos else kwargs.get('args') cwd=Path(kwargs.get('cwd')or os.getcwd()).resolve() target=None if kwargs.get('shell')or kwargs.get('executable')else _python_target(command,cwd) if target is not None and (kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding'))and kwargs.get('errors')is None:kwargs['errors']='replace' if target is not None and cfg.get('execution_budget_seconds')is not None: budget=cfg['execution_budget_seconds'] if type(budget)not in(int,float)or not 0<budget<=120:raise PolicyInfrastructureError('Invalid public execution budget') kwargs['timeout']=budget remaining=float(os.environ[DEADLINE])-time.monotonic()if target is not None else None if remaining is not None and remaining>0:kwargs['timeout']=min(kwargs.get('timeout')or remaining,remaining) try: if remaining is not None and remaining<=0:raise subprocess.TimeoutExpired(command,0) result=_original_run(*pos,**kwargs) if target is not None and result.returncode<0: (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_terminated=True,signal=-result.returncode,violations=[]))) return subprocess.CompletedProcess(result.args,128-result.returncode,result.stdout,result.stderr) return result except subprocess.TimeoutExpired as error: if target is None:raise (_folder()/(uuid.uuid4().hex+'.json')).write_text(json.dumps(dict(schema='bounded-policy-v1',state='finished',target=target[3],target_present=True,execution_timeout=True,violations=[]))) textual=kwargs.get('text')or kwargs.get('universal_newlines')or kwargs.get('encoding') empty=''if textual else b'' def output(value): if value is None:return empty return value.decode(kwargs.get('encoding')or'utf-8',errors='replace')if textual and isinstance(value,bytes)else value return subprocess.CompletedProcess(command,124,output(error.stdout),output(error.stderr)) subprocess.run=bounded_run
def status(require_execution=True): install();p=_folder();rows=[] for receipt in sorted(p.glob('*.json')): try:row=json.loads(receipt.read_text()) except (OSError,ValueError)as error:raise PolicyInfrastructureError('Unreadable policy receipt: '+str(receipt))from error if row.get('schema')!='bounded-policy-v1'or row.get('state')in ['launching','infrastructure_error']: raise PolicyInfrastructureError('Runtime instrumentation did not initialize: '+str(receipt)) rows.append(row) if require_execution and not any(r.get('target_present')for r in rows):return False return not any(r.get('violations')or r.get('execution_timeout')or r.get('execution_terminated')for r in rows)
def finalize(body,owner_ids,require_execution=True): observed=status(require_execution=require_execution) wanted=set(map(str,owner_ids)) for row in body.get('checks',[]): if str(row['id'])in wanted: if type(row.get('passed'))is not bool:raise PolicyInfrastructureError('Legacy ambiguous component remains in runtime owner '+str(row['id'])) row['passed']=row['passed']and observed row['reason']=str(row.get('reason',''))+'; evaluated bounded runtime import/resource policy' body['scoreable']=all(type(row.get('passed'))is bool for row in body.get('checks',[])) body['runtime_policy']=dict(scope='actual grader-launched Python script/module invocations',passed=observed) return body
def run(*args,**kwargs): install();return subprocess.run(*args,**kwargs)benchmarks/skillbench-venus-e/tasks/f6cd774b7fe2b3b56e0861e7/evaluator/auto_entry.pyAdded+38
benchmarks/skillbench-venus-e/tasks/f6cd774b7fe2b3b56e0861e7/evaluator/auto_policy.jsonAdded+3
benchmarks/skillbench-venus-e/tasks/f6cd774b7fe2b3b56e0861e7/evaluator/auto_policy.pyAdded+133