Running queryguard in CI and in GitHub code scanning#
pytest-queryguard already fails the test run on a new N+1 query, so any CI that runs pytest enforces it. To also see the findings in the GitHub UI, as code scanning alerts with a file, a line and a fix hint, use the pytest-queryguard action or upload the SARIF file yourself.
The action#
name: Tests
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
tests:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write # needed to upload to code scanning
actions: read # compare query counts with the base branch
pull-requests: write # comment the comparison on the pull request
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- run: pip install -e ".[test]" # your project and its test dependencies
- uses: MaciejZiel/pytest-queryguard-action@v1.1.0 # a release tag, or a commit SHA
with:
pytest-args: tests/ # no -x: see below
# baseline: queryguard-baseline.json # add once the file exists, see below
The action lives in
MaciejZiel/pytest-queryguard-action,
the repository listed in the GitHub Marketplace as
pytest-queryguard. It holds a copy of
action/action.yml of this repository that each release copies there, so its
vX.Y.Z is the same action as this repository's vX.Y.Z; issues and
changes go to this repository. A release tag or a commit SHA is the safer
pin: it never changes, and Dependabot proposes the updates. @v1 follows the
newest 1.x final release (never a release candidate), so a run can change
without a change to your workflow. Existing workflows that use
MaciejZiel/pytest-queryguard/action@<tag> keep working and get every 1.x
release too; switching is a change of the uses: line only, and the
comparison with the base branch, the trend and open code scanning alerts carry
over, since the inputs, outputs, artifact name, category and comment marker
are the same.
The push trigger is limited to main so that a pull request does not run
the workflow twice, once for the push and once for the pull request.
pytest-args has no -x. A run that stops at the first failure writes a
JSON file with "complete": false, which the comparison with the base branch
cannot fully use (see Query counts as JSON), and it
keeps --queryguard-update-baseline and the budget file update from writing
(see baseline.md).
The example has no baseline input on purpose. A baseline path that does
not exist makes pytest stop with baseline file ... does not exist; create it
with --queryguard-update-baseline, and the action never creates the file. To
use a baseline, create it locally with
pytest --queryguard-baseline=queryguard-baseline.json --queryguard-update-baseline
(see baseline.md), commit it, and then uncomment the
baseline line.
You do not need to set package. Left empty, the action installs the plugin
its own ref ships (the release's wheel in dist/ of the action repository,
the same file as on PyPI, or the checkout above action/ here), so pin the
action to a release tag or a commit and you get the plugin of that release. A
fixed default such as pytest-queryguard would let pip pick an older release
(for example 0.3.0, which has no --queryguard-sarif), and pytest would stop
with unrecognized arguments. Set
package only to install something else, such as pytest-queryguard==0.7.0
or a path. The action needs pytest-queryguard 0.6.0 or newer: it passes
--queryguard-sarif and --queryguard-json and runs
python -m pytest_queryguard.compare, which older releases do not have. The
trend input needs 0.8.0 or newer (python -m pytest_queryguard.trend),
and the lint input 0.10.0 or newer (--format github).
The action installs pytest-queryguard into the active Python, runs
pytest --queryguard-sarif=queryguard.sarif, uploads the file with
github/codeql-action/upload-sarif
(pinned by commit SHA inside the action) and then fails the step if pytest
failed. Install your own project first: the action does not know how.
| Input | Default | Meaning |
|---|---|---|
pytest-args |
empty | Arguments for pytest, as a list of shell words: quotes group words (-k "a or b"). The value is split by Python's shlex and is not evaluated by a shell, so $(...), backticks and $VAR are passed to pytest as literal text. |
python-version |
empty | Set up this Python. Empty: use the python on PATH. |
package |
empty | What to pip install. Empty: the plugin the action's own ref ships, matching the pinned ref. Otherwise a requirement like pytest-queryguard>=0.6 (the oldest release the action works with; 0.8.0 for trend, 0.10.0 for lint), or a path. |
baseline |
empty | Baseline file, see baseline.md. Empty: queryguard_baseline from your config. |
fail |
true |
true: fail the step when pytest fails. false: a failed test run does not fail the step, only report. An invalid input or a failed install still fails it. |
working-directory |
. |
Where to run pytest. Locations in the SARIF file are still relative to the repository root (see SARIF output). |
sarif-file |
queryguard.sarif |
Output file, relative to working-directory. |
upload |
true |
Upload to code scanning. false: only write the file. |
category |
pytest-queryguard |
Code scanning category; use one per job when several jobs upload, including each job of a matrix (see Limits). It also names the job's query-count artifact, queryguard-json-<category> with " : < > \| * ? \ / and line breaks turned into -, and its pull-request comment. Must not be empty. |
json-file |
queryguard.json |
The per-test query counts, relative to working-directory; uploaded as the artifact queryguard-json-<category>. Empty: none. |
compare |
true |
On a pull request, compare the counts with the base branch and write the result to the job summary. |
comment |
true |
Also post the comparison as a pull-request comment, updated in place on later pushes. |
trend |
false |
Since 0.8.0, experimental. A number of runs N (2 to 100; true means 10): on pushes to the default branch and on pull requests, show how the counts moved over the last N runs, see below. |
github-token |
github.token |
Token for the comparison, the trend, the comment and the changed files of lint: changed. |
lint |
false |
Since 0.10.0, experimental. true: after pytest, run the static check on lint-paths with --format github, so its findings show as warnings on the lines of the pull request. changed: on a pull request, only the changed Python files in lint-paths. See below. |
lint-models |
empty | The modules that define or import your mapped classes, separated by spaces (app.models). Required when lint is not false. |
lint-paths |
. |
Files and directories for the static check, relative to working-directory, split like pytest-args. |
fail, upload, compare and comment take true or false (in any
case) and nothing else: the action stops with an error on a value such as
yes, 1 or an empty string, which would otherwise quietly mean false.
trend takes false, true or a number from 2 to 100, and stops the same
way on anything else. lint takes true, changed or false; when it is
not false, lint-models must hold module names (letters, digits, _ and
dots), or the action stops before pytest runs.
Outputs: exit-code (pytest's), sarif-file, json-file, trend-report
(since 0.8.0: the trend's Markdown file, empty when there is none) and
lint-exit-code (since 0.10.0: the static check's, 0 or 1, empty when it
did not run).
Query counts on pull requests#
On every run the action writes the query counts and
uploads them as an artifact. On a pull request it downloads the file of the
latest finished run of the same workflow on the base branch (a push or
scheduled run, never a pull-request run: a fork's pull request from its own
main would otherwise count as the base), compares the
two, and writes the result to the job summary and to one pull-request
comment:
### pytest-queryguard: queries compared with the base branch
412 tests compared: 3120 -> 3187 statements (+67). 2 run more, 1 fewer; 1 new finding, 0 fixed.
#### New findings
| Kind | Label | Where | Times | Tests |
| relationship-load | `Order.items` | `app/orders.py in list_orders` | 50 | `tests/test_orders.py::test_list` |
#### Tests that run more statements
| Test | Before | After | Change |
| `tests/test_orders.py::test_list` | 3 | 53 | +50 |
A reviewer sees that a change made a test run more queries even when no rule fired yet (a new loop of two, a test under its budget). The comparison never fails the job.
- The base branch needs one run of the workflow with this version of the
action first (a push to
main); until then the summary says so. - Findings are matched by kind, label, file and function, so a finding that only moved to another line is neither new nor fixed. Baselined findings are left out.
- Without
actions: readthe job summary says the runs could not be listed; withoutpull-requests: write, or on a pull request from another repository (a fork) or Dependabot, there is no comment and the job summary still has the report. The action only edits its own comment. json-file: ""turns the file, the artifact and the comparison off. Do not pass--queryguard-jsoninpytest-argsas well: the action reads the file atjson-file.- Several jobs (for example one per database, or the jobs of a matrix) keep
apart by
category; see Limits. - The same report locally:
python -m pytest_queryguard.compare base.json head.json.
Query counts over the last runs#
Since 0.8.0; experimental (see Stability).
The comparison shows one step; trend: "10" shows the last ten runs, as an
APM shows a query count over time in production. On a push to the default
branch and on a pull request, the action downloads the query-count artifacts
of the latest finished runs of the same workflow on the (base) branch, adds
the file of this run as the newest, and appends the trend to the job summary.
On a pull request with a comment it is also folded into that comment, as a
collapsed <details> block below the comparison.
### pytest-queryguard: query counts over the last 5 runs
5 runs, statements 3120 -> 3187 (+67) `▁▁▂▂█`. 3 tests changed their count, 2 new, 0 not in the latest run; 1 new finding, 0 gone.
| Run | Tests | Statements | |
| `1a2b3c4` | 410 | 3120 | |
| ... | | | |
| `9f8e7d6 (this run)` | 412 | 3187 | |
#### Tests whose count changed most
| Test | Runs | First | Last | Change |
| `tests/test_orders.py::test_list` | `▁▁▁▁█` | 3 | 53 | +50 |
- Each run is named by its commit. A run that stopped early or whose
measurement failed (
complete: false) is markedincomplete: its total is partial, and tests missing from it did not run. - A test's change is its count in the latest run against its first run in the
window, with one sparkline character per run (
·where the test did not run), scaled between its lowest and highest count. A renamed test is one new test and one that is no longer in the latest run. - New and gone findings compare the oldest run with the newest, as the
comparison does;
Sinceis the run from which on a new finding is in every run. - Pull-request runs are not history: only runs of other events (push,
schedule) on the branch count, one per commit. Runs without
the artifact (expired after 30 days, or a job that stopped before writing
it) or with a file that cannot be read are skipped, so the window may have
fewer runs. The
trend needs
actions: readand never fails the job; without the permission it has this run only and the log has a warning.
The same report locally, from files given oldest first:
python -m pytest_queryguard.trend mon.json tue.json wed.json --top 20
python -m pytest_queryguard.trend runs/*.json --test "tests/test_orders.py::*" --format text
--format is markdown (the default), text or json; --test keeps the
tests whose node id contains the pattern, or matches it when it is a glob;
--label names the runs (once per file, default: the file names). The
sparklines use Unicode blocks; --ascii prints _-~=+*#@ instead, and the
console output falls back to it by itself when the console cannot print the
blocks (a Windows console with cp1252). The exit status is 2 when a file
cannot be read or is not a --queryguard-json file (--skip-unreadable
leaves it out instead) or the --output file cannot be written, otherwise 0.
--format json prints one object with "format": 1 (the number goes up when
a key changes meaning; new keys may be added): runs (per file, oldest first:
label, tests, statements, complete), complete, changed (the tests
whose count changed most, up to --top: nodeid, counts per run, null
where the test did not run, first, last, change), changed_total,
added_tests and gone_tests (how many tests are in the last run but not
the first, and in an earlier run but not the last), new_findings and gone_findings (kind,
label, file, function, count, tests; a new finding also has
since, the label of the run from which on it is in every run). Like the
rest of the trend it is experimental (see Stability).
A typical rollout: run once with fail: "false" to see the alerts, create a
baseline for what you cannot fix yet, then switch to
fail: "true" (the default).
The static check as annotations#
Add to the with: of the action:
lint: changed # or "true" for every file of lint-paths
lint-models: app.models
lint-paths: app
With lint, the action runs
python -m pytest_queryguard.lint --format github --models=app.models -- PATHS
in working-directory after pytest, the upload and the comparison, so that
a check that cannot run does not keep those from running. The paths of the
annotations are relative to the root of the checkout, also when
actions/checkout puts it below the workspace with path:. Each finding is a
workflow command,
::warning file=...,line=...,col=..., which GitHub shows as an annotation on
that line of the pull request's diff and in the run's summary. The check
imports lint-models (see Static check), so
the step needs your project installed, as pytest does.
lint: changedchecks the Python files the pull request adds or changes that are inlint-paths, as GitHub's list of the pull request's files names them; that list needspull-requests: read. Without it, the step warns and checks all oflint-paths, as it does for a pull request of 3000 files or more, the most GitHub lists. When no such file changed, the check does not run. On other events (a push),changedchecks all oflint-paths.- Findings do not fail the job: the check is experimental and reports likely
N+1 queries, not measured ones (pytest measures). Use the
lint-exit-codeoutput (1when anything is reported) in a later step to fail on them. A model module that cannot be imported, a missing path or an invalidlint-pathsfails the step. - GitHub shows at most 10 warning annotations per step and 50 per job; the rest are in the log.
- The annotations are not code scanning alerts. To get those, upload the check's SARIF file as shown in Static check.
lint, lint-models, lint-paths and lint-exit-code are experimental
(see Stability).
Permissions and forks#
- Uploading needs
security-events: writeon the job (or the workflow). Without it, the upload step fails with "Resource not accessible by integration". - Pull requests from forks get a read-only token, and GitHub does not
allow them to upload. The action skips the upload for them and still runs
pytest, so the test result is unaffected; the findings are in the job log.
The same holds for runs started by Dependabot (
github.actorisdependabot[bot]), which also have a read-only token: the upload is skipped for them too. - The upload step has
continue-on-error: true: an upload that GitHub refuses (for example a read-only token in a case the action does not recognize, such aspull_request_target, or code scanning turned off) shows as a failed step and a warning, but does not fail a job whose tests passed. The flip side is that a missingsecurity-events: writealso does not fail the job; look at the step in the log if alerts do not appear. Setupload: "false"for events where you do not want an upload at all. - Code scanning is free for public repositories. Private repositories need GitHub Code Security.
Permissions per input#
| Permission | Needed by | Without it |
|---|---|---|
contents: read |
actions/checkout |
The checkout fails. |
security-events: write |
upload: "true" |
The upload step fails (it has continue-on-error), the job does not. |
actions: read |
compare, trend; the upload in a private repository |
The job summary or the log says the runs could not be listed. |
pull-requests: write |
comment: "true" |
A warning in the log; the report stays in the job summary. |
pull-requests: read |
lint: changed |
A warning in the log; every file of lint-paths is checked. pull-requests: write includes it. |
Grant only what the inputs you use need: with upload: "false",
compare: "false" and comment: "false" the job needs contents: read
alone.
Limits and edge cases#
- Matrix jobs. A composite action cannot see the matrix, so every job of
a matrix gets the same default
category. Their artifacts then replace each other (the action uploads withoverwrite: true, so that a re-run of a job can upload again), their comparisons share one comment, and code scanning keeps the upload of the last job. Give each job its own category:category: queryguard-${{ matrix.python }}-${{ matrix.db }}. Two categories that differ only in characters turned into-(a/banda:b) share an artifact too. - The first run. Until a push to the base branch has run the workflow with this action, a pull request has nothing to compare with: the job summary says so, no comment is written, and the job is not failed.
- The comment's size. GitHub refuses a comment over 65536 characters. The comparison has at most 25 rows per table and cuts long names, so it fits; when the trend folded below it would not, the comment leaves the trend out and says it is in the job summary. A comparison that does not fit by itself is cut at a line, with a note. The job summary always has both in full.
- One comment, updated. A later run finds its comment by the marker on
the first line and by its author: the user of a personal access token
given as
github-token, or else a bot (github-actions[bot]for the default token, the app for an app's token), newest first, passing over one this token may not edit. A comment of a person that quotes the marker is never edited. When GitHub cannot name the user of a personal token for a moment, the run writes no comment rather than a second one. Two runs of one pull request that end at the same moment can both find no comment and post two; and a re-run of an older run writes its older comparison over the newer one. Cancelling older runs avoids both:
yaml
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
- Exit codes. pytest's exit code is the
exit-codeoutput. Withfail: "true"any code but 0 fails the job; 2 (interrupted), 3 (internal error), 4 (usage error) and 5 (no tests collected) also leave a warning, which is all they leave withfail: "false". A finding fails its test, so it is code 1, as any failed test. An invalid input, an unclosed quote inpytest-argsor a failed install fails the job whateverfailsays, and then the later steps are skipped. - Cancelled runs. After a cancel nothing more runs: no upload, no comparison, no comment. Failed tests do not stop them; an invalid input or a failed install skips them, as pytest did not run.
- Runners. Every step uses
bash; the repository's CI runs the action onubuntu-latest. macOS runners have bash andrealpath. On Windows, bash is Git Bash, and the action turns the file paths it hands to the upload steps into Windows paths (cygpath -w); macOS and Windows runners are not tested by the repository's CI. - Untrusted text. No input or event value is pasted into a script: each
reaches the shell as an environment variable, and
pytest-argsis split by Python'sshlexwithout a shell. Test ids, labels and file names in the comment are in code spans, with|escaped and backticks replaced, so a test id cannot start a mention, a link or a table cell.
Without the action#
- run: pytest --queryguard-sarif=queryguard.sarif
continue-on-error: true
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: queryguard.sarif
category: pytest-queryguard
The upload step prints one warning per finding (Calculated fingerprint ... but found
existing inconsistent fingerprint value). It is noise: the upload succeeds and alerts
are matched correctly. See SARIF output for why.
Query counts as JSON#
pytest --queryguard-json=queryguard.json writes one entry per test: how many
statements it ran, the same split by verb, the database time and the findings
it found (after ignores). Keep the file from the main
branch as an artifact and compare a pull request's file with it to see which
tests started running more queries before anything fails.
{
"format": 1,
"tool": {"name": "pytest-queryguard", "version": "0.8.0"},
"complete": true,
"tests": {
"tests/test_orders.py::test_list_orders": {
"statements": 51,
"by_verb": {"select": 51},
"db_time": 0.0007,
"truncated": false,
"findings": [
{"kind": "relationship-load", "label": "Order.customer", "count": 50,
"file": "app/orders.py", "function": "list_orders", "line": 10,
"stack": [{"file": "tests/test_orders.py", "function": "test_list_orders",
"line": 7}],
"baselined": false,
"message": "Order.customer was lazy-loaded 50 times\nfirst at app/orders.py:10 in list_orders\n..."}
],
"max_queries_marker": false
}
}
}
statementscounts the statements of the test function, as budgets do: the setup and teardown of fixtures are not measured.by_verbsorts the stored ones intoselect,insert,update,delete,transactionandother;truncatedis true when the test ran more thanqueryguard_max_eventsstatements, and thenby_verbcovers only the first of them.max_queries_markeris true for a test with its ownmax_queriesmarker.findingslists what the test found after ignores.stackholds the lines of your code that calledfile:line, innermost first, as the terminal report'scalled fromlines (queryguard_stack_depth). Findings in the baseline are listed too, with"baselined": true, so the file is the same whether or not the baseline is being updated.message(since 0.8.0) is the finding's text as the terminal report shows it, without the indent; like every message, its wording is not stable.db_timeis null when no statement was timed.completeis false when the run stopped early (-x, Ctrl-C, a collection error, a crashed pytest-xdist worker) or measurement failed: tests missing from such a file did not run, they did not stop querying.- With pytest-xdist the controller writes one file with the tests of every
worker. With
queryguard_mode = offnothing is measured andtestsis empty. formatchanges only when an existing field changes meaning; new fields may be added.
How this repository tests the action#
The action job in .github/workflows/ci.yml runs the local action
(uses: ./action) on examples/action-sample, a project with one N+1 query:
once with fail: "false" (the SARIF file is checked, including that its URI
starts with examples/action-sample/, the working directory), once expecting
the step to fail, and once with the finding in a baseline. The first run
also has trend: "5"; when the trend wrote a report, the job checks that it
has this run's row. None of them
uploads: a sample upload with no results would make every pull request report
"1 configuration not found" in its checks.
tests/test_action_steps.py runs the shell steps of action/action.yml with
crafted inputs, among them the install step in both layouts: with a
pyproject.toml above the action (this repository) and with a wheel in
dist/ (the action repository). The action repository's own workflow runs
the copy there, with the default package, on a project like
examples/action-sample.