Skip to content

FEAT-012 — Query advice: stable findings and a 1–100 score for allowed but wasteful queries #291

Done

Description

@jmmana

Parent epic: #290
Priority: P1

Problem

The guard answers one question: may this query run? Under a permissive policy, SELECT * FROM orders passes, gets LIMIT 1000 from max_rows and runs. Nothing tells the operator or the model that the query reads every column of every row without a filter. The opt-in complexity limits (max_joins, max_subquery_depth, forbid_cartesian) and required_filters can only refuse. Nothing reports allowed but wasteful queries.

Proposal

An opt-in, deterministic advisory pass over the same AST. It produces findings with stable codes and a score from 1 to 100 derived from them. Advice never changes the decision unless the policy opts in to min_score.

explanation = guard.explain("SELECT * FROM orders", context)
explanation.advice.score      # e.g. 35
explanation.advice.findings   # select-star (orders), no-filter (orders)

First set of findings. Each finding has a stable code and a default weight.

Code Fires on
select-star * or t.* in the outermost projection. The detail names the table and the column count when schema lists it
no-filter A table read with no predicate on it, unless listed in advice.small_tables
no-row-bound The model wrote no LIMIT / TOP / FETCH and the guard had to add one
leading-wildcard LIKE '%…' or ILIKE '%…'
function-on-filtered-column A function or cast around a column in WHERE or JOIN ... ON (YEAR(created_at) = 2026, UPPER(email) = …)
or-chain More than N OR branches over different columns
unlinked-join A cartesian product. Reuse rules/complexity.py, reported as a finding instead of a refusal
deep-nesting Subquery depth above the advice threshold. Reuse _depth
order-without-limit ORDER BY in the outermost query with no bound from the model

Column breakdown, per table: projected columns, columns in filters, joins, grouping and ordering, and columns wrapped in functions. Build it on Explanation.columns and scope_columns.

Score: max(1, 100 − Σ weights), with a cap on the weight of a repeated finding. The number summarizes for people and dashboards. The findings are the contract.

What is scored: the model's SQL, before the rewrite. Row filters, masks and limits that the guard adds are listed next to the findings and don't hide them.

advice:
  enabled: true
  small_tables: [countries, currencies]   # no-filter does not apply
  weights: {select-star: 15}               # override a default weight
  warn_below: 60                           # adds a warning to explain, MCP and CLI output
  min_score: null                          # opt-in: below this, reject with low_query_score

Out of scope

Database statistics and plans (FEAT-013, #292), any LLM, any execution.

Acceptance criteria

  • With advice on, Guard.explain() returns advice through Explanation.to_dict(), HTTP /v1/explain and the engine stdio protocol. With advice off, Guard.check() output and latency don't change. With advice on, the corpus stays within the CI performance budget (Performance budget: under 2 ms per check, measured in CI #19).
  • Each code has tests in the PostgreSQL, MySQL, T-SQL, SQLite, Snowflake and BigQuery dialects, including cases that must not fire: LIKE 'abc%', a filtered join, a listed small table.
  • Golden file: SELECT * FROM orders scores below SELECT id, total FROM orders WHERE created_at >= '2026-01-01' LIMIT 100, which has no findings.
  • min_score rejects with the experimental code low_query_score and a fix hint in the style of FEAT-008 — Rejections that teach: fix hints, with the accuracy cost measured #217. Without min_score, advice never changes ok.
  • sqlguardllm check --advice prints the findings and the score. The policy JSON Schema includes advice.
  • The Node.js and .NET clients expose advice, and the conformance suite (Cross-language conformance: the corpus through every client #37) covers it.
  • Docs (EN / ES) cover what each code means, how to fix it, and that the score is advisory and experimental in 1.x.

Files

src/sqlguardllm/advice.py (new) · explain.py · policy.py · schema.py and schema/ · cli.py · engine_stdio.py · clients/node · clients/dotnet · tests/test_advice.py (new)

Size

L

PR #306 merged after all 30 PR checks passed. It adds Policy.advice, nine stable finding codes, the score, the columns by clause (as written, not resolved through aliases), check --advice, the explain_query field and an opt-in min_score with the experimental code low_query_score. Without min_score the decision never changes. Remaining: the Node.js and .NET clients and the conformance suite (#37), and a per-table column breakdown. The default weights give SELECT * FROM orders 50 and a bounded, filtered query 100, not the 35 and 92 of the example above.

PR #313 merged after all its checks passed. Advice.tables now gives the columns used per physical table and clause, resolved like Guard.explain() resolves columns; the protocol schema lists advice, a conformance test checks that in-process, stdio and HTTP explanations agree, and Explanation (Node.js) and ExplainResult.Advice (.NET) are typed. All criteria are met.

Activity

  1. added
    type:feature
    area:core
    size:l
    lang:python
    p1
    on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corelang:pythonp1size:ltype:feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions