Skip to content
Physics0070Public

Latest commit

 

History

25 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

QueryPilot AI

Write smarter queries. Understand every execution.

Live demo: https://querypilot-ai-b1k0.onrender.com (free tier: the first request after idle takes about a minute) | Course project report | Source

A SQL query optimizer and performance workbench for any SQLite database. Paste a query and it shows how a cost-based optimizer would execute it, compares the alternatives, rewrites the SQL itself (subquery decorrelation, semi-/anti-joins, join and DISTINCT elimination, pre-aggregation, predicate simplification), checks that the rewrite returns the same rows, measures both, and tells you honestly whether it helped.

On a 5-table "everything at once" query it turns a 2.3 s query into a 4.8 ms one, verified row-for-row; across 422 generated benchmark queries, 52 of 84 rewrites measured faster and 6 slower (BENCHMARKS.md).

QueryPilot AI workspace

It is not tied to one database. Nothing in the optimizer knows a table or column name. Point it at any SQLite file (or switch files from the top bar) and the schema, statistics, example queries and plans all come from that database. Tests run the whole pipeline on two unrelated schemas and on a database with awkward identifiers ("Order Details").

What it does

For a read-only SELECT, the backend:

  1. Discovers the schema (tables, columns, keys, indexes, foreign keys).
  2. Computes statistics from the live data (row counts, distinct values, nulls, min/max, most-common values, equi-depth histograms).
  3. Parses the SQL with sqlglot into a relational-algebra tree.
  4. Estimates selectivity and cardinality (histograms, semi-/anti-join and outer-join estimates, interval-aware conjunctions), then costs candidate physical plans with an explicit, documented cost model (COST_MODEL.md, STATISTICS.md).
  5. Picks the cheapest plan and explains why it won.
  6. Rewrites the SQL with deterministic, AST-based rules — decorrelates correlated subqueries into grouped derived tables, turns EXISTS/NOT EXISTS into semi-/anti-joins, removes redundant LEFT JOINs, DISTINCT, GROUP BY and predicates, pre-aggregates before joins — chooses between candidates with a cost model calibrated on measured latencies, and verifies the rewrite returns the same rows on your database and on generated adversarial databases (NULLs, duplicates, empty tables). Unsafe rewrites are rejected with the reason (REWRITE_ENGINE.md).
  7. Benchmarks the original and the rewrite and reports faster / slower / no measurable difference — never a speedup the measurements don't support.
  8. Compares with SQLite's own EXPLAIN QUERY PLAN, advises on hypothetical indexes, and explains the result with an optional AI copilot (works offline without a key).

Being honest about results

The cost model is an educational estimator, not a copy of SQLite's planner, and SQLite's planner is good. In testing, join orders that the model preferred were sometimes slower when forced on SQLite. The UI therefore leads with the measurement:

Optimized query tab

  • Estimated (cost model) and Measured (wall-clock) are always labelled and never mixed.
  • A rewrite is shown only if the database confirms it returns the same columns and rows on this data (evidence, not a proof for every database).
  • "Faster" or "slower" is only claimed when the measured ranges don't overlap (in the app), or when a bootstrap 95% confidence interval excludes "no change" (in the benchmark framework).
  • Rewrites that benchmarks showed to lose (IN → EXISTS, NOT IN → anti-join) are off by default.
  • If the query is already optimal, it says so. A rewrite that was skipped (for example LIMIT without ORDER BY, or RANDOM() in the query) is reported as skipped for semantic safety, never as optimal.
  • The estimated gain is measured against your query as written, not a strawman.

Screenshots

Execution plan — cost-heat bars mark expensive operators; click a node for details.

Execution plan

Candidate plans — every enumerated join order, costed and ranked.

Candidates

Schema — discovered dynamically from whichever database is connected.

Schema

Benchmarks

backend/bench/framework.py generates 50–100 queries per database from its schema (27 query shapes), runs them on three e-commerce sizes and two library sizes, and reports estimation q-error, interleaved A/B latency (median, p95, confidence interval), planning overhead, SQLite's own plan next to the optimizer's, and how well the cost model ranks real latencies.

Database Queries q-error geomean Rewrites: faster / same / slower Speedup geomean Overhead median
e-commerce, 2k orders 100 1.12 16 / 3 / 0 11.9× 1.5 ms
e-commerce, 8k orders (held out) 100 1.13 15 / 3 / 1 12.2× 1.3 ms
e-commerce, 40k orders (held out) 100 1.07 10 / 3 / 1 7.0× 1.5 ms
library, 300 books 63 1.06 9 / 1 / 0 4.1× 1.0 ms
library, 2.4k books (held out) 59 1.05 8 / 2 / 0 12.1× 1.1 ms

Held out: not used to calibrate the cost model. Method, findings and remaining issues: BENCHMARKS.md; every query: backend/bench/results/REPORT.md.

cd backend
python bench/framework.py            # full run (~20 min) -> bench/results/REPORT.md
python bench/framework.py --quick    # small databases only

Quick start

