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.

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

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

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_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.

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

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.4.3

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.4.3
File Size Uploaded Provenance Actions
querygate_spark-0.4.3.tar.gz 50.3 kB With provenance Details for querygate_spark-0.4.3.tar.gz

Built distribution (wheel)

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

Total release size: 95.6 kB

Release files / querygate_spark-0.4.3.tar.gz

Download URL querygate_spark-0.4.3.tar.gz
Size 50.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9ecf9d930ddcddc44294a15c946bc5b025f346a658cc23548eac3aa5e6039990
BLAKE2b-256 checksum
How to use checksums
706c5b416602fd689658e0cf3df532c8262021676291d6120bf19749d2dd73c9
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 Nov 29, 2026.

Transparency log

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

Download URL querygate_spark-0.4.3-py3-none-any.whl
Size 45.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6aa4cf287e849507a73e2d608e08e1c931d8efad702f70906e43fd58dfcd47d1
BLAKE2b-256 checksum
How to use checksums
0e090ba68faa60175698c9b936b60be96078ba260e49c027ed074d9b2d845845
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 Nov 29, 2026.

Transparency log

Security for querygate-spark 0.4.3

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.4.3.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 Nov 29, 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