vinayaknandi05/sql-optimization-openenv
0
SQL Optimization OpenEnv ๐๏ธโก
An OpenEnv-compliant reinforcement learning environment where an AI agent learns to optimize SQL queries. The agent receives poorly-written SQL (with SELECT *, N+1 subqueries, broken aggregations) and must rewrite them to be correct, performant, and follow best practices.
๐ฏ Motivation
SQL query optimization is a genuine, high-value real-world skill. Poor queries cause slow dashboards, expensive cloud bills, and data bugs. This environment tests whether an agent can:
- Understand a database schema
- Identify anti-patterns in SQL (SELECT *, correlated subqueries, missing GROUP BY)
- Rewrite queries iteratively using feedback rewards
๐๏ธ Environment Description
Observation Space
class SQLObservation(BaseModel):
echoed_message: str # Status message / grading feedback
task_description: str # What the agent needs to do
original_query: str # The broken/unoptimized query to fix
schema_info: str # Full database schema (CREATE TABLE statements)
last_query_result: str # JSON of first 5 rows from last query (nullable)
last_query_error: str # Error if last query failed (nullable)
step: int # Current step number
done: bool # Episode ended?
score: float # Current score [0.0โ1.0]Action Space
class SQLAction(BaseModel):
query: str # The optimized SQL query to submit
message: str # Brief explanation of what was changed (optional)Reward Function
The reward at each step is:
reward = (current_score - previous_best_score) - 0.02 * step_penaltyThe score is computed by a multi-criteria grader:
- Clause usage (0.30): Uses required SQL clauses (WHERE, GROUP BY, JOIN, ORDER BY, etc.)
- Filter correctness (0.15): Required filter values present
- No SELECT * (0.10): Avoids selecting all columns
- Expected columns (0.25): Returns the required output columns
- Row count sanity (0.20): Result set is in expected range
๐ Tasks
Task 1 โ Easy: Fix SELECT * and Add WHERE Clause
- Original:
SELECT * FROM employees; - Goal: Select only
id, name, department, salary; filterWHERE department = 'Engineering'; addORDER BY salary DESC - Expected Score: โฅ 0.70 for correct solution
Task 2 โ Medium: Eliminate N+1 Subquery with JOIN
- Original: Correlated subquery inside SELECT per employee
- Goal: Rewrite using
LEFT JOIN + GROUP BYto count projects per employee in one query - Expected Score: โฅ 0.75 for correct solution
Task 3 โ Hard: Fix Broken Aggregation
- Original:
SELECT ... AVG(salary) FROM employees WHERE salary > AVG(salary);โ broken SQL - Goal: Use a subquery or CTE to compute department averages, then filter employees above their dept avg
- Expected Score: โฅ 0.65 for correct solution
๐ Setup & Usage
Prerequisites
python 3.11+
pip install -r requirements.txtRun Locally
# Start the API server
python app.py
# Server runs on http://localhost:7860Run with Docker
docker build -t sql-openenv .
docker run -p 7860:7860 sql-openenvAPI Endpoints
POST /reset โ Start a new episode
POST /step โ Submit an action (SQL query)
GET /state โ Get current environment state
GET /tasks โ List available tasks
GET /health โ Health check (returns 200)Example: Reset
curl -X POST http://localhost:7860/reset \
-H "Content-Type: application/json" \
-d '{"task_id": "task_easy"}'Example: Step
curl -X POST http://localhost:7860/step \
-H "Content-Type: application/json" \
-d '{
"session_id": "<session_id_from_reset>",
"action": {
"query": "SELECT id, name, department, salary FROM employees WHERE department = '\''Engineering'\'' ORDER BY salary DESC;",
"message": "Fixed SELECT *, added WHERE and ORDER BY"
}
}'๐ค Running the Baseline Inference Script
Set environment variables then run:
export API_BASE_URL="https://api.openai.com/v1"
export API_KEY="sk-..."
export MODEL_NAME="gpt-4o-mini"
export HF_TOKEN="hf_..."
python inference.pyThe script will run all 3 tasks sequentially and print structured [START], [STEP], and [END] JSON logs.
Baseline Scores (gpt-4o-mini)
โ Pre-Submission Validation
pip install pytest pyyaml
python validate.py๐งช Running Tests
pytest tests/ -v๐ Project Structure
sql-openenv/
โโโ app.py # FastAPI application (OpenEnv HTTP API)
โโโ inference.py # Baseline inference script (required by competition)
โโโ openenv.yaml # OpenEnv metadata spec
โโโ Dockerfile # Container definition for HF Spaces
โโโ requirements.txt # Python dependencies
โโโ validate.py # Pre-submission validation script
โโโ README.md # This file
โโโ env/
โ โโโ __init__.py
โ โโโ environment.py # Core environment implementation
โโโ tests/
โโโ test_environment.py # Pytest tests for all 3 tasks๐ท๏ธ Environment Tags
openenv sql optimization real-world code database
