CoolFace
Apppublic

vinayaknandi05/sql-optimization-openenv

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
App README

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:

  1. 1.Understand a database schema
  2. 2.Identify anti-patterns in SQL (SELECT *, correlated subqueries, missing GROUP BY)
  3. 3.Rewrite queries iteratively using feedback rewards

๐Ÿ—๏ธ Environment Description

PropertyValue
Action SpaceSQLAction(query: str, message: str)
Observation SpaceSQLObservation (see below)
Reward Range[-1.0, 1.0]
Max Steps / Episode10
Tasks3 (easy โ†’ medium โ†’ hard)

Observation Space

python
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

python
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_penalty

The 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; filter WHERE department = 'Engineering'; add ORDER 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 BY to 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

bash
python 3.11+
pip install -r requirements.txt

Run Locally

bash
# Start the API server
python app.py
# Server runs on http://localhost:7860

Run with Docker

bash
docker build -t sql-openenv .
docker run -p 7860:7860 sql-openenv

API 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
bash
curl -X POST http://localhost:7860/reset \
  -H "Content-Type: application/json" \
  -d '{"task_id": "task_easy"}'
Example: Step
bash
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:

bash
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.py

The script will run all 3 tasks sequentially and print structured [START], [STEP], and [END] JSON logs.

Baseline Scores (gpt-4o-mini)

TaskDifficultyScore
task_easyEasy~0.85
task_mediumMedium~0.75
task_hardHard~0.65

โœ… Pre-Submission Validation

bash
pip install pytest pyyaml
python validate.py

๐Ÿงช Running Tests

bash
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