Repository navigation
Description
Parent epic: #165
Priority: P1
Objetivo
Turn the guard benchmark from #174 into a tool other authors run on their own validators, in any language, without cloning this repository: a JSON-lines adapter protocol, a versioned corpus file, results per attack category and a badge. Each project that measures itself links back here, and the publication rule holds because authors publish their own results.
Scope
- Module
sqlguardllm.bench, run withpython -m sqlguardllm.bench. Do not changecli.py(to avoid conflicts with FEAT-003 — Proxy mode: guard any existing database MCP server #172); a CLI subcommand can come later. - Corpus shipped as package data,
src/sqlguardllm/bench/corpus-v1.json, generated by a script fromtests/corpus(the read-only attack codes already used by FEAT-005 — Public benchmark of SQL guards for LLM agents #174) andbenchmarks/guards/legitimate.yaml. Fields:version; per caseid,kind(attack or legitimate),category(write, not_a_query, stacked, row_lock, function),dialect,sql. - Adapters:
- Built in: sqlguardllm and the two baselines.
benchmarks/guards/run.pybecomes a thin wrapper around the module. --adapter-cmd "node my_guard.js": starts the process, writes one JSON line per case{"id", "dialect", "sql"}and reads{"id", "accept": true|false}. Per-case timeout. A missing, late or malformed answer is counted as an error and reported separately, never as accept or reject.--adapter-py module:functionfor Python validators.
- Built in: sqlguardllm and the two baselines.
- Output: markdown table,
--json, breakdown per category and per dialect, and--badge out.jsonin the shields.io endpoint format (for examplebypass 0/69 · FP 0/34). - Example adapter in Node under
benchmarks/guards/adapters/node-example/(keyword list), used by a test. - docs/BENCHMARK.md: how to run it on your own validator, the protocol, the badge, a GitHub Actions snippet (documentation only, no new workflow file) and the publication rule: this repository does not publish third-party results; authors publish their own.
- Publish the corpus JSON on the docs site (
docs/assets/) with a stable URL.
Criterios de aceptación
-
uv run python -m sqlguardllm.benchreproduces the FEAT-005 — Public benchmark of SQL guards for LLM agents #174 table: sqlguardllm 0/69 bypasses and 0/34 false positives. - Test with
--adapter-cmdand the Node example; malformed and timed-out answers are counted as errors (the test skips with a clear reason whennodeis not on PATH). - Drift test: the packaged corpus equals a fresh regeneration from the sources.
-
--badgeoutput has the shields.io endpoint fieldsschemaVersion,label,messageandcolor(test). - docs/BENCHMARK.md updated; the corpus JSON returns HTTP 200 from the docs site after the Pages deploy.
- No third-party adapters or results added.
uv run ruff check src tests,uv run ruff format --check src tests,uv run mypyanduv run pytestgreen.
Archivos relevantes
src/sqlguardllm/bench/(new),benchmarks/guards/run.py,benchmarks/guards/legitimate.yamlbenchmarks/guards/adapters/node-example/(new),tests/test_guard_benchmark.pydocs/BENCHMARK.md,docs/assets/,pyproject.toml(package data only, never the version)
Out of scope: package versions, .github/workflows/release.yml, PRs #155 and #156.
Claude API proposal (AGENTS.md)
Workflow run: https://github.com/jmmana/sqlguardllm/actions/runs/46439811767 · model claude-sonnet-5-5 · manifest in the run artifact. Review it against the code; model output is not validation evidence.
proposal.md
Proposal: sqlguardllm.bench, a guard benchmark any validator author can run (#182)
Parent epic: #165. Builds on #174. Suggestions only; nothing here has been run.
Goal
Turn benchmarks/guards/run.py into a reusable tool: python -m sqlguardllm.bench measures any validator, in any language, against a versioned corpus and reports bypass and false-positive rates per category and dialect, plus a shields.io badge. Third-party authors run it themselves and publish their own results. This repository publishes none, which keeps the publication rule in docs/BENCHMARK.md intact.
Assumptions (to confirm)
- A1.
benchmarks/guards/run.pyalready exposesattacks(),legitimate(),ADAPTERSandrun(repeats), astests/test_guard_benchmark.pyimplies. I have not seen the file and will read it before moving code. - A2.
Caseobjects inrun.pycarryid,dialectandsql. I do not know if they carry a category. The corpus fields areid, kind, category, dialect, sql, so category is probably derived in the generator from the violationcodesintests/corpus/*.yaml, and legitimate cases get no category (or a fixedlegitimate). - A3. Category mapping from
ViolationCode:write_operation→write,not_a_query→not_a_query,multiple_statements→stacked,row_lock→row_lock,denied_function→function. Cases whose codes span categories need a deterministic tie-break rule (see open questions). - A4. The package already builds with hatchling or setuptools via
pyproject.toml. The package-data change is one include line. - A5. The dotted
ViolationCodevalues and the corpus attack selection logic ("read-only codes only", from FEAT-005 — Public benchmark of SQL guards for LLM agents #174) live inrun.pytoday and can be reused unchanged by the generator.
Files to change
New:
src/sqlguardllm/bench/__init__.pysrc/sqlguardllm/bench/__main__.py: argparse and entrypoint.src/sqlguardllm/bench/corpus.py: load and validate packaged corpus.src/sqlguardllm/bench/adapters.py: built-in, subprocess and Python-callable adapters.src/sqlguardllm/bench/report.py: aggregation, markdown, JSON, badge.src/sqlguardllm/bench/corpus-v1.json: generated artifact, committed.benchmarks/guards/build_corpus.py: generator fromtests/corpusandlegitimate.yaml.benchmarks/guards/adapters/node-example/guard.js, plus a short README.tests/test_bench_cli.py,tests/test_bench_corpus.py.docs/assets/corpus-v1.json: copy served by the docs site.
Modified:
benchmarks/guards/run.py: thin wrapper over the module.tests/test_guard_benchmark.py: keep the existing assertions, pointed at the module where needed.docs/BENCHMARK.md: protocol, badge, CI snippet, publication rule.pyproject.toml: package data only, never the version.
Untouched: cli.py, release.yml, versions, PRs #155 and #156, any new workflow file.
Proposed implementation
Corpus
corpus-v1.json shape:
{"version": 1,
"cases": [{"id": "...", "kind": "attack", "category": "stacked",
"dialect": "postgres", "sql": "..."}]}build_corpus.py reuses the existing attacks() / legitimate() selection so the numbers stay 69 and 34 (assumption A5), sorts cases by id and writes with fixed formatting (indent=2, sort_keys=True, trailing newline) so regeneration is byte-stable. corpus.py loads via importlib.resources, validates required keys, unique ids and allowed kind/category values, and rejects unknown version.
Adapter interface
Internally an adapter is Callable[[Case], bool | None] returning accept, reject, or None for error, with an exception counting as error. That keeps error distinct from reject, as the issue requires.
- Built-in: the three existing guards.
--adapter-py module:function:function(sql: str, dialect: str) -> bool. An exception counts as error.--adapter-cmd "...": spawn once withsubprocess.Popenand an argv list fromshlex.split(nevershell=True), stdin/stdout piped. Per case, write{"id","dialect","sql"}\nand read one line with a per-case timeout (--timeout, default 5 s). A reader thread plusqueue.get(timeout=...)is portable and avoidsselecton Windows. Error outcomes: timeout, EOF, invalid JSON, missing or non-booleanaccept, oridmismatch. After a timeout or EOF, kill and restart the process, so a late reply cannot be attributed to the next case. After a bounded number of consecutive failures, abort the adapter and mark the remaining cases as errors.
The adapter command is whatever the person running the benchmark supplies, executed locally with their privileges. The docs should say so.
Metrics
- bypass = attacks accepted / attacks answered
- false positive = legitimate rejected / legitimate answered
- errors reported separately and excluded from both numerators and denominators, with the count shown beside every rate.
- Breakdown per category (attacks) and per dialect (both kinds).
Existing run.py reports bypass_rate as accepted over total attacks. The proposal keeps that when there are zero errors, so the #174 table reproduces exactly.
Output
- Default: markdown table to stdout.
--json PATH: full results, includingcorpus_versionand per-case outcomes for bypassed, false-positive and errored ids.--badge PATH:{"schemaVersion":1,"label":"sqlguard bench","message":"bypass 0/69 · FP 0/34","color":...}. Colour rule (to confirm):brightgreenif both are 0 and errors are 0;redif any bypass;yellowotherwise, including errors or only false positives.- Exit code 0 on completion regardless of results (a benchmark, not a gate); non-zero only for usage or protocol-setup failures.
Wrapper
benchmarks/guards/run.py keeps its flags (--json, --repeats) and calls sqlguardllm.bench.main with the three built-in adapters, so existing docs and CI invocations keep working.
Tests
- Reproduction: run the built-ins on the packaged corpus; assert sqlguardllm is 0/69 and 0/34, and both baselines stay above 50% bypass (kept from the existing test).
- Drift: run the generator in memory and compare it to
corpus-v1.json, and comparedocs/assets/corpus-v1.jsonto the packaged file. - Corpus validity: unique ids, allowed enums, every attack has a category.
- Subprocess protocol, Node example: skipped with a clear reason via
shutil.which("node"). Asserts sane results for the keyword-list example. - Subprocess protocol, no Node needed: small Python fixture scripts run with
sys.executablethat (a) answer malformed JSON, (b) never answer (timeout set low), (c) exit early, (d) answer the wrongid. Each must yield errors, never accept or reject. This keeps the error-path coverage running in CI where Node is absent. - Badge: the four fields exist, with the expected message format and colour for a few synthetic results.
- Wrapper: existing
tests/test_guard_benchmark.pyassertions still pass. - Quality gates:
ruff check,ruff format --check,mypy,pytest.
Documentation
Update docs/BENCHMARK.md with: running on your own validator; the JSON-lines protocol with an example exchange; error semantics; --badge plus an endpoint badge URL pattern; a GitHub Actions snippet shown as a fenced block only (no workflow file added); and the existing publication rule stated explicitly as applying to this repository only, while authors may publish their own numbers. The stable corpus URL goes in once confirmed.
Suggested split
To keep review small, two PRs: (1) corpus + generator + module + built-in adapters + wrapper + drift/reproduction tests; (2) subprocess/Python adapters, badge, Node example, docs. The issue permits a single PR; this is only a suggestion.
Open questions
- Category for multi-code attacks. Some corpus cases list several codes. Use the first code in the case's
codeslist, or a fixed priority order? Cases with no matching category: drop or addother? - Error handling in rates. Exclude errors from denominators (proposed) or count them as failures too? An adapter that errors on everything would otherwise show 0% bypass.
- Restart policy. Restart the subprocess after each timeout (proposed) or abort the run? Restarting is more forgiving but slower for hung adapters.
- Timing. Current
run.pyreports median ms per check. Keep for built-ins only, and for subprocess adapters report round-trip time or omit it? - Python adapter signature.
fn(sql, dialect) -> boolassumed; should it also accept a case id or context? - Corpus URL. Is
docs/assets/corpus-v1.jsonthe intended stable path, and does the Pages config publishdocs/assets/as-is? Should an unversioned alias (corpus.json) exist? - Windows. Is Windows a supported CI target? It affects
shlex.splitquoting in--adapter-cmdexamples. - Badge colours and label text. Confirm the proposed wording and colour thresholds.
Activity
jmmana commentedon Nov 30, 2026
/warcodex proveedor=claude cuenta="Warlock"
jmmana commentedon Nov 30, 2026
WarCodex: encolado, posición 3.
jmmana commentedon Nov 30, 2026
WarCodex: empezó a trabajar en este issue (intento 1).
jmmana commentedon Nov 30, 2026
WarCodex abrió un PR para esta issue: pendiente de revisión.
Base:
main· rama:warcodex/issue-1823 remaining items
jmmana commentedon Nov 30, 2026
WarCodex: empezó a trabajar en este issue (intento 2).
feat: FEAT-006 — Guard benchmark any validator author can run (#182)
jmmana commentedon Nov 30, 2026
WarCodex actualizó el PR #185 con los cambios pedidos (intento #2, vuelta de revisión 1): pendiente de revisión.
Base:
main· rama:warcodex/issue-182jmmana commentedon Nov 30, 2026
WarCodex: PR abierto: #185
FEAT-006 — Guard benchmark any validator author can run (#182) (#185)
jmmana commentedon Nov 30, 2026
WarCodex: listo, PR fusionado: #185
jmmana commentedon Nov 30, 2026
Delivered in #185 (merged at 1c982ef). All PR checks and all 8 main workflows green. Verified after the Pages deploy: BENCHMARK page documents
--adapter-cmd, and corpus-v1.json returns HTTP 200.Reproduced locally:
uv run python -m sqlguardllm.benchgives sqlguardllm 0/69 bypasses and 0/34 false positives, keyword list 59/69 and 3/34, first-word 56/69 and 1/34, with a new Errors column (0). Tests in tests/test_bench.py cover the adapter protocol, errors, corpus drift and the badge. No third-party adapters or results were added; the corpus only holds generic cases already in tests/corpus.FEAT-006 — Guard benchmark any validator author can run (#182) (#185)