Skip to main content

QueryGate for Spark SQL

DOI

Check Spark SQL before it runs. QueryGate combines three layers:

  1. Parser: SQLGlot (Spark dialect) catches grammar errors.
  2. Deterministic rules: no schema, no network, about 1 ms. They catch errors that only show up at runtime (invalid regex and datetime patterns, literal value errors, element_at(..., 0)), window functions in WHERE, missing GROUP BY, and text-certain wrong-answer hazards (= NULL, comma joins without a predicate, LIMIT without ORDER BY, a LEFT JOIN undone by a WHERE filter, NOT IN over a nullable subquery). They warn about runtime risks (casts and divisions that may fail under ANSI or silently return NULL).
  3. Optional LLM reviewer, through LiteLLM (any provider): explains errors in plain language and flags likely wrong-answer bugs. A certain rule finding skips the LLM call.

Each query gets a verdict: valid, warning (it runs, but may fail or return a misleading result) or invalid. Each verdict comes with short messages that say which part of the query is affected and why.

querygate check catching a LEFT JOIN undone by WHERE and a NOT IN over a nullable subquery

Benchmark at a glance

Scored against Apache Spark 4.0.1 ground truth on frozen query sets (full method, per-query results and caveats in benchmark/results/report.md). The LLM layer used gemini-2.5-flash; "plain LLM prompt" is the same model with a short generic prompt.

System Runtime and compile errors caught (heldout2, 24 faulty) Silent wrong answers caught for the right reason (heldout3, 36 faulty) False alarms on correct queries (68, all splits) Warnings on correct queries (68, all splits) Median latency (heldout3) Network or API key
QueryGate, rules only 18 12 0 5 0.6 ms no
QueryGate, rules + LLM (v0.4 prompt) 21 33 0 5 3.2 s yes
Plain LLM prompt 22 33 5 9 3.0 s yes
Spark EXPLAIN 12 0 1 0 needs Spark no
SQLFluff (all rules) 14 5 0 51 20 ms no
sqlsure 0 4 2 1 0.3 ms no
  • Runtime-only faults: 12 heldout2 queries pass Spark EXPLAIN and only fail during compute. The rules flag 11 of them, for the right reason, in under a millisecond and with no network. The plain LLM prompt also flags 11, but names the right reason for 9.
  • No false alarms: QueryGate never called a correct query invalid on any split; the plain LLM prompt did 5 times. On heldout3 the plain LLM prompt changed its verdict between runs on 5 queries, QueryGate on 1.
  • Read with care: QueryGate rules + LLM on dev, heldout and heldout2 is one run (three runs on heldout3). The dev split was used for tuning, and heldout2 was written by the rule author before the rules existed. See the report's Caveats section.

Install

pip install querygate-spark          # parser + rules only (no network, no API key)
pip install "querygate-spark[llm]"   # adds the LLM reviewer (LiteLLM)

Python 3.10+.

Quickstart

pre-commit

Add this to .pre-commit-config.yaml to check every staged .sql file before it is committed:

repos:
  - repo: https://github.com/vchaurasia95/querygate-spark-sql
    rev: v0.6.0
    hooks:
      - id: querygate

The hook runs querygate check --mode rules: offline, deterministic, no API key. A warning or invalid verdict fails the commit. To add the LLM reviewer, set a model and key (environment or .env) and use:

      - id: querygate
        args: [--mode, auto]
        additional_dependencies: [litellm]

Command line

querygate check query.sql                 # one or more files
cat query.sql | querygate check -         # stdin
querygate check --mode rules query.sql    # offline, deterministic
querygate check --json query.sql          # machine-readable
querygate check --model openai/gpt-4o-mini query.sql
querygate check -v query.sql               # trace each stage on stderr (-vv: raw LLM response too)

Exit codes (the worst over all inputs): 0 valid, 1 warning, 2 invalid, 3 error. That makes it usable as a CI or pre-commit gate.

$ querygate check --mode rules q.sql
q.sql: INVALID  (stage: rules, mode: rules)
  - [rules] The SELECT list mixes aggregate functions with name, which is not aggregated, and the query has no
    GROUP BY. Spark needs every non-aggregated column to appear in GROUP BY.

Python

from querygate_spark import validate

