Accuracy on a corpus of realistic code#

How often does pytest-queryguard report code that is fine, and how often does it miss code that is not? This page measures that on a corpus of 283 small scenarios, publishes the numbers, and lists every disagreement. The scenarios were written by the author of the plugin, so read the numbers as a regression baseline and a list of known limits, not as a benchmark of how the plugin does on your code.

Method#

Measured on 2026-11-07 on Linux 7.0.0 (x86_64, 13th Gen Intel Core i5-13500H, 16 threads), Python 3.13.18, SQLAlchemy 2.1.1, pytest 9.1.1, Flask-SQLAlchemy 3.1.1, FastAPI 0.141.1, pytest-queryguard 0.8.0 at main e527a3a plus the changes of its pull request (the scenarios and the two fixes below), with uv run python scripts/accuracy_report.py. The default tables, the opt-in tables and the release thresholds were measured again on the same day after the review of every disagreement (see Every disagreement reviewed), on the same machine and packages with Python 3.14.4; the two runs differ only in the scenarios that review changed. SQLModel was not installed (it needs SQLAlchemy below 2.1 and is only installed in the SQLAlchemy 2.0 CI job), so 272 of the 274 scenarios ran: 133 BUG and 139 CLEAN. The six scenarios of test code and calls on separate lines were added on 2026-11-07 and every table of the default and opt-in configurations was measured again then, with the plugin at main 7c7f2a8 plus the changes of its pull request (Python 3.13.18, the same packages): 278 of 280 scenarios ran, 135 BUG and 143 CLEAN. All numbers on this page are for those and SQLite (the same on MySQL and MariaDB), except the PostgreSQL run, which is the earlier 141-scenario measurement and says so, and the comparison with other tools, which ran the same 278 scenarios in GitHub Actions on 2026-11-10.

Three scenarios of loops of the test were added on 2026-11-15, after these measurements: clean_142_requests_in_a_test_loop (a loop of the test that calls a handler once per pass; the test code's repetition, see Loops of the test), clean_143_service_called_per_case_in_a_test_loop (an arrange step that calls a service with a limit check per row, as in a Django project's suite, where five tests needed a marker for it) and bug_137_application_loop_in_each_pass_of_a_test_loop (a handler that reads a relationship per row in each pass). In every configuration bug_137 is a relationship-load TP and clean_142 is clean, except in strict mode, which reports clean_142 as it reports clean_140; clean_143 is clean in every configuration. With them the relationship-load rows below are 53 TP (strict: 53 TP, 2 FP); the other rows do not change.

Results, default configuration#

117 of the 121 BUG scenarios that the default rules can report are flagged (the other 14 BUG scenarios are write loops, unused eager loads and unused columns, which are opt-in), and 2 of the 157 scenarios without an expected default kind are flagged.

kind TP FP FN precision recall
relationship-load 52 0 0 100% 100%
repeated-statement 47 1 3 98% 94%
column-load 12 0 1 100% 92%
cartesian-load 7 1 0 88% 100%

The small counts (52, 50, 13, 7) mean that one scenario moves a percentage by several points. The relationship-load row is 51 scenarios, not a claim about every ORM pattern.

The static-check scenarios (2026-11-07)#

14 scenarios (8 BUG, 6 CLEAN) were added later on 2026-11-07 to measure the static check: shapes reported to other static checks (orm-lens #72, #85, #146) and common ones (a repository with a service, FastAPI and Pydantic lists, a template-like loop, a statement built over several lines, an aliased() entity, an early return, an if guard), bug_125 to bug_132 and clean_131 to clean_136. All are relationship-load BUG or CLEAN, and all agreed with their verdict in every configuration, so they add 8 relationship-load true positives (51 instead of 43) and true negatives only; 6 of the 8 get a patch from --queryguard-write-patch (26 of 51 in all). The other tables on this page were not run again; only the relationship-load counts were updated.

Sessions begun on separate lines, before and after#

The real-world run of MLflow's tracking store found false findings of one shape: every store method opens its own Session and runs a shared lookup, and a test calls the store on separate lines with no loop. With the whole test one unit, the lookups of separate calls added up like the passes of a loop. Two CLEAN scenarios have that shape (clean_133_service_calls_at_separate_lines, a relationship read per call; clean_137_store_methods_at_separate_lines, a lookup six times), and two BUG scenarios loop over such a store (bug_133_store_method_per_key_in_loop, the shape of MLflow's test_log_batch_limits; bug_134_store_methods_alternating_in_loop, a loop whose passes call two methods in turn). The fix: a Session begun from application lines that no other Session of the test began from is counted on its own; those begun from repeated lines are counted together, as before.

configuration, kind before: TP, FP, FN after: TP, FP, FN
default, relationship-load 51, 1, 0 51, 0, 0
default, repeated-statement 47, 2, 2 47, 1, 2
small-repeat = 2, repeated-statement 49, 4, 0 49, 2, 0
write-loop = 2, write-loop 8, 4, 0 8, 3, 0
strict = true, relationship-load 51, 1, 0 51, 0, 0
strict = true, repeated-statement 46, 2, 3 46, 1, 3

Both runs have the four scenarios of this shape (272 ran after; the relationship-load rows of the "before" column add the 8 static-check BUG scenarios, which agree with their verdict in every configuration without the change). The rows of the default kinds change the same way with the other opt-in rules on. No other scenario changed in any configuration; both BUG scenarios are reported before and after, except with queryguard_scope = session, which counts each Session on its own by design.

