Spaces:
Running
Running
File size: 6,917 Bytes
29ce591 | 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | """
validator_fix.py β Phase 2 simulation test suite.
Replicates exactly what openenv validate does:
1. Imports each grader function by dotted path from openenv.yaml
2. Calls it with various state types (dict, None, empty, Pydantic)
3. Asserts 0.0 < score < 1.0 (strictly, not on boundary)
Run:
python validator_fix.py
Expected: ALL TESTS PASS
"""
from __future__ import annotations
import sys
import os
import importlib
import traceback
import numpy as np
# ββ Add repo root to path so imports resolve the same way the validator does ββ
ROOT = os.path.dirname(os.path.abspath(__file__))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
# ββββββββββββββββββββββββββββ Helpers ββββββββββββββββββββββββββββββββββββββββ
PASS = "PASS"
FAIL = "FAIL"
results: list[bool] = []
def check(name: str, score, lo: float = 0.0, hi: float = 1.0):
"""Assert score is strictly within (lo, hi)."""
try:
val = float(score)
ok = lo < val < hi
except Exception as exc:
print(f" {FAIL} [{name}] could not cast to float: {exc}")
results.append(False)
return
sym = PASS if ok else FAIL
print(f" {sym} [{name}] score={val:.6f} range=({lo},{hi})")
results.append(ok)
# ββββββββββββββββββββββββββββ Load grader module βββββββββββββββββββββββββββββ
def load_grader(dotted_path: str):
"""
Mimics importlib-based dynamic loading that openenv validate uses.
dotted_path e.g. 'graders.grader_easy'
"""
module_name, fn_name = dotted_path.rsplit(".", 1)
mod = importlib.import_module(module_name)
return getattr(mod, fn_name)
# ββββββββββββββββββββββββββββ Build test states ββββββββββββββββββββββββββββββ
def make_states():
states = []
# 1. None
states.append(("None", None))
# 2. Empty dict
states.append(("empty_dict", {}))
# 3. Dict with score=0 (boundary β clamp must move it up)
states.append(("dict_score_0", {"score": 0.0}))
# 4. Dict with score=1 (boundary β clamp must move it down)
states.append(("dict_score_1", {"score": 1.0}))
# 5. Dict with valid mid score
states.append(("dict_score_0.5", {"score": 0.5}))
# 6. Dict with progress key
states.append(("dict_progress_0.8", {"progress": 0.8}))
# 7. Dict with negative score
states.append(("dict_score_neg", {"score": -99.0}))
# 8. Dict with huge score
states.append(("dict_score_big", {"score": 999.0}))
# 9. Dict with NaN
states.append(("dict_score_nan", {"score": float("nan")}))
# 10. Dict with inf
states.append(("dict_score_inf", {"score": float("inf")}))
# 11. String state (garbage)
states.append(("string_state", "garbage"))
# 12. Integer state
states.append(("int_state", 42))
# 13. List state
states.append(("list_state", [0.3, 0.7]))
# 14. Pydantic-like object (mock BaseModel)
try:
from pydantic import BaseModel
class MockState(BaseModel):
score: float = 0.6
task: str = "easy"
states.append(("pydantic_score_0.6", MockState()))
except ImportError:
pass
# 15. Real environment state (if environment.py is importable)
try:
from environment import EmailTriageEnv # type: ignore
env = EmailTriageEnv()
env.reset(task="easy")
real_state = env.state
states.append(("real_env_state_easy", real_state))
except Exception:
pass
return states
# ββββββββββββββββββββββββββββ Main test runner ββββββββββββββββββββββββββββββββ
def run_tests():
print("=" * 60)
print(" OpenEnv Phase 2 Validator Replica β grader score tests")
print("=" * 60)
# Grader paths from openenv.yaml
grader_paths = [
("task_easy", "graders.grader_easy"),
("task_medium", "graders.grader_medium"),
("task_hard", "graders.grader_hard"),
]
# ββ Step 1: verify grader modules load without error ββββββββββββββββββ
print("\n[Step 1] Loading grader functions via importlib...")
fns = {}
for task_name, dotted_path in grader_paths:
try:
fn = load_grader(dotted_path)
fns[task_name] = fn
print(f" {PASS} Loaded '{dotted_path}' β {fn}")
except Exception as exc:
print(f" {FAIL} Could not load '{dotted_path}': {exc}")
traceback.print_exc()
results.append(False)
if not fns:
print("\nFATAL: No grader functions loaded. Cannot continue.")
return
# ββ Step 2: run each grader against every test state ββββββββββββββββββ
states = make_states()
print(f"\n[Step 2] Testing {len(fns)} graders Γ {len(states)} states = "
f"{len(fns) * len(states)} checks\n")
for task_name, fn in fns.items():
print(f" --- {task_name} ({fn.__name__}) ---")
for state_name, state_val in states:
try:
score = fn(state_val)
except Exception as exc:
print(f" {FAIL} [{state_name}] raised exception: {exc}")
results.append(False)
continue
check(f"{state_name}", score)
print()
# ββ Step 3: batch / vectorised test ββββββββββββββββββββββββββββββββββββ
print("[Step 3] Batch score array check (np.clip applied)...")
try:
from graders import batch_grade # type: ignore
edge_states = [{"score": 0.0}, {"score": 1.0}, {"score": 0.5}, None, {}]
scores = batch_grade(edge_states, task="easy")
for i, s in enumerate(scores):
check(f"batch[{i}]", s)
except Exception as exc:
print(f" (batch_grade not tested: {exc})")
# ββ Report βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
print("\n" + "=" * 60)
total = len(results)
passed = sum(results)
failed = total - passed
if failed == 0:
print(f" \033[92mALL {total} TESTS PASSED β Ready for Phase 3 β\033[0m")
else:
print(f" \033[91m{failed}/{total} TESTS FAILED\033[0m")
sys.exit(1)
print("=" * 60)
if __name__ == "__main__":
run_tests()
|