sql = "SELECT total / divisor AS ratio FROM payments"
r = validate(sql)
r.verdict       # "warning"
r.messages      # [Message(source="rules", severity="warning", text="'/ divisor' fails under ANSI ...", ...)]
r.stage         # "rules", "parser", "model_validator" or "error_interpreter"
r.latency_ms    # {"parser": ..., "rules": ..., "total": ...}, plus "llm": ... only when the LLM was called
r.to_dict()

validate(sql, mode="rules")                          # never calls an LLM
validate(sql, model="anthropic/claude-sonnet-4-5")   # any LiteLLM model string
validate(sql, suggest=True)                          # also ask for a suggested fix (see below)

Suggested fixes (opt-in)

QueryGate's job is to find the problem. A suggested fix is optional and off by default. Turn it on with --suggest, QUERYGATE_SUGGEST=1 or validate(sql, suggest=True). When the LLM raises a warning, QueryGate then makes one more LLM call, with a separate prompt that only writes fixes, and puts the answer in its own field (Message.suggestion, "suggestion" in --json). The suggestion never changes the verdict, and the detection prompt is the same with suggestions on or off.

QueryGate sees only the SQL text, not your schema or data, so a suggestion is not verified: check it before you apply it. The CLI labels it that way. When the model is not confident of a safe fix, it leaves the suggestion out. Rule findings are deterministic and keep their fix inside the message text.

$ querygate check --mode llm --suggest fanout.sql
fanout.sql: WARNING  (stage: model_validator, mode: llm, model: gemini/gemini-2.5-flash)
  - [llm] SUM(o.amount) after joining order_items adds each order's amount once per item ...
    suggestion (unverified, check against your schema): If amount is stored once per order, sum it from orders ...

Changed in 0.6: 0.5.0 showed suggestions by default, from the same call that does detection. --no-suggestions now turns suggestions off even when QUERYGATE_SUGGEST is set.

Configuration

Keyword arguments to validate() and CLI flags override environment variables.

Environment variable CLI flag Meaning
QUERYGATE_MODEL --model LiteLLM model string. Default gemini/gemini-2.5-flash
QUERYGATE_MODE --mode auto (default): use the LLM if a model and key are available, otherwise rules-only with a notice. rules: never call an LLM. llm: require the LLM (error if unavailable)
QUERYGATE_API_KEY API key passed to LiteLLM (overrides provider variables)
QUERYGATE_API_BASE --api-base Base URL for self-hosted or Ollama endpoints
QUERYGATE_TIMEOUT --timeout LLM request timeout in seconds (default 60)
QUERYGATE_SUGGEST --suggest / --no-suggestions 1 / true / yes: when the LLM raises a warning, make one more call for a suggested fix. Default off
QUERYGATE_ENV_FILE --env-file Explicit .env file to load (default: ./.env if present)
QUERYGATE_DOTENV Set to 0 / false / no to disable .env loading
GEMINI_API_KEY / GOOGLE_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, ... Provider keys, read by LiteLLM from its standard variables

.env file

QueryGate reads a .env file from the current working directory, if one exists. It does not search parent directories. This needs no extra dependency.

# .env  (never commit this file)
QUERYGATE_MODEL=gemini/gemini-2.5-flash
GEMINI_API_KEY=your-key-here
# or: QUERYGATE_MODEL=openai/gpt-4o-mini and OPENAI_API_KEY=...
  • Precedence: keyword arguments and CLI flags win over real environment variables, which win over .env values. A .env file only fills in variables that are not already set.
  • Another file: QUERYGATE_ENV_FILE=/path/to/file or querygate check --env-file PATH .... An explicit file must exist. A missing default ./.env is silently ignored.
  • Opt out: set QUERYGATE_DOTENV=0 (or false / no).
  • Format: KEY=VALUE, optional export, single or double quotes (\n escapes in double quotes), # comments. Values are never logged.
  • Keep .env out of version control: add it to .gitignore.

LLM calls use temperature 0 and request JSON output where the provider supports it. Otherwise QueryGate extracts the JSON from the text reply. If an LLM call fails in auto mode, the rules-only result is returned with a notice.

Verbose output

querygate check -v prints a trace of every stage to stderr, so --json output on stdout stays valid JSON. -vv also prints the raw LLM response (truncated to 2,000 characters). From Python, every Result carries the same information in result.trace (a list of per-stage records).

