Skip to content

FEAT-006 — Guard benchmark any validator author can run #182

Done

Description

@jmmana

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 with python -m sqlguardllm.bench. Do not change cli.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 from tests/corpus (the read-only attack codes already used by FEAT-005 — Public benchmark of SQL guards for LLM agents #174) and benchmarks/guards/legitimate.yaml. Fields: version; per case id, 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.py becomes 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:function for Python validators.
  • Output: markdown table, --json, breakdown per category and per dialect, and --badge out.json in the shields.io endpoint format (for example bypass 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.bench reproduces 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-cmd and the Node example; malformed and timed-out answers are counted as errors (the test skips with a clear reason when node is not on PATH).
  • Drift test: the packaged corpus equals a fresh regeneration from the sources.
  • --badge output has the shields.io endpoint fields schemaVersion, label, message and color (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 mypy and uv run pytest green.

Archivos relevantes

  • src/sqlguardllm/bench/ (new), benchmarks/guards/run.py, benchmarks/guards/legitimate.yaml
  • benchmarks/guards/adapters/node-example/ (new), tests/test_guard_benchmark.py
  • docs/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.py already exposes attacks(), legitimate(), ADAPTERS and run(repeats), as tests/test_guard_benchmark.py implies. I have not seen the file and will read it before moving code.
  • A2. Case objects in run.py carry id, dialect and sql. I do not know if they carry a category. The corpus fields are id, kind, category, dialect, sql, so category is probably derived in the generator from the violation codes in tests/corpus/*.yaml, and legitimate cases get no category (or a fixed legitimate).
  • 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 ViolationCode values and the corpus attack selection logic ("read-only codes only", from FEAT-005 — Public benchmark of SQL guards for LLM agents #174) live in run.py today and can be reused unchanged by the generator.

Files to change

New:

  • src/sqlguardllm/bench/__init__.py
  • src/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 from tests/corpus and legitimate.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 with subprocess.Popen and an argv list from shlex.split (never shell=True), stdin/stdout piped. Per case, write {"id","dialect","sql"}\n and read one line with a per-case timeout (--timeout, default 5 s). A reader thread plus queue.get(timeout=...) is portable and avoids select on Windows. Error outcomes: timeout, EOF, invalid JSON, missing or non-boolean accept, or id mismatch. 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, including corpus_version and 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): brightgreen if both are 0 and errors are 0; red if any bypass; yellow otherwise, 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 compare docs/assets/corpus-v1.json to 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.executable that (a) answer malformed JSON, (b) never answer (timeout set low), (c) exit early, (d) answer the wrong id. 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.py assertions 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

  1. Category for multi-code attacks. Some corpus cases list several codes. Use the first code in the case's codes list, or a fixed priority order? Cases with no matching category: drop or add other?
  2. 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.
  3. Restart policy. Restart the subprocess after each timeout (proposed) or abort the run? Restarting is more forgiving but slower for hung adapters.
  4. Timing. Current run.py reports median ms per check. Keep for built-ins only, and for subprocess adapters report round-trip time or omit it?
  5. Python adapter signature. fn(sql, dialect) -> bool assumed; should it also accept a case id or context?
  6. Corpus URL. Is docs/assets/corpus-v1.json the intended stable path, and does the Pages config publish docs/assets/ as-is? Should an unversioned alias (corpus.json) exist?
  7. Windows. Is Windows a supported CI target? It affects shlex.split quoting in --adapter-cmd examples.
  8. Badge colours and label text. Confirm the proposed wording and colour thresholds.

Activity

  1. added
    type:feature
    type:corpus
    area:security
    size:m
    lang:python
    p1
    on Nov 30, 2026
  2. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    /warcodex proveedor=claude cuenta="Warlock"

  3. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: encolado, posición 3.

  4. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: empezó a trabajar en este issue (intento 1).

  5. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex abrió un PR para esta issue: pendiente de revisión.

    Base: main · rama: warcodex/issue-182

  6. 3 remaining items

  7. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: empezó a trabajar en este issue (intento 2).

  8. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    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-182

  9. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: PR abierto: #185

  10. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    WarCodex: listo, PR fusionado: #185

  11. jmmana commented on Nov 30, 2026

    @jmmana
    OwnerAuthor

    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.bench gives 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.

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:securitylang:pythonp1size:mtype:corpustype:featurewarcodex:listo

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions