File size: 5,780 Bytes
b1a18a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""CPU checks: .venv/bin/python -m unittest -v test_runtime

No cloud resources, task downloads, or model calls.
"""
import ast
import asyncio
import copy
import importlib.util
from pathlib import Path
from types import SimpleNamespace as NS
import unittest
from unittest.mock import patch

import bash_timeout
import compaction_task

ROOT = Path(__file__).resolve().parent


class RuntimeTests(unittest.TestCase):
    def test_bash_feedback_and_timeout(self):
        for command in ('', '  ', None):
            self.assertIn('No command was executed', bash_timeout.run_bash(command))
        self.assertEqual(bash_timeout.run_bash('printf hello'), 'hello')
        output = bash_timeout.run_bash('printf started; sleep 10', timeout=0.1)
        self.assertIn('started', output)
        self.assertIn('process group killed', output)

    def test_compaction_retains_exact_task_and_latest_summary(self):
        spec = importlib.util.find_spec('verifiers.v1.harnesses.utils.compaction')
        source = Path(spec.origin).read_text()
        updated = compaction_task.patch_source(source)
        self.assertEqual(compaction_task.patch_source(updated), updated)
        with self.assertRaises(RuntimeError):
            compaction_task.patch_source(source + '\n# unreviewed change\n')
        # Execute the real patched method with an inert model response.
        method = next(node for node in ast.walk(ast.parse(updated))
                      if isinstance(node, ast.AsyncFunctionDef) and node.name == 'compact')
        replies = iter(('first summary', 'latest summary'))

        async def chat(*args, **kwargs):
            return NS(choices=[NS(message=NS(content=next(replies), tool_calls=[]))])

        env = dict(chat=chat, COMPACTION_ATTEMPTS=3, CHECKPOINT_COMPACTION_PROMPT='summarize',
                   POST_COMPACTION_FRAMING='summary:', APIStatusError=RuntimeError)
        exec(compile(ast.Module(body=[method], type_ignores=[]), '<patched-compaction>', 'exec'), env)
        compactor = NS(client=None, model=None, tools=[], note_good=lambda messages: None)
        task = {'role': 'user', 'content': [{'type': 'text', 'text': 'Exact task\nDo not lose this.'}]}
        messages = [{'role': 'system', 'content': 'system'}, task, {'role': 'assistant', 'content': 'history'}]
        original = copy.deepcopy(messages)
        first = asyncio.run(env['compact'](compactor, messages))
        second = asyncio.run(env['compact'](compactor, first))
        self.assertEqual(messages, original)
        self.assertEqual(second[:2], original[:2])
        self.assertEqual(len(second), 3)
        self.assertIn('latest summary', second[2]['content'])
        self.assertNotIn('first summary', str(second))

    def test_shared_native_task_gate(self):
        # Avoid importing the launcher, which declares Modal resources.
        tree = ast.parse((ROOT / 'modal_training.py').read_text())
        gate = next(node for node in tree.body if isinstance(node, ast.FunctionDef)
                    and node.name == 'load_evaluation_tasks')
        namespace = {}
        exec(compile(ast.Module(body=[gate], type_ignores=[]), '<task-gate>', 'exec'), namespace)
        sources = [{'env': {'taskset': {'tasks': ['a']}}}]
        original = copy.deepcopy(sources)
        tasks = [NS(data=NS(name='a', upload_environment=True))]
        from contextlib import nullcontext
        with patch('task_source.git_credentials', return_value=nullcontext()), \
             patch('task_source.task_manifest', return_value={'a': 'digest'}), \
             patch('verifiers.v1.tasksets.harbor.HarborConfig.model_validate', side_effect=lambda value: value), \
             patch('verifiers.v1.tasksets.harbor.HarborTaskset') as loader:
            loader.return_value.load.return_value = tasks
            self.assertEqual(namespace['load_evaluation_tasks'](sources, {'a': 'digest'}), tasks)
            self.assertEqual(sources, original)
            with self.assertRaises(AssertionError):
                namespace['load_evaluation_tasks'](sources, {'a': 'wrong'})
            tasks[0].data.upload_environment = False
            with self.assertRaises(AssertionError):
                namespace['load_evaluation_tasks'](sources, {'a': 'digest'})
            tasks[0].data.upload_environment = True
            tasks[0].data.name = 'unexpected'
            with self.assertRaises(AssertionError):
                namespace['load_evaluation_tasks'](sources, {'a': 'digest'})


if __name__ == '__main__':
    unittest.main()


class FinalTrainingTests(unittest.TestCase):
    def test_frozen_native_budget_and_mutation_guards(self):
        from final_training import freeze, validate
        frozen=freeze()
        parsed=validate(frozen)
        self.assertEqual([source.group_size for source in parsed.orchestrator.train.source],[8,8])
        self.assertEqual(parsed.inference.vllm.api_server_count,1)
        self.assertEqual([len(shard['task_manifest']) for shard in frozen['evaluation_shards']],[11,12])
        for key,value in (('max_steps',11),('seq_len',60000)):
            changed=copy.deepcopy(frozen);changed['training'][key]=value
            with self.assertRaises(AssertionError):validate(changed)
        changed=copy.deepcopy(frozen);changed['heldout_tasks'][0]=changed['train_tasks'][0]
        with self.assertRaises(AssertionError):validate(changed)
        changed=copy.deepcopy(frozen);changed['training']['orchestrator']['train']['source'][0]['ratio']=1
        with self.assertRaises(AssertionError):validate(changed)
        changed=copy.deepcopy(frozen)
        changed['evaluation_shards'][0]['evaluation']['source'][0]['env']['agent']['harness']['env']['VF_BASH_LENGTH_RECOVERY']='0'
        with self.assertRaises(AssertionError):validate(changed)