Spaces:
Sleeping
Sleeping
Akshaya Kumar commited on
Commit ·
50bf486
1
Parent(s): f1cc981
Add real project files
Browse files- Dockerfile +22 -0
- README.md +193 -7
- inference.py +229 -0
- openenv.yaml +42 -0
- pyproject.toml +43 -0
- server/Dockerfile +24 -0
- server/__init__.py +1 -0
- server/__pycache__/__init__.cpython-313.pyc +0 -0
- server/__pycache__/app.cpython-313.pyc +0 -0
- server/__pycache__/environment.cpython-313.pyc +0 -0
- server/__pycache__/grader.cpython-313.pyc +0 -0
- server/__pycache__/seed_db.cpython-313.pyc +0 -0
- server/__pycache__/tasks.cpython-313.pyc +0 -0
- server/app.py +162 -0
- server/environment.py +230 -0
- server/grader.py +160 -0
- server/requirements.txt +5 -0
- server/seed_db.py +275 -0
- server/tasks.py +164 -0
- sql_debug_env/__init__.py +6 -0
- sql_debug_env/__pycache__/__init__.cpython-313.pyc +0 -0
- sql_debug_env/__pycache__/client.cpython-313.pyc +0 -0
- sql_debug_env/__pycache__/models.cpython-313.pyc +0 -0
- sql_debug_env/client.py +45 -0
- sql_debug_env/models.py +96 -0
- uv.lock +0 -0
Dockerfile
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ── Hugging Face Spaces – Docker builder requires this at the repo root ──────
|
| 2 |
+
# Build context: repo root (same as: docker build -t sql-debug-env .)
|
| 3 |
+
FROM python:3.11-slim
|
| 4 |
+
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Copy requirements first (better layer caching)
|
| 8 |
+
COPY server/requirements.txt ./server/requirements.txt
|
| 9 |
+
RUN pip install --no-cache-dir -r server/requirements.txt
|
| 10 |
+
|
| 11 |
+
# Copy everything else
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
# 7860 is the only port HF Spaces will forward
|
| 15 |
+
EXPOSE 7860
|
| 16 |
+
|
| 17 |
+
# Health check so HF knows we're alive
|
| 18 |
+
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
|
| 19 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/health')" || exit 1
|
| 20 |
+
|
| 21 |
+
# Start the server
|
| 22 |
+
CMD ["python", "-m", "uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,12 +1,198 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
-
license: mit
|
| 9 |
-
short_description: An RL env where AI agents learn to fix broken SQL queries
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: SQL Debug Env
|
| 3 |
+
emoji: 🛠️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
|
|
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# sql-debug-env
|
| 12 |
+
|
| 13 |
+
> Teaching AI agents to debug SQL the way we all had to learn — by staring at cryptic error messages and wondering why our JOINs return 47x more rows than expected.
|
| 14 |
+
|
| 15 |
+
## What is this?
|
| 16 |
+
|
| 17 |
+
An [OpenEnv](https://github.com/openenv) environment for reinforcement learning. The agent gets a bugged SQL query, a database schema, and some sample data. It tries to fix the query, gets real feedback (actual error messages, result previews, row counts), and iterates until it either nails it or runs out of steps.
|
| 18 |
+
|
| 19 |
+
Think of it like a SQL homework grader, but the student is an LLM.
|
| 20 |
+
|
| 21 |
+
### Why SQL?
|
| 22 |
+
|
| 23 |
+
Honestly, debugging SQL felt like a natural fit for this kind of iterative RL setup:
|
| 24 |
+
|
| 25 |
+
- **Deterministic grading** — run the query against SQLite, compare results mathematically. No fuzzy evaluation needed.
|
| 26 |
+
- **Everyone encounters it** — data engineers, backend devs, analysts... we've all been there.
|
| 27 |
+
- **Genuine feedback loops** — not a one-shot problem. The agent can read error messages and actually learn from them mid-episode.
|
| 28 |
+
- **Rich partial credit** — an almost-right query that returns 90% of the correct rows isn't the same as a completely wrong one.
|
| 29 |
+
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
## Tasks
|
| 33 |
+
|
| 34 |
+
We have 3 tasks right now, ordered by difficulty:
|
| 35 |
+
|
| 36 |
+
| ID | What it does | Difficulty |
|
| 37 |
+
|----|-------------|-----------|
|
| 38 |
+
| `fix_syntax` | Fix misspelled keywords, wrong punctuation, etc. | Easy |
|
| 39 |
+
| `fix_join` | Fix JOIN that runs fine but gives wrong results (the sneaky kind) | Medium |
|
| 40 |
+
| `optimize_query` | Rewrite a correlated subquery that's technically correct but painfully slow | Hard |
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
## How the agent interacts
|
| 45 |
+
|
| 46 |
+
### Action space
|
| 47 |
+
|
| 48 |
+
Pretty simple — the agent just submits a SQL string:
|
| 49 |
+
|
| 50 |
+
```json
|
| 51 |
+
{ "query": "SELECT name, salary FROM employees WHERE department = 'Engineering' ORDER BY salary DESC" }
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### What it gets back (observation)
|
| 55 |
+
|
| 56 |
+
| Field | Type | What it is |
|
| 57 |
+
|-------|------|-----------|
|
| 58 |
+
| `task_id` | `string` | Which task we're on |
|
| 59 |
+
| `broken_query` | `string` | The original bugged query |
|
| 60 |
+
| `schema_description` | `string` | Human-readable schema info |
|
| 61 |
+
| `error_message` | `string?` | SQL error from last attempt (if any) |
|
| 62 |
+
| `result_preview` | `list[dict]?` | First 10 rows of what the query returned |
|
| 63 |
+
| `expected_row_count` | `int` | How many rows the correct answer has |
|
| 64 |
+
| `current_row_count` | `int?` | How many rows the agent's query returned |
|
| 65 |
+
| `step_number` | `int` | Where we are in the episode |
|
| 66 |
+
| `max_steps` | `int` | Hard cap (8 steps) |
|
| 67 |
+
| `hint` | `string?` | We give hints at certain steps if the agent is struggling |
|
| 68 |
+
|
| 69 |
+
---
|
| 70 |
+
|
| 71 |
+
## Scoring
|
| 72 |
+
|
| 73 |
+
Reward is ∈ [0, 1], broken into 4 components:
|
| 74 |
+
|
| 75 |
+
| Component | Weight | What earns it |
|
| 76 |
+
|-----------|--------|--------------|
|
| 77 |
+
| Syntax valid | 0.15 | Query parses without blowing up |
|
| 78 |
+
| Row-level F1 | 0.55 | How many correct rows did it get? (precision × recall) |
|
| 79 |
+
| Exact match | 0.20 | Bonus for getting it 100% right |
|
| 80 |
+
| Efficiency | 0.10 | Task 3 only — did it actually get rid of the correlated subquery? |
|
| 81 |
+
|
| 82 |
+
Episode ends when the agent hits ≥0.89 total reward or exhausts all 8 steps.
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## Database
|
| 87 |
+
|
| 88 |
+
### Task 1 (employees)
|
| 89 |
+
```sql
|
| 90 |
+
employees(id, name, department, salary, hire_date)
|
| 91 |
+
departments(id, name, budget, manager_id)
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
### Tasks 2 & 3 (e-commerce)
|
| 95 |
+
```sql
|
| 96 |
+
users(user_id, name, email, region)
|
| 97 |
+
orders(order_id, user_id, created_at, status)
|
| 98 |
+
order_items(item_id, order_id, product_id, quantity, price)
|
| 99 |
+
products(product_id, name, category, unit_price)
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
## Getting started
|
| 105 |
+
|
| 106 |
+
### Prerequisites
|
| 107 |
+
- Python 3.10+
|
| 108 |
+
- Docker (if you want to deploy it properly)
|
| 109 |
+
|
| 110 |
+
### Running locally
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
# install everything
|
| 114 |
+
pip install -e ".[server,inference,dev]"
|
| 115 |
+
|
| 116 |
+
# fire up the server
|
| 117 |
+
python -m uvicorn server.app:app --host 0.0.0.0 --port 7860
|
| 118 |
+
|
| 119 |
+
# in another terminal — run the baseline agent
|
| 120 |
+
export API_BASE_URL="https://api.openai.com/v1"
|
| 121 |
+
export MODEL_NAME="gpt-4o"
|
| 122 |
+
export OPENAI_API_KEY="your-key-here"
|
| 123 |
+
export ENV_URL="http://localhost:7860"
|
| 124 |
+
python inference.py
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
### Docker
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
docker build -t sql-debug-env -f server/Dockerfile .
|
| 131 |
+
docker run -p 7860:7860 sql-debug-env
|
| 132 |
+
|
| 133 |
+
# quick sanity check
|
| 134 |
+
curl http://localhost:7860/health
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### Using the Python client
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
from sql_debug_env import SQLDebugEnv, SQLAction
|
| 141 |
+
|
| 142 |
+
with SQLDebugEnv(base_url="http://localhost:7860").sync() as env:
|
| 143 |
+
result = env.reset(task_id="fix_syntax")
|
| 144 |
+
print(result.observation.error_message) # see what's wrong
|
| 145 |
+
|
| 146 |
+
result = env.step(SQLAction(query="SELECT name, salary FROM employees WHERE department = 'Engineering' ORDER BY salary DESC"))
|
| 147 |
+
print(f"reward={result.reward}, done={result.done}")
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
### REST API (if you prefer curl)
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
curl -s -X POST http://localhost:7860/reset \
|
| 154 |
+
-H "Content-Type: application/json" \
|
| 155 |
+
-d '{"task_id": "fix_syntax"}' | python -m json.tool
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
---
|
| 159 |
+
|
| 160 |
+
## Project layout
|
| 161 |
+
|
| 162 |
+
```
|
| 163 |
+
sql-debug-env/
|
| 164 |
+
├── openenv.yaml # OpenEnv manifest
|
| 165 |
+
├── README.md
|
| 166 |
+
├── inference.py # Baseline LLM agent
|
| 167 |
+
├── pyproject.toml
|
| 168 |
+
├── sql_debug_env/ # Client-side package
|
| 169 |
+
│ ├── __init__.py
|
| 170 |
+
│ ├── models.py # Action / Observation / State types
|
| 171 |
+
│ └── client.py # WebSocket client
|
| 172 |
+
└── server/
|
| 173 |
+
├── Dockerfile
|
| 174 |
+
├── requirements.txt
|
| 175 |
+
├── app.py # FastAPI + OpenEnv wiring
|
| 176 |
+
├── environment.py # Core env logic (reset/step/state)
|
| 177 |
+
├── tasks.py # Task definitions & broken queries
|
| 178 |
+
├── grader.py # Reward computation
|
| 179 |
+
└── seed_db.py # Populates the SQLite DB
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
---
|
| 183 |
+
|
| 184 |
+
## Baseline scores
|
| 185 |
+
|
| 186 |
+
Haven't run these yet — will fill in after the first round of evals.
|
| 187 |
+
|
| 188 |
+
| Model | fix_syntax | fix_join | optimize_query | Avg |
|
| 189 |
+
|-------|-----------|----------|---------------|-----|
|
| 190 |
+
| GPT-4o | — | — | — | — |
|
| 191 |
+
| GPT-4o-mini | — | — | — | — |
|
| 192 |
+
| Claude 3.5 Sonnet | — | — | — | — |
|
| 193 |
+
|
| 194 |
+
---
|
| 195 |
+
|
| 196 |
+
## License
|
| 197 |
+
|
| 198 |
+
MIT
|
inference.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Baseline inference script for the SQL Debug Environment.
|
| 4 |
+
|
| 5 |
+
Runs all 3 tasks using an OpenAI-compatible LLM to iteratively fix broken SQL.
|
| 6 |
+
Talks to the environment server via WebSocket (the standard OpenEnv way).
|
| 7 |
+
|
| 8 |
+
Logs follow the OpenEnv format:
|
| 9 |
+
[START] task=<name> env=<benchmark> model=<model>
|
| 10 |
+
[STEP] step=<n> action=<query> reward=<score> done=<bool> error=<msg>
|
| 11 |
+
[END] success=<bool> steps=<n> score=<best> rewards=<r1,r2,...>
|
| 12 |
+
|
| 13 |
+
Required environment variables (set before running):
|
| 14 |
+
HF_TOKEN — your HuggingFace / NVIDIA API key (no default — must be set)
|
| 15 |
+
API_BASE_URL — OpenAI-compatible endpoint (defaults to openai)
|
| 16 |
+
MODEL_NAME — model identifier (defaults to gpt-4o)
|
| 17 |
+
ENV_URL — environment server URL (default: http://localhost:7860)
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
from openai import OpenAI
|
| 27 |
+
|
| 28 |
+
from sql_debug_env.client import SQLDebugEnv
|
| 29 |
+
from sql_debug_env.models import SQLAction
|
| 30 |
+
|
| 31 |
+
# ── config ──────────────────────────────────────────────────────────
|
| 32 |
+
#
|
| 33 |
+
# Checklist requirements:
|
| 34 |
+
# - API_BASE_URL and MODEL_NAME have defaults (allowed)
|
| 35 |
+
# - HF_TOKEN has NO default — must be injected via environment
|
| 36 |
+
# - LOCAL_IMAGE_NAME is optional (only needed with from_docker_image())
|
| 37 |
+
#
|
| 38 |
+
# Using NVIDIA NIM (OpenAI-compatible endpoint):
|
| 39 |
+
# API_BASE_URL → https://integrate.api.nvidia.com/v1
|
| 40 |
+
# MODEL_NAME → meta/llama-3.3-70b-instruct (or any NVIDIA NIM model)
|
| 41 |
+
# HF_TOKEN → your NVIDIA API key from build.nvidia.com
|
| 42 |
+
|
| 43 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "https://integrate.api.nvidia.com/v1")
|
| 44 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "meta/llama-3.3-70b-instruct")
|
| 45 |
+
HF_TOKEN = os.getenv("HF_TOKEN") # no default — required at runtime
|
| 46 |
+
LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME") # optional
|
| 47 |
+
|
| 48 |
+
ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
|
| 49 |
+
|
| 50 |
+
BENCHMARK_NAME = "sql-debug-env"
|
| 51 |
+
TASK_IDS = ["fix_syntax", "fix_join", "optimize_query"]
|
| 52 |
+
MAX_STEPS = 8
|
| 53 |
+
|
| 54 |
+
# All LLM calls go through the OpenAI client — configured via the variables above
|
| 55 |
+
llm = OpenAI(
|
| 56 |
+
base_url=API_BASE_URL,
|
| 57 |
+
api_key=HF_TOKEN or "sk-placeholder",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ── prompts ─────────────────────────────────────────────────────────
|
| 62 |
+
|
| 63 |
+
SYSTEM_PROMPT = """\
|
| 64 |
+
You are an expert SQL developer. You'll receive a broken or slow SQL query \
|
| 65 |
+
along with the database schema. Your job is to fix it.
|
| 66 |
+
|
| 67 |
+
Rules:
|
| 68 |
+
1. Return ONLY the corrected SQL — no explanations, no markdown, nothing else.
|
| 69 |
+
2. Must be valid SQLite SQL.
|
| 70 |
+
3. Keep the original intent (same columns, same ordering) unless fixing it requires changes.
|
| 71 |
+
4. For optimization tasks: prefer CTEs and JOINs over correlated subqueries.\
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def build_user_prompt(observation, history: list[dict]) -> str:
|
| 76 |
+
"""Assemble the prompt from the current observation + recent history."""
|
| 77 |
+
obs = observation
|
| 78 |
+
|
| 79 |
+
parts = [
|
| 80 |
+
f"## Task: {obs.task_id}",
|
| 81 |
+
f"\n## Schema\n{obs.schema_description}",
|
| 82 |
+
f"\n## Broken Query\n```sql\n{obs.broken_query}\n```",
|
| 83 |
+
f"\nExpected row count: {obs.expected_row_count}",
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
if obs.error_message:
|
| 87 |
+
parts.append(f"\n## Error from last attempt\n{obs.error_message}")
|
| 88 |
+
|
| 89 |
+
if obs.result_preview:
|
| 90 |
+
preview = json.dumps(obs.result_preview[:5], indent=2)
|
| 91 |
+
parts.append(f"\n## Last result (first 5 rows)\n```json\n{preview}\n```")
|
| 92 |
+
parts.append(f"Rows returned: {obs.current_row_count or '?'}")
|
| 93 |
+
|
| 94 |
+
if obs.hint:
|
| 95 |
+
parts.append(f"\n## Hint\n{obs.hint}")
|
| 96 |
+
|
| 97 |
+
# Show the last few attempts so the model doesn't repeat mistakes
|
| 98 |
+
if history:
|
| 99 |
+
parts.append("\n## Previous attempts")
|
| 100 |
+
for h in history[-3:]:
|
| 101 |
+
parts.append(f"- Step {h['step']}: reward={h['reward']:.2f}")
|
| 102 |
+
if h.get("error"):
|
| 103 |
+
parts.append(f" Error: {h['error']}")
|
| 104 |
+
parts.append(f" Query: {h['query'][:200]}...")
|
| 105 |
+
|
| 106 |
+
parts.append("\nReturn the fixed SQL query. Nothing else.")
|
| 107 |
+
|
| 108 |
+
return "\n".join(parts)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# ── main loop ───────────────────────────────────────────────────────
|
| 112 |
+
|
| 113 |
+
def run_task(env, task_id: str) -> dict:
|
| 114 |
+
"""Run one task end-to-end and return a summary."""
|
| 115 |
+
print(f"[START] task={task_id} env={BENCHMARK_NAME} model={MODEL_NAME}")
|
| 116 |
+
|
| 117 |
+
result = env.reset(task_id=task_id)
|
| 118 |
+
observation = result.observation
|
| 119 |
+
history: list[dict] = []
|
| 120 |
+
rewards: list[float] = []
|
| 121 |
+
done = False
|
| 122 |
+
best_score = 0.0
|
| 123 |
+
steps_taken = 0
|
| 124 |
+
|
| 125 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 126 |
+
|
| 127 |
+
for step in range(1, MAX_STEPS + 1):
|
| 128 |
+
if done:
|
| 129 |
+
break
|
| 130 |
+
|
| 131 |
+
user_msg = build_user_prompt(observation, history)
|
| 132 |
+
msgs = messages + [{"role": "user", "content": user_msg}]
|
| 133 |
+
|
| 134 |
+
# Ask the LLM for a fix
|
| 135 |
+
try:
|
| 136 |
+
resp = llm.chat.completions.create(
|
| 137 |
+
model=MODEL_NAME,
|
| 138 |
+
messages=msgs,
|
| 139 |
+
temperature=0.0,
|
| 140 |
+
max_tokens=1024,
|
| 141 |
+
)
|
| 142 |
+
query = resp.choices[0].message.content.strip()
|
| 143 |
+
|
| 144 |
+
# Strip markdown fences if the model can't help itself
|
| 145 |
+
if query.startswith("```"):
|
| 146 |
+
lines = query.split("\n")
|
| 147 |
+
query = "\n".join(l for l in lines if not l.strip().startswith("```"))
|
| 148 |
+
query = query.strip()
|
| 149 |
+
except Exception as e:
|
| 150 |
+
# If the LLM call fails, just resubmit the broken query
|
| 151 |
+
# (it'll get a bad score but at least the loop continues)
|
| 152 |
+
query = observation.broken_query
|
| 153 |
+
print(
|
| 154 |
+
f"[STEP] step={step} action={query[:80]} "
|
| 155 |
+
f"reward=0.00 done=false error=LLM_ERROR:{e}"
|
| 156 |
+
)
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
# Send the query to the environment
|
| 160 |
+
try:
|
| 161 |
+
result = env.step(SQLAction(query=query))
|
| 162 |
+
observation = result.observation
|
| 163 |
+
reward = result.reward or 0.0
|
| 164 |
+
done = result.done
|
| 165 |
+
error_msg = observation.error_message
|
| 166 |
+
except Exception as e:
|
| 167 |
+
reward = 0.0
|
| 168 |
+
done = False
|
| 169 |
+
error_msg = str(e)
|
| 170 |
+
|
| 171 |
+
rewards.append(reward)
|
| 172 |
+
best_score = max(best_score, reward)
|
| 173 |
+
steps_taken = step
|
| 174 |
+
|
| 175 |
+
history.append({
|
| 176 |
+
"step": step,
|
| 177 |
+
"query": query,
|
| 178 |
+
"reward": reward,
|
| 179 |
+
"error": error_msg,
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
err_display = error_msg if error_msg else "null"
|
| 183 |
+
query_short = query.replace("\n", " ")[:100]
|
| 184 |
+
print(
|
| 185 |
+
f"[STEP] step={step} action={query_short} "
|
| 186 |
+
f"reward={reward:.2f} done={str(done).lower()} error={err_display}"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# optimize_query requires the efficiency bonus too (threshold 0.95)
|
| 190 |
+
# otherwise the broken query itself scores 0.90 and looks "solved"
|
| 191 |
+
threshold = 0.95 if task_id == "optimize_query" else 0.89
|
| 192 |
+
success = best_score >= threshold
|
| 193 |
+
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 194 |
+
print(
|
| 195 |
+
f"[END] success={str(success).lower()} steps={steps_taken} "
|
| 196 |
+
f"score={best_score:.2f} rewards={rewards_str}"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
return {
|
| 200 |
+
"task_id": task_id,
|
| 201 |
+
"success": success,
|
| 202 |
+
"steps": steps_taken,
|
| 203 |
+
"score": best_score,
|
| 204 |
+
"rewards": rewards,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def main():
|
| 209 |
+
"""Run all tasks and print a summary."""
|
| 210 |
+
with SQLDebugEnv(base_url=ENV_URL).sync() as env:
|
| 211 |
+
results = []
|
| 212 |
+
for task_id in TASK_IDS:
|
| 213 |
+
result = run_task(env, task_id)
|
| 214 |
+
results.append(result)
|
| 215 |
+
print()
|
| 216 |
+
|
| 217 |
+
# Print overall results
|
| 218 |
+
total = sum(r["score"] for r in results)
|
| 219 |
+
solved = sum(1 for r in results if r["success"])
|
| 220 |
+
print(
|
| 221 |
+
f"=== DONE: {solved}/{len(results)} solved, "
|
| 222 |
+
f"total score: {total:.2f}/{len(results):.2f} ==="
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
return 0 if solved == len(results) else 1
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
sys.exit(main())
|
openenv.yaml
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: sql-debug-env
|
| 2 |
+
description: >
|
| 3 |
+
Interactive SQL debugging environment — give an agent a broken query,
|
| 4 |
+
a schema, and some sample data, and see if it can fix it through
|
| 5 |
+
iterative feedback from a real SQLite database.
|
| 6 |
+
|
| 7 |
+
tags:
|
| 8 |
+
- sql
|
| 9 |
+
- debugging
|
| 10 |
+
- optimization
|
| 11 |
+
- database
|
| 12 |
+
- code-repair
|
| 13 |
+
|
| 14 |
+
tasks:
|
| 15 |
+
- id: fix_syntax
|
| 16 |
+
name: Fix SQL Syntax Errors
|
| 17 |
+
description: >
|
| 18 |
+
Query has typos in SQL keywords (SELEKT, WHER, etc). Agent needs to
|
| 19 |
+
spot and fix the syntax errors to get the correct result set.
|
| 20 |
+
difficulty: easy
|
| 21 |
+
|
| 22 |
+
- id: fix_join
|
| 23 |
+
name: Fix Wrong JOIN Logic
|
| 24 |
+
description: >
|
| 25 |
+
Query runs without errors but JOINs on the wrong column, producing
|
| 26 |
+
garbage results. Agent has to figure out the correct join key.
|
| 27 |
+
difficulty: medium
|
| 28 |
+
|
| 29 |
+
- id: optimize_query
|
| 30 |
+
name: Optimize Correlated Subquery
|
| 31 |
+
description: >
|
| 32 |
+
Query is correct but uses correlated subqueries that scale terribly.
|
| 33 |
+
Agent must rewrite using JOINs or CTEs while keeping output identical.
|
| 34 |
+
difficulty: hard
|
| 35 |
+
|
| 36 |
+
server:
|
| 37 |
+
dockerfile: server/Dockerfile
|
| 38 |
+
port: 7860
|
| 39 |
+
|
| 40 |
+
client:
|
| 41 |
+
module: sql_debug_env
|
| 42 |
+
class: SQLDebugEnv
|
pyproject.toml
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68.0", "wheel"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "sql-debug-env"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "OpenEnv environment for debugging and optimizing SQL queries"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.10"
|
| 11 |
+
license = {text = "MIT"}
|
| 12 |
+
authors = [
|
| 13 |
+
{name = "Akshaya Kumar"},
|
| 14 |
+
]
|
| 15 |
+
dependencies = [
|
| 16 |
+
"openenv-core>=0.2.0",
|
| 17 |
+
"pydantic>=2.0.0",
|
| 18 |
+
"websockets>=12.0",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
[project.optional-dependencies]
|
| 22 |
+
server = [
|
| 23 |
+
"fastapi>=0.104.0",
|
| 24 |
+
"uvicorn[standard]>=0.24.0",
|
| 25 |
+
"websockets>=12.0",
|
| 26 |
+
]
|
| 27 |
+
inference = [
|
| 28 |
+
"openai>=1.0.0",
|
| 29 |
+
]
|
| 30 |
+
dev = [
|
| 31 |
+
"pytest>=7.0",
|
| 32 |
+
"ruff>=0.1.0",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
[tool.setuptools.packages.find]
|
| 36 |
+
include = ["sql_debug_env*", "server*"]
|
| 37 |
+
|
| 38 |
+
[project.scripts]
|
| 39 |
+
server = "server.app:main"
|
| 40 |
+
|
| 41 |
+
[tool.ruff]
|
| 42 |
+
line-length = 100
|
| 43 |
+
target-version = "py310"
|
server/Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system deps (none needed for SQLite — it's built into Python)
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
+
# Copy requirements and install Python deps
|
| 10 |
+
COPY server/requirements.txt ./server/requirements.txt
|
| 11 |
+
RUN pip install --no-cache-dir -r server/requirements.txt
|
| 12 |
+
|
| 13 |
+
# Copy the entire project (build context must be project root)
|
| 14 |
+
COPY . .
|
| 15 |
+
|
| 16 |
+
# Expose the port
|
| 17 |
+
EXPOSE 7860
|
| 18 |
+
|
| 19 |
+
# Health check
|
| 20 |
+
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
|
| 21 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/health')" || exit 1
|
| 22 |
+
|
| 23 |
+
# Run the server
|
| 24 |
+
CMD ["python", "-m", "uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
|
server/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Server package."""
|
server/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
server/__pycache__/app.cpython-313.pyc
ADDED
|
Binary file (5.86 kB). View file
|
|
|
server/__pycache__/environment.cpython-313.pyc
ADDED
|
Binary file (9.35 kB). View file
|
|
|
server/__pycache__/grader.cpython-313.pyc
ADDED
|
Binary file (6.19 kB). View file
|
|
|
server/__pycache__/seed_db.cpython-313.pyc
ADDED
|
Binary file (8.9 kB). View file
|
|
|
server/__pycache__/tasks.cpython-313.pyc
ADDED
|
Binary file (5.21 kB). View file
|
|
|
server/app.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FastAPI server for the SQL Debug Environment.
|
| 3 |
+
|
| 4 |
+
Hooks into openenv-core's create_fastapi_app() for the standard /ws endpoint,
|
| 5 |
+
then slaps on a landing page and health check on top. Nothing fancy.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from fastapi.responses import HTMLResponse
|
| 15 |
+
|
| 16 |
+
from openenv.core.env_server import create_fastapi_app
|
| 17 |
+
|
| 18 |
+
from server.environment import SQLDebugEnvironment
|
| 19 |
+
from sql_debug_env.models import SQLAction, SQLObservation
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger("sql-debug-env")
|
| 22 |
+
logging.basicConfig(level=logging.INFO)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ── Wire up the OpenEnv app ────────────────────────────────────────
|
| 26 |
+
|
| 27 |
+
app: FastAPI = create_fastapi_app(
|
| 28 |
+
env=SQLDebugEnvironment,
|
| 29 |
+
action_cls=SQLAction,
|
| 30 |
+
observation_cls=SQLObservation,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
app.title = "SQL Debug Environment"
|
| 34 |
+
app.description = (
|
| 35 |
+
"OpenEnv-compatible environment for SQL debugging and optimization. "
|
| 36 |
+
"Agents fix broken queries through iterative execution feedback."
|
| 37 |
+
)
|
| 38 |
+
app.version = "1.0.0"
|
| 39 |
+
app.contact = {"name": "SQL Debug Env Team"}
|
| 40 |
+
app.license_info = {"name": "MIT", "url": "https://opensource.org/licenses/MIT"}
|
| 41 |
+
|
| 42 |
+
# Wide open CORS — this is a dev/hackathon tool, not a bank
|
| 43 |
+
app.add_middleware(
|
| 44 |
+
CORSMiddleware,
|
| 45 |
+
allow_origins=["*"],
|
| 46 |
+
allow_credentials=True,
|
| 47 |
+
allow_methods=["*"],
|
| 48 |
+
allow_headers=["*"],
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ── Landing page ────────────────────────────────────────────────────
|
| 53 |
+
#
|
| 54 |
+
# Just a quick info card so you know it's alive when you hit the root URL.
|
| 55 |
+
# Nothing too wild — dark theme, lists the tasks, links to the docs.
|
| 56 |
+
|
| 57 |
+
LANDING_HTML = """
|
| 58 |
+
<!DOCTYPE html>
|
| 59 |
+
<html lang="en">
|
| 60 |
+
<head>
|
| 61 |
+
<meta charset="UTF-8">
|
| 62 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 63 |
+
<title>SQL Debug Environment</title>
|
| 64 |
+
<style>
|
| 65 |
+
*{margin:0;padding:0;box-sizing:border-box}
|
| 66 |
+
body{font-family:'Segoe UI',system-ui,-apple-system,sans-serif;
|
| 67 |
+
background:#0f172a;color:#e2e8f0;min-height:100vh;
|
| 68 |
+
display:flex;align-items:center;justify-content:center}
|
| 69 |
+
.card{background:#1e293b;border-radius:16px;padding:48px;
|
| 70 |
+
max-width:720px;width:90%;box-shadow:0 25px 50px rgba(0,0,0,.4)}
|
| 71 |
+
h1{font-size:2rem;margin-bottom:8px;
|
| 72 |
+
background:linear-gradient(135deg,#38bdf8,#818cf8);
|
| 73 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
| 74 |
+
.subtitle{color:#94a3b8;margin-bottom:32px;font-size:1.05rem}
|
| 75 |
+
.tasks{display:grid;gap:12px;margin-bottom:32px}
|
| 76 |
+
.task{background:#334155;border-radius:10px;padding:16px 20px;
|
| 77 |
+
display:flex;align-items:center;gap:14px;
|
| 78 |
+
transition:transform .15s}
|
| 79 |
+
.task:hover{transform:translateX(4px)}
|
| 80 |
+
.badge{padding:4px 10px;border-radius:6px;font-size:.75rem;
|
| 81 |
+
font-weight:700;text-transform:uppercase;flex-shrink:0}
|
| 82 |
+
.easy{background:#166534;color:#4ade80}
|
| 83 |
+
.medium{background:#854d0e;color:#facc15}
|
| 84 |
+
.hard{background:#991b1b;color:#f87171}
|
| 85 |
+
.task-name{font-weight:600}
|
| 86 |
+
.task-id{color:#64748b;font-size:.85rem;font-family:monospace}
|
| 87 |
+
.endpoints{margin-bottom:28px}
|
| 88 |
+
.endpoints h2{font-size:1rem;color:#94a3b8;margin-bottom:12px}
|
| 89 |
+
.ep{font-family:monospace;font-size:.9rem;padding:6px 0;
|
| 90 |
+
display:flex;gap:10px;align-items:center}
|
| 91 |
+
.method{padding:2px 8px;border-radius:4px;font-weight:700;font-size:.75rem}
|
| 92 |
+
.post{background:#1d4ed8;color:#bfdbfe}
|
| 93 |
+
.get{background:#15803d;color:#bbf7d0}
|
| 94 |
+
.ws{background:#7e22ce;color:#e9d5ff}
|
| 95 |
+
a{color:#38bdf8;text-decoration:none}
|
| 96 |
+
a:hover{text-decoration:underline}
|
| 97 |
+
.footer{color:#475569;font-size:.85rem;margin-top:24px;
|
| 98 |
+
padding-top:20px;border-top:1px solid #334155}
|
| 99 |
+
</style>
|
| 100 |
+
</head>
|
| 101 |
+
<body>
|
| 102 |
+
<div class="card">
|
| 103 |
+
<h1>🛠️ SQL Debug Environment</h1>
|
| 104 |
+
<p class="subtitle">Interactive SQL debugging & optimization — powered by OpenEnv</p>
|
| 105 |
+
|
| 106 |
+
<div class="tasks">
|
| 107 |
+
<div class="task">
|
| 108 |
+
<span class="badge easy">Easy</span>
|
| 109 |
+
<div><span class="task-name">Fix SQL Syntax Errors</span><br>
|
| 110 |
+
<span class="task-id">fix_syntax</span></div>
|
| 111 |
+
</div>
|
| 112 |
+
<div class="task">
|
| 113 |
+
<span class="badge medium">Medium</span>
|
| 114 |
+
<div><span class="task-name">Fix Wrong JOIN Logic</span><br>
|
| 115 |
+
<span class="task-id">fix_join</span></div>
|
| 116 |
+
</div>
|
| 117 |
+
<div class="task">
|
| 118 |
+
<span class="badge hard">Hard</span>
|
| 119 |
+
<div><span class="task-name">Optimize Correlated Subquery</span><br>
|
| 120 |
+
<span class="task-id">optimize_query</span></div>
|
| 121 |
+
</div>
|
| 122 |
+
</div>
|
| 123 |
+
|
| 124 |
+
<div class="endpoints">
|
| 125 |
+
<h2>Endpoints</h2>
|
| 126 |
+
<div class="ep"><span class="method ws">WS</span> <span>/ws</span> — Main interaction (reset / step / state)</div>
|
| 127 |
+
<div class="ep"><span class="method get">GET</span> <span>/health</span> — Health check</div>
|
| 128 |
+
</div>
|
| 129 |
+
|
| 130 |
+
<p>📖 <a href="/docs">Swagger Docs</a> |
|
| 131 |
+
📋 <a href="/redoc">ReDoc</a></p>
|
| 132 |
+
|
| 133 |
+
<div class="footer">
|
| 134 |
+
Built with OpenEnv · FastAPI · SQLite
|
| 135 |
+
</div>
|
| 136 |
+
</div>
|
| 137 |
+
</body>
|
| 138 |
+
</html>
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@app.get("/", response_class=HTMLResponse)
|
| 143 |
+
async def root():
|
| 144 |
+
"""Serve the landing page."""
|
| 145 |
+
return LANDING_HTML
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@app.get("/health")
|
| 149 |
+
async def health():
|
| 150 |
+
"""Quick health check — just confirms the server is up."""
|
| 151 |
+
return {"status": "ok", "environment": "sql-debug-env"}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# ── Entry point ─────────────────────────────────────────────────────
|
| 155 |
+
|
| 156 |
+
def main():
|
| 157 |
+
import uvicorn
|
| 158 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
main()
|
server/environment.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core environment logic for the SQL Debug Environment.
|
| 3 |
+
|
| 4 |
+
Implements the standard OpenEnv interface:
|
| 5 |
+
reset(**kwargs) → SQLObservation
|
| 6 |
+
step(action) → SQLObservation
|
| 7 |
+
state → SQLState
|
| 8 |
+
|
| 9 |
+
Each episode spins up a fresh in-memory SQLite DB, seeds it with sample data,
|
| 10 |
+
and lets the agent take up to 8 attempts at fixing the broken query.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import sqlite3
|
| 16 |
+
import uuid
|
| 17 |
+
from typing import Any, Optional
|
| 18 |
+
|
| 19 |
+
from openenv.core.env_server import Environment
|
| 20 |
+
|
| 21 |
+
from server.grader import grade
|
| 22 |
+
from server.seed_db import seed_database
|
| 23 |
+
from server.tasks import TASKS
|
| 24 |
+
from sql_debug_env.models import SQLAction, SQLObservation, SQLState
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SQLDebugEnvironment(Environment[SQLAction, SQLObservation, SQLState]):
|
| 28 |
+
"""RL environment where an agent debugs SQL queries against a live SQLite instance."""
|
| 29 |
+
|
| 30 |
+
MAX_STEPS = 8
|
| 31 |
+
DONE_THRESHOLD = 0.89 # tasks 1 & 2: syntax+F1+exact = 0.90 → passes
|
| 32 |
+
# Task 3 needs a higher bar — the broken query already scores 0.90
|
| 33 |
+
# (correct rows, wrong approach). Agent must earn the efficiency bonus
|
| 34 |
+
# too, pushing the score to 1.0 before we consider it solved.
|
| 35 |
+
DONE_THRESHOLD_OPTIMIZE = 0.95
|
| 36 |
+
|
| 37 |
+
def __init__(self) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
self._conn: sqlite3.Connection | None = None
|
| 40 |
+
self._task_id: str = ""
|
| 41 |
+
self._task_config: dict | None = None
|
| 42 |
+
self._step: int = 0
|
| 43 |
+
self._done: bool = False
|
| 44 |
+
self._last_reward: float = 0.0
|
| 45 |
+
self._max_reward: float = 0.0
|
| 46 |
+
self._history: list[dict[str, Any]] = []
|
| 47 |
+
self._expected_rows: list[tuple] | None = None
|
| 48 |
+
self._expected_row_count: int = 0
|
| 49 |
+
self._episode_id: str = ""
|
| 50 |
+
|
| 51 |
+
# ── helpers ──────────────────────────────────────────────────────
|
| 52 |
+
|
| 53 |
+
def _init_db(self) -> sqlite3.Connection:
|
| 54 |
+
"""Spin up a clean in-memory SQLite and populate it."""
|
| 55 |
+
conn = sqlite3.connect(":memory:")
|
| 56 |
+
seed_database(conn)
|
| 57 |
+
return conn
|
| 58 |
+
|
| 59 |
+
def _run_query_safe(
|
| 60 |
+
self, query: str
|
| 61 |
+
) -> tuple[list[tuple], list[dict[str, Any]] | None, str | None]:
|
| 62 |
+
"""Execute a query safely — returns (rows, preview_dicts, error_msg).
|
| 63 |
+
|
| 64 |
+
The preview is capped at 10 rows so we don't flood the observation.
|
| 65 |
+
"""
|
| 66 |
+
assert self._conn is not None
|
| 67 |
+
try:
|
| 68 |
+
cur = self._conn.cursor()
|
| 69 |
+
cur.execute(query)
|
| 70 |
+
rows = cur.fetchall()
|
| 71 |
+
col_names = (
|
| 72 |
+
[desc[0] for desc in cur.description] if cur.description else []
|
| 73 |
+
)
|
| 74 |
+
preview = [dict(zip(col_names, row)) for row in rows[:10]]
|
| 75 |
+
return rows, preview, None
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return [], None, str(e)
|
| 78 |
+
|
| 79 |
+
def _build_observation(
|
| 80 |
+
self,
|
| 81 |
+
error_message: str | None = None,
|
| 82 |
+
result_preview: list[dict[str, Any]] | None = None,
|
| 83 |
+
current_row_count: int | None = None,
|
| 84 |
+
hint: str | None = None,
|
| 85 |
+
reward_value: float | None = None,
|
| 86 |
+
is_done: bool = False,
|
| 87 |
+
extra_metadata: dict[str, Any] | None = None,
|
| 88 |
+
) -> SQLObservation:
|
| 89 |
+
"""Construct an observation object with everything the agent needs."""
|
| 90 |
+
assert self._task_config is not None
|
| 91 |
+
return SQLObservation(
|
| 92 |
+
done=is_done,
|
| 93 |
+
reward=reward_value,
|
| 94 |
+
metadata=extra_metadata or {},
|
| 95 |
+
task_id=self._task_config["task_id"],
|
| 96 |
+
broken_query=self._task_config["broken_query"],
|
| 97 |
+
schema_description=self._task_config["schema_description"],
|
| 98 |
+
error_message=error_message,
|
| 99 |
+
result_preview=result_preview,
|
| 100 |
+
expected_row_count=self._expected_row_count,
|
| 101 |
+
current_row_count=current_row_count,
|
| 102 |
+
step_number=self._step,
|
| 103 |
+
max_steps=self.MAX_STEPS,
|
| 104 |
+
hint=hint,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# ── OpenEnv interface ────────────────────────────────────────────
|
| 108 |
+
|
| 109 |
+
def reset(
|
| 110 |
+
self,
|
| 111 |
+
seed: Optional[int] = None,
|
| 112 |
+
episode_id: Optional[str] = None,
|
| 113 |
+
**kwargs: Any,
|
| 114 |
+
) -> SQLObservation:
|
| 115 |
+
"""Initialize a new episode.
|
| 116 |
+
|
| 117 |
+
Pass task_id as a kwarg — one of 'fix_syntax', 'fix_join', 'optimize_query'.
|
| 118 |
+
Defaults to fix_syntax if you forget.
|
| 119 |
+
"""
|
| 120 |
+
task_id = kwargs.get("task_id", "fix_syntax")
|
| 121 |
+
|
| 122 |
+
if task_id not in TASKS:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"Unknown task '{task_id}'. Pick one of: {list(TASKS.keys())}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
self._task_id = task_id
|
| 128 |
+
self._task_config = TASKS[task_id]
|
| 129 |
+
self._step = 0
|
| 130 |
+
self._done = False
|
| 131 |
+
self._last_reward = 0.0
|
| 132 |
+
self._max_reward = 0.0
|
| 133 |
+
self._history = []
|
| 134 |
+
self._episode_id = episode_id or str(uuid.uuid4())
|
| 135 |
+
|
| 136 |
+
# Start fresh every time — no state leaking between episodes
|
| 137 |
+
if self._conn is not None:
|
| 138 |
+
self._conn.close()
|
| 139 |
+
self._conn = self._init_db()
|
| 140 |
+
|
| 141 |
+
# Figure out what the correct output looks like
|
| 142 |
+
expected_rows, _, _ = self._run_query_safe(self._task_config["correct_query"])
|
| 143 |
+
self._expected_rows = expected_rows
|
| 144 |
+
self._expected_row_count = len(expected_rows)
|
| 145 |
+
|
| 146 |
+
# Run the broken query so the agent can see what's wrong right away
|
| 147 |
+
_, preview, err = self._run_query_safe(self._task_config["broken_query"])
|
| 148 |
+
current_count = None if err else 0
|
| 149 |
+
|
| 150 |
+
return self._build_observation(
|
| 151 |
+
error_message=err,
|
| 152 |
+
result_preview=preview,
|
| 153 |
+
current_row_count=current_count,
|
| 154 |
+
reward_value=0.0,
|
| 155 |
+
is_done=False,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def step(
|
| 159 |
+
self,
|
| 160 |
+
action: SQLAction,
|
| 161 |
+
timeout_s: Optional[float] = None,
|
| 162 |
+
**kwargs: Any,
|
| 163 |
+
) -> SQLObservation:
|
| 164 |
+
"""Run the agent's query, grade it, and send back feedback."""
|
| 165 |
+
if self._done:
|
| 166 |
+
raise RuntimeError("Episode already finished — call reset() to start over.")
|
| 167 |
+
if self._task_config is None or self._conn is None:
|
| 168 |
+
raise RuntimeError("reset() hasn't been called yet.")
|
| 169 |
+
|
| 170 |
+
query = action.query
|
| 171 |
+
self._step += 1
|
| 172 |
+
|
| 173 |
+
# Grade it
|
| 174 |
+
reward, grade_info = grade(
|
| 175 |
+
submitted_query=query,
|
| 176 |
+
correct_query=self._task_config["correct_query"],
|
| 177 |
+
task_id=self._task_config["task_id"],
|
| 178 |
+
conn=self._conn,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
self._last_reward = reward
|
| 182 |
+
self._max_reward = max(self._max_reward, reward)
|
| 183 |
+
self._history.append({"query": query, "reward": reward})
|
| 184 |
+
|
| 185 |
+
# Done if they've solved it well enough, or exhausted all steps.
|
| 186 |
+
# optimize_query needs a higher threshold — the broken query already
|
| 187 |
+
# scores 0.90 without any real optimization, so we require 0.95
|
| 188 |
+
# (meaning the agent must also earn the efficiency bonus).
|
| 189 |
+
task_threshold = (
|
| 190 |
+
self.DONE_THRESHOLD_OPTIMIZE
|
| 191 |
+
if self._task_config["task_id"] == "optimize_query"
|
| 192 |
+
else self.DONE_THRESHOLD
|
| 193 |
+
)
|
| 194 |
+
if reward >= task_threshold or self._step >= self.MAX_STEPS:
|
| 195 |
+
self._done = True
|
| 196 |
+
|
| 197 |
+
# Run the query to generate a preview for the observation
|
| 198 |
+
_, preview, err = self._run_query_safe(query)
|
| 199 |
+
current_row_count = grade_info.get("submitted_row_count")
|
| 200 |
+
|
| 201 |
+
# Maybe give them a nudge
|
| 202 |
+
hint = self._task_config.get("hint_schedule", {}).get(self._step)
|
| 203 |
+
|
| 204 |
+
return self._build_observation(
|
| 205 |
+
error_message=err if err else grade_info.get("error_message"),
|
| 206 |
+
result_preview=preview,
|
| 207 |
+
current_row_count=current_row_count,
|
| 208 |
+
hint=hint,
|
| 209 |
+
reward_value=reward,
|
| 210 |
+
is_done=self._done,
|
| 211 |
+
extra_metadata={
|
| 212 |
+
**grade_info,
|
| 213 |
+
"step": self._step,
|
| 214 |
+
"max_reward": self._max_reward,
|
| 215 |
+
},
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def state(self) -> SQLState:
|
| 220 |
+
"""Snapshot of the current episode — useful for checkpointing or debugging."""
|
| 221 |
+
return SQLState(
|
| 222 |
+
episode_id=self._episode_id,
|
| 223 |
+
step_count=self._step,
|
| 224 |
+
task_id=self._task_id,
|
| 225 |
+
max_steps=self.MAX_STEPS,
|
| 226 |
+
last_reward=self._last_reward,
|
| 227 |
+
cumulative_max_reward=self._max_reward,
|
| 228 |
+
done=self._done,
|
| 229 |
+
history=self._history,
|
| 230 |
+
)
|
server/grader.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Grading logic for submitted SQL queries.
|
| 3 |
+
|
| 4 |
+
We compute a 4-part reward score between 0 and 1:
|
| 5 |
+
- 0.15 for syntax (does it even parse?)
|
| 6 |
+
- 0.55 for row-level F1 (how many right rows did you get?)
|
| 7 |
+
- 0.20 exact match bonus (nailed it perfectly)
|
| 8 |
+
- 0.10 efficiency bonus (task 3 only — did you actually optimize it?)
|
| 9 |
+
|
| 10 |
+
The idea is to give meaningful partial credit. Getting the syntax right
|
| 11 |
+
but the logic wrong should still earn *something*, and getting 90% of the
|
| 12 |
+
rows right is way better than getting 0%.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import sqlite3
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _run_query(conn: sqlite3.Connection, query: str) -> tuple[list[tuple], str | None]:
|
| 22 |
+
"""Try running a query. Returns the rows and an error string if it blew up."""
|
| 23 |
+
try:
|
| 24 |
+
cur = conn.cursor()
|
| 25 |
+
cur.execute(query)
|
| 26 |
+
return cur.fetchall(), None
|
| 27 |
+
except Exception as e:
|
| 28 |
+
return [], str(e)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _stringify_rows(rows: list[tuple]) -> set[str]:
|
| 32 |
+
"""Turn rows into a set of strings so we can do set comparisons.
|
| 33 |
+
|
| 34 |
+
Not the most elegant approach, but it handles mixed types cleanly
|
| 35 |
+
and sidesteps the whole "are these floats equal enough" problem.
|
| 36 |
+
"""
|
| 37 |
+
return {str(row) for row in rows}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _compute_f1(result_set: set[str], expected_set: set[str]) -> float:
|
| 41 |
+
"""Standard F1 between two sets.
|
| 42 |
+
|
| 43 |
+
If both are empty, that's technically a perfect match.
|
| 44 |
+
"""
|
| 45 |
+
if not result_set and not expected_set:
|
| 46 |
+
return 1.0
|
| 47 |
+
if not result_set or not expected_set:
|
| 48 |
+
return 0.0
|
| 49 |
+
|
| 50 |
+
overlap = result_set & expected_set
|
| 51 |
+
precision = len(overlap) / len(result_set)
|
| 52 |
+
recall = len(overlap) / len(expected_set)
|
| 53 |
+
|
| 54 |
+
if precision + recall == 0:
|
| 55 |
+
return 0.0
|
| 56 |
+
|
| 57 |
+
return 2 * precision * recall / (precision + recall)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _check_query_plan_efficiency(conn: sqlite3.Connection, query: str) -> bool:
|
| 61 |
+
"""Look at EXPLAIN QUERY PLAN output and check for correlated subqueries.
|
| 62 |
+
|
| 63 |
+
We mainly care about whether the optimizer is running a CORRELATED
|
| 64 |
+
scalar subquery — that's the O(n²) pattern we're trying to eliminate.
|
| 65 |
+
Scanning CTE results or small temp tables is fine; it's the correlated
|
| 66 |
+
part that kills performance.
|
| 67 |
+
"""
|
| 68 |
+
try:
|
| 69 |
+
cur = conn.cursor()
|
| 70 |
+
cur.execute(f"EXPLAIN QUERY PLAN {query}")
|
| 71 |
+
plan_rows = cur.fetchall()
|
| 72 |
+
plan_text = " ".join(str(row) for row in plan_rows)
|
| 73 |
+
|
| 74 |
+
has_correlated = "CORRELATED" in plan_text.upper()
|
| 75 |
+
|
| 76 |
+
# Also flag full scans on the base tables (not CTEs though)
|
| 77 |
+
for row in plan_rows:
|
| 78 |
+
detail = str(row).upper()
|
| 79 |
+
if "SCAN" in detail:
|
| 80 |
+
for table in ("USERS", "ORDERS ", "ORDER_ITEMS", "PRODUCTS"):
|
| 81 |
+
if f"SCAN {table.strip()}" in detail or f"SCAN TABLE {table.strip()}" in detail:
|
| 82 |
+
pass # noted, but we only hard-fail on correlated for now
|
| 83 |
+
|
| 84 |
+
return not has_correlated
|
| 85 |
+
except Exception:
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def grade(
|
| 90 |
+
submitted_query: str,
|
| 91 |
+
correct_query: str,
|
| 92 |
+
task_id: str,
|
| 93 |
+
conn: sqlite3.Connection,
|
| 94 |
+
) -> tuple[float, dict[str, Any]]:
|
| 95 |
+
"""Grade a submitted query against the reference answer.
|
| 96 |
+
|
| 97 |
+
Returns (score, info) where score is 0-1 and info has
|
| 98 |
+
the per-component breakdown for debugging.
|
| 99 |
+
"""
|
| 100 |
+
info: dict[str, Any] = {
|
| 101 |
+
"syntax_valid": False,
|
| 102 |
+
"syntax_score": 0.0,
|
| 103 |
+
"f1_score": 0.0,
|
| 104 |
+
"similarity_score": 0.0,
|
| 105 |
+
"exact_match": False,
|
| 106 |
+
"exact_match_score": 0.0,
|
| 107 |
+
"efficiency_score": 0.0,
|
| 108 |
+
"error_message": None,
|
| 109 |
+
"submitted_row_count": 0,
|
| 110 |
+
"expected_row_count": 0,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
score = 0.0
|
| 114 |
+
|
| 115 |
+
# --- Part 1: Can it even parse? (0.15) ---
|
| 116 |
+
try:
|
| 117 |
+
cur = conn.cursor()
|
| 118 |
+
cur.execute(f"EXPLAIN {submitted_query}")
|
| 119 |
+
info["syntax_valid"] = True
|
| 120 |
+
info["syntax_score"] = 0.15
|
| 121 |
+
score += 0.15
|
| 122 |
+
except Exception as e:
|
| 123 |
+
info["error_message"] = str(e)
|
| 124 |
+
# No point checking anything else if the syntax is broken
|
| 125 |
+
return max(0.0, min(score, 1.0)), info
|
| 126 |
+
|
| 127 |
+
# --- Run both queries ---
|
| 128 |
+
submitted_rows, submit_err = _run_query(conn, submitted_query)
|
| 129 |
+
if submit_err:
|
| 130 |
+
info["error_message"] = submit_err
|
| 131 |
+
return max(0.0, min(score, 1.0)), info
|
| 132 |
+
|
| 133 |
+
expected_rows, _ = _run_query(conn, correct_query)
|
| 134 |
+
|
| 135 |
+
info["submitted_row_count"] = len(submitted_rows)
|
| 136 |
+
info["expected_row_count"] = len(expected_rows)
|
| 137 |
+
|
| 138 |
+
result_set = _stringify_rows(submitted_rows)
|
| 139 |
+
expected_set = _stringify_rows(expected_rows)
|
| 140 |
+
|
| 141 |
+
# --- Part 2: How close are the results? F1 score (0.55) ---
|
| 142 |
+
f1 = _compute_f1(result_set, expected_set)
|
| 143 |
+
info["f1_score"] = round(f1, 4)
|
| 144 |
+
similarity = 0.55 * f1
|
| 145 |
+
info["similarity_score"] = round(similarity, 4)
|
| 146 |
+
score += similarity
|
| 147 |
+
|
| 148 |
+
# --- Part 3: Perfect match bonus (0.20) ---
|
| 149 |
+
if result_set == expected_set:
|
| 150 |
+
info["exact_match"] = True
|
| 151 |
+
info["exact_match_score"] = 0.20
|
| 152 |
+
score += 0.20
|
| 153 |
+
|
| 154 |
+
# --- Part 4: Efficiency — only matters for the optimization task (0.10) ---
|
| 155 |
+
if task_id == "optimize_query":
|
| 156 |
+
if _check_query_plan_efficiency(conn, submitted_query):
|
| 157 |
+
info["efficiency_score"] = 0.10
|
| 158 |
+
score += 0.10
|
| 159 |
+
|
| 160 |
+
return round(max(0.0, min(score, 1.0)), 4), info
|
server/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.104.0
|
| 2 |
+
uvicorn[standard]>=0.24.0
|
| 3 |
+
pydantic>=2.0.0
|
| 4 |
+
websockets>=12.0
|
| 5 |
+
openenv-core>=0.2.0
|
server/seed_db.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Database seeding for the SQL Debug Environment.
|
| 3 |
+
|
| 4 |
+
Sets up the tables and populates them with enough data to make the tasks
|
| 5 |
+
non-trivial. We're using realistic-ish names and values so the agent's
|
| 6 |
+
output looks sensible in logs.
|
| 7 |
+
|
| 8 |
+
Two schemas:
|
| 9 |
+
- employees/departments (Task 1)
|
| 10 |
+
- users/orders/order_items/products (Tasks 2 & 3)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import sqlite3
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def seed_database(conn: sqlite3.Connection) -> None:
|
| 19 |
+
"""Build out the tables and fill them with sample data."""
|
| 20 |
+
cur = conn.cursor()
|
| 21 |
+
|
| 22 |
+
# ── employees & departments (Task 1) ─────────────────────────────
|
| 23 |
+
|
| 24 |
+
cur.executescript(
|
| 25 |
+
"""
|
| 26 |
+
CREATE TABLE IF NOT EXISTS departments (
|
| 27 |
+
id INTEGER PRIMARY KEY,
|
| 28 |
+
name TEXT NOT NULL UNIQUE,
|
| 29 |
+
budget REAL NOT NULL,
|
| 30 |
+
manager_id INTEGER
|
| 31 |
+
);
|
| 32 |
+
|
| 33 |
+
CREATE TABLE IF NOT EXISTS employees (
|
| 34 |
+
id INTEGER PRIMARY KEY,
|
| 35 |
+
name TEXT NOT NULL,
|
| 36 |
+
department TEXT NOT NULL,
|
| 37 |
+
salary REAL NOT NULL,
|
| 38 |
+
hire_date TEXT NOT NULL
|
| 39 |
+
);
|
| 40 |
+
"""
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
departments_data = [
|
| 44 |
+
(1, "Engineering", 2500000.00, 1),
|
| 45 |
+
(2, "Marketing", 800000.00, 5),
|
| 46 |
+
(3, "Sales", 1200000.00, 9),
|
| 47 |
+
(4, "Human Resources", 600000.00, 13),
|
| 48 |
+
(5, "Finance", 900000.00, 17),
|
| 49 |
+
(6, "Product", 1100000.00, 21),
|
| 50 |
+
]
|
| 51 |
+
cur.executemany(
|
| 52 |
+
"INSERT OR IGNORE INTO departments (id, name, budget, manager_id) VALUES (?, ?, ?, ?)",
|
| 53 |
+
departments_data,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# 24 employees across 6 departments — 4 per dept
|
| 57 |
+
employees_data = [
|
| 58 |
+
# Engineering
|
| 59 |
+
(1, "Priya Sharma", "Engineering", 145000.00, "2019-03-15"),
|
| 60 |
+
(2, "James Chen", "Engineering", 138000.00, "2020-07-01"),
|
| 61 |
+
(3, "Aisha Patel", "Engineering", 152000.00, "2018-11-20"),
|
| 62 |
+
(4, "Marcus Johnson", "Engineering", 128000.00, "2021-01-10"),
|
| 63 |
+
# Marketing
|
| 64 |
+
(5, "Sofia Rodriguez", "Marketing", 95000.00, "2019-06-01"),
|
| 65 |
+
(6, "David Kim", "Marketing", 88000.00, "2020-09-15"),
|
| 66 |
+
(7, "Emma Watson", "Marketing", 102000.00, "2018-04-22"),
|
| 67 |
+
(8, "Lucas Brown", "Marketing", 79000.00, "2022-02-14"),
|
| 68 |
+
# Sales
|
| 69 |
+
(9, "Olivia Martinez", "Sales", 115000.00, "2017-08-30"),
|
| 70 |
+
(10, "Noah Williams", "Sales", 105000.00, "2019-12-01"),
|
| 71 |
+
(11, "Ava Thompson", "Sales", 98000.00, "2020-03-17"),
|
| 72 |
+
(12, "Liam Davis", "Sales", 110000.00, "2018-10-05"),
|
| 73 |
+
# HR
|
| 74 |
+
(13, "Isabella Garcia", "Human Resources", 92000.00, "2019-01-20"),
|
| 75 |
+
(14, "Ethan Moore", "Human Resources", 85000.00, "2020-06-15"),
|
| 76 |
+
(15, "Mia Anderson", "Human Resources", 78000.00, "2021-09-01"),
|
| 77 |
+
(16, "Alexander Taylor", "Human Resources", 82000.00, "2022-04-10"),
|
| 78 |
+
# Finance
|
| 79 |
+
(17, "Charlotte White", "Finance", 125000.00, "2018-02-28"),
|
| 80 |
+
(18, "Benjamin Harris", "Finance", 118000.00, "2019-07-14"),
|
| 81 |
+
(19, "Amelia Clark", "Finance", 105000.00, "2020-11-30"),
|
| 82 |
+
(20, "Daniel Lewis", "Finance", 112000.00, "2021-03-22"),
|
| 83 |
+
# Product
|
| 84 |
+
(21, "Harper Robinson", "Product", 135000.00, "2018-05-10"),
|
| 85 |
+
(22, "Sebastian Walker", "Product", 128000.00, "2019-09-18"),
|
| 86 |
+
(23, "Evelyn Hall", "Product", 115000.00, "2020-12-07"),
|
| 87 |
+
(24, "Jack Allen", "Product", 122000.00, "2021-06-25"),
|
| 88 |
+
]
|
| 89 |
+
cur.executemany(
|
| 90 |
+
"INSERT OR IGNORE INTO employees (id, name, department, salary, hire_date) VALUES (?, ?, ?, ?, ?)",
|
| 91 |
+
employees_data,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# ── e-commerce tables (Tasks 2 & 3) ──────────────────────────────
|
| 95 |
+
|
| 96 |
+
cur.executescript(
|
| 97 |
+
"""
|
| 98 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 99 |
+
user_id INTEGER PRIMARY KEY,
|
| 100 |
+
name TEXT NOT NULL,
|
| 101 |
+
email TEXT NOT NULL UNIQUE,
|
| 102 |
+
region TEXT NOT NULL
|
| 103 |
+
);
|
| 104 |
+
|
| 105 |
+
CREATE TABLE IF NOT EXISTS orders (
|
| 106 |
+
order_id INTEGER PRIMARY KEY,
|
| 107 |
+
user_id INTEGER NOT NULL,
|
| 108 |
+
created_at TEXT NOT NULL,
|
| 109 |
+
status TEXT NOT NULL,
|
| 110 |
+
FOREIGN KEY (user_id) REFERENCES users(user_id)
|
| 111 |
+
);
|
| 112 |
+
|
| 113 |
+
CREATE TABLE IF NOT EXISTS products (
|
| 114 |
+
product_id INTEGER PRIMARY KEY,
|
| 115 |
+
name TEXT NOT NULL,
|
| 116 |
+
category TEXT NOT NULL,
|
| 117 |
+
unit_price REAL NOT NULL
|
| 118 |
+
);
|
| 119 |
+
|
| 120 |
+
CREATE TABLE IF NOT EXISTS order_items (
|
| 121 |
+
item_id INTEGER PRIMARY KEY,
|
| 122 |
+
order_id INTEGER NOT NULL,
|
| 123 |
+
product_id INTEGER NOT NULL,
|
| 124 |
+
quantity INTEGER NOT NULL,
|
| 125 |
+
price REAL NOT NULL,
|
| 126 |
+
FOREIGN KEY (order_id) REFERENCES orders(order_id),
|
| 127 |
+
FOREIGN KEY (product_id) REFERENCES products(product_id)
|
| 128 |
+
);
|
| 129 |
+
"""
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# -- Users (went with Friends character names for fun) --
|
| 133 |
+
users_data = [
|
| 134 |
+
(1, "Rachel Green", "rachel.green@example.com", "North America"),
|
| 135 |
+
(2, "Ross Geller", "ross.geller@example.com", "North America"),
|
| 136 |
+
(3, "Monica Bing", "monica.bing@example.com", "Europe"),
|
| 137 |
+
(4, "Chandler Bing", "chandler.bing@example.com", "Europe"),
|
| 138 |
+
(5, "Joey Tribbiani", "joey.tribbiani@example.com", "North America"),
|
| 139 |
+
(6, "Phoebe Buffay", "phoebe.buffay@example.com", "Asia Pacific"),
|
| 140 |
+
(7, "Gunther Central", "gunther@example.com", "North America"),
|
| 141 |
+
(8, "Janice Hosenstein", "janice.h@example.com", "Europe"),
|
| 142 |
+
(9, "Mike Hannigan", "mike.hannigan@example.com", "Asia Pacific"),
|
| 143 |
+
(10, "Emily Waltham", "emily.w@example.com", "Europe"),
|
| 144 |
+
(11, "Richard Burke", "richard.burke@example.com", "North America"),
|
| 145 |
+
(12, "Carol Willick", "carol.willick@example.com", "North America"),
|
| 146 |
+
(13, "Susan Bunch", "susan.bunch@example.com", "Asia Pacific"),
|
| 147 |
+
(14, "David Scientist", "david.sci@example.com", "Europe"),
|
| 148 |
+
(15, "Tag Jones", "tag.jones@example.com", "North America"),
|
| 149 |
+
]
|
| 150 |
+
cur.executemany(
|
| 151 |
+
"INSERT OR IGNORE INTO users (user_id, name, email, region) VALUES (?, ?, ?, ?)",
|
| 152 |
+
users_data,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# -- Products --
|
| 156 |
+
products_data = [
|
| 157 |
+
(1, "Wireless Bluetooth Headphones", "Electronics", 79.99),
|
| 158 |
+
(2, "USB-C Hub Adapter", "Electronics", 34.99),
|
| 159 |
+
(3, "Mechanical Keyboard", "Electronics", 129.99),
|
| 160 |
+
(4, "Cotton Crew-Neck T-Shirt", "Clothing", 19.99),
|
| 161 |
+
(5, "Slim Fit Chinos", "Clothing", 49.99),
|
| 162 |
+
(6, "Running Shoes Pro", "Clothing", 89.99),
|
| 163 |
+
(7, "The Pragmatic Programmer", "Books", 42.99),
|
| 164 |
+
(8, "Designing Data-Intensive Applications", "Books", 38.99),
|
| 165 |
+
(9, "Clean Code", "Books", 35.99),
|
| 166 |
+
(10, "Yoga Mat Premium", "Sports", 29.99),
|
| 167 |
+
(11, "Resistance Bands Set", "Sports", 24.99),
|
| 168 |
+
(12, "Stainless Steel Water Bottle", "Kitchen", 18.99),
|
| 169 |
+
(13, "French Press Coffee Maker", "Kitchen", 27.99),
|
| 170 |
+
(14, "LED Desk Lamp", "Home", 44.99),
|
| 171 |
+
(15, "Ergonomic Mouse Pad", "Electronics", 14.99),
|
| 172 |
+
]
|
| 173 |
+
cur.executemany(
|
| 174 |
+
"INSERT OR IGNORE INTO products (product_id, name, category, unit_price) VALUES (?, ?, ?, ?)",
|
| 175 |
+
products_data,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# -- Orders (spread across Jan-Apr 2024) --
|
| 179 |
+
orders_data = [
|
| 180 |
+
(1, 1, "2024-01-15", "completed"),
|
| 181 |
+
(2, 1, "2024-02-20", "completed"),
|
| 182 |
+
(3, 2, "2024-01-22", "completed"),
|
| 183 |
+
(4, 2, "2024-03-10", "completed"),
|
| 184 |
+
(5, 2, "2024-04-05", "shipped"),
|
| 185 |
+
(6, 3, "2024-02-14", "completed"),
|
| 186 |
+
(7, 3, "2024-03-28", "completed"),
|
| 187 |
+
(8, 4, "2024-01-30", "completed"),
|
| 188 |
+
(9, 5, "2024-02-18", "completed"),
|
| 189 |
+
(10, 5, "2024-03-15", "completed"),
|
| 190 |
+
(11, 5, "2024-04-01", "shipped"),
|
| 191 |
+
(12, 6, "2024-01-10", "completed"),
|
| 192 |
+
(13, 7, "2024-03-05", "completed"),
|
| 193 |
+
(14, 8, "2024-02-25", "returned"),
|
| 194 |
+
(15, 9, "2024-04-02", "completed"),
|
| 195 |
+
(16, 9, "2024-04-08", "shipped"),
|
| 196 |
+
(17, 10, "2024-01-18", "completed"),
|
| 197 |
+
(18, 11, "2024-02-28", "completed"),
|
| 198 |
+
(19, 11, "2024-03-20", "completed"),
|
| 199 |
+
(20, 12, "2024-03-12", "completed"),
|
| 200 |
+
(21, 13, "2024-01-25", "completed"),
|
| 201 |
+
(22, 14, "2024-04-10", "shipped"),
|
| 202 |
+
(23, 15, "2024-02-08", "completed"),
|
| 203 |
+
(24, 1, "2024-04-12", "shipped"),
|
| 204 |
+
(25, 3, "2024-04-15", "pending"),
|
| 205 |
+
]
|
| 206 |
+
cur.executemany(
|
| 207 |
+
"INSERT OR IGNORE INTO orders (order_id, user_id, created_at, status) VALUES (?, ?, ?, ?)",
|
| 208 |
+
orders_data,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# -- Line items --
|
| 212 |
+
order_items_data = [
|
| 213 |
+
(1, 1, 1, 1, 79.99),
|
| 214 |
+
(2, 1, 7, 2, 42.99),
|
| 215 |
+
(3, 2, 3, 1, 129.99),
|
| 216 |
+
(4, 2, 4, 3, 19.99),
|
| 217 |
+
(5, 3, 2, 2, 34.99),
|
| 218 |
+
(6, 3, 8, 1, 38.99),
|
| 219 |
+
(7, 4, 5, 1, 49.99),
|
| 220 |
+
(8, 4, 6, 1, 89.99),
|
| 221 |
+
(9, 5, 14, 1, 44.99),
|
| 222 |
+
(10, 5, 15, 2, 14.99),
|
| 223 |
+
(11, 6, 10, 1, 29.99),
|
| 224 |
+
(12, 6, 12, 2, 18.99),
|
| 225 |
+
(13, 7, 1, 1, 79.99),
|
| 226 |
+
(14, 7, 9, 1, 35.99),
|
| 227 |
+
(15, 8, 3, 1, 129.99),
|
| 228 |
+
(16, 9, 7, 1, 42.99),
|
| 229 |
+
(17, 9, 11, 2, 24.99),
|
| 230 |
+
(18, 10, 6, 1, 89.99),
|
| 231 |
+
(19, 10, 4, 2, 19.99),
|
| 232 |
+
(20, 11, 2, 1, 34.99),
|
| 233 |
+
(21, 11, 13, 1, 27.99),
|
| 234 |
+
(22, 12, 8, 1, 38.99),
|
| 235 |
+
(23, 13, 1, 2, 79.99),
|
| 236 |
+
(24, 14, 5, 1, 49.99),
|
| 237 |
+
(25, 15, 3, 1, 129.99),
|
| 238 |
+
(26, 15, 10, 1, 29.99),
|
| 239 |
+
(27, 16, 14, 2, 44.99),
|
| 240 |
+
(28, 16, 12, 1, 18.99),
|
| 241 |
+
(29, 17, 9, 1, 35.99),
|
| 242 |
+
(30, 18, 2, 1, 34.99),
|
| 243 |
+
(31, 18, 7, 1, 42.99),
|
| 244 |
+
(32, 19, 11, 1, 24.99),
|
| 245 |
+
(33, 19, 15, 3, 14.99),
|
| 246 |
+
(34, 20, 6, 1, 89.99),
|
| 247 |
+
(35, 20, 4, 1, 19.99),
|
| 248 |
+
(36, 21, 13, 2, 27.99),
|
| 249 |
+
(37, 21, 12, 1, 18.99),
|
| 250 |
+
(38, 22, 1, 1, 79.99),
|
| 251 |
+
(39, 23, 3, 1, 129.99),
|
| 252 |
+
(40, 23, 5, 2, 49.99),
|
| 253 |
+
(41, 24, 10, 1, 29.99),
|
| 254 |
+
(42, 24, 14, 1, 44.99),
|
| 255 |
+
(43, 25, 8, 1, 38.99),
|
| 256 |
+
(44, 25, 2, 1, 34.99),
|
| 257 |
+
]
|
| 258 |
+
cur.executemany(
|
| 259 |
+
"INSERT OR IGNORE INTO order_items (item_id, order_id, product_id, quantity, price) VALUES (?, ?, ?, ?, ?)",
|
| 260 |
+
order_items_data,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
# ── Indexes ──────────────────────────────────────────────────────
|
| 264 |
+
# These matter for Task 3 — without them, the optimizer can't use
|
| 265 |
+
# index lookups and everything becomes a full table scan.
|
| 266 |
+
cur.executescript(
|
| 267 |
+
"""
|
| 268 |
+
CREATE INDEX IF NOT EXISTS idx_orders_user_id ON orders(user_id);
|
| 269 |
+
CREATE INDEX IF NOT EXISTS idx_order_items_order_id ON order_items(order_id);
|
| 270 |
+
CREATE INDEX IF NOT EXISTS idx_employees_department ON employees(department);
|
| 271 |
+
CREATE INDEX IF NOT EXISTS idx_employees_salary ON employees(salary);
|
| 272 |
+
"""
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
conn.commit()
|
server/tasks.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task definitions for the SQL Debug Environment.
|
| 3 |
+
|
| 4 |
+
Each task has:
|
| 5 |
+
- task_id / name / difficulty — the obvious stuff
|
| 6 |
+
- schema_description — what we tell the agent about the tables
|
| 7 |
+
- broken_query — the bugged query the agent needs to fix
|
| 8 |
+
- correct_query — what it should produce (used by the grader)
|
| 9 |
+
- hint_schedule — step-based hints if the agent is stuck
|
| 10 |
+
|
| 11 |
+
Adding a new task is just adding another dict to TASKS.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
TASKS: dict[str, dict] = {
|
| 17 |
+
|
| 18 |
+
# ─── Task 1: Easy — syntax errors ────────────────────────────────
|
| 19 |
+
#
|
| 20 |
+
# Classic case of fat-fingered SQL keywords. SELEKT, WHER, ORDDER...
|
| 21 |
+
# An LLM should spot these immediately, but it's a good warmup.
|
| 22 |
+
|
| 23 |
+
"fix_syntax": {
|
| 24 |
+
"task_id": "fix_syntax",
|
| 25 |
+
"name": "Fix SQL Syntax Errors",
|
| 26 |
+
"description": (
|
| 27 |
+
"The query below has several syntax errors — misspelled keywords, "
|
| 28 |
+
"wrong punctuation, messed up clause ordering. Fix it so it runs "
|
| 29 |
+
"and gives the right results."
|
| 30 |
+
),
|
| 31 |
+
"difficulty": "easy",
|
| 32 |
+
"schema_description": (
|
| 33 |
+
"Tables:\n"
|
| 34 |
+
" employees(id INTEGER PK, name TEXT, department TEXT, salary REAL, hire_date TEXT)\n"
|
| 35 |
+
" departments(id INTEGER PK, name TEXT, budget REAL, manager_id INTEGER)\n"
|
| 36 |
+
"\n"
|
| 37 |
+
"The 'department' column in employees stores the department name (not the id).\n"
|
| 38 |
+
"Departments: Engineering, Marketing, Sales, Human Resources, Finance, Product."
|
| 39 |
+
),
|
| 40 |
+
"broken_query": (
|
| 41 |
+
"SELEKT name, salary FORM employees "
|
| 42 |
+
"WHER department = 'Engineering' "
|
| 43 |
+
"ORDDER BY salary DESC"
|
| 44 |
+
),
|
| 45 |
+
"correct_query": (
|
| 46 |
+
"SELECT name, salary FROM employees "
|
| 47 |
+
"WHERE department = 'Engineering' "
|
| 48 |
+
"ORDER BY salary DESC"
|
| 49 |
+
),
|
| 50 |
+
"hint_schedule": {
|
| 51 |
+
3: "Look at the SQL keywords — some of them are misspelled.",
|
| 52 |
+
5: "The keywords should be SELECT, FROM, WHERE, ORDER BY. Just fix the typos.",
|
| 53 |
+
},
|
| 54 |
+
},
|
| 55 |
+
|
| 56 |
+
# ─── Task 2: Medium — wrong JOIN key ─────────────────────────────
|
| 57 |
+
#
|
| 58 |
+
# This one's trickier because the query actually runs without errors.
|
| 59 |
+
# It just joins on the wrong column (order_id instead of user_id),
|
| 60 |
+
# so you get garbage results and no error message to help you.
|
| 61 |
+
|
| 62 |
+
"fix_join": {
|
| 63 |
+
"task_id": "fix_join",
|
| 64 |
+
"name": "Fix Wrong JOIN Logic",
|
| 65 |
+
"description": (
|
| 66 |
+
"This query runs fine — no errors at all — but the results are wrong. "
|
| 67 |
+
"The JOIN condition is matching on the wrong column. Figure out which "
|
| 68 |
+
"JOIN is broken and fix the key."
|
| 69 |
+
),
|
| 70 |
+
"difficulty": "medium",
|
| 71 |
+
"schema_description": (
|
| 72 |
+
"Tables:\n"
|
| 73 |
+
" users(user_id INTEGER PK, name TEXT, email TEXT, region TEXT)\n"
|
| 74 |
+
" orders(order_id INTEGER PK, user_id INTEGER FK→users, created_at TEXT, status TEXT)\n"
|
| 75 |
+
" order_items(item_id INTEGER PK, order_id INTEGER FK→orders, product_id INTEGER, quantity INTEGER, price REAL)\n"
|
| 76 |
+
"\n"
|
| 77 |
+
"users → orders via users.user_id = orders.user_id\n"
|
| 78 |
+
"orders → order_items via orders.order_id = order_items.order_id"
|
| 79 |
+
),
|
| 80 |
+
"broken_query": (
|
| 81 |
+
"SELECT u.name, COUNT(o.order_id) as order_count, "
|
| 82 |
+
"SUM(oi.price * oi.quantity) as total_spent\n"
|
| 83 |
+
"FROM users u\n"
|
| 84 |
+
"JOIN orders o ON u.user_id = o.order_id\n" # <- the bug
|
| 85 |
+
"JOIN order_items oi ON oi.order_id = o.order_id\n"
|
| 86 |
+
"GROUP BY u.user_id, u.name\n"
|
| 87 |
+
"ORDER BY total_spent DESC"
|
| 88 |
+
),
|
| 89 |
+
"correct_query": (
|
| 90 |
+
"SELECT u.name, COUNT(o.order_id) as order_count, "
|
| 91 |
+
"SUM(oi.price * oi.quantity) as total_spent\n"
|
| 92 |
+
"FROM users u\n"
|
| 93 |
+
"JOIN orders o ON u.user_id = o.user_id\n"
|
| 94 |
+
"JOIN order_items oi ON oi.order_id = o.order_id\n"
|
| 95 |
+
"GROUP BY u.user_id, u.name\n"
|
| 96 |
+
"ORDER BY total_spent DESC"
|
| 97 |
+
),
|
| 98 |
+
"hint_schedule": {
|
| 99 |
+
3: "Look at the first JOIN condition. What column in orders should reference users?",
|
| 100 |
+
5: "The JOIN should be ON u.user_id = o.user_id — not o.order_id.",
|
| 101 |
+
},
|
| 102 |
+
},
|
| 103 |
+
|
| 104 |
+
# ─── Task 3: Hard — correlated subquery optimization ─────────────
|
| 105 |
+
#
|
| 106 |
+
# Correct results, terrible performance. The query uses correlated
|
| 107 |
+
# subqueries that run once per user row. On a big table this would
|
| 108 |
+
# be devastating. The agent needs to refactor into JOINs or a CTE.
|
| 109 |
+
|
| 110 |
+
"optimize_query": {
|
| 111 |
+
"task_id": "optimize_query",
|
| 112 |
+
"name": "Optimize Correlated Subquery",
|
| 113 |
+
"description": (
|
| 114 |
+
"This query gives the right answer but it's doing it the slow way — "
|
| 115 |
+
"correlated subqueries that run for every single row. Rewrite it "
|
| 116 |
+
"using JOINs, CTEs, or window functions. Output must stay identical."
|
| 117 |
+
),
|
| 118 |
+
"difficulty": "hard",
|
| 119 |
+
"schema_description": (
|
| 120 |
+
"Tables:\n"
|
| 121 |
+
" users(user_id INTEGER PK, name TEXT, email TEXT, region TEXT)\n"
|
| 122 |
+
" orders(order_id INTEGER PK, user_id INTEGER FK→users, created_at TEXT, status TEXT)\n"
|
| 123 |
+
" order_items(item_id INTEGER PK, order_id INTEGER FK→orders, product_id INTEGER FK→products, quantity INTEGER, price REAL)\n"
|
| 124 |
+
" products(product_id INTEGER PK, name TEXT, category TEXT, unit_price REAL)\n"
|
| 125 |
+
"\n"
|
| 126 |
+
"Indexes on: orders(user_id), order_items(order_id).\n"
|
| 127 |
+
"Goal: eliminate the correlated subqueries."
|
| 128 |
+
),
|
| 129 |
+
"broken_query": (
|
| 130 |
+
"SELECT \n"
|
| 131 |
+
" u.user_id,\n"
|
| 132 |
+
" u.name,\n"
|
| 133 |
+
" (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.user_id) as order_count,\n"
|
| 134 |
+
" (SELECT SUM(oi.price * oi.quantity) \n"
|
| 135 |
+
" FROM order_items oi \n"
|
| 136 |
+
" JOIN orders o ON oi.order_id = o.order_id \n"
|
| 137 |
+
" WHERE o.user_id = u.user_id) as total_spent\n"
|
| 138 |
+
"FROM users u\n"
|
| 139 |
+
"WHERE (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.user_id) > 0\n"
|
| 140 |
+
"ORDER BY total_spent DESC"
|
| 141 |
+
),
|
| 142 |
+
"correct_query": (
|
| 143 |
+
"WITH order_stats AS (\n"
|
| 144 |
+
" SELECT \n"
|
| 145 |
+
" o.user_id,\n"
|
| 146 |
+
" COUNT(DISTINCT o.order_id) as order_count,\n"
|
| 147 |
+
" SUM(oi.price * oi.quantity) as total_spent\n"
|
| 148 |
+
" FROM orders o\n"
|
| 149 |
+
" JOIN order_items oi ON oi.order_id = o.order_id\n"
|
| 150 |
+
" GROUP BY o.user_id\n"
|
| 151 |
+
")\n"
|
| 152 |
+
"SELECT u.user_id, u.name, os.order_count, os.total_spent\n"
|
| 153 |
+
"FROM users u\n"
|
| 154 |
+
"JOIN order_stats os ON os.user_id = u.user_id\n"
|
| 155 |
+
"ORDER BY total_spent DESC"
|
| 156 |
+
),
|
| 157 |
+
"hint_schedule": {
|
| 158 |
+
2: "Try using a CTE (WITH clause) to pre-compute the aggregates before joining.",
|
| 159 |
+
4: "Build a single CTE that groups orders + order_items by user_id first.",
|
| 160 |
+
6: "Something like: WITH order_stats AS (SELECT o.user_id, COUNT(...), SUM(...) FROM orders o JOIN order_items oi ... GROUP BY o.user_id) then JOIN users to that.",
|
| 161 |
+
7: "Careful! Joining orders to order_items creates multiple rows per order. Use COUNT(DISTINCT o.order_id) to avoid overcounting.",
|
| 162 |
+
},
|
| 163 |
+
},
|
| 164 |
+
}
|
sql_debug_env/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SQL Debug Environment — client package."""
|
| 2 |
+
|
| 3 |
+
from sql_debug_env.models import SQLAction, SQLObservation, SQLState
|
| 4 |
+
from sql_debug_env.client import SQLDebugEnv
|
| 5 |
+
|
| 6 |
+
__all__ = ["SQLAction", "SQLObservation", "SQLState", "SQLDebugEnv"]
|
sql_debug_env/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (438 Bytes). View file
|
|
|
sql_debug_env/__pycache__/client.cpython-313.pyc
ADDED
|
Binary file (2.45 kB). View file
|
|
|
sql_debug_env/__pycache__/models.cpython-313.pyc
ADDED
|
Binary file (4.03 kB). View file
|
|
|
sql_debug_env/client.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""WebSocket client for talking to the SQL Debug Environment server."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any, Dict
|
| 6 |
+
|
| 7 |
+
from openenv.core.env_client import EnvClient, StepResult
|
| 8 |
+
|
| 9 |
+
from sql_debug_env.models import SQLAction, SQLObservation, SQLState
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SQLDebugEnv(EnvClient[SQLAction, SQLObservation, SQLState]):
|
| 13 |
+
"""Client for the SQL Debug Environment.
|
| 14 |
+
|
| 15 |
+
Wraps the OpenEnv WebSocket protocol — handles serialization,
|
| 16 |
+
connection management, and type parsing so you don't have to.
|
| 17 |
+
|
| 18 |
+
Quick start:
|
| 19 |
+
async with SQLDebugEnv(base_url="http://localhost:7860") as env:
|
| 20 |
+
obs = await env.reset(task_id="fix_syntax")
|
| 21 |
+
obs = await env.step(SQLAction(query="SELECT ..."))
|
| 22 |
+
|
| 23 |
+
Or synchronously:
|
| 24 |
+
with SQLDebugEnv(base_url="http://localhost:7860").sync() as env:
|
| 25 |
+
obs = env.reset(task_id="fix_syntax")
|
| 26 |
+
obs = env.step(SQLAction(query="SELECT ..."))
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def _parse_result(self, payload: Dict[str, Any]) -> StepResult[SQLObservation]:
|
| 30 |
+
"""Turn the raw JSON payload into a typed StepResult."""
|
| 31 |
+
obs_data = payload.get("observation", payload)
|
| 32 |
+
observation = SQLObservation(**obs_data)
|
| 33 |
+
return StepResult(
|
| 34 |
+
observation=observation,
|
| 35 |
+
reward=payload.get("reward", observation.reward),
|
| 36 |
+
done=payload.get("done", observation.done),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
def _parse_state(self, payload: Dict[str, Any]) -> SQLState:
|
| 40 |
+
"""Deserialize a state payload."""
|
| 41 |
+
return SQLState(**payload)
|
| 42 |
+
|
| 43 |
+
def _step_payload(self, action: SQLAction) -> Dict[str, Any]:
|
| 44 |
+
"""Serialize the action for the wire."""
|
| 45 |
+
return action.model_dump()
|
sql_debug_env/models.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for the SQL Debug Environment.
|
| 3 |
+
|
| 4 |
+
These extend the openenv-core base types so the framework knows
|
| 5 |
+
how to serialize/deserialize our action and observation payloads.
|
| 6 |
+
|
| 7 |
+
Action → SQLAction (just a query string)
|
| 8 |
+
Observation → SQLObservation (all the feedback the agent sees)
|
| 9 |
+
State → SQLState (episode tracking for checkpoints)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from typing import Any, Optional
|
| 15 |
+
|
| 16 |
+
from openenv.core.env_server import Action, Observation, State
|
| 17 |
+
from pydantic import Field
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SQLAction(Action):
|
| 21 |
+
"""What the agent sends us — just a SQL query."""
|
| 22 |
+
|
| 23 |
+
query: str = Field(
|
| 24 |
+
...,
|
| 25 |
+
description="SQL query to run against the database.",
|
| 26 |
+
examples=[
|
| 27 |
+
"SELECT name, salary FROM employees WHERE department = 'Engineering' ORDER BY salary DESC"
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SQLObservation(Observation):
|
| 33 |
+
"""Everything the agent sees after a reset() or step().
|
| 34 |
+
|
| 35 |
+
Inherits done, reward, and metadata from the base Observation class.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
task_id: str = Field(
|
| 39 |
+
...,
|
| 40 |
+
description="Which task we're on (fix_syntax, fix_join, optimize_query).",
|
| 41 |
+
)
|
| 42 |
+
broken_query: str = Field(
|
| 43 |
+
...,
|
| 44 |
+
description="The original broken query that needs fixing.",
|
| 45 |
+
)
|
| 46 |
+
schema_description: str = Field(
|
| 47 |
+
...,
|
| 48 |
+
description="Human-readable schema description for the relevant tables.",
|
| 49 |
+
)
|
| 50 |
+
error_message: Optional[str] = Field(
|
| 51 |
+
None,
|
| 52 |
+
description="SQL error from the last query, if it failed.",
|
| 53 |
+
)
|
| 54 |
+
result_preview: Optional[list[dict[str, Any]]] = Field(
|
| 55 |
+
None,
|
| 56 |
+
description="First 10 rows of the last query's output (when it ran successfully).",
|
| 57 |
+
)
|
| 58 |
+
expected_row_count: int = Field(
|
| 59 |
+
...,
|
| 60 |
+
description="How many rows the correct query returns.",
|
| 61 |
+
)
|
| 62 |
+
current_row_count: Optional[int] = Field(
|
| 63 |
+
None,
|
| 64 |
+
description="How many rows the agent's last query returned.",
|
| 65 |
+
)
|
| 66 |
+
step_number: int = Field(
|
| 67 |
+
0,
|
| 68 |
+
description="Current step in the episode (0 = haven't submitted anything yet).",
|
| 69 |
+
)
|
| 70 |
+
max_steps: int = Field(
|
| 71 |
+
8,
|
| 72 |
+
description="Max steps before the episode auto-terminates.",
|
| 73 |
+
)
|
| 74 |
+
hint: Optional[str] = Field(
|
| 75 |
+
None,
|
| 76 |
+
description="Hint given at certain steps to nudge the agent in the right direction.",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class SQLState(State):
|
| 81 |
+
"""Episode-level state — mostly for debugging and checkpointing.
|
| 82 |
+
|
| 83 |
+
Inherits episode_id and step_count from the base State class.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
task_id: str = Field(default="", description="Which task is active.")
|
| 87 |
+
max_steps: int = Field(default=8, description="Step limit for the episode.")
|
| 88 |
+
last_reward: float = Field(default=0.0, description="Most recent step's reward.")
|
| 89 |
+
cumulative_max_reward: float = Field(
|
| 90 |
+
default=0.0, description="Best reward seen so far this episode."
|
| 91 |
+
)
|
| 92 |
+
done: bool = Field(default=False, description="Whether the episode is over.")
|
| 93 |
+
history: list[dict[str, Any]] = Field(
|
| 94 |
+
default_factory=list,
|
| 95 |
+
description="Log of (query, reward) pairs from this episode.",
|
| 96 |
+
)
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|