import contextlib import dataclasses import json import os import platform import sys import unittest from pathlib import Path from unittest.mock import patch from helpers import IMAGE_ID, Fixture, local_tools, record_run from pvbench_common.container import Outcome from t2 import evaluate from t2.config import Config, Case from t2.eval_toolchain import ContainerRunner, StageFailure, Toolchain, Tools from t2.io import write_json from t2.workspace import collect from t2.submission import check_c, check_helper from t2.obligations import interface, assumption_names GOAL='Definition toy_goal : Prop := True.\nModule Type VC_Correct.\nAxiom proof_of_toy : toy_goal.\nEnd VC_Correct.\n' AUTO='Lemma proof_of_toy : toy_goal.\nProof. Admitted.\n' MANUAL='Require Import T2Eval.goal.\n' CHECK='From T2Eval Require Import goal proof_auto manual.\nModule VC_Correctness : VC_Correct.\nInclude proof_auto.\nInclude manual.\nEnd VC_Correctness.\n' class SubmissionTests(unittest.TestCase): def test_preserves_tokens_literals_and_preprocessor_boundaries(self): original='int f() /*@ Require emp Ensure __return == 1 && emp */ { const char *x="a b"; return 1; }' self.assertFalse(check_c(original,original.replace('return 1;', '/*@ Assert emp */ return 1;'))[0]) for edited in (original.replace('a b','ab'), original.replace('return 1','return 2'),original.replace('int f','int g')): self.assertIn('CODE_CHANGED',[p['code'] for p in check_c(original,edited)[0]]) macro='#define X 1\nint f(){return X;}\n' self.assertTrue(check_c(macro,macro.replace('1\nint','1 int'))[0]) self.assertTrue(check_c('void f(){L\"hello\";}','void f(){L \"hello\";}')[0]) self.assertTrue(check_c('int f(){return a + +b;}','int f(){return a ++b;}')[0]) self.assertFalse(check_c('int f(){return 1;}','int f(){re\\\nturn 1;}')[0]) def test_multiple_located_invalid_findings(self): original='int f()\n/*@ Require emp Ensure __return == 1 && emp */\n{return 1;}' changed=original.replace('__return == 1','__return == 2').replace('return 1;','return 2;') errors,_=check_c(original,changed) self.assertIn('PUBLIC_CONTRACT_CHANGED',[e['code'] for e in errors]) self.assertIn('CODE_CHANGED',[e['code'] for e in errors]) self.assertTrue(all(e['line']>=1 and e['column']>=1 for e in errors)) def test_auxiliary_declaration_for_existing_function(self): original='int f(int x) /*@ Require emp Ensure __return == x && emp */ {return x;}' aux='int f(int x) /*@ aux With x Require emp Ensure __return == x && emp */;\n' self.assertEqual(check_c(original,aux+original)[0],[]) self.assertTrue(check_c(original,aux.replace('int x','char x')+original)[0]) self.assertTrue(check_c(original,'int evil(){return 0;}\n'+original)[0]) def test_safeexec_public_contract_moved_to_refinement_prototype(self): original='#include "safeexec_def.h"\nint f(int x) /*@ With n Require x == n && emp Ensure __return == n && emp */ {return x;}' candidate='#include "safeexec_def.h"\nint f(int x) /*@ public <= auxiliary With n Require x == n && emp Ensure __return == n && emp */;\nint f(int x) /*@ auxiliary With X Require safeExec(X) && emp Ensure safeExec(X) && emp */ {return x;}' self.assertEqual(check_c(original,candidate)[0],[]) declarations='/*@ Extern Coq (desired: Z -> Prop) */\n/*@ Import Coq Require Import PVbench.Toy.rocq.spec_lib */\n' self.assertEqual(check_c(original.replace('int f',declarations+'int f',1), candidate.replace('int f',declarations+'int f',1))[0],[]) for changed in (candidate.replace('public <= auxiliary','public <= disconnected'), candidate.replace('__return == n','__return == 0'), candidate.replace('int f(int x) /*@ public','int g(int x) /*@ public')): self.assertTrue(check_c(original,changed)[0]) def test_helper_comments_binders_imports_and_shadowing(self): valid='(* Axiom secret. (* Admitted. *) *)\nRequire Import Coq.ZArith.ZArith.\nLemma okay : forall x:Z, x=x. Proof. reflexivity. Qed.' self.assertEqual(check_helper(valid,{'Fixed'},'PVbench.Toy.rocq',('Coq',))[0],[]) for text,code in [('Axiom leak : False.','FORBIDDEN_HELPER_COMMAND'), ('Lemma x : False. Admitted.','UNPROVED_ASSUMPTION'), ('Definition Fixed := False.','SPEC_SYMBOL_SHADOWED'), ('Require Import Other.secret.','FORBIDDEN_DEPENDENCY'), ('Set Guard Checking.','UNSAFE_PROOF_SETTING'), ('Local Unset Guard Checking.','UNSAFE_PROOF_SETTING'), ('Polymorphic Definition Fixed := False.','SPEC_SYMBOL_SHADOWED'), ('Declare ML Module "evil".','FORBIDDEN_HELPER_COMMAND'), ('Timeout 2 Axiom bad : False.','FORBIDDEN_HELPER_COMMAND'), ('Variable x : False.','UNPROVED_ASSUMPTION')]: self.assertIn(code,[p['code'] for p in check_helper(text,{'Fixed'},'PVbench.Toy.rocq',('Coq',))[0]]) def test_section_hypotheses_and_unknown_syntax(self): text='Section S. Variable P : Prop. Hypothesis h : P. Lemma identity : P. Proof. exact h. Qed. End S.' self.assertFalse(check_helper(text,set(),'PVbench.Toy.rocq',('Coq',))[0]) errors,_=check_helper('Elpi SomeCommand.',set(),'PVbench.Toy.rocq',('Coq',)) self.assertEqual(errors[0]['class'],'infrastructure') def test_extend_or_regroup_extern_block_without_redeclaring_fixed_symbols(self): original='/*@ Extern Coq (Pre : Z -> Prop) (Array::full : Z -> (Z -> Prop)) */\nint f(){return 1;}' extended=original.replace('(Pre :', '(Array::missing : Z -> Prop) (Pre :') self.assertEqual(check_c(original,extended)[0],[]) regrouped=original.replace(' (Array::full', ' */\n/*@ Extern Coq (Array::full') self.assertEqual(check_c(original,regrouped)[0],[]) for changed in (extended.replace('Pre : Z','Pre : nat'), extended.replace('(Pre : Z -> Prop)',''), extended.replace('Array::full','Array::other'), extended.replace('int f()', 'int f() /*@ Extern Coq (Pre : nat -> Prop) */')): with self.subTest(changed=changed): self.assertTrue(check_c(original,changed)[0]) # repeating a fixed binding unchanged is harmless; rebinding it is not self.assertEqual(check_c(original,extended.replace('int f()', 'int f() /*@ Extern Coq (Pre : Z -> Prop) */'))[0],[]) errors,_=check_c(original,extended.replace('(Array::missing : Z -> Prop)','(Array::full : Z -> Prop)')) self.assertTrue(any(p['code']=='SPEC_SYMBOL_SHADOWED' and 'Array::full' in p['message'] for p in errors)) self.assertFalse(any('symbol Array ' in p['message'] for p in errors)) def test_manual_counts_exclude_aborted_split_hints(self): manual='Lemma split_hint : True. Proof. Abort.\nLemma proof_of_toy : toy_goal. Proof. Admitted.\n' info=interface(GOAL,'',manual) self.assertEqual(list(info['manual']),['proof_of_toy']) self.assertEqual(list(info['required_manual']),['proof_of_toy']) self.assertEqual(list(info['manual_auxiliary']),['split_hint']) self.assertEqual(info['manual_declarations']['split_hint']['status'],'abort') self.assertFalse(interface(GOAL,AUTO,'Lemma split_hint : True. Proof. Abort.')['manual']) self.assertFalse(interface(GOAL,'','Lemma proof_of_toy : toy_goal. Proof. exact I. Qed.')['manual']) self.assertTrue(interface(GOAL,'','Lemma proof_of_toy : toy_goal. Proof. Abort.')['manual']) with self.assertRaises(ValueError): interface(GOAL,'','Lemma proof_of_toy : toy_goal. Proof.') def test_complete_interface_not_lemma_count(self): self.assertEqual(list(interface(GOAL,AUTO,MANUAL)['required']),['proof_of_toy']) with self.assertRaises(ValueError): interface(GOAL,'',MANUAL) with self.assertRaises(ValueError): interface('Definition x := 1.',AUTO,MANUAL) self.assertEqual(assumption_names('Closed under the global context\n'),set()) self.assertEqual(assumption_names('Axioms:\nT2Eval.proof_auto.a : True\n'),{'T2Eval.proof_auto.a'}) with self.assertRaises(ValueError): assumption_names('coqc terminated before report') class EvaluationTests(Fixture): def finished(self): manifest=self.prepared() collection=collect(self.case,manifest) summary={'status':'completed','returncode':0,'collection':collection} write_json(self.case.root/'summary.json',summary) write_json(self.case.evidence/'status.json',summary) record_run(self.cfg,self.case) self.binary('coqc',"import sys\nprint('Closed under the global context' if sys.argv[-1].endswith('assumptions.v') else 'fake coqc')\n") self.generator() def generator(self,auto=AUTO,manual=MANUAL,goal=GOAL,missing=False): script="from pathlib import Path\nimport sys\n" script+="root=Path(next(a.split('=',1)[1] for a in sys.argv if a.startswith('--goal-file='))).parent\n" script+=f"files={dict({'goal.v':goal,'proof_auto.v':auto,'manual.v':manual},**({} if missing else {'goal_check.v':CHECK}))!r}\n" script+="for name,text in files.items(): (root/name).write_text(text)\n" self.binary('symexec',script) def fake_adapter(self): # Evaluation stages run as direct children (LocalRunner) instead of EVAL containers; # fresh files, stages and verdict logic are the production code. return local_tools(self) def run_eval(self,**kw): with self.fake_adapter(): return evaluate.evaluate(self.cfg,self.case,**kw) def test_resolved_unapproved_helper_import_updates_validity(self): from t2.eval_toolchain import StageFailure self.finished() (self.case.root/'out/helper_lib.v').write_text('Require Import Lia.') with patch('t2.evaluate.check_short_imports', side_effect=StageFailure('INVALID', 'FORBIDDEN_DEPENDENCY: Lia resolves outside approved libraries')) as resolve: result=self.run_eval() resolve.assert_called_once() self.assertEqual(result['verdict'],'INVALID') self.assertEqual(result['validity'],'INVALID') report=json.loads((evaluate.eval_directory(self.cfg,self.case)/'validity.json').read_text()) self.assertEqual(report['status'],'INVALID') self.assertEqual(report['findings'][-1]['code'],'FORBIDDEN_DEPENDENCY') self.assertNotIn('helper_lib',[s['name'] for s in result['stages']]) def test_specification_dependency_is_frozen_and_compiled_first(self): dependency=self.bench/'Dependency/rocq' dependency.mkdir(parents=True) (dependency/'spec_lib.v').write_text('Definition dependency_value := 1.') (self.bench/'Toy/rocq/spec_lib.v').write_text('Require Import PVbench.Dependency.rocq.spec_lib. Definition public_value := dependency_value.') self.finished() r=self.run_eval() self.assertEqual(r['verdict'],'ACCEPT',r) names=[s['name'] for s in r['stages']] self.assertLess(names.index('spec_dependency_0'),names.index('spec_lib')) saved=evaluate.eval_directory(self.cfg,self.case)/'inputs/spec_dependencies/Dependency/rocq/spec_lib.v' self.assertEqual(saved.read_text(),'Definition dependency_value := 1.') from t2.judge_task import files_at self.assertIn('inputs/spec_dependencies/Dependency/rocq/spec_lib.v',files_at(saved.parents[4])) def test_answer_header_and_extra_library_are_built_and_checked(self): self.finished() (self.case.root/'out/defs.h').write_text('/*@ Extern Coq (extra_pred : Z -> Prop) */\n') (self.case.root/'out/solution_annotated.c').write_text('#include "defs.h"\n'+(self.bench/'Toy/rocq/solution_spec.c').read_text()) (self.case.root/'out/helper_lib.v').write_text('Require Import T2Answer.lemmas.\nDefinition h := l.') (self.case.root/'out/lemmas.v').write_text('Definition l := 1.') r=self.run_eval() self.assertEqual(r['verdict'],'ACCEPT',r) names=[s['name'] for s in r['stages']] self.assertLess(names.index('lemmas'),names.index('helper_lib')); self.assertIn('lemmas_assumptions_0',names) directory=evaluate.eval_directory(self.cfg,self.case) self.assertEqual((directory/'snapshot/defs.h').read_text(),'/*@ Extern Coq (extra_pred : Z -> Prop) */\n') self.assertTrue((directory/'snapshot/lemmas.v').exists()) def test_answer_library_cycle_and_missing_import_are_invalid(self): self.finished() (self.case.root/'out/helper_lib.v').write_text('Require Import T2Answer.a.') (self.case.root/'out/a.v').write_text('Require Import T2Answer.helper_lib.') r=self.run_eval() self.assertEqual(r['verdict'],'INVALID'); self.assertIn('FORBIDDEN_DEPENDENCY',[e['code'] for e in r['errors']]) def test_automatic_accept_is_complete_and_does_not_touch_run(self): self.finished(); before=(self.case.root/'summary.json').read_bytes() r=self.run_eval() self.assertEqual(r['verdict'],'ACCEPT',r) self.assertFalse(r['judge_ready']) names=[s['name'] for s in r['stages']] self.assertIn('goal_check',names); self.assertIn('assumptions_0',names) self.assertEqual((self.case.root/'summary.json').read_bytes(),before) self.assertFalse((evaluate.eval_directory(self.cfg,self.case)/'judge-input.json').exists()) def test_manual_goals_ready_without_gold_reuse_or_model(self): self.finished(); self.generator(auto='',manual='Lemma proof_of_toy : toy_goal. Proof. Admitted.\n') r=self.run_eval() self.assertEqual(r['verdict'],'JUDGE_READY',r) self.assertNotIn('goal_check',[s['name'] for s in r['stages']]) self.assertEqual(r['manual_obligations'],1) def test_fixed_vc_assumptions_checked_before_judge_ready(self): from t2.eval_toolchain import StageFailure self.finished(); self.generator(auto='',manual='Lemma proof_of_toy : toy_goal. Proof. Admitted.\n') def audit(*args): if args[-1]=='fixed_vc_assumptions':raise StageFailure('INFRA_ERROR','Unapproved fixed VC assumption') return [] with patch('t2.evaluate.audit_assumptions',side_effect=audit):result=self.run_eval() self.assertEqual(result['verdict'],'INFRA_ERROR') self.assertFalse(result['judge_ready']) def test_aborted_split_hints_do_not_need_judging_when_exports_are_automatic(self): self.finished(); self.generator(manual='Lemma unused_split_hint : True. Proof. Abort.') result=self.run_eval() self.assertEqual(result['verdict'],'ACCEPT',result) self.assertEqual(result['manual_obligations'],0) self.assertEqual(result['manual_auxiliary_declarations'],1) self.assertIn('goal_check',[stage['name'] for stage in result['stages']]) def test_no_hash_gate_and_no_candidate_wrapper_execution(self): self.finished() m=json.loads((self.case.evidence/'manifest.json').read_text()); m['inputs']={'changed':'value'}; m['fixed_files']={} write_json(self.case.evidence/'manifest.json',m) (self.case.workspace/'answer/feedback/latest.json').write_text('{}') (self.case.workspace/'answer/solution_annotated.c').write_text('new unsaved answer') (self.case.workspace/'answer/extra.tmp').write_text('scratch') r=self.run_eval(); self.assertEqual(r['verdict'],'ACCEPT',r) def test_code_and_contract_invalid_no_tools_and_detailed_files(self): self.finished(); p=self.case.root/'out/solution_annotated.c' p.write_text(p.read_text().replace('== 1','== 2').replace('return 1','return 2')) with patch('t2.eval_toolchain.Toolchain.execute',side_effect=AssertionError('no tool may run')): r=self.run_eval() self.assertEqual(r['verdict'],'INVALID') root=evaluate.eval_directory(self.cfg,self.case) self.assertIn('CODE_CHANGED',(root/'validity.txt').read_text()) self.assertIn('PUBLIC_CONTRACT_CHANGED',(root/'validity.txt').read_text()) self.assertGreaterEqual(len(json.loads((root/'validity.json').read_text())['findings']),2) def test_check_cli_never_launches_tools_and_eval_parser(self): self.finished() from t2.cli import main, parser import contextlib, io with patch('t2.cli.Config.load',return_value=self.cfg), patch('t2.eval_toolchain.Toolchain.execute',side_effect=AssertionError('tool')), contextlib.redirect_stdout(io.StringIO()): self.assertEqual(main(['check','--config','unused','--case','Toy','--model','fake-model','--mask','unit']),0) self.assertTrue((self.case.root/'validity.txt').exists()) self.assertTrue(parser().parse_args(['eval','--config','unused','--case','Toy','--model','fake-model','--force']).force) def test_lock_blocks_parallel_overwrite(self): self.finished(); root=evaluate.eval_directory(self.cfg,self.case) with evaluate.exclusive(root): with self.assertRaisesRegex(ValueError,'locked'): self.run_eval() self.assertFalse(root.exists()) def test_collection_errors_block_judging(self): self.finished() summary=json.loads((self.case.root/'summary.json').read_text()) summary['collection']['errors']=['helper could not be collected'] write_json(self.case.root/'summary.json',summary) write_json(self.case.evidence/'collection.json',summary['collection']) r=self.run_eval(); self.assertEqual(r['verdict'],'INFRA_ERROR',r) self.assertIn('COLLECTION_INCOMPLETE',[x['code'] for x in r['errors']]) def test_resource_and_missing_tool_errors_are_infrastructure(self): self.finished(); self.eval_timeout=0.5 self.binary('coqc','import time\ntime.sleep(2)\n') r=self.run_eval(); self.assertEqual(r['verdict'],'INFRA_ERROR',r) self.assertFalse(r['judge_ready']) self.assertIn('time limit',r['errors'][0]['message']) self.eval_timeout=10; self.coqc.unlink() r=self.run_eval(force=True); self.assertEqual(r['verdict'],'INFRA_ERROR',r) def test_symexec_failure_and_logs(self): self.finished(); self.binary('symexec',"import sys\nprint('annotation error line 6',file=sys.stderr)\nsys.exit(1)\n") r=self.run_eval(); self.assertEqual(r['verdict'],'SYMEXEC_FAIL',r) self.assertIn('annotation error line 6',r['errors'][0]['message']) self.assertFalse(r['judge_ready']) def test_helper_compile_failure_and_missing_generation(self): self.finished(); (self.case.root/'out/helper_lib.v').write_text('Definition helper := missing_symbol.\n') self.binary('coqc',"import sys\nif sys.argv[-1].endswith('helper_lib.v'): print('unknown identifier',file=sys.stderr); sys.exit(1)\n") r=self.run_eval(); self.assertEqual(r['verdict'],'COMPILE_FAIL',r) self.binary('coqc',"print('Closed under the global context')\n"); self.generator(missing=True) r=self.run_eval(force=True); self.assertEqual(r['verdict'],'INFRA_ERROR',r) self.assertIn('goal_check.v',r['errors'][0]['message']) def test_no_overwrite_and_force_archives(self): self.finished(); self.run_eval() root=evaluate.eval_directory(self.cfg,self.case) old=(root/'summary.json').read_bytes() with self.assertRaises(ValueError): self.run_eval() self.assertEqual((root/'summary.json').read_bytes(),old) self.run_eval(force=True) archives=list(root.parent.glob(root.name+'.archived-*')) self.assertEqual(len(archives),1) previous=json.loads((archives[0]/'summary.json').read_text()) self.assertTrue((archives[0]/previous['stages'][0]['stdout']).is_file()) self.assertFalse(Path(previous['stages'][0]['stdout']).is_absolute()) def test_missing_output_and_symlink_are_invalid(self): self.finished(); p=self.case.root/'out/solution_annotated.c'; p.unlink() self.assertEqual(self.run_eval()['verdict'],'INVALID') try: p.symlink_to(self.case.workspace/'problem/solution_spec.c') except OSError as exc: if getattr(exc, 'winerror', None) == 1314: self.skipTest('Windows symlink privilege is unavailable; native reparse tests cover the adapter') raise self.assertEqual(self.run_eval(force=True)['verdict'],'INVALID') def test_dry_run_or_original_changed_is_infrastructure(self): self.prepared() self.assertEqual(self.run_eval()['verdict'],'INFRA_ERROR') def test_unapproved_assumptions_never_accept(self): self.finished() self.binary('coqc',"import sys\nif sys.argv[-1].endswith('assumptions.v'): print('Axioms:\\nUnknown.unsound : False')\n") r=self.run_eval(); self.assertEqual(r['verdict'],'INFRA_ERROR',r) self.assertIn('Unknown.unsound',r['errors'][0]['message']) def test_helper_assumptions_checked_before_judge_ready(self): self.finished(); (self.case.root/'out/helper_lib.v').write_text('Definition helper := True.\n') self.generator(auto='',manual='Lemma proof_of_toy : toy_goal. Proof. Admitted.\n') self.binary('coqc',"import sys\nif sys.argv[-1].endswith('assumptions.v'): print('Axioms:\\nUnknown.unsound : False')\n") r=self.run_eval(); self.assertEqual(r['verdict'],'INFRA_ERROR',r) self.assertFalse(r['judge_ready']) def test_timeout_saved_submission_eligible(self): self.finished() for p in (self.case.root/'summary.json',self.case.evidence/'status.json'): s=json.loads(p.read_text()); s.update(status='timeout',returncode=-9); write_json(p,s) self.assertEqual(self.run_eval()['verdict'],'ACCEPT') def test_audit_flags_confirmed_writes_outside_writable_container_paths(self): import shlex self.finished(); events=self.case.evidence/'events.jsonl' event={'type':'item.completed','item':{'type':'command_execution', 'command':'touch '+shlex.quote('/opt/qcp/Rocq/planted.v'),'exit_code':1}} done=json.dumps({'type':'turn.completed','usage':{}})+'\n' events.write_text(json.dumps(event)+'\n'+done) self.assertEqual(self.run_eval()['verdict'],'ACCEPT') event['item']['exit_code']=0; events.write_text(json.dumps(event)+'\n'+done) r=self.run_eval(force=True) self.assertEqual(r['verdict'],'INVALID') self.assertIn('UNAUTHORIZED_WRITE',[e['code'] for e in r['errors']]) for path in ('/work/answer/scratch.v','answer/x.v','/tmp/x','/home/coq/.cache/x'): event['item']['command']='touch '+path; events.write_text(json.dumps(event)+'\n'+done) self.assertEqual(evaluate.inspect(self.cfg,self.case)[0]['status'],'PASS',path) def test_run_validity_failures_are_infrastructure(self): self.finished() (self.case.workspace/'symexec.sh').write_text('exit 99\n') report,_=evaluate.inspect(self.cfg,self.case) self.assertEqual(report['status'],'INFRA_ERROR',report) self.assertIn('RUN_INTEGRITY',[f['code'] for f in report['findings']]) self.assertTrue(all(f['class']=='infrastructure' for f in report['findings'])) def test_environment_mismatch_needs_allow_flag(self): self.finished() with local_tools(self), patch('pvbench_common.container.image_id',return_value='sha256:'+'b'*64): r=evaluate.evaluate(self.cfg,self.case) self.assertEqual(r['verdict'],'INFRA_ERROR') self.assertEqual(r['errors'][0]['code'],'ENVIRONMENT') self.assertEqual(r['stages'],[]) r=evaluate.evaluate(self.cfg,self.case,force=True,allow_env_mismatch=True) self.assertEqual(r['verdict'],'ACCEPT',r) self.assertIn('image id mismatch',r['env_warnings'][0]) def test_batch_uses_saved_runner_and_no_models(self): self.finished(); path=self.root/'cases.txt'; path.write_text('Toy\nToy\n') with self.fake_adapter(): r=evaluate.eval_all(self.cfg,path,'fake-model','unit') self.assertEqual(r['counts'],{'ACCEPT':1}) self.assertEqual(r['duplicates_ignored'],['Toy']) def test_missing_batch_run_is_reported_without_stopping(self): self.finished(); path=self.root/'cases.txt'; path.write_text('Missing\nToy\n') with self.fake_adapter(): r=evaluate.eval_all(self.cfg,path,'fake-model','unit') self.assertEqual(r['counts'],{'INFRA_ERROR':1,'ACCEPT':1}) class ContainerRunnerTests(Fixture): """The EVAL-container path with a mocked container.run that executes eval.sh's contract.""" def fake_container(self, *, fail=None, timeout_at=None, oom_at=None): calls=[] def run(inv,*,timeout_s,stdout,stderr): calls.append((inv,timeout_s)) build=Path(next(h for h,at,mode in inv.mounts if at=='/work/answer')) phase=inv.command[-1].split('/')[-2] folder=build/'.t2'/phase script=(folder/'eval.sh').read_text() (folder/'coqlib.txt').write_text('/home/coq/.opam/x/lib/coq\n') timed_out=oom=False for line in script.splitlines(): if not line.startswith('step '): continue label=line.split()[1] if label==timeout_at: (folder/(label+'.out')).write_text(''); timed_out=True; break (folder/(label+'.out')).write_text('Closed under the global context\n' if 'assumptions' in label else 'fake '+label+'\n') (folder/(label+'.err')).write_text('boom\n' if label==fail else '') (folder/(label+'.ms')).write_text('5') if label=='symexec': goal=build/'goals' for name,text in self.generated.items(): (goal/name).write_text(text) if label==oom_at: (folder/(label+'.oom')).write_text('') code=137 if label==oom_at else 1 if label==fail else 0 (folder/(label+'.exit')).write_text(str(code)) if code: break Path(stdout).write_text(''); Path(stderr).write_text('') return Outcome(137 if timed_out else 0,timed_out,False,0.0,1.0,Path(stdout),Path(stderr)) return calls,run def setUp(self): super().setUp() self.generated={'goal.v':GOAL,'proof_auto.v':AUTO,'manual.v':MANUAL,'goal_check.v':CHECK} EvaluationTests.finished(self) def generator(self,**kw): EvaluationTests.generator(self,**kw) def evaluate(self,**kw): calls,run=self.fake_container(**kw) with patch('pvbench_common.container.run',side_effect=run): result=evaluate.evaluate(self.cfg,self.case,force=True) return result,calls def test_two_phases_in_eval_containers_with_container_paths(self): result,calls=self.evaluate() self.assertEqual(result['verdict'],'ACCEPT',result) self.assertEqual(result['evaluation_containers'],2) self.assertEqual(len(calls),2) directory=evaluate.eval_directory(self.cfg,self.case) for inv,timeout_s in calls: args=list(inv.args) self.assertEqual(args[args.index('--network')+1],'none') self.assertIn('--read-only',args) self.assertEqual([at for _,at,mode in inv.mounts if mode=='rw'],['/work/answer']) self.assertEqual([h for h,at,mode in inv.mounts if mode=='rw'],[str(directory/'build')]) self.assertLessEqual(timeout_s,self.cfg.task.limits.eval_timeout_s) first=(directory/'build/.t2/phase-1/eval.sh').read_text() for script in (first,(directory/'build/.t2/phase-2/eval.sh').read_text()): for host in ('/Users/',str(self.root),str(self.backend)): self.assertNotIn(host,script) self.assertIn('step coqc-version coqc --version || exit 0',first) self.assertIn('step symexec /opt/qcp/bin/symexec --goal-file=/work/answer/goals/goal.v',first) self.assertIn('/work/answer/spec/spec_lib.v',first) names=[s['name'] for s in result['stages']] self.assertEqual(names[:2],['coqc-version','spec_lib']) self.assertIn('goal_check',names) self.assertEqual(result['stages'][0]['container']['phase'],'phase-1') self.assertEqual((directory/'evidence/generation/spec_lib.stdout.log').read_text(),'fake spec_lib\n') versions=json.loads((directory/'evidence/tool-versions.json').read_text()) self.assertEqual(versions['coqc'],'fake coqc-version\n') self.assertEqual(versions['symexec']['image_id'],IMAGE_ID) def test_failure_stops_the_phase_and_keeps_the_verdict_mapping(self): result,calls=self.evaluate(fail='symexec') self.assertEqual(result['verdict'],'SYMEXEC_FAIL',result) self.assertEqual(len(calls),1) self.assertIn('boom',result['errors'][0]['message']) def test_timeout_and_oom_are_infrastructure_with_reasons(self): result,_=self.evaluate(timeout_at='spec_lib') self.assertEqual(result['verdict'],'INFRA_ERROR') self.assertEqual(result['stages'][-1]['status'],'timeout') self.assertIn('time limit',result['errors'][0]['message']) result,_=self.evaluate(oom_at='spec_lib') self.assertEqual(result['verdict'],'INFRA_ERROR') self.assertEqual(result['stages'][-1]['status'],'memory_limit') self.assertIn('memory limit 8g',result['errors'][0]['message']) def test_manual_goals_need_no_goal_check_container(self): self.generated['proof_auto.v']=''; self.generated['manual.v']='Lemma proof_of_toy : toy_goal. Proof. Admitted.\n' result,calls=self.evaluate() self.assertEqual(result['verdict'],'JUDGE_READY',result) self.assertEqual(len(calls),2) self.assertNotIn('goal_check',[s['name'] for s in result['stages']]) def test_runner_paths_and_unplanned_command_fallback(self): runner=ContainerRunner(self.cfg.task,self.cfg.image,'Toy',host_roots=(('/opt/qcp/Rocq',self.backend/'Rocq'),)) root=self.root/'direct'; root.mkdir() tool=Toolchain(Tools(self.cfg.tool_env(),runner,30),root) self.assertEqual(tool.path(tool.build/'goals/goal.v'),'/work/answer/goals/goal.v') self.assertEqual(tool.host_path('/work/answer/goals/goal.v'),tool.build/'goals/goal.v') self.assertEqual(tool.host_path('/opt/qcp/Rocq/sets/x.v'),self.backend/'Rocq/sets/x.v') self.assertIsNone(tool.host_path('/home/coq/x')) calls,run=self.fake_container() with patch('pvbench_common.container.run',side_effect=run): self.assertEqual(tool.execute('probe',['coqc','--version']),'fake probe\n') self.assertEqual(len(calls),1) self.assertEqual(tool.coqlib,'/home/coq/.opam/x/lib/coq') with self.assertRaises(StageFailure): runner.run(tool,[('bad label',['x'])],5) if __name__ == '__main__': unittest.main()