Test code and calls on separate lines, before and after#

A run of Faraday's suite (2112 tests) with the plugin installed and its defaults failed about a quarter of the tests, nearly all for code that is not the application: a factory that looks the role up for every user it creates, helpers of the tests that read relationships lazily, a statistics function that runs one count per severity on lines of its own, and tests that send several requests through the test client, whose Session all requests share. Four CLEAN scenarios have those shapes (clean_138_factory_lookup_per_object, clean_139_lazy_loop_in_a_test_helper, clean_140_requests_at_separate_lines, clean_141_same_count_at_separate_lines), and two BUG scenarios check that a loop in the application is still reported when test code calls it (bug_135_app_loop_called_from_a_test_helper, through a helper of the test; bug_136_lookup_loop_among_separate_requests, one of several requests sent on separate lines). The changes: a finding whose statements all ran in test code is left out by default (Test code), and a statement whose call path no other run of it has is counted on its own (Calls on separate lines).

configuration, kind before: TP, FP, FN after: TP, FP, FN
default, relationship-load 52, 3, 0 52, 0, 0
default, repeated-statement 48, 4, 2 47, 1, 3
small-repeat = 2, repeated-statement 50, 5, 0 50, 2, 0
write-loop = 2, write-loop 8, 4, 0 8, 3, 0
scope session, repeated-statement 42, 4, 8 41, 1, 9
strict = true, relationship-load 52, 3, 0 52, 1, 0
strict = true, repeated-statement 47, 3, 3 46, 1, 4

Both columns ran the same 278 scenarios, the six new ones included. The rows of the default kinds change the same way with the other opt-in rules on; no other scenario changed in any configuration. The new false negative is bug_46_fstring_sql_literals: a comprehension of four passes and a fifth run on a line of its own, which is now four runs of a loop, below the threshold of 5 (the small-repeat rule reports it). The false positive left in strict mode is clean_140: strict mode raises at a lazy load, before the later loads show which test lines call the application again, so it counts the lazy loads of all test lines together.

Every disagreement reviewed (2026-11-07)#

After the scenarios of 2026-11-07 were added, each disagreement of the default configuration and each documented limit (73 strict xfails of (scenario, configuration)) was read again and put in one of three classes: a bug of the plugin, fixed at its cause with a unit test first; a limit of the approach, explained in the user documentation with a workaround; or a wrong verdict, corrected. No verdict was wrong. Two causes were bugs:

The other 58 are limits, each explained where a user looks for it (the page in brackets) with what to do. (bug_04 and bug_06 in strict mode, a strict error that Pydantic wraps, were limits too; they are fixed since.)

scenarios configurations limit what to do
clean_16_polling_loop all a polling loop and a loop-invariant query repeat one statement with the same parameters (Limitations) the queryguard_ignore marker on the test
clean_82_two_small_collections_joined all the cartesian-load rule cannot know that collections stay small (How detection works) it only warns by default; an ignore pattern or ignore("cartesian-load") for a product that stays small by design
bug_42, bug_45 (repeats), bug_44 (column loads) all but the threshold-2 ones below the default thresholds of 5 (Limitations) queryguard_small_repeat_threshold, queryguard_column_load_threshold
clean_20, clean_22 small-repeat, column-load-2 what those lower thresholds also report (Limitations) keep the defaults, or ignore the test
clean_18, clean_30, clean_77 write-loop, all opt-in seeding and per-row writes on purpose look like a write loop (Limitations, Factory Boy) the rule is opt-in for that reason
bug_47, bug_48, bug_52, bug_53 session-scope each Session is counted on its own, by design (Several sessions) the default scope
bug_86_unused_columns_via_selectinload unused-columns, all opt-in rows loaded through a relationship are not grouped (Unused columns) selectinload(...).load_only(...) by hand
clean_124_collection_checked_through_inspect unused-eager-load, all opt-in reads through inspect() are invisible (Unused eager loads) ignore it
bug_88_strict_lazy_then_lookup_loop strict strict mode stops the test at the first N+1 (When a test fails) fix it and run again, or run without strict mode

Before and after, every configuration, on the 252 scenarios that ran (no other finding of any scenario changed in any configuration):

configuration kind before: TP, FP, FN after: TP, FP, FN
every configuration cartesian-load 6, 1, 1 (86%, 86%) 7, 1, 0 (88%, 100%)
unused-columns = fail, all five rules unused-columns 8, 2, 1 (80%, 89%) 8, 0, 1 (100%, 89%)

The scenarios of 2026-11-07, before and after#

57 scenarios were added on 2026-11-07 (28 BUG, 29 CLEAN) for mapping and loading features the corpus did not have, and for shapes reported to other tools (see the method). Before the two fixes of the same pull request they disagreed with their verdict in two places, and one verdict had to be corrected:

All other new scenarios agreed with their verdict in every configuration. Before and after, for the default configuration, on the whole corpus:

kind 2026-11-06, 195 ran: TP, FP, FN 2026-11-07, 252 ran: TP, FP, FN
relationship-load 29, 0, 0 43, 0, 0
repeated-statement 37, 1, 2 45, 1, 2
column-load 6, 0, 1 12, 0, 1
cartesian-load 6, 1, 1 6, 1, 1