# Backend
cd backend
python -m venv .venv && . .venv/Scripts/activate   # macOS/Linux: source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
python -m seed.generate                 # optional: create the demo database
uvicorn app.main:app --reload --port 8000

# Frontend (second terminal)
cd frontend
npm install
npm run dev                             # http://localhost:5173

Open the dashboard and press Optimize — the editor starts with an example generated from your database's own schema. Use the database chip in the top bar to open any other SQLite file. Details: SETUP.md.

Configuration

Set in backend/.env (see .env.example). Highlights:

Variable Default Meaning
DATABASE_PATH optimizer_demo.db SQLite file connected at startup
ALLOW_INDEX_CREATION false Databases are opened read-only unless this is true
OPENAI_API_KEY (empty) Optional; the copilot works offline without it
MIN_ESTIMATED_GAIN_PCT 0.5 A rewrite must beat your query by at least this estimate
SQLITE_STATEMENT_TIMEOUT_MS 30000 Any SQLite statement running longer is interrupted
TRUSTED_PROXIES (empty) Reverse proxies whose X-Forwarded-For identifies the client for rate limiting
PATH_CONNECT_SCOPE local Connecting by file path only from this machine unless API_TOKEN is set (any = everyone)
MAX_SESSIONS 64 Browser sessions with their own connected database
STATS_SAMPLE_THRESHOLD / STATS_SAMPLE_ROWS 200000 / 20000 Larger tables get sampled statistics
STATS_PERSIST true Keep statistics on disk until the database file changes
REWRITE_MAX_CANDIDATES / REWRITE_BUDGET_MS 24 / 1500 Budget for the rewrite candidate search
REWRITE_VERIFY_DATASETS 6 Generated adversarial databases per verification (+1 empty)
REWRITE_USE_CALIBRATION true Use the measured cost weights in sql_rewrite/calibration.json
REWRITE_IN_TO_EXISTS / REWRITE_NOT_IN_ANTI_JOIN false Rewrites that benchmarks showed to lose
cost-model constants see .env.example I/O, CPU, rows-per-page and fallback selectivities

Query shapes and verdicts

  • Comma joins and JOIN ... ON are the same query: a WHERE a.id = b.id between two tables is attached to the join that connects them, so both forms get the same estimate and plan.
  • CTEs and FROM subqueries (including chained CTEs, window functions and UNION bodies) are analysed as virtual relations: row counts and column statistics are estimated from the definition, and the cost of building them is charged. Recursive CTEs are estimated from the anchor part and flagged.
  • Every analysis ends in one verdict: rewrite measured faster, original measured faster, no clear difference, original has the lowest estimated cost, rewrite skipped for semantic safety, unsupported feature, equivalence check failed or not verified, benchmark unavailable, optimization failed.
  • Equivalence compares rows as a multiset (duplicates and NULLs counted) and, under ORDER BY, the sort-key order (ties may differ, as SQL allows). LIMIT with ORDER BY is allowed and must return identical rows.
  • Benchmarks are interleaved and randomized, report median / mean / min / max / std dev / p95, state the cache condition, and give break-even executions only when the rewrite is measurably faster.

Details: REWRITE_ENGINE.md, LIMITATIONS.md.

Deployment

The repository root has a Dockerfile (builds the frontend, serves it from the API on one port, seeded demo database inside, non-root, read-only SQL). The live demo above runs it as a Render Docker web service, auto-deployed from main. To run it yourself:

docker build -t querypilot . && docker run -p 8000:8000 querypilot

See DEPLOYMENT.md for the one-worker requirement, sessions, proxies and rate limiting.

Tests

cd backend && pytest -q

368 backend tests (25 more run only against live MySQL/PostgreSQL) and 17 Playwright end-to-end tests (cd frontend && npm run test:e2e), including stale-result and out-of-order-response protection. They cover parsing and semantic checks, safety, schema discovery, statistics and histograms, selectivity and cardinality (checked against actual row counts), cost, join ordering, plans, every rewrite rule (applied and rejected), equivalence verification on adversarial data (including a deliberately wrong rewrite it must catch), the MAD regression query, the benchmark workload generator and cost calibration, the statement timeout, the HTTP API, database switching, the read-only guarantee, concurrency, determinism across hash seeds, and awkward identifiers — on more than one schema.

Documentation

Doc Contents
SETUP.md Install and run
ARCHITECTURE.md Modules and data flow
OPTIMIZER.md Parsing, plans, rewrite and verification
REWRITE_ENGINE.md SQL-to-SQL rewrite rules, preconditions, verification, calibration
BENCHMARKS.md Benchmark framework, results, what it found
COST_MODEL.md Every cost formula
STATISTICS.md How statistics and selectivity work
DATABASES.md Database support and the adapter layer
API.md HTTP endpoints
DEMO.md Demo data and sample queries
LIMITATIONS.md What it does not do
QueryPilot_AI_Project_Report.docx Course project report

License

MIT — see LICENSE.

Releases

Packages

Contributors

Languages