Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

pycoati

pycoati audits a Python test suite for mock smells and suspicious tests. It walks the project with tree-sitter, optionally runs pytest for collection, durations and coverage, and emits a structured inventory: per-file and per-test counts, mock-API smells, and a per-test suspicion score.

It is meant for an occasional audit, not every commit: the suite is green but you don’t trust it. For the per-commit gate, see zorilla.

Install

uvx pycoati@latest guide      # agent-oriented instructions
uvx pycoati@latest .          # audit the current project

What it does

Audit. pycoati <PATH> scores every test for suspicion and lists the most suspicious first, with a remediation ladder for the agent to work through.

pycoati . --output inventory.json   # structured inventory (JSON)
pycoati . --format pretty           # aligned-column terminal view
pycoati . --static-only             # no pytest subprocesses

Review decisions persist in .pycoati-accept.toml, one test and one signal at a time, each with a reason. See Set up and run an audit.

Plan. pycoati plan <ROOT> [MEMBER]... works out how to run a monorepo’s pytest suites in parallel: how many pytest processes are worth starting side by side, and which subprojects share one. It runs no tests.

pycoati . --no-coverage --output inventory.json            # measure once
pycoati plan . api core web --timings inventory.json --max-jobs 8
pycoati plan . --format pretty                             # no timings: balance on test counts

The recommendation is the fewest lanes whose wall time is within --tolerance percent of the best packing found, so a lane that buys nothing is never suggested. See Plan parallel pytest runs.

The guide

pycoati guide [PAGE] prints the pages in the Agent guide section of this site. They are embedded in the binary at compile time, so they always describe the schema that exact build emits; a test fails the build when a serialized field goes undocumented.

For your CLAUDE.md

### `pycoati` — test-suite audit

- Run `pycoati . --output inventory.json` now and then (not every commit), then
  `pycoati guide analyze`: it ranks the tests most likely to be weak (mock-only
  assertions, patch stacks, no assertions) and gives a remediation ladder.
- Ask before changing a test it flags. Keep a legitimate one with an entry in
  `.pycoati-accept.toml` (a `reason` is required).
- Monorepo: `pycoati plan . --timings inventory.json` says how many pytest
  processes to run side by side, and which subprojects go in each.

Suspicion-score weights

pycoati’s suspicion_score blends five static heuristics into a single number per test in [0.0, 0.80) (see Reachable range), plus a small mock_construction bonus per file. The values below are the v1 defaults that ship in src/suspicion.rs::DEFAULT; they are heuristic starting points, not empirically tuned constants. Treat the formula as the contract and the numbers as defaults you may want to revise after running pycoati on a real project (see How to revise).

Formula

Per-test score:

score = w_mock_only      * (only_asserts_on_mock ? 1.0 : 0.0)
      + w_patch_count    * min(patches / 5.0, 1.0)
      + w_setup_ratio    * sigmoid((setup_to_assertion_ratio - 8.0) / 4.0)
      + w_zero_asserts   * (unverified ? 1.0 : 0.0)
      + w_smell_density  * min(smell_hits.len() / 2.0, 1.0)

unverified = assertion_count == 0 && external_verification_count == 0
             && helper_assertion_count == 0
patches    = patch_decorator_count + patch_call_count

sigmoid(x) = 1.0 / (1.0 + e^-x).

Weights

WeightValueRationale
w_mock_only0.35Strongest single signal — a test whose only assertions target the Mock API is exercising the test double itself, not production logic.
w_patch_count0.20High patch density flags tests where the System Under Test has been replaced wholesale; saturates at 5 to avoid runaway scores on extreme outliers. Counts every patch the test installs — @patch decorators, with patch(...) / patch.object(...) in the body, mocker.patch* — so the spelling does not change the score.
w_setup_ratio0.15Long setup before the first assertion correlates with brittle tests that drift from their intent; sigmoid keeps the term smooth and bounded.
w_zero_asserts0.20A test that verifies nothing cannot fail by intent — it survives only by not raising. Weight is high but slightly below w_mock_only because such tests are often vestigial smoke tests rather than mock-theater. The term is gated on unverified, not on assertion_count alone: a test that checks a child process’s exit status, or verifies through an assertion helper, does fail by intent.
w_smell_density0.10Re-uses information already captured by other heuristics, so weighted lowest — but a test that trips multiple smells should rank above one that trips none.

Sum of the weight values: 1.00. That sum is not a reachable score — see the next section.

Reachable range

Two of the five terms can never fire together. w_mock_only requires only_asserts_on_mock, which requires assertion_count > 0; w_zero_asserts requires assertion_count == 0. So the highest-scoring test is one of two shapes:

Branchmock-onlypatchsetupzero-assertssmellsSupremum
Mock-only (asserts only on the double)0.350.20→ 0.1500.10 (both smells)0.80
Unverified (no verification at all)00.20→ 0.150.200.05 (mock_overuse only)0.60

The unverified branch can carry only one smell: mock_only_assertions needs an assertion. The setup term is a sigmoid, which approaches w_setup_ratio without reaching it, so both bounds are approached and never attained: every test score lies in [0.0, 0.80), and in practice in (0.018, 0.80), because the setup term is never zero either. A file score adds at most 0.10 to a mean of test scores, so it lies in [0.0, 0.90).

Changing a weight changes these bounds; recompute them from the table.

Sub-metric definitions

  • assertion_count counts four kinds of assertion site, one each: assert_statement nodes, with pytest.raises(...) / with raises(...) context-manager blocks, self.assertXxx(...) calls inside a test class, and bare Mock-API assertion calls written as their own statement (m.assert_called_once_with(1), any assert_* name in MOCK_API_ATTRIBUTES). All four raise at the line they sit on, which is what keeps the count syntactic. A raises block is always a non-mock assertion: it disqualifies only_asserts_on_mock. A bare Mock-API assertion call is always a mock assertion. Raises blocks and bare mock calls participate in setup_to_assertion_ratio like an assert_statement; self.assertXxx(...) calls do not.
  • mock_assertion_count is the subset of assertion_count that inspects the test double: bare m.assert_*(...) calls; assert statements whose expression reads a Mock-API attribute directly, through not, parentheses, len(...), an index or attribute hanging off it (m.call_args[0][0]), or on either side of a comparison (m.call_count == len(items) counts; result == m.return_value does not, since return_value is not in the set); and self.assertXxx(...) calls whose every argument is a Mock-API read, a literal, or a unittest.mock assertion helper (call(...), ANY), with at least one Mock-API read. only_asserts_on_mock is exactly assertion_count > 0 && mock_assertion_count == assertion_count, which is what the w_mock_only term reads. and / or counts as a mock read only when every operand is one; assert m.called and result == 3 is real verification. An arbitrary call wrapped around an attribute (helper(m.call_count)) is also classified as real verification: the helper may check anything, and only len(...) is known not to.
  • external_verification_count counts call sites that propagate a failure from outside the test process: a call resolving to subprocess.check_call / subprocess.check_output, a call resolving to subprocess.run carrying the literal check=True, and <receiver>.check_returncode(). Import aliases are canonicalized first. It is deliberately not folded into assertion_count, which stays a syntactic count — the two answer different questions, and merging them would silently change a published field’s meaning. Its effects on the score are two: the w_zero_asserts term switches off, and setup_to_assertion_ratio is measured to the first verification call site instead of the body height (see the next bullet). The mock, patch and smell terms are computed as usual, so a checked-subprocess test that overuses mocks still ranks for that. A checked call against a name the test itself replaced with a double (@patch, monkeypatch.setattr, a fixture of the same name, a local assigned from a Mock(), a patcher a setUp started for the whole class) is excluded, as is one whose failure may never reach pytest — nested in a def/lambda or a generator expression, inside a try that has an except, or inside with contextlib.suppress(...). Evidence the test manufactured, or that cannot escape, is not evidence. from subprocess import * is never matched at all, which under-counts; that is the safe direction.
  • helper_assertion_count counts verification delegated to a call: a call canonicalizing to numpy.testing.assert_* / pandas.testing.assert_* / polars.testing.assert_* / pytest.fail; a with pytest.warns(...) / with pytest.deprecated_call() block; and a call to a same-file helper (module-level function by bare name, or self.<method> on the test’s class) whose body holds a non-mock effective assertion — one level deep, no imports, no conftest.py. The closed lists live in src/assertion_helpers.rs. Like external_verification_count it stays out of assertion_count; unlike it, each site is a full non-mock assertion: it switches off w_zero_asserts, disqualifies only_asserts_on_mock (so w_mock_only is off), is an assertion site for setup_to_assertion_ratio, and counts in the mock_overuse denominator (asserts, below). Sites inside a nested def / lambda the test may never call are not counted, and a local rebinding of a helper’s name (check = lambda x: None) shadows it.
  • setup_to_assertion_ratio (locked, Run 3; extended to raises blocks and to external verification): when at least one effective assertion exists in the body, (first_effective_line - def_line) / effective_count measured in tree-sitter start_position().row deltas, where an effective assertion is an assert_statement, a with pytest.raises(...) block, a bare Mock-API assertion call or a helper_assertion_count site. When the body has no effective assertion but does carry external verification, the first verification call site takes the assertion’s place: (first_verification_line - def_line) / external_verification_count — the body is not “setup with no payoff”, so the fallback below would misread it. When it has neither, the numerator becomes (last_body_line - def_line) and the denominator is 1 — the result is the body height. This naturally pushes setup-heavy unverified tests up the ranking, complementing the w_zero_asserts term.
  • patches saturates at 5: the term becomes 1.0 once a test installs five or more patches, by decorator or in the body. Five is the point past which incremental patches add no new signal — the test is already maximally mock-mediated.
  • smell_hits.len() saturates at 2, the number of per-test smell categories (mock_only_assertions, mock_overuse). The saturation point is derived from that category list in src/smells.rs, so a test that trips every per-test smell gets the full w_smell_density; a third category would move it to 3 automatically. Before this was tied to the category count it sat at 3 and the term could only reach two thirds of its weight.
  • The setup-ratio sigmoid uses (setup_to_assertion_ratio - 8.0) / 4.0 as its argument. The -8.0 term places the inflection point at 8 setup lines — the row delta at which a test is becoming suspect (eight lines of arrange-act-assert prelude before the first assertion is a lot for a unit test). The / 4.0 divisor controls the sigmoid’s slope: a ratio of 4 lines on either side of the inflection produces ~0.27 / ~0.73, and ratios beyond 16 / 0 saturate cleanly.