The new scenarios add true positives and true negatives only, because they were checked against the plugin while they were written: read them as a regression baseline for these features, not as a measurement of new precision.

The newer kinds, before and after 2026-11-06#

Before 2026-11-06 the corpus had 147 scenarios (145 ran) and did not measure cartesian-load, unused-columns or strict mode at all; unused-eager-load was one BUG scenario. 50 scenarios were added for them. The plugin's findings did not change: the one fix of that change is to the patch file (see The patch of --queryguard-write-patch). The relationship-load rule changed right after, in #307; the "after" column is measured with it.

kind (configuration) before: TP, FP, FN after: TP, FP, FN precision, recall after
cartesian-load (default, warns) not measured 6, 1, 1 86%, 86%
unused-eager-load (= fail) 1, 0, 0 5, 0, 0 100%, 100%
unused-columns (= fail) not measured 8, 2, 1 80%, 89%
relationship-load (strict) not measured 27, 0, 2 100%, 93%
repeated-statement (strict) not measured 36, 1, 3 97%, 92%
relationship-load (default) 20, 0, 0 29, 0, 0 100%, 100%
repeated-statement (default) 36, 1, 2 37, 1, 2 97%, 95%
column-load (default) 5, 0, 1 6, 0, 1 100%, 86%

The "before" column for the default kinds is the 145-scenario run of 2026-11-06 on the same machine and packages, before the new scenarios. One new CLEAN scenario, clean_93_two_single_object_lookups (one order from session.get, another from a select, each showing its customer), was a relationship-load false positive in every configuration, strict mode included: the rule counted the distinct parents of a relationship wherever they were loaded. Since #307 the report groups the parents by the query line that loaded them, as strict mode does, and the scenario passes; no other scenario's findings changed.

The repeated-statement precision went from 83% to 89% when 13 BUG and 10 CLEAN scenarios were added on 2026-10-13, with the plugin unchanged: the same 4 false positives against 12 more true positives. That is a change of the corpus, not of the plugin. The 12 new repeated-statement BUG scenarios include shapes chosen to look like batching or pagination (LIMIT 1 OFFSET n per row, the first page of each customer's orders, IN lists of one id or built from each item) and a loop-invariant query with the same parameters on every run. Five more BUG scenarios, bug_64 to bug_68, were added while reviewing the rule for pagination and chunks: loops that it first left alone (an IN list of each customer's ten orders, WHERE id > :row_id LIMIT 3 per row, the same on a string column, a paginated loop-invariant lookup per order) and a moving window read with LIMIT 3 OFFSET i.

Before and after the rule for pagination and chunks#

On 2026-10-13 the repeat rules learned to leave pagination and chunked IN loads alone when their parameters show them (see "Pagination and chunks" in How detection works). The same 141 scenarios, before and after:

configuration repeated-statement before after
default 36 TP, 9 FP, 2 FN (80%, 95%) 36 TP, 1 FP, 2 FN (97%, 95%)
small-repeat = 2 38 TP, 11 FP, 0 FN (78%, 100%) 38 TP, 2 FP, 0 FN (95%, 100%)
repeat scope session 32 TP, 8 FP, 6 FN (80%, 84%) 32 TP, 1 FP, 6 FN (97%, 84%)

No BUG scenario was lost in any configuration: the findings of every BUG scenario are the same before and after in all seven configurations, and the BUG scenarios that look like pagination or batching (bug_58 to bug_60, bug_63 to bug_68) are still reported. Read the "before" column with care: five of the CLEAN scenarios (clean_62_dataloader_max_batch_size, clean_69_celery_batch_task_chunks, clean_72_keyset_pagination_desc, clean_73_paginate_twice, clean_74_chunked_in_string_keys) were written together with the rule, to test it, so they are false positives before it by construction. Without them, on the 136 scenarios without them, the default row goes from 36 TP, 4 FP (90%) to 36 TP, 1 FP (97%): the three false positives removed are clean_12_offset_pagination, clean_13_keyset_pagination and clean_15_chunked_in_six_chunks. clean_14_chunked_in_three_chunks is no longer reported by the small-repeat rule either.

Results with the opt-in rules#

configuration kind TP FP FN precision recall
small-repeat = 2 repeated-statement 50 2 0 96% 100%
write-loop = 2 write-loop 8 3 0 73% 100%
column-load threshold 2 column-load 13 2 0 87% 100%
unused-eager-load = fail unused-eager-load 5 1 0 83% 100%
unused-columns = fail unused-columns 8 0 1 100% 89%
repeat scope session repeated-statement 41 1 9 98% 82%
strict = true relationship-load 52 1 0 98% 100%
strict = true repeated-statement 46 1 4 98% 92%
all five rules repeated-statement 50 2 0 96% 100%
all five rules column-load 13 2 0 87% 100%
all five rules write-loop 8 3 0 73% 100%
all five rules unused-eager-load 5 1 0 83% 100%
all five rules unused-columns 8 0 1 100% 89%

