CoolFace
Apppublic

Kalletlamadhav/sql-optimization-env

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

๐Ÿ—„๏ธ SQL Query Optimization โ€” RL Training Environment

Meta PyTorch OpenEnv Hackathon ร— SST 2026 Author: Kalletla Madhav OpenEnv-compliant ยท SQLite ยท Indian Data Domains ยท Curriculum Learning

Overview

A containerised FastAPI service that exposes the OpenEnv standard API (/reset, /step, /state) for training LLM agents to optimise slow SQL queries.

The environment actually executes queries on a real SQLite database populated with synthetic Indian enterprise data (GST, PDS/Ration, IRCTC, MGNREGA) and grades agents on real wall-clock speedup โ€” no simulations, no fake timing.


Quick Start

bash
# Clone and build
git clone https://huggingface.co/spaces/Kalletlamadhav/sql-optimization-env
cd sql-optimization-env

# Generate the benchmark database
python data/seed_database.py --rows 100000

# Start the server
uvicorn server.main:app --host 0.0.0.0 --port 7860

# Run the baseline inference script
export OPENAI_API_KEY=sk-...
export MODEL_NAME=gpt-4o-mini
python inference.py

Or with Docker:

bash
docker build -t sql-opt-env .
docker run -p 7860:7860 -e OPENAI_API_KEY=sk-... sql-opt-env

API Reference

POST /reset

Start a new episode. Optionally pin to a specific task.

json
{ "task_id": "gst_missing_index" }

POST /step

Submit an optimised query.

json
{
  "optimized_query": "SELECT invoice_id, invoice_date FROM gst_invoice_records WHERE gstin_supplier = '27AABCU9603R1ZX' AND invoice_date >= '2025-01-01'",
  "identified_pattern": "MISSING_INDEX",
  "explanation": "The query does a full table scan because gstin_supplier has no index.",
  "index_statements": [
    "CREATE INDEX idx_gst_supplier_date ON gst_invoice_records(gstin_supplier, invoice_date DESC)"
  ],
  "schema_analysis": "Table has 100k rows; gstin_supplier is high-selectivity but unindexed."
}

GET /state

Returns full environment state including curriculum level and episode history.


Observation Space

FieldTypeDescription
task_idstringCurrent task identifier
step_numberintCurrent step within episode
goalstringNatural language optimisation objective
schema_ddlstringCREATE TABLE statements for all involved tables
current_querystringThe slow SQL query to optimise
execution_planobjectStructured EXPLAIN QUERY PLAN output
execution_time_msfloatWall-clock execution time in milliseconds
row_countintRows returned by current query
db_statsobjectPer-table row counts and existing indexes
curriculum_levelintCurrent difficulty level (1โ€“5)
anti_pattern_hintstringHint provided at levels 1โ€“2 only

Action Space

FieldTypeDescription
optimized_querystringThe agent's rewritten SQL
identified_patternenumOne of 7 anti-pattern types
explanationstringAgent's reasoning for the fix
index_statementslist[string]Optional CREATE INDEX statements
schema_analysisstringAgent's schema observations

Anti-pattern enum values: N_PLUS_ONE, CARTESIAN_PRODUCT, MISSING_INDEX, SELECT_STAR, LEADING_WILDCARD, IMPLICIT_CAST, UNBOUNDED_AGGREGATION, NONE


Reward Function

DimensionWeightDescription
Speedup0.35log10(orig_time / opt_time) scaled to 0โ€“0.35
Equivalence0.25Jaccard similarity of result sets
Pattern0.20Correct identification + explanation quality
Index0.10Index created AND used by query planner
Simplicity0.10Optimised query โ‰ค original length

Penalties: syntax error (โˆ’0.30), wrong results (โˆ’0.20), slower query (โˆ’0.10), timeout (โˆ’0.05/s), reward hacking (โˆ’0.40).


Tasks

IDLevelAnti-PatternDomain
pds_select_star1 โ€” IntroSELECT_STARPDS Ration
gst_missing_index2 โ€” EasyMISSING_INDEXGST
railway_simple_filter2 โ€” EasyMISSING_INDEXIRCTC
gst_n_plus_one3 โ€” MediumNPLUSONEGST
pds_cartesian3 โ€” MediumCARTESIAN_PRODUCTPDS Ration
mgnrega_wildcard3 โ€” MediumLEADING_WILDCARDMGNREGA
gst_multi_join4 โ€” HardNPLUSONEGST
railway_tatkal_workload4 โ€” HardNPLUSONE + CARTESIANIRCTC
mgnrega_schema_e5 โ€” ExpertUNBOUNDED_AGGREGATIONMGNREGA

Curriculum Learning

The environment automatically adjusts difficulty:

  • โ€”Graduate up after 3 consecutive episodes with score โ‰ฅ 0.70
  • โ€”Step down after 2 consecutive episodes with score < 0.40
  • โ€”State persisted to /tmp/curriculum_state.json across restarts

Baseline Scores

Scores from gpt-4o-mini running inference.py (SEED=42):

TaskStepsFinal Reward
gst_missing_index1TBD
gst_n_plus_one2TBD
gst_multi_join3TBD
Averageโ€”TBD

Run `python inference.py` to reproduce.


Data Domains

SchemaDomain
GSTIndian GST e-invoicing (100k invoices)
PDSPublic Distribution System ration cards
IRCTCIndian Railway PNR bookings
MGNREGARural employment attendance + payments

All data is synthetic, seeded with SEED=42 for full reproducibility.


Project Structure

sql-optimization-env/
โ”œโ”€โ”€ openenv.yaml
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ inference.py
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ server/
โ”‚   โ”œโ”€โ”€ main.py
โ”‚   โ”œโ”€โ”€ environment.py
โ”‚   โ”œโ”€โ”€ models.py
โ”‚   โ”œโ”€โ”€ reward.py
โ”‚   โ”œโ”€โ”€ hack_detector.py
โ”‚   โ””โ”€โ”€ graders/
โ”œโ”€โ”€ tasks/
โ”‚   โ”œโ”€โ”€ easy/   (3 tasks)
โ”‚   โ”œโ”€โ”€ medium/ (3 tasks)
โ”‚   โ””โ”€โ”€ hard/   (3 tasks)
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ schemas/
โ”‚   โ””โ”€โ”€ fixtures/benchmark_seed42.db
โ””โ”€โ”€ curriculum/

Validation

bash
pip install openenv-core
openenv validate

License

MIT โ€” built for Meta PyTorch OpenEnv Hackathon 2026.