Mock-smell thresholds

Mock-smell detection (src/smells.rs) feeds the w_smell_density term. Its v1 thresholds:

  • mock_overuse_floor = 2 — the minimum value used as the floor in the mocks > max(asserts, floor) predicate. Stops the smell firing on a test with zero or one assertion just because the mock count is small but non-zero.
  • mock_overuse_ratio = 2.0 — the mocks / max(asserts, 1) ratio that must be exceeded for mock_overuse to fire, where mocks is the sum defined below.
  • Both predicates use strict > semantics — a 2-mock-2-assert test sits on the boundary and does not fire.
  • asserts is assertion_count + helper_assertion_count — summed over the file’s tests at file scope. A test that verifies through assert_frame_equal balances its mocks exactly as one using assert does.

mocks decomposition

The numerator of mock_overuse is a sum of three disjoint counts. The same sum is used at test scope and at file scope (where each count is the sum over the file’s tests).

  • mock_construction_count — calls in a test body whose head resolves, through the file’s imports, to Mock / MagicMock / AsyncMock / create_autospec / patch / patch.object / patch.dict / patch.multiple in unittest.mock or the mock backport. A bare name no import binds (star import, conftest) is assumed to be unittest.mock’s when it is itself one of those names; any other unbound head (factory.Mock, a local mock) is not counted.
  • patch_decorator_count — @patch-shaped decorators on the test function: @patch, @<x>.patch, @patch.<attr>, or any decorator resolving to a patch* variant (@mock.patch.object).
  • stubs_count — fixture-driven calls whose dotted call-head matches STUB_HEADS (monkeypatch.setattr, monkeypatch.setenv, monkeypatch.delattr, monkeypatch.delenv, monkeypatch.context, monkeypatch.syspath_prepend, monkeypatch.chdir, mocker.patch, mocker.patch.object, mocker.patch.dict, mocker.patch.multiple, mocker.spy, mocker.stub, mocker.Mock, mocker.MagicMock, mocker.AsyncMock, mocker.create_autospec). The mocker fixture is not an import, so these are matched as written and never overlap the construction count.

A fourth count, patch_call_count, feeds the patch term only. It is the body-level patches — the patch* subset of mock_construction_count plus the mocker.patch* subset of stubs_count — and is never added to mocks. That gives every patch the same footprint whatever its spelling:

SpellingPatch term inputmocks term
@patch("a.b")patch_decorator_countpatch_decorator_count
with patch("a.b"): / patch.object(...)patch_call_countmock_construction_count
mocker.patch("a.b")patch_call_countstubs_count
Mock() / mock.MagicMock()—mock_construction_count
mocker.MagicMock() / monkeypatch.setattr(...)—stubs_count

File-level score

file_score = mean(test_scores_in_file) + bonus
where bonus = min(0.1, max(0.0, (mock_construction_count / max(assertion_count, 1)) - 1.0) * 0.05)

The bonus is zero when the ratio is at most 1.0; it grows linearly past that threshold (one extra 0.05 per unit of ratio above 1.0) and is capped at 0.1. Files with no tests yield 0.0 (no panic on empty test_scores_in_file).

Concrete shapes:

  • 1 mock, 1 assert → ratio = 1.0 → bonus = 0.0.
  • 2 mocks, 1 assert → ratio = 2.0 → bonus = 0.05.
  • 3 mocks, 1 assert → ratio = 3.0 → bonus = 0.10 (cap).
  • 100 mocks, 1 assert → ratio = 100.0 → bonus = 0.10 (still capped).

Deferred extensions

These are intentionally not implemented in Run 3 / v1.

  • Top-called overlap bonus. The original spec sketched an additional per-test term that boosts the score of tests that touch many of the top-called SUT entries (the assumption: tests calling popular SUT surface area are the most consequential, and so the highest-yield candidates to review). Implementing this requires the sut_calls.top_called list to be rank-stable, which it is in v1, but the term has not been calibrated against real-world traces and lands later.
  • Runtime-tunable weights. Planned --weights <path> CLI override loading a TOML file that mirrors the SuspicionWeights struct. The shape is straightforward; we are deferring because v1 callers (the workflow’s Phase 2 LLM and an early-adopter human) all want the same defaults, and shipping the knob without a story for how Phase 2 picks weight overrides is a vector for inconsistent outputs.

How to revise

These weights are heuristic starting points. The intended workflow:

  1. Run pycoati on a real project.
  2. Skim top_suspicious.test_functions (default 20 entries).
  3. For each entry, mentally label it useful / borderline / noise.
  4. If a category of test consistently appears as noise (or fails to appear), revise the weights — bump the term that should have caught the missing case, or shrink the term that brought in the noise.
  5. Update this file and src/suspicion.rs::DEFAULT together — they are the single source of truth.

The defaults will not stay defaults forever. Revising them is expected.

Release notes

What changed for users, release by release. Each entry is one change you can notice. Dependency bumps and internal clean-ups are left out.

Nothing yet.

pycoati — setup

pycoati audits a Python test suite and emits a structured inventory: per-file and per-test counts, mock-API smells, and a per-test suspicion score. It never edits your code and never mutates your environment.

You are here to produce inventory.json. Do that, then move to the next page.

Where this fits

pycoati is a periodic audit, not a commit hook. A scan runs the suite under pytest for durations and coverage, so it is minutes, not milliseconds, and its verdict is a ranked list to work through, not a pass/fail. Run it on a schedule, before a refactor of the tests, or when the suite feels slow or untrustworthy. Do not wire it into a pre-commit gate such as madoqua.

The per-commit gate for test quality is zorilla, which lints the changed test files in milliseconds and exits non-zero on findings; uvx zorilla guide explains how to wire it in. The two overlap on purpose: zorilla catches the smell as it is written, pycoati finds the ones already in the suite.

Preconditions

  • pycoati is on PATH. Check with pycoati --version.
  • The project has a test directory. The default is every testpaths entry in <path>/pyproject.toml, else <path>/tests.
  • For runtime metrics (test count, runtime, coverage), pytest and pytest-cov must be importable by the interpreter pycoati picks: uv add --dev pytest pytest-cov. Without pytest the scan still succeeds and every suite.* field is null. Without pytest-cov the coverage pass fails with pytest exit=4, line_coverage_pct is null, and stderr says so; pass --no-coverage if coverage is not wanted.

Configuration

No knob is configurable. pycoati has no coati.toml, reads no [tool.pycoati] table, and exposes no way to change a threshold, a weight, or a scoring rule. Every switch is a command-line flag, and the defaults below are the values compiled into the binary.

The one file of its own that pycoati reads is .pycoati-accept.toml, the accepted-findings baseline. It changes no threshold and no score — it records reviewed per-test exceptions. See “Accepted findings” below.

It also reads four tables that other tools own, and only these:

  • [project].name — seeds project.name and the coverage package.
  • [tool.uv.workspace].members — switches the scan into workspace mode.
  • [tool.hatch.build.targets.wheel].packages, [tool.setuptools].packages, [tool.setuptools.packages.find].include — declare which import names count as project-internal for sut_calls.
  • [tool.pytest.ini_options].testpaths (or the pytest 9 native [tool.pytest].testpaths) — the default test directories when --tests-dir is not given.

If sut_calls comes back empty on a project that clearly calls its own code, the cause is almost always that none of these package tables are present. Pass --project-package <module> to fix it.

Run the scan

From the project root:

pycoati . --output inventory.json

That is the invocation the rest of this guide assumes. inventory.json in the current directory is a convention this guide establishes, not a default the binary knows — pycoati writes to stdout unless you pass --output.

Single file instead of a project:

pycoati tests/test_thing.py --output inventory.json

Human-readable view for a terminal, no file written:

pycoati . --format pretty

