File size: 6,609 Bytes
e8c001c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
mysql_004: End-to-end verification that ground_truth.py scores 100 via grade().

Complete flow:
  1. Start Docker container (mount init/ as /app)
  2. Setup workspace (/app -> /tmp_workspace)
  3. Copy ground_truth.py as result.py (simulating agent output)
  4. Init MySQL database (mysql -u root < init_db.sql)
  5. Inject gt/ directory
  6. Run grade(workspace_path='/tmp_workspace')
  7. Assert product_score == 70 (without chat.jsonl, process=0, product=70)
  8. Cleanup container

Usage:
    python3 verify_grade.py
"""
import json
import os
import subprocess
import sys
import tempfile
import time
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  # mysql_004/
CONTAINER_NAME = f"verify_gt_mysql_004_{uuid.uuid4().hex[:8]}"


def run_cmd(cmd, timeout=300, 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 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:
        # 1. Start container
        print("[verify] Step 1: Starting container...")
        cmd = [
            "docker", "run", "-d",
            "--name", CONTAINER_NAME,
            "-v", f"{workspace_path}/init:/app:ro",
            DOCKER_IMAGE, "/bin/bash", "-c", "tail -f /dev/null",
        ]
        run_cmd(cmd)

        # 2. Setup workspace
        print("[verify] Step 2: Setting up workspace...")
        run_cmd([
            "docker", "exec", CONTAINER_NAME, "/bin/bash", "-c",
            f"cp -r /app/. {TMP_WORKSPACE} && chmod -R u+w {TMP_WORKSPACE}",
        ])

        # 3. Init MySQL database (mysql -u root < init_db.sql)
        print("[verify] Step 3: Initializing MySQL database...")
        # Start MySQL daemon first (init_db.sql needs it)
        run_cmd([
            "docker", "exec", CONTAINER_NAME, "/bin/bash", "-c",
            "mysqld_safe --user=root &",
        ], timeout=60)
        time.sleep(5)  # wait for MySQL to be ready

        # Run init SQL
        run_cmd([
            "docker", "exec", CONTAINER_NAME, "/bin/bash", "-c",
            f"mysql -u root < {TMP_WORKSPACE}/init_db.sql",
        ], timeout=60)

        print("[verify] MySQL init complete")

        # 4. Copy ground_truth.py as result.py (simulating agent produced this)
        print("[verify] Step 4: Copying ground_truth.py -> result.py...")
        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.py {TMP_WORKSPACE}/result.py",
        ])

        # 5. Run grade inside container
        print("[verify] Step 5: 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)

        # Parse result
        stdout = r.stdout or ""
        if "__VERIFY_JSON_START__" not in stdout or "__VERIFY_JSON_END__" not in stdout:
            print(f"[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(f"[verify] Grade result:")
        print(json.dumps(scores, indent=2, ensure_ascii=False))

        # 6. Assert expected score
        overall = scores.get("overall_score", 0)
        total_points = scores.get("total_points", 0)
        product_points = scores.get("product_points", 0)
        process_points = scores.get("process_points", 0)

        # Without transcript (no chat.jsonl):
        # product dims total max = 15+15+20+40+10 = 100
        # product_score = 100 * 0.7 = 70, overall_score = 70/100 = 0.7
        expected_overall = 0.7
        expected_product = 70

        if product_points == expected_product and overall == expected_overall:
            print(f"\n[verify] PASS: {total_points}/100 (product={product_points}, process={process_points}, overall_score={overall})")
        else:
            print(f"\n[verify] FAIL: Expected product_points={expected_product} overall_score={expected_overall}")
            print(f"  Got: total_points={total_points}, product={product_points}, process={process_points}, overall={overall}")
            if "details" in scores:
                for dim, info in scores["details"].items():
                    print(f"  {dim}: {info.get('score', 0)}/{info.get('max', 0)}")
            if "error" in scores:
                print(f"  Error: {scores['error']}")
            if "diagnostics" in scores:
                for diag in scores["diagnostics"]:
                    print(f"  Diagnostic: {diag}")
            sys.exit(1)

    except Exception as e:
        print(f"[verify] ERROR: {e}")
        sys.exit(1)
    finally:
        cleanup()


if __name__ == "__main__":
    main()