A test failed: now what#

A test that passed yesterday now fails with queryguard: N+1 detected. This page is the checklist: read the report, decide whether the finding is real, then fix it or leave it out on purpose. Nothing here needs a change to the plugin's configuration unless you decide to silence something.

1. Read the report#

queryguard: N+1 detected

  Order.customer was lazy-loaded 50 times
  first at app/orders.py:10 in list_orders
    called from tests/test_orders.py:7 in test_list_orders
  parents loaded at app/orders.py:9 in list_orders
  kind: relationship-load  label: Order.customer
  docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#relationship-load
  sql: SELECT customer.id, customer.name FROM customer WHERE customer.id = ?
  fix: load it with the parent query, e.g.
       select(Order).options(joinedload(Order.customer))

The kind: line is what you need to silence a finding; the table below shows how each headline maps to the kind and label, for the cases where you want to write a pattern with a wildcard.

The report says Kind Label (for ignore patterns and the baseline) Usual fix
Order.customer was lazy-loaded 50 times relationship-load Order.customer joinedload (many-to-one) or selectinload (collection) on the query that loaded the parents
the same statement ran 7 times repeated-statement the normalized SQL, on the kind: line one query with WHERE id IN (...), or a join, instead of a loop
Customer had its columns reloaded 50 times for 50 instances, after commit(), ... column-load Customer (expired) expire_on_commit=False, or load the objects again with one query
Engineer loaded its subclass columns on its own 50 times ... column-load Engineer (polymorphic) selectin_polymorphic(Employee, [Engineer]) or with_polymorphic on the query, or polymorphic_load on the mapping
Customer.name was loaded on its own 50 times for 50 instances (deferred column) column-load Customer.name undefer(Customer.name), or drop defer() / load_only()
the same INSERT ran 6 times, one row at a time (opt-in) write-loop the normalized INSERT, UPDATE or DELETE session.add_all() and one flush, or session.execute(insert(Model), rows)
Customer.notes and Customer.orders were joined into one query side by side, once (warns by default) cartesian-load Customer.notes + Customer.orders selectinload for all collections but one, see How detection works
Customer.orders was loaded with selectinload and never read (experimental, off by default) unused-eager-load Customer.orders drop the loader option, see Unused eager loads
Account: 12 columns loaded, 9 never read (experimental, off by default) unused-columns Account load_only() the columns the code reads, or defer() the large ones; see Unused columns
len() of a Book queryset loaded all its rows (3 rows) only to count them (experimental, off by default, Django) queryset-len len(Book) or bool(Book) .count() for len(), .exists() for bool(); see Django
queryguard: missing index (opt-in) missing-index the table the CREATE INDEX on the fix: line; see the index advisor
queryguard: expected at most 2 queries, got 4 a budget, not a finding none fix the code, or raise the budget; ignore patterns and the baseline do not apply

To list the kind and label of every finding of a run in one file, write a scratch baseline:

pytest --queryguard-baseline=findings.json --queryguard-update-baseline

Then read findings.json and delete it. A budget test still fails this run, since the baseline does not apply to budgets.

The SARIF file (--queryguard-sarif=PATH) carries the kind: line in each message and the kind as the queryguard/<kind> rule id.

The same finding in many tests#

A loop in a shared helper or fixture is reported by every test that runs it, and each of them prints the same block. After the run, the summary names such a finding once:

========== queryguard: the same finding in several tests ==========
   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])
a finding from one place in the code is fixed once for all its tests

A finding is listed when two tests or more reported it, failing or as a warning, grouped by kind and label. "From one place in the code" means every test reached it through the same function; with several places, the same relationship or statement is loaded in a loop in more than one function. The example is the first of the tests by name. Ignored and baselined findings are not counted, a test that runs again (a rerun plugin) counts once, and it works the same with pytest-xdist.

Strict mode: fail at the access#

The report comes when the test ends. With queryguard_strict = true (or --queryguard-strict) the N+1 fails the test where it happens instead: the lazy load of a relationship for the second parent loaded at the same line (queryguard_relationship_threshold, 2 by default) raises NPlusOneDetected, and the traceback ends at the line that read the attribute, the frames of SQLAlchemy and the plugin left out:

    def list_orders(session):
        names = []
        for order in _helper_query(session):
>           name = order.customer.name
                   ^^^^^^^^^^^^^^
