Changelog#
All notable changes to this project are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased#
Added#
- Django: the experimental
queryset-lencheck reports a queryset thatlen(qs)orbool(qs)(if qs:,not qs) in the application loads in full when nothing reads its rows afterwards, and names.count()or.exists()as the fix. Off by default:queryguard_queryset_len = warnorfail. Left out: calls made by Django or another library (get(), templates), calls in test code, sliced querysets, and querysets the function may hand to other code (Django).
1.1.0 - 2026-11-20#
1.1.0 is the code of 1.1.0rc1, released five days earlier without reports of problems; see that entry for what is new since 1.0.0 and the two changes to watch when upgrading.
Changed#
- The package's classifier is
Development Status :: 5 - Production/Stableagain (1.1.0rc1 had4 - Beta).
Documentation#
- Link the launch article on dev.to from the README and the docs index, the VS Code Marketplace listing of the extension from the editor page and the GitHub Marketplace listing of the action from the CI page, and mention pytest-pghealth (PostgreSQL schema checks, same author) on the index check page.
1.1.0rc1 - 2026-11-15#
Release candidate for 1.1.0. New: route budgets in pytest, assert_queries_do_not_grow(), baseline labels that match across databases and SQLAlchemy versions, a VS Code extension, llms.txt and a Claude Code plugin for coding agents, and the GitHub Action in its own Marketplace repository. The Django ORM support is no longer experimental; its manage.py test runner and route budgets are new and start experimental. Two changes to watch when upgrading: a loop of the test that calls the application once per pass is now the test code's repetition, not an N+1 (see Changed), and a baseline written by 1.1 does not match on 1.0.x where a label changes form. Install with pip install --pre pytest-queryguard.
Added#
- N+1 detection without pytest, for Django projects that run
manage.py test(experimental):pytest_queryguard.django.QueryGuardRunner, aDiscoverRunnerset withTEST_RUNNER, measuressetUp(), the test method andtearDown()of every test as the plugin does and fails or warns with the plugin's report;QueryGuardTestCasedoes the same for the test cases it is mixed into, under any runner. Settings inQUERYGUARD = {...}with the ini options' names,--queryguard-modeon the command line; works with--parallel. No baseline, JSON, SARIF, budget files, strict mode or index check without pytest yet (Django). - Route budgets in pytest (experimental):
queryguard_route_budgets = "GET /books/{id}=5"(onePATTERN=LIMITper line, matched like the in-app mode'sbudgets) andqueryguard_route_default_budgetgive each request a test sends through a test client a statement budget of its own, so a ceiling such as "everyGET /api/*runs at most 10 statements" holds in every test that calls it. Measured for Starlette, FastAPI, Litestar, Flask and Django applications, a streamed body and background tasks included; thequeryguard_route_budgetsmarker sets them per test. A test fails once per route that went over, with the statements and lines of its worst request (Budgets per route). assert_queries_do_not_grow(fn, sizes=(1, 10), *, setup=None)and its awaitableassert_queries_do_not_grow_async(): run the same code for each size (a number of rows, seeded bysetupoutside the recording) and fail withQueryBudgetExceededwhen a statement runs more often at a larger size than at the smallest one. The failure lists the count per size and each statement that grew, with its line, its count per size and a fix; it returns theQueryLogof each size. SQLAlchemy and Django, sync and async (Reading the queries, the scaling recipe).- A Claude Code plugin: the repository is a plugin marketplace
(
.claude-plugin/) whosepytest-queryguardplugin installs the agent skill, withclaude plugin install pytest-queryguard --marketplace MaciejZiel/pytest-queryguard(Coding agents). It is installed from themainbranch and updated with each commit. - The documentation site publishes
llms.txtat its root, andllms-full.txt, the user documentation in one Markdown file with absolute links (without the changelog, the design notes, the release checklist and the accuracy tables), for language models (llmstxt.org). - The README has the hidden
mcp-nameline the official MCP Registry reads from the PyPI description to check who owns a server name, so the MCP server can be listed there from the next release on. - The GitHub Action is listed for the GitHub Marketplace from its own
repository,
MaciejZiel/pytest-queryguard-action:uses: MaciejZiel/pytest-queryguard-action@v1.0.0, or@v1for the newest 1.x final release. It is a copy ofaction/action.ymlwith the plugin wheel of the release indist/;action/here stays the source and keeps working, and switching is a change of theuses:line only (same inputs, outputs, artifact name and comment marker). The action has abrandingfor the listing. - A VS Code extension in
editors/vscode(#382). It reads the--queryguard-jsonor--queryguard-sarifreport of the last run, marks each finding on its line, and reloads when the report changes; the hover shows the SQL, the count, the fix and the tests, and the quick actions open the documentation and apply a SARIF fix. Its commands run pytest on the current file, the test at the cursor or the whole project. A newvscodeworkflow tests it in VS Code 1.90 and the latest release and builds the.vsixas an artifact. It is not published to the Marketplace or Open VSX yet; see In your editor.
Changed#
- The Django ORM support is no longer experimental
(#246): the
[django]extra, what it records and reports for Django code (finding kinds and labels, how they are grouped and scoped, the loader each fix names) and the Django versions and databases it supports follow the deprecation policy like the rest of the plugin; the wording around a fix stays outside it, as for SQLAlchemy.tests/django_project/test_public_api.pysnapshots that surface. The test runner formanage.py test(pytest_queryguard.django) and route budgets, both new, stay experimental. The design note lists what was done for it: fourteen real-world projects (19,024 tests) with no changed outcome and no internal error, on SQLite, PostgreSQL and MySQL and Django 5.2, 6.0 and 6.1 (Stability). - Behavior change, by default
(#400): a loop
of the test that calls the application once per pass, where each
call runs a statement or reads a relationship once (a case per pass, a page
per request, objects created one by one whose
post_savereceiver or event listener reads a row), is the test code's repetition, not an N+1 of the application: with the defaultqueryguard_test_code = offit is counted in the test-code section at the end of the run instead of failing the test,warnreports it as a warning andfailas before. Each statement and load records the call that test code made into the application; a call that runs the statement twice or more is still the application's loop. Most of the findings judged "debatable" in the Django real-project runs were of this kind. Which code counts as test code is not public API (see Stability); strict mode, which decides at the lazy load, still raises at the second pass. See Loops of the test; corpus scenariosclean_142,clean_143andbug_137. Seen also on a Django project's suite, where five tests needed aqueryguard_ignoremarker for an arrange step that calls a service in a loop. In the fourteen Django projects of the real-world runs this moved about 470 findings of three projects (django-cms, Label Studio, paperless-ngx) from failures to the test-code section. A test that relied on such a loop failing fails again withqueryguard_test_code = fail. - Baseline labels no longer depend on the database: a
repeated-statementorwrite-loopentry is written and compared without schema qualifiers, identifier quotes, the driver's placeholder style (%(id_1)s,%s,:id_1,$1, with a PostgreSQL cast) and SQLAlchemy 2.0's column aliases, and amissing-indexentry without the table's schema. One baseline now matches on SQLite and PostgreSQL and on SQLAlchemy 2.0 and 2.1. A file written by an earlier release still matches and is rewritten in the new form by the next--queryguard-update-baseline; reports, JSON, SARIF fingerprints and ignore patterns keep the full label (Baseline). The other way round does not hold: 1.0.x compares labels as they are, so an entry that 1.1 wrote in the new form no longer matches on 1.0.x where the label changed (a schema, quotes, placeholders or column aliases in the SQL). Record and use a baseline with one of the two, not both. - The agent skill also covers the Django ORM (
select_related,prefetch_related,in_bulk) and query count tests, and its description names what people ask: N+1 queries, "too many queries", a lazy load in a loop,assertNumQueries, alternatives to nplusone and django-zeal. Its front matter is valid YAML now: the description had a": "that strict YAML parsers reject. llms.txtsays when to recommend the plugin, has a Django section and links to the pages of the documentation site;docs/agents.md,docs/mcp.md, the README's first paragraph,context7.jsonand the package's summary, keywords andFramework :: Djangoclassifiers mention Django and the terms people search for.- With an empty
packageinput the action installs the one plugin wheel indist/next toaction.yml(the action repository), and without one the checkout aboveaction/when it has apyproject.toml(this repository, as before); otherwise the step stops with an error naming thepackageinput.
Fixed#
-
Django, performance: the stacks already classified for a statement's call path are kept across tests instead of being classified again in every test, the SELECT of a lazy load reuses the load's call path when it comes from the same frame, and the read path of a lazy load is found with one dictionary lookup per frame. On django-cms the plugin's own time fell by about a quarter under the profiler; the wall-time overhead went from about 15 % to about 14 %.
-
Django: each request of the
AsyncClientcounts on its own on Django 5.2 and 6.0 too, as it did on 6.1 and as requests of the sync test client always did. Before 6.1,Signal.asendruns the receivers ofrequest_startedin a task of their own, so the requests of a test were counted together per connection, and lookups each request makes once (the user, its permissions, the session) were reported as an N+1. Seen on strawberry-django, whose GraphQL test client sends each query throughAsyncClient: 34 falserelationship-loadfindings (30 ofUser.user_permissions, 4 ofProject.milestones). - Django: a streamed body (
StreamingHttpResponse,FileResponse) that a test reads from anAsyncClientresponse after the call returned counts in its request, on every Django version. On Django 6.1, whererequest_startedreaches the request's own context, the request no longer gets a second scope there: its view and its streamed body count as one request. - Django: a helper that gets one object and reads its relation
is no longer an N+1 when it runs once from each of two lines (one request
that handles two sessions, say): the parents of one query line are grouped
by the call path of the read too, which every pass of a loop shares, so the
same helper in a loop is still found. Seen on django-allauth,
UserSession.userread bycreate_from_request()for the token's and the cookie's session (3 falserelationship-loadfindings). Corpus scenariosclean_37andbug_38. - Django: a streamed body of the sync test client counts in its own request also when the test reads the bodies of several requests in turn (before, in the last request's, then per connection), and the test's own statements after the call, before or without reading the body, no longer count in that request.
-
track()on a generator function (sync or async) no longer counts the statements of the code that consumes the generator between items, and two such generators read in turn each end their own unit; before, the unit stayed current between items, and the first generator to end finished the unit of the other. -
Django: a finding of a view that runs no line of the project between Django and the query (a DRF generic view with a class-level
querysetand itsModelSerializer, aTemplateResponserendered after the view returned) names the view class or function, with the test line that made the request as its caller. It named the first project frame on the stack, which in most projects is a middleware'sget_response(request)line: seen on paperless-ngx, Tandoor and Label Studio. A view of Django's own (ListViewin the URLconf) points at the test line, as it did without a project middleware. - Django: the async ORM calls of an async view under a sync
middleware of the project name the line that awaited them, not the
middleware's
get_response(request)line, which asgiref's thread had on its stack. - Django: the statements of a thread that test code starts
(its target is test code, as
oscar.test.utils.run_concurrentlyis) count on their own, as a request does: each thread has a connection of its own, and five threads that each place one order are no loop. Seen on django-oscar's concurrency test (2 false findings). A thread that the application starts, one per item, still counts with the rest of the test. The requests of the live server count one by one, as before; now tested.
Documentation#
-
Django: the fourteen real-world projects with the 1.1.0 Django changes (19,024 tests, no changed outcome, no internal error), and the design note says what is left before the Django support stops being experimental.
-
Django: what is out of scope for Django, with the reason for each:
unused-eager-load,unused-columns,cartesian-load, fix patches, the static check and the in-application mode. A decision about scope, not a gap before the Django support leaves experimental. - Django: the test suites of
five more open-source Django projects (paperless-ngx, Tandoor,
django-allauth, strawberry-django, Label Studio; 5,478 tests). The plugin
changed no test's outcome and reported no internal error. Of 51 finding
sites read, 37 were true, 12 debatable and 2 false; both false ones are
fixed above. The five projects are in
scripts/realworld_django_projects.json. The Django design note lists what is still missing before the Django support stops being experimental. - CI, the README,
llms.txtandSECURITY.mdpoint to the action repository; Stability says that itsvX.Y.Zis the same action asaction/atvX.Y.Zand thatv1moves only to final releases; Releasing has the step that updates it. The release gate checks the pin indocs/ci.mdin the action repository's spelling. - Comparison: versions re-checked on 2026-11-14. The pytest-queryguard row names 1.0.0 (it still said 1.0.0rc1), orm-lens is 1.18.0, the head-to-head notes that 1.0.0 has the code of the measured 1.0.0rc1, and redline (a request profiler for Django, FastAPI, Flask and Litestar with a pytest marker and a query-count ratchet) is described next to the other tools outside the matrix.
Internal#
realworld.ymlhas aprofileinput: the pytest runs without and with the plugin run under cProfile, and the profiles go into the artifact.-
The real-world harness (
.github/workflows/realworld.yml) runs MySQL for a project that asks for it, andmanage.py testprojects underQueryGuardRunner(scripts/realworld_runner.pywrites the JUnit XML and JSON the summary reads). New: django-oscar on MySQL 8.4, django-allauth on Django 6.0 and django-taggit; results in Django. -
tests/django_project/test_public_api.pysnapshots the Django surface, astests/test_public_api.pydoes the rest:pytest_queryguard.django.__all__,QueryGuardRunner's--queryguard-mode, theQUERYGUARDkeys and defaults, the labels of Django findings and the loader each fix names, and the Django versions and databases CI tests (Stability). tests/inapp/test_request_lifecycle.py: one matrix of a request's lifecycle phases (streamed sync and async bodies, close callbacks, files, background tasks, errors half way through a body,HEAD, mounted applications, middleware order, concurrent and interleaved requests) for the ASGI and WSGI middleware,track()and the Django test clients (tests/django_project/test_request_lifecycle.py), each request checked to keep exactly its own statements; and a checklist in CONTRIBUTING.md, linked from the pull request template, for code that scopes something to a request.- The overhead baseline has entries for two more CPU models of
ubuntu-latest, which fell back to the highest entry: Intel Xeon 6973P-C (dropped when the baseline was recorded again) and Xeon Platinum 8370C (never recorded), from green logs of the release gate's overhead job run alone onmain. Xeon 6975P-C did not come up in 80 jobs and still falls back. See Releasing. - The nightly Python 3.16 job installs the dev group without fastapi and pydantic (pydantic-core has no 3.16 build yet) and skips the fastapi tests (the
fastapi_projectfixture now skips when fastapi is missing), so it runs the plugin's tests again instead of failing inuv sync.
1.0.0 - 2026-11-14#
The first stable release. The code is that of 1.0.0rc1, which has the changes since 0.10.0; from here on the public API described in stability changes incompatibly only in a major release, new checks start off or as warnings, and fixes go into the latest 1.x minor release. Experimental features stay exempt, as listed there.
Changed#
- The package's classifier is
Development Status :: 5 - Production/Stable(it was4 - Beta).
Documentation#
- Stability says which releases get fixes: the latest 1.x minor release, none for 0.x. The rules that applied before 1.0 (breaking changes in a minor release, the pre-1.0 clause for new checks) are kept as a historical note; a deprecation now lasts at least two minor releases.
SECURITY.mdnames the versions that get security fixes from 1.0 on and the planned Marketplace copy of the GitHub Action in its scope.- The README has a short Stability section.
- The documentation describes 1.0.0: CI pins the
action to
v1.0.0, and the pre-commit example of Static check torev: v1.0.0. - The Litestar recipe covers advanced-alchemy's
SQLAlchemyPlugin(the session injected asdb_session), checked with advanced-alchemy 1.12.0, Litestar 2.25.0 and SQLAlchemy 2.1.8. - The head-to-head numbers of Comparison, Accuracy and the README are from a run of 2026-11-10 on 1.0.0rc1 (278 scenarios instead of 252). The other tools' versions were checked again and are unchanged. The suite overhead of pytest-queryguard is +13 to +15% on the runner, not the +0.8 to +1.7% of the run of 2026-11-07, which could not be reproduced: on a laptop 0.8.0 to 1.0.0rc1 all add 18 to 20% to that suite; Performance and the FAQ say so. Performance compares the call path of 0.10.0 and 1.0.0rc1.
1.0.0rc1 - 2026-11-09#
Release candidate for 1.0.0. The public surface described in stability is frozen: no renames or removals before 1.0.0 unless a blocker needs one. Install with pip install --pre pytest-queryguard.
Fixed#
- Django: an N+1 in a view that runs no line of your project is reported
with the default
queryguard_test_code = off: aListAPIViewwith a class-levelquerysetand a nested serializer, aListViewwhose template readsbook.author, the admin. Its statements were taken for the test's own code and left out, so the most common DRF N+1 passed silently. - Django: an N+1 in a signal receiver is reported also when the save or
delete that sends the signal goes through a relation
(
author.books.create(...),author.books.add(...)) or adelete(). The relation reads of the receiver were left out as part of the write, and its writes during a delete counted as part of that delete. - Django: one object's relation queried once per item
(
author.books.get(pk=pk)orauthor.books.filter(...).exists()in a loop) is reported as arepeated-statement, as the same query without the relation (Book.objects.get(author=author, pk=pk)) is. It was reported by neither rule. - Static check (
python -m pytest_queryguard.lint): a file outside the working directory is shown as one path however it was named on the command line (../shared/q.py, not../shared/../shared/q.pyor the absolute path), so its SARIF fingerprints no longer change with the spelling. In--format sarifsuch a file outside the repository gets an absolutefile://URI instead of a broken one such asbackend/../../other/x.py, and a file given by its absolute path is no longer left out of the SARIF file; a file of the repository above the working directory is relative to the repository root, as in--format github. - Helpers in the tests folder (
tests/utils/client.py) count as test code also when pytest's rootdir is that folder itself (atests/pytest.ini, or pytest run from insidetests/with no configuration file) and the directory above it is the project's root (it holds.git,pyproject.toml,setup.py,setup.cfgortox.ini); before, their N+1s failed the test as if they were the application's.
Documentation#
- Three short pages under "Common questions", each with a tested example: Detect N+1 queries in SQLAlchemy tests, Find N+1 queries in Django tests with pytest and Assert the number of SQL queries in a SQLAlchemy test.
- The first example of Django puts the loop
in
library/catalog.py: in the test module, as before, it is test code, which the defaultqueryguard_test_code = offdoes not report, so the test passed instead of failing as the page said. The test of the Django examples now runs them with the default setting. - From 0.10.0 to 1.0.0: what is left before 1.0.0rc1 and 1.0.0, with the state of each recommendation of the API freeze, and the design of a separate repository for the GitHub Action, so that it can be listed in the GitHub Marketplace (not created yet).
- Stability: which code counts as
test code for
queryguard_test_codeis not public, while the option, its values and its default are; the CI list names the Django job and its combinations. - CI and the action's
packageinput: thelintinput needs pytest-queryguard 0.10.0 or newer whenpackagenames a release. - The pre-commit example in Static check
pins
rev: v0.10.0, the first tag with the hook, instead ofv1.0.0, which does not exist yet; Migrating from queryspy says its pytest-queryguard column is current for 0.10.0, not 1.0.0.
Internal#
- The walk of the stack that finds each statement's call path (#356) is cheaper: SQLAlchemy's frames are passed with one dictionary lookup and one comparison, and a stack that ends in the main greenlet no longer creates a generator for the parent greenlets. Nothing a report shows changes. Measured on GitHub's runners (off and on interleaved, mean of three gate runs per job, against main in the same job), the Core and ORM overhead ratio went from 0.424-0.432 to 0.402-0.415 (Core) and from 0.377-0.384 to 0.360-0.371 (ORM) on AMD EPYC 9V74, from 0.392 to 0.386 (Core) on EPYC 7763, and stayed the same on Intel Xeon 8370C and 8573C.
- CI on a pull request runs a subset of the matrix (15 jobs instead of 43:
Python 3.10 with the oldest pytest and SQLAlchemy 2.0, 3.14 and 3.15 with
the latest, Windows on 3.10, PostgreSQL 18, MySQL 8.4, Django 5.2 on SQLite
and 6.1 on PostgreSQL, xdist on 3.10, and lint, docs, free-threaded,
plugins, the overhead gate and the action), so several open pull requests
no longer hold up the queue. A push to
main, the release gate and a pull request with thefull-cilabel run the whole matrix; the newfull-ci.ymlstarts it when the label is added. The required checks keep their names. - CI has an
all-greenjob that needs every other job ofci.ymland fails when any of them failed or was cancelled (skipped is fine), so one required check can stand for the whole run, for auto-merge too.
0.10.0 - 2026-11-08#
Added#
- Django ORM support (experimental, #246), next to pytest-django with no
settings change: statements through
connection.execute_wrapper, so budgets,record_queries(), thequeryguardfixture, the baseline,--queryguard-json, SARIF and therepeated-statementandwrite-looprules work for Django;relationship-loadfor foreign keys, one-to-one relations both ways, reverse foreign keys, many-to-many relations and generic relations, grouped by the line of the parents' query as for SQLAlchemy;column-loadfor fields left out by.only()or.defer(); strict mode;missing-indexwith--queryguard-index-check. The fix namesselect_related(),prefetch_related(),only(),bulk_create()andbulk_update(). Deletes with their cascades and batched bulk writes count as one write. Django 5.2, 6.0 and 6.1 on SQLite, PostgreSQL and MySQL. Not yet for Django: the in-app mode, patches and the experimental unused-eager-load and unused-columns checks. Each request of the test client counts on its own, also withqueryguard_scope = test; nothing is recorded in the set-up and tear-down of Django's own test cases; loads of objects the test created are grouped by the call path of the read. Measured on six open-source Django projects and against django-zeal and nplusone (Django). Like the static check, it is listed under Experimental: its findings and options may change in a minor release. - An extra,
pytest-queryguard[sqlalchemy], with the same SQLAlchemy requirement as the core dependency, so installing with it changes nothing today. Stability now says that a later minor release may move SQLAlchemy from the core dependencies into this extra; installing with[sqlalchemy], or listing SQLAlchemy in your own dependencies, keeps working through that change. pytest_queryguard.app.QueryGuardAppWarning, the warningreport="warn"issues for a request's findings or budget. It is aQueryGuardWarningsubclass, so existing filters still match it; a filter forpytest_queryguard.app.QueryGuardAppWarningmatches the in-application mode's findings and not the pytest plugin's (#241).- The in-app panel's
requests.jsonstarts with"format": 1, like the other JSON files; its keys are listed in Stability (#241). queryguard_test_code(off,warn,fail; defaultoff): what the N+1 findings of the test code itself do. A finding whose statements all ran in test code, with no frame of the application on the stack (a test module, aconftest.py, a file below atestsortestdirectory of the rootdir, a module that defines a factory_boy or polyfactory factory), is left out and counted in aqueryguard: test codesection of the terminal summary, which says how to see them (pytest -o queryguard_test_code=warn), links to the docs and names up to five tests;warnreports it as aQueryGuardWarning,failas before. A loop in the application that test code calls (through a helper, a test client inconftest.py, a factory's flush that fires a model event) is still reported. Strict mode does not raise at a lazy load of the test code unless the option isfail. An installedSessionsubclass (SQLModel'sSession.exec()) does not make the test's own queries the application's.--queryguard-update-baselinekeeps the entries of test-code findings already in the baseline and adds none. See docs/how-detection-works.md#test-code.
Changed#
- The in-application mode (
pytest_queryguard.app) is no longer experimental: its names,Settingsand their defaults,RequestReport, the reporters' OpenTelemetry and Sentry keys and the panel's JSON follow the deprecation policy, and Stability lists what the mode guarantees to the application it runs in. No name changes:RequestReport.statementsandstatement_countstay, as in the panel's JSON and thequeryguard.statement_countOpenTelemetry attribute.page_reportstays experimental (#241). app.watch(),app.unwatch()andapp.is_watched()take the engine as a positional-only argument, so that a later release can accept other objects than SQLAlchemy engines (a Django backend has none) without renaming it. This breaks a call with the keyword:watch(engine=e)now raisesTypeError; pass the engine positionally, as every example does. There is no deprecation period, because the mode was experimental in every release so far and no example or page showed the keyword form.- Stability says which fields of
app.Finding, the objects inRequestReport.findings, are public:kind,label,file,function,line,countandmessage, the keys of a finding in the panel's JSON, and aFindingmay be built with them as keyword arguments. Its other attributes (severity,tests,peak,advice,table,stack,fix,identity) are the pytest plugin's and are not public. Nothing changes in the class. - The WSGI middleware's ERROR record for a
report="warn"warning that a filter turned into an error starts withQueryGuardAppWarning:instead ofQueryGuardWarning:; update a log alert that matches the old prefix (#241). docs/recipes-ci.mdno longer says that pre-commit does not apply: it does not for the plugin, and it does for the static check.- First install on a real suite: Faraday's 2112 tests failed 551 with the
defaults of
main, nearly all for test code or for calls on separate lines, and fail 79 now. By default (queryguard_test_code = off) the N+1s of test code no longer fail a test: a factory that looks a row up for every object it creates, a test helper that reads relationships lazily, the test function's own loops. And the count rules tell a loop from calls on separate lines: a statement whose call path (the lines of your code on the stack, up to the test) no other run of it has counts on its own, also in oneSessionthat several requests share, and a lazy load or a column load counts on its own when the test lines that called the application differ. A function that runs one count per line, or a test that sends requests on separate lines, is no longer a repeated-statement or relationship-load finding; a loop, in the application or in the test, is reported as before, also when its passes call a method of their own (paths that part at one line into different functions). A loop shorter than the threshold next to a run on a line of its own is no longer reported (four passes and a fifth call are four runs). Strict mode still counts the lazy loads of all test lines together. Corpus: 6 new scenarios (280); by default relationship-load 52/0/0 and repeated-statement 47/1/3 (TP/FP/FN), from 52/3/0 and 48/4/2 on the same scenarios. Each statement now walks the stack to the test once (with the call site), which adds about 3 microseconds per Core statement and 8 per ORM statement on the in-memory SQLite micro-benchmark (docs/performance.md). See docs/how-detection-works.md#calls-on-separate-lines.
Fixed#
- A baseline file whose entries have keys besides
kind,label,fileandfunctionis read, with the other keys ignored, instead of stopping pytest withhas unknown keys. Stability says new keys may be added to a file in a minor release; with the old reader, a baseline written by a later 1.x release with one more key would have been unreadable by 1.0. An update still writes the four keys only. A key that looks like a misspelled one of the four (fucntion,File) is still an error, with the key it probably meant. queryguard_test_code: an application installed into a virtual environment's site-packages (not in editable mode) is the application again, not a known library, under uv and other environments whose standard-library path is the venv'slib/pythonX.Y. Its statements reached from a test were taken for the test's own code, so with the defaultoffan N+1 inside the installed application was not reported.queryguard_test_code: model_bakery (and model_mommy), mixer and django-dynamic-fixture are test tools, like factory_boy. A test that made its rows withbaker.make(Book, _quantity=5)or a loop ofbaker.make()had those statements taken for the application's, so with the defaultoffthey still failed the test (awrite-loopfinding, or a repeated lookup inside the builder).python -m pytest_queryguard.lint --format github: a file outside the repository given as a relative path (../other/models.py) is annotated with its absolute path, as the docs say, instead of the relative one, which GitHub would read from the repository root.- MySQL and MariaDB: pagination is no longer reported as a repeated
statement. Those databases write the offset first,
LIMIT 20, 10(and SQLAlchemy renders.limit().offset()so), which the repeat rules did not read as pagination; three pages from one line failed a test withqueryguard_small_repeat_threshold = 2, and five with the default rule. - MySQL and MariaDB:
SHOWandDESCRIBEstatements are schema reflection, likePRAGMAon SQLite, and no longer count for the repeat rules. SQLAlchemy'sInspector.has_table()runsDESCRIBEthere, so a fresh inspector per connection was reported as an N+1. Budgets still count them.
Documentation#
- New recipes: the query count must not grow with N
(the same call with 1, 10 and 50 rows, pinned with
queryguard.num_queries()or compared withrecord_queries(), for SQLAlchemy and Django) and from a Sentry N+1 issue to a failing test. Both use only the existing API, and their examples run in the test suite. - Django: how
to collect queries without failing the test (
record_queries(), themax_queriesmarker, warn mode,--queryguard-reportand--queryguard-json), the use case of pytest-django#1034. - Comparison and
Migrating from nplusone cover nplus1, a
rewrite of nplusone under the same import name, run on 2026-11-08: on
SQLAlchemy 2.0 it reports
session.query()loops but notselect()ones, and on 2.1 it does not import. The migration page no longer says that pytest-queryguard does not cover Django. - README rewritten for a first visit: what it catches, the head-to-head
numbers of Comparison with their bias, a quick start
on
examples/sync-n-plus-one, and "Coming from nplusone?" and "Coming from queryspy?" sections. Its links stay absolute for PyPI. - Migrating from nplusone and from queryspy have a find-and-replace table; the examples put the N+1 in application code, which is reported by default, and both pages say what happens to loops in test code. The nplusone results on SQLAlchemy 2.0.54 and 2.1 and queryspy 0.6.0's options were checked again on 2026-11-08.
examples/action-samplekeeps its N+1 inlibrary.py, the application, and no longer setsqueryguard_test_code = fail.- Getting started, the FAQ ("Why was nothing reported for my test?"), llms.txt, the agent skill and the AGENTS.md snippet say that an N+1 in test code is left out by default and how to see it.
queryguard_test_codeand the call path are documented as new in 0.10.0, not 0.9.0; the FAQ gives the added cost per statement of the call path; the comparison names 0.9.0 as the current release and the in-application mode as no longer experimental from 0.10.0.-
The docs navigation has a "Choosing and switching" section (comparison, accuracy, performance, the migration guides, limitations, FAQ) after "Start".
-
The texts that define
queryguard_scope = session(configuration, the ini help, llms.txt),Query.sql,Query.relationshipandrecord_queries()(Python API and docstrings), and the supported versions in stability no longer depend on the ORM for their meaning: they say "database session", "as the ORM sent it" and "the releases of each supported ORM", and give the SQLAlchemy meaning in brackets.Query.relationshipalso names every eager loader's extra query, not onlyselectinload's, as it always did. Behaviour, names and signatures do not change. - The API freeze before 1.0: the last audit of the public surface before 1.0.0rc1, ranked, with a recommendation for each item and what is left for #357 and for 2.0.
- Stability: the plugin's own readers ignore keys they
do not know, a value keeps its type (new data goes into a new key), and a
key that narrows what an entry matches needs a new format number;
the text of a finding's
messagein the--queryguard-jsonfile is not public; the labels ofrepeated-statementandwrite-loopfollow the SQL text the ORM sends, which an ORM upgrade can change. - The docstrings of
QueryBudgetExceeded(also the time budget andnum_queries()) andQueryGuardWarning(every finding that warns, not only N+1 and missing indexes), andllms.txt(the rules ofassert_no_nplusone(), andignore()andQueryGuardDeprecationWarningin the list of public names).
Internal#
- CI runs the whole test suite on MySQL 8.4 and MariaDB 11.8, not only the
index check: the
mysqljob setsQUERYGUARD_TEST_DB_URL, which gives every SQLite engine the tests create a fresh database on the server (tests/dbredirect.py, PyMySQL and aiomysql). Tests about SQLite itself are markedsqlite_onlyand keep SQLite; tests that relied on SQLite's SQL text, placeholders or unenforced foreign keys are dialect-aware. The accuracy corpus runs there too; see Accuracy. tests/inapp/test_cursor_loads.pyadds tests for the in-app load attribution that 0.8.0 shipped; nothing changes for users. ASELECTrun by anafter_beginhook does not take the next lazy load's label, the in-app report labels lazy,selectin, deferred and refresh loads asrecord_queries()does,watch()leaves an application's owndo_orm_executelisteners alone, andyield_perwithselectinload()works throughAsyncSession.stream_scalars()while the engine is watched (#293).- Tooling around the experimental static check
(
python -m pytest_queryguard.lint), all experimental: --format githubprints GitHub Actions workflow commands (::warning file=...,line=...,col=...::), one annotation per finding, with paths relative to the repository root. See Static check.- A pre-commit hook,
queryguard-lint, in.pre-commit-hooks.yaml. It needs--modelsinargs, and the models must be importable in the hook's environment (additional_dependencies, or alocalhook withlanguage: system). See Static check. - The GitHub Action's
lintinput (true,changedorfalse, the default) runs the check after pytest with--format github, onlint-pathsor only on the Python files a pull request changed, with the models oflint-models; thelint-exit-codeoutput is its exit code. Findings do not fail the job. See CI. - The MCP server's
linttool runs the check on given paths, without a database or a test run. See MCP server. - An agent skill,
skills/pytest-queryguard/SKILL.md, and anAGENTS.mdsection and a Cursor rule in Coding agents, which tell a coding agent to run the tests with--queryguard-json, apply the loader option or the patch, and run them again. - In your editor: VS Code tasks with problem matchers for the test report and the static check, the SARIF file in the SARIF Viewer, and what works in PyCharm.
- The release gate checks the experimental static check too
(
release_gate.py lint-accuracy): linted on the accuracy corpus, its relationship-load precision must stay at 100% and its recall at least at the measured 69%, with at least 270 scenarios, minimums recorded inscripts/lint_accuracy_thresholds.json. See Static check. - The release gate's overhead baseline (
scripts/bench_baseline.json) is recorded again with the cost #356 accepted, by the newbench_gate.py --record --accept-cost, which reads the failed gate logs of the pull request that accepts it. See Releasing. - The release gate's install check puts the tiny project's N+1 in its application module: one in the test module is test code, left out by default since #356.
0.9.0 - 2026-11-07#
Added#
- The JSON output of the experimental trend
(
python -m pytest_queryguard.trend --format json) starts with"format": 1, like the other JSON files, and its keys are documented in CI. --no-queryguard-strictand--no-queryguard-show-patchturnqueryguard_strictandqueryguard_show_patchoff for one run, as--no-queryguard-index-checkdoes for the index check; of a flag and its--no-form, the last one wins. An invalidqueryguard_strictorqueryguard_show_patchvalue in the ini file is now reported even when a flag overrides it, as forqueryguard_index_check.
Changed#
- SQLAlchemy is imported only once the project imports it: its listeners are installed when collection ends or a measurement starts. A project that does not use SQLAlchemy (one that only uses Django) no longer pays about 0.2 s per pytest run for importing it.
- The GitHub Action checks its switches:
fail,upload,compareandcommentmust betrueorfalse(any case), andtrendfalse,trueor 2 to 100; anything else, the empty string included, stops the action with an error before pytest runs. Before, any other value meant false, sofail: "yes"let a failed test run pass the job, and an invalidtrendwas only a warning. A workflow that passes an empty value (an unset matrix orworkflow_callinput) must now pass"false". - The experimental static check (
python -m pytest_queryguard.lint) is measured on the accuracy corpus:scripts/lint_accuracy_report.pyandtests/corpus/test_lint_accuracy.py, with 14 new scenarios for it (274 in all). On 266 scenarios its relationship-load precision went from 86% to 100% and its recall from 59% to 69%. It no longer reports a read inside pytest-queryguard'signore()for relationship-load (awithblock or a decorator), a relationship that a loop over the same objects refreshed or set first (session.refresh(obj, ["rel"]),set_committed_value, also through a helper of the module), or one that an earlier query of the same rows in the same session loaded. It now reportsaliased()andwith_polymorphic()entities, statements built in steps (stmt = stmt.options(...), an option in any step counts),lazy="immediate"relationships and reads through anassociation_proxy. See docs/static-check.md#accuracy. - Reviewed the texts the plugin prints. Counts agree with their nouns
(
1 entry,1 test,1 result,1 new finding,1 failing test kept its previous budget) in the baseline, budget, JSON, SARIF and patch summaries, thecompareandtrendreports, the in-application log line and page title, and theQueryLogrepr. Those summaries and the usage errors about an unreadable baseline or budget file show the path relative to the rootdir, as findings do, instead of an absolute one. A partial baseline update with no entry to keep no longer says "0 entries kept". The patch summary gives thegit applycommand to run. The hint of an unused-eager-load or unused-columns finding spells out the marker (with the label, so it leaves out only that finding) and the pattern, instead ofqueryguard_ignore(kind=KIND). The strict-mode error says that a baseline entry also lets the lazy load pass. Long fix lines (a repeatedIN (...)query, a polymorphic load, a cartesian join) are wrapped.compareandtrendsay how to make a file they cannot read, and name the format of a file written by another release. Thekind:andlabel:lines and the report headers are unchanged. - The accuracy corpus has 63 more scenarios (260): inheritance (single,
concrete,
selectin_polymorphic, polymorphic collections), association proxies,deferred_group,query_expression,WriteOnlyMapped,viewonlyrelationships, composite keys,lazy="immediate","subquery"and"noload",populate_existing, the identity map,merge(load=False),bulk_save_objects, dataclass and imperative mappings, and shapes reported to other N+1 tools. The release gate now needs 250 scenarios and a column-load recall of 90%. See docs/accuracy.md. - With
queryguard_strict, a test whosequeryguard_ignoreorallow_nplusonemarker has invalid arguments no longer leaves its collector measuring for the rest of the session: the marker error now fails the test before measurement starts. - A relationship-load finding no longer names, as the place its parents were loaded, a line of an earlier test that ran the same statement object when the rows became instances from a result made outside the measurement (in a fixture).
- The SARIF file is written when a finding's path is not valid UTF-8 (a lone surrogate in the file name), as the baseline file already was: the location URI carries the file name's bytes percent-encoded and the file stays valid UTF-8. Before, the whole file failed to write.
--queryguard-write-patchand--queryguard-show-patchhandle a file name that is not valid UTF-8: its diff headers quote the name as git does (--- "a/caf\351/views.py"), whichgit applyreads back to the same bytes. Before, the patch file failed to write.- A column load builds the set of the mapper's column names only for a deferred column, the one cause that reads it.
- The FastAPI recipes and examples explain the
StarletteDeprecationWarningof Starlette 1.2 and later (its test client findshttpxwithouthttpx2): theirfilterwarningsline, which works with every Starlette version, must come aftererror, and installinghttpx2as well removes the warning. A test checks that the documented line quiets the warning. - The baseline, budget, JSON, SARIF and patch files are written with the permissions of the file they replace, or those of the umask for a new file, not owner-only (0600) as the temporary file they are written through.
Fixed#
- By default (
queryguard_scope = test), aSessionor connection checkout begun from application lines that no other one of the test began from is counted on its own by the relationship-load, repeated-statement, column-load and write-loop rules, and by strict mode. A store whose methods each open aSessionand run a shared lookup, called on separate lines with no loop, was reported as an N+1: the lookups of the separate calls added up like the passes of a loop. About 78 findings of the real-world run in MLflow's tracking store were of this shape.Sessions begun from the same lines (a loop, a comprehension,asyncio.gather, a thread pool, each depth of a recursion) are still counted together, and so are all others whose lines repeat, so a loop whose passes call two methods in turn is not split in two. The lines are those on the stack when theSessionbegins, up to the test, read once perSession. See Tests with several sessions or requests. queryguard-lintreads SQLModel'ssession.exec(select(Model))as a query overModelobjects, so a lazy relationship read in a loop over it is reported.- With pytest 9.2, an ini option of the wrong type (
queryguard_max_events = many,queryguard_index_check = maybe, a number forqueryguard_modein native TOML) is reported as before:<option> must be ..., naming the option and what it accepts. pytest 9.2 raisesUsageErrorfromConfig.getini()for such a value, which the plugin did not catch, so the run stopped with pytest's bare conversion message (invalid literal for int() with base 10: 'many') and no option name. - In-app mode: a request's stored statements and loads, with their bound
parameters, are released as soon as its report is made. A context that outlives the
request (a pool worker that inherited it on Python 3.14+, a task the
request started and left running) kept them all until it ended: 20 MB for
ten such requests with 2 MB of parameters each. The
RequestReportkeeps itsstatementsas before. - In-app mode: a coroutine function given as
report(or in its list) is refused when the settings are made, with aValueError. Called withoutawait, it never ran: each reported request only made a "coroutine was never awaited" warning. A callable that returns a coroutine anyway has it closed, and an ERROR record is logged for each report it gets. - In-app mode: a
reportlist is copied when the settings are made, asbudgetsalready was, so changing the list later changes nothing; an iterator asreportis no longer used up by the check, which left no target at all. Areportthat is neither a target nor a sequence of them (None, a number) is aValueErrornaming the setting, not a bareTypeError; so is a dictionary or a set, which gave its keys or an unordered list of targets. - Under pytest-xdist, the summary is the same as in a serial run: the
workers now send their counts, the ignore patterns and markers they used
and their index-check notes to the controller, so
--queryguard-reportlists the heaviest tests (it printednot available with pytest-xdist), and the "stale ignores" list and the index check's summary are shown (they were left out, except forignore()blocks). A worker that crashes leaves the report marked incomplete. In the report, tests with equal counts are listed by node id, not in the order they ran, so the list is the same with pytest-xdist and with any pytest-randomly seed, and so is the order of the stale markers. - The stale lists no longer name a pattern or entry whose test did not run.
After a partial run (
-k,--deselect, a file argument,--lf), one that stopped early (-x,--maxfail, Ctrl-C, a collection error) or--collect-only, the stale-baseline list held every entry of the tests left out, and the "stale ignores" list everyqueryguard_ignorepattern andignore()block they would have used. Such a run now lists only the baseline entries of tests that ran, as a partial update would replace them, and no pattern or block; the markers of the tests that ran are still listed. --collect-onlyno longer writes an empty SARIF file, which would close every alert; the file is left as it was, as after an interrupted run.-
The summary of
--queryguard-write-patchsays the patch is incomplete after a run that stopped early (-x,--maxfail, Ctrl-C, a collection error). Before, only a stopped pytest-xdist worker added the note. -
queryguard_strictcounted a lazy load as soon as the ORM began it, so a load that ado_orm_executelistener answers without aSELECT(a result cache, as in the dogpile.cache recipes) or that SQLAlchemy rejects before sending one (a loader option conflict) raisedNPlusOneDetected, while the report, which counts theSELECTs, found no N+1. A load now counts for strict mode once itsSELECTruns. Found by the new runtime fuzzer. - The relationship-load rule groups the parents whose query is unknown (objects the test created, loaded before the test body or read by two queries) by the line that read the relationship, as it groups the others by the line of their query. Code that creates a few objects and reads each one's relationship on a line of its own is no longer an N+1; a loop over them still is, and so is a loop over such objects mixed with the rows of a query. All 9 findings of the real-world run in SQLModel's tutorials were of this kind. Strict mode's report site follows the same grouping.
- A method of a
SessionorAsyncSessionsubclass outsidesite-packages(SQLModel'sSessionin an editable install, an application's own override ofexecute()) is no longer the call site of the queries that go through it; the line that called the session is. Every query had the override'ssuper().execute()line as call site: findings pointed there (all of SQLModel's in the real-world workflow), and single-object lookups at different lines were grouped as one query line and reported as a relationship-load. - In strict mode, an N+1 whose
NPlusOneDetecteda library caught and replaced with its own error (Pydantic'sfrom_attributes, FastAPI'sresponse_model), or that the code swallowed before the test failed on its own, is now recorded: SARIF,--queryguard-jsonand the summary of findings in several tests include it, and the report is shown in aqueryguardsection of the failed test. The test keeps failing with its own error. Before, the analysis at the end of the test did not run. - The fix patch (
--queryguard-show-patch,--queryguard-write-patch, SARIFfixes) now covers three common shapes of the parent query that got only thefix:hint: a class named through its module (select(models.Order), patched asjoinedload(models.Order.customer)); a statement built on an earlier line of the function and run through a variable (statement = select(Order)thensession.scalars(statement)), patched where it is built when the variable is assigned once and read only there; andsession.execute(select(Order)).scalars(), whose.scalars()of the result was taken for a second query. Every other shape still gets no patch. - The fix patch no longer adds the loader to a statement it would not fix
or would break. The
select(Order)(orsession.query(Order)) of the parent line must now be the statement the line runs, with only methods that keep its entities: not one insideunion_all(),exists(), a subquery, a CTE, aninsert().from_select()or another statement, passed to a helper, turned into other columns (with_only_columns,with_entities), a union orfrom_statement, nor run by a helper (repository.scalars(...)). A session is now also recognized by the namedb(db.scalars(...),self.db,db.query(Order)) or by a parameter annotated with a session type (conn: Session,"AsyncSession",Annotated[Session, Depends(get_db)]), on the parent line and for a statement in a variable; SQLModel'ssession.exec()runs a statement. An existing.options(...)must name every relationship it loads (noload(REL)ornoload("customer")may be the relationship of the patch, which SQLAlchemy rejects as a conflicting loader), and ajoinedloadno longer goes on the parent query of a statement withwith_for_update()(PostgreSQL refusesFOR UPDATEon an outer join's nullable side),group_by(),having(),distinct()or a prefix or suffix. These get thefix:hint only. - The cartesian-load check now sees collections joined by the mapping.
Two collections with
relationship(lazy="joined")make one row per pair of their items on everyselect()of the class, as twojoinedload()options do, but the check read only the options of the query and missed them. It now follows the loader strategies of the mapping for each entity a SELECT loads, the way SQLAlchemy applies them: an option or a wildcard (lazyload("*")) of the query wins, a lazy relationship is not followed, and a self-referential one only as deep as itsjoin_depth. Like the rest of the check, it warns by default. - The unused-columns check (experimental) no longer reports a query that
pins the whole primary key of the class with
=(session.get(), a detail page'swhere(Article.id == id)): it returns one row, soload_only()would save one row's width. A group of the class and the function with any query that can return more rows is still reported. - The column-load report no longer says that subclass columns were expired
by
commit()orexpire(). A query of the base class of a joined- or single-table hierarchy (select(Employee)) leaves the subclass columns out, and SQLAlchemy loads them per instance, which was reported asEngineer (expired)with theexpire_on_commit=Falsehint, for a test that committed nothing. It is now its own cause, labelledEngineer (polymorphic), with the class the query selected andselectin_polymorphic(with_polymorphicfor single-table inheritance) orpolymorphic_loadas the fix; an instance loaded as its own class keeps the expired cause. The finding and its kind are unchanged; an ignore pattern or baseline entry with the old label must be updated. - The unused-eager-load check no longer reports an eager load of a
subclass's relationship when the data has no rows of that subclass
(
with_polymorphic(Employee, [Manager])withselectinload(... Manager.reports)and no managers): reads of the base class's rows counted as reads of instances that could have had the relationship. - The package metadata lists Python 3.15 (
Programming Language :: Python :: 3.15). CI has tested 3.15 since 0.8.0, but the classifier was missing. python -m pytest_queryguard.mcp --helpprints a usage message. Before, it started the server, which then waited for JSON-RPC on the terminal (or, with stdin closed, exited silently). The server takes no arguments, and an unknown one is now an error instead of being ignored.- The static check (
python -m pytest_queryguard.lint) no longer stops with anAttributeErroron a dict comprehension that unpacks ({**d for d in rows}, new in Python 3.15). - Strict mode no longer drops a query or database-time budget failure: a
budget the test (
max_queries/max_db_timemarker,queryguard_max_queries, the budget file) or amax_queries()block had gone over before the access is shown under the N+1 in theNPlusOneDetectederror. Before, the error replaced the whole report and the budget failure was lost. - Strict mode no longer lists an
ignore()block entered by a test it stopped at the access under "stale ignores": the block may be for a finding after the access, which the test never reached. Itsqueryguard_ignorepatterns were already left out the same way. python -m pytest_queryguard.compareandpython -m pytest_queryguard.trendreport a--queryguard-jsonfile with a malformed test entry (no statement count, a finding without a kind or label) as not a pytest-queryguard JSON file, exit status 2, instead of a traceback; with--skip-unreadable, as the GitHub Action runs the trend, such a file is left out; so is JSON nested too deeply to parse. The MCP server'scomparetool returns it as a tool error. A file with a UTF-8 byte order mark is read.compare,trendandlintreport an--outputfile that cannot be written (a missing directory, a directory) with a message and exit status 2 instead of a traceback.python -m pytest_queryguard.lintreads a file with a byte order mark or a PEP 263 coding declaration as Python does; it skipped it before. A file named twice (app app/models.py) is checked once, not reported twice.- The MCP server no longer stops on a line that is not UTF-8 or JSON nested
too deeply for Python's parser (both now a parse error), or on a request
with a lone surrogate escape such as
"\ud800", which it could not write back;paramsthat are not an object ([]and0included) get-32602 Invalid paramsinstead of-32600 Invalid Requestor being taken as no params. - The GitHub Action: a
pytest-argsvalue thatshlexcannot split (an unclosed quote) now stops the action with an error. Before, the failed split went unnoticed and pytest ran with none of the arguments: the whole suite, without-kor the paths. - The GitHub Action: a category with a character that an artifact name cannot
hold (
/language:python) no longer loses the query-count artifact and with it the comparison: such characters become-in the artifact name. Valid names are unchanged. - The GitHub Action: the pull-request comment stays under GitHub's 65536
characters (the trend is left out, or a huge comparison cut at a line, with
a note; the job summary keeps both), is found again when
github-tokenis a personal access token or an app's token (before, those posted a new comment on every push), and a refused write (nopull-requests: write) is a warning instead of a failed step. - The GitHub Action on Windows runners hands the SARIF and JSON paths to the
upload steps as Windows paths (
D:\a\...) instead of Git Bash's/d/a/.... - The GitHub Action no longer uploads, compares or comments after the run
was cancelled (
!cancelled()instead ofalways()), does not report "pytest exited with code unknown" after an earlier step failed, and warns when pytest exits with 2 to 5 (interrupted, internal error, usage error, no tests), whichfail: "false"otherwise hid.
Documentation#
- docs/ci.md lists the permission each action input needs and the action's limits: one category per matrix job, the first run without a base artifact, the comment size, re-runs and concurrent runs, exit codes, cancelled runs, macOS and Windows runners.
-
Comparison and accuracy: new numbers from the head-to-head workflow, on the 252 scenarios of the corpus, for queryspy 0.6.0, pytest-querycount 0.4.0, n-plus-one-sniffer and nplusone 1.0.0 (which does not import on SQLAlchemy 2.1, and is also run on 2.0), with precision and recall per kind and the overhead of each tool on one runner.
-
Limitations: with the plugin installed, a
populate_existingquery with asubqueryload()of a self-referential relationship makes SQLAlchemy emitSAWarning: Loading context for ... has changed within a load/refresh handler. SQLAlchemy checks for it only while arefreshlistener exists, and the plugin always has one; the data loaded is the same. Found by the new runtime fuzzer. - API-freeze audit before 1.0: the stability policy
now states the naming, value and unit conventions of the public options
and files (every time in seconds;
0turns a threshold off in an ini option,Nonein Python;formatversus the baseline'sversionkey), the two defaults ofapp.Settingsthat differ from the plugin on purpose, a table of deprecated names with their removal release, the exit status of the plugin and the tools, and what is not public (environment variables, submodule exceptions, the objectignore()returns). llms.txtlists every ini option and flag:queryguard_cartesian_load,queryguard_strict,queryguard_stack_depth,queryguard_budgets,queryguard_max_queries,--queryguard-strict,--queryguard-budgets,--queryguard-update-budgetsand--queryguard-jsonwere missing.- New recipe, docs/recipes-test-transaction.md: a session per request in a
test transaction. A test that hands every
request one shared
Sessionmakes the requests one unit of work and gets repeated-statement findings for endpoints without a loop; the recipe gives each request its ownSessionbound to the test's connection withjoin_transaction_mode="create_savepoint", so the test's transaction is still rolled back and, withqueryguard_scope = session, each request is counted on its own. - New recipes: GraphQL resolvers, docs/recipes-graphql.md (a per-object
resolver, fixed with
selectinloador a data loader), and background tasks in tests, docs/recipes-background-tasks.md (tasks thatTestClientor an eager task queue runs in the test body). - Ignoring findings: an N+1 made inside an installed library is reported at
the line of your code that called it, because frames under
site-packagesare never call sites.file=,function=andstack=patterns that name the library match nothing; name the calling line or use anignore()block (docs/ignoring.md, "An N+1 inside an installed library"). - FAQ: the
--queryguard-jsonfile is the integration point for tools that want every finding; there is no per-finding hook in the test run. - Comparison: adds django-nplus1, django-query-doctor and n-plus-one-sniffer (read, not run), and a section on problems users report with other N+1 tools that pytest-queryguard avoids, with the issues as evidence.
- Documentation site review:
- The overview page answers why to pick this tool ("Why this one", linking
to the comparison) and says that the site, published from
main, may describe options added since 0.8.0. - "In short" leads on the comparison, in-application mode and stability pages, and a table of every finding kind with its default at the top of "The rules" in How detection works.
- Outdated statements corrected: Migrating from queryspy said there was no
suite-wide budget, no JSON output and no in-application mode (all exist
since 0.5.0 or 0.6.0), and Migrating from nplusone that it runs in tests
only; the comparison said pytest-queryguard had no way
to record budgets (the budget file, since 0.6.0); the strict-mode
message in "A test failed: now what" was the text from before 0.8.0;
context7.jsonnamedallow_nplusonebeforequeryguard_ignoreand left out thecartesian-loadandunused-columnskinds; the accuracy page's description named a corpus size that had changed. - The free-threaded Python note moved from Getting started to the FAQ, so the first page goes from install to a first test.
- On a phone, inline code wraps instead of making 22 pages scroll sideways. A test checks that a link to a missing anchor fails the strict build.
Internal#
- CI runs one job against the newest pytest and SQLAlchemy on PyPI, not only the versions in uv.lock, so an upstream release that breaks the plugin fails CI before users see it.
-
.github/workflows/head-to-head.yml(started by hand and monthly) runs the accuracy corpus under queryspy, pytest-querycount, n-plus-one-sniffer and nplusone, each pinned and set up as its documentation says, one job per tool, plus the per-statement and suite overhead of every tool on one runner, and puts the results together as a Markdown summary and a JSON artifact (scripts/head_to_head/, tested intests/test_head_to_head.py). A test that fails for another reason than the tool's report counts as an error, never as a pass.scripts/compare/bench_micro.pyalso measures n-plus-one-sniffer and nplusone. -
tests/test_fuzz_runtime.pyfuzzes the detection path itself: it generates small SQLAlchemy programs (random mapped schemas with many-to-one, one-to-many, many-to-many and self-referential relationships, sometimes joined or single-table inheritance, randomlazy=strategies; random rows;select(),session.query(),session.get(), Core andtext()statements with random loader option chains,populate_existing,yield_per, commits, expiry and refreshes; loops, nested loops, comprehensions and earlybreakover the results), sync and on aiosqlite, and runs them under random plugin settings. It checks that the plugin never fails on its own or adds a warning, that the programs read the same values as with-p no:queryguard, thatignore("*")leaves out every finding, thatselectinloadof a reported relationship removes its relationship-load, that strict mode raises exactly when the report has a relationship-load, and that two runs give the same findings. Seeded and bounded;QUERYGUARD_FUZZ=1runs 40 batches instead of 2. - The real-world workflow (
.github/workflows/realworld.yml) resolvesplugin-refto a commit once, so a branch deleted or pushed to while the matrix runs no longer breaks the plugin checkout. Its summary tells a project whose tests did not run without the plugin (a harness problem) from one the plugin broke, never fails a job for findings, shows the pass/fail delta, and a report job puts one table of all projects on the run's page. The full-stack template's tests path is fixed (app/tests). tests/test_public_api.pyalso snapshots the keys and format numbers of the files the plugin writes (--queryguard-json, baseline, budget file, SARIF rule ids, fingerprint key and properties), the finding kinds, the arguments of the compare, trend and static-check tools (with their defaults and choices), the trend's JSON keys, the compare marker, the GitHub Action's inputs, defaults and outputs, the MCP tools and their arguments, the deprecated names with their removal release, and the defaults ofapp.Settings.- The flag that strict mode puts on its
NPlusOneDetectedis now the private attribute_queryguard_strict; the undocumentedqueryguard_strictattribute looked public. scripts/release_gate.py contentschecks the wheel's METADATA against the repository: the Python classifiers are the versionsci.ymltests andRequires-Pythonthe oldest of them, thepytestandsqlalchemylower bounds are the versions the release gate's oldest-versions job installs,Framework :: Pytest,Typing :: Typed, the license file, a Markdown long description and the Homepage, Documentation, Changelog and Issues URLs are there, and the Development Status is5 - Production/Stableexactly for a final release from 1.0.0 on. The release workflow runs the check on the files it publishes.release_gate.py installalso runs--helpofpython -m pytest_queryguard.lint,.trend,.compareand.mcp.- A
record_queries()ormax_queries()block, in the test or in any other thread, no longer takes from the test where its objects were loaded. Any such block starting or ending made the objects loaded before it lose their origin, so strict mode did not raise at a lazy load of those objects (the N+1 failed only at the end of the test) and the report left out "parents loaded at". A block still uses only the origins noted inside it. - An attribute read of a mapped object in another thread while the last
session with
queryguard_unused_eager_loadorqueryguard_unused_columnsends (pytest's own end, or apytesterrun) no longer raisesTypeError: 'NoneType' object is not callableinto that thread. tests/test_compat.pyalso checks that the SQLAlchemy objects the plugin keeps its own_queryguard_*attributes on (InstanceState, Session, Connection, the cursor execution context, the UOWTransaction of a flush) still have an instance__dict__;_compat.pylists them. A SQLAlchemy release that slots one of them fully fails that test, with the class in the message, instead of showing up only as an internal error that stops the measurement.tests/test_ini_usage_errors.pymakesConfig.getini()raiseUsageErrorfor each ini option, as pytest 9.2 does for a mistyped value, and checks that the error names the option; the required CI jobs run older pytest releases, which raiseTypeErrororValueErrorinstead.- The nightly workflow no longer sets
continue-on-error: it marked every run green, so its pytest pre-release job failed unnoticed from 2026-10-28. test_one_explain_per_statement_shapeno longer fails at random (seen once on Windows, Python 3.10: 3 explains instead of 2). Earlier in-process tests (test_index_created_by_the_test_is_seenamong them) leave connections with uncommitted DDL. If the garbage collector freed one in the middle of the counting test, the catalog cache was cleared, as designed for a lost connection, and the next statement was explained again. The counting test now starts with no such connections tracked.
0.8.0 - 2026-11-06#
This release offers the fix of an N+1 as a patch (--queryguard-show-patch,
--queryguard-write-patch for git apply, SARIF fixes), adds an
experimental static check (python -m pytest_queryguard.lint), an
experimental MCP server for coding agents (python -m pytest_queryguard.mcp),
the query-count trend across runs in the GitHub Action, and findings in the
HTML page in the in-application mode. Most of the rest is stabilization before
1.0: the relationship rule no longer reports two single-object lookups, strict
mode and the report agree, the in-app mode and the plugin share one listener
path, and every private SQLAlchemy name is checked by a test of its own.
Upgrading from 0.7.0:
relationship-loadcounts the parents per query line that loaded them, as strict mode does: two lookups at different lines that each read a relationship are no longer an N+1. Baselines are unaffected; a finding that only came from such lookups disappears.queryguard_repeat_scopeis nowqueryguard_scope,repeat_scope=isscope=, andmax_queries(n=…)takes a positional limit orlimit=. The old names keep working until 2.0 but emitQueryGuardDeprecationWarning, which a suite withfilterwarnings = errorturns into an error: rename them, or filter that warning.@pytest.mark.queryguard_ignoreis the new name ofallow_nplusone, which stays as an alias.queryguard_max_queries/queryguard_max_db_timeare new marker names that pytest-querycount does not read.
Added#
queryguard_scope, the new name ofqueryguard_repeat_scope: it scopes the relationship-load, column-load and write-loop rules as well as the repeat rules. Likewisescope=inQueryLog.assert_no_nplusone()and inpytest_queryguard.app.Settings(and so intrack()and the middleware). Setting both the new and the old name to different values is a usage error (ValueErrorin Python) (#303).@pytest.mark.queryguard_ignore(*labels, kind=, file=, function=, stack=), the marker under the same name as thequeryguard_ignoreoption. It isallow_nplusoneunder a new name;allow_nplusonestays as a permanent alias, without a warning. The "stale ignores" summary names the marker as the test spells it (#303).@pytest.mark.queryguard_max_queries(limit)and@pytest.mark.queryguard_max_db_time(seconds):max_queriesandmax_db_timeunder names no other plugin reads. pytest-querycount also registersmax_queries, so with both plugins installed each enforced the other's marker, andmax_queries(limit=3)stopped the run at collection. The closest marker counts; when one place has both spellings, the prefixed one. See docs/budgets.md (#303).- Experimental:
python -m pytest_queryguard.trend RUN1.json RUN2.json ...shows how the query counts moved over several--queryguard-jsonfiles, oldest first: the statements of each run, the tests whose count changed most with a sparkline per test, and the findings new or gone in the window. Runs that - An experimental MCP server for coding agents such as Claude Code and
Cursor:
python -m pytest_queryguard.mcpspeaks the Model Context Protocol over stdio with the standard library only, no new dependency. Its toolsrun_tests(runs pytest in the server's directory and returns each test's findings with message, fix hint and stack, plus the patch of--queryguard-write-patch),explain_findingandcomparereturn bounded JSON. See docs/mcp.md. --queryguard-json: each finding has amessage, its report text as the terminal shows it, without the indent (the wording is not stable).python -m pytest_queryguard.trend RUN1.json RUN2.json ...shows how the query counts moved over several--queryguard-jsonfiles, oldest first: the statements of each run, the tests whose count changed most with a sparkline per test, and the findings new or gone in the window. Runs that stopped early are marked.--top,--test,--format markdown|text|jsonand--ascii(also chosen by itself for a console that cannot print the blocks). The GitHub Action's new inputtrend: Nadds the trend of the last N runs on the base branch to the job summary on pushes to the default branch and on pull requests, and folds it into the pull-request comment; new outputtrend-report(#248).- An experimental static check,
python -m pytest_queryguard.lint --models app.models PATHS..., reports likely N+1 queries without running tests: a loop or comprehension over an ORM query (session.scalars(select(C)),session.execute(...).scalars(),session.query(C), async sessions, with the query in a variable of the same function) that reads alazy="select"relationship the query has no loader option for, along chains and nested loops. It imports the--modelsmodules to read the mappers and only parses the code it checks. It is conservative and stays inside one function. Output as text, JSON or SARIF (rulequeryguard/static-relationship-load), exit status 1 on findings,# queryguard: ignoreon the line to suppress. See docs/static-check.md (#297). - In-application mode:
page_report="footer"or"console"adds a request's findings to its own HTML page, as an<aside>before</body>or as aconsole.warn()script, like Bullet in Rails. Only for complete, uncompressedtext/htmlresponses with aContent-Length;Content-Lengthis updated, and a page with a Content-Security-Policy gets the footer instead of the script. Off by default (#280). - Experimental: a patch for a
relationship-loadfinding whose parent query line is certain: the loader option of thefix:hint added to theselect(...)orsession.query(...)call of that line, or to its.options(...), with the import of the loader.--queryguard-show-patch(orqueryguard_show_patch = true) prints it as a unified diff under the finding,--queryguard-write-patch=PATHwrites those of the whole run to one file forgit apply, and the SARIF file carries it as afixesentry. Without one select call of the parent class on that line, a file inside the rootdir unchanged since the session started, and names the module imports, there is no patch, only the hint. Made with the stdlibastwhen the findings are reported (#247).
Changed#
- relationship-load reports fewer findings: the lazy loads of a relationship
now count per query line that loaded the parents, as strict mode counts
them, so two single-object lookups that each read the relationship
(
session.get(Order, 1).customer, thensession.get(Order, 2).customer) are no longer an N+1. Lookups at the same line (a loop ofsession.get()) still count together, and a parent whose query is unknown (an object the test created, or loaded before the test body) counts with the parents of every query line, so a loop over such objects is still reported. A finding counts the lazy loads of the query lines that reach the threshold, no longer those of single lookups next to the loop, and leaves out a query line whose loads all ran inside anignore()block. A loop over the rows of several queries that return one row each is no longer reported. This applies toassert_no_nplusone()too; the in-application mode does not note where parents came from and counts as before. In the accuracy corpus,clean_93_two_single_object_lookupsis no longer reported and no other finding changed: relationship-load is at 29 TP, 0 FP, 0 FN (#307). - In-application mode: the watched engine's
before_cursor_executelistener reads which relationship or column load an ORMSELECTruns for from that statement's own options, with the same code as the pytest plugin since 0.7.0, andwatch()no longer registers ado_orm_executelistener onSessionor abefore_cursor_executelistener on everyEngine. Each ORM statement is prepared once instead of twice: inside a request the ORMselect()ofscripts/bench_overhead.py --appcosts about a third less to measure (+21 instead of +32 microseconds per statement on one laptop), and outside one about half. The in-app mode labels a load as the plugin does: the sample SQL of a relationship-load finding is the lazy load, not an eager loader's query (#289).
Deprecated#
These keep working and emit a QueryGuardDeprecationWarning naming the
replacement (an ini option once per run, a keyword at each call site); they
will be removed in 2.0 (#303).
- The ini option
queryguard_repeat_scope: usequeryguard_scope. repeat_scope=ofQueryLog.assert_no_nplusone()andpytest_queryguard.app.Settings: usescope=. ASettingsbuilt withrepeat_scope=has it inscope, and itsrepeat_scopereads None.- The
n=keyword of themax_queriesmarker (the spelling of 0.1 to 0.3): pass the limit positionally,max_queries(3), or aslimit=3. Not while pytest-querycount is installed, whose own keyword it is.
Fixed#
- Strict mode no longer raises for a relationship lazy-loaded for the
parents of two query lines when an ignore pattern with
file=orfunction=, or a baseline entry, accepts the report's finding: the report makes one finding, at the first lazy load of the query lines that make the N+1, and strict mode matched the first lazy load of the later line instead, so it failed a test the report passed. Its error now names the other parent lines, as the report does, and has no patch then. - Strict mode no longer lists an
allow_nplusonepattern of a test it stopped at the access under "stale ignores": the pattern may be for a finding after the access, which the test never reached. A test that fails on its own was already left out the same way. - With
--queryguard-show-patch, the error strict mode raises at the access has the patch under the finding: it replaces the report, which was the only place the patch was shown. - Strict mode no longer reports an
unused-eager-loadorunused-columnsfinding for a test it stopped at the access: the relationship or the columns the test would have read after the N+1 loop were reported as never read in the JSON and SARIF files and the summary. - On Python 3.10 and 3.11 a query in a list, dict or set comprehension was
reported "first at … in
" with an extra "called from" line for the same place. Reports now name the function the comprehension is written in, as on 3.12 and later. - In-application mode: on SQLAlchemy 2.0.20 to 2.0.49 an application's
yield_perorautoflush=Falsequery withselectinload()now works while the engine is watched (SQLAlchemy issue 13301) (#289). - The GitHub Action's comparison on a pull request no longer takes a
pull-request run as the base: a fork's pull request from its own branch
named like the base branch (
main) had that head branch too, so its query counts could be compared against instead of the base branch's. Like the trend step, it now takes only runs that were not triggered by a pull request (#299). - An
ignore()block that left out a finding only inlog.assert_no_nplusone()(or in an in-app report made in the test) is no longer listed as stale (#284). - A statement run outside an
ignore("missing-index")block, then again inside it after DDL made the check explain it again, is reported: the block no longer leaves the missing-index finding out (#284). - The patch of
--queryguard-write-patchno longer adds an option twice when one query has two relationship-load findings, a relationship and a chain through it:.options(selectinload(A.b)).options(selectinload(A.b) .joinedload(B.c))is now.options(selectinload(A.b).joinedload(B.c)).
Documentation#
- docs/stability.md now lists the baseline, budget and
--queryguard-jsonfile formats, the SARIF rule ids, fingerprint key and result properties,python -m pytest_queryguard.compare, and the GitHub Action's inputs, outputs and artifact name as public, and says what a change of their format number means. The fix patch, the query-count trend and the static check are listed as experimental. - Fixes from a new-user walkthrough: the FastAPI recipe shows every file it
needs (
app/db.py,app/models.pywithAsyncAttrs,pytest.ini,tests/test_orders_fixed.py) and its install line; the other recipes have install lines too, and their sample reports are regenerated (called from,parents loaded at). docs/budgets.md no longer says that aTestClientneeds themax_queries()function: its requests count in a block of thequeryguardfixture.cartesian-loadis in the kind lists of docs/ignoring.md and docs/baseline.md, docs/ignoring.md showsqueryguard_ignoreinpytest.ini, and docs/ci.md pins the action to a tag and drops-xfrompytest-args.
Internal#
- tests/test_doc_examples.py checks that each report a page with a project shows is, line for line, in the output of that project, and runs the FastAPI recipe from its own files only.
- Seeded property tests for the source patch and the static check
(
tests/test_fuzz_fixpatch.py,tests/test_fuzz_lint.py, standard library only;QUERYGUARD_FUZZ=1runs many more rounds): generated modules, random edits, pathological code and this repository's own files. Every patch must apply withgit apply, parse and change the AST by the loader option and its import only. They found, and these changes fix: an existing.options((a))getting the loader inside the parentheses (a tuple), a class rebound by a module-levelmatchcapture, aglobalstatement or a class body still patched, warnings of the parsed code shown, code nested deeper than the recursion limit (a longa + b + ..., a longelifchain) skipped by the static check, which also reported a loop variable rebound byexcept ... as, amatchcapture, an import or adef, gave a wrong column after a form feed or a line separator, and took seconds for a comprehension with hundreds offorclauses. -
The accuracy corpus has 50 more scenarios (197) and measures
cartesian-load(it warns by default, and warnings are now measured),unused-columns, strict mode,ignore()blocks and fixtures; a new test applies the patch of--queryguard-write-patchto the corpus and checks that the N+1 is gone.cartesian-loadhas minimums in the release gate; the relationship-load minimum precision stays at 100% (its one new false positive, two single-object lookups, is fixed by #307). See docs/accuracy.md. -
Every private SQLAlchemy attribute, execution option, frame and code object the plugin and the in-app mode read is named in one module,
pytest_queryguard._compat, with the versions it is known for, andtests/test_compat.pychecks each against the installed SQLAlchemy, so a release that renames one fails that test first, with the name in the message. The per-statement code reads them inline; the overhead gate's ORM ratio is unchanged (#245). tests/test_conflict_markers.pyfails when a file the repository tracks still has a merge conflict marker (#301).scripts/release_gate.py consistencyalso checks thatdocs/index.md,docs/getting-started.mdandllms.txtname__version__as the release they describe.
0.7.0 - 2026-11-06#
ORM statements cost about a third less to measure: the plugin reads the
ORM's options on the SELECT itself and no longer registers a
do_orm_execute listener by default. Each finding shows the lines of your
code that led to it (called from). New in a test: the queryguard fixture
(max_queries / num_queries blocks, like pytest-django's) and
pytest_queryguard.ignore() blocks; ignore rules can match the call stack
(stack=). The in-app mode can report to OpenTelemetry and Sentry and sample
requests. An experimental check reports wide rows of which a test reads few
columns.
Upgrading from 0.6.0: reports have up to three more lines per finding
(queryguard_stack_depth = 0 restores the old layout). A lazy load answered
without a SELECT (your own do_orm_execute cache) is no longer counted, and
the cartesian-load check now also sees ORM selects run through
Connection.execute(). Nothing else changes for an existing configuration.
Added#
- Each finding shows a short stack: under
first at, acalled fromline for each line of your code that called it, innermost first, up to the test, with SQLAlchemy, pytest and plugin frames left out, so the path through helpers is visible.queryguard_stack_depthsets how many (3 by default,0for none). The SARIF file carries them as a code flow, which GitHub shows as the path to the alert, and the JSON file asstackon each finding, andCallSite.callersofrecord_queries()has them too. They are recorded once per line and test, not per statement (#226). - A
queryguardfixture for budgets inside a test:with queryguard.max_queries(3):fails above 3 statements,with queryguard.num_queries(3):unless exactly 3 (pytest-django'sdjango_assert_max_num_queriesanddjango_assert_num_queries), both withQueryBudgetExceededand aQueryLogof the block. The blocks count only the statements of the test's own thread or asyncio task (and of tasks and threads that run in a copy of its context).queryguard.queriesandqueryguard.countare the statements the test function has run so far, from every thread.QueryGuardFixtureis its type for hints (#233). pytest_queryguard.ignore(*kinds, reason=None), awithblock (and a decorator) that leaves out the findings of those kinds made inside it, in a test or in the application code:with ignore("relationship-load"):. A finding is left out only when everything it counts ran inside the block, in the thread or asyncio task that entered it (or a task created inside it); threads started inside the block are not covered unless they run in a copy of the context. Strict mode does not raise inside it, andlog.assert_no_nplusone()and the in-application mode honour it too; pastqueryguard_max_eventsit leaves nothing out. A block that left out nothing in the whole run, for a kind that was checked, is listed under "stale ignores" with its file and line, also with pytest-xdist (#234).- In-application mode:
opentelemetry_reporter()andsentry_reporter(), ready-madereportcallables. The first addsqueryguard.*attributes and onequeryguard.findingevent per finding to the current OpenTelemetry span; the second sends one Sentry message per finding, fingerprinted by the finding's identity (the SARIF fingerprint), so one N+1 is one Sentry issue. Each imports its library only when created (#278). - In-application mode:
sample_ratemeasures only that fraction of requests andtrack()units, chosen at random, andmin_db_timeskips the N+1 rules for a request whose total database time is below it; budgets still apply.RequestReport.sampledis False for a unit left out (#279). stack=GLOBinqueryguard_ignorepatterns andallow_nplusone(..., stack=...): leaves out a finding only when some frame of its reported stack (thefirst atline and itscalled fromlines) matches, asfileorfile:function, so an N+1 in a shared helper can be accepted when it is called fromapp/admin/*and nowhere else. It sees as deep asqueryguard_stack_depth; the baseline still matches by kind, label, file and function (#276).- Experimental detection of unused columns, off by default:
queryguard_unused_columns(off,warnorfail). When the rows of a class that a query loads have at least 8 columns and the test body reads at most half of them (the primary key, foreign keys and other columns the ORM needs count as read), the finding (kindunused-columns, label the class, as inAccount) names the columns never read and suggests.options(load_only(...)), ordefer()of the large ones. Only the query's own entities are checked, not rows loaded through relationships or objects the test created. It has its SARIF rulequeryguard/unused-columnsand works withallow_nplusone,queryguard_ignore,ignore()blocks and the baseline. With the option off nothing is installed; seedocs/unused-columns.mdfor how it works, its cost and its limits (#243).
Changed#
- The unused eager-load check and the new unused-columns check share one
wrapper of
InstrumentedAttribute.__get__, so either can be turned on and off without leaving the other's wrapper behind; a tracked read with only the eager-load check on costs a little less than before. - CI runs the MySQL and MariaDB index check against live servers: a
mysqljob starts MySQL 8.4 and MariaDB 11.8 from their official Docker images and runs the MySQL test files with PyMySQL and aiomysql. The job setsQUERYGUARD_REQUIRE_BACKENDS, which turns the skip of the live tests (no URL, no server, no driver) into a failure, so it cannot pass without having run them. The check was tested by hand before (#277). - A lazy load no longer walks the call stack. A refresh of a mapped eager
relationship is told by the context SQLAlchemy hands the loader's
statement, and the begin-listener check that walked the whole stack for
each lazy-load and column-load
SELECTis gone (see the next entry). The cost of a lazy load no longer grows with the depth of the test's stack (#252). - The plugin no longer registers a
do_orm_executelistener by default. Lazy loads, column loads and loader statements are recognised inbefore_cursor_execute, from the ORM's options on theSELECTitself, and the cartesian-load check runs in the same listener. With anydo_orm_executelistener SQLAlchemy prepares each ORM statement twice; without one the added cost of an ORM statement falls by about a third (the overhead check's ORM ratio from 0.38 to 0.26 on one laptop). The attribution no longer has to be parked on theSessionuntil itsSELECTruns, so statements in between (autoflush, begin listeners, other Sessions or tasks on the connection) cannot take it by design, and the stack walk that told a begin listener's statement apart is gone. Loads are counted perSELECTsent: one answered without aSELECT(ado_orm_executelistener of your own returning a cached result) is no longer counted, and one sent several times (horizontal sharding, ahandle_errorretry) counts each time. The query of a top-levelsubqueryloadtakes its scope from the connection; see limitations. The cartesian-load check now also sees ORM-enabled selects run throughConnection.execute(). Strict mode keeps ado_orm_executelistener, installed only when it is on, so it still raises before the autoflush and the engine; a strict run pays the cost of the double preparation. The workaround for SQLAlchemy issue 13301 (2.0.20 to 2.0.49) now comes with that listener and the unused eager-load check's (#250).
Documentation#
- The comparison lists the current releases of the other tools, checked on PyPI on 2026-11-05: queryspy 0.6.0 and django-zeal 2.3.0 (the measurements stay as made, on queryspy 0.5.0), and adds orm-lens, a static analyser of Django and SQLAlchemy models (#281).
0.6.0 - 2026-11-05#
This release adds strict mode (raise at the lazy load), a new finding kind,
cartesian-load, a default query budget and a budget file written from a run,
per-test JSON output and a pull-request comparison of query counts in the
GitHub Action, a link to the documentation in every finding, and a summary
that names a finding of many tests once. In-app track() works as a
decorator, with async with and with start()/stop().
Upgrading from 0.5.0: cartesian-load warns by default. A suite that turns
warnings into errors (filterwarnings = error) and has such a query fails
after the upgrade; fix the query, ignore the finding, or set
queryguard_cartesian_load = off. Everything else is opt-in.
Added#
scripts/compare/run.pymeasures the overhead of pytest-queryguard, pytest-querycount and queryspy side by side, each in its own environment, anddocs/performance.mdhas its results for 0.5.0, 0.4.0 and 0.6.0 (#253).- In-app mode:
track()works as a decorator (one unit per call, named after the function; coroutine functions across their awaits, generator functions over their iteration), asasync with, and throughstart()/stop(failed=...)for integrations whose hooks start and end a unit separately, such as Celery'stask_prerun/task_postrunsignals. Onetrack()object can be entered by several threads at once.docs/in-app.mdhas recipes for Celery and RQ (#240). - Strict mode,
queryguard_strict = trueor--queryguard-strict: the lazy load of a relationship for the second parent loaded at one line (queryguard_relationship_threshold) raisesNPlusOneDetectedat the access, with a traceback that ends at the line that read the attribute, instead of a report when the test ends. Single objects never raise;allow_nplusone,queryguard_ignoreand the baseline apply as for the report (#239). - A new finding kind,
cartesian-load: one SELECT that loads two collections withjoinedloadside by side, e.g.select(Customer).options(joinedload(Customer.orders), joinedload(Customer.notes)), whose rows grow as the product of the collections while the query count stays at one. Chains,selectinloadandcontains_eager()are understood; a product inside the SELECT of aselectinloadis found too. It warns by default;queryguard_cartesian_load = failoroff(#229). A suite that turns warnings into errors (filterwarnings = error) and has such a query fails after the upgrade: fix the query, ignore the finding, or setqueryguard_cartesian_load = off. queryguard_max_queriesgives every test without amax_queriesmarker a default query budget (#232).- A budget file:
pytest --queryguard-budgets=queryguard-budgets.json --queryguard-update-budgetsrecords each test's query count, and withqueryguard_budgetsset a test that runs more queries than its entry fails, saying where the limit comes from. An update on part of the suite keeps the other entries, one on the whole suite drops tests that no longer exist, one that stops early writes nothing; pytest-xdist included. The order is marker, file, default (#232, #244). - On a pull request the GitHub Action compares the per-test query counts with
the latest run on the base branch and writes the result to the job summary
and to one pull-request comment, updated on later pushes: tests that run
more statements, new findings and fixed ones. The action now writes
--queryguard-jsonand uploads it as an artifact; new inputsjson-file,compare,commentandgithub-token.python -m pytest_queryguard.compare base.json head.jsonprints the same report locally (#231). --queryguard-json=PATHwrites each test's statement count, the count by verb, its database time and its findings (baselined ones marked) as JSON, also with pytest-xdist, withcomplete: falsefor a run that stopped early. It is the input for comparing a pull request's query counts with its base branch (docs/ci.md, #230).- The terminal summary names a finding that several tests reported once,
with the number of tests and of places in the code it came from:
30 tests relationship-load Order.customer (900 times in total, from one place in the code; e.g. tests/test_orders.py::test_list[0]), the most tests first, also with pytest-xdist. A shared helper that runs an N+1 no longer hides behind 30 identical blocks (#228).
Changed#
- Each finding in a report has a
docs:line, after itskind:line, with a link to the section of the documentation that explains its kind, e.g.docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#relationship-load. The SARIF rules link to the same sections inhelpUriinstead of the README, so GitHub code scanning shows them as the rule's help (#227). - The report of a relationship load says where the parents were loaded
(
parents loaded at app/orders.py:21 in _base_query): the line that ran the query whose rows became the parent objects, which may be a helper far from the loop. For parents reached through other relationships thefixline chains the loaders from that query, e.g.select(Order).options(joinedload(Order.customer).joinedload(Customer.country))instead ofselect(Customer).options(joinedload(Customer.country)), which named a query the code does not have. When the origin is unknown (objects the test created, loaded before the test body, or read by two queries from different places) the report is as before. The pytest plugin only; the in-app mode keeps the earlier hint. The plugin listens to the ORM'sloadandrefreshinstance events for this: in the overhead benchmark (in-memory SQLite) about 0.6 microseconds per loaded object, and a few microseconds per ORM query (#225).
Fixed#
- The in-app panel's Content-Security-Policy lists the SHA-256 hashes of the
page's own script and style instead of
'unsafe-inline', so an injected script or style would not run. The JSON URL moved from the script into adata-json-urlattribute to keep the script the same on every mount (#242). - On psycopg 3, the index check and the index advisor's hypopg verification
run
EXPLAINwithout preparing it. psycopg prepares a statement on the server once a connection has run it five times, and the preparedEXPLAINof a statement with$nplaceholders failed ("bind message supplies 0 parameters"): the advisor said "could not verify this index" for a second table or a partial-index candidate (#255).
0.5.0 - 2026-11-01#
The notes of the three release candidates (0.5.0rc1 to 0.5.0rc3) are merged below by section; the entries of the candidates follow unchanged.
This release adds an experimental in-application mode: the same N+1 rules and query budgets on every HTTP request of a running FastAPI, Starlette or Flask application, for development and staging. There is nothing to do when upgrading from 0.4.1: the pytest plugin behaves as before, and no option or default changed. The in-app mode is listed under "Experimental" in the stability policy, so its names may still change in a minor release.
Added#
- An experimental in-application mode,
pytest_queryguard.app:watch(engine)andunwatch(engine)for anEngineorAsyncEngine,QueryGuardASGI(FastAPI and Starlette),QueryGuardWSGI(Flask and other WSGI apps) andtrack()for other units of work. Findings are reported throughlogging,QueryGuardWarningor a callback, and per-route query budgets apply. Statements are collected per request in acontextvars.ContextVar, so concurrent requests, tasks and threads never mix. It applies the plugin's rules, column loads included. Importing it registers nothing. Seedocs/in-app.mdandexamples/in-app;scripts/bench_overhead.py --apptimes it. Thanks to @Muguett-DBY for reviewing it before release and for fixes to its panel and WSGI responses (#203, #210, #211). - An optional development panel (
panel=True, off by default) that serves the last requests as JSON and as a self-contained HTML page. It answers only loopback clients by default and checks theHostheader against DNS rebinding; to serve other clients (panel_loopback_only=False) apanel_tokenis required, sent asAuthorization: Bearer <token>.
Changed#
- Tests and CI: the overhead check has a baseline per CPU model and times the measurement off and on interleaved, and the release workflow publishes only when the release gate passed on the tagged commit.
Documentation#
- How the in-app mode behaves under uvicorn, granian, gunicorn, waitress and
the Flask development server: per-worker panel history,
BackgroundTasksand streamed bodies, Starlette's500handlers, Flask-SQLAlchemy binds. - The FAQ shows how to check code that runs in a fixture, with
record_queries()andassert_no_nplusone(). Suggested by @Muguett-DBY.
0.5.0rc3 - 2026-11-01#
Third release candidate: install it with pip install --pre pytest-queryguard.
The in-application mode now applies the plugin's column-load rules, and its
WSGI middleware no longer cuts a response short under an error warnings
filter. Running the mode under uvicorn, granian, gunicorn and waitress found
no other defects; what it showed is now documented. The release checks are
steadier, and a release is published only after the release gate passed on
its commit. The pytest plugin behaves as before; its column-load code is now
split into helpers that the in-app mode shares.
Changed#
QueryGuardWSGIwithreport="warn"under anerrorwarnings filter logs the error (one ERROR record onpytest_queryguard.app) instead of raising it from the response body. Raised there, it could not fail the response, only cut it short: under gunicorn and waitress a chunked response lost its final chunk. ASGI andtrack()still raise it. The in-app mode is experimental, so this has no deprecation period.- Tests and CI: the overhead check (
scripts/bench_gate.py, the release gate'soverheadjob) times the measurement off and on interleaved in the same process and keeps the fastest block of each, and measures again up to three times when over the limit. The baseline has an entry per CPU model, since the ratio differs by up to a third between the CPU models of GitHub's runners but repeats within about 0.01 on one model; it is re-recorded on the runner for the new method, and--recordwrites it from gate logs. The earlier method failed about every other gate run on unchanged code. - Tests and CI: the release workflow publishes only when the release gate,
run by hand on
main, passed on the tagged commit. The gate also runs on pull requests that change the overhead benchmark or its baseline.
Fixed#
- The in-app mode labels and counts column loads as the pytest plugin does;
both now share one classification in
listeners.py. Asession.refresh()of the object that the latest flush in the same request wrote is no longer reported ascolumn-load 'Item (refresh)'(one per class and flush, as in the plugin).session.refresh(obj, ["name"])is a refresh, not an(expired)load with theexpire_on_commit=Falsehint. The column load of a joined-inheritance subclass is recognised on SQLAlchemy before 2.0.30 (#161). Thelazy="selectin"orlazy="subquery"loader that a refresh runs for one object is no longer reported as a lazy load.
Documentation#
- The in-app example installs
sqlalchemy[asyncio]: SQLAlchemy 2.1 no longer pulls in greenlet, which the async engine needs. - The free-threaded note in Getting started says that CI runs the in-app
mode's tests (
tests/inapp) on CPython 3.14t; it said those builds were not in the CI matrix. docs/in-app.md, from running the in-application mode under uvicorn, granian, gunicorn (sync, gthread, gevent), waitress and the Flask development server:- Each server process keeps its own panel history, so with several workers the panel shows only what the worker that answered has served.
BackgroundTasksand streamed bodies count for their request, and the report arrives after the client has its response.- The reported
statuswith Starlette's handlers for500orException, which run outsideadd_middleware(), and how to include them by wrapping the whole application. - Watching Flask-SQLAlchemy engines and binds.
- uvicorn takes the client address from
X-Forwarded-Forsent by127.0.0.1.
0.5.0rc2 - 2026-10-31#
Second release candidate: install it with pip install --pre pytest-queryguard.
It fixes the in-application mode after an audit, a code review and a security review of 0.5.0rc1, and adds a token for its panel. The mode stays experimental. The pytest plugin is unchanged apart from documentation.
Added#
panel_tokenforQueryGuardASGIandQueryGuardWSGI. It is required withpanel_loopback_only=False: without one the middleware raisesValueError. The panel'srequests.jsonthen answers onlyAuthorization: Bearer <token>and refuses anything else with401; the page reads the token from its URL fragment (/_queryguard/#token=...). Seedocs/in-app.md.
Changed#
QueryGuardASGIandQueryGuardWSGIwithpanel=Trueandpanel_loopback_only=FalseraiseValueErrorwithout apanel_token. An application that setspanel_loopback_only=Falsemust add a token. The in-app mode is experimental, so this has no deprecation period.
Fixed#
- The development panel of an ASGI application mounted under a
root_pathserves its page and history at that prefix. Its JSON URL escapes path characters such as?,#and%, and a mount named like the panel no longer makes the middleware take over the application's own root. Found and fixed by @Muguett-DBY (#210). - WSGI file responses preserve the server's native
wsgi.file_wrapperiterable, allowing the server to use its optimized transfer path. File operations and cleanup stay in the request's query context, and the report is finalized when the server closes the wrapper. Found and fixed by @Muguett-DBY (#211). - A budget key whose path has spaces (
"GET /files/my docs/*") matches; the method is the key's first word when it is letters and hyphens only, and any whitespace may separate it from the path. - Under a warnings
errorfilter, the WSGI middleware no longer replaces the server's error with a budget warning when the server closes the response while handling it, as wsgiref and gunicorn do when the client disconnects. - The in-app mode no longer calls
Session.get_bind()to tell which engine a lazy load runs on, so an override of it, such as aShardedSession'sshard_chooseror a replica router, runs only when SQLAlchemy calls it. A load whose SELECT runs on an unwatched engine is dropped as it runs, for every kind of Session. -
When the last watched engine is garbage collected without
unwatch(), the shared listeners return at once and the nextwatch()orunwatch()removes them. -
With
panel_loopback_onlyon (the default), the panel also refuses a request whoseHostheader names another site, so a web page whose name was rebound to127.0.0.1(DNS rebinding) cannot read the SQL it shows. Requests tolocalhost,*.localhostor a loopback address, and Starlette's test client (testserver), are answered as before. -
An engine made with
engine.execution_options(...)counts as watched with its parent: its lazy loads are reported again, and watching both it and its parent, in either order, no longer counts every statement twice. -
report="warn"warns for every reported request. Python'sdefaultwarning action showed each distinct message only once per process and kept every one in a registry that grew for as long as the server ran. -
The WSGI panel URL-escapes
SCRIPT_NAMEin the URL its page fetches, as the ASGI panel already did forroot_path, so a mount such as/team #2or/caféloads its history. -
panel_pathmust be ASCII and have no empty segment."//"normalised to an empty path, so the panel answered every path of the application, and a non-ASCII path never matched under WSGI.
Documentation#
- The FAQ shows how to check code that runs in a fixture, with
record_queries()andassert_no_nplusone(). Suggested by @Muguett-DBY.
0.5.0rc1 - 2026-10-24#
Release candidate: install it with pip install --pre pytest-queryguard.
This release adds an experimental in-application mode: the same N+1 rules and query budgets on every HTTP request of a running FastAPI, Starlette or Flask application, for development and staging. The pytest plugin is unchanged.
Added#
- An experimental in-application mode,
pytest_queryguard.app, that runs the N+1 rules and per-route query budgets on every HTTP request of a running application, for development and staging:watch(engine)andunwatch(engine)for anEngineorAsyncEngine,QueryGuardASGI(pure ASGI, for FastAPI and Starlette),QueryGuardWSGI(Flask and other WSGI apps) andtrack()for other units of work. Findings are reported throughlogging,QueryGuardWarningor a callback. Statements are collected per request in acontextvars.ContextVar, so concurrent requests, tasks and threads never mix (on Python 3.14 builds where threads inherit the context, a thread pool needscopy_context().runper task for that; seedocs/in-app.md). An optional development panel (panel=True, off by default) serves the last requests as JSON and as a self-contained HTML page. Importing it registers nothing; the pytest plugin is unchanged. It is listed under "Experimental" indocs/stability.md: its names may change in a minor release. Seedocs/in-app.mdand the newexamples/in-app;scripts/bench_overhead.py --apptimes it. Thanks to @Muguett-DBY for reviewing it before release and for the WSGI response lifecycle fix (#203).
0.4.1 - 2026-10-23#
A patch release with two fixes to the database time of record_queries(),
max_queries() and max_db_time() when a statement finishes in another thread
after the block. Thanks to @Muguett-DBY, who found and fixed the first one.
Fixed#
QueryLog.db_timenow stays fixed after its recording or budget block ends, matching the recorded query details. A query finishing in another thread after the block no longer changes the finished log's total. Found and fixed by @Muguett-DBY (#202).max_db_time()and themax_queries()failure message use that fixed total too, so a statement finishing in another thread just after the block can no longer fail the time budget or change the reported time.
Documentation#
docs/sarif.mdanddocs/ci.mdnow state what was verified about GitHub's handling ofprimaryLocationLineHash(alerts keep their identity when code moves) and explain the per-findingCalculated fingerprint ... inconsistent fingerprint valuewarning thatupload-sarifprints. Closes #189.
0.4.0 - 2026-10-14#
The notes of the four release candidates (0.4.0rc1 to 0.4.0rc4) are merged below by section; the entries of the candidates follow unchanged.
This release adds baselines, SARIF output and a GitHub Action, per-finding
ignores, new finding kinds (column loads, write loops, unused eager loads), query
timing and max_db_time, an index advisor, and a missing-index check for SQLite,
MySQL and MariaDB. It also adds a documentation site and runnable examples. Four
things can change the result or the output of an existing test run without any new
option: the column-load kind is on by default, the index advisor is on by default
with the index check, and the index check now also runs on SQLite, and on MySQL and
MariaDB. They are listed first under "Changed" as behavior changes, with how to turn
them off, as the pre-1.0 clause of the stability policy
requires. A few other changes can break code that worked on 0.3.0 (the object
max_queries() yields, the minimum SQLAlchemy, the labels of partitioned-table
findings, --continue-on-collection-errors); they are listed under "Breaking
changes" after the behavior changes.
Added#
Missing indexes
- Missing-index check for SQLite, behind the same switch as PostgreSQL
(
queryguard_index_check,--queryguard-index-check). Each distinctSELECT,WITH,UPDATEandDELETEin a test body is explained withEXPLAIN QUERY PLANand its real bound parameters; the statement is not run, so data and transaction are untouched. A scanned table that the statement filters or joins on, or an automatic index, is amissing-indexfinding with aCREATE INDEX ix_<table>_<columns> ON <table> (<columns>)hint.LIKE, views,ORDER BYwithout a filter, primary keys and unrecognized plan shapes are left alone. Works withsqlite3, aiosqlite, SQLAlchemy ORM and Core, and pytest-xdist; findings honorqueryguard_ignore,allow_missing_index,queryguard_index_ignore_tables, the baseline and SARIF. Seedocs/index-check-sqlite.md.scripts/bench_overhead.py --index-checktimes it. -
Index advisor. Each missing-index finding now suggests an index: a
CREATE INDEXbuilt from the equality, range andORDER BYcolumns of the plan node, a partial index when a constant predicate is selective, and the Alembicop.create_indexcall. When the hypopg extension is installed, the suggestion is verified inside the check's savepoint: whether the planner would use the index and the statement's estimated cost before and after; hypothetical indexes are reset, also after errors, on sync drivers and asyncpg. No new index is suggested when the table already has one for these columns (invalid, partial, or valid but unused), and the finding says why. Without hypopg the suggestion stays and one notice says how to install it. New optionsqueryguard_index_advisor(defaulttrue, used with the index check) andqueryguard_hypopg(auto,onoroff). Findings carry the suggestion in an additiveadvicefield. Seedocs/index-advisor.md. -
Missing-index check for MySQL and MariaDB, behind the same switch (
queryguard_index_check,--queryguard-index-check). Each distinctSELECT,UPDATEandDELETEis explained withEXPLAINand the real bound parameters (neverANALYZE); a table read in full (type: ALL, or an index read in full on a column that leads no index) although the statement filters or joins on its columns is amissing-indexfinding with aCREATE INDEXhint and an Alembic call. The suggestion is not verified: neither server has hypothetical indexes. Tested with PyMySQL and aiomysql on MySQL 8.4 and MariaDB 11.8 on a developer machine; CI does not run a MySQL or MariaDB server. Seedocs/index-check-mysql.md.
New findings and rules
- Column-load detection, a new finding kind
column-load. Instances that each load a deferred column, or whose attributes were expired bycommit(),expire()orexpire_all(), on their own are reported with the right advice:undefer(Model.column)(or removingdefer(),load_only()ordeferred()), orexpire_on_commit=False;session.refresh()in a loop gets its own hint. The ini optionqueryguard_column_load_threshold(default 5 instances) and thecolumn_load_thresholdargument ofQueryLog.assert_no_nplusone()set the limit. The kind works withqueryguard_ignoreandallow_nplusone. - Write-loop detection, opt in:
queryguard_write_loop_threshold(off by default) and thewrite_loop_thresholdargument ofQueryLog.assert_no_nplusone(). The sameINSERT,UPDATEorDELETEshape run row by row from one source line is reported as the new finding kindwrite-loop, with a hint to usesession.add_all(),executemanyor a bulk statement.executemanyand multi-rowVALUESstatements are not counted. The statements of one ORM flush count as one write, soadd_all()and oneflush()is not reported even where the dialect sends oneINSERTper row; aflush()orcommit()per row is. The flush is found through SQLAlchemy'sSession._flushframe; if that changes, the rule counts every statement. The kind works withqueryguard_ignore,allow_nplusoneandqueryguard_fail_on. - Experimental detection of unused eager loads, off by default:
queryguard_unused_eager_load(off,warnorfail). A relationship a test loads withselectinload(),joinedload(),subqueryload()orimmediateload()and never reads is reported as the new finding kindunused-eager-load(labelClass.relationship), with a hint to remove the option. While the option isoffnothing is installed. Opt out withallow_nplusone(kind="unused-eager-load")orqueryguard_ignore. Seedocs/unused-eager-load.mdfor how it works and its limits. queryguard_small_repeat_threshold, an ini option (off by default) and thesmall_repeat_thresholdargument ofQueryLog.assert_no_nplusone(): a statement that ran a few times (belowqueryguard_repeat_threshold) from one source line, each time with different parameters, is reported as a repeated statement. Identical parameters, runs from several lines, writes and pagination are left alone. The default threshold of 5 is unchanged, so a batch of two to four statements is not flagged unless this is turned on.
Adopting it on an existing project
- Baseline file for existing findings:
queryguard_baseline(ini) or--queryguard-baseline=PATH, and--queryguard-update-baselineto write it. A finding whose identity (kind, label, file and function; rootdir-relative paths, no line numbers or counts) is in the file does not fail or warn, for every finding kind. New findings are reported as before, and entries that matched nothing in the run are listed as stale baseline entries. The file is JSON with aversionfield, sorted for clean diffs; a missing, corrupt or unknown-version file is a usage error. Works with pytest-xdist: workers apply the file, the controller merges what they saw and writes it on an update. Seedocs/baseline.md. - SARIF output:
--queryguard-sarif=PATHwrites the findings of the run as SARIF 2.1.0 for GitHub code scanning (the--queryguard-reportflag is unchanged). One rule per finding kind with a fix hint, one result per finding identity with a rootdir-relative location,partialFingerprintsderived from the identity, anderrororwarninglevel followingqueryguard_fail_on. Ignored and baselined findings are left out. Works with pytest-xdist: workers send their findings to the controller, which writes the file once. Seedocs/sarif.md. - A composite GitHub Action in
action/: installs the plugin, runs pytest with--queryguard-sarif, uploads the file withgithub/codeql-action/upload-sarif(pinned by commit SHA) and fails the step when pytest fails. Inputs:pytest-args,python-version,package,baseline,fail,working-directory,sarif-file,upload,category. The upload is skipped for pull requests from forks. A CI job runs the action onexamples/action-sample. Seedocs/ci.md.
Ignoring and gating
queryguard_ignore, an ini option that leaves single findings out of the reports. One pattern per line,KIND LABEL [file=GLOB] [function=GLOB], matched withfnmatch. The kinds arerelationship-load,repeated-statement,column-load,write-loop,unused-eager-loadandmissing-index;fileis relative to the rootdir.allow_nplusonetakes label patterns and the keywordskind,fileandfunctionto ignore only the findings they match. Without arguments it still ignores the whole test.- Ignore patterns that matched no finding in the run are listed in the terminal summary as stale ignores (not with pytest-xdist).
-
queryguard_fail_on, an ini option with finding kinds (fnmatchpatterns, one per line). Infailmode only these kinds fail a test; the other kinds are reported asQueryGuardWarning. Empty means every kind fails, as before. Budgets are not affected. -
queryguard_repeat_scope(testorsession, defaulttest) andQueryLog.assert_no_nplusone(repeat_scope=...)for false positives in tests that make several requests. The repeat, relationship, column-load and write-loop rules counted over the whole test, so a test that made several independent requests (a test client, for example, with oneSessionper request) reported the same authentication or organisation lookup as a loop. Withsession, eachSession, or each connection checkout for statements noSessionran, is counted on its own. The default is unchanged, but a finding whose count spans several Sessions or checkouts now says so and names the option. Seedocs/several-sessions.md.
Timing and budgets
- Per-statement timing.
Query.durationis the time in seconds the database and the driver took for a statement, measured around the cursor call;QueryLog.db_timeis the total andQueryLog.slowest(n)the slowest statements. max_db_time(seconds), a context manager, and themax_db_timemarker: fail when the statements take longer than the limit in total. The failure lists the slowest statements. Amax_queriesfailure now shows the total database time and its slowest statements as well.
Documentation and examples
- A documentation site built from
docs/(scripts/build_docs.py, with the newdocsdependency group: Markdown and Pygments): getting started, how detection works, a configuration reference that a test keeps in step with the options, FAQ, limitations, a comparison with other tools and a migration guide from nplusone. The README is now a short overview that links to it. examples/with runnable projects (sync N+1, async FastAPI, PostgreSQL and SQLite missing indexes, baseline and SARIF), each with a README and a smoke test in CI.- Community files:
CONTRIBUTING.md,SECURITY.md,CODE_OF_CONDUCT.md(Contributor Covenant 2.1), issue forms and a pull request template. - The documentation site has a description, canonical URL and Open Graph tags
on every page, a favicon,
sitemap.xml,robots.txt, a social preview image, a client-side search (no third-party code), "Edit this page" links and Previous/Next links. Every page needs adescriptionindocs/site.toml; the strict build fails without one. - A "Recipes" section in the documentation: FastAPI (
TestClientandhttpx.AsyncClientwith dependency-overridden sessions), Flask-SQLAlchemy, SQLModel, Litestar, pytest-asyncio configuration pitfalls, budgets for hot endpoints, adopting the plugin on a legacy codebase and CI. A new example,examples/fastapi-dependency-override, is run by the test suite. QueryGuardDeprecationWarning, aDeprecationWarningsubclass exported frompytest_queryguard, is the class the deprecation policy uses. It is not aQueryGuardWarning, sofilterwarnings = ["error::pytest_queryguard.QueryGuardWarning"](andignore::for findings) neither turns a deprecation into a failure nor hides it.docs/stability.mdnames it in step 1 of the policy. Nothing is deprecated yet.
Changed#
Behavior changes
- The
column-loadfinding kind is on by default (threshold 5, seequeryguard_column_load_threshold). A test that loops over deferred columns, or over objects expired bycommit(), passed before and now fails infailmode. To keep such tests green while you fix them, use a baseline,queryguard_fail_onwithoutcolumn-load(it then only warns), orqueryguard_ignore = ["column-load *"]. - Those loops used to be reported as a
repeated-statementwith the wrong advice (WHERE id IN (...)); they are no longer counted by that rule, so a baseline or ignore entry for such a finding has to use the new kind. - The index advisor is on by default whenever the index check is on
(
queryguard_index_advisor = falseturns it off). Missing-index findings now carry afix: CREATE INDEX ...line and analembic:line, and without the hypopg extension one notice at the end of the session says how to install it (queryguard_hypopg = offsilences it). queryguard_index_checknow also checks SQLite. A project that turned the check on and ran its tests on SQLite used to get a "not checked" notice and now gets findings, which fail tests infailmode.queryguard_index_checknow also checks MySQL and MariaDB. A project that turned the check on and ran its tests on MySQL or MariaDB used to get a "not checked" notice and now gets findings, which fail tests infailmode. Turn the check off again withqueryguard_index_check = false, skip tables withqueryguard_index_ignore_tables, or record the findings in a baseline.- Durations below one millisecond are printed in microseconds (
37 us) instead of0.0 msin the report and in budget failures. - The hint for a lazy-loaded many-to-one or one-to-one relationship is now
joinedload(...); collections still getselectinload(...). - A test stores at most 10000 statements and 10000 relationship loads for its
reports (
queryguard_max_events,0for no limit). Past the limit they are only counted. - When a listener raises, the plugin still stops measuring so that it never breaks the suite, but it warns and prints a "queryguard: measurement stopped" section instead of staying silent (see Fixed).
The other new options are off by default and change nothing until you turn them on:
queryguard_small_repeat_threshold, queryguard_write_loop_threshold,
queryguard_unused_eager_load, queryguard_baseline, queryguard_fail_on (empty:
every kind fails, as before) and --queryguard-sarif.
Breaking changes
These can break code or configuration that worked on 0.3.0.
-
max_queries()andmax_db_time()now yield the publicQueryLog(the objectrecord_queries()yields) instead of the internalQueryCollector, and are annotatedAbstractContextManager[QueryLog].with max_queries(3) as log:giveslog.count,log.queries,log.slowest()andlog.assert_no_nplusone(). Code that read.statementsof the yielded object, an undocumented attribute, must uselog.queriesorlog.count. -
The declared minimum SQLAlchemy is now 2.0.13 (
sqlalchemy>=2.0.13). The suite and the async helpers needAsyncAttrs, which does not exist in earlier 2.0 releases, so the old>=2.0bound promised more than was tested. -
PostgreSQL index check: a statement on a partitioned table is now one finding on the partitioned table, with
CREATE INDEX ON <table> (...)(which creates the index on every partition) and its hypopg verification, instead of one finding and oneCREATE INDEXper partition (#86). An ignore or baseline entry that named a partition no longer matches: replace the partition's name with the partitioned table's inqueryguard_index_ignore_tables,allow_missing_indexandmissing-indexpatterns, and record the baseline again with--queryguard-update-baseline(seedocs/index-check.md). A statement that names a partition itself is reported under the partitioned table too; inheritance children (INHERITS) are still reported one by one. Each partition is looked up once per session (pg_partition_root()), only for statements with findings. The advisor's reason for an invalid existing index now also namesCREATE INDEX ON ONLYa partitioned table whose partitions are not all attached. -
A serial run with
--continue-on-collection-errorsand a collection error no longer rewrites the baseline or writes the--queryguard-sariffile, as it did before (under pytest-xdist, and in a run with-x, this was already so). The tests of the module that did not collect never ran: a rewritten baseline would drop their entries and an uploaded report would close their alerts. The summary gives the interrupted-run reason; the GitHub Action skips the upload with a warning.
Internals
- The missing-index check reads the conditions of a plan node with a tokenizer
and parser (
pytest_queryguard.predicates) instead of regular expressions over the text. PostgreSQL's JSON plan has no structured form of a predicate, so the relation, alias, schema and index still come from the plan's fields and the condition text is parsed into a tree; the old text matching stays as the fallback for syntax the parser does not know. Findings do not change. The parsing is tested on realEXPLAIN (GENERIC_PLAN, VERBOSE, FORMAT JSON)plans captured from PostgreSQL 14 to 18 (scripts/capture_plans.py). - The measurement registers one more SQLAlchemy listener (
after_cursor_execute) to time statements.scripts/bench_overhead.pyputs the added cost of all the measurement, not of this listener alone, at about 20 to 55 microseconds per statement on in-memory SQLite (roughly +30 to +40 %); against a real database round trip it is small. See the FAQ. - Internal: detectors now hand their results to a stable
Findingmodel (kind,label,file,function,message,severity) before the report is rendered. The messages and the public API are unchanged. - The check that decides whether a stack frame belongs to SQLAlchemy, pytest or
the standard library is now cached per file name. Measured with
scripts/bench_overhead.py, this cuts the per-statement overhead of the measurement by about half. - Tests: an accuracy corpus under
tests/corpus: 110 small scenarios of realistic ORM code (views, serializers, FastAPI, Flask-SQLAlchemy, SQLModel, repositories, pagination, bulk writes, async), each marked BUG or CLEAN, run through the plugin in its default configuration and with each opt-in rule. Limitations it found are indocs/limitations.md;scripts/accuracy_report.pyprints the precision and recall. -
The repeated-statement rules no longer report pagination and chunked
INloads when the bound parameters show them: only theOFFSETor an integer keyset bound changes, in one direction, by at least a page of more than one row (the walk may be repeated once); or oneINlist of at least 50 values changes, the lists share no value and all but one have the same length.LIMIT 1 OFFSET nwalks, a page per item, a keyset bound per row, string and date keyset bounds, per-itemINlists, a paginated lookup inside a loop and identical repeats are still reported. Closes #60. The accuracy corpus has five more CLEAN scenarios for these shapes and five more BUG scenarios that imitate them; on its 141 scenarios the default repeated-statement precision goes from 80% to 97% (90% to 97% without the five CLEAN ones), recall is unchanged at 95%, no BUG scenario changes in any configuration, and the release gate's minimum precision for the kind is now 90%. See "Pagination and chunks" indocs/how-detection-works.md. -
docs/stability.mdhas an "Experimental" section: thequeryguard_unused_eager_loadoption, theunused-eager-loadfinding kind and the missing-index check on MySQL and MariaDB are exempt from the deprecation policy and may change or go in a minor release with a changelog entry. The policy had no such tier although the option was labelled experimental. -
The options with a fixed set of values now agree on case.
queryguard_mode,queryguard_hypopgand--queryguard-modeused to rejectFAIL,ONandWarnwhilequeryguard_unused_eager_loadandqueryguard_repeat_scopeaccepted any case; all of them now ignore case and surrounding spaces, and unknown values are still a usage error. -
Lower the per-statement overhead by about a sixth in the in-memory SQLite micro-benchmark: one shared
CallSiteper source location, one write check per statement and a cache fornormalize(). Behaviour is unchanged. Newdocs/performance.mdandscripts/bench_suite.py(a whole-suite benchmark for file-based SQLite or PostgreSQL). -
allow_nplusonewith patterns now also applies to missing-index findings.kind="missing-index"was accepted but never matched anything and was then reported as a stale ignore; it now works like the same pattern inqueryguard_ignore. The marker without arguments still leaves the index check alone (allow_missing_indexskips it). -
The accuracy corpus has 23 more scenarios (133 in all): GraphQL-style resolvers and DataLoaders,
asyncio.gatherand Celery-style fan-out, caching repositories,with_for_update, nested transactions,yield_per, largeselectinload, ORM bulk statements, upserts, and BUG scenarios that look like pagination, batching or polling.docs/accuracy.mdand the release gate's minimum scenario count are updated; the plugin is unchanged. -
Tests and CI: a release gate (
.github/workflows/release-gate.yml,scripts/release_gate.py) that checks the test matrix, the accuracy minimums, the documentation examples, clean installs, the upgrade from the previous release, the overhead budget, the package contents and the changelog before a release is tagged. Seedocs/releasing.md. -
The classes and functions in
pytest_queryguard.__all__now reportpytest_queryguardas their__module__. Tracebacks and logs showpytest_queryguard.NPlusOneDetectedinstead ofpytest_queryguard.api.NPlusOneDetected, so the printed name matches the documented import path and the submodules can move without changing it. Afilterwarningsentry that names the submodule (error::pytest_queryguard.warnings.QueryGuardWarning) keeps working. -
The keyword of the
max_queriesmarker is nowlimit, as in themax_queries(limit)function:@pytest.mark.max_queries(limit=3). The keywordn=of earlier releases is still accepted, without a warning. It may be removed in a future minor release, but only after a deprecation period with a warning, as described indocs/stability.md. The positional form is unchanged. -
Every finding in a report now has a
kind: ... label: ...line, the pair thatqueryguard_ignore,allow_nplusoneand the baseline match on, for examplekind: relationship-load label: Order.customer. For a repeated statement or a write loop the line replaces the separate line with the normalized statement (a statement longer than 200 characters is cut and ends with*, so the printed label still works as a pattern). An ignore pattern that is the exact label now matches even when the label holds[or]. The line is in the SARIF message too (#105).
Fixed#
- The index check no longer reports a missing index, and the advisor no longer
recommends a redundant one, for a statement that an existing partial index
may serve. The generic plan cannot see bound values, so it could not know
that
status = $1matches... WHERE status = 'open'. Such statements are skipped and counted in the session summary. A missing index on them is not found; see the limitations. - Loops over deferred or expired columns were reported as a repeated statement
with the wrong advice (
WHERE id IN (...)). They are now acolumn-loadfinding and no longer count towards the repeated-statement rule. - When a listener raises, the plugin still stops measuring so that it never
breaks the suite, but it no longer does so silently. The warning names the
listener or step that failed, and the end of the session prints a
"queryguard: measurement stopped" section with the listener, the error and
the line that raised it, once per session, with or without
--queryguard-report. - A lazy load or column load that autoflushed pending changes first was attributed to the flush's write: the UPDATE or DELETE carried the relationship name and the load's SELECT carried none, so one loop was also reported as a repeated statement. Writes no longer take the pending attribution (#59).
- Documentation: the limitations page, the FAQ and the README now say that a
raw
sqlite3or other DB-API connection and non-SQLAlchemy ORMs (Django ORM, Peewee, Tortoise ORM) are not seen, and that nothing reports it; the limitations page also points to the repeat-scope limits. - The SQLite index check no longer says a table "is read in full" when the
plan walks an existing index that the filter cannot use (
SCAN INDEX ix_...). It says the table scans the whole index and that the filter does not match the start of any index; the suggestedCREATE INDEXis unchanged. - A SARIF result merged from several tests no longer shows one test's count in
message.textnext to the total inproperties.count. The message now starts withSeen in N tests: T times in total, up to M times in one test, andpropertiesgainstestsandpeakCountfor such results.count, the fingerprints and the baseline identity are unchanged. Seedocs/sarif.md. - The
repeated-statementhint no longer says to fetch the rows withWHERE id IN (...)when the statement already usesIN (...). It says the batched query ran several times and should be called once, or the calls combined. - SARIF locations are now relative to the repository root when
GITHUB_WORKSPACEis set and the pytest rootdir is inside it. Before, they were relative to the rootdir, so with the action'sworking-directoryset to a subdirectory GitHub created alerts on paths that do not exist and showed no pull request annotations. Fingerprints and baseline identities are unchanged. Seedocs/sarif.md. - The action skips the SARIF upload for runs triggered by Dependabot (read-only token), and a refused upload no longer fails the job.
-
On SQLAlchemy 2.0.20 to 2.0.49 (and 2.1.0b1, 2.1.0b2) the plugin's
do_orm_executelistener triggered SQLAlchemy issue 13301 (fixed in 2.0.50): the outer statement'syield_per,autoflush,populate_existingandidentity_tokenoptions became load options of itsselectinloadandimmediateloadstatements. Ayield_perplusselectinloadtest failed with "Can't use the ORM yield_per feature in conjunction with unique()", andautoflush=Falsestopped the loader statement from flushing, only because the plugin was installed. On those versions the plugin now removes the inherited options from a loader statement before SQLAlchemy reads them, so the statement runs as it does without the plugin. When ado_orm_executelistener of your own takes part, the plugin changes nothing: your listener triggers the same issue without the plugin (#169). -
Tests: the accuracy corpus now checks that a scenario never fails without a finding in every run, not only in the pytest-xdist worker that happened to measure it.
-
On SQLAlchemy 2.0.13 to 2.0.29 the column load of a joined-inheritance subclass (reading
manager.budgetafterselect(Employee)) was not recognised as a column load and was reported as a repeated statement. Before 2.0.30 SQLAlchemy reportsis_selectandis_column_loadas False for thefrom_statement()execution that loads those columns; the plugin now also reads the refresh state from the statement and the execution options. The oldest-versions job of the release gate now installs exactlysqlalchemy==2.0.13, the declared minimum, instead of the latest 2.0.x. Fixes #161. -
Free-threaded CPython (3.14t): statements, relationship and column loads and database time reported from several threads into one collector lost updates (
counted 15839, expected 16000), which budgets and the truncation flag rely on. The collector now updates them under a lock on a build without the GIL and takes no lock with the GIL (scripts/bench_overhead.pyshows no change on CPython 3.12). Tests: the memory test measures what the plugin itself allocated, because the whole-process figure on the free-threaded build reflects SQLAlchemy's late freeing, not a leak in the plugin. Free-threaded builds are still not in the CI matrix;docs/getting-started.mdsays so. Fixes #159. -
The repeat rules (repeated statement and small repeat) no longer count transaction-control statements:
BEGIN,COMMIT,ROLLBACK,SAVEPOINT,RELEASE,START TRANSACTIONandSET TRANSACTION. With SQLAlchemy's pysqliteBEGINrecipe a loop that commits each pass was reported withBEGINas a repeated statement and the advice to fetch rows in one query. Budgets still count them. ABEGINthat opens a block (BEGIN load_order(:id); END;) is still counted, and a loop with aSAVEPOINTper row is still a write loop. The accuracy corpus gives the same result before and after. Fixes #158. -
Stability: with
-W errororfilterwarnings = error, an internal error no longer fails the user's test.QueryGuardInternalWarningwas raised as an exception from the test call, from the terminal summary (which aborted it), from arecord_queries()block and, for the unused eager-load check, from inside SQLAlchemy'sdo_orm_execute. Now it is always shown and recorded, never raised, and an "ignore" filter still hides it (#124). - Stability: an error inside the
after_beginlistener no longer reaches the user'sSession.begin(). Like every other listener, it now stops the measurement with aQueryGuardInternalWarning(#123). - Stability: a baseline file nested too deep for the JSON parser is a usage
error instead of an
INTERNALERROR, and any error while writing the baseline is reported instead of crashing the end of the session (#125). - PostgreSQL index check: an internal error after the check opened its
savepoint (or, on an autocommit connection, its own transaction) left that
savepoint or transaction open on the user's connection. In autocommit mode
the user's later writes were then never committed, and inside a transaction
enable_seqscanstayedoff. The check now rolls them back before the error stops the plugin (#126). -
Stability: an error inside
pytest_configure, the per-test start or end of the measurement, the pytest-xdist hand-over of the findings,pytest_unconfigureor the attribute-read hook of the unused eager-load check no longer ends the session with anINTERNALERRORor fails every test. It stops the measurement and is reported once, like an error in a listener; an error in the xdist hand-over marks the run incomplete, so the baseline is not rewritten and the SARIF summary says findings may be missing.KeyboardInterrupt,SystemExitandasyncio.CancelledErrorare still never swallowed.docs/stability.mddescribes the contract under "Failing open" (#127). -
Tests: the accuracy corpus now runs on PostgreSQL (
QUERYGUARD_CORPUS_PG_URL). Two scenarios (bug_23_get_or_create_loop,bug_30_flush_per_insert) failed there because seeded rows with explicit ids did not advance the sequences; the corpus moves them after each setup. The results on PostgreSQL 17 match SQLite; seedocs/accuracy.md. Fixes #120. -
SARIF: a finding whose call site is unknown (for example
session.executehanded straight to a worker thread) is located at the test instead of being left out of the file, so code scanning shows it. The terminal text, the baseline and the ignore rules are unchanged.docs/limitations.mdexplains the cause and the workaround (#132). -
GitHub Action: the
packageinput now defaults to the plugin in the action's own checkout instead of the namepytest-queryguard, so the installed plugin matches the pinned ref and accepts--queryguard-sarif(pip used to pick the stable 0.3.0 while 0.4 was a release candidate) (#106). -
The index check notice for a database it cannot check (SQL Server, Oracle) said the check needs PostgreSQL 16, although SQLite, MySQL and MariaDB are supported. It now lists every supported database, and the help texts of
--queryguard-index-checkandqueryguard_index_checkname MySQL and MariaDB too. Fixes #154. -
PostgreSQL index check: a finding for an index the plan walks end to end (a filter on the trailing column of a composite key, a whole index with a filter, a whole-index bitmap) now says
t scans the whole index ix: the ... does not match the start of any index, as the SQLite check does, instead of saying the table is read in full. The closing note no longer calls such a scan sequential (#130). -
A lazy load keeps its relationship when another statement runs between the load and its
SELECT: statements of otherAsyncSessions running concurrently (asyncio.gather), theBEGINof SQLAlchemy's pysqlite recipe or any statement of abeginorafter_beginlistener. The attribution is now parked on theSessionthat issued the load instead of on the thread, so these loops are no longer reported a second time as a repeated statement. Fixes #97 and #99. -
The relationship-load finding shows a lazy load as its sample SQL. It used the first statement with the relationship's label, which was the
selectinloadquery when that ran first; that query is now used only when no lazy load was recorded (#131). -
The SARIF level of an unused-eager-load finding now follows the test outcome: with
queryguard_unused_eager_load = warnit iswarning, noterror. Fixes #98. -
A statement that starts with a comment (sqlcommenter tags, a
-- notein atext()) is now classified like the statement after the comment. A loop of commented single-rowINSERTs was reported as a repeated statement with the advice to fetch the rows in one query, and the write-loop rule never saw it. Fixes #96. -
The MySQL and MariaDB index check no longer fails on a literal
%in a statement that was run with theno_parametersexecution option: theEXPLAINwas formatted by PyMySQL (query % args) although the statement itself was not, so it was reported as "could not be explained" (a literal%%was sent as%). Fixes #116. -
--queryguard-update-baselineno longer rewrites the baseline, and--queryguard-sarifno longer writes the file, after an interrupted run (a collection error, Ctrl-C, a usage error or an internal pytest error). The summary says why. Fixes #95. -
Tests: the public API snapshot recorded a wrong return type for
QueryLog.slowest()and did not assert it. It now recordstuple[Query, ...]and checks every member ofQueryLogthe same way. -
--queryguard-update-baselinewrites a usable baseline when a test lives in a directory whose name is not valid UTF-8: such characters are written as\udcXXescapes (other text stays readable), so the entry matches on the next run instead of the write failing. Fixes #89. -
PostgreSQL index check:
NOT IN (subquery)on PostgreSQL 17 and 18 no longer getsfix: CREATE INDEX ON t (col)for the compared column, which was wrong even for a primary key (#83). Plan conditions withCASE,AT TIME ZONE,EXTRACT(... FROM ...),count(*),COLLATEor an array subscript are now parsed instead of matched as text, so a column inside them is no longer suggested as a plain index and gets the expression-index note (#84). A row comparison such as(a, b) > ($1, $2)no longer asks for an expression index (#85). -
PostgreSQL index check: a server newer than the tested releases (16 to 18) is still checked and now gets one notice in the session summary that its version is untested. Older servers keep their one "not checked" notice. The tested versions are listed in
docs/index-check.md. - The index check no longer rolls back a transaction the application opened by
hand on an AUTOCOMMIT connection (
exec_driver_sql("BEGIN"), with pg8000 or asyncpg). Theautocommitflag is the driver's setting, not the server's state, so the check now tries a savepoint first and starts a transaction of its own only when none is open (SQLSTATE 25P01). Fixes #91. - Documentation: the index check page was published as raw Markdown from the partial-index paragraph on, including its SQLite section (#117). A test now fails the build for any page left like that.
- Documented that PostgreSQL evaluates
IMMUTABLEfunctions with constant arguments at plan time, so the index check and the advisor can call such a function again and its non-transactional side effects (for examplenextval()) are not rolled back with the savepoint. Fixes #92. - The repeated-statement and small-repeat rules no longer count schema
reflection:
PRAGMAstatements, reads ofsqlite_master,sqlite_schemaand their temp variants, and reads ofpg_catalogorinformation_schema(MetaData.reflect(),Inspector.has_table(),create_all(), Alembic's version-table check).max_queriesbudgets still count them. Seedocs/how-detection-works.mdfor the exact rule (#129). -
PostgreSQL index check: a sequential scan whose filter is only not-equal comparisons against parameters (
<> $1,NOT INwith bound values) is no longer reported as a missing index. No index serves them, so the advice could not be followed, even on an indexed column; the SQLite check never reported them. A filter with one more servable condition, or a not-equal against a constant in the SQL (which a partial index serves), is still reported (#133). -
Baseline: a file nested more than 100 levels deep is now rejected by a depth check before parsing, so the "nested too deep" usage error no longer depends on the interpreter hitting its recursion limit (which on Python 3.10 could surface as a second, unraisable
RecursionError). -
--queryguard-update-baselineon a partial run (-k,-m,--deselect,--lf,--sw,--ignore, a node id or a path narrower thantestpaths, with or without pytest-xdist) no longer drops the entries of tests that did not run. Only the entries of tests that ran are replaced, the others are kept, and the summary says how many were kept. A deleted test's entries are removed on the next full run.docs/baseline.mddescribes which runs are full and which are partial. Fixes #148. -
--queryguard-update-baselinewith--collect-onlyemptied the baseline file. It now leaves the file alone and says why. session.refresh()of an object whose collection is mappedlazy="selectin"orlazy="subquery"(also reached through alazy="joined"relationship) was reported as a relationship-load N+1 with aselectinloadhint for the strategy that is already mapped; two creates followed by a refresh each were enough to fail a test, on sync and async sessions. The loads SQLAlchemy runs for a refresh or an expired reload are no longer counted as lazy loads. Alazy="select"collection read per parent and animmediateload()option are reported as before.- The refresh a repository runs after each create or update (advanced-alchemy's
auto_refresh) was a column-load finding as soon as a test created five rows. Asession.refresh()of an object that the latest flush of its Session inserted or changed is no longer counted (one object per class and flush); a write loop itself stays the opt-in write-loop rule's finding. A loop of refreshes of objects that were only read or flushed without a net change, a refresh of every row of one bulk insert and a second refresh of the same write are reported as before. On litestar-fullstack this removes the column-load finding of two tests that create ten tokens each; their repeated-statement findings remain. session.refresh(obj, ["name"])in a loop was labelled as an expired load with anexpire_on_commit=Falsehint; it is now a refresh (Book (refresh)) with the refresh hint.- In
warnmode, a finding turned into an error byfilterwarnings(error::pytest_queryguard.QueryGuardWarningor a blanketerror) no longer prints about 50 lines of the plugin's hook wrapper source before the finding; the failure shows the finding message, as infailmode. - Under pytest-xdist, a collection error without
-xno longer rewrites the baseline or writes the--queryguard-sariffile: the run is handled as the interrupted run a serial run is, with the same reason. Closes #194. - An internal error in the budget markers, the
allow_missing_indexcheck or the end of a measurement in thepytest_runtest_callhook no longer fails the user's test: it ends measurement with aQueryGuardInternalWarningand the "queryguard: measurement stopped" section, as other internal errors do. The collection-report and pytest-xdist worker hooks are guarded the same way. AKeyboardInterruptorSystemExitat the end of a measurement still stops the run, and leaves no collector or eager-load tracker behind. Closes #197. - Under pytest-xdist, a run stopped by
-xor--maxfailis handled as in a serial run instead of as an interrupted one: the baseline is not updated because the run stopped early (it no longer blames a collection error, Ctrl-C or an internal error), and the--queryguard-sariffile is written. A collection error under-x, serial or with pytest-xdist, is still reported as an interrupted run. Closes #187. - The GitHub Action example in
docs/ci.mdno longer fails on a first run: thebaselineinput is commented out until the file exists. The examples useactions/checkout@v7andactions/setup-python@v7(Node 24) and run onpushtomainpluspull_request, so a pull request does not run twice. - A table name in a missing-index finding is now matched the same way in
queryguard_index_ignore_tables,allow_missing_index,queryguard_ignoreandallow_nplusone(..., kind="missing-index"): a bare name,schema.table(also for a table the report prints without its schema), quoted or unquoted identifiers (unquoted as written, case-sensitive; quoted exactly, may hold dots). The documentedallow_nplusone("public.audit_log", kind="missing-index")now matches. Every spelling that matched before still does, and the labels in reports and baselines are unchanged. This can leave out missing-index findings that were reported before: inqueryguard_ignoreandallow_nplusone, a bare name (audit_log) now also matches the table in a schema off the search path (labelaudit.audit_log),schema.tablematches a table printed without its schema, and an unquoted name matches a table whose label is quoted (UserAccountfor"UserAccount"). Findings of other kinds match as before. docs/sarif.mdanddocs/baseline.mdlisted five finding kinds; the SARIF file lists six rules,unused-eager-loadincluded.- The budget failure says
expected at most 1 query(it said1 queries); other limits are unchanged. - Documentation: the recipes,
python-api.mdand the migration guide now run as written (found in a walk of the 0.4.0rc3 docs);tests/test_doc_examples.pyruns more of the recipe pages as projects.
0.4.0rc4 - 2026-10-13#
Fixed#
session.refresh()of an object whose collection is mappedlazy="selectin"orlazy="subquery"(also reached through alazy="joined"relationship) was reported as a relationship-load N+1 with aselectinloadhint for the strategy that is already mapped; two creates followed by a refresh each were enough to fail a test, on sync and async sessions. The loads SQLAlchemy runs for a refresh or an expired reload are no longer counted as lazy loads. Alazy="select"collection read per parent and animmediateload()option are reported as before.- The refresh a repository runs after each create or update (advanced-alchemy's
auto_refresh) was a column-load finding as soon as a test created five rows. Asession.refresh()of an object that the latest flush of its Session inserted or changed is no longer counted (one object per class and flush); a write loop itself stays the opt-in write-loop rule's finding. A loop of refreshes of objects that were only read or flushed without a net change, a refresh of every row of one bulk insert and a second refresh of the same write are reported as before. On litestar-fullstack this removes the column-load finding of two tests that create ten tokens each; their repeated-statement findings remain. session.refresh(obj, ["name"])in a loop was labelled as an expired load with anexpire_on_commit=Falsehint; it is now a refresh (Book (refresh)) with the refresh hint.- In
warnmode, a finding turned into an error byfilterwarnings(error::pytest_queryguard.QueryGuardWarningor a blanketerror) no longer prints about 50 lines of the plugin's hook wrapper source before the finding; the failure shows the finding message, as infailmode. - Under pytest-xdist, a collection error without
-xno longer rewrites the baseline or writes the--queryguard-sariffile: the run is handled as the interrupted run a serial run is, with the same reason. Closes #194. - Behavior change: a serial run with
--continue-on-collection-errorsand a collection error also no longer rewrites the baseline or writes the--queryguard-sariffile, where it did before. The tests of the module that did not collect never ran: a rewritten baseline would drop their entries and an uploaded report would close their alerts. The summary gives the interrupted-run reason; the GitHub Action skips the upload with a warning. - An internal error in the budget markers, the
allow_missing_indexcheck or the end of a measurement in thepytest_runtest_callhook no longer fails the user's test: it ends measurement with aQueryGuardInternalWarningand the "queryguard: measurement stopped" section, as other internal errors do. The collection-report and pytest-xdist worker hooks are guarded the same way. AKeyboardInterruptorSystemExitat the end of a measurement still stops the run, and leaves no collector or eager-load tracker behind. Closes #197. - Under pytest-xdist, a run stopped by
-xor--maxfailis handled as in a serial run instead of as an interrupted one: the baseline is not updated because the run stopped early (it no longer blames a collection error, Ctrl-C or an internal error), and the--queryguard-sariffile is written. A collection error under-x, serial or with pytest-xdist, is still reported as an interrupted run. Closes #187. - The GitHub Action example in
docs/ci.mdno longer fails on a first run: thebaselineinput is commented out until the file exists. The examples useactions/checkout@v7andactions/setup-python@v7(Node 24) and run onpushtomainpluspull_request, so a pull request does not run twice. - A table name in a missing-index finding is now matched the same way in
queryguard_index_ignore_tables,allow_missing_index,queryguard_ignoreandallow_nplusone(..., kind="missing-index"): a bare name,schema.table(also for a table the report prints without its schema), quoted or unquoted identifiers (unquoted as written, case-sensitive; quoted exactly, may hold dots). The documentedallow_nplusone("public.audit_log", kind="missing-index")now matches. Every spelling that matched before still does, and the labels in reports and baselines are unchanged. This can leave out missing-index findings that were reported before: inqueryguard_ignoreandallow_nplusone, a bare name (audit_log) now also matches the table in a schema off the search path (labelaudit.audit_log),schema.tablematches a table printed without its schema, and an unquoted name matches a table whose label is quoted (UserAccountfor"UserAccount"). Findings of other kinds match as before. docs/sarif.mdanddocs/baseline.mdlisted five finding kinds; the SARIF file lists six rules,unused-eager-loadincluded.- The budget failure says
expected at most 1 query(it said1 queries); other limits are unchanged. - Documentation found in a walk of the 0.4.0rc3 docs, each snippet run in a
fresh environment: the Flask-SQLAlchemy, SQLModel, Litestar and
pytest-asyncio recipes show
pytest.iniwithpythonpath = .(copied literally, they failed withNo module named 'app') and the models and test files they were missing;python-api.mdandmigrating-from-queryspy.mdimport the fixed modules where they expect the fixed behaviour;python-api.mddocumentscolumn_load_threshold,small_repeat_thresholdandwrite_loop_thresholdofassert_no_nplusone(); the legacy recipe puts its settings in the example'spytest.ini, which pytest reads instead of apyproject.toml; the JUnit XML of the CI recipe, a line number in the budgets recipe, a test file name in the FastAPI recipe, a missing file on the getting-started page and the stale0.4.0rc2install lines are corrected.tests/test_doc_examples.pynow runs the SQLModel, Litestar and pytest-asyncio pages as projects too (skipped where the package is not installed).
0.4.0rc3 - 2026-10-13#
Added#
QueryGuardDeprecationWarning, aDeprecationWarningsubclass exported frompytest_queryguard, is the class the deprecation policy uses. It is not aQueryGuardWarning, sofilterwarnings = ["error::pytest_queryguard.QueryGuardWarning"](andignore::for findings) neither turns a deprecation into a failure nor hides it.docs/stability.mdnames it in step 1 of the policy. Nothing is deprecated yet.
Changed#
-
The repeated-statement rules no longer report pagination and chunked
INloads when the bound parameters show them: only theOFFSETor an integer keyset bound changes, in one direction, by at least a page of more than one row (the walk may be repeated once); or oneINlist of at least 50 values changes, the lists share no value and all but one have the same length.LIMIT 1 OFFSET nwalks, a page per item, a keyset bound per row, string and date keyset bounds, per-itemINlists, a paginated lookup inside a loop and identical repeats are still reported. Closes #60. The accuracy corpus has five more CLEAN scenarios for these shapes and five more BUG scenarios that imitate them; on its 141 scenarios the default repeated-statement precision goes from 80% to 97% (90% to 97% without the five CLEAN ones), recall is unchanged at 95%, no BUG scenario changes in any configuration, and the release gate's minimum precision for the kind is now 90%. See "Pagination and chunks" indocs/how-detection-works.md. -
docs/stability.mdhas an "Experimental" section: thequeryguard_unused_eager_loadoption, theunused-eager-loadfinding kind and the missing-index check on MySQL and MariaDB are exempt from the deprecation policy and may change or go in a minor release with a changelog entry. The policy had no such tier although the option was labelled experimental. -
max_queries()andmax_db_time()now yield the publicQueryLog(the objectrecord_queries()yields) instead of the internalQueryCollector, and are annotatedAbstractContextManager[QueryLog].with max_queries(3) as log:giveslog.count,log.queries,log.slowest()andlog.assert_no_nplusone(). Code that read.statementsof the yielded object, an undocumented attribute, must uselog.queriesorlog.count. -
The declared minimum SQLAlchemy is now 2.0.13 (
sqlalchemy>=2.0.13). The suite and the async helpers needAsyncAttrs, which does not exist in earlier 2.0 releases, so the old>=2.0bound promised more than was tested. -
The options with a fixed set of values now agree on case.
queryguard_mode,queryguard_hypopgand--queryguard-modeused to rejectFAIL,ONandWarnwhilequeryguard_unused_eager_loadandqueryguard_repeat_scopeaccepted any case; all of them now ignore case and surrounding spaces, and unknown values are still a usage error. -
Lower the per-statement overhead by about a sixth in the in-memory SQLite micro-benchmark: one shared
CallSiteper source location, one write check per statement and a cache fornormalize(). Behaviour is unchanged. Newdocs/performance.mdandscripts/bench_suite.py(a whole-suite benchmark for file-based SQLite or PostgreSQL). -
allow_nplusonewith patterns now also applies to missing-index findings.kind="missing-index"was accepted but never matched anything and was then reported as a stale ignore; it now works like the same pattern inqueryguard_ignore. The marker without arguments still leaves the index check alone (allow_missing_indexskips it). -
The accuracy corpus has 23 more scenarios (133 in all): GraphQL-style resolvers and DataLoaders,
asyncio.gatherand Celery-style fan-out, caching repositories,with_for_update, nested transactions,yield_per, largeselectinload, ORM bulk statements, upserts, and BUG scenarios that look like pagination, batching or polling.docs/accuracy.mdand the release gate's minimum scenario count are updated; the plugin is unchanged. -
Tests and CI: a release gate (
.github/workflows/release-gate.yml,scripts/release_gate.py) that checks the test matrix, the accuracy minimums, the documentation examples, clean installs, the upgrade from the previous release, the overhead budget, the package contents and the changelog before a release is tagged. Seedocs/releasing.md. -
PostgreSQL index check: a statement on a partitioned table is now one finding on the partitioned table, with
CREATE INDEX ON <table> (...)(which creates the index on every partition) and its hypopg verification, instead of one finding and oneCREATE INDEXper partition (#86). An ignore or baseline entry that named a partition no longer matches: replace the partition's name with the partitioned table's inqueryguard_index_ignore_tables,allow_missing_indexandmissing-indexpatterns, and record the baseline again with--queryguard-update-baseline(seedocs/index-check.md). A statement that names a partition itself is reported under the partitioned table too; inheritance children (INHERITS) are still reported one by one. Each partition is looked up once per session (pg_partition_root()), only for statements with findings. The advisor's reason for an invalid existing index now also namesCREATE INDEX ON ONLYa partitioned table whose partitions are not all attached. -
The classes and functions in
pytest_queryguard.__all__now reportpytest_queryguardas their__module__. Tracebacks and logs showpytest_queryguard.NPlusOneDetectedinstead ofpytest_queryguard.api.NPlusOneDetected, so the printed name matches the documented import path and the submodules can move without changing it. Afilterwarningsentry that names the submodule (error::pytest_queryguard.warnings.QueryGuardWarning) keeps working. -
The keyword of the
max_queriesmarker is nowlimit, as in themax_queries(limit)function:@pytest.mark.max_queries(limit=3). The keywordn=of earlier releases is still accepted, without a warning. It may be removed in a future minor release, but only after a deprecation period with a warning, as described indocs/stability.md. The positional form is unchanged. -
Every finding in a report now has a
kind: ... label: ...line, the pair thatqueryguard_ignore,allow_nplusoneand the baseline match on, for examplekind: relationship-load label: Order.customer. For a repeated statement or a write loop the line replaces the separate line with the normalized statement (a statement longer than 200 characters is cut and ends with*, so the printed label still works as a pattern). An ignore pattern that is the exact label now matches even when the label holds[or]. The line is in the SARIF message too (#105).
Fixed#
-
On SQLAlchemy 2.0.20 to 2.0.49 (and 2.1.0b1, 2.1.0b2) the plugin's
do_orm_executelistener triggered SQLAlchemy issue 13301 (fixed in 2.0.50): the outer statement'syield_per,autoflush,populate_existingandidentity_tokenoptions became load options of itsselectinloadandimmediateloadstatements. Ayield_perplusselectinloadtest failed with "Can't use the ORM yield_per feature in conjunction with unique()", andautoflush=Falsestopped the loader statement from flushing, only because the plugin was installed. On those versions the plugin now removes the inherited options from a loader statement before SQLAlchemy reads them, so the statement runs as it does without the plugin. When ado_orm_executelistener of your own takes part, the plugin changes nothing: your listener triggers the same issue without the plugin (#169). -
Tests: the accuracy corpus now checks that a scenario never fails without a finding in every run, not only in the pytest-xdist worker that happened to measure it.
-
On SQLAlchemy 2.0.13 to 2.0.29 the column load of a joined-inheritance subclass (reading
manager.budgetafterselect(Employee)) was not recognised as a column load and was reported as a repeated statement. Before 2.0.30 SQLAlchemy reportsis_selectandis_column_loadas False for thefrom_statement()execution that loads those columns; the plugin now also reads the refresh state from the statement and the execution options. The oldest-versions job of the release gate now installs exactlysqlalchemy==2.0.13, the declared minimum, instead of the latest 2.0.x. Fixes #161. -
Free-threaded CPython (3.14t): statements, relationship and column loads and database time reported from several threads into one collector lost updates (
counted 15839, expected 16000), which budgets and the truncation flag rely on. The collector now updates them under a lock on a build without the GIL and takes no lock with the GIL (scripts/bench_overhead.pyshows no change on CPython 3.12). Tests: the memory test measures what the plugin itself allocated, because the whole-process figure on the free-threaded build reflects SQLAlchemy's late freeing, not a leak in the plugin. Free-threaded builds are still not in the CI matrix;docs/getting-started.mdsays so. Fixes #159. -
The repeat rules (repeated statement and small repeat) no longer count transaction-control statements:
BEGIN,COMMIT,ROLLBACK,SAVEPOINT,RELEASE,START TRANSACTIONandSET TRANSACTION. With SQLAlchemy's pysqliteBEGINrecipe a loop that commits each pass was reported withBEGINas a repeated statement and the advice to fetch rows in one query. Budgets still count them. ABEGINthat opens a block (BEGIN load_order(:id); END;) is still counted, and a loop with aSAVEPOINTper row is still a write loop. The accuracy corpus gives the same result before and after. Fixes #158. -
Stability: with
-W errororfilterwarnings = error, an internal error no longer fails the user's test.QueryGuardInternalWarningwas raised as an exception from the test call, from the terminal summary (which aborted it), from arecord_queries()block and, for the unused eager-load check, from inside SQLAlchemy'sdo_orm_execute. Now it is always shown and recorded, never raised, and an "ignore" filter still hides it (#124). - Stability: an error inside the
after_beginlistener no longer reaches the user'sSession.begin(). Like every other listener, it now stops the measurement with aQueryGuardInternalWarning(#123). - Stability: a baseline file nested too deep for the JSON parser is a usage
error instead of an
INTERNALERROR, and any error while writing the baseline is reported instead of crashing the end of the session (#125). - PostgreSQL index check: an internal error after the check opened its
savepoint (or, on an autocommit connection, its own transaction) left that
savepoint or transaction open on the user's connection. In autocommit mode
the user's later writes were then never committed, and inside a transaction
enable_seqscanstayedoff. The check now rolls them back before the error stops the plugin (#126). -
Stability: an error inside
pytest_configure, the per-test start or end of the measurement, the pytest-xdist hand-over of the findings,pytest_unconfigureor the attribute-read hook of the unused eager-load check no longer ends the session with anINTERNALERRORor fails every test. It stops the measurement and is reported once, like an error in a listener; an error in the xdist hand-over marks the run incomplete, so the baseline is not rewritten and the SARIF summary says findings may be missing.KeyboardInterrupt,SystemExitandasyncio.CancelledErrorare still never swallowed.docs/stability.mddescribes the contract under "Failing open" (#127). -
Tests: the accuracy corpus now runs on PostgreSQL (
QUERYGUARD_CORPUS_PG_URL). Two scenarios (bug_23_get_or_create_loop,bug_30_flush_per_insert) failed there because seeded rows with explicit ids did not advance the sequences; the corpus moves them after each setup. The results on PostgreSQL 17 match SQLite; seedocs/accuracy.md. Fixes #120. -
SARIF: a finding whose call site is unknown (for example
session.executehanded straight to a worker thread) is located at the test instead of being left out of the file, so code scanning shows it. The terminal text, the baseline and the ignore rules are unchanged.docs/limitations.mdexplains the cause and the workaround (#132). -
GitHub Action: the
packageinput now defaults to the plugin in the action's own checkout instead of the namepytest-queryguard, so the installed plugin matches the pinned ref and accepts--queryguard-sarif(pip used to pick the stable 0.3.0 while 0.4 was a release candidate) (#106). -
The index check notice for a database it cannot check (SQL Server, Oracle) said the check needs PostgreSQL 16, although SQLite, MySQL and MariaDB are supported. It now lists every supported database, and the help texts of
--queryguard-index-checkandqueryguard_index_checkname MySQL and MariaDB too. Fixes #154. -
PostgreSQL index check: a finding for an index the plan walks end to end (a filter on the trailing column of a composite key, a whole index with a filter, a whole-index bitmap) now says
t scans the whole index ix: the ... does not match the start of any index, as the SQLite check does, instead of saying the table is read in full. The closing note no longer calls such a scan sequential (#130). -
A lazy load keeps its relationship when another statement runs between the load and its
SELECT: statements of otherAsyncSessions running concurrently (asyncio.gather), theBEGINof SQLAlchemy's pysqlite recipe or any statement of abeginorafter_beginlistener. The attribution is now parked on theSessionthat issued the load instead of on the thread, so these loops are no longer reported a second time as a repeated statement. Fixes #97 and #99. -
The relationship-load finding shows a lazy load as its sample SQL. It used the first statement with the relationship's label, which was the
selectinloadquery when that ran first; that query is now used only when no lazy load was recorded (#131). -
The SARIF level of an unused-eager-load finding now follows the test outcome: with
queryguard_unused_eager_load = warnit iswarning, noterror. Fixes #98. -
A statement that starts with a comment (sqlcommenter tags, a
-- notein atext()) is now classified like the statement after the comment. A loop of commented single-rowINSERTs was reported as a repeated statement with the advice to fetch the rows in one query, and the write-loop rule never saw it. Fixes #96. -
The MySQL and MariaDB index check no longer fails on a literal
%in a statement that was run with theno_parametersexecution option: theEXPLAINwas formatted by PyMySQL (query % args) although the statement itself was not, so it was reported as "could not be explained" (a literal%%was sent as%). Fixes #116. -
--queryguard-update-baselineno longer rewrites the baseline, and--queryguard-sarifno longer writes the file, after an interrupted run (a collection error, Ctrl-C, a usage error or an internal pytest error). The summary says why. Fixes #95. -
Tests: the public API snapshot recorded a wrong return type for
QueryLog.slowest()and did not assert it. It now recordstuple[Query, ...]and checks every member ofQueryLogthe same way. -
--queryguard-update-baselinewrites a usable baseline when a test lives in a directory whose name is not valid UTF-8: such characters are written as\udcXXescapes (other text stays readable), so the entry matches on the next run instead of the write failing. Fixes #89. -
PostgreSQL index check:
NOT IN (subquery)on PostgreSQL 17 and 18 no longer getsfix: CREATE INDEX ON t (col)for the compared column, which was wrong even for a primary key (#83). Plan conditions withCASE,AT TIME ZONE,EXTRACT(... FROM ...),count(*),COLLATEor an array subscript are now parsed instead of matched as text, so a column inside them is no longer suggested as a plain index and gets the expression-index note (#84). A row comparison such as(a, b) > ($1, $2)no longer asks for an expression index (#85). -
PostgreSQL index check: a server newer than the tested releases (16 to 18) is still checked and now gets one notice in the session summary that its version is untested. Older servers keep their one "not checked" notice. The tested versions are listed in
docs/index-check.md. - The index check no longer rolls back a transaction the application opened by
hand on an AUTOCOMMIT connection (
exec_driver_sql("BEGIN"), with pg8000 or asyncpg). Theautocommitflag is the driver's setting, not the server's state, so the check now tries a savepoint first and starts a transaction of its own only when none is open (SQLSTATE 25P01). Fixes #91. - Documentation: the index check page was published as raw Markdown from the partial-index paragraph on, including its SQLite section (#117). A test now fails the build for any page left like that.
- Documented that PostgreSQL evaluates
IMMUTABLEfunctions with constant arguments at plan time, so the index check and the advisor can call such a function again and its non-transactional side effects (for examplenextval()) are not rolled back with the savepoint. Fixes #92. - The repeated-statement and small-repeat rules no longer count schema
reflection:
PRAGMAstatements, reads ofsqlite_master,sqlite_schemaand their temp variants, and reads ofpg_catalogorinformation_schema(MetaData.reflect(),Inspector.has_table(),create_all(), Alembic's version-table check).max_queriesbudgets still count them. Seedocs/how-detection-works.mdfor the exact rule (#129). -
PostgreSQL index check: a sequential scan whose filter is only not-equal comparisons against parameters (
<> $1,NOT INwith bound values) is no longer reported as a missing index. No index serves them, so the advice could not be followed, even on an indexed column; the SQLite check never reported them. A filter with one more servable condition, or a not-equal against a constant in the SQL (which a partial index serves), is still reported (#133). -
PostgreSQL index check: a server newer than the tested releases (16 to 18) is still checked and now gets one notice in the session summary that its version is untested. Older servers keep their one "not checked" notice. The tested versions are listed in
docs/index-check.md. - Documentation: the index check page was published as raw Markdown from the partial-index paragraph on, including its SQLite section (#117). A test now fails the build for any page left like that.
-
Baseline: a file nested more than 100 levels deep is now rejected by a depth check before parsing, so the "nested too deep" usage error no longer depends on the interpreter hitting its recursion limit (which on Python 3.10 could surface as a second, unraisable
RecursionError). -
--queryguard-update-baselineon a partial run (-k,-m,--deselect,--lf,--sw,--ignore, a node id or a path narrower thantestpaths, with or without pytest-xdist) no longer drops the entries of tests that did not run. Only the entries of tests that ran are replaced, the others are kept, and the summary says how many were kept. A deleted test's entries are removed on the next full run.docs/baseline.mddescribes which runs are full and which are partial. Fixes #148. -
--queryguard-update-baselinewith--collect-onlyemptied the baseline file. It now leaves the file alone and says why.
0.4.0rc2 - 2026-10-12#
Added#
- Community files:
CONTRIBUTING.md,SECURITY.md,CODE_OF_CONDUCT.md(Contributor Covenant 2.1), issue forms and a pull request template. - The documentation site has a description, canonical URL and Open Graph tags
on every page, a favicon,
sitemap.xml,robots.txt, a social preview image, a client-side search (no third-party code), "Edit this page" links and Previous/Next links. Every page needs adescriptionindocs/site.toml; the strict build fails without one. - A "Recipes" section in the documentation: FastAPI (
TestClientandhttpx.AsyncClientwith dependency-overridden sessions), Flask-SQLAlchemy, SQLModel, Litestar, pytest-asyncio configuration pitfalls, budgets for hot endpoints, adopting the plugin on a legacy codebase and CI. A new example,examples/fastapi-dependency-override, is run by the test suite. - Missing-index check for MySQL and MariaDB, behind the same switch
(
queryguard_index_check,--queryguard-index-check). Each distinctSELECT,UPDATEandDELETEis explained withEXPLAINand the real bound parameters (neverANALYZE); a table read in full (type: ALL, or an index read in full on a column that leads no index) although the statement filters or joins on its columns is amissing-indexfinding with aCREATE INDEXhint and an Alembic call. The suggestion is not verified: neither server has hypothetical indexes. Tested with PyMySQL and aiomysql on MySQL 8.4 and MariaDB 11.8 on a developer machine; CI does not run a MySQL or MariaDB server. Seedocs/index-check-mysql.md.
Changed#
- Tests: an accuracy corpus under
tests/corpus: 110 small scenarios of realistic ORM code (views, serializers, FastAPI, Flask-SQLAlchemy, SQLModel, repositories, pagination, bulk writes, async), each marked BUG or CLEAN, run through the plugin in its default configuration and with each opt-in rule. Limitations it found are indocs/limitations.md;scripts/accuracy_report.pyprints the precision and recall.
Fixed#
- A lazy load or column load that autoflushed pending changes first was attributed to the flush's write: the UPDATE or DELETE carried the relationship name and the load's SELECT carried none, so one loop was also reported as a repeated statement. Writes no longer take the pending attribution (#59).
- Documentation: the limitations page, the FAQ and the README now say that a
raw
sqlite3or other DB-API connection and non-SQLAlchemy ORMs (Django ORM, Peewee, Tortoise ORM) are not seen, and that nothing reports it; the limitations page also points to the repeat-scope limits. - The SQLite index check no longer says a table "is read in full" when the
plan walks an existing index that the filter cannot use (
SCAN INDEX ix_...). It says the table scans the whole index and that the filter does not match the start of any index; the suggestedCREATE INDEXis unchanged. - A SARIF result merged from several tests no longer shows one test's count in
message.textnext to the total inproperties.count. The message now starts withSeen in N tests: T times in total, up to M times in one test, andpropertiesgainstestsandpeakCountfor such results.count, the fingerprints and the baseline identity are unchanged. Seedocs/sarif.md. - The
repeated-statementhint no longer says to fetch the rows withWHERE id IN (...)when the statement already usesIN (...). It says the batched query ran several times and should be called once, or the calls combined. - Added
queryguard_repeat_scope(testorsession, defaulttest) andQueryLog.assert_no_nplusone(repeat_scope=...)for false positives in tests that make several requests. The repeat, relationship, column-load and write-loop rules counted over the whole test, so a test that made several independent requests (a test client, for example, with oneSessionper request) reported the same authentication or organisation lookup as a loop. Withsession, eachSession, or each connection checkout for statements noSessionran, is counted on its own. The default is unchanged, but a finding whose count spans several Sessions or checkouts now says so and names the option. Seedocs/several-sessions.md. - SARIF locations are now relative to the repository root when
GITHUB_WORKSPACEis set and the pytest rootdir is inside it. Before, they were relative to the rootdir, so with the action'sworking-directoryset to a subdirectory GitHub created alerts on paths that do not exist and showed no pull request annotations. Fingerprints and baseline identities are unchanged. Seedocs/sarif.md. - The action skips the SARIF upload for runs triggered by Dependabot (read-only token), and a refused upload no longer fails the job.
0.4.0rc1 - 2026-10-12#
Release candidate: install it with pip install --pre pytest-queryguard.
This release adds baselines, SARIF output and a GitHub Action, per-finding
ignores, new finding kinds (column loads, write loops, unused eager loads), query
timing and max_db_time, an index advisor, and a missing-index check for SQLite.
It also adds a documentation site and runnable examples. Three things can change the
result or the output of an existing test run without any new option: the column-load
kind is on by default, the index advisor is on by default with the index check, and
the index check now also runs on SQLite. They are listed first under "Changed" as
behavior changes, with how to turn them off, as the pre-1.0 clause of the
stability policy requires.
Added#
Missing indexes
- Missing-index check for SQLite, behind the same switch as PostgreSQL
(
queryguard_index_check,--queryguard-index-check). Each distinctSELECT,WITH,UPDATEandDELETEin a test body is explained withEXPLAIN QUERY PLANand its real bound parameters; the statement is not run, so data and transaction are untouched. A scanned table that the statement filters or joins on, or an automatic index, is amissing-indexfinding with aCREATE INDEX ix_<table>_<columns> ON <table> (<columns>)hint.LIKE, views,ORDER BYwithout a filter, primary keys and unrecognized plan shapes are left alone. Works withsqlite3, aiosqlite, SQLAlchemy ORM and Core, and pytest-xdist; findings honorqueryguard_ignore,allow_missing_index,queryguard_index_ignore_tables, the baseline and SARIF. Seedocs/index-check-sqlite.md.scripts/bench_overhead.py --index-checktimes it. - Index advisor. Each missing-index finding now suggests an index: a
CREATE INDEXbuilt from the equality, range andORDER BYcolumns of the plan node, a partial index when a constant predicate is selective, and the Alembicop.create_indexcall. When the hypopg extension is installed, the suggestion is verified inside the check's savepoint: whether the planner would use the index and the statement's estimated cost before and after; hypothetical indexes are reset, also after errors, on sync drivers and asyncpg. No new index is suggested when the table already has one for these columns (invalid, partial, or valid but unused), and the finding says why. Without hypopg the suggestion stays and one notice says how to install it. New optionsqueryguard_index_advisor(defaulttrue, used with the index check) andqueryguard_hypopg(auto,onoroff). Findings carry the suggestion in an additiveadvicefield. Seedocs/index-advisor.md.
New findings and rules
- Column-load detection, a new finding kind
column-load. Instances that each load a deferred column, or whose attributes were expired bycommit(),expire()orexpire_all(), on their own are reported with the right advice:undefer(Model.column)(or removingdefer(),load_only()ordeferred()), orexpire_on_commit=False;session.refresh()in a loop gets its own hint. The ini optionqueryguard_column_load_threshold(default 5 instances) and thecolumn_load_thresholdargument ofQueryLog.assert_no_nplusone()set the limit. The kind works withqueryguard_ignoreandallow_nplusone. - Write-loop detection, opt in:
queryguard_write_loop_threshold(off by default) and thewrite_loop_thresholdargument ofQueryLog.assert_no_nplusone(). The sameINSERT,UPDATEorDELETEshape run row by row from one source line is reported as the new finding kindwrite-loop, with a hint to usesession.add_all(),executemanyor a bulk statement.executemanyand multi-rowVALUESstatements are not counted. The statements of one ORM flush count as one write, soadd_all()and oneflush()is not reported even where the dialect sends oneINSERTper row; aflush()orcommit()per row is. The flush is found through SQLAlchemy'sSession._flushframe; if that changes, the rule counts every statement. The kind works withqueryguard_ignore,allow_nplusoneandqueryguard_fail_on. - Experimental detection of unused eager loads, off by default:
queryguard_unused_eager_load(off,warnorfail). A relationship a test loads withselectinload(),joinedload(),subqueryload()orimmediateload()and never reads is reported as the new finding kindunused-eager-load(labelClass.relationship), with a hint to remove the option. While the option isoffnothing is installed. Opt out withallow_nplusone(kind="unused-eager-load")orqueryguard_ignore. Seedocs/unused-eager-load.mdfor how it works and its limits. queryguard_small_repeat_threshold, an ini option (off by default) and thesmall_repeat_thresholdargument ofQueryLog.assert_no_nplusone(): a statement that ran a few times (belowqueryguard_repeat_threshold) from one source line, each time with different parameters, is reported as a repeated statement. Identical parameters, runs from several lines, writes and pagination are left alone. The default threshold of 5 is unchanged, so a batch of two to four statements is not flagged unless this is turned on.
Adopting it on an existing project
- Baseline file for existing findings:
queryguard_baseline(ini) or--queryguard-baseline=PATH, and--queryguard-update-baselineto write it. A finding whose identity (kind, label, file and function; rootdir-relative paths, no line numbers or counts) is in the file does not fail or warn, for every finding kind. New findings are reported as before, and entries that matched nothing in the run are listed as stale baseline entries. The file is JSON with aversionfield, sorted for clean diffs; a missing, corrupt or unknown-version file is a usage error. Works with pytest-xdist: workers apply the file, the controller merges what they saw and writes it on an update. Seedocs/baseline.md. - SARIF output:
--queryguard-sarif=PATHwrites the findings of the run as SARIF 2.1.0 for GitHub code scanning (the--queryguard-reportflag is unchanged). One rule per finding kind with a fix hint, one result per finding identity with a rootdir-relative location,partialFingerprintsderived from the identity, anderrororwarninglevel followingqueryguard_fail_on. Ignored and baselined findings are left out. Works with pytest-xdist: workers send their findings to the controller, which writes the file once. Seedocs/sarif.md. - A composite GitHub Action in
action/: installs the plugin, runs pytest with--queryguard-sarif, uploads the file withgithub/codeql-action/upload-sarif(pinned by commit SHA) and fails the step when pytest fails. Inputs:pytest-args,python-version,package,baseline,fail,working-directory,sarif-file,upload,category. The upload is skipped for pull requests from forks. A CI job runs the action onexamples/action-sample. Seedocs/ci.md.
Ignoring and gating
queryguard_ignore, an ini option that leaves single findings out of the reports. One pattern per line,KIND LABEL [file=GLOB] [function=GLOB], matched withfnmatch. The kinds arerelationship-load,repeated-statement,column-load,write-loop,unused-eager-loadandmissing-index;fileis relative to the rootdir.allow_nplusonetakes label patterns and the keywordskind,fileandfunctionto ignore only the findings they match. Without arguments it still ignores the whole test.- Ignore patterns that matched no finding in the run are listed in the terminal summary as stale ignores (not with pytest-xdist).
queryguard_fail_on, an ini option with finding kinds (fnmatchpatterns, one per line). Infailmode only these kinds fail a test; the other kinds are reported asQueryGuardWarning. Empty means every kind fails, as before. Budgets are not affected.
Timing and budgets
- Per-statement timing.
Query.durationis the time in seconds the database and the driver took for a statement, measured around the cursor call;QueryLog.db_timeis the total andQueryLog.slowest(n)the slowest statements. max_db_time(seconds), a context manager, and themax_db_timemarker: fail when the statements take longer than the limit in total. The failure lists the slowest statements. Amax_queriesfailure now shows the total database time and its slowest statements as well.
Documentation and examples
- A documentation site built from
docs/(scripts/build_docs.py, with the newdocsdependency group: Markdown and Pygments): getting started, how detection works, a configuration reference that a test keeps in step with the options, FAQ, limitations, a comparison with other tools and a migration guide from nplusone. The README is now a short overview that links to it. examples/with runnable projects (sync N+1, async FastAPI, PostgreSQL and SQLite missing indexes, baseline and SARIF), each with a README and a smoke test in CI.
Changed#
Behavior changes
- The
column-loadfinding kind is on by default (threshold 5, seequeryguard_column_load_threshold). A test that loops over deferred columns, or over objects expired bycommit(), passed before and now fails infailmode. To keep such tests green while you fix them, use a baseline,queryguard_fail_onwithoutcolumn-load(it then only warns), orqueryguard_ignore = ["column-load *"]. - Those loops used to be reported as a
repeated-statementwith the wrong advice (WHERE id IN (...)); they are no longer counted by that rule, so a baseline or ignore entry for such a finding has to use the new kind. - The index advisor is on by default whenever the index check is on
(
queryguard_index_advisor = falseturns it off). Missing-index findings now carry afix: CREATE INDEX ...line and analembic:line, and without the hypopg extension one notice at the end of the session says how to install it (queryguard_hypopg = offsilences it). queryguard_index_checknow also checks SQLite. A project that turned the check on and ran its tests on SQLite used to get a "not checked" notice and now gets findings, which fail tests infailmode.- Durations below one millisecond are printed in microseconds (
37 us) instead of0.0 msin the report and in budget failures. - The hint for a lazy-loaded many-to-one or one-to-one relationship is now
joinedload(...); collections still getselectinload(...). - A test stores at most 10000 statements and 10000 relationship loads for its
reports (
queryguard_max_events,0for no limit). Past the limit they are only counted. - When a listener raises, the plugin still stops measuring so that it never breaks the suite, but it warns and prints a "queryguard: measurement stopped" section instead of staying silent (see Fixed).
Everything else is off by default and changes nothing until you turn it on:
queryguard_small_repeat_threshold, queryguard_write_loop_threshold,
queryguard_unused_eager_load, queryguard_baseline, queryguard_fail_on (empty:
every kind fails, as before) and --queryguard-sarif.
Internals
- The missing-index check reads the conditions of a plan node with a tokenizer
and parser (
pytest_queryguard.predicates) instead of regular expressions over the text. PostgreSQL's JSON plan has no structured form of a predicate, so the relation, alias, schema and index still come from the plan's fields and the condition text is parsed into a tree; the old text matching stays as the fallback for syntax the parser does not know. Findings do not change. The parsing is tested on realEXPLAIN (GENERIC_PLAN, VERBOSE, FORMAT JSON)plans captured from PostgreSQL 14 to 18 (scripts/capture_plans.py). - The measurement registers one more SQLAlchemy listener (
after_cursor_execute) to time statements.scripts/bench_overhead.pyputs the added cost of all the measurement, not of this listener alone, at about 20 to 55 microseconds per statement on in-memory SQLite (roughly +30 to +40 %); against a real database round trip it is small. See the FAQ. - Internal: detectors now hand their results to a stable
Findingmodel (kind,label,file,function,message,severity) before the report is rendered. The messages and the public API are unchanged. - The check that decides whether a stack frame belongs to SQLAlchemy, pytest or
the standard library is now cached per file name. Measured with
scripts/bench_overhead.py, this cuts the per-statement overhead of the measurement by about half.
Fixed#
- The index check no longer reports a missing index, and the advisor no longer
recommends a redundant one, for a statement that an existing partial index
may serve. The generic plan cannot see bound values, so it could not know
that
status = $1matches... WHERE status = 'open'. Such statements are skipped and counted in the session summary. A missing index on them is not found; see the limitations. - Loops over deferred or expired columns were reported as a repeated statement
with the wrong advice (
WHERE id IN (...)). They are now acolumn-loadfinding and no longer count towards the repeated-statement rule. - When a listener raises, the plugin still stops measuring so that it never
breaks the suite, but it no longer does so silently. The warning names the
listener or step that failed, and the end of the session prints a
"queryguard: measurement stopped" section with the listener, the error and
the line that raised it, once per session, with or without
--queryguard-report.
0.3.0 - 2026-10-11#
Added#
- The missing-index check now covers async engines on asyncpg. asyncpg
prepares statements, and PostgreSQL would take the
$ninsideEXPLAINas theEXPLAIN's own parameters. So on asyncpg theEXPLAINruns in a PL/pgSQLDOblock on the test's own connection and savepoint, and the plan comes back through a transaction-local setting. Findings, notices and guarantees are those of sync engines. Other async drivers are still skipped with a notice. Seedocs/design-0.3.md. - On a database without PL/pgSQL, the asyncpg index check now reports one
notice for the session instead of one failed
EXPLAINper statement. pytest_queryguard.record_queries(), a context manager that records the SQL statements a block sends and yields aQueryLog. The log has the statements asQueryobjects (sql,callsite,relationship), theircount, andassert_no_nplusone(), which applies the N+1 rules to the block and raisesNPlusOneDetected.Query,QueryLog,CallSiteandNPlusOneDetectedare exported for type hints. It works in pytest and outside it, and changes nothing else. AQueryLogis also sized, iterable and indexable (len(),for,log[i],log[a:b]) but not acollections.abc.Sequence.QueryGuardInternalWarning(exported since 0.2.0) is now documented. Arecord_queries()block that ends after an internal error (including one recorded before the block, which had already stopped the recording) issues it, saying that the log may be incomplete, andQueryLog.assert_no_nplusone()raisesRuntimeErrorinstead of passing on such a log. This also applies outside pytest and with--queryguard-mode=off, where the plugin itself reports nothing.
Changed#
- The index check reads the first column of each btree index and the
varcharcolumns of each table from the catalog once per engine for the whole session instead of once per test. Any statement that may change them (CREATE,DROP,ALTER,REINDEX,TRUNCATEand other DDL, seen in tests and fixtures alike) clears the cache, as does the end of a transaction that ran one. On 100 tests with 10 indexed statements each against PostgreSQL 17, the check went from about 2.3 ms to 1.2 ms per statement (#5). The same statement is explained again after such DDL, so a rolled-back index change no longer hides a finding. Clearing is safe while a plan is being read, also from another thread or when a connection is garbage collected, and when a two-phase transaction with DDL ends. A statement that cannot be planned is counted once in the "could not be explained" summary even when DDL made the check retry it. QueryLog.assert_no_nplusone()is documented as ignoring thequeryguard_*ini options: a project with a customqueryguard_repeat_thresholdpassesrepeat_thresholdexplicitly.- Paths in the
NPlusOneDetectedmessage, and in theQueryBudgetExceededmessage of awith max_queries(n):block, are relative to pytest's rootdir, as in the plugin's own failures, instead of the working directory (which is still the base outside pytest).
Fixed#
- The index check now judges temporary tables: trailing columns of their
multicolumn indexes and
varcharcasts were silently skipped, because PostgreSQL names the schemapg_tempin plans andpg_temp_<n>in the catalog. - The index check now reports a partial index read in full as a bitmap.
With an index such as
(id) WHERE deleted_at IS NULLandWHERE deleted_at IS NULL AND email = ?, the plan beforeANALYZEwas skipped, while the plan after it was reported (#4).
0.2.0 - 2026-10-11#
Added#
- Missing-index check for PostgreSQL 16 and newer, off by default. With
--queryguard-index-checkorqueryguard_index_check = true, each distinctSELECTin a test body is planned withEXPLAIN (GENERIC_PLAN, VERBOSE, FORMAT JSON)andenable_seqscanoff, inside a savepoint on the statement's own connection. The test fails (or warns, inwarnmode) when the plan reads a whole table to apply a filter, walks a whole index for an equality filter, or uses an index condition that leaves out a btree index's first column (PostgreSQL 16 and 17). The message names the table, the condition, the SQL and the call site and, when the column is obvious, gives aCREATE INDEXhint. --no-queryguard-index-checkto turn the check off for one run.queryguard_index_ignore_tablesini option and@pytest.mark.allow_missing_indexmarker to exclude small lookup tables or whole tests from the index check.- A session summary for statements the index check could not check: other databases, PostgreSQL before 16, async engines, statements PostgreSQL could not plan, and a check stopped by a broken savepoint.
- CI job that runs the test suite against PostgreSQL 15, 16 and 17.
Changed#
INlists whose placeholders carry multi-word, schema-qualified or quoted type casts ($1::DOUBLE PRECISION,$1::public.mood) or useCAST(? AS INTEGER)now collapse to one form for N+1 detection.
0.1.0 - 2026-10-11#
First release.
Added#
- Automatic N+1 detection for SQLAlchemy 2 in every test, with no
configuration. Two rules: one relationship lazy-loaded for several parent
objects, and one normalized
SELECTrepeated several times. - Failure messages that point to the line of application code that caused
the N+1, show the SQL involved and, for relationship loads, suggest a
selectinloadfix. @pytest.mark.max_queries(n)marker (alsomax_queries(n=...)) that fails a test running more thannSQL statements and lists every statement with its call site.pytest_queryguard.max_queries()context manager, which raisesQueryBudgetExceededand also works outside pytest.@pytest.mark.allow_nplusonemarker to skip N+1 detection for one test.- Ini options
queryguard_mode(fail,warn,off),queryguard_relationship_thresholdandqueryguard_repeat_threshold, readable from[tool.pytest.ini_options],pytest.ini,setup.cfgand pytest 9's native[tool.pytest]table. --queryguard-modecommand-line option that overrides the ini value.--queryguard-reportcommand-line option that prints the ten tests with the most queries at the end of the session.- Support for
AsyncSession, FastAPI'sTestClientand code that queries from other threads. - Only the test function body is measured; fixture setup and teardown are not.
- An internal error disables the plugin with a single warning instead of failing the test suite.