Spaces:
Paused
Paused
Commit Β·
cae90e3
1
Parent(s): 915c50c
Add team tooling: dashboard, status checker, run aliases, cheat sheets
Browse files- sqlsage/dashboard.py, status_checker.py, run.py, generate_cheatsheets.py
- Root entrypoints dashboard.py, run.py; optional [run] extra in pyproject
- cheatsheets/ MD+HTML for three roles
- Colab notebook: [training,plots,run], secrets, Cell 6 utilities
Made-with: Cursor
Files changed (14)
- cheatsheets/person1_env_engineer.htmlAdded+99
- cheatsheets/person1_env_engineer.mdAdded+57
- cheatsheets/person2_reward_engineer.htmlAdded+106
- cheatsheets/person2_reward_engineer.mdAdded+71
- cheatsheets/person3_training_lead.htmlAdded+101
- cheatsheets/person3_training_lead.mdAdded+62
- dashboard.pyAdded+7
- notebooks/sqlsage_grpo_colab.ipynb+278-218
- pyproject.toml+7
- run.pyAdded+7
- sqlsage/dashboard.pyAdded+909
- sqlsage/generate_cheatsheets.pyAdded+439
- sqlsage/run.pyAdded+625
- sqlsage/status_checker.pyAdded+573
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>SQLSage β Person 1: Environment Engineer</title><style>@page { size: A4; margin: 10mm; }@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }}* { box-sizing: border-box; }body { background: #fff; color: #000; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 8.5pt; line-height: 1.22; max-width: 195mm; margin: 0 auto; padding: 4mm 5mm 8mm 5mm;}h1 { font-size: 12pt; margin: 0.15em 0; font-weight: 700; }h2 { font-size: 9.5pt; margin: 0.5em 0 0.15em; border-bottom: 1px solid #333; }h3 { font-size: 8.7pt; margin: 0.35em 0 0.1em; }p { margin: 0.2em 0; }ul, ol { margin: 0.15em 0; padding-left: 1.2em; }ul { list-style: disc; }table.cheat { width: 100%; border-collapse: collapse; margin: 0.25em 0; font-size: 7.8pt; }table.cheat th { background: #1a365d; color: #fff; text-align: left; padding: 2px 4px; font-weight: 600; font-size: 7.5pt;}table.cheat td { border: 1px solid #999; padding: 2px 3px; vertical-align: top; }pre.cmd { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.3pt; background: #f4f4f4; border: 1px solid #ccc; padding: 3px 4px; margin: 0.25em 0; white-space: pre-wrap; word-break: break-word;}code.ic { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.5pt; background: #f0f0f0; padding: 0 2px;}br { line-height: 0.2em; }</style></head><body><h1>SQLSage β Person 1: Environment Engineer</h1><p><strong>Deadline: Hour 8 = HF Space live</strong></p><h2>Setup Commands</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">openenv init sqlsage-env</code></td><td>Creates the scaffold (run from parent of the repo dir)</td></tr><tr><td><code class="ic">docker compose up -d</code></td><td>Start Postgres (see <code class="ic">docker-compose.yml</code>; default <strong>port 5433</strong> in README)</td></tr><tr><td><code class="ic">uvicorn sqlsage.app:app --reload --port 8000</code></td><td>Runs environment locally (set <code class="ic">POSTGRES_HOST</code> / <code class="ic">POSTGRES_PORT</code>)</td></tr><tr><td><code class="ic">openenv push your-username/sqlsage-env</code></td><td>Deploys to HF Spaces</td></tr><tr><td><code class="ic">docker run --name sqlsage-pg -e POSTGRES_PASSWORD=sqlsage -e POSTGRES_DB=sqlsage -p 5432:5432 -d postgres:16</code></td><td>Single-container Postgres 16 (alt. to compose)</td></tr><tr><td><code class="ic">curl http://localhost:8000/reset</code></td><td>Tests reset endpoint (local)</td></tr><tr><td><code class="ic">curl -sS "$SQLSAGE_ENV_URL/reset"</code></td><td>Tests deployed Space (set URL from <code class="ic">.env</code>)</td></tr><tr><td><code class="ic">psql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" -c 'SELECT version();'</code></td><td>Verify DB (project default port <strong>5433</strong>)</td></tr><tr><td><code class="ic">openenv validate</code></td><td>OpenEnv project validation</td></tr><tr><td><code class="ic">python -m sqlsage.run p1-serve</code></td><td><strong>Alias</strong> β uvicorn (from <code class="ic">sqlsage.run</code>)</td></tr><tr><td><code class="ic">python -m sqlsage.run p1-test</code></td><td><strong>Alias</strong> β curl local <code class="ic">/reset</code> \</td><td><code class="ic">json.tool</code></td></tr><tr><td><code class="ic">python -m sqlsage.run p1-push</code> / <code class="ic">p1-deploy</code></td><td><strong>Alias</strong> β push + optional HF curl</td></tr></tbody></table><h2>TPC-H Data Load</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">git clone https://github.com/electrum/tpch-dbgen.git && cd tpch-dbgen && make</code></td><td>Clone TPC-H tools</td></tr><tr><td><code class="ic">./dbgen -s 1</code></td><td>Generate SF=1 data (~1GB, ~2 min)</td></tr><tr><td><code class="ic">./dbgen -s 0.1</code></td><td>Generate SF=0.1 (fast, for training)</td></tr><tr><td><code class="ic">psql -U postgres -d sqlsage -f dss.ddl</code></td><td>Create schema (paths per your load process)</td></tr><tr><td>TPC-H bootstrap in Docker / HF image</td><td><code class="ic">sql/bootstrap_tpch_schema.sql</code> auto-runs in Space; load data separately for real rewards</td></tr></tbody></table><h2>Drop Indexes (Creates Optimization Headroom)</h2><pre class="cmd">psql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" \ -f sql/scripts/drop_curriculum_indexes.sqlpsql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_orders_status;"psql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_lineitem_shipdate;"</pre><h2>Stress & Levels (phases: curriculum / env hardening)</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">POSTGRES_HOST=127.0.0.1 POSTGRES_PORT=5433 python scripts/stress_env.py --episodes 50 --levels 2 --identity-step</code></td><td>Stress <code class="ic">reset</code> / optional identity <code class="ic">step</code> (no GRPO)</td></tr><tr><td><code class="ic">SQLSageEnv(tasks=tasks_for_levels(2))</code></td><td>Level 2 only (see <code class="ic">sqlsage.tasks</code>)</td></tr><tr><td><code class="ic">GET /health</code></td><td>Health check (OpenEnv HTTP)</td></tr><tr><td><code class="ic">GET /state</code>, <code class="ic">GET /schema</code>, <code class="ic">GET /metadata</code></td><td>Session / schema metadata</td></tr></tbody></table><h2>Troubleshooting</h2><table class="cheat"><thead><tr><th>Symptom</th><th>Fix</th></tr></thead><tbody><tr><td><code class="ic">curl /reset</code> returns 500</td><td><code class="ic">docker ps</code> / <code class="ic">docker compose ps</code> β DB + API up; check logs</td></tr><tr><td>HF Space build failing</td><td><code class="ic">Dockerfile</code> + entrypoint: Postgres as service, <code class="ic">uvicorn</code> on <code class="ic">$PORT</code> (7860 on HF)</td></tr><tr><td>TPC-H load too long</td><td>Use SF=0.1 for dev; SF=1 for final demo; raise <code class="ic">SQLSAGE_TIMEOUT_MS</code> if needed</td></tr><tr><td>Intermittent 500 under load</td><td>OpenEnv uses a <strong>lock</strong> for reset/step; avoid parallel <code class="ic">step</code> to same process</td></tr></tbody></table><h2>Hour Gates</h2><ul><li>Hour 1: psql connects β</li><li>Hour 4: <code class="ic">curl /reset</code> returns JSON β</li><li>Hour 6: <code class="ic">step()</code> returns <code class="ic">{reward, done, state}</code> β</li><li>Hour 8: <strong>HF Space live</strong> β <strong>SHARE URL WITH TEAM</strong> (<code class="ic">SQLSAGE_ENV_URL</code> in Colab) β</li></ul></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# SQLSage β Person 1: Environment Engineer**Deadline: Hour 8 = HF Space live**
## Setup Commands| Command | What it does ||---------|-------------|| `openenv init sqlsage-env` | Creates the scaffold (run from parent of the repo dir) || `docker compose up -d` | Start Postgres (see `docker-compose.yml`; default **port 5433** in README) || `uvicorn sqlsage.app:app --reload --port 8000` | Runs environment locally (set `POSTGRES_HOST` / `POSTGRES_PORT`) || `openenv push your-username/sqlsage-env` | Deploys to HF Spaces || `docker run --name sqlsage-pg -e POSTGRES_PASSWORD=sqlsage -e POSTGRES_DB=sqlsage -p 5432:5432 -d postgres:16` | Single-container Postgres 16 (alt. to compose) || `curl http://localhost:8000/reset` | Tests reset endpoint (local) || `curl -sS "$SQLSAGE_ENV_URL/reset"` | Tests deployed Space (set URL from `.env`) || `psql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" -c 'SELECT version();'` | Verify DB (project default port **5433**) || `openenv validate` | OpenEnv project validation || `python -m sqlsage.run p1-serve` | **Alias** β uvicorn (from `sqlsage.run`) || `python -m sqlsage.run p1-test` | **Alias** β curl local `/reset` \| `json.tool` || `python -m sqlsage.run p1-push` / `p1-deploy` | **Alias** β push + optional HF curl |
## TPC-H Data Load| Command | What it does ||---------|-------------|| `git clone https://github.com/electrum/tpch-dbgen.git && cd tpch-dbgen && make` | Clone TPC-H tools || `./dbgen -s 1` | Generate SF=1 data (~1GB, ~2 min) || `./dbgen -s 0.1` | Generate SF=0.1 (fast, for training) || `psql -U postgres -d sqlsage -f dss.ddl` | Create schema (paths per your load process) || TPC-H bootstrap in Docker / HF image | `sql/bootstrap_tpch_schema.sql` auto-runs in Space; load data separately for real rewards |
## Drop Indexes (Creates Optimization Headroom)```bashpsql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" \ -f sql/scripts/drop_curriculum_indexes.sqlpsql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_orders_status;"psql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_lineitem_shipdate;"```
## Stress & Levels (phases: curriculum / env hardening)| Command | What it does ||---------|-------------|| `POSTGRES_HOST=127.0.0.1 POSTGRES_PORT=5433 python scripts/stress_env.py --episodes 50 --levels 2 --identity-step` | Stress `reset` / optional identity `step` (no GRPO) || `SQLSageEnv(tasks=tasks_for_levels(2))` | Level 2 only (see `sqlsage.tasks`) || `GET /health` | Health check (OpenEnv HTTP) || `GET /state`, `GET /schema`, `GET /metadata` | Session / schema metadata |
## Troubleshooting| Symptom | Fix ||---------|-----|| `curl /reset` returns 500 | `docker ps` / `docker compose ps` β DB + API up; check logs || HF Space build failing | `Dockerfile` + entrypoint: Postgres as service, `uvicorn` on `$PORT` (7860 on HF) || TPC-H load too long | Use SF=0.1 for dev; SF=1 for final demo; raise `SQLSAGE_TIMEOUT_MS` if needed || Intermittent 500 under load | OpenEnv uses a **lock** for reset/step; avoid parallel `step` to same process |
## Hour Gates- Hour 1: psql connects β- Hour 4: `curl /reset` returns JSON β- Hour 6: `step()` returns `{reward, done, state}` β- Hour 8: **HF Space live** β **SHARE URL WITH TEAM** (`SQLSAGE_ENV_URL` in Colab) β123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>SQLSage β Person 2: Reward & Verifier Engineer</title><style>@page { size: A4; margin: 10mm; }@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }}* { box-sizing: border-box; }body { background: #fff; color: #000; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 8.5pt; line-height: 1.22; max-width: 195mm; margin: 0 auto; padding: 4mm 5mm 8mm 5mm;}h1 { font-size: 12pt; margin: 0.15em 0; font-weight: 700; }h2 { font-size: 9.5pt; margin: 0.5em 0 0.15em; border-bottom: 1px solid #333; }h3 { font-size: 8.7pt; margin: 0.35em 0 0.1em; }p { margin: 0.2em 0; }ul, ol { margin: 0.15em 0; padding-left: 1.2em; }ul { list-style: disc; }table.cheat { width: 100%; border-collapse: collapse; margin: 0.25em 0; font-size: 7.8pt; }table.cheat th { background: #1a365d; color: #fff; text-align: left; padding: 2px 4px; font-weight: 600; font-size: 7.5pt;}table.cheat td { border: 1px solid #999; padding: 2px 3px; vertical-align: top; }pre.cmd { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.3pt; background: #f4f4f4; border: 1px solid #ccc; padding: 3px 4px; margin: 0.25em 0; white-space: pre-wrap; word-break: break-word;}code.ic { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.5pt; background: #f0f0f0; padding: 0 2px;}br { line-height: 0.2em; }</style></head><body><h1>SQLSage β Person 2: Reward & Verifier Engineer</h1><p><strong>Your job: reward pipeline works, no reward hacking, plots committed by Hour 16</strong></p><h2>Core Commands</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">pytest tests/ -v</code></td><td>All unit tests</td></tr><tr><td><code class="ic">pytest tests/test_reward.py -v</code></td><td>Reward tests only</td></tr><tr><td><code class="ic">pytest tests/test_explain_parser.py -v</code></td><td>Parser tests only</td></tr><tr><td><code class="ic">pytest tests/test_anti_cheat.py -v</code></td><td>Anti-cheat tests only</td></tr><tr><td><code class="ic">wandb login</code></td><td>Authenticate W&B</td></tr><tr><td><code class="ic">python monitor_training.py</code></td><td>Live reward diagnostics (when configured)</td></tr><tr><td><code class="ic">python plots/generate_plots.py</code></td><td><strong>Actual path</strong> β generate PNGs in <code class="ic">plots/</code></td></tr><tr><td><code class="ic">python -m sqlsage.run p2-reward</code></td><td><strong>Alias</strong> β quick <code class="ic">compute_reward</code> demo + breakdown</td></tr><tr><td><code class="ic">python -m sqlsage.run p2-plots</code></td><td><strong>Alias</strong> β <code class="ic">plots/generate_plots.py</code></td></tr><tr><td><code class="ic">python -m sqlsage.run p2-anticheat</code></td><td><strong>Alias</strong> β <code class="ic">fix_training.py --issue reward_hacking</code></td></tr><tr><td><code class="ic">python -m sqlsage.status_checker --json</code></td><td>Milestone + reward/plots/git checks (JSON)</td></tr></tbody></table><h2>Quick Reward Test</h2><p><code class="ic">compute_reward</code> returns <strong>(normalized β [-1,1], breakdown dict)</strong> β use both:</p><pre class="cmd">from sqlsage.reward import compute_reward, format_reward_breakdownnew_plan = { "seq_scans": 0, "nested_loops": 0, "hash_joins": 1, "total_cost": 1000, "rows": 1e5, "node_type": "x",}old_plan = { "seq_scans": 2, "nested_loops": 1, "hash_joins": 0, "total_cost": 50000, "rows": 1e6, "node_type": "y",}n, b = compute_reward(8420.0, 310.0, new_plan, old_plan, step_number=0)print("normalized:", n)print(format_reward_breakdown(b))# Raw sum can be large; see breakdown["raw"] and breakdown["normalized"]</pre><h2>Quick EXPLAIN Test</h2><pre class="cmd">psql -h 127.0.0.1 -p 5433 -U postgres -d sqlsage -c \"EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders WHERE orderstatus='F' LIMIT 100;"</pre><h2>Anti-Cheat Attack Vectors to Test Manually</h2><ol><li><code class="ic">LIMIT 0</code> β strong negative / guard</li><li><code class="ic">WHERE 1=0</code> β strong negative / guard</li><li>Remove <code class="ic">WHERE</code> clause (wrong result) β <code class="ic">result_changed</code> / penalty</li><li><code class="ic">CREATE INDEX</code> / DDL β should be rejected / exception</li><li>Unchanged query β <code class="ic">noop_penalty</code> (escalates by step)</li></ol><h2>Reward Component Reference (see <code class="ic">sqlsage/reward.py</code>)</h2><table class="cheat"><thead><tr><th>Component</th><th>Rule (simplified)</th></tr></thead><tbody><tr><td>Speedup</td><td>Up to <code class="ic">MAX_SPEEDUP_REWARD</code> Γ speedup ratio + <code class="ic">BIG_WIN</code> / <code class="ic">EXCEPTIONAL</code> bonuses at high ratio</td></tr><tr><td>Plan</td><td><code class="ic">+SEQ_SCAN_BONUS</code> per seq scan removed, <code class="ic">+NESTED_LOOP_BONUS</code> per nested loop removed</td></tr><tr><td>Rows / cost</td><td><code class="ic">ROWS_SIGNAL_WEIGHT</code> Γ row reduction; <code class="ic">COST_SIGNAL_WEIGHT</code> Γ cost reduction</td></tr><tr><td>No-op</td><td><code class="ic">NOOP_PENALTIES[step]</code> if plan+latency effectively unchanged</td></tr><tr><td>Slowdown</td><td><code class="ic">-SLOWDOWN_WEIGHT</code> Γ slowdown ratio</td></tr><tr><td>Normalize</td><td><code class="ic">raw / NORMALIZATION_DIVISOR</code> β <strong>[-1, 1]</strong></td></tr></tbody></table><h2>If Reward Hacking Detected</h2><pre class="cmd">python fix_training.py --issue reward_hacking</pre><h2>Plots + Evidence (phases: Phase 8, rollout comparison)</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">export WANDB_ENTITY=...; export WANDB_PROJECT=sqlsage-grpo</code></td><td>Match training project (see <code class="ic">docs/PHASE8_CLOSEOUT_CHECKLIST.md</code>)</td></tr><tr><td><code class="ic">SQLSAGE_PLOTS_DEBUG=1 python plots/generate_plots.py</code></td><td>Debug missing W&B data for plots</td></tr><tr><td><code class="ic">python scripts/compare_rollouts.py --baseline results/baseline.jsonl --trained results/trained.jsonl</code></td><td>Table when both JSONL exist</td></tr></tbody></table></body></html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# SQLSage β Person 2: Reward & Verifier Engineer**Your job: reward pipeline works, no reward hacking, plots committed by Hour 16**
## Core Commands| Command | What it does ||---------|-------------|| `pytest tests/ -v` | All unit tests || `pytest tests/test_reward.py -v` | Reward tests only || `pytest tests/test_explain_parser.py -v` | Parser tests only || `pytest tests/test_anti_cheat.py -v` | Anti-cheat tests only || `wandb login` | Authenticate W&B || `python monitor_training.py` | Live reward diagnostics (when configured) || `python plots/generate_plots.py` | **Actual path** β generate PNGs in `plots/` || `python -m sqlsage.run p2-reward` | **Alias** β quick `compute_reward` demo + breakdown || `python -m sqlsage.run p2-plots` | **Alias** β `plots/generate_plots.py` || `python -m sqlsage.run p2-anticheat` | **Alias** β `fix_training.py --issue reward_hacking` || `python -m sqlsage.status_checker --json` | Milestone + reward/plots/git checks (JSON) |
## Quick Reward Test`compute_reward` returns **(normalized β [-1,1], breakdown dict)** β use both:
```pythonfrom sqlsage.reward import compute_reward, format_reward_breakdownnew_plan = { "seq_scans": 0, "nested_loops": 0, "hash_joins": 1, "total_cost": 1000, "rows": 1e5, "node_type": "x",}old_plan = { "seq_scans": 2, "nested_loops": 1, "hash_joins": 0, "total_cost": 50000, "rows": 1e6, "node_type": "y",}n, b = compute_reward(8420.0, 310.0, new_plan, old_plan, step_number=0)print("normalized:", n)print(format_reward_breakdown(b))# Raw sum can be large; see breakdown["raw"] and breakdown["normalized"]```
## Quick EXPLAIN Test```bashpsql -h 127.0.0.1 -p 5433 -U postgres -d sqlsage -c \"EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders WHERE orderstatus='F' LIMIT 100;"```
## Anti-Cheat Attack Vectors to Test Manually1. `LIMIT 0` β strong negative / guard2. `WHERE 1=0` β strong negative / guard3. Remove `WHERE` clause (wrong result) β `result_changed` / penalty4. `CREATE INDEX` / DDL β should be rejected / exception5. Unchanged query β `noop_penalty` (escalates by step)
## Reward Component Reference (see `sqlsage/reward.py`)| Component | Rule (simplified) ||-----------|------------------|| Speedup | Up to `MAX_SPEEDUP_REWARD` Γ speedup ratio + `BIG_WIN` / `EXCEPTIONAL` bonuses at high ratio || Plan | `+SEQ_SCAN_BONUS` per seq scan removed, `+NESTED_LOOP_BONUS` per nested loop removed || Rows / cost | `ROWS_SIGNAL_WEIGHT` Γ row reduction; `COST_SIGNAL_WEIGHT` Γ cost reduction || No-op | `NOOP_PENALTIES[step]` if plan+latency effectively unchanged || Slowdown | `-SLOWDOWN_WEIGHT` Γ slowdown ratio || Normalize | `raw / NORMALIZATION_DIVISOR` β **[-1, 1]** |
## If Reward Hacking Detected```bashpython fix_training.py --issue reward_hacking```
## Plots + Evidence (phases: Phase 8, rollout comparison)| Command | What it does ||---------|-------------|| `export WANDB_ENTITY=...; export WANDB_PROJECT=sqlsage-grpo` | Match training project (see `docs/PHASE8_CLOSEOUT_CHECKLIST.md`) || `SQLSAGE_PLOTS_DEBUG=1 python plots/generate_plots.py` | Debug missing W&B data for plots || `python scripts/compare_rollouts.py --baseline results/baseline.jsonl --trained results/trained.jsonl` | Table when both JSONL exist |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>SQLSage β Person 3: Training Lead</title><style>@page { size: A4; margin: 10mm; }@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }}* { box-sizing: border-box; }body { background: #fff; color: #000; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 8.5pt; line-height: 1.22; max-width: 195mm; margin: 0 auto; padding: 4mm 5mm 8mm 5mm;}h1 { font-size: 12pt; margin: 0.15em 0; font-weight: 700; }h2 { font-size: 9.5pt; margin: 0.5em 0 0.15em; border-bottom: 1px solid #333; }h3 { font-size: 8.7pt; margin: 0.35em 0 0.1em; }p { margin: 0.2em 0; }ul, ol { margin: 0.15em 0; padding-left: 1.2em; }ul { list-style: disc; }table.cheat { width: 100%; border-collapse: collapse; margin: 0.25em 0; font-size: 7.8pt; }table.cheat th { background: #1a365d; color: #fff; text-align: left; padding: 2px 4px; font-weight: 600; font-size: 7.5pt;}table.cheat td { border: 1px solid #999; padding: 2px 3px; vertical-align: top; }pre.cmd { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.3pt; background: #f4f4f4; border: 1px solid #ccc; padding: 3px 4px; margin: 0.25em 0; white-space: pre-wrap; word-break: break-word;}code.ic { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.5pt; background: #f0f0f0; padding: 0 2px;}br { line-height: 0.2em; }</style></head><body><h1>SQLSage β Person 3: Training Lead</h1><p><strong>Critical: Non-zero reward by Hour 12. 300+ episodes by Hour 18.</strong></p><h2>Colab Setup Sequence</h2><ol><li>Runtime β Change runtime type β <strong>A100</strong> GPU</li><li><code class="ic">!pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' -q</code></li><li><code class="ic">!pip install trl openenv wandb psycopg2-binary -q</code> β add <code class="ic">torch</code> as needed</li><li><code class="ic">import torch; print(torch.cuda.get_device_name(0))</code> β must be A100 for Colab template</li><li><code class="ic">pip install -e '.[training]'</code> (local) per README for <code class="ic">scripts/rollout_wandb.py</code></li></ol><h2>Env URL for rollouts</h2><table class="cheat"><thead><tr><th>Variable</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">SQLSAGE_ENV_URL</code></td><td>Person 1 Space or local <code class="ic">http://127.0.0.1:8000</code> (see <code class="ic">README</code> / <code class="ic">.env.example</code>)</td></tr><tr><td><code class="ic">WANDB_ENTITY</code>, <code class="ic">WANDB_PROJECT</code></td><td>W&B org + project (e.g. <code class="ic">sqlsage-grpo</code>)</td></tr></tbody></table><h2>One-liners (phases: rollout, benchmark, closeout)</h2><table class="cheat"><thead><tr><th>Command</th><th>What it does</th></tr></thead><tbody><tr><td><code class="ic">python scripts/rollout_wandb.py --episodes 5</code></td><td>Quick smoke (see README)</td></tr><tr><td><code class="ic">python run_benchmark.py</code></td><td>TPC-H style benchmark; writes <code class="ic">results/benchmark_results.json</code></td></tr><tr><td><code class="ic">python -m sqlsage.run p3-benchmark</code></td><td><strong>Alias</strong> β <code class="ic">run_benchmark.py</code></td></tr><tr><td><code class="ic">python -m sqlsage.run p3-gpu</code></td><td><strong>Alias</strong> β CUDA check (<code class="ic">torch</code>)</td></tr><tr><td><code class="ic">python -m sqlsage.run p3-verify</code></td><td>Quick 5 checks (URL, W&B, plots, benchmark file, README links)</td></tr><tr><td><code class="ic">python -m sqlsage.status_checker --json</code></td><td>Full hackathon gate JSON</td></tr><tr><td><code class="ic">docs/PERSON3_PHASE8_MANUAL.md</code></td><td><strong>Β§7β8 + Β§9</strong> β Colab, Hub, demo video, submission</td></tr><tr><td><code class="ic">docs/PHASE8_CLOSEOUT_CHECKLIST.md</code></td><td>All-roles Phase 8 closeout</td></tr><tr><td><code class="ic">notebooks/sqlsage_grpo_colab.ipynb</code></td><td>GRPO training skeleton</td></tr></tbody></table><h2>Model Save β CRITICAL</h2><p><strong>CORRECT</strong></p><pre class="cmd">model.save_pretrained_merged( "sqlsage-trained", tokenizer, save_method="merged_16bit")</pre><p><strong>WRONG β can corrupt 4-bit quality</strong></p><pre class="cmd">model.merge_and_unload() # DO NOT USE on 4-bit as sole export path</pre><h2>Common Fixes</h2><table class="cheat"><thead><tr><th>Symptom</th><th>Fix</th></tr></thead><tbody><tr><td>CUDA OOM</td><td><code class="ic">batch_size=2</code>, <code class="ic">max_completion_length=256</code>, <code class="ic">grad_accum=8</code></td></tr><tr><td>Invalid JSON from model</td><td>Few-shot JSON example in prompt (see <code class="ic">fix_training</code> / notebook)</td></tr><tr><td>Reward flat after ~50 ep</td><td><code class="ic">python fix_training.py --issue flat_reward</code></td></tr><tr><td><code class="ic">result_changed</code> penalty</td><td><code class="ic">python fix_training.py --issue result_changed</code></td></tr><tr><td>Episodes very slow</td><td>Smaller TPC-H SF (0.1), or lighter tasks</td></tr><tr><td>Curriculum stuck</td><td><code class="ic">python fix_training.py --issue curriculum_stuck</code></td></tr><tr><td>Syntax errors in actions</td><td><code class="ic">python fix_training.py --issue syntax_error</code></td></tr></tbody></table><h2>Reward is working when</h2><ul><li><code class="ic">reward/mean</code> trending up in W&B</li><li><code class="ic">plan/seq_scans_removed</code> (or similar) > 0 when appropriate</li><li><code class="ic">penalty/result_changed</code> near <strong>zero</strong> when results match</li><li>Episode length / latency moving in the right direction for your run</li><li>Benchmark: example target <strong>Q5</strong> latency under your documented threshold (adjust per SF)</li></ul><h2>wandb metrics to watch</h2><p><code class="ic">reward/mean</code>, speedup-related scalars, <code class="ic">penalty/result_changed</code>, <code class="ic">penalty/syntax_error</code>, plan/scan metrics, <code class="ic">episode_length</code> β names depend on your logging callback (see <code class="ic">monitor_training.py</code> / notebook).</p></body></html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# SQLSage β Person 3: Training Lead**Critical: Non-zero reward by Hour 12. 300+ episodes by Hour 18.**
## Colab Setup Sequence1. Runtime β Change runtime type β **A100** GPU2. `!pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' -q`3. `!pip install trl openenv wandb psycopg2-binary -q` β add `torch` as needed4. `import torch; print(torch.cuda.get_device_name(0))` β must be A100 for Colab template5. `pip install -e '.[training]'` (local) per README for `scripts/rollout_wandb.py`
## Env URL for rollouts| Variable | What it does ||----------|---------------|| `SQLSAGE_ENV_URL` | Person 1 Space or local `http://127.0.0.1:8000` (see `README` / `.env.example`) || `WANDB_ENTITY`, `WANDB_PROJECT` | W&B org + project (e.g. `sqlsage-grpo`) |
## One-liners (phases: rollout, benchmark, closeout)| Command | What it does ||---------|-------------|| `python scripts/rollout_wandb.py --episodes 5` | Quick smoke (see README) || `python run_benchmark.py` | TPC-H style benchmark; writes `results/benchmark_results.json` || `python -m sqlsage.run p3-benchmark` | **Alias** β `run_benchmark.py` || `python -m sqlsage.run p3-gpu` | **Alias** β CUDA check (`torch`) || `python -m sqlsage.run p3-verify` | Quick 5 checks (URL, W&B, plots, benchmark file, README links) || `python -m sqlsage.status_checker --json` | Full hackathon gate JSON || `docs/PERSON3_PHASE8_MANUAL.md` | **Β§7β8 + Β§9** β Colab, Hub, demo video, submission || `docs/PHASE8_CLOSEOUT_CHECKLIST.md` | All-roles Phase 8 closeout || `notebooks/sqlsage_grpo_colab.ipynb` | GRPO training skeleton |
## Model Save β CRITICAL**CORRECT**```pythonmodel.save_pretrained_merged( "sqlsage-trained", tokenizer, save_method="merged_16bit")```
**WRONG β can corrupt 4-bit quality**```pythonmodel.merge_and_unload() # DO NOT USE on 4-bit as sole export path```
## Common Fixes| Symptom | Fix ||---------|-----|| CUDA OOM | `batch_size=2`, `max_completion_length=256`, `grad_accum=8` || Invalid JSON from model | Few-shot JSON example in prompt (see `fix_training` / notebook) || Reward flat after ~50 ep | `python fix_training.py --issue flat_reward` || `result_changed` penalty | `python fix_training.py --issue result_changed` || Episodes very slow | Smaller TPC-H SF (0.1), or lighter tasks || Curriculum stuck | `python fix_training.py --issue curriculum_stuck` || Syntax errors in actions | `python fix_training.py --issue syntax_error` |
## Reward is working when- `reward/mean` trending up in W&B- `plan/seq_scans_removed` (or similar) > 0 when appropriate- `penalty/result_changed` near **zero** when results match- Episode length / latency moving in the right direction for your run- Benchmark: example target **Q5** latency under your documented threshold (adjust per SF)
## wandb metrics to watch`reward/mean`, speedup-related scalars, `penalty/result_changed`, `penalty/syntax_error`, plan/scan metrics, `episode_length` β names depend on your logging callback (see `monitor_training.py` / notebook).1234567#!/usr/bin/env python3"""Run from sqlsage-env: python dashboard.py --person 1 (or: python -m sqlsage.dashboard)."""
from sqlsage.dashboard import main
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221{"nbformat": 4,"nbformat_minor": 5,"metadata": {"colab": {"provenance": [],"gpuType": "T4"},"kernelspec": {"display_name": "Python 3","name": "python3","language": "python"},"language_info": {"name": "python","version": "3.10.0"}},"cells": [{"cell_type": "markdown","metadata": {},"source": ["# SQLSage on Google Colab (GPU)\n","\n","Pipeline: **install \u2192 Space liveness \u2192 W&B \u2192 rollouts \u2192 GRPO training \u2192 plots**.\n","\n","1. **Runtime \u2192 Change runtime type \u2192 GPU** (T4 works for 1.5B 4-bit).\n","2. **Colab secrets** (\ud83d\udd11): `WANDB_API_KEY` (optional), `SQLSAGE_ENV_URL` (required for real env), `HF_TOKEN` (Hub upload), `WANDB_ENTITY` (optional).\n","3. **Repo** cloned to `/content/SQLSage`. If your code uses `pyproject.toml` only under `sqlsage-env/`, Cell 1 `cd`s there automatically.\n","4. The Hugging Face Space must implement **`GET /health`** and **`POST /reset`** (included in the SQLSage app). Cold-start can take many minutes.\n","5. T4 defaults: `max_seq=1024`, `max_completion=256`, `num_generations=4`, `batch=2`, `grad_accum=8`, `epochs=1` in the GRPO cell (override `SQLSAGE_NUM_TRAIN_EPOCHS=3` for a full run).\n"]},{"cell_type": "code","metadata": {},"execution_count": null,"outputs": [],"source": ["# Cell 1 \u2014 GPU check, clone repo, install package\n","\n","# Optional: os.environ[\"SQLSAGE_GIT_URL\"] = \"https://github.com/YOU/SQLSage.git\"\n","\n","%pip install -q 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git'\n","%pip install -q trl openenv-core wandb transformers datasets accelerate huggingface_hub requests \"psycopg2-binary\"\n","\n","import os, pathlib, sys, subprocess\n","import torch\n","\n","if not torch.cuda.is_available():\n"," raise RuntimeError(\"Enable GPU: Runtime \u2192 Change runtime type \u2192 T4 (or A100).\")\n","\n","print(\"Device:\", torch.cuda.get_device_name(0), \"| CUDA:\", torch.version.cuda)\n","\n","REPO = pathlib.Path(\"/content/SQLSage\")\n","URL = os.environ.get(\"SQLSAGE_GIT_URL\", \"https://github.com/neelshingavi/SQLSage.git\")\n","if not REPO.is_dir():\n"," subprocess.run([\"git\", \"clone\", \"--depth\", \"1\", URL, str(REPO)], check=True)\n","else:\n"," print(\"Reusing\", REPO)\n","\n","if (REPO / \"pyproject.toml\").is_file():\n"," os.chdir(REPO)\n","elif (REPO / \"sqlsage-env\" / \"pyproject.toml\").is_file():\n"," os.chdir(REPO / \"sqlsage-env\")\n","else:\n"," raise FileNotFoundError(\"pyproject.toml not found at /content/SQLSage or .../sqlsage-env\")\n","\n","ROOT = pathlib.Path().resolve()\n","print(\"Working directory:\", ROOT)\n","%pip install -q -e '.[training,plots]'\n","\n","if str(ROOT) not in sys.path:\n"," sys.path.insert(0, str(ROOT))\n","pathlib.Path(\"results\").mkdir(exist_ok=True)\n","print(\"OK: sqlsage package ready.\")\n"]},{"cell_type": "code","metadata": {},"execution_count": null,"outputs": [],"source": ["# Cell 2 \u2014 Colab secrets, W&B, Space liveness ( /health, /docs, or /reset )\n","\n","import os, sys, time, requests, wandb\n","\n","try:\n"," from google.colab import userdata\n"," for key in (\"WANDB_API_KEY\", \"WANDB_ENTITY\", \"SQLSAGE_ENV_URL\", \"HF_TOKEN\"):\n"," try:\n"," v = userdata.get(key)\n"," except Exception:\n"," v = None\n"," if v and not os.environ.get(key, \"\").strip():\n"," os.environ[key] = v.strip()\n","except ImportError:\n"," pass\n","\n","if os.environ.get(\"HF_TOKEN\", \"\").strip():\n"," os.environ[\"HUGGINGFACE_HUB_TOKEN\"] = os.environ[\"HF_TOKEN\"].strip()\n","\n","os.environ.setdefault(\"SQLSAGE_ENV_URL\", \"https://adity00-sqlsage-env.hf.space\")\n","os.environ.setdefault(\"WANDB_PROJECT\", \"sqlsage-grpo\")\n","\n","base = os.environ[\"SQLSAGE_ENV_URL\"].rstrip(\"/\")\n","print(\"SQLSAGE_ENV_URL =\", base)\n","\n","if os.environ.get(\"WANDB_API_KEY\", \"\").strip():\n"," try:\n"," wandb.login()\n"," print(\"W&B: logged in\")\n"," except Exception as e:\n"," print(\"W&B login warning:\", e)\n","else:\n"," os.environ[\"WANDB_MODE\"] = \"offline\"\n"," print(\"W&B: offline (add Secret WANDB_API_KEY to sync to cloud)\")\n","\n","def space_ready(url: str) -> None:\n"," read_timeout = int(os.environ.get(\"SQLSAGE_HEALTH_READ_TIMEOUT\", \"120\"))\n"," max_wait = int(os.environ.get(\"SQLSAGE_HEALTH_MAX_WAIT\", \"600\"))\n"," poll = int(os.environ.get(\"SQLSAGE_HEALTH_POLL_S\", \"8\"))\n"," deadline = time.time() + max_wait\n"," n = 0\n"," while time.time() < deadline:\n"," n += 1\n"," for path in (\"/health\", \"/docs\", \"/openapi.json\"):\n"," try:\n"," r = requests.get(url + path, timeout=read_timeout)\n"," if r.status_code == 200:\n"," print(\"Space OK:\", path, \"->\", r.status_code)\n"," r2 = requests.post(url + \"/reset\", json={}, timeout=180)\n"," print(\"/reset\", r2.status_code, (r2.text or \"\")[:200])\n"," if r2.status_code == 200:\n"," ob = (r2.json() or {}).get(\"observation\", {})\n"," print(\"task_level\", ob.get(\"task_level\"), \"step\", ob.get(\"step_count\"))\n"," return\n"," except requests.RequestException as e:\n"," print(\"Try\", n, path, e)\n"," time.sleep(poll)\n"," raise RuntimeError(\"Space not reachable. Open the .hf.space URL in a browser, wait, re-run.\")\n","\n","space_ready(base)\n","print(\"\u2014 Ready for rollouts & training \u2014\")\n"]},{"cell_type": "code","metadata": {},"execution_count": null,"outputs": [],"source": ["# Cell 3 \u2014 Rollout smoke + baseline JSONL (identity policy) \u2192 W&B\n","\n","import os, sys, subprocess, pathlib\n","\n","base = os.environ[\"SQLSAGE_ENV_URL\"].rstrip(\"/\")\n","proj = os.environ.get(\"WANDB_PROJECT\", \"sqlsage-grpo\")\n","name = os.environ.get(\"WANDB_RUN_NAME_ROLLOUT\", \"colab-baseline\")\n","ep_smoke = int(os.environ.get(\"SQLSAGE_ROLLOUT_SMOKE_EPISODES\", \"5\"))\n","ep_base = int(os.environ.get(\"SQLSAGE_ROLLOUT_BASELINE_EPISODES\", \"50\"))\n","envp = os.environ.copy()\n","\n","def run_cmd(args):\n"," print(\"$\", \" \".join(args))\n"," subprocess.check_call(args, env=envp, cwd=pathlib.Path().resolve())\n","\n","run_cmd([sys.executable, \"scripts/rollout_wandb.py\", \"--episodes\", str(ep_smoke), \"--base-url\", base, \"--project\", proj, \"--run-name\", f\"{name}-smoke\", \"--out-jsonl\", \"results/smoke.jsonl\"])\n","run_cmd([sys.executable, \"scripts/rollout_wandb.py\", \"--episodes\", str(ep_base), \"--policy\", \"identity\", \"--base-url\", base, \"--project\", proj, \"--run-name\", f\"{name}-baseline\", \"--out-jsonl\", \"results/baseline.jsonl\"])\n","if pathlib.Path(\"results\").is_dir():\n"," for p in sorted(pathlib.Path(\"results\").glob(\"*.jsonl\")):\n"," print(p, p.stat().st_size, \"bytes\")\n"]},{"cell_type": "code","metadata": {},"execution_count": null,"outputs": [],"source": ["# Cell 4 \u2014 Full GRPO (train.run_training) \u2014 T4-tuned via env (see also train.py)\n","\n","import os\n","os.environ[\"SQLSAGE_MAX_SEQ_LENGTH\"] = \"1024\"\n","os.environ[\"SQLSAGE_MAX_COMPLETION_LENGTH\"] = \"256\"\n","os.environ[\"SQLSAGE_NUM_GENERATIONS\"] = \"4\"\n","os.environ[\"SQLSAGE_PER_DEVICE_TRAIN_BATCH_SIZE\"] = \"2\"\n","os.environ[\"SQLSAGE_GRADIENT_ACCUMULATION_STEPS\"] = \"8\"\n","# 1 = smoke, 3 = full run\n","os.environ[\"SQLSAGE_NUM_TRAIN_EPOCHS\"] = os.environ.get(\"SQLSAGE_NUM_TRAIN_EPOCHS\", \"1\")\n","os.environ[\"SQLSAGE_GRPO_TEMPERATURE\"] = \"0.9\"\n","os.environ[\"SQLSAGE_OUTPUT_DIR\"] = \"sqlsage-grpo\"\n","os.environ[\"SQLSAGE_MERGED_DIR\"] = \"sqlsage-grpo-merged\"\n","os.environ[\"SQLSAGE_MODEL_NAME\"] = os.environ.get(\"SQLSAGE_MODEL_NAME\", \"Qwen/Qwen2.5-1.5B-Instruct\")\n","os.environ[\"WANDB_RUN_NAME\"] = os.environ.get(\"WANDB_GRPO_RUN_NAME\", \"colab-grpo-t4\")\n","\n","assert os.environ.get(\"SQLSAGE_ENV_URL\", \"\").strip(), \"Set SQLSAGE_ENV_URL (Colab Secret or above)\"\n","\n","from train import run_training\n","print(run_training())\n"]},{"cell_type": "code","metadata": {},"execution_count": null,"outputs": [],"source": ["# Cell 5 \u2014 Plots, artifact paths, optional download\n","\n","!python plots/generate_plots.py\n","!ls -la plots/*.png 2>/dev/null; ls -la sqlsage-grpo/ sqlsage-grpo-merged/ 2>/dev/null; true\n","# from google.colab import files; files.download(\"plots/reward_curve.png\")\n","# !python scripts/push_model_to_hub.py --folder ./sqlsage-grpo-merged --repo-id USER/sqlsage-merged\n","print(\"LoRA: ./sqlsage-grpo | merged 16bit: ./sqlsage-grpo-merged\")\n"]}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281{"cells": [{"cell_type": "markdown","metadata": {},"source": ["# SQLSage on Google Colab (GPU)\n","\n","Pipeline: **install β Space liveness β W&B β rollouts β GRPO training β plots**.\n","\n","1. **Runtime β Change runtime type β GPU** (T4 works for 1.5B 4-bit smoke; **A100** is faster for long GRPO if available).\n","2. **Colab secrets** (optional): `WANDB_API_KEY`, `SQLSAGE_ENV_URL` (Hugging Face Space **base** URL for rollouts and training), `HF_TOKEN` (Hub upload), `WANDB_ENTITY`, plus optionally `SQLSAGE_HF_SPACE_URL` (Space URL for milestone checks) and `SQLSAGE_WANDB_RUN_ID` (full W&B run path, `entity/project/run_id`, for `status_checker` API checks). If you only set `SQLSAGE_ENV_URL`, Cell 2 copies it to `SQLSAGE_HF_SPACE_URL` when unset.\n","3. **Repo** is cloned to `/content/SQLSage`. This notebook `cd`s into `sqlsage-env/` when `pyproject.toml` is there.\n","4. The Space must serve **`GET /health`** and **`POST /reset`**. Cold-start can take many minutes.\n","5. Cell 4 default hyperparams are T4-friendly. Set `SQLSAGE_NUM_TRAIN_EPOCHS=3` (or higher) in the environment for a longer run.\n","\n","**Team tooling in-repo** (after **Cell 1**): `python -m sqlsage.run help` (short aliases, e.g. `p3-gpu`, `p2-reward`), `python -m sqlsage.status_checker` / `--json` (milestone and reward/plots checks), `python -m sqlsage.generate_cheatsheets` (one-page `cheatsheets/*.md` + `.html`). **Cell 6** runs these optionally (read-only; safe to re-run any time).\n"],"id": "a93e4f3f"},{"cell_type": "code","metadata": {},"source": ["# Cell 1 β GPU check, clone repo, install package\n","\n","# Optional: os.environ[\"SQLSAGE_GIT_URL\"] = \"https://github.com/YOU/SQLSage.git\"\n","\n","%pip install -q 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git'\n","%pip install -q trl openenv-core wandb transformers datasets accelerate huggingface_hub requests \"psycopg2-binary\"\n","\n","import os, pathlib, sys, subprocess\n","import torch\n","\n","if not torch.cuda.is_available():\n"," raise RuntimeError(\"Enable GPU: Runtime β Change runtime type β T4 (or A100).\")\n","\n","print(\"Device:\", torch.cuda.get_device_name(0), \"| CUDA:\", torch.version.cuda)\n","\n","REPO = pathlib.Path(\"/content/SQLSage\")\n","URL = os.environ.get(\"SQLSAGE_GIT_URL\", \"https://github.com/neelshingavi/SQLSage.git\")\n","if not REPO.is_dir():\n"," subprocess.run([\"git\", \"clone\", \"--depth\", \"1\", URL, str(REPO)], check=True)\n","else:\n"," print(\"Reusing\", REPO)\n","\n","if (REPO / \"pyproject.toml\").is_file():\n"," os.chdir(REPO)\n","elif (REPO / \"sqlsage-env\" / \"pyproject.toml\").is_file():\n"," os.chdir(REPO / \"sqlsage-env\")\n","else:\n"," raise FileNotFoundError(\"pyproject.toml not found at /content/SQLSage or .../sqlsage-env\")\n","\n","ROOT = pathlib.Path().resolve()\n","print(\"Working directory:\", ROOT)\n","# training + plots + run extras (rich, python-dotenv) for `sqlsage.run` and dashboard-style helpers\n","%pip install -q -e '.[training,plots,run]'\n","\n","if str(ROOT) not in sys.path:\n"," sys.path.insert(0, str(ROOT))\n","pathlib.Path(\"results\").mkdir(exist_ok=True)\n","print(\"OK: sqlsage package ready.\")\n"],"execution_count": null,"outputs": [],"id": "4c6b5ef6"},{"cell_type": "code","metadata": {},"source": ["# Cell 2 β Colab secrets, W&B, Space liveness ( /health, /docs, or /reset )\n","\n","import os, sys, time, requests, wandb\n","\n","try:\n"," from google.colab import userdata\n"," for key in (\n"," \"WANDB_API_KEY\",\n"," \"WANDB_ENTITY\",\n"," \"SQLSAGE_ENV_URL\",\n"," \"SQLSAGE_HF_SPACE_URL\",\n"," \"SQLSAGE_WANDB_RUN_ID\",\n"," \"HF_TOKEN\",\n"," ):\n"," try:\n"," v = userdata.get(key)\n"," except Exception:\n"," v = None\n"," if v and not os.environ.get(key, \"\").strip():\n"," os.environ[key] = v.strip()\n","except ImportError:\n"," pass\n","\n","if os.environ.get(\"HF_TOKEN\", \"\").strip():\n"," os.environ[\"HUGGINGFACE_HUB_TOKEN\"] = os.environ[\"HF_TOKEN\"].strip()\n","\n","os.environ.setdefault(\"SQLSAGE_ENV_URL\", \"https://adity00-sqlsage-env.hf.space\")\n","os.environ.setdefault(\"WANDB_PROJECT\", \"sqlsage-grpo\")\n","\n","base = os.environ[\"SQLSAGE_ENV_URL\"].rstrip(\"/\")\n","# sqlsage.status_checker uses this name; default to the same Space URL as training/rollouts\n","if not (os.environ.get(\"SQLSAGE_HF_SPACE_URL\") or \"\").strip():\n"," os.environ[\"SQLSAGE_HF_SPACE_URL\"] = base\n","print(\"SQLSAGE_ENV_URL =\", base)\n","print(\"SQLSAGE_HF_SPACE_URL =\", os.environ.get(\"SQLSAGE_HF_SPACE_URL\", \"\"))\n","\n","if os.environ.get(\"WANDB_API_KEY\", \"\").strip():\n"," try:\n"," wandb.login()\n"," print(\"W&B: logged in\")\n"," except Exception as e:\n"," print(\"W&B login warning:\", e)\n","else:\n"," os.environ[\"WANDB_MODE\"] = \"offline\"\n"," print(\"W&B: offline (add Secret WANDB_API_KEY to sync to cloud)\")\n","\n","def space_ready(url: str) -> None:\n"," read_timeout = int(os.environ.get(\"SQLSAGE_HEALTH_READ_TIMEOUT\", \"120\"))\n"," max_wait = int(os.environ.get(\"SQLSAGE_HEALTH_MAX_WAIT\", \"600\"))\n"," poll = int(os.environ.get(\"SQLSAGE_HEALTH_POLL_S\", \"8\"))\n"," deadline = time.time() + max_wait\n"," n = 0\n"," while time.time() < deadline:\n"," n += 1\n"," for path in (\"/health\", \"/docs\", \"/openapi.json\"):\n"," try:\n"," r = requests.get(url + path, timeout=read_timeout)\n"," if r.status_code == 200:\n"," print(\"Space OK:\", path, \"->\", r.status_code)\n"," r2 = requests.post(url + \"/reset\", json={}, timeout=180)\n"," print(\"/reset\", r2.status_code, (r2.text or \"\")[:200])\n"," if r2.status_code == 200:\n"," ob = (r2.json() or {}).get(\"observation\", {})\n"," print(\"task_level\", ob.get(\"task_level\"), \"step\", ob.get(\"step_count\"))\n"," return\n"," except requests.RequestException as e:\n"," print(\"Try\", n, path, e)\n"," time.sleep(poll)\n"," raise RuntimeError(\"Space not reachable. Open the .hf.space URL in a browser, wait, re-run.\")\n","\n","space_ready(base)\n","print(\"β Ready for rollouts & training β\")\n"],"execution_count": null,"outputs": [],"id": "d00c614b"},{"cell_type": "code","metadata": {},"source": ["# Cell 3 β Rollout smoke + baseline JSONL (identity policy) β W&B\n","\n","import os, sys, subprocess, pathlib\n","\n","base = os.environ[\"SQLSAGE_ENV_URL\"].rstrip(\"/\")\n","proj = os.environ.get(\"WANDB_PROJECT\", \"sqlsage-grpo\")\n","name = os.environ.get(\"WANDB_RUN_NAME_ROLLOUT\", \"colab-baseline\")\n","ep_smoke = int(os.environ.get(\"SQLSAGE_ROLLOUT_SMOKE_EPISODES\", \"5\"))\n","ep_base = int(os.environ.get(\"SQLSAGE_ROLLOUT_BASELINE_EPISODES\", \"50\"))\n","envp = os.environ.copy()\n","\n","def run_cmd(args):\n"," print(\"$\", \" \".join(args))\n"," subprocess.check_call(args, env=envp, cwd=pathlib.Path().resolve())\n","\n","run_cmd([sys.executable, \"scripts/rollout_wandb.py\", \"--episodes\", str(ep_smoke), \"--base-url\", base, \"--project\", proj, \"--run-name\", f\"{name}-smoke\", \"--out-jsonl\", \"results/smoke.jsonl\"])\n","run_cmd([sys.executable, \"scripts/rollout_wandb.py\", \"--episodes\", str(ep_base), \"--policy\", \"identity\", \"--base-url\", base, \"--project\", proj, \"--run-name\", f\"{name}-baseline\", \"--out-jsonl\", \"results/baseline.jsonl\"])\n","if pathlib.Path(\"results\").is_dir():\n"," for p in sorted(pathlib.Path(\"results\").glob(\"*.jsonl\")):\n"," print(p, p.stat().st_size, \"bytes\")\n"],"execution_count": null,"outputs": []},{"cell_type": "code","metadata": {},"source": ["# Cell 4 β Full GRPO (train.run_training) β T4-tuned via env (see also train.py)\n","\n","import os\n","os.environ[\"SQLSAGE_MAX_SEQ_LENGTH\"] = \"1024\"\n","os.environ[\"SQLSAGE_MAX_COMPLETION_LENGTH\"] = \"256\"\n","os.environ[\"SQLSAGE_NUM_GENERATIONS\"] = \"4\"\n","os.environ[\"SQLSAGE_PER_DEVICE_TRAIN_BATCH_SIZE\"] = \"2\"\n","os.environ[\"SQLSAGE_GRADIENT_ACCUMULATION_STEPS\"] = \"8\"\n","# 1 = smoke, 3 = full run\n","os.environ[\"SQLSAGE_NUM_TRAIN_EPOCHS\"] = os.environ.get(\"SQLSAGE_NUM_TRAIN_EPOCHS\", \"1\")\n","os.environ[\"SQLSAGE_GRPO_TEMPERATURE\"] = \"0.9\"\n","os.environ[\"SQLSAGE_OUTPUT_DIR\"] = \"sqlsage-grpo\"\n","os.environ[\"SQLSAGE_MERGED_DIR\"] = \"sqlsage-grpo-merged\"\n","os.environ[\"SQLSAGE_MODEL_NAME\"] = os.environ.get(\"SQLSAGE_MODEL_NAME\", \"Qwen/Qwen2.5-1.5B-Instruct\")\n","os.environ[\"WANDB_RUN_NAME\"] = os.environ.get(\"WANDB_GRPO_RUN_NAME\", \"colab-grpo-t4\")\n","\n","assert os.environ.get(\"SQLSAGE_ENV_URL\", \"\").strip(), \"Set SQLSAGE_ENV_URL (Colab Secret or above)\"\n","\n","from train import run_training\n","print(run_training())\n"],"execution_count": null,"outputs": []},{"cell_type": "code","metadata": {},"source": ["# Cell 5 β Plots, artifact paths, optional download\n","# Same as local: `python -m sqlsage.run p2-plots` (from repo root)\n","\n","!python plots/generate_plots.py\n","!ls -la plots/*.png 2>/dev/null; ls -la sqlsage-grpo/ sqlsage-grpo-merged/ 2>/dev/null; true\n","# from google.colab import files; files.download(\"plots/reward_curve.png\")\n","# !python scripts/push_model_to_hub.py --folder ./sqlsage-grpo-merged --repo-id USER/sqlsage-merged\n","# `python -m sqlsage.run p3-benchmark` needs a local DB β run on your dev machine, not in Colab\n","print(\"LoRA: ./sqlsage-grpo | merged 16bit: ./sqlsage-grpo-merged\")\n"],"execution_count": null,"outputs": [],"id": "ed8527f2"},{"cell_type": "code","metadata": {},"source": ["# Cell 6 β (Optional) team utilities: status checks, cheat sheets, alias list\n","# Re-run any time. Does not start training. Exit codes may be != 0 if a milestone is \"red\" β that is expected.\n","\n","import os, subprocess, sys, pathlib\n","\n","ROOT = pathlib.Path().resolve()\n","os.environ.setdefault(\"SQLSAGE_HF_SPACE_URL\", (os.environ.get(\"SQLSAGE_ENV_URL\", \"\") or \"\").rstrip(\"/\"))\n","print(\"SQLSAGE_HF_SPACE_URL (for /reset check):\", os.environ.get(\"SQLSAGE_HF_SPACE_URL\", \"(not set)\"))\n","if (os.environ.get(\"SQLSAGE_WANDB_RUN_ID\") or \"\").strip():\n"," print(\"SQLSAGE_WANDB_RUN_ID set (entity/project/run) β full W&B gate checks enabled\")\n","\n","# JSON milestone + reward/plot/git checks\n","subprocess.run(\n"," [sys.executable, \"-m\", \"sqlsage.status_checker\", \"--json\"],\n"," cwd=ROOT,\n",")\n","print(\"---\")\n","\n","# Printable one-page MD + HTML cheat sheets under ./cheatsheets/\n","subprocess.run(\n"," [sys.executable, \"-m\", \"sqlsage.generate_cheatsheets\"],\n"," cwd=ROOT,\n",")\n","print(\"Cheat sheets:\", ROOT / \"cheatsheets\")\n","print(\"---\")\n","\n","# Short list of one-command aliases (p3-gpu, p2-reward, status, β¦)\n","subprocess.run(\n"," [sys.executable, \"-m\", \"sqlsage.run\", \"help\"],\n"," cwd=ROOT,\n",")"],"id": "4413c34c","execution_count": null,"outputs": []}],"metadata": {"colab": {"gpuType": "T4","provenance": []},"kernelspec": {"display_name": "Python 3","language": "python","name": "python3"},"language_info": {"name": "python","version": "3.10.0"}},"nbformat": 4,"nbformat_minor": 5}
25 unmodified lines26272829303125 unmodified lines"rich>=13","torch",][project.scripts]server = "server.app:main"25 unmodified lines2627282930313233343536373825 unmodified lines"rich>=13","torch",]# sqlsage.run CLI + status_checker extrasrun = ["rich>=13","python-dotenv>=1.0.0","requests>=2.28","wandb>=0.16",][project.scripts]server = "server.app:main"
1234567#!/usr/bin/env python3"""From sqlsage-env: python run.py p1-serve (same as python -m sqlsage.run)."""
from sqlsage.run import main
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909"""Live terminal dashboard for the SQLSage hackathon (Rich).
cd sqlsage-env python dashboard.py --person 1 python -m sqlsage.dashboard --team python -m sqlsage.dashboard --person 2 --live --refresh 30
Env: ``SQLSAGE_HF_RESET_URL`` β HF /reset URL for the hour-8 check (else NOT CHECKED)."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport subprocessimport timefrom datetime import datetimefrom typing import Any, Callable, Optional
# --- Time constants (naive local time) ---
HACKATHON_START = datetime(2026, 4, 25, 17, 0, 0) # Day 1, 5 PMHACKATHON_END = datetime(2026, 4, 26, 17, 0, 0) # Day 2, 5 PMSUBMISSION_HARD_DEADLINE = datetime(2026, 4, 26, 16, 30, 0) # 23.5h
# --- Rich (optional heavy imports in render) ---
PERSON_ROLES: dict[int, str] = { 1: "Environment Engineer", 2: "Reward & Verifier Engineer", 3: "Training Lead",}
MILESTONES: list[dict[str, Any]] = [ { "hour": 8, "gate": "Environment deployed to HF Spaces", "owner": "Person 1", "check_command": "curl https://your-hf-username-sqlsage-env.hf.space/reset", "if_missed": "CRISIS: Stop all other work. Fix deployment NOW.", "verify_fn": "check_hf_space_live()", }, { "hour": 12, "gate": "First training run showing non-zero reward", "owner": "Person 3", "check_command": "python monitor_training.py", "if_missed": "DEBUG: Print every reward value. Check reward pipeline.", "verify_fn": "check_wandb_nonzero_reward()", }, { "hour": 18, "gate": "Full training run complete (300+ episodes). Plots committed.", "owner": "Person 3", "check_command": "python generate_plots.py && git add plots/ && git commit -m 'plots'", "if_missed": "Reduce to 100 episodes. Plots > long run.", "verify_fn": "check_plots_committed()", }, { "hour": 21, "gate": "Before/after comparison documented with real numbers", "owner": "All", "check_command": "python run_benchmark.py", "if_missed": "Use whatever numbers you have. Do not invent.", "verify_fn": "check_benchmark_results_exist()", }, { "hour": 23, "gate": "README done. All links. Form ready.", "owner": "All", "check_command": "cat README.md | grep 'hf.space'", "if_missed": "Submit what you have. 80% submitted > 100% unsubmitted.", "verify_fn": "check_readme_has_links()", }, { "hour": 24, "gate": "Google Form submitted", "owner": "All", "check_command": "# Open submission form link", "if_missed": "HARD DEADLINE. Submit at hour 23.5 β do NOT wait.", "verify_fn": None, },]
# --- Per-person tasks (data from hackathon spec) ---
PERSON_TASKS: dict[int, list[dict[str, Any]]] = { 1: [ { "hours": "0-1", "task": "openenv init + PostgreSQL Docker + TPC-H schema load", "commands": [ "openenv init sqlsage-env", "docker run --name sqlsage-pg -e POSTGRES_PASSWORD=sqlsage -e POSTGRES_DB=sqlsage -p 5432:5432 -d postgres:16", "psql -h localhost -U postgres -d sqlsage -c 'SELECT version();'", ], "done_when": "psql connects, tables exist, row counts correct", }, { "hours": "1-4", "task": "Implement env.py: reset(), step(), state(). Implement explain_parser.py.", "commands": [ "uvicorn sqlsage.app:app --reload --port 8000", "curl http://localhost:8000/reset", ], "done_when": "curl /reset returns valid JSON observation", }, { "hours": "4-6", "task": "execute_and_measure() + get_result_hash() + anti_cheat.py", "commands": [ "pytest tests/test_anti_cheat.py -v", 'python -c "from sqlsage.env import SQLSageEnv; e=SQLSageEnv(); print(e.step(\'rewrite_join\', \'SELECT 1\'))"', ], "done_when": "step() with valid rewrite returns {reward, done, state}", }, { "hours": "6-8", "task": "Level 1 tasks (Q1, Q6, Q14). Drop indexes. Deploy to HF Spaces.", "commands": [ "psql -U postgres -d sqlsage -c 'DROP INDEX IF EXISTS idx_orders_status;'", "psql -U postgres -d sqlsage -c 'DROP INDEX IF EXISTS idx_lineitem_shipdate;'", "openenv push your-hf-username/sqlsage-env", "curl https://your-hf-username-sqlsage-env.hf.space/reset", ], "done_when": "Remote env.reset() works. URL shared with Person 3.", }, { "hours": "8-14", "task": "Debug issues. Add Level 2 tasks. Test anti-cheat guards.", "commands": [ "python fix_training.py --issue env_500", "pytest tests/ -v", ], "done_when": "Training run completes 50+ episodes", }, { "hours": "14-18", "task": "Add Level 3 tasks. Stress test. Fix race conditions.", "commands": [ "python monitor_training.py", "pytest tests/test_level3.py -v", ], "done_when": "All 3 curriculum levels work end-to-end", }, { "hours": "18-22", "task": "Write README environment section. Test HF Space UI.", "commands": [ "openenv push your-hf-username/sqlsage-env", "curl https://your-hf-username-sqlsage-env.hf.space/reset", ], "done_when": "README done. Judges can run env.reset()", }, { "hours": "22-24", "task": "Buffer for submission issues.", "commands": ["# Monitor HF Space. Fix any last-minute issues."], "done_when": "Google Form submitted", }, ], 2: [ { "hours": "0-3", "task": "Implement explain_parser.py. Write unit tests.", "commands": [ 'psql -h localhost -U postgres -d sqlsage -c "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders LIMIT 100;"', 'python -c \'from sqlsage.explain_parser import get_explain_dict; import psycopg2; conn=psycopg2.connect(host="localhost",user="postgres",password="sqlsage",dbname="sqlsage"); print(get_explain_dict(conn, "SELECT * FROM orders LIMIT 100"))\'', "pytest tests/test_explain_parser.py -v", ], "done_when": "All parser unit tests pass", }, { "hours": "3-7", "task": "Implement reward.py with all components. pytest all reward cases.", "commands": [ "pytest tests/test_reward.py -v", 'python -c \'from sqlsage.reward import compute_reward; print(compute_reward(8420, 310, {"seq_scans":0,"nested_loops":0,"hash_joins":1,"total_cost":1000}, {"seq_scans":2,"nested_loops":1,"hash_joins":0,"total_cost":50000}))\'', ], "done_when": "All 10+ reward unit tests pass", }, { "hours": "7-10", "task": "Implement anti_cheat.py. Test all 5 attack vectors.", "commands": [ "python fix_training.py --issue reward_hacking", "pytest tests/test_anti_cheat.py -v", ], "done_when": "All 5 attack vectors correctly penalized", }, { "hours": "10-16", "task": "Monitor training. Watch wandb. Flag reward hacking.", "commands": [ "wandb login", "python monitor_training.py", "python fix_training.py --issue flat_reward", ], "done_when": "100+ episodes. No reward hacking detected.", }, { "hours": "16-20", "task": "Generate reward curve plots. Commit to repo.", "commands": [ "python generate_plots.py", "git add plots/ && git commit -m 'Add training reward plots'", "git push", ], "done_when": "3 plots committed to repo", }, { "hours": "20-22", "task": "Write HF blog post (< 2 min read).", "commands": [ "# Go to huggingface.co/blog/new", "# Title: SQLSage: Teaching LLMs to Read Query Plans with RL", ], "done_when": "Blog post published on HF", }, { "hours": "22-24", "task": "Buffer. Help with pitch rehearsal.", "commands": ["# Run demo script from Section 10"], "done_when": "Pitch rehearsed. Form ready.", }, ], 3: [ { "hours": "0-3", "task": "Set up Colab. Install deps. Verify GPU. Load Qwen 2.5 1.5B.", "commands": [ "# Runtime β Change runtime type β A100 GPU", "!pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' -q", "!pip install trl openenv wandb psycopg2-binary -q", "import torch; print(torch.cuda.get_device_name(0))", ], "done_when": "Model loads. GPU confirmed A100.", }, { "hours": "3-6", "task": "Build dataset pipeline. Test prompt template.", "commands": [ "python sqlsage/prompt_builder.py --test", "python -c 'from sqlsage.dataset import build_dataset; print(len(build_dataset()))'", ], "done_when": "Model generates parseable JSON", }, { "hours": "6-10", "task": "Connect to P1's env. Run first small training: 20 episodes, Level 1.", "commands": [ "# In Colab: env = Environment.from_hub('your-hf-username/sqlsage-env')", "# Run GRPOTrainer for 20 episodes", ], "done_when": "First reward curve visible in wandb", }, { "hours": "10-14", "task": "Tune prompt. Run 100-episode Level 1 run.", "commands": [ "python fix_training.py --issue syntax_error", "python fix_training.py --issue flat_reward", ], "done_when": "Reward trend upward. >30% pass rate.", }, { "hours": "14-18", "task": "Add Level 2. Run full 300-episode training. Save checkpoints.", "commands": [ "# In Colab: run full training cell", "model.save_pretrained_merged('sqlsage-trained', tokenizer, save_method='merged_16bit')", ], "done_when": "Full training run complete. Plots show improvement.", }, { "hours": "18-20", "task": "Run baseline comparison. Record before/after numbers.", "commands": [ "python run_benchmark.py", ], "done_when": "Specific ms values documented.", }, { "hours": "20-22", "task": "Save final model. Push to HF Hub. Test inference.", "commands": [ "huggingface-cli login", "model.save_pretrained_merged('sqlsage-trained', tokenizer, save_method='merged_16bit')", "# Upload to HF Hub via notebook", ], "done_when": "Model on HF Hub. Inference works.", }, { "hours": "22-24", "task": "Record 2-minute demo video.", "commands": [ "# Follow demo script from Section 10 exactly", "# Record screen. Upload to YouTube (unlisted). Copy URL.", ], "done_when": "Video uploaded. Link in README.", }, ],}
# --- Time helpers ---
def _now() -> datetime: return datetime.now().replace(microsecond=0)
def get_current_hour() -> float: """Returns elapsed hours since HACKATHON_START (0β24) as a float, e.g. 7.5.""" n = _now() if n < HACKATHON_START: return 0.0 if n >= HACKATHON_END: return 24.0 delta = n - HACKATHON_START h = delta.total_seconds() / 3600.0 return min(24.0, h)
def get_time_remaining() -> str: """e.g. '9h 23m remaining' or 'DEADLINE PASSED'.""" n = _now() if n >= HACKATHON_END: return "DEADLINE PASSED" sec = (HACKATHON_END - n).total_seconds() if sec <= 0: return "DEADLINE PASSED" h, r = divmod(int(sec), 3600) m, _ = divmod(r, 60) return f"{h}h {m:02d}m remaining"
def get_submission_time_remaining() -> str: """Time until the hard form submission cut (23.5h).""" n = _now() if n >= SUBMISSION_HARD_DEADLINE: if n >= HACKATHON_END: return "PAST DEADLINES" return "PAST SUBMISSION β final 30m" sec = (SUBMISSION_HARD_DEADLINE - n).total_seconds() h, r = divmod(int(sec), 3600) m, _ = divmod(r, 60) return f"{h}h {m:02d}m to submission (23.5h)"
# --- Project root (sqlsage-env) ---
def _project_root() -> str: return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
# --- Verify fns: return True / False, or None = NOT CHECKED (no crash) ---
def check_hf_space_live() -> Optional[bool]: url = os.environ.get("SQLSAGE_HF_RESET_URL", "").strip() if not url: return None try: import requests except ImportError: return None try: r = requests.get( url, timeout=float(os.environ.get("SQLSAGE_DASHBOARD_HTTP_TIMEOUT", "5")), ) return 200 <= r.status_code < 500 except Exception: return None
def check_wandb_nonzero_reward() -> Optional[bool]: try: from pathlib import Path
root = Path(_project_root()) wdir = root / "wandb" if not wdir.is_dir(): return None for run in sorted(wdir.glob("run-*"), reverse=True): summ = run / "files" / "wandb-summary.json" if not summ.is_file(): continue try: data = json.loads(summ.read_text(encoding="utf-8", errors="replace")) except (OSError, json.JSONDecodeError, ValueError): continue if not isinstance(data, dict): continue found_reward_key = False for k, v in data.items(): lk = k.lower() if "reward" in lk and isinstance(v, (int, float)): found_reward_key = True if v != 0: return True if found_reward_key: return False return None except Exception: return None
def check_plots_committed() -> Optional[bool]: try: root = _project_root() r = subprocess.run( ["git", "log", "-1", "--oneline", "--", "plots/"], capture_output=True, text=True, timeout=8, cwd=root, ) if r.returncode != 0: return None if not (r.stdout or "").strip(): return False return True except Exception: return None
def check_benchmark_results_exist() -> Optional[bool]: try: from pathlib import Path
p = Path(_project_root()) / "results" / "benchmark_results.json" if not p.is_file(): return False if p.stat().st_size < 4: return False data = json.loads(p.read_text(encoding="utf-8", errors="replace")) if not isinstance(data, (dict, list)) or (isinstance(data, dict) and not data): return False return True except Exception: return None
def check_readme_has_links() -> Optional[bool]: try: from pathlib import Path
p = Path(_project_root()) / "README.md" if not p.is_file(): return None t = p.read_text(encoding="utf-8", errors="replace") t_lower = t.lower() if "http" in t and ( "hf." in t_lower or "huggingface" in t_lower or "hf.space" in t_lower ): return True if "http" in t and "space" in t_lower: return True return False except Exception: return None
def _parse_verify_name(verify_field: str | None) -> str: if not verify_field: return "" s = str(verify_field).strip() if s.endswith("()"): s = s[:-2] return s
_VERIFY_DISPATCH: dict[str, Callable[[], Optional[bool]]] = { "check_hf_space_live": check_hf_space_live, "check_wandb_nonzero_reward": check_wandb_nonzero_reward, "check_plots_committed": check_plots_committed, "check_benchmark_results_exist": check_benchmark_results_exist, "check_readme_has_links": check_readme_has_links,}
def run_verify_for_milestone( milestone: dict[str, Any], cache: dict[str, Optional[bool]]) -> Optional[bool]: name = _parse_verify_name(milestone.get("verify_fn")) if not name: return None if name in cache: return cache[name] fn = _VERIFY_DISPATCH.get(name) if not fn: cache[name] = None return None try: out = fn() except Exception: out = None cache[name] = out return out
def get_milestone_status( milestone: dict[str, Any], current_hour: float, cache: dict[str, Optional[bool]] | None = None,) -> str: """ Returns: "DONE" | "IN_PROGRESS" | "UPCOMING" | "MISSED" MISSED = current hour > hour + 0.5 and verify returns False IN_PROGRESS = within 1h before the gate, grace window, or late / NOT CHECKED """ if cache is None: cache = {} h = float(milestone["hour"]) vr = run_verify_for_milestone(milestone, cache)
if vr is True: return "DONE" if current_hour > h + 0.5 and vr is False: return "MISSED" in_before = h - 1.0 <= current_hour < h in_grace = h <= current_hour <= h + 0.5 if in_before or (in_grace and vr is not True): return "IN_PROGRESS" if current_hour < h - 1.0: return "UPCOMING" if current_hour < h: return "IN_PROGRESS" if current_hour > h + 0.5: return "IN_PROGRESS" return "UPCOMING"
# --- Task engine ---
def _parse_hour_range(s: str) -> tuple[float, float]: m = re.match(r"^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)$", s.strip()) if not m: return (0.0, 0.0) return (float(m.group(1)), float(m.group(2)))
def get_current_task(person: int, current_hour: float) -> dict[str, Any]: """ Return the task dict for this person at current_hour. Intervals are [lo, hi) in hackathon hours; the last block includes up to 24.0. """ tasks = PERSON_TASKS.get(person, []) for i, t in enumerate(tasks): lo, hi = _parse_hour_range(str(t.get("hours", "0-0"))) is_last = i == len(tasks) - 1 if is_last: if lo <= current_hour <= 24.0: return t elif lo <= current_hour < hi: return t return tasks[-1] if tasks else {}
def get_next_task( person: int, current_hour: float, current: dict[str, Any] | None = None) -> Optional[dict[str, Any]]: cur = current if current is not None else get_current_task(person, current_hour) tasks = PERSON_TASKS.get(person, []) for i, t in enumerate(tasks): if t is cur and i + 1 < len(tasks): return tasks[i + 1] return None
# --- Dashboard (Rich) ---
def _milestone_label(gate: str) -> str: short = { "Environment deployed to HF Spaces": "Environment on HF Spaces", "First training run showing non-zero reward": "Non-zero reward", "Full training run complete (300+ episodes). Plots committed.": "Full training + plots", "Before/after comparison documented with real numbers": "Before/after numbers", "README done. All links. Form ready.": "README + form ready", "Google Form submitted": "SUBMITTED", } return short.get(gate, gate[:48] + ("β¦" if len(gate) > 48 else ""))
def _format_status_pretty(code: str) -> str: m = { "DONE": "β DONE", "IN_PROGRESS": "β‘ IN PROGRESS", "UPCOMING": "β UPCOMING", "MISSED": "β MISSED", } return m.get(code, code)
def _style_for_status_text(code: str) -> str: if code == "DONE": return "green" if code == "IN_PROGRESS": return "yellow" if code == "MISSED": return "bold red" return "dim"
def _milestone_away(hour: float, ch: float, st: str) -> str: if st != "IN_PROGRESS" or ch >= hour: return "" d = max(0.0, hour - ch) return f" β{d:.1f}h"
def _next_milestone_hours(ch: float) -> float | None: """Smallest m['hour'] with m['hour'] > ch, else None.""" nxt: list[float] = [] for m in MILESTONES: mh = float(m["hour"]) if mh > ch + 1e-6: nxt.append(mh) if not nxt: return None return min(nxt) - ch
def _any_milestone_missed(ch: float, cache: dict[str, Optional[bool]]) -> bool: for m in MILESTONES: if get_milestone_status(m, ch, cache) == "MISSED": return True return False
def _bar_style(ch: float, cache: dict[str, Optional[bool]]) -> tuple[str, str]: """ GREEN: on track (next > 2h) YELLOW: next < 2h RED: any MISSED or < 0.5h to next """ if _any_milestone_missed(ch, cache): return ( "bold red", "CRISIS: milestone missed (or run checks). See MISSED row(s).", ) d = _next_milestone_hours(ch) if d is None: return ( "green", "Hackathon window: no more gates ahead. Finish & submit on time.", ) if d < 0.5: return ("bold red", f"CRISIS: next gate in {d*60:.0f} min.") if d < 2.0: return ( "yellow", f"Watch out: next gate in {d:.1f}h. Prioritize that milestone.", ) return ("green", f"On track. Next gate in {d:.1f}h.")
def _build_task_panel( person: int, ch: float, show_role_header: bool = True) -> "Columns": from rich.columns import Columns from rich.panel import Panel from rich.text import Text
cur = get_current_task(person, ch) nxt = get_next_task(person, ch, cur) cur_block = str(cur.get("hours", "β")) if cur else "β" task_lines: list[Text] = [] if show_role_header: task_lines.append( Text( f"Person {person} β {PERSON_ROLES.get(person, 'Member')}\n", style="bold cyan", ) ) task_lines.append( Text(f"NOW: Hour {cur_block}\n", style="bold") + Text(f"{(cur or {}).get('task', 'β')}\n\n", style="default") ) task_lines.append(Text("COMMANDS TO RUN:\n", style="bold")) for c in (cur or {}).get("commands", []): task_lines.append(Text(f" $ {c}\n", style="white")) task_lines.append( Text(f"\nDONE WHEN: {(cur or {}).get('done_when', 'β')}", style="green") ) now_panel = Panel( Text.assemble(*task_lines), title="[bold]Current Task[/]", border_style="blue", ) nxt_text = ( f"Hour {nxt.get('hours', 'β')}\n{nxt.get('task', 'β')}" if nxt else "β (final block)" ) next_panel = Panel( nxt_text, title="[bold]Next[/]", border_style="magenta", ) return Columns([now_panel, next_panel], equal=True, expand=True)
def _build_milestone_table( ch: float, cache: dict[str, Optional[bool]]) -> "Table": from rich import box from rich.table import Table from rich.text import Text
t = Table( title="Team milestones", box=box.ROUNDED, show_header=True, header_style="bold", ) t.add_column("When", style="dim", width=6) t.add_column("Milestone", width=28, no_wrap=True) t.add_column("Owner", width=8, no_wrap=True) t.add_column("Status", no_wrap=True, width=28) t.add_column("Verify", style="dim", width=14, no_wrap=True)
for m in MILESTONES: st = get_milestone_status(m, ch, cache) vr = run_verify_for_milestone(m, cache) vlabel = "NOT CHECKED" if vr is None else ( "pass" if vr else "no" ) away = _milestone_away(float(m["hour"]), ch, st) row = [ f"H{int(m['hour']):d}", _milestone_label(m["gate"]), m.get("owner", "β"), Text( f"{_format_status_pretty(st)}{away}", style=_style_for_status_text(st) ), vlabel, ] t.add_row(*row) return t
def _top_bar_ch(person: int | None) -> "Text": from rich.text import Text
ch = get_current_hour() rem = get_time_remaining() sub = get_submission_time_remaining() label = "Team (all 3)" if person is None else f"Person {person}: {PERSON_ROLES.get(person, '')}" line1 = f" SQLSage Dashboard β {label} " line2 = f" Hour {ch:.1f} / 24 | {rem} | {sub} " return Text.assemble( (line1, "bold white on dark_blue"), "\n", (line2, "default"), )
def _footer_bar(ch: float, cache: dict[str, Optional[bool]]) -> "Text": from rich.text import Text
style, msg = _bar_style(ch, cache) return Text(f" {msg} ", style=style)
def render_person_dashboard(person: int) -> "Group": from rich.console import Group
ch = get_current_hour() cache: dict[str, Optional[bool]] = {} return Group( _top_bar_ch(person), _build_task_panel(person, ch), _build_milestone_table(ch, cache), _footer_bar(ch, cache), )
def render_team_dashboard() -> "Group": from rich import box from rich.columns import Columns from rich.console import Group from rich.panel import Panel from rich.text import Text
ch = get_current_hour() cache: dict[str, Optional[bool]] = {} per_cols: list[Panel] = [] for p in (1, 2, 3): cur = get_current_task(p, ch) nxt = get_next_task(p, ch, cur) lines: list[Text] = [ Text( f"{PERSON_ROLES.get(p, '')}\n", style="bold cyan", ), Text( f"NOW ({cur.get('hours', 'β')}): {cur.get('task', '')}\n\n", style="default" ), ] for c in (cur.get("commands") or [])[:5]: lines.append(Text(f" {c}\n", style="dim white")) if nxt: lines.append( Text( f"\nNext ({nxt.get('hours', '')}): {nxt.get('task', '')}\n", style="magenta", ) ) per_cols.append( Panel( Text.assemble(*lines) if lines else Text("β"), title=f"Person {p}", box=box.ROUNDED, ) ) return Group( _top_bar_ch(None), Columns(per_cols, equal=True, expand=True, padding=1), _build_milestone_table(ch, cache), _footer_bar(ch, cache), )
def _console() -> "Console": from rich.console import Console
try: w = os.get_terminal_size().columns except OSError: w = 120 return Console(width=max(100, w))
def run_live( person: int | None, refresh_seconds: int = 60, team: bool = False) -> None: from rich.live import Live
console = _console() with Live( render_team_dashboard() if team else render_person_dashboard(person or 1), console=console, refresh_per_second=4, screen=True, ) as live: try: while True: time.sleep(refresh_seconds) if team: live.update(render_team_dashboard()) else: live.update(render_person_dashboard(int(person or 1))) except KeyboardInterrupt: pass
def main() -> None: parser = argparse.ArgumentParser( description="SQLSage hackathon live terminal dashboard (Rich).", ) parser.add_argument( "--person", type=int, choices=(1, 2, 3), help="Teammate: 1=Environment, 2=Reward, 3=Training", ) parser.add_argument( "--team", action="store_true", help="All three roles side by side (compact)", ) parser.add_argument( "--live", action="store_true", help="Auto-refresh (Ctrl+C to exit)", ) parser.add_argument( "--refresh", type=int, default=60, metavar="S", help="Seconds between refreshes in --live mode (default: 60)", ) args = parser.parse_args() if args.team and args.person is not None: parser.error("Use either --team or --person, not both.") if not args.team and args.person is None: parser.error("Specify --person 1, 2, or 3, or use --team.")
console = _console() if args.live: run_live( person=args.person, refresh_seconds=max(1, args.refresh), team=args.team ) elif args.team: console.print(render_team_dashboard()) else: console.print(render_person_dashboard(int(args.person)))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439"""Generate one-page printable cheat sheets (Markdown + HTML) for each SQLSage role.
cd sqlsage-env && python -m sqlsage.generate_cheatsheets
Output: ./cheatsheets/person{1,2,3}_*.{md,html} β no third-party dependencies."""
from __future__ import annotations
import htmlimport refrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentOUT = ROOT / "cheatsheets"
# --- Markdown bodies (Section 13 style + commands from project phases) ---
PERSON1_MD = r"""# SQLSage β Person 1: Environment Engineer**Deadline: Hour 8 = HF Space live**
## Setup Commands| Command | What it does ||---------|-------------|| `openenv init sqlsage-env` | Creates the scaffold (run from parent of the repo dir) || `docker compose up -d` | Start Postgres (see `docker-compose.yml`; default **port 5433** in README) || `uvicorn sqlsage.app:app --reload --port 8000` | Runs environment locally (set `POSTGRES_HOST` / `POSTGRES_PORT`) || `openenv push your-username/sqlsage-env` | Deploys to HF Spaces || `docker run --name sqlsage-pg -e POSTGRES_PASSWORD=sqlsage -e POSTGRES_DB=sqlsage -p 5432:5432 -d postgres:16` | Single-container Postgres 16 (alt. to compose) || `curl http://localhost:8000/reset` | Tests reset endpoint (local) || `curl -sS "$SQLSAGE_ENV_URL/reset"` | Tests deployed Space (set URL from `.env`) || `psql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" -c 'SELECT version();'` | Verify DB (project default port **5433**) || `openenv validate` | OpenEnv project validation || `python -m sqlsage.run p1-serve` | **Alias** β uvicorn (from `sqlsage.run`) || `python -m sqlsage.run p1-test` | **Alias** β curl local `/reset` \| `json.tool` || `python -m sqlsage.run p1-push` / `p1-deploy` | **Alias** β push + optional HF curl |
## TPC-H Data Load| Command | What it does ||---------|-------------|| `git clone https://github.com/electrum/tpch-dbgen.git && cd tpch-dbgen && make` | Clone TPC-H tools || `./dbgen -s 1` | Generate SF=1 data (~1GB, ~2 min) || `./dbgen -s 0.1` | Generate SF=0.1 (fast, for training) || `psql -U postgres -d sqlsage -f dss.ddl` | Create schema (paths per your load process) || TPC-H bootstrap in Docker / HF image | `sql/bootstrap_tpch_schema.sql` auto-runs in Space; load data separately for real rewards |
## Drop Indexes (Creates Optimization Headroom)```bashpsql "host=127.0.0.1 port=5433 user=postgres dbname=sqlsage password=sqlsage" \ -f sql/scripts/drop_curriculum_indexes.sqlpsql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_orders_status;"psql -U postgres -d sqlsage -c "DROP INDEX IF EXISTS idx_lineitem_shipdate;"```
## Stress & Levels (phases: curriculum / env hardening)| Command | What it does ||---------|-------------|| `POSTGRES_HOST=127.0.0.1 POSTGRES_PORT=5433 python scripts/stress_env.py --episodes 50 --levels 2 --identity-step` | Stress `reset` / optional identity `step` (no GRPO) || `SQLSageEnv(tasks=tasks_for_levels(2))` | Level 2 only (see `sqlsage.tasks`) || `GET /health` | Health check (OpenEnv HTTP) || `GET /state`, `GET /schema`, `GET /metadata` | Session / schema metadata |
## Troubleshooting| Symptom | Fix ||---------|-----|| `curl /reset` returns 500 | `docker ps` / `docker compose ps` β DB + API up; check logs || HF Space build failing | `Dockerfile` + entrypoint: Postgres as service, `uvicorn` on `$PORT` (7860 on HF) || TPC-H load too long | Use SF=0.1 for dev; SF=1 for final demo; raise `SQLSAGE_TIMEOUT_MS` if needed || Intermittent 500 under load | OpenEnv uses a **lock** for reset/step; avoid parallel `step` to same process |
## Hour Gates- Hour 1: psql connects β- Hour 4: `curl /reset` returns JSON β- Hour 6: `step()` returns `{reward, done, state}` β- Hour 8: **HF Space live** β **SHARE URL WITH TEAM** (`SQLSAGE_ENV_URL` in Colab) β"""
PERSON2_MD = r"""# SQLSage β Person 2: Reward & Verifier Engineer**Your job: reward pipeline works, no reward hacking, plots committed by Hour 16**
## Core Commands| Command | What it does ||---------|-------------|| `pytest tests/ -v` | All unit tests || `pytest tests/test_reward.py -v` | Reward tests only || `pytest tests/test_explain_parser.py -v` | Parser tests only || `pytest tests/test_anti_cheat.py -v` | Anti-cheat tests only || `wandb login` | Authenticate W&B || `python monitor_training.py` | Live reward diagnostics (when configured) || `python plots/generate_plots.py` | **Actual path** β generate PNGs in `plots/` || `python -m sqlsage.run p2-reward` | **Alias** β quick `compute_reward` demo + breakdown || `python -m sqlsage.run p2-plots` | **Alias** β `plots/generate_plots.py` || `python -m sqlsage.run p2-anticheat` | **Alias** β `fix_training.py --issue reward_hacking` || `python -m sqlsage.status_checker --json` | Milestone + reward/plots/git checks (JSON) |
## Quick Reward Test`compute_reward` returns **(normalized β [-1,1], breakdown dict)** β use both:
```pythonfrom sqlsage.reward import compute_reward, format_reward_breakdownnew_plan = { "seq_scans": 0, "nested_loops": 0, "hash_joins": 1, "total_cost": 1000, "rows": 1e5, "node_type": "x",}old_plan = { "seq_scans": 2, "nested_loops": 1, "hash_joins": 0, "total_cost": 50000, "rows": 1e6, "node_type": "y",}n, b = compute_reward(8420.0, 310.0, new_plan, old_plan, step_number=0)print("normalized:", n)print(format_reward_breakdown(b))# Raw sum can be large; see breakdown["raw"] and breakdown["normalized"]```
## Quick EXPLAIN Test```bashpsql -h 127.0.0.1 -p 5433 -U postgres -d sqlsage -c \"EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders WHERE orderstatus='F' LIMIT 100;"```
## Anti-Cheat Attack Vectors to Test Manually1. `LIMIT 0` β strong negative / guard2. `WHERE 1=0` β strong negative / guard3. Remove `WHERE` clause (wrong result) β `result_changed` / penalty4. `CREATE INDEX` / DDL β should be rejected / exception5. Unchanged query β `noop_penalty` (escalates by step)
## Reward Component Reference (see `sqlsage/reward.py`)| Component | Rule (simplified) ||-----------|------------------|| Speedup | Up to `MAX_SPEEDUP_REWARD` Γ speedup ratio + `BIG_WIN` / `EXCEPTIONAL` bonuses at high ratio || Plan | `+SEQ_SCAN_BONUS` per seq scan removed, `+NESTED_LOOP_BONUS` per nested loop removed || Rows / cost | `ROWS_SIGNAL_WEIGHT` Γ row reduction; `COST_SIGNAL_WEIGHT` Γ cost reduction || No-op | `NOOP_PENALTIES[step]` if plan+latency effectively unchanged || Slowdown | `-SLOWDOWN_WEIGHT` Γ slowdown ratio || Normalize | `raw / NORMALIZATION_DIVISOR` β **[-1, 1]** |
## If Reward Hacking Detected```bashpython fix_training.py --issue reward_hacking```
## Plots + Evidence (phases: Phase 8, rollout comparison)| Command | What it does ||---------|-------------|| `export WANDB_ENTITY=...; export WANDB_PROJECT=sqlsage-grpo` | Match training project (see `docs/PHASE8_CLOSEOUT_CHECKLIST.md`) || `SQLSAGE_PLOTS_DEBUG=1 python plots/generate_plots.py` | Debug missing W&B data for plots || `python scripts/compare_rollouts.py --baseline results/baseline.jsonl --trained results/trained.jsonl` | Table when both JSONL exist |"""
PERSON3_MD = r"""# SQLSage β Person 3: Training Lead**Critical: Non-zero reward by Hour 12. 300+ episodes by Hour 18.**
## Colab Setup Sequence1. Runtime β Change runtime type β **A100** GPU2. `!pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' -q`3. `!pip install trl openenv wandb psycopg2-binary -q` β add `torch` as needed4. `import torch; print(torch.cuda.get_device_name(0))` β must be A100 for Colab template5. `pip install -e '.[training]'` (local) per README for `scripts/rollout_wandb.py`
## Env URL for rollouts| Variable | What it does ||----------|---------------|| `SQLSAGE_ENV_URL` | Person 1 Space or local `http://127.0.0.1:8000` (see `README` / `.env.example`) || `WANDB_ENTITY`, `WANDB_PROJECT` | W&B org + project (e.g. `sqlsage-grpo`) |
## One-liners (phases: rollout, benchmark, closeout)| Command | What it does ||---------|-------------|| `python scripts/rollout_wandb.py --episodes 5` | Quick smoke (see README) || `python run_benchmark.py` | TPC-H style benchmark; writes `results/benchmark_results.json` || `python -m sqlsage.run p3-benchmark` | **Alias** β `run_benchmark.py` || `python -m sqlsage.run p3-gpu` | **Alias** β CUDA check (`torch`) || `python -m sqlsage.run p3-verify` | Quick 5 checks (URL, W&B, plots, benchmark file, README links) || `python -m sqlsage.status_checker --json` | Full hackathon gate JSON || `docs/PERSON3_PHASE8_MANUAL.md` | **Β§7β8 + Β§9** β Colab, Hub, demo video, submission || `docs/PHASE8_CLOSEOUT_CHECKLIST.md` | All-roles Phase 8 closeout || `notebooks/sqlsage_grpo_colab.ipynb` | GRPO training skeleton |
## Model Save β CRITICAL**CORRECT**```pythonmodel.save_pretrained_merged( "sqlsage-trained", tokenizer, save_method="merged_16bit")```
**WRONG β can corrupt 4-bit quality**```pythonmodel.merge_and_unload() # DO NOT USE on 4-bit as sole export path```
## Common Fixes| Symptom | Fix ||---------|-----|| CUDA OOM | `batch_size=2`, `max_completion_length=256`, `grad_accum=8` || Invalid JSON from model | Few-shot JSON example in prompt (see `fix_training` / notebook) || Reward flat after ~50 ep | `python fix_training.py --issue flat_reward` || `result_changed` penalty | `python fix_training.py --issue result_changed` || Episodes very slow | Smaller TPC-H SF (0.1), or lighter tasks || Curriculum stuck | `python fix_training.py --issue curriculum_stuck` || Syntax errors in actions | `python fix_training.py --issue syntax_error` |
## Reward is working when- `reward/mean` trending up in W&B- `plan/seq_scans_removed` (or similar) > 0 when appropriate- `penalty/result_changed` near **zero** when results match- Episode length / latency moving in the right direction for your run- Benchmark: example target **Q5** latency under your documented threshold (adjust per SF)
## wandb metrics to watch`reward/mean`, speedup-related scalars, `penalty/result_changed`, `penalty/syntax_error`, plan/scan metrics, `episode_length` β names depend on your logging callback (see `monitor_training.py` / notebook)."""
def _is_gfm_table_separator(cells: list[str]) -> bool: if not cells: return False for c in cells: t = c.strip() t = t.replace(" ", "").lstrip(":").rstrip(":") if not t or not all(ch == "-" for ch in t): return False return True
def _html_wrap(fragment: str, title: str) -> str: css = """@page { size: A4; margin: 10mm; }@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }}* { box-sizing: border-box; }body { background: #fff; color: #000; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 8.5pt; line-height: 1.22; max-width: 195mm; margin: 0 auto; padding: 4mm 5mm 8mm 5mm;}h1 { font-size: 12pt; margin: 0.15em 0; font-weight: 700; }h2 { font-size: 9.5pt; margin: 0.5em 0 0.15em; border-bottom: 1px solid #333; }h3 { font-size: 8.7pt; margin: 0.35em 0 0.1em; }p { margin: 0.2em 0; }ul, ol { margin: 0.15em 0; padding-left: 1.2em; }ul { list-style: disc; }table.cheat { width: 100%; border-collapse: collapse; margin: 0.25em 0; font-size: 7.8pt; }table.cheat th { background: #1a365d; color: #fff; text-align: left; padding: 2px 4px; font-weight: 600; font-size: 7.5pt;}table.cheat td { border: 1px solid #999; padding: 2px 3px; vertical-align: top; }pre.cmd { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.3pt; background: #f4f4f4; border: 1px solid #ccc; padding: 3px 4px; margin: 0.25em 0; white-space: pre-wrap; word-break: break-word;}code.ic { font-family: ui-monospace, "Cascadia Code", "Consolas", monospace; font-size: 7.5pt; background: #f0f0f0; padding: 0 2px;}br { line-height: 0.2em; }""".strip() return f"""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>{html.escape(title)}</title><style>{css}</style></head><body>{fragment}</body></html>"""
def _md_to_html_v2(src: str, title: str) -> str: """Line-oriented Markdown β HTML (tables, code fences, headers, lists, paragraphs).""" lines = src.splitlines() out: list[str] = [] i = 0 in_fence = False code_lines: list[str] = [] in_ol = False in_ul = False
def close_lists() -> None: nonlocal in_ol, in_ul if in_ul: out.append("</ul>") in_ul = False if in_ol: out.append("</ol>") in_ol = False
while i < len(lines): line = lines[i] st = line.strip() if st.startswith("```"): if in_fence: body = "\n".join(code_lines) out.append( "<pre class=\"cmd\">" + html.escape(body) + "</pre>" ) code_lines = [] in_fence = False else: close_lists() in_fence = True i += 1 continue if in_fence: code_lines.append(line) i += 1 continue
if st.startswith("|") and st.count("|") >= 2: close_lists() tbl: list[list[str]] = [] j = i while j < len(lines) and lines[j].strip().startswith("|"): tbl.append( [c.strip() for c in lines[j].strip().strip("|").split("|")] ) j += 1 if len(tbl) >= 2 and _is_gfm_table_separator(tbl[1]): head, body = tbl[0], tbl[2:] else: head = tbl[0] if tbl else [] body = tbl[1:]
out.append('<table class="cheat">') out.append( "<thead><tr>" + "".join( f"<th>{_inline_on(html.escape(c))}</th>" for c in head ) + "</tr></thead><tbody>" ) for row in body: if not row or (len(row) == 1 and not row[0].strip()): continue out.append( "<tr>" + "".join( f"<td>{_inline_on(html.escape(c))}</td>" for c in row ) + "</tr>" ) out.append("</tbody></table>") i = j continue
if st.startswith("### "): close_lists() out.append(f"<h3>{_inline_on(html.escape(st[4:]))}</h3>") elif st.startswith("## "): close_lists() out.append(f"<h2>{_inline_on(html.escape(st[3:]))}</h2>") elif st.startswith("# "): close_lists() out.append(f"<h1>{_inline_on(html.escape(st[2:]))}</h1>") elif st.startswith(("- ", "* ")): if not in_ul: close_lists() out.append("<ul>") in_ul = True out.append(f"<li>{_inline_on(html.escape(st[2:]))}</li>") elif re.match(r"^\d+\.\s", st): if not in_ol: close_lists() out.append("<ol>") in_ol = True item = re.sub(r"^\d+\.\s+", "", st) out.append(f"<li>{_inline_on(html.escape(item))}</li>") elif st == "": # Blank line: keep <ol>/<ul> open (numbered Colab list spans blanks) pass else: close_lists() if st: out.append(f"<p>{_inline_on(html.escape(line))}</p>")
i += 1
close_lists() return _html_wrap("\n".join(out), title)
def _inline_on(escaped: str) -> str: """`escaped` is HTML-escaped; add ** and ` handling.""" t = re.sub( r"\*\*([^*]+)\*\*", lambda m: f"<strong>{m.group(1)}</strong>", escaped, ) t = re.sub( r"`([^`]+)`", lambda m: f'<code class="ic">{m.group(1)}</code>', t, ) return t
def _write_file(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8")
def main() -> None: sheets = [ ( "person1_env_engineer", "SQLSage β Person 1: Environment Engineer", PERSON1_MD, ), ( "person2_reward_engineer", "SQLSage β Person 2: Reward & Verifier Engineer", PERSON2_MD, ), ( "person3_training_lead", "SQLSage β Person 3: Training Lead", PERSON3_MD, ), ] for stem, t, md in sheets: _write_file(OUT / f"{stem}.md", md) h = _md_to_html_v2(md, t) _write_file(OUT / f"{stem}.html", h) print("Generated 6 files in ./cheatsheets/")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625"""SQLSage command alias dispatcher β one short command per common task.
cd sqlsage-env python -m sqlsage.run p1-serve python -m sqlsage.run dashboard 2"""
from __future__ import annotations
import jsonimport osimport reimport shleximport subprocessimport sysfrom pathlib import Pathfrom typing import Any, Callable
# sqlsage-env/ROOT = Path(__file__).resolve().parent.parentENV_PATH = ROOT / ".env"DOTENV_OK = True
# --- .env -----------------------------------------------------------------
_DOTENV = False
def _load_dotenv() -> None: global _DOTENV if _DOTENV: return if DOTENV_OK: try: from dotenv import load_dotenv
load_dotenv(ENV_PATH) load_dotenv(ROOT / ".env.local", override=True) except ImportError: pass _DOTENV = True
def _set_env_key(key: str, value: str) -> None: os.environ[key] = value if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key): return if not ENV_PATH.is_file(): ENV_PATH.parent.mkdir(parents=True, exist_ok=True) ENV_PATH.write_text(f"{key}={value}\n", encoding="utf-8") return text = ENV_PATH.read_text(encoding="utf-8", errors="replace") lines: list[str] = [] pat = re.compile(rf"^{re.escape(key)}=") replaced = False for line in text.splitlines(keepends=True): if line.strip() and not line.lstrip().startswith("#") and pat.match(line): lines.append(f"{key}={value}\n") replaced = True else: lines.append(line) if not replaced: if lines and (not lines[-1].endswith("\n")): lines[-1] = lines[-1] + "\n" if lines and lines[-1].strip() != "": lines.append("\n") lines.append(f"{key}={value}\n") with ENV_PATH.open("w", encoding="utf-8") as f: f.write("".join(lines).rstrip() + "\n")
def _prompt_and_save( key: str, message: str, default: str | None = None) -> str: _load_dotenv() v = (os.environ.get(key) or "").strip() if v: return v hint = f" [{default}]" if default else "" s = input(f"{message}{hint}: ").strip() or (default or "") if s: _set_env_key(key, s) return s
def _get_hf_space_url() -> str: _load_dotenv() for k in ("SQLSAGE_HF_SPACE_URL", "SQLSAGE_ENV_URL"): u = (os.environ.get(k) or "").strip() if u: return u.rstrip("/") s = _prompt_and_save( "SQLSAGE_HF_SPACE_URL", "Hugging Face Space base URL (https://...hf.space)", "" ) return s.rstrip("/")
def _get_hf_username() -> str: _load_dotenv() for k in ("HUGGINGFACE_HUB_USER", "HF_USERNAME", "SQLSAGE_HF_USERNAME"): u = (os.environ.get(k) or "").strip() if u: return u s = _prompt_and_save("HUGGINGFACE_HUB_USER", "Hugging Face username (for openenv push)", "") return s
# --- console / run --------------------------------------------------------
def _c() -> Any: from rich.console import Console
return Console(highlight=False)
def _announce(alias: str, command_desc: str) -> None: _c().print(f"[bold cyan]{alias}[/] β [yellow]{command_desc}[/]")
def _suggest_fix_training() -> None: _c().print( "[dim]If this looks like training/reward/RL: " "try [white]python -m sqlsage.run p2-anticheat[/] or [white]python fix_training.py --issue NAME[/][/]" )
def _run( label: str, cmd: list[str] | str, *, cwd: Path | None = None, shell: bool = False, env: dict[str, str] | None = None,) -> int: if isinstance(cmd, str): _announce(label, cmd) else: _announce(label, " ".join(shlex.quote(p) for p in cmd)) wdir = str(cwd or ROOT) e = {**os.environ, **(env or {})} if shell and isinstance(cmd, str): r = subprocess.run(cmd, shell=True, cwd=wdir, env=e, text=True) elif isinstance(cmd, list): r = subprocess.run(cmd, cwd=wdir, env=e, text=True) else: r = subprocess.run( shlex.split(cmd), cwd=wdir, env=e, text=True ) if r.returncode != 0: _c().print( f"[red]Exited {r.returncode}[/] β [white]{label}[/] failed", style="red" ) _suggest_fix_training() return r.returncode
# --- P1 -------------------------------------------------------------------
def cmd_p1_init() -> int: _load_dotenv() _announce("p1-init", f"openenv init sqlsage-env (cwd: {ROOT.parent})") return _run( "p1-init", ["openenv", "init", "sqlsage-env"], cwd=ROOT.parent, shell=False )
def cmd_p1_db() -> int: return _run( "p1-db", [ "docker", "run", "--name", "sqlsage-pg", "-e", "POSTGRES_PASSWORD=sqlsage", "-e", "POSTGRES_DB=sqlsage", "-p", "5432:5432", "-d", "postgres:16", ], )
def cmd_p1_serve() -> int: return _run("p1-serve", ["uvicorn", "sqlsage.app:app", "--reload", "--port", "8000"])
def cmd_p1_push() -> int: _announce( "p1-push", "openenv push <HUGGINGFACE_HUB_USER>/sqlsage-env (.env or prompt)", ) user = _get_hf_username() if not user: _c().print("[red]Set HUGGINGFACE_HUB_USER in .env or enter when prompted.[/]") return 1 return _run("p1-push", ["openenv", "push", f"{user}/sqlsage-env"])
def cmd_p1_test() -> int: cmd = f'curl -sS "http://localhost:8000/reset" | {sys.executable} -m json.tool' return _run("p1-test", cmd, shell=True)
def cmd_p1_deploy() -> int: r = cmd_p1_push() if r != 0: return r base = _get_hf_space_url() if not base: _c().print("[red]Set SQLSAGE_HF_SPACE_URL (or SQLSAGE_ENV_URL) in .env.[/]") return 1 b = base.rstrip("/") u = f"{b}/reset" if not b.endswith("reset") else b if not u.startswith("http"): u = "https://" + u.lstrip("/") cmd = f'curl -sS {shlex.quote(u)} | {shlex.quote(sys.executable)} -m json.tool' return _run("p1-deploy (then curl HF /reset + json.tool)", cmd, shell=True)
# --- P2 -------------------------------------------------------------------
def _pg_dsn() -> dict[str, Any]: _load_dotenv() return { "host": os.environ.get("POSTGRES_HOST", "127.0.0.1"), "port": int(os.environ.get("POSTGRES_PORT", "5433")), "user": os.environ.get("POSTGRES_USER", "postgres"), "password": os.environ.get("POSTGRES_PASSWORD", "sqlsage"), "dbname": os.environ.get("POSTGRES_DB", "sqlsage"), }
def cmd_p2_explain() -> int: _announce("p2-explain", "psycopg2: EXPLAIN (ANALYZE, FORMAT JSON) for your query") sql = input("SQL to EXPLAIN: ").strip().rstrip(";") if not sql: _c().print("[red]Empty query.[/]") return 1 try: import psycopg2
c = _pg_dsn() conn = psycopg2.connect( host=c["host"], port=c["port"], user=c["user"], password=c["password"], dbname=c["dbname"], ) ex = f"EXPLAIN (ANALYZE, FORMAT JSON) {sql}" cur = conn.cursor() cur.execute(ex) row = cur.fetchone() conn.close() if not row or not row[0]: _c().print("[red]No result[/]") return 1 plan = row[0] if isinstance(plan, str): data = json.loads(plan) else: data = plan _c().print( json.dumps(data, indent=2), style="white", ) except Exception as e: # noqa: BLE001 _c().print(f"[red]{e}[/]") _suggest_fix_training() return 1 return 0
def cmd_p2_test() -> int: return _run("p2-test", [sys.executable, "-m", "pytest", "tests/", "-v"])
def cmd_p2_reward() -> int: _announce("p2-reward", "compute_reward() demo with sample before/after plans") try: from sqlsage.reward import compute_reward, format_reward_breakdown except Exception as e: # noqa: BLE001 _c().print(f"[red]{e}[/]") return 1 old_p = { "seq_scans": 2, "nested_loops": 1, "hash_joins": 0, "total_cost": 50000, "rows": 1e6, "node_type": "foo", } new_p = { "seq_scans": 0, "nested_loops": 0, "hash_joins": 1, "total_cost": 1000, "rows": 5e4, "node_type": "bar", } total, b = compute_reward(8420.0, 310.0, new_p, old_p, step_number=0) _c().print( f"[white]Total normalized reward:[/] [white]{total:.4f}[/]\n{format_reward_breakdown(b)}" ) return 0
def cmd_p2_anticheat() -> int: return _run("p2-anticheat", [sys.executable, "fix_training.py", "--issue", "reward_hacking"])
def cmd_p2_plots() -> int: return _run("p2-plots", [sys.executable, "plots/generate_plots.py"])
def cmd_p2_wandb() -> int: return _run("p2-wandb", ["wandb", "login"])
# --- P3 -------------------------------------------------------------------
def cmd_p3_gpu() -> int: _announce("p3-gpu", "torch: device name + total VRAM (if available)") try: import torch except ImportError as e: _c().print(f"[red]install torch: {e}[/]") return 1 if not torch.cuda.is_available(): _c().print( "[white]CUDA not available in this process (expect GPU Colab for training).[/]" ) return 0 _c().print( f"[white]{torch.cuda.get_device_name(0)}[/]", style="white", ) try: mem = int(torch.cuda.get_device_properties(0).total_memory) _c().print( f"[white]device memory β {mem / 1_073_741_824.0:.2f} GiB[/]", style="white", ) except Exception: # noqa: BLE001 pass return 0
def cmd_p3_benchmark() -> int: return _run("p3-benchmark", [sys.executable, "run_benchmark.py"])
def cmd_p3_save() -> int: _announce("p3-save", "Unsloth/TRL merged export (read carefully)") _c().print( "[white]Use Unslothβs merged 16-bit save in Colab (per notebook), e.g.:\n" " [yellow]model.save_pretrained_merged(" "'sqlsage-trained', tokenizer, save_method='merged_16bit')[/]\n" "Do not use raw [yellow]model.save_pretrained(...)[/] alone if your workflow expects a merged model for vLLM/HF.[/]\n" "Also push with [yellow]huggingface-cli upload ...[/] or the Hub notebook cell after [yellow]huggingface-cli login[/]." ) return 0
def cmd_p3_verify() -> int: _announce("p3-verify", "training pipeline checks 1β5 (env URL, DB path, W&B, plots, benchmark JSON)") _load_dotenv() ok1 = ok2 = ok3 = ok4 = ok5 = False c = _c() u = (os.environ.get("SQLSAGE_HF_SPACE_URL") or os.environ.get("SQLSAGE_ENV_URL") or "").strip() if u: try: import requests
b = u.rstrip("/") test = f"{b}/reset" if not b.lower().rstrip("/").endswith("reset") else b if not test.startswith("http"): test = "https://" + test.lstrip("/") r = requests.get(test, timeout=5) ok1 = 200 <= r.status_code < 500 except Exception: ok1 = False if not u: c.print( "[dim][1] No SQLSAGE_HF_SPACE_URL / SQLSAGE_ENV_URL β set for remote /reset check[/]" ) if not u: t1 = "SKIP" elif ok1: t1 = "PASS" else: t1 = "FAIL" c.print( f"[1] [white]{t1:4} HF /reset check (if URL in .env) β 200β499 = ok[/]" ) p = ROOT / "results" / "benchmark_results.json" ok2 = p.is_file() and p.stat().st_size > 4 c.print( f"[2] [white]{'PASS' if ok2 else 'FAIL':4} benchmark_results.json present[/]" ) ok3 = bool((os.environ.get("WANDB_API_KEY") or "").strip()) c.print( f"[3] [white]{'PASS' if ok3 else 'FAIL':4} WANDB_API_KEY in env[/] " f"(or run [yellow]python -m sqlsage.run p2-wandb[/])" ) plots = list((ROOT / "plots").glob("*.png")) if (ROOT / "plots").is_dir() else [] ok4 = len(plots) >= 3 c.print( f"[4] [white]{'PASS' if ok4 else 'FAIL':4} β₯3 plot PNGs in plots/[/] " f"([dim]{len(plots)} found[/])" ) readme = ROOT / "README.md" t = (readme.read_text(encoding="utf-8", errors="replace") if readme.is_file() else "").lower() ok5 = "hf.space" in t and "colab" in t and "wandb" in t and ( "youtube" in t or "huggingface.co/blog" in t ) c.print( f"[5] [white]{'PASS' if ok5 else 'FAIL':4} README: hf.space + colab + wandb + (youtube|blog)[/]" ) check1 = (not u) or ok1 if not (check1 and ok2 and ok3 and ok4 and ok5): c.print( "\n[dim]Full milestone JSON: [white]python -m sqlsage.status_checker --json[/][/]" ) return 0 if (check1 and ok2 and ok3 and ok4 and ok5) else 1
def cmd_p3_video() -> int: cands = [ ROOT / "docs" / "PERSON3_PHASE8_MANUAL.md", ROOT / "docs" / "PHASE8_CLOSEOUT_CHECKLIST.md", ] path = next((p for p in cands if p.is_file()), None) if not path: _c().print("[red]No docs found for demo rehearsal.[/]") return 1 rel = str(path) if str(ROOT) in str(path) and str(path).startswith(str(ROOT) + os.sep): rel = str(path).replace(str(ROOT) + os.sep, "", 1) _announce("p3-video", f"less {rel} (Section Β§7/Β§8 style demo checklist)") return _run("p3-video (less β q to quit)", f'less {shlex.quote(str(path))}', shell=True)
# --- shared ---------------------------------------------------------------
def cmd_status() -> int: return _run("status", [sys.executable, "-m", "sqlsage.status_checker"])
def cmd_dashboard(n: int) -> int: dash = ROOT / "dashboard.py" if not dash.is_file(): return _run( f"dashboard {n}", [sys.executable, "-m", "sqlsage.dashboard", "--person", str(n)] ) return _run(f"dashboard {n}", [sys.executable, str(dash), "--person", str(n)])
def cmd_crisis() -> None: _announce("crisis", "CRISIS PROTOCOL (from runbook)") text = """[bold cyan]Missed Hour 8 (HF Space not live):[/] 1. Check Docker: [yellow]docker ps | grep sqlsage-pg[/] 2. Check FastAPI logs: [yellow]docker logs sqlsage-pg[/] (if API is in another container, use that name) 3. Check HF Spaces [white]build logs in the UI[/] 4. If still failing after 30 min: [white]run environment locally and use ngrok as fallback[/]
[bold cyan]Missed Hour 12 (reward still zero):[/] 1. [yellow]python -m sqlsage.run p2-reward[/] β verify compute_reward returns > 0 for a fast rewrite 2. [yellow]python fix_training.py --issue flat_reward[/] 3. Print 5 raw model outputs β are they all the same? 4. Check prompt: does the model see the EXPLAIN plan? Print the full prompt.
[bold cyan]Missed Hour 18 (training not done):[/] 1. [white]Reduce to 100 episodes immediately[/] 2. [yellow]python plots/generate_plots.py[/] β generate plots from whatever episodes you have 3. [yellow]git add plots/ && git commit -m 'partial training plots'[/] 4. Document in README: "100 episodes shown β full run in progress"
[bold cyan]Missed Hour 21 (no benchmark numbers):[/] 1. [yellow]python run_benchmark.py[/] β runs in ~5 minutes 2. If model not saved: [white]use untrained baseline with an honest note[/] 3. [red]NEVER invent numbers.[/] Use real numbers from any run, even partial.""".strip() _c().print(text)
def cmd_submit() -> None: _announce("submit", "Β§9-style submission checklist (PHASE8 closeout)") lines = [ "[ ] Space URL works (open in browser, /reset returns JSON)", "[ ] Colab / notebook link opens and has GPU / deps instructions", "[ ] Public GitHub repo is up to date (latest plots, results/)", "[ ] W&B: entity/project and at least one run with reward history", "[ ] `results/benchmark_results.json` (or docβd numbers from run_benchmark.py)", "[ ] `plots/*.png` committed with real W&B data (Person 2)", "[ ] README: problem, env, reward, anti-cheat, training, baseline vs trained table, **links** (HF, Colab, video/blog, repo)", "[ ] Demo video (β€2 min) or blog URL in README (Β§7 PERSON3 doc)", "[ ] Google Form filled before deadline (all required links)", ] for line in lines: _c().print(f"[white]{line}[/]")
def cmd_help() -> None: from rich import box from rich.table import Table
t = Table( title="[bold]SQLSage [cyan]run.py[/] aliases[/]", box=box.ROUNDED, show_header=True, ) t.add_column("Alias", style="bold cyan", no_wrap=True) t.add_column("What it does", style="white") rows: list[tuple[str, str]] = [ ("p1-init", "openenv init sqlsage-env (parent directory)"), ("p1-db", "Start Postgres 16 in Docker (port 5432)"), ("p1-serve", "uvicorn sqlsage.app:app --reload :8000"), ("p1-push", "openenv push <user>/sqlsage-env (.env / prompt)"), ("p1-test", "curl /reset on localhost:8000 | json.tool"), ("p1-deploy", "p1-push, then test HF /reset with curl"), ("p2-explain", "Prompt for SQL β EXPLAIN (ANALYZE, FORMAT JSON) (pretty)"), ("p2-test", "pytest tests/ -v"), ("p2-reward", "Demo compute_reward() + per-component breakdown"), ("p2-anticheat", "fix_training.py --issue reward_hacking"), ("p2-plots", "plots/generate_plots.py"), ("p2-wandb", "wandb login"), ("p3-gpu", "torch: CUDA device name + memory (if any)"), ("p3-benchmark", "python run_benchmark.py"), ("p3-save", "Print correct merged save + upload guidance"), ("p3-verify", "5 quick environment/training/benchmark/README checks"), ("p3-video", "less docs (demo + submission rehearsal)"), ("status", "python -m sqlsage.status_checker (milestone JSON)"), ("dashboard 1|2|3", "python dashboard.py --person N (or -m sqlsage.dashboard)"), ("crisis", "CRISIS PROTOCOL for missed hours"), ("submit", "Submission checklist with checkboxes"), ("help", "This table"), ] for a, b in rows: t.add_row(a, b) _c().print(t)
# --- main -----------------------------------------------------------------
def main(argv: list[str] | None = None) -> int: argv = argv if argv is not None else sys.argv[1:] if not argv: cmd_help() return 0 a0 = argv[0] if a0 in ("-h", "--help", "help"): cmd_help() return 0 if a0 == "dashboard" and len(argv) < 2: _c().print( "[red]Usage: python -m sqlsage.run dashboard 1|2|3[/]" ) return 1 if a0 == "dashboard" and len(argv) >= 2: n = argv[1] if n not in ("1", "2", "3"): _c().print(f"[red]Person must be 1, 2, or 3, got {n!r}[/]") return 1 return cmd_dashboard(int(n)) m: dict[str, Callable[[], int | None] | None] = { "p1-init": cmd_p1_init, "p1-db": cmd_p1_db, "p1-serve": cmd_p1_serve, "p1-push": cmd_p1_push, "p1-test": cmd_p1_test, "p1-deploy": cmd_p1_deploy, "p2-explain": cmd_p2_explain, "p2-test": cmd_p2_test, "p2-reward": cmd_p2_reward, "p2-anticheat": cmd_p2_anticheat, "p2-plots": cmd_p2_plots, "p2-wandb": cmd_p2_wandb, "p3-gpu": cmd_p3_gpu, "p3-benchmark": cmd_p3_benchmark, "p3-save": cmd_p3_save, "p3-verify": cmd_p3_verify, "p3-video": cmd_p3_video, "status": cmd_status, "crisis": None, "submit": None, } if a0 not in m: _c().print( f"[red]Unknown alias {a0!r}. Use [white]python -m sqlsage.run help[/][/]" ) return 1 if a0 == "crisis": cmd_crisis() return 0 if a0 == "submit": cmd_submit() return 0 if a0 == "help": cmd_help() return 0 fn = m[a0] if fn is None: return 1 r = fn() return 0 if r is None else int(r)
if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: _c().print("\n[dim]Interrupted.[/]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573"""Automated hackathon milestone checks. Used by the dashboard; usable standalone.
cd sqlsage-env python -m sqlsage.status_checker
Set ``SQLSAGE_HF_SPACE_URL`` and/or ``SQLSAGE_WANDB_RUN_ID`` when not passing args."""
from __future__ import annotations
import jsonimport osimport reimport subprocessimport timefrom datetime import datetimefrom typing import Any
# Same hackathon window as ``dashboard.py`` (keep in sync; avoids circular imports)HACKATHON_START = datetime(2026, 4, 25, 17, 0, 0)HACKATHON_END = datetime(2026, 4, 26, 17, 0, 0)
def _now() -> datetime: return datetime.now().replace(microsecond=0)
def get_current_hour() -> float: n = _now() if n < HACKATHON_START: return 0.0 if n >= HACKATHON_END: return 24.0 delta = n - HACKATHON_START h = delta.total_seconds() / 3600.0 return min(24.0, h)
def get_time_remaining() -> str: n = _now() if n >= HACKATHON_END: return "DEADLINE PASSED" sec = (HACKATHON_END - n).total_seconds() if sec <= 0: return "DEADLINE PASSED" h, r = divmod(int(sec), 3600) m, _ = divmod(r, 60) return f"{h}h {m:02d}m remaining"
# --- project root: sqlsage-env ---
def _project_root() -> str: return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def _reset_url(hf_space_url: str) -> str: u = (hf_space_url or "").strip().rstrip("/") if not u: return u if re.search(r"/reset(\?|#|$)", u): return u return f"{u}/reset"
# --- per-check implementations ---
def check_hf_space_live(hf_space_url: str) -> dict[str, Any]: """ GET {hf_space_url}/reset with 5s timeout. Returns: {"ok": bool, "latency_ms": int, "error": None|str, ...} """ t0 = time.perf_counter() try: u = (hf_space_url or "").strip() if not u: return { "ok": False, "latency_ms": 0, "error": "empty hf_space_url", } try: import requests except ImportError as e: return { "ok": False, "latency_ms": 0, "error": f"requests not available: {e}", } full = _reset_url(u) r = requests.get( full, timeout=float(os.environ.get("SQLSAGE_DASHBOARD_HTTP_TIMEOUT", "5")), ) ms = int((time.perf_counter() - t0) * 1000) ok = 200 <= r.status_code < 500 return { "ok": ok, "latency_ms": ms, "error": (None if ok else f"HTTP {r.status_code}"), } except Exception as e: # noqa: BLE001 β intentional graceful reporting ms = int((time.perf_counter() - t0) * 1000) return { "ok": False, "latency_ms": ms, "error": str(e), }
def check_wandb_nonzero_reward(wandb_run_id: str) -> dict[str, Any]: """ W&B API: reward/mean (or any *reward* series). Pass if any value > 0.5. ``wandb_run_id`` is the full run path, e.g. ``entity/project/run_id``. """ rid = (wandb_run_id or "").strip() if not rid: return { "ok": False, "max_reward_seen": 0.0, "episodes_logged": 0, "error": "empty wandb_run_id", } try: import wandb except ImportError as e: return { "ok": False, "max_reward_seen": 0.0, "episodes_logged": 0, "error": f"wandb not installed: {e}", } try: api = wandb.Api( timeout=int(os.environ.get("SQLSAGE_WANDB_API_TIMEOUT", "30")) ) run = api.run(rid) except Exception as e: # noqa: BLE001 return { "ok": False, "max_reward_seen": 0.0, "episodes_logged": 0, "error": str(e), }
max_r = 0.0 eps = 0 err: str | None = None _cap = 50_000 try: for row in run.scan_history(): if not isinstance(row, dict): continue for k, v in row.items(): if "reward" in k.lower() and isinstance(v, (int, float)) and v == v: max_r = max(max_r, float(v)) eps += 1 if eps >= _cap: break except Exception as e: # noqa: BLE001 err = str(e) if max_r <= 0.5: try: s = getattr(run, "summary", None) if s is not None and hasattr(s, "items"): for k, v in s.items(): if "reward" in k.lower() and isinstance(v, (int, float)) and v == v: max_r = max(max_r, float(v)) st = s.get("_step") if hasattr(s, "get") else None if st is not None: try: eps = max(eps, int(st or 0)) except (TypeError, ValueError): pass except Exception as e2: # noqa: BLE001 if err is None: err = str(e2)
ok = max_r > 0.5 return { "ok": ok, "max_reward_seen": round(max_r, 4), "episodes_logged": eps, "error": err, }
def check_plots_committed() -> dict[str, Any]: """ β₯3 PNGs under ``plots/``; recent git commit mentioning ``plots`` in the last 24h. """ from pathlib import Path
root = Path(_project_root()) pdir = root / "plots" plots_found: list[str] = [] try: if pdir.is_dir(): for p in sorted(pdir.iterdir()): if p.suffix.lower() == ".png" and p.is_file(): plots_found.append(p.name) except Exception as e: # noqa: BLE001 return { "ok": False, "plots_found": [], "committed": False, "error": str(e), }
committed = False try: r = subprocess.run( [ "git", "log", "--since=24.hours.ago", "-20", "--oneline", ], capture_output=True, text=True, timeout=15, cwd=str(root), ) logtxt = (r.stdout or "") if r.returncode == 0 else "" for line in logtxt.splitlines(): if "plot" in line.lower(): committed = True break if not committed: r2 = subprocess.run( [ "git", "log", "-1", "--oneline", "--", "plots/", ], capture_output=True, text=True, timeout=10, cwd=str(root), ) if r2.returncode == 0 and (r2.stdout or "").strip(): out = (r2.stdout or "").lower() committed = "plot" in out except Exception as e: # noqa: BLE001 return { "ok": False, "plots_found": plots_found, "committed": False, "error": str(e), }
ok = len(plots_found) >= 3 and committed return { "ok": ok, "plots_found": plots_found, "committed": committed, "error": None, }
def _best_speedup_from_payload(payload: dict[str, Any]) -> tuple[str, float, int]: """Return (summary string, best ratio, n queries).""" queries = payload.get("queries") if not isinstance(queries, list) or not queries: return ("", 0.0, 0) best = 0.0 best_id = "" for q in queries: if not isinstance(q, dict): continue um = q.get("untrained_ms") tm = q.get("trained_ms") qid = str(q.get("query_id", "?")) try: if ( um is not None and tm is not None and float(um) == float(um) and float(tm) == float(tm) and float(tm) > 0 ): su = float(um) / float(tm) if su == su and su > best: best, best_id = su, qid except (TypeError, ValueError, ZeroDivisionError): continue s = f"{best:.1f}x on {best_id}" if best > 0 and best == best else "" return (s, best, len(queries))
def check_benchmark_results_exist() -> dict[str, Any]: from pathlib import Path
p = Path(_project_root()) / "results" / "benchmark_results.json" if not p.is_file(): return { "ok": False, "queries_benchmarked": 0, "best_speedup": "", "error": f"missing {p.name}", } try: payload = json.loads(p.read_text(encoding="utf-8", errors="replace")) except Exception as e: # noqa: BLE001 return { "ok": False, "queries_benchmarked": 0, "best_speedup": "", "error": str(e), } if not isinstance(payload, dict): return { "ok": False, "queries_benchmarked": 0, "best_speedup": "", "error": "invalid JSON structure", } qlist = payload.get("queries", []) n = len(qlist) if isinstance(qlist, list) else 0 best_s, _ratio, nq = _best_speedup_from_payload(payload) if nq == 0 and isinstance(qlist, list): nq = n ok = n >= 3 return { "ok": ok, "queries_benchmarked": nq or n, "best_speedup": best_s, "error": None if ok else "need at least 3 query entries", }
def check_readme_has_links() -> dict[str, Any]: from pathlib import Path
p = Path(_project_root()) / "README.md" if not p.is_file(): return { "ok": False, "missing_links": ["hf.space", "colab", "wandb", "youtube|huggingface blog"], "error": "README.md not found", } try: text = p.read_text(encoding="utf-8", errors="replace") except Exception as e: # noqa: BLE001 return { "ok": False, "missing_links": ["readme"], "error": str(e), } t = text.lower() has_hf = "hf.space" in t has_colab = "colab" in t has_wandb = "wandb" in t has_video = "youtube" in t or "huggingface.co/blog" in t missing: list[str] = [] if not has_hf: missing.append("hf.space") if not has_colab: missing.append("colab") if not has_wandb: missing.append("wandb") if not has_video: missing.append("youtube or huggingface.co/blog") ok = not missing return { "ok": ok, "missing_links": missing, "error": None, }
def _time_remaining_short() -> str: s = get_time_remaining() if s == "DEADLINE PASSED": return s return s.replace(" remaining", "").strip()
def _milestone_time_status( gate_hour: float, ch: float, satisfied: bool) -> tuple[str, str]: """ Return (IN_PROGRESS|UPCOMING|DONE, empty detail for gate). """ h = float(gate_hour) if satisfied: return "DONE", "" if ch < h - 1.0: return "UPCOMING", "" if h - 1.0 <= ch < h or (h <= ch <= h + 0.5): return "IN_PROGRESS", "" if ch > h + 0.5 and not satisfied: return "IN_PROGRESS", "missed" return "UPCOMING", ""
def check_all_milestones(hf_space_url: str, wandb_run_id: str) -> dict[str, Any]: """ Run all checks, map to hours, set overall_status and optional crisis_message. Fills empty ``hf_space_url`` / ``wandb_run_id`` from the environment. """ h_url = (hf_space_url or "").strip() or os.environ.get("SQLSAGE_HF_SPACE_URL", "") w_id = (wandb_run_id or "").strip() or os.environ.get("SQLSAGE_WANDB_RUN_ID", "")
ch = get_current_hour() tr = _time_remaining_short()
hf = check_hf_space_live(h_url) wb = check_wandb_nonzero_reward(w_id) pl = check_plots_committed() bm = check_benchmark_results_exist() rd = check_readme_has_links()
def det_hf() -> str: if hf.get("ok"): return f"latency {hf.get('latency_ms', 0)}ms" return hf.get("error") or "not live"
def det_wb() -> str: if wb.get("ok"): return f"max reward {wb.get('max_reward_seen', 0)} (threshold >0.5)" m = float(wb.get("max_reward_seen") or 0.0) err = wb.get("error") if err: return f"max {m} β {err}" return f"max reward {m} (need >0.5)"
def det_pl() -> str: if pl.get("ok"): n = len(pl.get("plots_found", []) or []) c = "yes" if pl.get("committed") else "no" return f"{n} png(s), committed={c}" perr = pl.get("error") return (perr and str(perr)) or f"need β₯3 png + git; found {pl.get('plots_found')}"
def det_bm() -> str: if bm.get("ok"): b = bm.get("best_speedup", "") n = bm.get("queries_benchmarked", 0) return f"{n} queries; best {b}" if b else f"{n} queries" return bm.get("error") or "benchmarks incomplete"
def det_rd() -> str: if rd.get("ok"): return "all required link tokens present" miss = rd.get("missing_links", []) return f"missing: {', '.join(miss)}" if miss else "README check failed"
# Per-gate check satisfaction (independent of clock) s8 = bool(hf.get("ok")) s12 = bool(wb.get("ok")) s18 = bool(pl.get("ok")) s21 = bool(bm.get("ok")) s23 = bool(rd.get("ok"))
st8, _ = _milestone_time_status(8, ch, s8) st8 = "DONE" if s8 else st8 st12, _ = _milestone_time_status(12, ch, s12) st12 = "DONE" if s12 else st12 st18, _ = _milestone_time_status(18, ch, s18) st18 = "DONE" if s18 else st18 st21, _ = _milestone_time_status(21, ch, s21) st21 = "DONE" if s21 else st21 st23, _ = _milestone_time_status(23, ch, s23) st23 = "DONE" if s23 else st23 st24 = "UPCOMING" d24 = "Manual β cannot auto-check"
# Crisis: past grace + check failed (only if env was set so a real attempt was made) crisis: str | None = None if h_url and ch > 8.5 and not s8: crisis = "CRISIS: Hour 8 milestone missed β HF Space not live" elif w_id and ch > 12.5 and not s12: crisis = "CRISIS: Hour 12 milestone missed β reward still β€0.5 (or W&B unreachable)" elif ch > 18.5 and not s18: crisis = "CRISIS: Hour 18 milestone β need β₯3 PNGs in plots/ + commit mentioning plots" elif ch > 21.5 and not s21: crisis = "CRISIS: Hour 21 milestone β benchmark results incomplete" elif ch > 23.5 and not s23: crisis = "CRISIS: Hour 23 milestone β README links incomplete"
nxt: list[tuple[str, float]] = [] for k, h in (("8", 8.0), ("12", 12.0), ("18", 18.0), ("21", 21.0), ("23", 23.0), ("24", 24.0)): nxt.append((k, h)) hours_left: list[float] = [h - ch for _k, h in nxt if h > ch + 0.0001] d_next = min(hours_left) if hours_left else None
overall = "GREEN" if crisis: overall = "RED" elif d_next is not None and d_next < 0.5: overall = "RED" elif d_next is not None and d_next < 2.0: overall = "YELLOW"
return { "checked_at_hour": round(ch, 2), "time_remaining": tr, "checks_raw": { "hf": hf, "wandb": wb, "plots": pl, "benchmark": bm, "readme": rd, }, "milestones": { "hour_8": { "gate": "HF Space live", "status": st8, "detail": det_hf(), }, "hour_12": { "gate": "Non-zero reward", "status": st12, "detail": det_wb() if w_id else "set SQLSAGE_WANDB_RUN_ID (or pass wandb run path)", }, "hour_18": { "gate": "Plots committed", "status": st18, "detail": det_pl(), }, "hour_21": { "gate": "Benchmark results", "status": st21, "detail": det_bm(), }, "hour_23": { "gate": "README links complete", "status": st23, "detail": det_rd(), }, "hour_24": { "gate": "Form submitted", "status": st24, "detail": d24, }, }, "overall_status": overall, "crisis_message": crisis, }
def _cli() -> None: import argparse import pprint
p = argparse.ArgumentParser(description="Run SQLSage hackathon status checks (JSON out).") p.add_argument("--hf", default=None, help="Override SQLSAGE_HF_SPACE_URL") p.add_argument("--wandb", default=None, help="Override SQLSAGE_WANDB_RUN_ID (entity/project/run)") p.add_argument( "--json", action="store_true", help="Print JSON instead of a pretty object dump", ) a = p.parse_args() env_hf = a.hf or os.environ.get("SQLSAGE_HF_SPACE_URL", "") env_w = a.wandb or os.environ.get("SQLSAGE_WANDB_RUN_ID", "") out = check_all_milestones(env_hf, env_w) if a.json: print(json.dumps(out, indent=2, default=str)) else: pprint.pprint(out, width=100)
if __name__ == "__main__": _cli()cheatsheets/person1_env_engineer.htmlAdded+99
cheatsheets/person1_env_engineer.mdAdded+57
cheatsheets/person2_reward_engineer.htmlAdded+106
cheatsheets/person2_reward_engineer.mdAdded+71
cheatsheets/person3_training_lead.htmlAdded+101
cheatsheets/person3_training_lead.mdAdded+62
dashboard.pyAdded+7
notebooks/sqlsage_grpo_colab.ipynb+278-218
pyproject.toml+7
run.pyAdded+7
sqlsage/dashboard.pyAdded+909
sqlsage/generate_cheatsheets.pyAdded+439
sqlsage/run.pyAdded+625
sqlsage/status_checker.pyAdded+573