sql-debug-env / server /environment.py
Akshaya Kumar
Add real project files
50bf486
Raw History Blame
8.49 kB
"""
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.0,
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,
)