relationship-load stays at 52 TP, 0 FP, 0 FN in every configuration but strict mode, which reports clean_140_requests_at_separate_lines (see above), and cartesian-load at 7 TP, 1 FP, 0 FN in every configuration. The unused-eager-load row is five BUG scenarios (a joined many-to-one of which only the foreign key is read, the unread second link of a selectinload chain, a repository method reused by a page that needs less, an async handler) against CLEAN scenarios where the eager load is read by some rows only, by Pydantic, by an association_proxy, or by a delete cascade. Its one false positive is clean_124_collection_checked_through_inspect (a read through inspect(), see below). With all rules on, 134 of 135 BUG scenarios are flagged, and 9 of 143 CLEAN scenarios are.

Effect of queryguard_scope = session (added after the first run of this corpus): the scenarios that run each lookup in its own Session (bug_47_session_per_item, bug_48_threadpool_lookups, bug_52_async_gather_session_per_task, bug_53_celery_task_per_id, bug_133_store_method_per_key_in_loop, bug_134_store_methods_alternating_in_loop) are no longer reported, which is what the option is for; they are reported by default, and the six false negatives are the price. Calls on separate lines, each with a Session of its own, need no option (clean_133_service_calls_at_separate_lines, clean_137): see Sessions begun on separate lines. In both scopes the only CLEAN scenario the default rules report is the polling loop, which repeats one statement inside one Session.

Every disagreement#

