File size: 8,553 Bytes
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ef23a4
50bf486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Core environment logic for the SQL Debug Environment.

Implements the standard OpenEnv interface:
  reset(**kwargs) β†’ SQLObservation
  step(action)    β†’ SQLObservation
  state           β†’ SQLState

Each episode spins up a fresh in-memory SQLite DB, seeds it with sample data,
and lets the agent take up to 8 attempts at fixing the broken query.
"""

from __future__ import annotations

import sqlite3
import uuid
from typing import Any, Optional

from openenv.core.env_server import Environment

from server.grader import grade
from server.seed_db import seed_database
from server.tasks import TASKS
from sql_debug_env.models import SQLAction, SQLObservation, SQLState


class SQLDebugEnvironment(Environment[SQLAction, SQLObservation, SQLState]):
    """RL environment where an agent debugs SQL queries against a live SQLite instance."""

    MAX_STEPS = 8
    DONE_THRESHOLD = 0.89  # tasks 1 & 2: syntax+F1+exact = 0.90 β†’ passes
    # Task 3 needs a higher bar β€” the broken query already scores 0.90
    # (correct rows, wrong approach). Agent must earn the efficiency bonus
    # too, pushing the score to 1.0 before we consider it solved.
    DONE_THRESHOLD_OPTIMIZE = 0.95

    def __init__(self) -> None:
        super().__init__()
        self._conn: sqlite3.Connection | None = None
        self._task_id: str = ""
        self._task_config: dict | None = None
        self._step: int = 0
        self._done: bool = False
        self._last_reward: float = 0.0
        self._max_reward: float = 0.0
        self._history: list[dict[str, Any]] = []
        self._expected_rows: list[tuple] | None = None
        self._expected_row_count: int = 0
        self._episode_id: str = ""

    # ── helpers ──────────────────────────────────────────────────────

    def _init_db(self) -> sqlite3.Connection:
        """Spin up a clean in-memory SQLite and populate it."""
        conn = sqlite3.connect(":memory:")
        seed_database(conn)
        return conn

    def _run_query_safe(
        self, query: str
    ) -> tuple[list[tuple], list[dict[str, Any]] | None, str | None]:
        """Execute a query safely β€” returns (rows, preview_dicts, error_msg).

        The preview is capped at 10 rows so we don't flood the observation.
        """
        assert self._conn is not None
        try:
            cur = self._conn.cursor()
            cur.execute(query)
            rows = cur.fetchall()
            col_names = (
                [desc[0] for desc in cur.description] if cur.description else []
            )
            preview = [dict(zip(col_names, row)) for row in rows[:10]]
            return rows, preview, None
        except Exception as e:
            return [], None, str(e)

    def _build_observation(
        self,
        error_message: str | None = None,
        result_preview: list[dict[str, Any]] | None = None,
        current_row_count: int | None = None,
        hint: str | None = None,
        reward_value: float | None = None,
        is_done: bool = False,
        extra_metadata: dict[str, Any] | None = None,
    ) -> SQLObservation:
        """Construct an observation object with everything the agent needs."""
        assert self._task_config is not None
        return SQLObservation(
            done=is_done,
            reward=reward_value,
            metadata=extra_metadata or {},
            task_id=self._task_config["task_id"],
            broken_query=self._task_config["broken_query"],
            schema_description=self._task_config["schema_description"],
            error_message=error_message,
            result_preview=result_preview,
            expected_row_count=self._expected_row_count,
            current_row_count=current_row_count,
            step_number=self._step,
            max_steps=self.MAX_STEPS,
            hint=hint,
        )

    # ── OpenEnv interface ────────────────────────────────────────────

    def reset(
        self,
        seed: Optional[int] = None,
        episode_id: Optional[str] = None,
        **kwargs: Any,
    ) -> SQLObservation:
        """Initialize a new episode.

        Pass task_id as a kwarg β€” one of 'fix_syntax', 'fix_join', 'optimize_query'.
        Defaults to fix_syntax if you forget.
        """
        task_id = kwargs.get("task_id", "fix_syntax")

        if task_id not in TASKS:
            raise ValueError(
                f"Unknown task '{task_id}'. Pick one of: {list(TASKS.keys())}"
            )

        self._task_id = task_id
        self._task_config = TASKS[task_id]
        self._step = 0
        self._done = False
        self._last_reward = 0.0
        self._max_reward = 0.0
        self._history = []
        self._episode_id = episode_id or str(uuid.uuid4())

        # Start fresh every time β€” no state leaking between episodes
        if self._conn is not None:
            self._conn.close()
        self._conn = self._init_db()

        # Figure out what the correct output looks like
        expected_rows, _, _ = self._run_query_safe(self._task_config["correct_query"])
        self._expected_rows = expected_rows
        self._expected_row_count = len(expected_rows)

        # Run the broken query so the agent can see what's wrong right away
        _, preview, err = self._run_query_safe(self._task_config["broken_query"])
        current_count = None if err else 0

        return self._build_observation(
            error_message=err,
            result_preview=preview,
            current_row_count=current_count,
            reward_value=0.01,   # strictly > 0.0 β€” hackathon requires open interval (0, 1)
            is_done=False,
        )

    def step(
        self,
        action: SQLAction,
        timeout_s: Optional[float] = None,
        **kwargs: Any,
    ) -> SQLObservation:
        """Run the agent's query, grade it, and send back feedback."""
        if self._done:
            raise RuntimeError("Episode already finished β€” call reset() to start over.")
        if self._task_config is None or self._conn is None:
            raise RuntimeError("reset() hasn't been called yet.")

        query = action.query
        self._step += 1

        # Grade it
        reward, grade_info = grade(
            submitted_query=query,
            correct_query=self._task_config["correct_query"],
            task_id=self._task_config["task_id"],
            conn=self._conn,
        )

        self._last_reward = reward
        self._max_reward = max(self._max_reward, reward)
        self._history.append({"query": query, "reward": reward})

        # Done if they've solved it well enough, or exhausted all steps.
        # optimize_query needs a higher threshold β€” the broken query already
        # scores 0.90 without any real optimization, so we require 0.95
        # (meaning the agent must also earn the efficiency bonus).
        task_threshold = (
            self.DONE_THRESHOLD_OPTIMIZE
            if self._task_config["task_id"] == "optimize_query"
            else self.DONE_THRESHOLD
        )
        if reward >= task_threshold or self._step >= self.MAX_STEPS:
            self._done = True

        # Run the query to generate a preview for the observation
        _, preview, err = self._run_query_safe(query)
        current_row_count = grade_info.get("submitted_row_count")

        # Maybe give them a nudge
        hint = self._task_config.get("hint_schedule", {}).get(self._step)

        return self._build_observation(
            error_message=err if err else grade_info.get("error_message"),
            result_preview=preview,
            current_row_count=current_row_count,
            hint=hint,
            reward_value=reward,
            is_done=self._done,
            extra_metadata={
                **grade_info,
                "step": self._step,
                "max_reward": self._max_reward,
            },
        )

    @property
    def state(self) -> SQLState:
        """Snapshot of the current episode β€” useful for checkpointing or debugging."""
        return SQLState(
            episode_id=self._episode_id,
            step_count=self._step,
            task_id=self._task_id,
            max_steps=self.MAX_STEPS,
            last_reward=self._last_reward,
            cumulative_max_reward=self._max_reward,
            done=self._done,
            history=self._history,
        )