querygate-spark 0.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ """QueryGate for Spark SQL: check Spark SQL before it runs.
2
+
3
+ from querygate_spark import validate
4
+ result = validate("SELECT name, COUNT(*) FROM users")
5
+ result.verdict # "invalid"
6
+ result.messages # [Message(source="rules", ...)]
7
+ """
8
+ __version__ = "0.4.3"
9
+
10
+ from .core import validate # noqa: E402
11
+ from .result import Message, Result # noqa: E402
12
+
13
+ __all__ = ["validate", "Result", "Message", "__version__"]
querygate_spark/cli.py ADDED
@@ -0,0 +1,173 @@
1
+ """`querygate` command line.
2
+
3
+ querygate check query.sql [more.sql ...]
4
+ querygate check - # read SQL from stdin
5
+ querygate check --mode rules --json query.sql
6
+ querygate check --env-file ~/.querygate.env query.sql
7
+ querygate check -v query.sql # trace of every stage on stderr; -vv adds the raw LLM response
8
+
9
+ Exit code (worst over all inputs): 0 valid, 1 warning, 2 invalid, 3 error.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import sys
16
+
17
+ from . import __version__, redact
18
+ from .core import validate
19
+ from .result import EXIT_CODES
20
+
21
+ RAW_LIMIT = 2000
22
+ TEXT_LIMIT = 500
23
+
24
+
25
+ def _cap(text: str, n: int = TEXT_LIMIT) -> str:
26
+ return text if len(text) <= n else text[:n] + f"... [{len(text)} chars]"
27
+
28
+ _ICON = {"valid": "OK", "warning": "WARNING", "invalid": "INVALID", "error": "ERROR"}
29
+
30
+
31
+ def _read(path: str) -> str:
32
+ if path == "-":
33
+ return sys.stdin.read()
34
+ with open(path, encoding="utf-8") as f:
35
+ return f.read()
36
+
37
+
38
+ def main(argv=None) -> int:
39
+ p = argparse.ArgumentParser(prog="querygate", description="Check Spark SQL before it runs.")
40
+ p.add_argument("--version", action="version", version=f"querygate-spark {__version__}")
41
+ sub = p.add_subparsers(dest="command", required=True)
42
+ c = sub.add_parser("check", help="check one or more SQL files ('-' for stdin)")
43
+ c.add_argument("files", nargs="+")
44
+ c.add_argument("--model", help="LiteLLM model string (env QUERYGATE_MODEL)")
45
+ c.add_argument("--mode", choices=["auto", "rules", "llm"], help="env QUERYGATE_MODE (default auto)")
46
+ c.add_argument("--api-base", help="base URL for self-hosted / Ollama (env QUERYGATE_API_BASE)")
47
+ c.add_argument("--timeout", type=float, help="LLM timeout in seconds (env QUERYGATE_TIMEOUT)")
48
+ c.add_argument("--env-file", help="load this .env file (env QUERYGATE_ENV_FILE; default ./.env if present)")
49
+ c.add_argument("--json", action="store_true", help="machine-readable output")
50
+ c.add_argument("-v", "--verbose", action="count", default=0,
51
+ help="trace every stage on stderr (-vv also prints the raw LLM response)")
52
+ a = p.parse_args(argv)
53
+
54
+ from .dotenv import load_dotenv_once
55
+ try:
56
+ load_dotenv_once(a.env_file) if a.env_file else load_dotenv_once()
57
+ except FileNotFoundError as e:
58
+ print(f"querygate: {e}", file=sys.stderr)
59
+ return EXIT_CODES["error"]
60
+
61
+ worst, out = 0, []
62
+ for path in a.files:
63
+ try:
64
+ sql = _read(path)
65
+ except OSError as e:
66
+ res_d = {"file": path, "verdict": "error", "error": str(e)}
67
+ worst = max(worst, EXIT_CODES["error"])
68
+ out.append(res_d)
69
+ if not a.json:
70
+ print(f"{path}: ERROR {e}", file=sys.stderr)
71
+ continue
72
+ try:
73
+ res = validate(sql, model=a.model, mode=a.mode, api_base=a.api_base, timeout=a.timeout)
74
+ except ValueError as e: # bad configuration
75
+ print(f"querygate: {e}", file=sys.stderr)
76
+ return EXIT_CODES["error"]
77
+ worst = max(worst, res.exit_code) if res.verdict != "error" else EXIT_CODES["error"]
78
+ secrets = redact.collect()
79
+ if a.verbose:
80
+ name = "<stdin>" if path == "-" else path
81
+ for line in format_trace(name, res.trace, a.verbose):
82
+ print(redact.scrub(line, secrets), file=sys.stderr)
83
+ if a.json:
84
+ out.append(redact.scrub({"file": path, **res.to_dict()}, secrets))
85
+ continue
86
+ name = "<stdin>" if path == "-" else path
87
+ print(f"{name}: {_ICON[res.verdict]} (stage: {res.stage or '-'}, mode: {res.mode}"
88
+ + (f", model: {res.model}" if res.llm_called else "") + ")")
89
+ if res.notice:
90
+ print(f" note: {res.notice}")
91
+ if res.error:
92
+ print(f" error: {res.error}")
93
+ for m in res.messages:
94
+ print(f" - [{m.source}] {m.text}")
95
+ if a.json:
96
+ print(json.dumps(out if len(out) != 1 else out[0], indent=2, default=str))
97
+ return worst
98
+
99
+
100
+ def format_trace(name: str, trace: list, level: int = 1) -> list:
101
+ """Human-readable lines for a Result.trace (no secret values are ever in it)."""
102
+ out = [f"[querygate] {name}"]
103
+ for r in trace:
104
+ st = r.get("stage")
105
+ if st == "config":
106
+ status = r.get("env_file_status")
107
+ env = {"loaded": f"{r.get('env_file')} (keys: {', '.join(r.get('env_keys_loaded') or []) or 'none new'})",
108
+ "disabled": "disabled (QUERYGATE_DOTENV)", "none": "none",
109
+ "not attempted": "not loaded"}.get(status, str(status))
110
+ key = (f"found via {r['api_key_source']}" if r.get("api_key_found") else "not found")
111
+ out += [f" config: .env: {env}",
112
+ f" mode: {r['mode_requested']} -> {r['mode_used']} ({r['mode_reason']})",
113
+ f" model: {r['model']}; API key: {key}"
114
+ + (f"; api_base: {r['api_base']}" if r.get("api_base") else "")
115
+ + f"; timeout: {r.get('timeout_s')}s"]
116
+ elif st == "input":
117
+ out.append(f" input: {r['chars_before']} -> {r['chars_after']} chars"
118
+ + (" (whitespace / trailing ';' removed)" if r.get("normalized") else " (unchanged)"))
119
+ elif st == "parser":
120
+ msg = f": {r['message']}" if r.get("message") else ""
121
+ out.append(f" parser: {r['result']}{msg} ({r['ms']:.2f} ms)")
122
+ elif st == "rules":
123
+ if r.get("skipped"):
124
+ out.append(f" rules: skipped ({r['skipped']})")
125
+ continue
126
+ fs = r.get("findings") or []
127
+ out.append(f" rules: {len(fs)} finding(s) ({r['ms']:.2f} ms)" if fs else
128
+ f" rules: no findings ({r['ms']:.2f} ms)")
129
+ for f in fs:
130
+ out.append(f" - [{f['severity']}] {f['rule']}: {f['message']}")
131
+ if r.get("short_circuit"):
132
+ out.append(" short-circuit: a certain finding decides the verdict; LLM not called")
133
+ elif st == "llm":
134
+ if r.get("skipped"):
135
+ out.append(f" llm: skipped ({r['skipped']})")
136
+ continue
137
+ line = f" llm: called {r['prompt']} on {r['model']}"
138
+ if "ms" in r:
139
+ line += f" ({r['ms']:.0f} ms)"
140
+ out.append(line)
141
+ if r.get("error"):
142
+ out.append(f" error: {r['error']}")
143
+ continue
144
+ u = r.get("usage")
145
+ if u:
146
+ out.append(f" tokens: prompt {u.get('prompt_tokens')}, completion {u.get('completion_tokens')},"
147
+ f" total {u.get('total_tokens')}")
148
+ jp = r.get("json_parse")
149
+ out.append(f" response_format: {r.get('response_format')}; JSON: "
150
+ + {"json": "parsed directly", "fenced": "extracted from a ```json block (fallback)",
151
+ "embedded": "extracted from surrounding text (fallback)",
152
+ "failed": "could not be parsed"}.get(jp, str(jp)))
153
+ out.append(f" verdict: {r.get('verdict')}")
154
+ if r.get("summary"):
155
+ out.append(f" summary: {_cap(r['summary'])}")
156
+ if r.get("warning"):
157
+ out.append(f" warning: {_cap(r['warning'])}")
158
+ if level >= 2 and r.get("raw") is not None:
159
+ raw = r["raw"]
160
+ cut = f"\n ... [truncated, {len(raw)} chars total]" if len(raw) > RAW_LIMIT else ""
161
+ out.append(" raw response:\n " + raw[:RAW_LIMIT].replace("\n", "\n ") + cut)
162
+ elif st == "merge":
163
+ out.append(f" merge: kept {', '.join(r.get('kept') or []) or 'nothing'}"
164
+ + (f"; dropped {', '.join(r['dropped'])}" if r.get("dropped") else ""))
165
+ elif st == "final":
166
+ out.append(f" final: {r['verdict']} (exit code {r['exit_code']}; decided by {r.get('decided_by') or '-'})"
167
+ + (f"; note: {r['notice']}" if r.get("notice") else "")
168
+ + (f"; error: {r['error']}" if r.get("error") else ""))
169
+ return out
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())
@@ -0,0 +1,122 @@
1
+ """Configuration: validate() kwargs and CLI flags override environment variables.
2
+
3
+ | env var | meaning |
4
+ |---------------------|-----------------------------------------------------------------|
5
+ | QUERYGATE_MODEL | LiteLLM model string (default gemini/gemini-2.5-flash) |
6
+ | QUERYGATE_MODE | auto | rules | llm (default auto) |
7
+ | QUERYGATE_API_KEY | API key passed to LiteLLM as api_key (overrides provider vars) |
8
+ | QUERYGATE_API_BASE | base URL for self-hosted / Ollama endpoints |
9
+ | QUERYGATE_TIMEOUT | LLM request timeout in seconds (default 60) |
10
+ | QUERYGATE_ENV_FILE | explicit .env file to load (default: ./.env if present) |
11
+ | QUERYGATE_DOTENV | set to 0 / false / no to disable .env loading |
12
+
13
+ A .env file fills in only variables that are not already set in the real
14
+ environment; kwargs and CLI flags override both (see dotenv.py).
15
+
16
+ Provider keys are read by LiteLLM from its standard variables (GEMINI_API_KEY or
17
+ GOOGLE_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, ...).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+
25
+ DEFAULT_MODEL = "gemini/gemini-2.5-flash"
26
+ MODES = ("auto", "rules", "llm")
27
+
28
+
29
+ @dataclass
30
+ class Settings:
31
+ model: str = DEFAULT_MODEL
32
+ mode: str = "auto"
33
+ api_key: Optional[str] = None
34
+ api_base: Optional[str] = None
35
+ timeout: float = 60.0
36
+
37
+
38
+ def resolve(model=None, mode=None, api_key=None, api_base=None, timeout=None, env=None) -> Settings:
39
+ if env is None:
40
+ # lazily load ./.env (or QUERYGATE_ENV_FILE) once; real env vars win
41
+ from .dotenv import load_dotenv_once
42
+ load_dotenv_once()
43
+ env = os.environ
44
+ mode = (mode or env.get("QUERYGATE_MODE") or "auto").strip().lower()
45
+ if mode not in MODES:
46
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}")
47
+ t = timeout if timeout is not None else env.get("QUERYGATE_TIMEOUT")
48
+ return Settings(
49
+ model=model or env.get("QUERYGATE_MODEL") or DEFAULT_MODEL,
50
+ mode=mode,
51
+ api_key=api_key or env.get("QUERYGATE_API_KEY") or None,
52
+ api_base=api_base or env.get("QUERYGATE_API_BASE") or None,
53
+ timeout=float(t) if t not in (None, "") else 60.0,
54
+ )
55
+
56
+
57
+ def _gemini_key_alias(env) -> Optional[str]:
58
+ """LiteLLM's Gemini provider reads GEMINI_API_KEY; accept GOOGLE_API_KEY too."""
59
+ return env.get("GEMINI_API_KEY") or env.get("GOOGLE_API_KEY")
60
+
61
+
62
+ def llm_available(s: Settings, env=None) -> tuple[bool, str]:
63
+ """Can LLM mode run? Returns (ok, reason-if-not)."""
64
+ env = os.environ if env is None else env
65
+ try:
66
+ import litellm # noqa: F401
67
+ except ImportError:
68
+ return False, "litellm is not installed (pip install 'querygate-spark[llm]')"
69
+ if s.api_key or s.api_base:
70
+ return True, ""
71
+ if s.model.startswith(("gemini/", "gemini-")) and _gemini_key_alias(env):
72
+ return True, ""
73
+ try:
74
+ import litellm
75
+ info = litellm.validate_environment(model=s.model)
76
+ if info.get("keys_in_environment"):
77
+ return True, ""
78
+ missing = ", ".join(info.get("missing_keys") or []) or "a provider API key"
79
+ return False, f"no API key found for model {s.model!r} (set {missing}, or QUERYGATE_API_KEY)"
80
+ except Exception as e: # unknown provider string etc.
81
+ return False, f"cannot use model {s.model!r}: {e}"
82
+
83
+
84
+ _PROVIDER_KEYS = {"openai/": "OPENAI_API_KEY", "anthropic/": "ANTHROPIC_API_KEY", "azure/": "AZURE_API_KEY",
85
+ "mistral/": "MISTRAL_API_KEY", "groq/": "GROQ_API_KEY", "cohere/": "COHERE_API_KEY",
86
+ "deepseek/": "DEEPSEEK_API_KEY", "together_ai/": "TOGETHERAI_API_KEY",
87
+ "openrouter/": "OPENROUTER_API_KEY"}
88
+
89
+
90
+ def key_source(s: Settings, env=None, explicit_api_key: Optional[str] = None) -> Optional[str]:
91
+ """NAME of where the API key comes from (never the value), or None if no key.
92
+ Adds ' (from .env)' when the variable was loaded from a .env file."""
93
+ env = os.environ if env is None else env
94
+ from .dotenv import last_load
95
+
96
+ def tag(name):
97
+ return f"{name} (from .env)" if name in (last_load.get("keys") or []) else name
98
+ if explicit_api_key:
99
+ return "api_key argument"
100
+ if s.api_key:
101
+ return tag("QUERYGATE_API_KEY")
102
+ if s.model.startswith(("gemini/", "gemini-")):
103
+ for name in ("GEMINI_API_KEY", "GOOGLE_API_KEY"):
104
+ if env.get(name):
105
+ return tag(name)
106
+ return None
107
+ for prefix, name in _PROVIDER_KEYS.items():
108
+ if s.model.startswith(prefix) and env.get(name):
109
+ return tag(name)
110
+ return None
111
+
112
+
113
+ def safe_url(url: Optional[str]) -> Optional[str]:
114
+ """scheme://host[:port] only (drops credentials, path and query)."""
115
+ if not url:
116
+ return None
117
+ from urllib.parse import urlsplit
118
+ u = urlsplit(url)
119
+ host = u.hostname or ""
120
+ if u.port:
121
+ host += f":{u.port}"
122
+ return f"{u.scheme}://{host}" if u.scheme else host or None
@@ -0,0 +1,209 @@
1
+ """validate(): parser -> deterministic rules -> LLM, same logic as the
2
+ benchmarked ADK pipeline (v0.4), without ADK.
3
+
4
+ - SQLGlot ParseError: in LLM mode the error interpreter explains it; in rules
5
+ mode the parser message is returned. Verdict: invalid.
6
+ - A certain ("invalid") rule finding short-circuits: no LLM call.
7
+ - Otherwise in LLM mode the model validator decides; rule warnings and the
8
+ model's own warning are merged (the model's is dropped if it repeats a rule
9
+ finding). In rules mode, rule warnings alone decide warning vs valid.
10
+
11
+ Every Result carries a `trace`: one record per stage (config, input, parser,
12
+ rules, llm, merge, final) with timings and decisions, never secret values.
13
+ `querygate check -v` prints it. Known secret values are scrubbed from the trace,
14
+ the raw LLM response and the messages (see redact.py).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ import time
20
+
21
+ from . import llm, redact, rules
22
+ from .config import Settings, key_source, llm_available, resolve, safe_url
23
+ from .parser import validate_sql_syntax
24
+ from .prompts import (ERROR_INTERPRETER_DESCRIPTION, ERROR_INTERPRETER_NAME, ERROR_INTERPRETER_PROMPT,
25
+ MODEL_VALIDATOR_DESCRIPTION, MODEL_VALIDATOR_NAME, MODEL_VALIDATOR_PROMPT, identity, render)
26
+ from .result import EXIT_CODES, Message, Result
27
+
28
+ _ANSI = re.compile(r"\x1b\[[0-9;]*m")
29
+
30
+
31
+ def _clean(text: str) -> str:
32
+ return _ANSI.sub("", text or "").strip()
33
+
34
+
35
+ def _truthy(v) -> bool:
36
+ return v.strip().lower() == "true" if isinstance(v, str) else bool(v)
37
+
38
+
39
+ def _system(prompt: str, state: dict, name: str, description: str) -> str:
40
+ # ADK order: rendered instruction, then the agent identity line, joined by a blank line
41
+ return render(prompt, state) + "\n\n" + identity(name, description)
42
+
43
+
44
+ def validate(sql: str, *, model=None, mode=None, api_key=None, api_base=None, timeout=None) -> Result:
45
+ """Validate one Spark SQL query and return a Result.
46
+
47
+ mode: "auto" (default; LLM if a model and key are available, else rules-only),
48
+ "rules" (no network), or "llm" (require the LLM; errors if unavailable).
49
+ Other settings fall back to QUERYGATE_* environment variables (see config.py).
50
+ The returned Result.trace lists what each stage did (see module docstring).
51
+ """
52
+ s: Settings = resolve(model, mode, api_key, api_base, timeout)
53
+ from .dotenv import last_load
54
+ trace, lat, notice = [], {}, None
55
+
56
+ # ---- config -------------------------------------------------------------
57
+ src = key_source(s, explicit_api_key=api_key)
58
+ use_llm, why = s.mode == "llm", ""
59
+ if s.mode in ("auto", "llm"):
60
+ ok, why = llm_available(s)
61
+ use_llm = ok
62
+ if s.mode == "auto" and not ok:
63
+ notice = f"Running rules-only: {why}."
64
+ reason = {"rules": "mode=rules requested",
65
+ "llm": "mode=llm requested" + ("" if use_llm else f" but unavailable: {why}"),
66
+ "auto": "LLM available" if use_llm else f"no LLM: {why}"}[s.mode]
67
+ trace.append({"stage": "config", "env_file": last_load.get("path") or last_load.get("status"),
68
+ "env_file_status": last_load.get("status"), "env_keys_loaded": list(last_load.get("keys") or []),
69
+ "mode_requested": s.mode, "mode_used": "llm" if use_llm else "rules", "mode_reason": reason,
70
+ "model": s.model, "api_key_found": bool(src), "api_key_source": src,
71
+ "api_base": safe_url(s.api_base), "timeout_s": s.timeout})
72
+ secrets = redact.collect(s.api_key or api_key)
73
+
74
+ def finish(res: Result) -> Result:
75
+ res.latency_ms = {**lat, "total": (time.perf_counter() - t0) * 1000}
76
+ res.notice = res.notice or notice
77
+ trace.append({"stage": "final", "verdict": res.verdict, "exit_code": EXIT_CODES[res.verdict],
78
+ "decided_by": res.stage, "llm_called": res.llm_called, "notice": res.notice,
79
+ "error": res.error})
80
+ res.trace = redact.scrub(trace, secrets)
81
+ res.raw = redact.scrub(res.raw, secrets)
82
+ res.error = redact.scrub(res.error, secrets)
83
+ res.notice = redact.scrub(res.notice, secrets)
84
+ for m in res.messages:
85
+ m.text = redact.scrub(m.text, secrets)
86
+ return res
87
+
88
+ if s.mode == "llm" and not use_llm:
89
+ t0 = time.perf_counter()
90
+ return finish(Result("error", stage=None, mode="llm", model=s.model, error=why))
91
+
92
+ # ---- input normalization -------------------------------------------------
93
+ # Normalize the input the way the benchmark harness did: surrounding
94
+ # whitespace and trailing semicolons removed. LLM verdicts were observed to
95
+ # change with a single trailing newline, so every path sees the same text.
96
+ raw_sql = sql or ""
97
+ sql = raw_sql.strip().rstrip(";").strip()
98
+ trace.append({"stage": "input", "chars_before": len(raw_sql), "chars_after": len(sql),
99
+ "normalized": raw_sql != sql})
100
+
101
+ t0 = time.perf_counter()
102
+ parsed = validate_sql_syntax(sql)
103
+ lat["parser"] = (time.perf_counter() - t0) * 1000
104
+ pstate = {True: "parsed", False: "parse error", None: "undecided (parser could not decide)"}[parsed["valid"]]
105
+ trace.append({"stage": "parser", "result": pstate, "message": _clean(parsed["message"]) if parsed["valid"] is not True
106
+ else None, "ms": round(lat["parser"], 3)})
107
+
108
+ # ---- parse error ------------------------------------------------------
109
+ if parsed["valid"] is False:
110
+ pmsg = _clean(parsed["message"])
111
+ trace.append({"stage": "rules", "skipped": "parse error (rules need a parsed query)"})
112
+ if not use_llm:
113
+ trace.append({"stage": "llm", "skipped": "rules-only mode"})
114
+ return finish(Result("invalid", [Message("parser", "invalid", pmsg)], stage="parser", mode="rules"))
115
+ return finish(_call_llm("error_interpreter", s, sql, {"sql_to_validate": sql, "error": parsed["message"]},
116
+ [], [Message("parser", "invalid", pmsg)], trace, lat, secrets))
117
+
118
+ # ---- deterministic rules ----------------------------------------------
119
+ t1 = time.perf_counter()
120
+ findings = rules.check(sql)
121
+ lat["rules"] = (time.perf_counter() - t1) * 1000
122
+ level, _ = rules.verdict(findings)
123
+ trace.append({"stage": "rules", "findings": [{"rule": f.rule, "severity": f.severity, "message": f.message}
124
+ for f in findings], "ms": round(lat["rules"], 3),
125
+ "short_circuit": level == "invalid"})
126
+ if level == "invalid":
127
+ trace.append({"stage": "llm", "skipped": "a certain rule finding decided the verdict (short-circuit)"})
128
+ msgs = [Message("rules", "invalid", f.message, f.rule) for f in findings if f.severity == "invalid"]
129
+ return finish(Result("invalid", msgs, stage="rules", mode="llm" if use_llm else "rules",
130
+ model=s.model if use_llm else None))
131
+ rule_warnings = [Message("rules", "warning", f.message, f.rule) for f in findings if f.severity == "warning"]
132
+ if not use_llm:
133
+ trace.append({"stage": "llm", "skipped": f"rules-only mode ({reason})"})
134
+ trace.append({"stage": "merge", "kept": [f"rules:{m.rule}" for m in rule_warnings], "dropped": []})
135
+ return finish(Result("warning" if rule_warnings else "valid", rule_warnings, stage="rules", mode="rules"))
136
+ return finish(_call_llm("model_validator", s, sql, {"sql_to_validate": sql}, findings, rule_warnings,
137
+ trace, lat, secrets))
138
+
139
+
140
+ def _call_llm(which, s, sql, state, findings, base_msgs, trace, lat, secrets) -> Result:
141
+ """Call the model validator or error interpreter and build the Result."""
142
+ if which == "error_interpreter":
143
+ prompt, name, desc = ERROR_INTERPRETER_PROMPT, ERROR_INTERPRETER_NAME, ERROR_INTERPRETER_DESCRIPTION
144
+ else:
145
+ prompt, name, desc = MODEL_VALIDATOR_PROMPT, MODEL_VALIDATOR_NAME, MODEL_VALIDATOR_DESCRIPTION
146
+ rec = {"stage": "llm", "prompt": which.replace("_", " "), "model": s.model}
147
+ trace.append(rec)
148
+ fallback_stage = "parser" if which == "error_interpreter" else "rules"
149
+ fallback_verdict = "invalid" if which == "error_interpreter" else ("warning" if base_msgs else "valid")
150
+ t1 = time.perf_counter()
151
+ try:
152
+ out = llm.complete_ex(_system(prompt, state, name, desc), sql, s)
153
+ except Exception as e:
154
+ lat["llm"] = (time.perf_counter() - t1) * 1000
155
+ rec.update(ms=round(lat["llm"], 1), error=f"{type(e).__name__}: {str(e)[:300]}")
156
+ return _llm_failed(s, e, Result(fallback_verdict, list(base_msgs), stage=fallback_stage, mode="rules"))
157
+ lat["llm"] = (time.perf_counter() - t1) * 1000
158
+ raw = out["text"]
159
+ obj, how = llm.extract_json_info(raw)
160
+ rec.update(ms=round(lat["llm"], 1), usage=out.get("usage"), response_format=out.get("response_format"),
161
+ json_parse=how or "failed", raw=raw)
162
+ base = dict(stage=which, mode="llm", model=s.model, llm_called=True, raw=raw)
163
+
164
+ if which == "error_interpreter":
165
+ text = (obj or {}).get("summary") or base_msgs[0].text
166
+ rec.update(verdict="invalid", summary=_clean(text))
167
+ trace.append({"stage": "merge", "kept": ["llm:summary" if obj else "parser:message"], "dropped": []})
168
+ return Result("invalid", [Message("llm" if obj else "parser", "invalid", _clean(text))], **base,
169
+ notice=None if obj else "LLM response was not valid JSON; showing the parser message.")
170
+
171
+ if obj is None or "isValidSQL" not in obj:
172
+ rec.update(verdict="unparseable")
173
+ failed = _llm_failed(s, ValueError("LLM response was not valid JSON with isValidSQL"),
174
+ Result(fallback_verdict, list(base_msgs), stage="rules", mode="rules"))
175
+ failed.raw, failed.llm_called = raw, True
176
+ return failed
177
+ if not _truthy(obj["isValidSQL"]):
178
+ summary = _clean(obj.get("summary") or "Invalid query.")
179
+ rec.update(verdict="invalid", summary=summary)
180
+ trace.append({"stage": "merge", "kept": ["llm:summary"],
181
+ "dropped": [f"rules:{m.rule} (verdict is invalid)" for m in base_msgs]})
182
+ return Result("invalid", [Message("llm", "invalid", summary)], **base)
183
+ msgs, kept, dropped = list(base_msgs), [f"rules:{m.rule}" for m in base_msgs], []
184
+ llm_warn = _truthy(obj.get("warning", False))
185
+ rec.update(verdict="warning" if llm_warn else "valid",
186
+ warning=_clean(obj.get("warning_message") or "") if llm_warn else None,
187
+ summary=_clean(obj.get("summary") or ""))
188
+ if llm_warn:
189
+ w = obj.get("warning_message") or obj.get("summary")
190
+ tokens = [str(f.token).lower() for f in findings if f.severity == "warning"]
191
+ hit = next((t for t in tokens if t and len(t) > 2 and t in (w or "").lower()), None)
192
+ if w and not hit:
193
+ msgs.append(Message("llm", "warning", _clean(w)))
194
+ kept.append("llm:warning")
195
+ elif w:
196
+ dropped.append(f"llm:warning (repeats rule finding on '{hit}')")
197
+ trace.append({"stage": "merge", "kept": kept, "dropped": dropped})
198
+ return Result("warning" if msgs else "valid", msgs, **base)
199
+
200
+
201
+ def _llm_failed(s: Settings, exc: Exception, fallback: Result) -> Result:
202
+ """LLM call failed: auto mode falls back to the rules/parser result with a
203
+ notice; llm mode reports an error."""
204
+ why = f"{type(exc).__name__}: {str(exc)[:300]}"
205
+ if s.mode == "llm":
206
+ return Result("error", fallback.messages, stage=fallback.stage, mode="llm", model=s.model,
207
+ llm_called=True, error=f"LLM call failed: {why}")
208
+ fallback.notice = f"LLM call failed, showing rules-only result: {why}"
209
+ return fallback
@@ -0,0 +1,140 @@
1
+ """Minimal built-in .env support (no extra dependency).
2
+
3
+ Format: KEY=VALUE per line; optional leading `export `; values may be single-
4
+ quoted (literal) or double-quoted (\\n, \\t, \\", \\\\ escapes); `#` starts a
5
+ comment on its own line or after an unquoted value (preceded by whitespace);
6
+ blank lines are ignored. Malformed lines are skipped (logged once at debug).
7
+
8
+ Loading rules (see load_dotenv_once):
9
+ - file: QUERYGATE_ENV_FILE or an explicit path (must exist), else ./.env in the
10
+ current working directory only (no search of parent directories; silent if absent)
11
+ - only variables NOT already in the environment are set (real env wins)
12
+ - opt-out: QUERYGATE_DOTENV=0 / false / no / off
13
+ - values are never logged; at debug level only the loaded key names are
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import re
20
+ from typing import Optional
21
+
22
+ log = logging.getLogger("querygate_spark.dotenv")
23
+
24
+ _KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$")
25
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\"}
26
+ _loaded = False
27
+ # status of the last load attempt, for verbose output (key NAMES only, never values)
28
+ last_load = {"status": "not attempted", "path": None, "keys": []}
29
+
30
+
31
+ def parse(text: str) -> dict:
32
+ """Parse .env text into a dict. Later duplicates override earlier ones."""
33
+ out, bad = {}, 0
34
+ for raw in text.splitlines():
35
+ line = raw.strip()
36
+ if not line or line.startswith("#"):
37
+ continue
38
+ if line.startswith("export ") or line.startswith("export\t"):
39
+ line = line[7:].lstrip()
40
+ if "=" not in line:
41
+ bad += 1
42
+ continue
43
+ key, _, rest = line.partition("=")
44
+ key = key.strip()
45
+ if not _KEY.match(key):
46
+ bad += 1
47
+ continue
48
+ rest = rest.lstrip()
49
+ value = _parse_value(rest)
50
+ if value is None:
51
+ bad += 1
52
+ continue
53
+ out[key] = value
54
+ if bad:
55
+ log.debug("skipped %d malformed .env line(s)", bad)
56
+ return out
57
+
58
+
59
+ def _parse_value(rest: str) -> Optional[str]:
60
+ if not rest:
61
+ return ""
62
+ q = rest[0]
63
+ if q in ("'", '"'):
64
+ buf, i = [], 1
65
+ while i < len(rest):
66
+ c = rest[i]
67
+ if q == '"' and c == "\\" and i + 1 < len(rest):
68
+ buf.append(_ESCAPES.get(rest[i + 1], "\\" + rest[i + 1]))
69
+ i += 2
70
+ continue
71
+ if c == q:
72
+ tail = rest[i + 1:].strip()
73
+ if tail and not tail.startswith("#"):
74
+ return None # garbage after the closing quote
75
+ return "".join(buf)
76
+ buf.append(c)
77
+ i += 1
78
+ return None # unterminated quote
79
+ # unquoted: strip an inline comment (" #...") and surrounding whitespace
80
+ m = re.search(r"\s#", rest)
81
+ if m:
82
+ rest = rest[:m.start()]
83
+ return rest.strip()
84
+
85
+
86
+ def _disabled(env) -> bool:
87
+ return str(env.get("QUERYGATE_DOTENV", "1")).strip().lower() in ("0", "false", "no", "off")
88
+
89
+
90
+ def load_dotenv_once(path: Optional[str] = None, env=None, force: bool = False) -> list:
91
+ """Load a .env file into `env` (default os.environ) once per process.
92
+
93
+ path: explicit file (missing -> FileNotFoundError). If None, use
94
+ QUERYGATE_ENV_FILE (also must exist) or ./.env (silently skipped if absent).
95
+ Returns the list of keys that were set.
96
+ """
97
+ global _loaded
98
+ env = os.environ if env is None else env
99
+ if _loaded and not force and path is None:
100
+ return []
101
+ _loaded = True
102
+ if _disabled(env):
103
+ last_load.update(status="disabled", path=None, keys=[])
104
+ return []
105
+ explicit = path or env.get("QUERYGATE_ENV_FILE") or None
106
+ target = explicit or os.path.join(os.getcwd(), ".env")
107
+ if not os.path.isfile(target):
108
+ last_load.update(status="none", path=None, keys=[])
109
+ if explicit:
110
+ last_load.update(status="missing", path=explicit)
111
+ raise FileNotFoundError(f".env file not found: {explicit}")
112
+ return []
113
+ with open(target, encoding="utf-8-sig") as f:
114
+ values = parse(f.read())
115
+ set_keys = []
116
+ for k, v in values.items():
117
+ if k not in env:
118
+ env[k] = v
119
+ set_keys.append(k)
120
+ last_load.update(status="loaded", path=os.path.abspath(target), keys=sorted(set_keys))
121
+ from .redact import is_secret_name
122
+ _secret_values.update(v for k, v in values.items() if v and is_secret_name(k))
123
+ if set_keys:
124
+ log.debug("loaded %s from %s", ", ".join(sorted(set_keys)), target)
125
+ return set_keys
126
+
127
+
128
+ # values of secret-looking variables read from a .env file, for redaction
129
+ _secret_values: set = set()
130
+
131
+
132
+ def loaded_secret_values() -> set:
133
+ return set(_secret_values)
134
+
135
+
136
+ def _reset_for_tests():
137
+ global _loaded
138
+ _loaded = False
139
+ last_load.update(status="not attempted", path=None, keys=[])
140
+ _secret_values.clear()