Flags

  • --output <PATH> / -o — write to this file instead of stdout. Files are written with no trailing newline. Default: stdout.
  • --format <json|pretty> — json is the structured inventory and the only format this guide can read. pretty is an aligned-column terminal view for humans. Default: json.
  • --tests-dir <PATH> — override test discovery root. Default: every entry of testpaths in <path>/pyproject.toml, relative to <path> — a list, or a string split on whitespace as pytest does. Glob entries (src/*/tests) are not expanded; they are skipped with a warning. Entries that do not exist are skipped with a warning, and when none exists <path>/tests is used if it does. With no testpaths setting the default is <path>/tests. Workspace members use their own pyproject.toml the same way. pytest.ini, tox.ini and setup.cfg are not read. Directory input only; rejected for single-file input and for workspace roots.
  • --static-only — skip every pytest subprocess. The scan becomes pure AST analysis: fast, no test execution, and every suite.* field stays null. Use when pytest cannot run or when the suite is too slow to execute.
  • --no-coverage — skip only the coverage subprocess. Collection and durations still run.
  • --top-suspicious <N> — cap the top_suspicious.test_functions and top_suspicious.files lists. Default: 20. 0 returns empty lists. This changes list length only — it is not a threshold and it does not change any score.
  • --project-package <NAME> — the importable module name used for coverage and for classifying calls as project-internal. Default: [project].name with hyphens converted to underscores, else the directory basename. The override is used verbatim, with no normalization.
  • --python <CMD> — interpreter to run pytest under, whitespace-split, no shell expansion. --python "uv run python" runs uv run python -m pytest .... Default: auto-detect, in order — nearest ancestor .venv/bin/python, then uv run --no-sync python if uv --version succeeds, then bare python.
  • --pytest-args <STR> — extra arguments appended to every pytest invocation, whitespace-split, no shell expansion. Default: empty.
  • --member-cwd <root|member> — workspace mode only. root runs every member’s pytest from the workspace root; member runs each from its own directory so member-local conftest.py applies. Default: root. Silently ignored outside workspace mode.
  • --accept-file <PATH> — accepted-findings baseline. Default for a project scan: <project>/.pycoati-accept.toml when that file exists, otherwise none. For a single-file scan: the nearest .pycoati-accept.toml at or above the file’s own directory. A path passed explicitly must exist, or the scan fails. Rejected against a workspace root — each member reads its own.
  • --no-accept — ignore the baseline and report the raw shortlist. Nothing is read, and accepted.path is null.
  • --include-accepted — keep accepted findings on top_suspicious.test_functions. The full audit report rather than the default actionable shortlist. The accepted block is emitted either way.

Accepted findings

A periodic audit re-surfaces the same legitimate tests every time it runs. The baseline is where a reviewer records that judgement once, with a reason, so the next scan does not make them reconstruct it.

Put .pycoati-accept.toml at the project root — a single-file scan looks there too, walking up from the file’s own directory to the nearest one:

schema_version = "1"

[[accept]]
test = "tests/test_packaging.py::test_wheel_installs"
signals = ["zero_asserts", "high_setup_ratio"]
reason = "assertions run in a child interpreter; the parent propagates failure via subprocess.run(check=True)"
reviewed = "2026-09-12"
fingerprint = "3f0a1c7d9b2e4a56"
  • test — required. The nodeid exactly as it appears in test_functions[].nodeid. In a workspace, relative to the member.

    Copy it from the inventory, and scan the same way every time. In project mode the file prefix is relative to the project root, so pycoati . and pycoati /abs/path/to/project produce the same nodeid. In single-file mode the prefix is the path exactly as typed, so scanning the same file by a different path produces a different nodeid and the entry reports unknown_test instead of applying.

  • signal / signals — required, exactly one of the two. One signal name, or a list of them. The closed set is mock_only_assertions, mock_overuse, zero_asserts, high_setup_ratio. There is no wildcard, on purpose: accepting this test’s current finding must not accept a future one.

  • reason — required and non-empty. A file with an entry that omits it does not parse. The reason is the point of the entry.

  • reviewed — optional, free-form (a date, a name, a PR link). Never interpreted.

  • fingerprint — optional. Copy test_functions[].fingerprint from the inventory. When set, editing the test lapses the acceptance until someone reviews it again. When unset, the acceptance survives edits.

zero_asserts means the test verifies nothing at all: no assert-shaped construct and no external_verification_count. A test that checks a child process’s exit status never trips it, so it needs no entry.

An assertionless test usually trips high_setup_ratio too, because the ratio degrades to the height of the whole body. Accept both signals in one entry if that is the reviewed judgement — accepting only zero_asserts deliberately leaves the other one visible.

What acceptance does, and does not do

  • The test is still discovered, still parsed, still counted, and still run by pytest. suite.test_count, suite.runtime_seconds, and suite.line_coverage_pct are identical with and without a baseline. This is not pytest deselection.
  • Every count, every smell_hits entry, and every suspicion_score stays exactly as measured. Nothing is subtracted.
  • The only effect is on top_suspicious.test_functions: a test whose every active signal is accepted is held back from it. One unreviewed signal and the test is back on the list.
  • The accepted findings and their reasons are reported under accepted, and --include-accepted puts them back on the shortlist for a full report.

Stale entries

Every scan re-checks each entry and reports the ones that no longer apply under accepted.stale[], with a warning on stderr:

  • unknown_test — the nodeid is gone. Delete the entry.
  • signal_not_active — the signal stopped firing. Delete the entry.
  • content_changed — the test was edited since its recorded fingerprint. The finding is live again until a reviewer updates the entry.

A stale entry never suppresses anything.

What gets scanned

Test files are discovered recursively under the tests directory. A file qualifies when its basename matches test_*.py or *_test.py. Hidden files, gitignored files, and symlinks are skipped.

Within a file, pycoati collects top-level def test_* and async def test_*, plus test_* methods on classes whose name starts with Test, plus every test* method on a class that subclasses unittest.TestCase or IsolatedAsyncioTestCase (directly or through same-file base classes), whatever the class is called. Classes nested inside a collected Test* class are collected too, with nodeid <file>::Outer::Inner::test_x; classes nested in a TestCase subclass are not, matching pytest. Test methods inherited from a base class in the same file are collected on each subclass, as pytest does (<file>::Leaf::test_x); bases imported from another module are not followed. Functions nested inside other functions are not collected.

Scan behaviour you must not misread

  • A failed pytest subprocess is not a failed scan. Collection, durations, and coverage each degrade to null independently, with a warning on stderr. Check tool.ran_pytest and tool.ran_coverage before trusting any suite.* value.
  • Diagnostics go to stderr. stdout carries only the payload, so pycoati . > inventory.json is safe.
  • A non-zero exit means the scan did not produce an inventory. The reason is on stderr, prefixed pycoati:.

Workspaces

If the root pyproject.toml declares [tool.uv.workspace], the output is a workspace payload: a members array holding one complete inventory per member, wrapped with a workspace_root key. Analyze each member independently — scores and rankings are computed per member and are not comparable across members. --tests-dir and --project-package are rejected against a workspace root.

To decide how many of the members’ pytest runs to start in parallel, and which members share a run, see pycoati guide plan. It is a side trip: the audit does not need it.

Verify before moving on

inventory.json is usable when all of these hold:

  • It parses as JSON.
  • schema_version is "3".
  • test_functions is non-empty. An empty array on a project with tests means discovery found nothing — check --tests-dir and the file naming convention above before continuing.

next: run pycoati . --output inventory.json, then pycoati guide analyze

pycoati — analyze

You have inventory.json. This page defines every field in it, then defines the anti-patterns you are looking for and the signals that flag each one.

Read this whole page before opening the inventory. Produce no edits from this page — analysis only.

The one rule for this phase

A signal is a lead, not a verdict. Every heuristic below is computed from the AST without understanding what the test means. A test can trip three signals and still be correct, and a test can trip none and still be worthless. Every candidate you identify must be confirmed by reading the test source before it appears in your report. If reading the test contradicts the signal, the test wins — drop the candidate.


Part 1 — field reference

Every field is always present. null never means zero; it means not measured. The payload has two shapes, discriminated by one key.

Top level, single project

  • schema_version — schema contract version, as a string. This page describes "3". Any other value means this guide and the inventory disagree; stop and re-run pycoati guide analyze from the binary that produced the file.
  • project — object. Identity of the audited project.
  • suite — object. Suite-level runtime metrics from pytest.
  • files — array of file records, one per discovered test file, sorted by path. A file with zero tests still gets a record in directory mode.
  • test_functions — array of test records, one per collected test function.
  • sut_calls — object. Aggregated project-internal call frequency.
  • top_suspicious — object. Pre-ranked shortlists.
  • accepted — object. Reviewed suppressions in effect for this run.
  • tool — object. Producer metadata.

Top level, workspace

A workspace payload carries schema_version, workspace_root, members, and tool, and nothing else. Each member carries its own accepted block — acceptance is per member, because a nodeid is only unique within one.

  • workspace_root — path of the workspace root. The presence of this key is the only discriminator between the two shapes. Check for it first.
  • members — array of complete single-project inventories, one per workspace member. Analyze each independently; scores are computed per member and are not comparable across members.

project

  • path — absolute, canonicalized path of the project root. In single-file mode this is the directory containing the file, not the file itself. Falls back to the path as given only if canonicalization fails, which logs a warning to stderr.
  • name — [project].name from pyproject.toml, else the directory basename.

suite

Every field here is null under --static-only and on any pytest failure. Check tool.ran_pytest and tool.ran_coverage before using any of them.

  • test_count — count of items pytest collected. Parametrize is expanded, so this legitimately exceeds the sum of test_function_count across files. null = not measured.
  • runtime_seconds — wall-clock seconds for the whole durations run, as reported by pytest’s summary line. null = not measured.
  • line_coverage_pct — line coverage as a percentage in 0–100, not a fraction. Suite-wide. There is no per-test or per-file coverage attribution anywhere in this schema. null = not measured.
  • slowest_tests — array of at most 20 entries, descending by duration.

suite.slowest_tests[]

  • nodeid — pytest’s nodeid. Parametrize is expanded, so this looks like tests/test_x.py::test_y[case-3]. This is a different string space from test_functions[].nodeid — see the joining rule under slow-without-reason.
  • seconds — wall-clock duration of that test item.

files[]

One record per discovered test file.

What paths are relative to, which differs by mode. In directory mode, files[].path, test_functions[].file, and the file prefix of every nodeid are relative to project.path. In single-file mode they are the path exactly as it was typed on the command line — absolute if you passed an absolute path, cwd-relative if you passed a relative one — and are therefore not relative to project.path, which is canonicalized in both modes. Resolve a path before opening a file at file:line.

  • path — path to the test file.
  • test_function_count — number of def test_* functions parsed from this file via AST. Class-nested test methods are counted. Parametrize is not expanded.
  • assertion_count — effective assertions across every test body in the file: the sum of test_functions[].assertion_count for this file’s tests, with the same definition.
  • mock_construction_count — sum of test_functions[].mock_construction_count for this file’s tests, with the same definition.
  • patch_decorator_count — sum of the per-test decorator counts in this file.
  • stubs_count — fixture-driven patch call sites in this file. The matched set is closed and exact: monkeypatch.setattr, monkeypatch.setenv, monkeypatch.delattr, monkeypatch.delenv, monkeypatch.context, monkeypatch.syspath_prepend, monkeypatch.chdir, mocker.patch, mocker.patch.object, mocker.patch.dict, mocker.patch.multiple, mocker.spy, mocker.stub, mocker.Mock, mocker.MagicMock, mocker.AsyncMock, mocker.create_autospec.
  • fixture_count — @pytest.fixture / @fixture decorators anywhere in the file, including on non-test functions. File scope only.
  • smell_hits — array of smell hits at file scope. See smell_hits[] below.

test_functions[]

One record per collected test function. This is the primary array; most of your analysis reads from here.

  • nodeid — <file>::<test>, or <file>::<Class>::<method> for class-based tests, with one ::<Class> segment per level for nested classes (<file>::TestOuter::TestInner::test_x). Classes are collected when named Test* or when they subclass unittest.TestCase / IsolatedAsyncioTestCase (directly or through same-file base classes), matching what pytest collects. Classes nested inside a TestCase subclass are not collected, as pytest does not. In a TestCase subclass every test* method counts, as unittest’s loader does; in other classes and at module level only test_* counts — narrower than pytest’s own default, which would also collect def testfoo(). Test methods a same-file base class defines and the subclass does not override are collected on the subclass too (<file>::Leaf::test_x), as pytest does; bases imported from another module are not followed. Known gap: only unittest’s own base classes are recognised (a django.test.TestCase subclass is collected only when it is named Test*). Parametrize is not expanded, so there is never a [...] suffix.

  • file — path to the file containing this test. Joins to files[].path.

  • line — line of the def. 1-indexed, matching what an editor shows. An inherited test reports the base class’s def line, so the copies on each subclass share one line (and one fingerprint).

  • assertion_count — effective assertion sites in this test body, one each: assert statements, with pytest.raises(...) blocks, self.assertXxx(...) calls inside a test class, and bare mock-API assertion calls written as a statement on their own (m.assert_called_once_with(1)). Every one of these fails the test at the line it sits on. Verification that happens elsewhere is counted separately — see external_verification_count.

  • only_asserts_on_mock — true when the test has at least one assertion and every one of them targets the mock API, i.e. mock_assertion_count == assertion_count > 0. A raises block never targets the mock API, so one in the body makes this false. false when the test has zero assertions — this flag never fires on an assertionless test, so it does not overlap dead-test.

  • mock_assertion_count — the part of assertion_count that inspects a test double rather than a value the code under test produced. The mock-API attribute set is closed and exact: called, call_count, call_args, call_args_list, assert_called, assert_called_with, assert_called_once, assert_called_once_with, assert_not_called, assert_any_call, assert_has_calls, their AsyncMock counterparts await_count, await_args, await_args_list, assert_awaited, assert_awaited_once, assert_awaited_with, assert_awaited_once_with, assert_any_await, assert_has_awaits, assert_not_awaited, and the call records mock_calls, method_calls. A site counts here when it is:

    • a bare call to one of the assert_* names on any receiver except bare self — m.assert_called_once_with(1), self.client.send.assert_called();
    • an assert whose expression reads one of those attributes, directly or through not, parentheses, len(...), an indexing or attribute access hanging off it (m.call_args[0][0], m.call_args.kwargs), or either side of a comparison — assert not m.called, assert m.call_count == 2, assert m.call_count == len(items). assert result == m.return_value does not count: return_value is configuration, not part of the set;
    • a self.assertXxx(...) call where at least one argument reads one of those attributes and every other argument is a literal, a mock assertion helper (call(...), call.save(...), ANY, imported from unittest.mock or mock) or a container of those — self.assertEqual(m.call_count, 1), self.assertFalse(m.called). self.assertEqual(m.call_count, len(items)) does not count, because the argument list does not say which side is the value under test. A msg= argument is ignored.

    and / or counts only when every operand reads the mock API (assert m.called and m.call_count == 1); one real operand (assert m.called and result == 3) makes it real verification. So does an arbitrary call around the attribute (helper(m.call_count)).

  • patch_decorator_count — @patch, @mock.patch, @patch.object, or any @<something>.patch decorator on this test.

  • patch_call_count — patches this test installs without a decorator: calls in the body resolving to patch, patch.object, patch.dict or patch.multiple from unittest.mock or the mock backport (usually as with patch(...):), plus mocker.patch, mocker.patch.object, mocker.patch.dict and mocker.patch.multiple. Spelling does not matter: with mock.patch(...) under from unittest import mock counts. Read it beside patch_decorator_count — together they are every patch the test installs, and the score’s patch term reads their sum. Do not add it to mock_construction_count or stubs_count: each site here is already in exactly one of those.

  • mock_construction_count — Mock-API constructions in this test’s body: calls resolving to Mock, MagicMock, AsyncMock, create_autospec, patch, patch.object, patch.dict or patch.multiple in unittest.mock or the mock backport. Call heads are resolved through the file’s imports, so mock.Mock() under from unittest import mock and an aliased MagicMock as MM both count, while factory.Mock() or a Mock imported from your own package do not. A bare Mock() that no import binds (star import, conftest) still counts. mocker.Mock() and friends are stubs, not constructions.

  • stubs_count — fixture-driven patch call sites in this test’s body, from the closed list given under files[].stubs_count.

  • setup_to_assertion_ratio — lines of setup per assertion, as a float. Computed as (first_effective_assertion_line - def_line) / effective_assertion_count, where an effective assertion is an assert statement, a with pytest.raises(...) block, a bare mock-API assertion call (m.assert_called_once_with(1)) or a helper_assertion_count site. self.assertXxx(...) calls raise assertion_count without feeding this denominator. When the body has no effective assertion but does carry external verification, the first such call site stands in for the first assertion: (first_verification_line - def_line) / external_verification_count. When it has neither, it degrades to (last_body_line - def_line) / 1, i.e. the height of the whole body — so a long unverified test scores high here by design. Units are source lines. 0.0 means the first assertion is on the def line itself, which in practice means a one-line body.

  • external_verification_count — call sites in this test body that verify an outcome the body itself cannot see, because a failure raised outside this process still fails the test. The matched set is closed and exact: a call resolving to subprocess.check_call or subprocess.check_output; a call resolving to subprocess.run that passes the literal check=True; and <receiver>.check_returncode(). Import aliases are resolved first, so import subprocess as sp and from subprocess import run as r both match. This is not part of assertion_count, which stays a syntactic count of assertion sites in the body — read the two together. A non-zero value means zero assertions is not the absence of verification; it does not mean the child process checks anything worth checking. See dead-test below.

    Four shapes are deliberately not counted, so a 0 here is sometimes a known miss rather than a verdict: a call against a name the test replaced with a double (@patch on the test or its class, monkeypatch.setattr, a patcher started in setUp, a fixture of the same name, a local assigned from a Mock()); a call whose failure may never reach pytest — inside a nested def/lambda or a generator expression, inside a try that has an except, or inside with contextlib.suppress(...); a call under from subprocess import *, which binds an unknown set of names; and every check_returncode() in a test that patched any subprocess name at all, including one on a real CompletedProcess.

  • helper_assertion_count — verification this test delegates to a call rather than writing as an assertion site. Three closed sources, one each:

    • a call resolving through the file’s imports to numpy.testing.assert_*, pandas.testing.assert_*, polars.testing.assert_* or pytest.fail — np.testing.assert_allclose(...) under import numpy as np counts;
    • a with pytest.warns(...): or with pytest.deprecated_call(): block, one per block, like a raises block;
    • a call to a same-file helper whose own body holds a non-mock assertion: a module-level function called by bare name (and not shadowed by one of the test’s parameters), or self.<method>(...) for a method of the test’s class or of a base class defined in the same file (the nearest definition wins, so a non-asserting override does not count). One level only: a helper that verifies by calling another helper does not count, nor does anything imported or defined in conftest.py. A helper whose only assertions target the mock API does not count either.

    Not part of assertion_count — read the two together, like external_verification_count. Each site counts as a non-mock assertion everywhere else: it switches off zero_asserts, makes only_asserts_on_mock false, and is an assertion site for setup_to_assertion_ratio, and it counts as an assertion in the mock_overuse ratio. Two shapes are never credited: a helper call inside a nested def or lambda the test may never call, and a call to a name the test rebinds itself (a parameter, check = lambda x: None, a nested def of the same name).

  • called_names — sorted, deduplicated, dot-joined names of calls in this test body, filtered to project-internal names only. Calls into the standard library, into third-party packages, and self.* calls are all excluded. An empty array means this test calls none of your own code by a name pycoati could resolve. Resolution goes through the file’s imports, so aliases are canonicalized: from myproj.repo import Repository used as Repository.save appears as myproj.repo.Repository.save.

  • smell_hits — array of smell hits at test scope. See below.

  • suspicion_score — float, always below 0.80. Composite; see the formula and its reachable range below. Higher is more suspicious. This is a ranking device, not a measurement — the absolute value has no meaning beyond ordering.

  • fingerprint — 16 hex digits identifying this test’s current source, decorators included. Trailing whitespace and blank lines are ignored; everything else, comments included, is part of it. Its only use is the fingerprint key of an accept entry: recording it there makes the acceptance lapse when the test is edited. Not a checksum of anything else, and not comparable across tests. null only when the source could not be read as UTF-8 — an entry pinned against such a test reports content_changed rather than silently matching.

  • accepted_signals — sorted signal names a baseline entry accepted for this test, or []. A signal listed here was reviewed and signed off; it is still computed, still scored, and still present in smell_hits. Read this alongside accepted.findings, which carries the reason for each.

smell_hits[]

Appears on both files[] and test_functions[].

  • category — a closed set of exactly two strings: mock_only_assertions and mock_overuse. Any other value means the schema changed under you.
  • test — the nodeid this hit belongs to, or null for a file-scope hit. Use null here as the file-vs-test scope discriminator.
  • line — 1-indexed line for test-scope hits; 0 for file-scope hits, which is a sentinel and not line 1.
  • evidence — short human-readable string naming the counts that fired the rule, e.g. 7 mocks, 2 assertions. Display it in your report; do not parse it.

sut_calls

  • by_name — array of entries, one per resolved project-internal name, sorted by name ascending.
  • top_called — at most 20 names, descending by number of calling tests, ties broken by name ascending. A shortlist over by_name; carries no extra data.

sut_calls.by_name[]

  • name — the canonical dotted project-internal name.
  • test_function_count — number of distinct test functions whose body calls this name. Not the number of call sites: a test calling it five times counts once.
  • test_nodeids — sorted nodeids of those tests. Joins to test_functions[].nodeid.

top_suspicious

Convenience shortlists, capped by --top-suspicious (default 20). They contain no information that is not already in test_functions and files.

  • test_functions — nodeids of the highest-scoring tests, descending by suspicion_score, ties broken by nodeid ascending. A test whose every active signal was accepted is omitted unless the scan ran with --include-accepted; accepted.included_in_shortlist tells you which. The test’s own record in test_functions[] is there either way.
  • files — paths of the highest-scoring files, descending by file score, ties broken by path ascending. Acceptance is per test and never filters this list: a file whose tests were all accepted keeps its score and its place.

accepted

Reviewed per-test suppressions, read from the baseline file described on the setup page. This block is the only place a suppression is visible — nothing is removed from files, test_functions, smell_hits, or any count.

  • path — the baseline file that was read, or null when none was found or the scan ran with --no-accept. null with a non-empty findings array is impossible.
  • included_in_shortlist — true when the scan ran with --include-accepted, meaning accepted findings were not held back from top_suspicious.test_functions. Report this: it changes what the shortlist means.
  • findings — array of acceptances that matched a live finding.
  • stale — array of acceptances that matched nothing. Each one is a finding that is actionable again, or an entry to delete. Both are reported to stderr as warnings during the scan.

accepted.findings[]

  • test — nodeid of the accepted test. Joins to test_functions[].nodeid.
  • signal — the one signal accepted for that test, from the closed set: mock_only_assertions, mock_overuse, zero_asserts, high_setup_ratio. The first two mirror smell_hits[].category; the last two are score-bearing signals that produce no smell hit. zero_asserts fires on the same condition as the score’s term — assertion_count == 0, external_verification_count == 0 and helper_assertion_count == 0 — so a test that checks a child process or verifies through a helper never offers it, and an entry accepting it on such a test goes stale.
  • reason — the reviewer’s recorded justification. Always non-empty; the file will not parse without it. Quote it in your report — it is the whole content of the review decision, and re-deriving it is what this block exists to prevent.
  • reviewed — free-form provenance note (a date, a name, a PR link), or null. Never interpreted.
  • fingerprint — the test_functions[].fingerprint recorded at review time, or null when the entry did not pin one. When present it matched, or this entry would be under stale instead.

accepted.stale[]

  • test, signal, reason — copied verbatim from the entry that did not apply.
  • status — why, from a closed set of three:
    • unknown_test — no test in this inventory carries that nodeid. The test was renamed, moved, or deleted; the entry is dead weight.
    • signal_not_active — the test is there and the signal no longer fires. The underlying problem was fixed, or the heuristic changed.
    • content_changed — the test’s fingerprint differs from the one the entry pinned, or the test has no fingerprint at all. The acceptance is suspended until a human looks again. This is the only status that can hide a real, currently-firing finding, so treat it as an unreviewed finding, not as bookkeeping.
  • detail — human-readable explanation, carrying the current fingerprint for the content_changed case. Display it; do not parse it.

tool

  • name — always pycoati.
  • version — the binary’s version. Record it in your report.
  • ran_pytest — true only if the collection/durations subprocesses actually succeeded. When false, every suite.* field is null and no timing-based finding is available.
  • ran_coverage — true only if the coverage subprocess succeeded. When false, line_coverage_pct is null.

The suspicion score

suspicion_score = 0.35 * (only_asserts_on_mock ? 1 : 0)
                + 0.20 * min((patch_decorator_count + patch_call_count) / 5, 1)
                + 0.15 * sigmoid((setup_to_assertion_ratio - 8) / 4)
                + 0.20 * (unverified ? 1 : 0)
                + 0.10 * min(len(smell_hits) / 2, 1)

unverified = assertion_count == 0 and external_verification_count == 0
             and helper_assertion_count == 0

sigmoid(x) = 1 / (1 + e^-x). Weights sum to 1.00, but no test can score 1.00: the 0.35 mock-only term needs at least one assertion and the 0.20 zero-assert term needs none, so they never fire together.

Consequences you need when reading scores:

  • The setup term is never zero. Even a test with a ratio of 0 contributes 0.15 * sigmoid(-2) ≈ 0.018, so scores are never exactly 0.00.
  • Patches (patch_decorator_count + patch_call_count) saturate at 5 and len(smell_hits) at 2 — the number of per-test smell categories, so a test with both smells gets the full 0.10. Ten patches score the same as five, and a with patch(...) scores the same as a @patch.
  • The highest reachable score is just under 0.80: mock-only assertions (0.35), five or more patches (0.20), both smells (0.10) and a very long setup (approaching 0.15). A test that verifies nothing tops out just under 0.60 (0.20 zero-assert, 0.20 patches, 0.05 for its one possible smell, approaching 0.15 setup). Read scores against those ceilings, not against 1.0.
  • The setup sigmoid inflects at a ratio of 8.0 with scale 4.0: ratio 8 contributes exactly half the setup weight.
  • File scores are the mean of their tests’ scores plus a bonus that grows at 0.05 per unit once mock_construction_count / max(assertion_count, 1) exceeds 1.0, capped at 0.10, so they stay below 0.90. File scores are therefore not directly comparable to test scores.

Two of the five terms fire on unverified tests (w_zero_asserts plus an inflated setup ratio), so an empty test lands between about 0.22 for a short body and 0.35 for a long one — 0.35 is the ceiling of those two terms together and is approached, never reached. Do not read a score in that band as mock abuse.

A test with assertion_count == 0 and external_verification_count > 0 or helper_assertion_count > 0 does not reach that band for those reasons: the w_zero_asserts term is off, and the setup ratio is measured to the first verification call site instead of the whole body height, so it is no longer inflated — though it still contributes, exactly as it does for a test with a real assertion. The mock, patch and smell terms score as they would on any other test, so such a test can still reach 0.22+ on those. When it does, that is a real signal about mock abuse, not about the test being empty — read the field, not just the score.

Smell thresholds

  • mock_only_assertions fires per test when only_asserts_on_mock is true and assertion_count > 0. It fires per file when every test in the file that verifies (assertion_count > 0 or helper_assertion_count > 0) has only_asserts_on_mock true; tests that verify nothing are excluded from that predicate.
  • mock_overuse fires when mocks > max(asserts, 2) and mocks / max(asserts, 1) > 2.0, where asserts is assertion_count + helper_assertion_count (summed over the file’s tests at file scope). Both comparisons strict. mocks is mock_construction_count + patch_decorator_count + stubs_count at both test and file scope. Each patch lands in exactly one of those three, whatever its spelling: a decorator in patch_decorator_count, with patch(...) in mock_construction_count, mocker.patch(...) in stubs_count.

Accepted findings and what they mean for your report

An acceptance is a review decision recorded once, not a rule change and not a threshold. Read it as: a human looked at this exact test, agreed the signal fires, and wrote down why it is correct anyway.

They live in .pycoati-accept.toml at the project root, one [[accept]] block per (test, signal) pair, each with a required reason. accepted.path names the file this run actually read. Run pycoati guide setup for the full format — you do not need it to read an inventory, only to propose an entry.

Three consequences for how you read an inventory:

  • Do not re-litigate an accepted finding. If accepted.findings covers a test and signal, that judgement has been made. Quote the reason and move on.
  • An acceptance covers one signal, never a test. A test with accepted_signals: ["zero_asserts"] that also carries a mock_overuse hit is a live candidate for that hit, and it will be on the shortlist. Work it.
  • Every stale entry is work. A content_changed entry in particular means the accepted test was edited since review and the finding is live again — report it as a candidate, and say the acceptance lapsed.

If you cannot confirm a finding by reading the test, and the reason it looks suspicious is genuinely project context the AST cannot see, the right output is a proposed accept entry in your report — test nodeid, signal, reason, fingerprint — for a human to add to .pycoati-accept.toml. Not a threshold change, and not a deleted test. The remediate page gives the exact block to put in the report, and the rule that you propose it rather than write it.


Part 2 — anti-pattern taxonomy

Eight patterns. For each: what it is, what flags it, and what to check by hand.

Work the list top to bottom against top_suspicious.test_functions first, then sweep the full test_functions array for the patterns whose signals are not score-bearing (redundant, slow-without-reason, wrong-layer).

A test may match more than one pattern. Record every match; the remedy page decides precedence.

1. mock-as-assertion

Definition. The test’s assertions are about the test double, not about the system. It verifies that a mock was called, and nothing about what the code produced. Such a test passes as long as the call shape is unchanged, including when the underlying behaviour is broken or entirely absent.

Signals.

  • only_asserts_on_mock == true and assertion_count > 0. This is the definitive signal; the flag is computed to mean exactly this pattern. It covers bare m.assert_called_once_with(...) statements, assert m.call_count == 2, assert not m.called and self.assertEqual(m.call_count, 1) alike.
  • mock_assertion_count > 0 with only_asserts_on_mock == false is the partial form: some assertions verify the double, some verify output. Not a candidate on its own.
  • Equivalently, a smell_hits[] entry with category == "mock_only_assertions".
  • Strength scales with assertion_count: a test with six mock-API assertions and nothing else is a stronger candidate than one with a single such assertion.

Verify by reading. Confirm the test has no observable outcome to assert on. Legitimate exceptions exist: a test whose entire contract is the interaction — verifying a retry fired three times, verifying a destructive call was not made (assert_not_called) — is correctly written this way. Check whether the callee returns a value or mutates state that the test could have asserted on instead. If it does not, this is not a finding.

2. implementation coupling

Definition. The test is bound to how the code is structured rather than what it does. It patches internal collaborators by dotted path, so any rename, move, or refactor breaks the test even though behaviour is unchanged.

Signals.

  • patch_decorator_count + patch_call_count >= 3 on a single test — every patch, decorator or with.
  • stubs_count >= 3 on a single test.
  • mock_construction_count + patch_decorator_count + stubs_count high relative to assertion_count — the mock_overuse hit at test scope encodes exactly this ratio.
  • called_names is short or empty while patch and stub counts are high: the test replaced more of your code than it calls.

Verify by reading. Look at what the patch targets name. Patching an external boundary (network, clock, filesystem, subprocess) is appropriate and is not this pattern. Patching internal functions of the module under test, or reaching through several dotted segments into another module’s internals, is. The distinction is not in the inventory — you must read the target paths.

3. tautology

Definition. The assertion cannot fail, or can only fail if the test itself is broken. It compares a value to itself, asserts a literal, or asserts a property of a mock the test just configured.

Signals.

  • only_asserts_on_mock == true combined with patch_decorator_count > 0 and called_names empty — the test configured a double and then asserted on the double, never reaching project code.
  • assertion_count > 0 with called_names empty: the test asserts, but calls none of your code by any resolvable name.
  • A high suspicion_score with a very low setup_to_assertion_ratio: assertions packed together with almost no setup preceding them.

Verify by reading. This pattern is only weakly visible in the inventory — pycoati does not compare the two sides of an assertion. You must read the assertion expressions. Confirm that the asserted value does not depend on any project code path. Note that called_names is empty for tests that only exercise pure standard-library or third-party behaviour, which may be a deliberate contract test rather than a tautology.

4. setup-heavy

Definition. Arrangement dwarfs verification. The test spends dozens of lines constructing state to check one thing, which makes it slow to read, expensive to change, and unclear about what it protects.

Signals.

  • setup_to_assertion_ratio >= 8.0. This is the sigmoid inflection point in the score — at 8 the term is at half strength, and it is near saturation by 20.
  • setup_to_assertion_ratio >= 15.0 is a strong candidate on its own.
  • High fixture_count on the containing files[] record alongside a high ratio: setup that was extracted into fixtures and still leaves the test long.
  • assertion_count == 1 with a high ratio: maximum setup for minimum verification.

Verify by reading. The ratio is a line count and knows nothing about what those lines do. A test built around a large but genuinely necessary data fixture is not this pattern. Check whether the setup is incidental (could move to a fixture or a builder) or essential (it is the scenario). Also check whether the numerator is inflated by a long docstring or a block comment before the first assertion — those count as lines.

5. redundant

Definition. Several tests exercise the same path with trivially different inputs, so they fail together, are maintained together, and carry the information of one test.

Signals.

  • Two or more nodeids in the same sut_calls.by_name[].test_nodeids list whose called_names arrays are identical, and whose assertion_count values match.
  • A sut_calls.by_name[] entry with a high test_function_count where the named callee is narrow — many tests converging on one function.
  • Groups of test_functions[] entries in the same file with matching assertion_count, matching patch_decorator_count, and identical called_names.

Verify by reading. Identical signals do not prove identical coverage — two tests can call the same function with inputs that take different branches, which is exactly what good boundary tests do. Read the inputs and the expected values. This is a candidate only when the inputs differ in a way the code does not distinguish.

6. slow-without-reason

Definition. A test consumes disproportionate wall-clock time without exercising anything that justifies it — sleeping, hitting a real service, or building far more than it needs.

Signals.

  • The test appears in suite.slowest_tests[] while its test_functions[] record shows a low assertion_count and short called_names.
  • A slowest_tests[] entry whose seconds is an order of magnitude above the median of that array.
  • High patch_decorator_count and slow: the test mocks heavily yet still takes real time, so the time is going somewhere the mocks do not cover.

Joining rule — read this before using these signals. slowest_tests[].nodeid is parametrize-expanded and test_functions[].nodeid is not. To join, strip a trailing [...] suffix from the slowest_tests nodeid and match the remainder against test_functions[].nodeid. This is best-effort: several parametrized cases collapse onto one test record, and a nodeid containing a literal [ in a parameter value can strip incorrectly. Treat an unmatched entry as unjoinable and say so in the report rather than guessing.

Precondition. tool.ran_pytest must be true. When it is false, slowest_tests is empty and this entire pattern is unavailable — state that in your report rather than omitting the pattern silently.

Verify by reading. Some tests are legitimately slow: they are integration tests, or the scenario needs volume. Confirm the time is accidental before reporting.

7. wrong-layer

Definition. The test verifies behaviour at a level that cannot see it, or duplicates a check that belongs elsewhere — a unit test asserting on end-to-end wiring, or an integration test re-checking a pure function’s arithmetic.

Signals.

  • called_names spans several distinct top-level modules while the test lives in a file named for one of them.
  • High patch_decorator_count and a long called_names list at once: the test reaches broadly and then stubs out most of what it reached.
  • A test in a file whose files[].fixture_count is high while its own called_names names a single pure function — heavy machinery around a narrow check.
  • The test’s file path and the module prefix of its called_names entries disagree.

Verify by reading. The inventory has no model of your architecture. It does not know which directories are unit tests and which are integration tests, and it cannot tell a layering violation from a deliberate seam. This pattern is always a judgement call — treat every signal here as weak.

8. dead-test

Definition. The test cannot fail for the reason it exists. It has no assertions, or it exercises no project code, so it survives on the absence of an exception.

Signals.

  • assertion_count == 0, external_verification_count == 0 and helper_assertion_count == 0. Definitive for the assertionless variant. Note this contributes 0.20 to the score on its own and inflates setup_to_assertion_ratio to the full body height, so these tests cluster near the top of top_suspicious.test_functions.
  • The same three zeros and called_names empty: the test neither asserts nor calls project code.
  • The test’s nodeid appears in no sut_calls.by_name[].test_nodeids list and external_verification_count == 0 — a test that shells out calls no project code by construction, so this signal fires on it by default.

Not this pattern: verification in a child process. A test with assertion_count == 0 and external_verification_count > 0 asserts in a process the AST cannot see and propagates the failure — subprocess.run(..., check=True) raises CalledProcessError, which fails the parent test. This is how a packaging or CLI integration test checks something the source-tree interpreter cannot: it installs a wheel into a temporary directory, then runs an isolated interpreter that asserts on the installed artifact. Those tests are correct as written; do not report them as assertionless, and do not ask for a local assertion that would have to duplicate the child’s.

The evidence is narrow on purpose. check=True proves the child’s failure reaches the parent — nothing more. If the child command asserts nothing (a bare --help, a true), the test is still dead, and only reading it tells you which you have. A subprocess call with no check=True proves nothing at all and does not set this field: it needs its own evidence, such as an assert completed.returncode == 0, which is a normal assertion and counts as one.

Not this pattern: verification through a helper. A test with assertion_count == 0 and helper_assertion_count > 0 verifies through a call that raises on failure — a pandas.testing.assert_frame_equal, a pytest.warns block, or a same-file check_* helper that asserts. Do not report it as assertionless.

Verify by reading. Three legitimate shapes still look identical here. A smoke test that asserts nothing but would raise on failure is doing real work — importing a module, constructing an object, running a migration. A test whose assertions live in a helper pycoati cannot see — imported from another module, defined in conftest.py, or reached through a second helper — shows all three counts at zero, because helpers are followed one level deep within the file only. And a test that verifies in a child process the parser could not prove, as above. Check for all three before reporting.

There is no per-test coverage in this schema, so “this test covers nothing” is not something the inventory can tell you. Do not claim it.


What to produce

For each confirmed candidate, record: nodeid, file, line, the pattern, the specific field values that flagged it, and one sentence on what you found when you read the test. Also record tool.version, tool.ran_pytest, and tool.ran_coverage — they determine which patterns were available to you.

Do not edit anything yet.

next: run pycoati guide remediate

pycoati — remediate

You have a list of confirmed candidates from the analyze page. This page tells you what to do with them and in what order.

The approval gate

Produce the full findings report, present it, and edit no file until a human approves it.

This is the first rule on the page because it is the one that matters. Not a draft edit, not a “small obvious one first”, not a branch you plan to show later. Zero file modifications exist between finishing analysis and receiving approval.

The report must contain, for every finding:

  • nodeid, file, and line.
  • The anti-pattern, and the specific field values that flagged it.
  • What you found when you read the test.
  • The rung of the ladder it lands on, and the concrete action that implies.
  • Anything that made you uncertain.
  • The mutation check result for its test, when one ran (see below).

Group findings by rung, and put the escalation rung’s findings first — those are the ones a human has to decide, and they should not be at the bottom of a long list.

Also state which patterns were unavailable. If tool.ran_pytest was false, slow-without-reason was never checked, and the report must say so rather than implying a clean result.

Mutation check — evidence for the report

A signal says a test looks like it checks nothing. A small mutation run shows whether it does: change the code the test calls, run only that test, and see if it notices. Do this before you present the report, for the top of the shortlist only. Never run the whole suite’s mutation run — that takes hours; this takes minutes.

Skip the check, and say so in the report, when tool.ran_pytest was false or the project’s tests cannot run. A mutation run needs a passing baseline.

Pick the tests

  1. Take confirmed candidates from top_suspicious.test_functions, top down, at most five.
  2. Drop any whose called_names is empty — there is no project code to mutate, and the finding stands on the inventory alone.
  3. Drop any with a current entry in .pycoati-mutation.toml (see below). Quote that entry’s result in the report instead.

Run it

Use mutmut 3. It can be limited to single functions and to a single test, which is what keeps the run small.

mutmut reads its settings only from pyproject.toml or setup.cfg, and writes a mutants/ folder. Neither may touch the working tree before approval, so run it in a throwaway copy:

git worktree add --detach ../coati-mutation HEAD
cd ../coati-mutation

If the test or the code it calls has uncommitted changes, the copy does not have them — check the committed version or skip the test.

In the copy, add to pyproject.toml, one test at a time:

[tool.mutmut]
source_paths = ["src"]                 # where the project's code lives
pytest_add_cli_args_test_selection = ["tests/test_repo.py::test_save"]

Then run only the mutants of the functions that test calls. Each called_names entry maps to a mutant-name pattern:

  • myproj.repo.save → myproj.repo.x_<function>__mutmut_*, here myproj.repo.x_save__mutmut_*.
  • myproj.repo.Repository.save → myproj.repo.xǁRepositoryǁsave__mutmut_*.
  • A class called as a constructor, myproj.repo.Repository → myproj.repo.xǁRepositoryǁ__init____mutmut_*.

The module part is the path under source_paths, so src/myproj/repo.py with source_paths = ["src"] gives myproj.repo.

uv run --with mutmut mutmut run "myproj.repo.x_save__mutmut_*" "myproj.repo.xǁRepositoryǁsave__mutmut_*"
uv run --with mutmut mutmut results --all true

Run it in the project’s own environment, so the tests can import the project. mutmut results --all true lists every mutant name generated, also after a run whose pattern matched nothing, so use it to fix a pattern. When done, leave the copy and remove it: git worktree remove --force ../coati-mutation.

Read the result

Each mutant ends as one of:

  • killed — the test failed on the changed code. It checks that code.
  • survived — the test passed on changed code. This is the evidence. A test that lets mutants of the code it calls survive is not checking that code. mutmut show <name> prints the diff; put one or two in the report.
  • no tests — the test never reached the function. Its called_names entry is a call pycoati saw but the test does not execute (it was patched out, or sits on a branch never taken). That is evidence too, often of mock-as-assertion.

A survivor is a lead, like any signal. Some mutants change nothing a caller can see (an equivalent mutant). Read the diff before you count it.

The check never changes a rung on its own. It confirms or weakens a finding you already have. A test that killed every mutant is weaker as a candidate — say so, and look again at why it was flagged.

Remember what was checked

Results go in .pycoati-mutation.toml at the project root, one entry per checked test, so a later run checks only new or changed tests:

[[check]]
test = "tests/test_repo.py::test_save"
fingerprint = "<test_functions[].fingerprint at check time>"
targets = ["myproj.repo.Repository.save"]
source_files = ["src/myproj/repo.py"]
commit = "<git rev-parse HEAD of the copy>"
killed = 3
survived = 4
no_tests = 0
date = "2026-10-28"
tool = "mutmut 3.8.1"

An entry is current only when both hold:

  • its fingerprint equals the test’s fingerprint in today’s inventory, so the test was not edited; and
  • git diff --quiet <commit> -- <source_files> exits 0, so the code it calls was not edited either.

Otherwise check the test again and replace the entry. Delete entries whose test no longer exists.

This file is a measurement log, not a review decision, so you write it — unlike .pycoati-accept.toml. But writing it is still a file change: put the new entries in the report and write them as the first step after approval.

The record is for the next agent run only: pycoati never reads this file, and the tool stays stateless.

The remedy ladder

Take the first rung that applies to a finding. Do not skip ahead. A finding that matches rungs 1 and 4 is a rung 1 finding.

Rung 0 — already accepted → skip it. A finding covered by accepted.findings has been reviewed and signed off. Quote the reason in your report and take no action. This rung exists so the ladder never walks over a recorded decision. It applies only to the exact (test, signal) pair listed, and never to an entry under accepted.stale — a lapsed acceptance is an ordinary finding again, and a content_changed one means the test was edited since review.

Rung 1 — dead-test → delete. A test with no assertions that calls no project code protects nothing. Delete it. Before deleting, confirm once more that it is not a smoke test whose value is that it does not raise, that its assertions are not made through a helper function, and that it does not verify in a child process (external_verification_count > 0 — a failing child fails the test through CalledProcessError). If any is true, it is not a rung 1 finding — drop it from the ladder entirely.

Rung 2 — tautology → fix the assertion, or delete. Prefer fixing: replace the self-referential assertion with one about a value the system under test produced. If no such value exists — the test calls nothing that can be asserted on — delete it. Do not “fix” a tautology by adding an assertion about a mock; that trades this finding for a rung 4 finding.

Rung 3 — redundant → parametrize, or delete. When several tests differ only in input values, collapse them into one parametrized test carrying every case. When the extra tests add no case at all, delete them and keep one. Preserve every distinct input that reaches a distinct branch — collapsing cases that actually differ is a coverage loss, not a cleanup.

Rung 4 — mock-as-assertion → rewrite against observable behaviour. Replace assertions about the double with assertions about what the code produced: the return value, the state it changed, the output it wrote. Keep an interaction assertion only when the interaction is the contract — a retry count, a call that must not happen. If the behaviour genuinely has no observable outcome, that is a design problem, not a test problem: escalate at rung 6 instead.

Rung 5 — slow-without-reason → remove the cost, or escalate. When the cost is accidental — a real sleep, an unnecessarily large fixture, a call that should have been stubbed at a boundary — remove it and keep the assertions identical. When the time is inherent to what the test covers, do not touch it; escalate at rung 6 so a human can decide whether the test belongs in this suite at all.

Rung 6 — implementation coupling, setup-heavy, wrong-layer → stop and escalate to a human. These three are design judgements. Fixing implementation coupling means changing what the code exposes as a seam. Fixing setup-heavy means deciding what the scenario really is. Fixing wrong-layer means knowing the architecture. None of these can be settled from the inventory, and a mechanical fix makes the suite worse while making the score better.

Do not edit these. For each, report: file, test name, line, the signals that flagged it, what you found reading the test, and the specific decision you need from a human. Then move on to the next finding.

This rung is where a large share of real findings land. That is the correct outcome, not a failure to finish.

Rung 7 — correct as written, for a reason only the project knows → propose an accept entry. Some tests trip a signal and are right anyway, in a way no amount of static analysis will ever see: assertions made in a child interpreter, a smoke contract whose value is that it does not raise, assertions made through a helper. When you have read the test and concluded that, the finding is not a code change — it is a review decision to record.

Put the proposed entry in your report, for a human to add to .pycoati-accept.toml:

[[accept]]
test = "<nodeid>"
signals = ["<the signals you confirmed>"]
reason = "<what you found when you read the test>"
fingerprint = "<test_functions[].fingerprint>"

Do not write this file yourself. It records someone’s judgement, and signing it on their behalf is exactly the thing the approval gate exists to prevent. Name only the signals you actually confirmed; a test you accept for zero_asserts must still surface tomorrow if it grows a mock_overuse hit.

After approval — the edit loop

Approval covers the report that was approved. Work one finding at a time, in ladder order.

For each finding:

  1. Run the affected tests before touching anything. Record the result. If they already fail, stop — you cannot verify a change against a broken baseline. Report it and move to the next finding.
  2. Make the change for this one finding.
  3. Run the same tests again. They must pass.
  4. Re-scan: pycoati . --output inventory.json.
  5. Confirm two things in the new inventory: the finding is gone, and no new finding appeared. A rising suspicion_score anywhere you did not touch, or a new smell_hits entry, counts as a new finding.
  6. On any failure at step 3 or step 5, revert this finding’s change and record what happened. Do not attempt a second approach without reporting the first one failed.

Deleting a test always reduces coverage. Before a rung 1 or rung 2 deletion, check whether the behaviour is covered elsewhere. If it is not, the finding becomes a rung 6 escalation: the test is bad and the behaviour is untested, which is a decision for a human.

Do not

  • Do not raise a threshold or edit configuration to make a finding disappear. pycoati’s thresholds are compiled into the binary and are deliberately not configurable per run. --top-suspicious changes list length only — shortening the list does not resolve anything, and using it to trim a report is falsifying the report.
  • Do not write or edit .pycoati-accept.toml. Propose entries in the report (rung 7) and let a human add them. Adding an acceptance to make a finding go away, widening an existing entry to cover a new signal, or re-pinning a content_changed entry’s fingerprint without reading the test are all the same move as raising a threshold, dressed as a review.
  • Do not delete or skip a test to make a gate pass. Adding a skip marker, an expected-failure marker, or a narrowing condition to silence a failing test is out of scope for every rung on this ladder.
  • Do not weaken an assertion to make a test pass after your edit. If your rewrite makes the test fail, the rewrite is wrong. Revert.
  • Do not batch edits across findings before the report is approved, and do not batch them after approval either — one finding, one verification cycle. A batch you cannot revert individually is a batch you cannot verify.
  • Do not edit production code to satisfy a test finding. Every rung on this ladder changes tests. A finding that can only be fixed by changing the system under test is a rung 6 escalation.
  • Do not report a score improvement as the outcome. The score is a ranking device. Report what changed about the tests.

Finishing

Report, in this order: findings resolved and how, findings escalated and what decision each needs, accept entries proposed and for which signals, findings reverted and why, the tests mutation-checked and the entries written to .pycoati-mutation.toml, and the before/after of top_suspicious.test_functions. State plainly if any finding was left untouched.

Also list every accepted.stale[] entry, with what you did about it: worked the finding, or proposed deleting a dead entry. A stale list that grows every scan is a baseline nobody is reading.

next: run pycoati . --output inventory.json and pycoati guide analyze to confirm the result

pycoati — plan

pycoati plan answers one question about a monorepo: given the subprojects you want to test, how many pytest processes are worth running side by side, and which subprojects go in which one. It runs no tests, edits nothing, and is separate from the audit workflow on the other pages.

You are here to produce a run plan and execute it. Read recommended, start one worker per lane, run each lane’s commands in order.

The model

  • Every subproject is one pytest invocation with one cost: its runtime plus a fixed start-up allowance for the process itself.
  • A lane is one parallel slot. The subprojects in a lane run one after another, so a lane costs the sum of its subprojects.
  • The plan’s wall cost is its most expensive lane. That is how long the whole thing takes when every lane starts together.
  • For each lane count from 1 to --max-jobs, pycoati packs the subprojects to minimise the wall cost. The recommendation is the smallest lane count whose wall cost is within --tolerance percent of the best one found. A lane that buys nothing is never recommended.

Subprojects are never merged into one pytest process. Two subprojects’ conftest.py files, rootdirs and same-named test modules routinely clash in a single process, so each keeps its own invocation whatever lane it lands in.

Run it

Costs are only as good as their source, so measure first. The audit already records each member’s suite runtime; --no-coverage keeps that scan to two pytest passes per member:

pycoati . --no-coverage --output inventory.json
pycoati plan . --timings inventory.json --output plan.json

Plan only the subprojects you are about to run by naming them after the root:

pycoati plan . api core --timings inventory.json

Without --timings the plan still works, balancing on test counts:

pycoati plan . --format pretty

Which subprojects

  • uv workspace ([tool.uv.workspace] in the root pyproject.toml): with no names, every member. A name matches a member by its path relative to the root (packages/api), else by directory name or [project].name (api). A name that matches nothing, or more than one member, is an error that lists the member paths.
  • Any other monorepo: name the subproject directories relative to the root (pycoati plan . services/api libs/core). With none named the command fails — pycoati does not guess where the subprojects are.

Each subproject’s tests are found as in the audit: every testpaths entry of its own pyproject.toml, else <subproject>/tests.

Where costs come from

  • measured — suite.runtime_seconds for that subproject in a --timings inventory. Matched by project path, else by [project].name when exactly one entry carries it, so an inventory produced in CI works locally. When several --timings files measure the same project, the last one wins.
  • estimated — the subproject has no measured runtime, but others do: its test count times the measured seconds-per-test rate. A rough figure; re-measure when it matters.
  • test_count — nothing usable was measured. Every cost in the plan is a test count, and cost_unit is tests. Seconds and counts are never mixed.

Every seconds cost then gets --startup-seconds added. pytest’s own runtime figure starts counting after the interpreter, pytest and its plugins have loaded, so a suite it reports as 0.02s still occupies a lane for most of a second. In a monorepo of many small suites that start-up is the bulk of the work, and leaving it out would make every plan look like “one lane is enough”. A test_count plan carries no allowance.

Test counts come from the timings inventory’s suite.test_count when it is above zero, else from static analysis, which counts a parametrised test once.

A plan in tests units still balances the lanes, but treats every test as equally slow. Do not report its wall_cost as a time. Every scheduled subproject costs at least 1 in such a plan.

Flags

  • --max-jobs <N> — upper bound on lanes. Default: the CPUs available to the process. Set it to what the machine or CI runner pool can really give you; more lanes than subprojects are never used.
  • --tolerance <PCT> — how much slower than the fastest plan is acceptable in exchange for fewer lanes. Default: 10. 0 insists on the fastest wall cost (still with the fewest lanes that reach it).
  • --startup-seconds <SECS> — added to every subproject’s cost when costs are in seconds. Default: 0.5. Raise it when each run pays for something heavier before the first test — uv run resolving an environment, a container start, a database fixture; set 0 to plan on runtimes alone.
  • --timings <FILE> — inventory to read measured runtimes from. Repeatable; accepts a workspace inventory or a single-project one.
  • --member-cwd <root|member> — where the emitted commands run from. root addresses each subproject’s tests from the monorepo root; member runs from inside the subproject so its own pytest configuration and conftest.py apply. Default: root. Use the value your suite already passes with.
  • --pytest-cmd <CMD> — prefix of the emitted commands; test paths are appended. Default: python -m pytest. For a uv workspace, --pytest-cmd "uv run pytest" is typical.
  • --format <json|pretty> — json is the plan payload described below; pretty is a terminal view. Default: json.
  • --output <PATH> / -o — write to a file instead of stdout.

Plan fields

  • schema_version — "1". Versioned separately from the inventory.
  • root — absolute path of the monorepo root. Every path and cwd below is relative to it.
  • cost_unit — seconds or tests: the unit of every cost, serial_cost and wall_cost in this plan.
  • max_jobs — the lane cap the plan was computed under.
  • tolerance_pct — the tolerance the recommendation was chosen with.
  • startup_seconds — the allowance included in every cost, or null in a tests plan, where none applies.
  • members — the subprojects that will run, in the order asked for.
  • name — the subproject’s [project].name, else its directory name.
  • path — the subproject’s directory, /-separated; . for the root.
  • test_count — collected count from the timings inventory, else the static count.
  • runtime_seconds — the measured runtime as pytest reported it, without the start-up allowance, or null when not measured.
  • cost — what the packing used for this subproject, lane, or run. In a seconds plan a subproject’s cost is its runtime (measured or estimated) plus startup_seconds.
  • cost_source — measured, estimated or test_count. See above.
  • skipped — selected subprojects with nothing to run. They appear in no lane.
  • reason — why: no tests directory or no tests.
  • serial_cost — the sum of all member costs: one lane, no parallelism.
  • bottleneck — the most expensive member. No lane count finishes sooner than it.
  • member — a subproject’s name, in bottleneck and in each run.
  • limits_wall_time — true when the recommended plan is already down to the bottleneck’s own cost. Adding lanes cannot help any further; only making that subproject faster can — for example running it under pytest-xdist (-n), or splitting it into two subprojects.
  • options — one entry per lane count from 1 to max_jobs (never more than there are members): the trade-off the recommendation was picked from.
  • jobs — number of lanes, i.e. pytest processes running at once.
  • wall_cost — cost of the most expensive lane at that lane count.
  • speedup — serial_cost / wall_cost.
  • recommended — the chosen option, plus its lanes.
  • lanes — what to run, most expensive lane first.
  • lane — 1-based lane number.
  • runs — the lane’s pytest invocations. Run them in order, one at a time; start the next only when the previous exits.
  • cwd — directory to run the command from, relative to root.
  • command — the command line: --pytest-cmd followed by the test paths. A path containing a space or another shell-special character is single-quoted for a POSIX shell; path and cwd are always raw.

Executing a plan

  • Start recommended.jobs workers at once, one per lane. In CI that is a job matrix over recommended.lanes; locally, one shell per lane.
  • Within a lane, run every command from its cwd even if an earlier one failed, and fail the lane if any did. Stopping at the first failure hides the results of the subprojects behind it.
  • Add your own pytest flags through --pytest-cmd, not by editing commands afterwards, so the plan stays the record of what ran.
  • If bottleneck.limits_wall_time is true and the wall cost is still too high, more lanes are the wrong lever. Speed up that one subproject.
  • If options shows the wall cost barely moving between lane counts, the recommendation already took the smaller one. Raise --tolerance to trade more time for fewer workers, lower it for the reverse.

What a plan cannot tell you

  • Costs are sequential runtimes measured on one machine. Lanes that compete for the same CPUs, database or ports will run slower than the plan says. --max-jobs is where you account for that.
  • It assumes subprojects are independent. Two suites that share a fixed port, a temp path or a database schema must not be in different lanes at the same time; the plan does not know about them.
  • Timings go stale. Regenerate inventory.json when suites change shape.

next: run pycoati plan . --timings inventory.json --output plan.json