E           pytest_queryguard.NPlusOneDetected: queryguard strict: Order.customer was lazy-loaded for 2 parents loaded at the same line; this access is the N+1
E
E             Order.customer was lazy-loaded 2 times
E             first at app/orders.py:13 in list_orders
E               called from tests/test_orders.py:5 in test_list_orders
E             parents loaded at app/orders.py:7 in _helper_query
E             kind: relationship-load  label: Order.customer
E             docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#relationship-load
E             fix: load it with the parent query, e.g.
E                  select(Order).options(joinedload(Order.customer))
E
E             (queryguard_strict raises at the lazy load instead of at the end of the
E             test; a queryguard_ignore marker or pattern, an ignore() block or a
E             baseline entry lets it pass, as for the report)

It is Rails' strict_loading!(mode: :n_plus_one_only) and Laravel's preventLazyLoading() for SQLAlchemy:

2. Is it real?#

Most findings are real: the code ran one statement per row, and the test database only hides the cost because it holds few rows. Look closer when:

--queryguard-report prints how many statements each test ran, and record_queries() lists every statement of a block with its call site, if you want to look at them in the test itself.

3. Fix it#

Apply the hint at the line the report names and run the test again. The fix: line shows the loader option, not its import: add joinedload or selectinload to the file's from sqlalchemy.orm import line, or the hint raises NameError. Two patterns cover most cases:

from sqlalchemy import select
from sqlalchemy.orm import joinedload, selectinload

# a many-to-one read for every row: join it into the parent query
orders = select(Order).options(joinedload(Order.customer))

# a collection read for every row: one extra query for all of them
customers = select(Customer).options(selectinload(Customer.orders))

# a session.get() or a SELECT in a loop: one query with IN
rows = session.scalars(select(Customer).where(Customer.id.in_(ids))).all()

A patch for the parent query#

Since 0.8.0; experimental (see Stability).

For a relationship-load finding, pytest-queryguard can write that change for you. --queryguard-show-patch (or queryguard_show_patch = true) prints a unified diff under the finding, and --queryguard-write-patch=PATH writes the diffs of the whole run to one file:

pytest --queryguard-write-patch=queryguard.patch
git apply queryguard.patch      # from the rootdir
--- a/app/orders.py
+++ b/app/orders.py
@@ -1,9 +1,9 @@
 from sqlalchemy import select
-from sqlalchemy.orm import Session
+from sqlalchemy.orm import Session, joinedload

 from app.models import Order


 def list_orders(session: Session) -> list[Order]:
-    orders = session.scalars(select(Order)).all()
+    orders = session.scalars(select(Order).options(joinedload(Order.customer))).all()
     return [order.customer.name for order in orders]

The option goes on the select(Order) or session.query(Order) call of the line in parents loaded at: as .options(...) right after the call, or as one more argument of the .options(...) already in its chain. When that line runs a statement built earlier in the function (statement = select(Order) and then session.scalars(statement)), the option goes on the line that builds it. A class named through its module (select(models.Order)) is named the same way in the option: joinedload(models.Order.customer). The loader is joinedload or selectinload, the same as in the fix: hint, chained through the relationships that reached the parents. A loader the module does not import yet is added to its from sqlalchemy.orm import line, or on a new line after the imports at the top of the file.

A wrong patch is worse than none, so a finding gets one only when the line is certain, and otherwise only the fix: hint:

The diff paths are relative to the rootdir (a/app/orders.py). When the rootdir is a subdirectory of the git repository, apply it with git apply --directory=<subdirectory>, or with patch -p1 from the rootdir. Fixes of the same file are merged into one diff; two relationships of one query become two .options(...) calls, which SQLAlchemy accepts. Findings left out by an ignore or the baseline get no patch. The patch is made when the test's findings are reported, from its source file: no cost per statement. Read it before you apply it, as any generated change: joinedload of a collection or a large row can cost more than the lazy loads it replaces.

To keep the fix from regressing, put a budget on the test: @pytest.mark.max_queries(2) fails it the day the count goes up again.

4. Or leave it out on purpose#

If the code is right as it is, or you cannot fix it now, leave the finding out, from the narrowest scope to the widest:

Ignoring findings has the details. Ignore patterns that no longer match anything are listed as stale at the end of the run, so they do not outlive the code they were written for.

Next#

Once the suite is green, run it in CI (CI and GitHub Action); on a project with many existing findings, start from a baseline.

Edit this page on GitHub