#!/usr/bin/env python3 """ flinksql_019: End-to-end verification that ground_truth.sql earns FULL product score. GT is graded as if it were the agent's answer. We assert the ground truth earns the FULL product score (A/B/C/D dims, product_ratio == 1.0). Process dims (G/H/I/J) are ignored: a bare GT run has no agent transcript, so those dims are legitimately 0 and must NOT count against the case. Flow: 1. Start Docker container with Flink environment 2. Setup workspace (copy init/) 3. Copy ground_truth.sql -> result.sql 4. Inject gt/ directory 5. Run grade(workspace_path='/tmp_workspace') 6. Assert product_ratio == 1.0 (GT must earn full product score) 7. Cleanup container Usage: python3 verify_grade.py """ import json import os import subprocess import sys import tempfile import uuid from pathlib import Path DOCKER_IMAGE = os.environ.get("DOCKER_IMAGE", "dataclaw-eval:v1.0") TMP_WORKSPACE = "/tmp_workspace" TASK_DIR = Path(__file__).resolve().parent.parent # flinksql_019/ CONTAINER_NAME = f"verify_gt_flinksql_019_{uuid.uuid4().hex[:8]}" PRODUCT_PREFIXES = ("A_", "B_", "C_", "D_") def run_cmd(cmd, timeout=300, check=True): """Run a command, raise on failure if check=True.""" r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=timeout) if check and r.returncode != 0: raise RuntimeError("Command failed: {}\nstderr: {}\nstdout: {}".format( ' '.join(cmd), r.stderr, r.stdout)) return r def cleanup(): subprocess.run(["docker", "rm", "-f", CONTAINER_NAME], stdout=subprocess.PIPE, stderr=subprocess.PIPE) def product_ratio(scores): """GT product ratio (0..1) = sum(A/B/C/D raw score) / sum(A/B/C/D max). Uses RAW dimension scores, NOT product_points: product_points already applies a per-case product_weight (0.6 or 0.7) which differs across cases and is irrelevant to "did GT max out the product dims". """ raw = mx = 0.0 for dim, info in (scores.get("details", {}) or {}).items(): if dim.startswith(PRODUCT_PREFIXES) and isinstance(info, dict): raw += info.get("score", 0) or 0 mx += info.get("max", 0) or 0 return round(raw / mx, 4) if mx else 0.0 def main(): workspace_path = str(TASK_DIR) print(f"[verify] Task dir: {workspace_path}") print(f"[verify] Container: {CONTAINER_NAME}") print(f"[verify] Docker image: {DOCKER_IMAGE}") cleanup() try: print("[verify] Step 1: Starting container...") run_cmd([ "docker", "run", "-d", "--name", CONTAINER_NAME, "-v", f"{workspace_path}/init:/app:ro", DOCKER_IMAGE, "/bin/bash", "-c", "tail -f /dev/null", ]) print("[verify] Step 2: Setting up workspace...") run_cmd([ "docker", "exec", CONTAINER_NAME, "/bin/bash", "-c", f"mkdir -p {TMP_WORKSPACE}/init && cp -r /app/. {TMP_WORKSPACE}/init/ " f"&& chmod -R u+w {TMP_WORKSPACE}", ]) print("[verify] Step 3: Copying ground_truth.sql -> result.sql...") gt_host = os.path.join(workspace_path, "gt") run_cmd(["docker", "cp", gt_host, f"{CONTAINER_NAME}:{TMP_WORKSPACE}/gt"]) run_cmd([ "docker", "exec", CONTAINER_NAME, "/bin/bash", "-c", f"cp {TMP_WORKSPACE}/gt/ground_truth.sql {TMP_WORKSPACE}/result.sql", ]) print("[verify] Step 4: Running grade()...") grade_runner = "\n".join([ "import json", "import sys", f"sys.path.insert(0, '{TMP_WORKSPACE}')", f"sys.path.insert(0, '{TMP_WORKSPACE}/gt')", "from grade import grade", f"result = grade(workspace_path='{TMP_WORKSPACE}')", "print('__VERIFY_JSON_START__')", "print(json.dumps(result, ensure_ascii=False))", "print('__VERIFY_JSON_END__')", ]) + "\n" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False, encoding="utf-8") as f: f.write(grade_runner) runner_host = f.name try: run_cmd(["docker", "cp", runner_host, f"{CONTAINER_NAME}:/tmp/_verify_runner.py"]) r = subprocess.run( ["docker", "exec", CONTAINER_NAME, "python3", "/tmp/_verify_runner.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=600, ) finally: os.unlink(runner_host) stdout = r.stdout or "" if "__VERIFY_JSON_START__" not in stdout or "__VERIFY_JSON_END__" not in stdout: print("[verify] FAIL: No JSON output from grade") print(f" stdout (last 2000): {stdout[-2000:]}") print(f" stderr (last 2000): {(r.stderr or '')[-2000:]}") sys.exit(1) json_str = stdout.split("__VERIFY_JSON_START__")[1].split("__VERIFY_JSON_END__")[0].strip() scores = json.loads(json_str) print("[verify] Grade result:") print(json.dumps(scores, indent=2, ensure_ascii=False)) ratio = product_ratio(scores) print(f"[verify] product_ratio = {ratio} " f"(product_points={scores.get('product_points')}, " f"overall_score={scores.get('overall_score')})") if ratio >= 1.0: print(f"\n[verify] PASS: GT earned full product score (product_ratio={ratio})") else: print(f"\n[verify] FAIL: GT did NOT earn full product score (product_ratio={ratio})") for dim, info in (scores.get("details", {}) or {}).items(): if dim.startswith(PRODUCT_PREFIXES) and isinstance(info, dict): print(f" {dim}: {info.get('score', 0)}/{info.get('max', 0)}") for d in (scores.get("diagnostics") or []): print(f" diag: {d}") sys.exit(1) except Exception as e: print(f"[verify] ERROR: {e}") sys.exit(1) finally: cleanup() if __name__ == "__main__": main()