Metadata-Version: 2.5
Name: querygate-spark
Version: 0.4.3
Summary: Check Spark SQL before it runs: a SQLGlot parser, deterministic rules for runtime and wrong-answer hazards, and an optional LLM reviewer (any provider via LiteLLM).
Project-URL: Homepage, https://github.com/vchaurasia95/querygate-spark-sql
Project-URL: Repository, https://github.com/vchaurasia95/querygate-spark-sql
Project-URL: Issues, https://github.com/vchaurasia95/querygate-spark-sql/issues
Project-URL: DOI, https://doi.org/10.5281/zenodo.24633580
Author: Vishal Chaurasia
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: linter,llm,spark,spark-sql,sql,sqlglot,static-analysis,validation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Requires-Dist: sqlglot<31,>=30.0
Provides-Extra: llm
Requires-Dist: litellm>=1.40; extra == 'llm'
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# QueryGate for Spark SQL

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24633580.svg)](https://doi.org/10.5281/zenodo.24633580)

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](https://docs.litellm.ai/) (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

```bash
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

```bash
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.

```text
$ 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

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

```dotenv
# .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).

```text
$ 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](https://docs.litellm.ai/docs/providers), 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`](https://github.com/vchaurasia95/querygate-spark-sql/blob/master/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](https://github.com/vchaurasia95/querygate-spark-sql/blob/master/CITATION.cff)).

## License

Apache License 2.0 (see [LICENSE](https://github.com/vchaurasia95/querygate-spark-sql/blob/master/LICENSE)). Benchmark queries and results under `benchmark/` are licensed CC BY 4.0
(see [benchmark/LICENSE-DATA](https://github.com/vchaurasia95/querygate-spark-sql/blob/master/benchmark/LICENSE-DATA)).