scenario verdict the plugin why
bug_42_small_get_loop_below_threshold, bug_45_async_session_get_small BUG: 4 and 3 get calls not reported The repeat threshold is 5. The small-repeat rule reports both.
bug_44_expired_after_commit_three BUG: 3 objects reload after a commit not reported The column-load threshold is 5. Threshold 2 reports it.
bug_46_fstring_sql_literals BUG: a comprehension of 4 lookups with literals, and a fifth on a line of its own not reported since the rule for calls on separate lines A run whose call path no other run has is no pass of a loop, so the loop has 4 runs, below the repeat threshold of 5. The small-repeat rule reports it.
clean_138, clean_139, clean_140, clean_141 CLEAN: a factory's lookup per object, a test helper's lazy loop, requests on separate lines through one Session, one count per line relationship-load and repeated-statement before the rules for test code and calls on separate lines, nothing after; clean_140 still relationship-load in strict mode See Test code and calls on separate lines.
bug_50_cascade_delete_loop BUG: delete cascade loads per parent relationship-load and also repeated-statement (before the fix) Bug #59, fixed: an autoflush before the lazy load took over its relationship attribution. After the fix the repeated-statement false positive of this scenario is gone, and the repeated-statement rows on this page were re-measured.
clean_12_offset_pagination, clean_13_keyset_pagination, clean_15_chunked_in_six_chunks CLEAN: pages and chunks repeated-statement before 2026-10-13, nothing after Fixed by the rule for pagination and chunks (#60). clean_14_chunked_in_three_chunks was reported by the small-repeat rule before it.
clean_16_polling_loop CLEAN: polling a status on purpose repeated-statement Every run has the same parameters, like the loop-invariant query of bug_55_loop_invariant_query, which is a bug. The statements cannot tell them apart. Use the queryguard_ignore marker.
clean_20_cached_lookup CLEAN repeated-statement with small-repeat on Two statements of one shape from one line are what the rule reports.
clean_22_expire_on_commit_two_objects CLEAN column-load with threshold 2 Two reloads after a commit are the threshold.
clean_132_new_objects_read_one_by_one CLEAN column-load with threshold 2 Three refreshes after one commit: of the rows of one flush only the first refresh is let through.
clean_18_factory_boy_seed_in_body, clean_30_savepoint_per_row_insert, clean_77_refresh_after_each_create CLEAN: seeding, per-row inserts with their own error handling, eight creates each refreshed write-loop with the rule on The rule cannot tell them from a write loop.
bug_47_session_per_item, bug_48_threadpool_lookups, bug_52_async_gather_session_per_task, bug_53_celery_task_per_id, bug_133_store_method_per_key_in_loop, bug_134_store_methods_alternating_in_loop BUG not reported with scope session By design of the option.
clean_93_two_single_object_lookups CLEAN: one order from session.get, another from a select, each showing its customer relationship-load in every configuration before #307, nothing after Fixed by #307: the report groups the parents of a relationship by the query line that loaded them, as strict mode does, so two single-object lookups at two lines are no N+1.
clean_82_two_small_collections_joined CLEAN: a user's two roles and two e-mail addresses joined in one login query cartesian-load (a warning) The rule reads the loader strategies, not how many rows the collections hold. A product of 2 x 2 rows is reported like one of 20 x 20.
bug_77_cartesian_mapping_lazy_joined BUG: two collections with lazy="joined" on the mapping not reported before the fix; cartesian-load after Fixed on 2026-11-07: the rule follows the loader strategies of the mapping, not only the options of the query.
bug_76_cartesian_async_endpoint, clean_78_joined_collection_and_scalar the cartesian verdict, and no unused columns: a page for one article unused-columns with the check on, before the fix; nothing after Fixed on 2026-11-07: a query that pins the whole primary key returns one row, and the check no longer reports a group of such queries.
bug_86_unused_columns_via_selectinload BUG: selectinload(Author.articles), only title read of each article not reported by the unused-columns check The check groups only the instances a query returns itself, not those loaded through a relationship (documented in Unused columns).
bug_04_pydantic_from_attributes, bug_06_fastapi_response_model BUG: Pydantic from_attributes and a FastAPI response_model over lazy relationships no finding in strict mode before the fix; relationship-load after Pydantic catches the NPlusOneDetected that strict mode raises at the access and raises its own validation error, with the strict message inside. The plugin saw that error, not its own, so the report at the end (and SARIF, --queryguard-json, the summary) did not run. Fixed after 0.8.0: when strict mode raised in a test that then fails with another error, the analysis still runs and records the N+1; the test keeps failing with the library's error.
bug_88_strict_lazy_then_lookup_loop BUG: a lazy loop, then a session.get loop only relationship-load in strict mode Strict mode stops the test at the first N+1, so the second loop never runs.
clean_123_polymorphic_subclass_without_rows CLEAN: selectinload of a subclass relationship, no subclass rows in the data unused-eager-load with the check on, before the fix; nothing after Fixed on 2026-11-07: reads of base-class rows no longer count as reads of instances that could have the subclass's relationship.
clean_124_collection_checked_through_inspect CLEAN: the collection is read through inspect(obj).attrs.x.loaded_value unused-eager-load with the check on The check sees reads through the attribute, not through inspect() or __dict__ (documented in Unused eager loads).
bug_18_joined_inheritance_columns, bug_99_polymorphic_collection_subclass_columns, bug_114_single_table_subclass_columns BUG: subclass columns loaded per row after a query of the base class column-load, as expected, but labelled (expired) with the expire_on_commit=False hint, before the fix Fixed on 2026-11-07: labelled (polymorphic), with the selectin_polymorphic hint. The kind did not change, so the tables did not either.

The four BUG scenarios below the default thresholds, and the BUG scenarios that are only write loops, unused eager loads or unused columns, are the "FN" column of the default tables or are outside their scope; they are listed here rather than hidden.

Not shown because they agreed with the verdict: lazy-load loops through views, serializers, Pydantic, FastAPI (sync and async), Flask-SQLAlchemy, SQLModel, __str__, properties, hybrids, many-to-many, nested relationships, trees, Jinja templates, with_parent, joined-table inheritance, deferred columns, expired columns, session.refresh, Core and text() and driver SQL loops, merge loops, dynamic relationships, threads and a session per item, GraphQL-style resolvers, a DataLoader awaited key by key, asyncio.gather and Celery-style fan-out, caching repositories that miss, with_for_update per row, yield_per with a query per row, LIMIT 1 OFFSET n walks, a first page per customer, IN lists of one id or built per item (also ten ids per customer), a keyset-shaped query per row on an integer and on a string column, a paginated lookup per order, a moving window with LIMIT 3 OFFSET i, a loop-invariant query and per-row upserts (with the write-loop rule on); and, as CLEAN, all the eager loading fixes, loader options on the mapping, raiseload, identity-map hits, new objects, backref assignment, executemany, multi-row VALUES, add_all, streaming, savepoints, recursive CTEs, bulk updates, a batching DataLoader, selectinload two levels deep over 1500 parents, yield_per with selectinload, ORM bulk UPDATE and INSERT with a list of rows, a multi-row upsert, one FOR UPDATE for a batch, a nested transaction around a batch, a prefetching repository, asyncio.gather over different statements, and pagination and chunked loads: offset and keyset pages (also newest first, and the same walk twice), IN chunks of ids and of string keys, a DataLoader with a maximum batch size, and Celery-style tasks per chunk.

Of the scenarios added on 2026-11-07, all but clean_124 agree with the verdict in every configuration (clean_123 since its fix). As BUG: lazy loads under single- and concrete-table inheritance, through an association_proxy, a viewonly relationship with a custom primaryjoin, a "generic foreign key", a self-referential many-to-many, a composite foreign key, lazy="immediate", MappedAsDataclass and imperative mappings, an async awaitable_attrs many-to-one, a loop over a limit(10) query, an eager load dropped by populate_existing or made in another Session; column loads of a deferred_group, of a column load_only left out, of subclass columns (a polymorphic collection, single-table inheritance), of a refresh(obj, ["orders"]) per customer and of a commit() per row (with its UPDATEs under the write-loop rule); repeated statements of a WriteOnlyMapped select per author, session.get with a composite key, a populate_existing select per row, an exists() check per imported row, IN lists of one to four ids, a batch loader called with one id, an "attach related" helper and one lookup reached through two helpers in turn. As CLEAN: selectin_polymorphic, polymorphic_load="selectin", single-table with_polymorphic, undefer_group, query_expression with with_expression, appending to WriteOnlyMapped collections, a viewonly and a self-referential many-to-many relationship loaded with selectinload, session.get with a composite key answered by the identity map, lazy="subquery" and lazy="noload" mappings, one populate_existing query after a bulk UPDATE, merge(load=False), bulk_save_objects, two foreign keys and two selectinload chains to one table, a five-check sign-up validator, tags assigned through a two-way many-to-many, eager loads of empty collections, contains_eager over an outer join that keeps empty collections, an eager chain read only by a proxy and a property, a second query answered by the identity map, a custom __eq__ over a joined relationship, pickled eager results and six dashboard queries that differ only in a select-list subquery.

Of the scenarios added on 2026-11-06, these agreed with the verdict in every configuration: two and three collections joined side by side (a detail page, an admin CSV export, the legacy session.query() API, an async endpoint), two joined collections inside the query of a selectinload, a many-to-one on the way to one of them; as CLEAN, a joined collection with a joined many-to-one, a joinedload chain, joinedload with selectinload, contains_eager over a filtering join, two selectinload chains in a FastAPI endpoint, one joined collection on a paginated query and a collection of each subclass under with_polymorphic; the unused-eager-load scenarios above; unused columns in a sitemap, a three-field Pydantic summary, an async background job and a paginated API, and, as CLEAN, load_only, a to_dict of every column, a select of three columns, an edit form that reads seven of twelve, and deferred columns with a column_property; in strict mode, a view whose except Exception swallows the strict error (the report at the end still fails the test); ignore() around a loop, as a decorator and around asyncio.gather (CLEAN), and one that a later access outside it escapes (reported in full); an N+1 in a fixture only (CLEAN) and a loop in the test over parents a fixture loaded (reported); an association object walked lazily, a marshmallow-style nested schema, a paginated API reading each author, a self-referential comment thread, a polymorphic list reading a subclass's collection and a deferred column_property read per row.

The patch of --queryguard-write-patch#

tests/corpus/test_fix_patches.py copies the corpus into the rootdir of a pytest session, runs the 52 BUG scenarios with a relationship-load with --queryguard-write-patch, applies the patch with git apply --check and git apply, and runs them again, with queryguard_test_code = fail: the copy is below a tests/ folder of the rootdir, where the plugin would take the scenarios for test code. A scenario module with PATCH = True expects a patch; every other one expects none, so a patch that appears or disappears fails the test.

Measured on 2026-11-07: 27 of the 52 get a patch; every patch applies, and in all 27 the relationship-load is gone after it, with no new finding (a joinedload next to another joined collection would be a cartesian-load). The other finding of bug_88_strict_lazy_then_lookup_loop, a repeated-statement, stays, as it should. The 25 without a patch, each a case where the patch cannot be certain of the change:

why no patch scenarios
the query runs inside a comprehension or generator expression 14 (bug_03, bug_13, bug_16, bug_19, bug_41, bug_43, bug_92, bug_100, bug_104, bug_105, bug_112, bug_113, bug_122, bug_123)
a recursive walk of a self-referential relationship: the deeper parents were loaded by the relationship itself, so no one query started them 2 (bug_37, bug_95)
the objects were first loaded by another query that already eager-loads the relationship, and populate_existing or a second Session undid it 2 (bug_116, bug_117)
Flask-SQLAlchemy's db.select(Author) 1 (bug_07)
select(with_polymorphic(...)) or select(aliased(...)) 2 (bug_96, bug_130)
a statement assigned more than once (stmt = stmt.options(...)) 1 (bug_129)
the parents were loaded by a fixture, before the measurement 1 (bug_90)
the query selects the base class of a concrete-table hierarchy (select(Payment)), the relationship is a subclass's own 1 (bug_98)

The fix: line of the report still shows the option for each of them.

Fixed with the 2026-11-07 measurement: 10 scenarios that got no patch now get one. A class named through its module (select(shop.Customer), 14 scenarios before) is patched as selectinload(shop.Customer.orders); a statement built on an earlier line (stmt = select(...), then session.scalars(stmt), 3 scenarios before) is patched where it is built when the function assigns it once and reads it only there; and session.execute(select(...)).scalars() no longer counts the .scalars() of the result as a second query. The remaining scenarios of those two rows moved to the rows above: their query runs in a comprehension, or walks a tree.

Fixed with the 2026-11-06 measurement: when one query got two findings, a relationship and a chain through it (Playlist.entries and PlaylistEntry.track in bug_91_association_object_loop), the combined patch added both options as two .options() calls, .options(selectinload(Playlist.entries)).options(selectinload(Playlist.entries).joinedload(PlaylistEntry.track)). That ran and fixed the N+1, but the first call repeats the start of the second. The patch now keeps only the chain.

Release thresholds#

A release does not go out when the corpus gets worse. The release gate (scripts/release_gate.py accuracy, see "Releasing" in CONTRIBUTING.md) runs the corpus with the default configuration and fails when the precision or the recall of a finding kind is below the minimum recorded in scripts/accuracy_thresholds.json, when fewer than 250 scenarios ran, or when a disagreement with a verdict is not documented in the scenario. The minimums are the values measured on 2026-11-07 (SQLAlchemy 2.1.1, pytest 9.1.1, SQLModel not installed, 252 of the 254 scenarios), rounded down to a multiple of 10%. Measured again with the later scenarios of 2026-11-07 (278 of 280), every value is at or above its minimum:

kind minimum precision minimum recall measured
relationship-load 100% 100% 52 TP, 0 FP, 0 FN (100% and 100%)
repeated-statement 90% 90% 47 TP, 1 FP, 3 FN (98% and 94%)
column-load 100% 90% 12 TP, 0 FP, 1 FN (100% and 92%)
cartesian-load 80% 100% 7 TP, 1 FP, 0 FN (88% and 100%)

The repeated-statement minimum precision went from 80% to 90% with the rule for pagination and chunks, in the same change. The relationship-load minimum precision went from 100% to 90% on 2026-11-06, when clean_93_two_single_object_lookups was added (a CLEAN scenario the rule then reported), and back to 100% with #307, which fixed it. cartesian-load got its minimums on 2026-11-06, the first time it was measured; its minimum recall went from 80% to 100% on 2026-11-07, when the rule learned the loader strategies of the mapping. The column-load minimum recall went from 80% to 90%, and the minimum number of scenarios from 195 to 250, with the scenarios of 2026-11-07. The minimums are a floor against regressions, not a goal. Raise one in the same pull request that improves the corpus result; lower one only with a reason in that pull request, because every lowered minimum is a release that detects less.

Comparison with other tools#

Measured on 2026-11-10 by the head-to-head workflow (.github/workflows/head-to-head.yml, scripts/head_to_head/) in GitHub Actions: the same 278 scenarios, one job per tool, each tool pinned and set up the way its own documentation says to fail a test on an N+1, with its defaults otherwise. Python 3.13.18, SQLAlchemy 2.1.1, pytest 9.1.1; pytest-queryguard 1.0.0rc1, run from its tag. The method, the settings of each tool and the overhead of each are in Comparison.

tool BUG flagged BUG missed BUG error CLEAN passed CLEAN flagged CLEAN error precision recall (all BUG) recall (kinds it claims)
pytest-queryguard 1.0.0rc1, defaults 117 18 0 141 2 0 98% 87% 97%
pytest-queryguard 1.0.0rc1, all opt-in rules 134 1 0 134 9 0 94% 99% 99%
queryspy 0.6.0, --queryspy-strict 110 25 0 109 34 0 76% 81% 96%
pytest-querycount 0.4.0, no_n_plus_one on every test 115 20 0 108 35 0 77% 85% 100%
n-plus-one-sniffer (git d4790f8), no_n_plus_one on every test 115 20 0 113 30 0 79% 85% 97%
nplusone 1.0.0 on SQLAlchemy 2.1.1 0 0 135 0 0 143 n/a 0% 0%
nplusone 1.0.0 on SQLAlchemy 2.0.54 1 134 0 141 0 2 100% 1% 2%

Precision is flagged BUG over everything flagged. "Recall (kinds it claims)" counts only the BUG scenarios with a kind the tool says it detects: relationship, column and repeated-statement loads for queryspy and pytest-querycount, those and write loops for n-plus-one-sniffer, lazy loads and unused eager loads for nplusone. A test that failed for another reason than the tool's report is an error, never a pass. Per kind, precision / recall; n/a where the tool does not claim the kind (or, for the defaults of pytest-queryguard, where the rule is off by default), - where the tool does not say which kind it found or reported nothing of that kind:

tool relationship-load repeated-statement column-load write-loop unused-eager-load cartesian-load unused-columns
pytest-queryguard, defaults 100% / 100% 98% / 94% 100% / 92% n/a n/a 88% / 100% n/a
pytest-queryguard, all opt-in rules 100% / 100% 96% / 100% 87% / 100% 73% / 100% 83% / 100% 88% / 100% 100% / 89%
queryspy 83% / 100% 60% / 90% 76% / 100% n/a n/a n/a n/a
pytest-querycount - / 100% - / 100% - / 100% n/a n/a n/a n/a
n-plus-one-sniffer - / 98% - / 98% - / 92% - / 100% n/a n/a n/a
nplusone, SQLAlchemy 2.0 - / 0% n/a n/a n/a 100% / 20% n/a n/a

On PostgreSQL#

Not run again on 2026-11-06: this section is the 141-scenario measurement of 2026-10-13. The same 141 scenarios, every configuration, with the database on PostgreSQL instead of an SQLite file.

Result: the output of scripts/accuracy_report.py on PostgreSQL 17 is identical to the output on SQLite (same commit, Python and packages): the same TP, FP and FN in every table and the same disagreements, scenario by scenario. With the default configuration, 59 of 62 BUG scenarios that its rules can report are flagged and 1 of 79 CLEAN scenarios are; with all opt-in rules, 67 of 67 and 5 of 74. The report took 3 minutes 36 seconds on PostgreSQL.

What the first PostgreSQL run found. Before the fix, two BUG scenarios (bug_23_get_or_create_loop, bug_30_flush_per_insert) were listed as UNEXPLAINED without a finding: their first INSERT raised duplicate key value violates unique constraint "tag_pkey". The seed data inserts explicit primary keys; SQLite numbers the next row after the largest one, but a PostgreSQL sequence still starts at 1. That was a bug of the corpus (#120), not of the plugin: the scenario never reached its loop. The corpus now moves every serial and identity sequence past the seeded rows after a scenario's setup (Ctx.sync_sequences()). The run showed no difference between PostgreSQL and SQLite that comes from the plugin.

On MySQL and MariaDB#

2026-11-08. The 278 scenarios that run without SQLModel, every configuration, with each scenario's database on MySQL 8.4.13 and on MariaDB 11.8.9 (the official Docker images) instead of an SQLite file.

Result: on MySQL 8.4 and on MariaDB 11.8 the output of scripts/accuracy_report.py is identical to the output on SQLite (same commit and packages): the same TP, FP and FN in every table and the same disagreements, scenario by scenario. With the default configuration, 117 of 121 BUG scenarios that its rules can report are flagged and 2 of 157 CLEAN scenarios are; with all opt-in rules, 134 of 135 and 9 of 143. Precision and recall per kind are those of the tables above (for example repeated-statement 98% and 94% by default).

What the first MySQL runs found. In the plugin, two false positives of the repeat rules, both fixed: MySQL writes pagination as LIMIT <offset>, <count>, which the rules did not read as pagination, and SQLAlchemy's has_table() runs DESCRIBE, which was not treated as schema reflection. No scenario of the corpus pages through rows from one line or calls has_table() in a loop, so neither changed the numbers; the regular test suite, which also runs on these servers now, found them. In the corpus, five scenarios did not run there: two seeded rows in an order that only SQLite, which does not check foreign keys by default, accepts; one wrote the table name in double quotes; one passed ? placeholders to exec_driver_sql; and the yield_per scenario streams on a server-side cursor that PyMySQL ends when the selectinload statement runs (without the plugin too), so it reads buffered rows on MySQL. The polling scenario reads with READ COMMITTED there: with MySQL's default REPEATABLE READ the loop never sees the other connection's update.

Real projects#

The corpus is written by the author of the plugin. To see what the plugin does on code nobody wrote for it, the workflow .github/workflows/realworld.yml runs the test suites of open-source projects that use the SQLAlchemy 2 ORM: SQLModel, the FastAPI full-stack template (on PostgreSQL), MLflow's SQLAlchemy tracking store, SQLAdmin, Advanced Alchemy (its unit tests) and the SQLAlchemy adapter of FastAPI Users. Each project is pinned to a release tag in scripts/realworld_projects.json, which also holds its install and test commands and what to reset (a fresh database) before each run.

Each suite runs twice in the same environment: once without the plugin (-p no:queryguard) and once with it in warn mode, with the experimental unused-eager-load and unused-columns kinds on. scripts/realworld_summary.py compares the two runs' JUnit XML and reads the plugin's JSON file:

The workflow is started by hand only, never on pushes or pull requests, because it installs and runs third-party code. Findings never fail a job; a job fails when the plugin broke something or when the project's tests did not run without the plugin either (a harness problem), and a last job puts one table of all projects on the run's page.

Results of 2026-11-07#

Plugin main at 4e1a888 (0.8.0 plus the unreleased changes), runs 42389509168 (four projects; MLflow and SQLAdmin stopped at collection under SQLAlchemy 2.1, since capped below 2.1) and 42390905254 (MLflow and SQLAdmin), on GitHub's ubuntu-latest. Every finding was read against the project's code at its tag.

project tag (commit) Python, SQLAlchemy tests without the plugin (pass/fail/skip) changed by the plugin internal warnings/errors findings false debatable
SQLModel 0.0.24 (de78b8c) 3.12, 2.0.57 220/35/3 0 0/0 9 9 0
full-stack FastAPI template 0.8.0 (2eb8f5b) 3.12, 2.0.35, PostgreSQL 17 53/2/0 0 0/0 0 0 0
MLflow tracking store v2.22.0 (fd2d986) 3.11, 2.0.57 219/1/16 0 0/0 179 78 54
SQLAdmin 0.20.1 (ab2d48a) 3.12, 2.0.57 177/2/3 0 0/0 51 16 1
Advanced Alchemy (unit tests) v1.4.4 (6cc26ef) 3.12, 2.0.41 564/0/3 0 0/0 0 0 0
FastAPI Users SQLAlchemy v7.0.0 (6397ace) 3.12, 2.0.57 6/0/0 0 0/0 0 0 0

The failures without the plugin come from the projects' unpinned test dependencies (SQLModel's OpenAPI snapshots, the template's called_once_with on a newer mock); they fail the same way with the plugin. The plugin changed no test's outcome, raised no internal warning or error, and its wall time was within the noise of one run each (from −28 % to +4 %).

What the findings were:

The true findings were not reported to the projects.

Test code and calls on separate lines (Faraday, openFEC)#

Faraday (master d00e81c, 2112 tests, Flask-SQLAlchemy on PostgreSQL 16, its tests through a test client defined in conftest.py and factory_boy factories) and openFEC (71f5dbb, 702 tests) ran in a temporary workflow, one job with main at 7c7f2a8 and one with the rules for test code and calls on separate lines, run 42422988856, both with the default configuration (mode fail).

project failed by the plugin, main failed, after findings in test code left out
Faraday 551 79 547 in 334 tests
openFEC 5 2 3 in 3 tests

On main, Faraday's failures were nearly all noise: the user factory's post_generation hook looks the role up for every user it creates (422 findings), helpers and tests that read relationships lazily, the statistics of a workspace counted with one helper called on six separate lines (about 480 findings, debouncer.py), and requests sent on separate lines through the Session that the whole suite shares (get_workspace in before_request, the serialization of one object per request). All of those are gone; 225 of the 359 findings located in the application went with them, and those read by hand (the statistics helper, get_workspace, the serializers, the sequence values of bulk_create.py) were all calls or requests on separate lines, no loop over rows. The 79 tests left are a loop in the test that calls the application once per pass (ten paginated requests in a for loop, a commit() per object that fires an event listener of the application, a helper that assigns an association proxy per object, whose creator looks a row up), which the stack cannot tell from a loop in the application (see Limitations), and the application's own N+1s, such as the lazy loads in the serializers of credentials.py and of the workflow pages. No test failed for another reason with the plugin.

The six projects of realworld.yml ran with main at 7c7f2a8, run 42418975007, and with the branch, run 42422956906: the same findings in every project (MLflow 114, SQLAdmin 51, the others none), no finding of test code left out, no test outcome changed and no internal warning.

Known limits#

See also Limitations.

Edit this page on GitHub