$ querygate check -v --model gemini/gemini-2.5-flash orders.sql
[querygate] orders.sql
  config: .env: /work/project/.env (keys: GEMINI_API_KEY, QUERYGATE_MODEL)
          mode: auto -> llm (LLM available)
          model: gemini/gemini-2.5-flash; API key: found via GEMINI_API_KEY (from .env); timeout: 60.0s
  input: 132 -> 131 chars (whitespace / trailing ';' removed)
  parser: parsed (0.41 ms)
  rules: no findings (0.62 ms)
  llm: called model validator on gemini/gemini-2.5-flash (2310 ms)
    tokens: prompt 9120, completion 96, total 9216
    response_format: json_object; JSON: parsed directly
    verdict: warning
    summary: Query is syntactically valid Spark SQL.
    warning: SUM(o.amount) after joining order_items counts each order once per item ...
  merge: kept llm:warning
  final: warning (exit code 1; decided by model_validator)

The trace never contains secret values. It shows which variable supplied the API key, never the key itself, and api_base is reduced to scheme and host. As a safeguard, any known secret value is scrubbed ([REDACTED]) from the verbose output, the raw response and the JSON output. Known secrets are the key in use, plus values of environment or .env variables whose names contain KEY, TOKEN, SECRET, PASSWORD, CREDENTIAL or AUTH.

Providers

Any model LiteLLM supports, for example:

Provider Model string Key
Google Gemini gemini/gemini-2.5-flash GEMINI_API_KEY or GOOGLE_API_KEY
OpenAI openai/gpt-4o-mini OPENAI_API_KEY
Anthropic anthropic/claude-sonnet-4-5 ANTHROPIC_API_KEY
Ollama (local) ollama/llama3.1 none; set QUERYGATE_API_BASE=http://localhost:11434

Accuracy and models

The published benchmark results (benchmark/results/report.md, DOI above) were measured with gemini-2.5-flash against Apache Spark 4.0.1 ground truth. Quality varies by model: smaller or local models may miss more problems or produce more false warnings. The rules layer gives the same results with any model, or with none. The benchmark report also compares QueryGate with external baselines, including the same model with a plain prompt (summary in Benchmark at a glance).

Privacy

In rules mode nothing leaves your machine. In llm and auto mode, the SQL text is sent to the model provider you configure (or to your own endpoint with QUERYGATE_API_BASE). QueryGate sends no data itself and has no telemetry. Use --mode rules (or QUERYGATE_MODE=rules) for queries that must not leave your environment.

Repository layout

src/querygate_spark/   the library (published to PyPI)
tests/                 unit tests (no network)
benchmark/             queries, Spark ground truth, harness and results (not shipped in the package)
examples/adk_agent/    the original Google ADK runtime, kept as an optional example
demo/                  the README demo GIF, its SQL files and the scripts that record it

Citation

If you use QueryGate or its benchmark, please cite it via the DOI above (see CITATION.cff).

License

Apache License 2.0 (see LICENSE). Benchmark queries and results under benchmark/ are licensed CC BY 4.0 (see benchmark/LICENSE-DATA).

Metadata

Release files for querygate-spark 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for querygate-spark 0.6.0
File Size Uploaded Provenance Actions
querygate_spark-0.6.0.tar.gz 57.6 kB With provenance Details for querygate_spark-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for querygate-spark 0.6.0
File Interpreter ABI Platform Actions
querygate_spark-0.6.0-py3-none-any.whl Python 3 none any Details for querygate_spark-0.6.0-py3-none-any.whl

Total release size: 108.4 kB

Release files / querygate_spark-0.6.0.tar.gz

Download URL querygate_spark-0.6.0.tar.gz
Size 57.6 kB
Tags Source
SHA-256 checksum
How to use checksums
d8cfffbfdc9e33705b04e0cfca0644840bd310e08b7810edd75114757d6c9070
BLAKE2b-256 checksum
How to use checksums
cb684aafa6156723a200a880e8610ebb5e62773deb74b96cb82f83cc04ba3285
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / querygate_spark-0.6.0-py3-none-any.whl

Download URL querygate_spark-0.6.0-py3-none-any.whl
Size 50.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5003d6ab79f63d65c7d0b3f12cccd5fa091755d11c09ae1e37b9da312a0849dd
BLAKE2b-256 checksum
How to use checksums
e80e0390b2d6a9f35affff88679f747d24a99c99dd67cc97a79d5e51fc99fc27
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for querygate-spark 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for querygate_spark-0.6.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page