Spaces:
Sleeping
Sleeping
File size: 9,663 Bytes
2f8e591 | 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | """
test_env.py — Local end-to-end test for the OpenENV SQL Debugging environment.
Does NOT require an HF_TOKEN — it uses hard-coded correct SQL fixes to validate
that the server is returning expected rewards, not an LLM.
Prerequisites:
pip install requests
docker run -p 7860:7860 sql-debug-env (or uvicorn running locally)
Run:
python test_env.py
python test_env.py --url http://localhost:7860 # custom server URL
Exit code: 0 if all tests pass, 1 if any test fails.
"""
import sys
import json
import argparse
import requests
# ---------------------------------------------------------------------------
# Correct ("golden") fix queries for every task
# ---------------------------------------------------------------------------
TASK_FIXES = {
"fix-syntax": [
# Bug: missing comma between id and name
"SELECT id, name FROM users WHERE active = 1;",
],
"fix-logic": [
# Bugs: INNER JOIN → LEFT JOIN, > → >=, move date filter to ON clause
(
"SELECT u.name, o.total "
"FROM users u "
"LEFT JOIN orders o ON u.id = o.user_id AND o.created_at >= '2024-01-01';"
),
],
"fix-and-optimize": [
# Bug: missing alias 'e' on outer table + GROUP BY
(
"SELECT e.dept, AVG(e.salary) "
"FROM employees e "
"WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept) "
"GROUP BY e.dept;"
),
],
}
# Minimum expected reward for the golden fix on the first correct attempt
MIN_PASS_REWARD = {
"fix-syntax": 0.9,
"fix-logic": 0.9,
"fix-and-optimize": 0.9,
}
PASS = "✅ PASS"
FAIL = "❌ FAIL"
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def health_check(base: str) -> None:
"""Verify server is reachable and healthy."""
try:
r = requests.get(f"{base}/health", timeout=10)
r.raise_for_status()
data = r.json()
assert data.get("status") == "ok", f"Unexpected health response: {data}"
print(f"[health] {PASS} → {data}")
except Exception as exc:
print(f"[health] {FAIL} → {exc}")
print("\nIs the server running? Start it with:")
print(" docker run -p 7860:7860 sql-debug-env")
print(" OR: cd server && uvicorn main:app --port 7860")
sys.exit(1)
def reset_env(base: str, task: str) -> dict:
r = requests.post(f"{base}/reset", params={"task": task}, timeout=30)
r.raise_for_status()
return r.json()
def step_env(base: str, query: str) -> dict:
payload = {"query": query}
r = requests.post(
f"{base}/step",
data=json.dumps(payload),
headers={"Content-Type": "application/json"},
timeout=30,
)
r.raise_for_status()
return r.json()
def get_state(base: str) -> dict:
r = requests.get(f"{base}/state", timeout=10)
r.raise_for_status()
return r.json()
# ---------------------------------------------------------------------------
# Test routines
# ---------------------------------------------------------------------------
def test_reset_returns_observation(base: str, task: str) -> bool:
"""POST /reset should return a valid SQLObservation."""
try:
obs = reset_env(base, task)
required = ["schema_str", "task_description", "broken_query", "step_number"]
missing = [k for k in required if k not in obs]
if missing:
print(f" [{task}] reset missing fields: {missing} {FAIL}")
return False
if obs["step_number"] != 0:
print(f" [{task}] step_number should be 0 after reset, got {obs['step_number']} {FAIL}")
return False
print(f" [{task}] /reset observation {PASS}")
return True
except Exception as exc:
print(f" [{task}] /reset error: {exc} {FAIL}")
return False
def test_state_endpoint(base: str, task: str) -> bool:
"""GET /state should mirror the current observation without side effects."""
try:
reset_env(base, task)
state = get_state(base)
required = ["schema_str", "task_description", "broken_query", "step_number"]
missing = [k for k in required if k not in state]
if missing:
print(f" [{task}] /state missing fields: {missing} {FAIL}")
return False
print(f" [{task}] /state returns observation {PASS}")
return True
except Exception as exc:
print(f" [{task}] /state error: {exc} {FAIL}")
return False
def test_broken_query_fails(base: str, task: str) -> bool:
"""Submitting the original broken query should return reward=0 (or low)."""
try:
obs = reset_env(base, task)
broken = obs["broken_query"]
result = step_env(base, broken)
reward = result["reward"]
# Broken queries may run but score low, or fail (reward 0)
# We just verify the structure
for field in ["observation", "reward", "done", "info"]:
if field not in result:
print(f" [{task}] /step missing field '{field}' {FAIL}")
return False
print(f" [{task}] broken query step (reward={reward:.4f}) {PASS}")
return True
except Exception as exc:
print(f" [{task}] broken query step error: {exc} {FAIL}")
return False
def test_golden_fix_scores_high(base: str, task: str) -> bool:
"""Submitting the correct fix should yield a high reward."""
try:
reset_env(base, task)
fix_queries = TASK_FIXES[task]
result = None
for query in fix_queries:
result = step_env(base, query)
reward = result["reward"]
done = result["done"]
min_r = MIN_PASS_REWARD[task]
ok = reward >= min_r
status = PASS if ok else FAIL
print(f" [{task}] golden fix reward={reward:.4f} (need>={min_r}) {status}")
if not ok:
print(f" done={done} info={result.get('info')}")
return ok
except Exception as exc:
print(f" [{task}] golden fix error: {exc} {FAIL}")
return False
def test_wrong_query_gives_nonperfect(base: str, task: str) -> bool:
"""A completely wrong query should not give reward=1.0."""
try:
reset_env(base, task)
result = step_env(base, "SELECT 1;")
reward = result["reward"]
ok = reward < 1.0
status = PASS if ok else FAIL
print(f" [{task}] wrong query reward={reward:.4f} (<1.0) {status}")
return ok
except Exception as exc:
print(f" [{task}] wrong query test error: {exc} {FAIL}")
return False
def test_max_steps_triggers_done(base: str, task: str, max_steps: int = 8) -> bool:
"""After max_steps steps the env should set done=True."""
try:
reset_env(base, task)
done = False
last_result = None
for i in range(max_steps + 2): # go slightly over
last_result = step_env(base, "SELECT 1;")
done = last_result["done"]
if done:
break
ok = done
status = PASS if ok else FAIL
extra = f" (after {i+1} steps)" if ok else " (never triggered)"
print(f" [{task}] done=True at max_steps {status}{extra}")
return ok
except Exception as exc:
print(f" [{task}] max_steps test error: {exc} {FAIL}")
return False
# ---------------------------------------------------------------------------
# Full suite
# ---------------------------------------------------------------------------
def run_suite(base: str) -> bool:
tasks = ["fix-syntax", "fix-logic", "fix-and-optimize"]
results = []
print("\n" + "=" * 60)
print("OpenENV — Local End-to-End Test Suite")
print(f"Server : {base}")
print("=" * 60)
# 1. Health check
print("\n── Health Check ─────────────────────────────────────────")
health_check(base)
# 2. Per-task tests
for task in tasks:
print(f"\n── Task: {task} ──────────────────────────────────────────")
results.append(test_reset_returns_observation(base, task))
results.append(test_state_endpoint(base, task))
results.append(test_broken_query_fails(base, task))
results.append(test_wrong_query_gives_nonperfect(base, task))
results.append(test_golden_fix_scores_high(base, task))
results.append(test_max_steps_triggers_done(base, task))
# 3. Summary
passed = sum(results)
total = len(results)
print("\n" + "=" * 60)
if passed == total:
print(f"ALL TESTS PASSED ✅ ({passed}/{total})")
else:
print(f"SOME TESTS FAILED ❌ ({passed}/{total} passed)")
print("=" * 60 + "\n")
return passed == total
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="OpenENV local test suite")
parser.add_argument(
"--url",
default="http://localhost:7860",
help="Base URL of the running OpenENV server (default: http://localhost:7860)",
)
args = parser.parse_args()
ok = run_suite(args.url)
sys.exit(0 if ok else 1)
|