Skip to content

Each directory conftest claims the ambient conftest slot for its own subtree (#305) - #406

Merged
brettheap merged 3 commits into
mainfrom
fix/conftest-slot-order-independence
Aug 27, 2026
Merged

brettheap merged 3 commits into
mainfrom
fix/conftest-slot-order-independence

Conversation

@brettheap

@brettheap brettheap commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

The mechanism, proved rather than assumed

conftest is an ambient top-level module name with exactly one sys.modules
entry
. tests/doc-health/, tests/ideation-dashboard/ and
tests/avatar_runtime/ each carry a rootless conftest.py (no __init__.py),
and ~133 modules across the first two do from conftest import AS_OF, FIXTURES, FakeGit, REPO_ROOT, … at import.

Read out of pytest 9.1.1's own source:

step where
_importconftest deletes sys.modules["conftest"] before importing each rootless conftest, so the last one loaded owns the slot _pytest/config/__init__.py:733, :753 (guarded by resolve_package_path(conftestpath) is None)
_set_initial_conftests loads every path ARGUMENT's conftest before collection begins _pytest/config/__init__.py:615-667
pytest_collectstart is dispatched through the node's ihook, immediately before collect() — which for a Module is where the test module is imported _pytest/runner.py:587-588
pytest_runtest_setup is dispatched through the item's ihook _pytest/runner.py:239-241
Node.ihook → Session.gethookproxy(path) → FSHookProxy with remove_plugins = _conftest_plugins − _getconftestmodules(path), i.e. conftest hooks are path-scoped _pytest/nodes.py:227-230, _pytest/main.py:731-745

So with several arguments the last argument's conftest is what the first
argument's modules import from, and a hook installed by
tests/doc-health/conftest.py cannot fire for an ideation-dashboard node.
Hypothesis confirmed at every step.

Scratch-tree RED/GREEN (two rootless dirs a/, b/, each exporting only its own name)

RED   pytest a b  →  ImportError: cannot import name 'A_ONLY' from 'conftest' (…/b/conftest.py)
RED   pytest b a  →  ImportError: cannot import name 'B_ONLY' from 'conftest' (…/a/conftest.py)
RED   pytest .    →  1 failed, 1 passed   (module-level imports fine; the RUN-TIME
                                           `from conftest import …` inside the body reads b's)
GREEN (helper installed) pytest a b / pytest b a / pytest . / pytest a  →  all pass

The single-argument RED is the quieter half of the same defect and is why the
repair needs two hooks, not one.

The repair

claim_conftest_slot(globals()) in tests/hermeticity.py — a closure factory
that installs two path-scoped hooks into the calling conftest's namespace:

module = sys.modules["conftest"]          # captured while THIS conftest is the occupant
def pytest_collectstart(collector): sys.modules["conftest"] = module
def pytest_runtest_setup(item):     sys.modules["conftest"] = module

Called from the bottom of all three directory conftests. pytest.ini is
untouched as configuration — it gains comment lines only and stays option-free
(PR #49 finding 17, FR-043). No import site was rewritten and no conftest.py was
added.

Design choices

  • Where — tests/hermeticity.py, beside CONFTEST_HOOKUPS. Every directory
    conftest already imports that module to register the FR-043 guard, so opting in
    costs one added name in an existing import plus one call; and the flat-slot
    hazard is already documented there, so the repair now sits next to it. (A new
    tests/conftest_slot.py would need its own hookup pin to stay honest, and
    tests/hermeticity.py must stay importable without pytest — the helper is,
    it touches only sys.)
  • Name — claim_conftest_slot. "Claim", not "restore" or "fix": the slot has
    a legitimate single occupant at any moment and each subtree asserts ownership
    of it for its own nodes.
  • Opt-in shape — claim_conftest_slot(globals()). A re-exported hook pair
    cannot work: one shared function object cannot know which module to install, so
    the hooks have to be closures the calling conftest owns. Passing globals() is
    the shortest way to hand over both the module identity (__name__) and the
    namespace the hooks must land in. It raises RuntimeError if __name__ is not
    the flat conftest, because claiming from a package-qualified conftest would
    install the wrong module for everyone, silently.
  • tests/avatar_runtime/ claims even though no test there imports from
    conftest.
    An unclaiming directory still poisons its siblings when it is
    the last argument — it was avatar_runtime's conftest sitting in the slot that
    produced the 27 doc-health collection errors in the measurement below — and the
    invariant "every rootless directory conftest owns the slot for its own subtree"
    is worth more than a per-directory judgement call. Explained in a comment there.
  • tests/conftest.py must NOT claim, and that is load-bearing. pluggy calls
    hook implementations in LIFO registration order and the suite-wide conftest
    registers first, so its claim would run last and clobber every directory's.
    Measured on the scratch tree: adding the call to the root conftest turns
    pytest a b straight back into two collection errors. Pinned by a test.
  • tests/hermes_runtime_contracts/ needs nothing. Its directories carry
    __init__.py, so resolve_package_path is non-None and pytest never clears the
    flat slot for them; probed live — they import as
    hermes_runtime_contracts.conftest and hermes_runtime_contracts.postgres.conftest.
    Pinned too (the exemption asserts the __init__.py).

Before / after (--collect-only -q, this worktree)

invocation before after
tests/doc-health tests/avatar_runtime 184 collected, 27 errors 993 collected, clean
tests/avatar_runtime tests/doc-health 993 collected, clean 993 collected, clean
tests/doc-health tests/ideation-dashboard 4827 collected, 19 errors 5475 collected, clean
tests/ideation-dashboard tests/doc-health 3948 collected, 47 errors 5475 collected, clean
tests/doc-health tests/avatar_runtime tests/ideation-dashboard 4924 collected, 19 errors 5572 collected, clean
tests/ 6972 collected, clean 6976 collected, clean (+4 new tests)

(The issue quoted 23 errors / 182 collected for the first row; the tree has grown
since. The shape is identical.)

The pin, written RED first

tests/ideation-dashboard/test_hermeticity.py (it already drives subprocess
probes with cwd set, and it is where the conftest set is pinned):

  1. test_a_directory_conftest_owns_the_ambient_slot_for_its_own_subtree — builds
    the two-rootless-directory tree in tmp_path (each conftest imports the
    shipped claim_conftest_slot, so mutating the helper reds this), runs
    pytest a b, pytest b a and pytest . as subprocesses, asserts 4 passed
    each time.
  2. test_without_the_claim_the_same_tree_reproduces_the_slot_collision — the
    negative control: the identical tree with the claim removed must fail with
    cannot import name 'A_ONLY' from 'conftest' naming the other directory's
    conftest, and the single-argument run must show 1 failed, 3 passed. This is
    what makes the pin prove the mechanism rather than an outcome.
  3. test_every_flat_conftest_claims_the_slot_and_the_suite_wide_one_does_not —
    every entry in CONFTEST_HOOKUPS except conftest.py carries
    claim_conftest_slot(globals()); tests/conftest.py carries none; every
    CONFTEST_EXEMPT_HOOKUPS directory has an __init__.py.
  4. test_the_claim_refuses_a_conftest_that_pytest_imports_under_a_package_name —
    the precondition, checked because the failure it prevents is silent.

RED output before the helper existed:

>           assert proc.returncode == 0, f"{args}: {proc.stdout}{proc.stderr}"
E           AssertionError: ('a', 'b'): ImportError while loading conftest '/tmp/.../a/conftest.py'.
E             a/conftest.py:5: in <module>
E                 from hermeticity import claim_conftest_slot
E             E   ImportError: cannot import name 'claim_conftest_slot' from 'hermeticity'
...
FAILED …::test_a_directory_conftest_owns_the_ambient_slot_for_its_own_subtree
FAILED …::test_every_flat_conftest_claims_the_slot_and_the_suite_wide_one_does_not
2 failed, 1 passed, 24 deselected in 2.54s

(the negative control passes RED and GREEN alike, by construction).
The four tests add ~3.5 s.

Mutation round — both mutants died

mutant result
drop pytest_collectstart from the helper killed — ('a','b'): ImportError: cannot import name 'A_ONLY' from 'conftest' (…/b/conftest.py), 2 collection errors
drop pytest_runtest_setup from the helper killed — collection is clean but a/test_a.py::test_a_runtime_import_sees_its_own_conftest fails: 1 failed, 3 passed

That second mutant is the reason the run-time leg is in the pin at all: nothing
in the current suite would have caught it. Seven tests do from conftest import … inside a test body (tests/doc-health/test_family_enumeration.py:159/171/204,
tests/ideation-dashboard/test_gate_console.py:2243,
test_session_notebook.py:1071, test_doxbench_knowledge_service.py:126,
test_doxbench_thread_wiring.py:948). Under a plain pytest tests/ those read
the last-collected directory's conftest today; it is harmless only because the
name they mostly read (REPO_ROOT) is defined identically in both. This hook stops
that being luck. It is the same class of defect as finding 19a, which was fixed
one call site at a time
(test_the_scratch_harness_does_not_depend_on_the_ambient_conftest_name).

Verification

invocation result
pytest tests/ideation-dashboard/test_hermeticity.py -q 28 passed (was 24)
pytest tests/doc-health -q 896 passed
pytest tests/ideation-dashboard -q 4563 passed, 16 skipped (12m40s)
pytest tests/doc-health tests/avatar_runtime tests/ideation-dashboard -q 5556 passed, 16 skipped, 0 errors (12m49s) — the shape that used to abort with 19 collection errors
the four new tests ~3.1 s of call time

5556 + 16 = 5572, i.e. every test the three-directory invocation now collects
also runs. Neither known-local failure reproduced (the doc-health
bootstrap-cluster drift test passed; the hermes release-inventory merge-base test
is outside these directories). CI on this PR: pytest-suite pass,
wallet-validation pass.

Prose

  • tests/hermeticity.py CONFTEST_HOOKUPS block — a new closing paragraph: the
    hijack has a repair, adding a conftest.py is still not free, tests/conftest.py
    is the one entry that must not claim.
  • pytest.ini — a new closing paragraph: the per-directory-conftest paragraph
    still holds for a conftest that does nothing about the slot; the four that exist
    claim it; a new one is still the wrong answer to a rootdir problem.
  • .github/workflows/pytest-suite.yml "SCOPE" comment — reworded: the
    two-directory shape is no longer order-dependent and is pinned by the new test;
    --import-mode=importlib was never available (option-free pytest.ini) and
    would break every from conftest import … site besides. No run: step
    changed.
  • tests/ideation-dashboard/test_hermeticity.py — a new closing paragraph on
    test_every_conftest_under_tests_registers_the_guard's docstring.

Review round (second commit, 5782e367)

origin/main merged in (ef791639, #403) — no conflicts. Five findings closed.

The three deferred prose edits are applied on top of #403's wording; its
validate-docs.sh sentences are byte-identical (git diff | grep validate-docs
is empty). The hazard now reads as what an unclaiming conftest does.

NIT-1 — the refusal could abort a run. The precondition keyed on
namespace["__name__"] != "conftest". Measured: under --import-mode=importlib
a ROOTLESS conftest gets __name__ == "a.conftest" — so the guard would have
raised inside conftest collection, aborting the whole run at rc=4 with the
FR-043 guard never registered, and misnaming the cause; base main merely
collected with errors. It now keys on the conftest directory's missing
__init__.py, which is the actual condition for contending for the flat slot.
A real package still raises. test_the_claim_does_not_abort_a_run_under_a_non_prepend_import_mode
runs the scratch tree under both --import-mode=importlib and
-o consider_namespace_packages=true and requires rc=0 with no refusal in the
output (both pass — the claim in fact still works under importlib, which the
docstring is careful not to claim as pinned).

NIT-2 — hook collision was silent. claim_conftest_slot now returns the hook
pair and refuses if either name is already bound, telling the caller to invoke the
returned function from inside its own implementation (worked example in the
docstring). The define-it-afterwards direction, which no runtime check can see,
is pinned by source against a new HOOKS_INSTALLED_BY_THE_CLAIM tuple —
demonstrated: appending def pytest_collectstart to tests/avatar_runtime/conftest.py
reds the pin.

The real worry — the shipped claim was pinned only by a text grep.
test_the_real_two_directory_invocation_collects_the_same_in_either_order now
runs the real pytest --co -q over two directory PAIRS, both orders each, and
requires the orders to agree. 11.06 s, four child collections (budget was
~15 s, so both orders and both pairs stay). Mutation:

claim removed from behavioural pin
tests/doc-health/conftest.py red (2.1 s)
tests/ideation-dashboard/conftest.py red (8.3 s) — this is why there are two pairs; one pair leaves this claim unobserved
tests/avatar_runtime/conftest.py green — not observable, nothing there imports through conftest. Stated plainly in the docstring; covered by the source pin only.

NIT-3 — numerals. "the seven directories that have none" was wrong. Measured
2026-08-27: 18 test-bearing directories under tests/, 13 with no
conftest of their own, 10 of those rootless (3 are packages). The measuring
command sits in pytest.ini beside the number, and the pre-existing
pytest.ini:11 "Seven of the nine" is corrected the same way. The 184/27/993
counts are now labelled measured at f9457d6 and explained as pinning the
DIFFERENCE between two orders — the behavioural test re-measures that on the live
tree instead.

Post-merge verification

invocation result
pytest tests/ideation-dashboard/test_hermeticity.py -q 31 passed (24 before this PR)
pytest tests/doc-health tests/avatar_runtime -q 1017 passed — the shape that aborted with 27 collection errors at base, now run to completion
--co both orders, doc-health/avatar_runtime 1017 = 1017
--co both orders, ideation-dashboard/doc-health 5543 = 5543
--co tests/ 7041

Closes #305

🤖 Generated with Claude Code

…n subtree

`conftest` is an ambient top-level module name with exactly one `sys.modules`
entry, and `_importconftest` deletes that entry before importing each rootless
conftest.py (`_pytest/config/__init__.py:753`). `_set_initial_conftests` loads
EVERY path argument's conftest before collection begins (`:615`), so with two
directory arguments the last one loaded owned the slot and the first argument's
~133 `from conftest import AS_OF, FakeGit, ...` sites read the wrong module:
`pytest tests/doc-health tests/avatar_runtime --collect-only` gave 184 collected
with 27 collection errors, the same two arguments swapped gave 993 clean.

`claim_conftest_slot(globals())` (tests/hermeticity.py, beside CONFTEST_HOOKUPS
because every directory conftest already imports that module) installs two hooks
into the calling conftest's namespace, both dispatched through the node's
path-scoped `ihook` (`_pytest/main.py:731`) so a directory's copy can never fire
for a sibling: `pytest_collectstart`, immediately before a Module imports
(`_pytest/runner.py:588`), and `pytest_runtest_setup`, before each test body
(`:241`) — the leg the seven run-time `from conftest import ...` sites need, and
which nothing in the suite covered before. All three rootless directory
conftests call it. `tests/conftest.py` must NOT: pluggy's LIFO hook order would
make its claim the last to run and clobber every directory's.

pytest.ini stays option-free (PR #49 finding 17, FR-043); no import site was
rewritten and no conftest.py added. After: every order collects 993 / 5475 /
5572 clean, `pytest tests/` 6976.

Pinned by four new tests in tests/ideation-dashboard/test_hermeticity.py,
written RED first, including a negative control that reproduces the collision in
a scratch tree without the claim. Both hook-deletion mutants die.

Closes #305

Co-Authored-By: Claude Opus 5 <[email protected]>
Copilot AI lite review requested due to automatic review settings August 27, 2026 03:24

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @brettheap! 👋

Your private repo does not have access to Sourcery.

Please upgrade to continue using Sourcery ✨

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes pytest’s rootless conftest.py “ambient module name” collision across multiple test subtrees (e.g., tests/doc-health/, tests/ideation-dashboard/, tests/avatar_runtime/) by introducing an opt-in helper that re-claims sys.modules["conftest"] for the currently-active subtree at both collection time and test setup time, making multi-directory invocations order-independent. It also adds a regression/negative-control pin that reproduces the failure mode in a scratch tree and verifies the shipped hookup set.

Changes:

  • Add claim_conftest_slot(globals()) helper in tests/hermeticity.py that installs two path-scoped hooks to reassert the correct ambient conftest module for a subtree.
  • Invoke the helper from each rootless directory conftest (doc-health, ideation-dashboard, avatar_runtime), and add a scratch-tree regression test + negative control that proves the mechanism.
  • Update comments/docs in pytest.ini and the pytest-suite workflow to reflect the repaired behavior and the new pin.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/hermeticity.py Adds claim_conftest_slot() helper and updates conftest hookup documentation.
tests/doc-health/conftest.py Imports and calls claim_conftest_slot(globals()) for this subtree.
tests/ideation-dashboard/conftest.py Imports and calls claim_conftest_slot(globals()) for this subtree.
tests/avatar_runtime/conftest.py Imports and calls claim_conftest_slot(globals()) (including rationale comment).
tests/ideation-dashboard/test_hermeticity.py Adds scratch-tree pins (positive + negative control) and updates related docstring text.
pytest.ini Adds explanatory comments about the new conftest-slot repair.
.github/workflows/pytest-suite.yml Updates scope comment to reflect the repaired multi-directory behavior and pin tests.
Suppressed comments (1)

tests/ideation-dashboard/test_hermeticity.py:437

  • Same as above: these failure-mode assertions only look at proc.stdout. Joining stdout + stderr avoids flakes if pytest writes the failure summary or traceback to stderr.
    proc = _slot_run(root, ".")
    assert proc.returncode != 0, proc.stdout
    assert "3 passed" in proc.stdout and "1 failed" in proc.stdout, proc.stdout
    assert "cannot import name 'A_ONLY' from 'conftest'" in proc.stdout, proc.stdout

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread pytest.ini
Comment on lines +31 to +35
# THE OTHER HALF OF THE AMBIENT-NAME PROBLEM is repaired inside the conftests
# rather than here (issue #305). Each of the four that exist calls
# `claim_conftest_slot(globals())` from `tests/hermeticity.py`, re-claiming
# `sys.modules["conftest"]` for its own subtree, so
# `pytest tests/doc-health tests/ideation-dashboard` no longer depends on
Comment on lines +429 to +432
proc = _slot_run(root, *args)
assert proc.returncode != 0, f"{args}: {proc.stdout}"
assert f"cannot import name '{wanted}' from 'conftest'" in proc.stdout, proc.stdout
assert f"{hijacker}/conftest.py" in proc.stdout, proc.stdout
brettheap and others added 2 commits August 27, 2026 00:04
…lisions, pin the real invocation

Adversarial review of #406. Five findings, all closed.

The three prose edits deferred until #403 landed are applied on top of its
wording, leaving its validate-docs.sh sentences byte-identical: the hazard is now
stated as what an UNCLAIMING conftest does.

NIT-1 (the one that could break a run). The precondition keyed on
`namespace["__name__"] != "conftest"`, but under `--import-mode=importlib` or
`consider_namespace_packages=true` — both reachable through PYTEST_ADDOPTS —
pytest names a ROOTLESS conftest `a.conftest` (measured). The guard would have
raised inside conftest collection, aborting the whole run at rc=4 with the FR-043
guard never registered, over a configuration that merely renames modules; main
only collected with errors. It now keys on the conftest directory's missing
`__init__.py`, which is the actual condition for contending for the flat slot. A
real package still raises. Pinned both ways.

NIT-2. The two hooks were written into `globals()` by plain assignment, so a
conftest defining its own `pytest_collectstart` silently defeated the claim in
either order. The helper now returns the hook pair and refuses if either name is
already bound, with a message saying to call the returned function from inside
your own implementation; the define-it-afterwards direction, which no runtime
check can see, is pinned by source against HOOKS_INSTALLED_BY_THE_CLAIM.

The reviewer's real worry: the claim on the shipped conftests was pinned only by
a text grep. `test_the_real_two_directory_invocation_collects_the_same_in_either_order`
now runs the real `pytest --co` over two directory PAIRS, both orders, and
requires the orders to agree — 11.06s, four child collections. Dropping the claim
from doc-health's or ideation-dashboard's conftest reds it (measured);
avatar_runtime's is not observable, since nothing there imports through
`conftest`, and the docstring says so rather than implying coverage it lacks.

NIT-3. "the seven directories that have none" was wrong: measured 2026-08-27, 18
test-bearing directories, 13 with no conftest of their own, 10 of those rootless.
The measurement command is in pytest.ini beside the number, and the pre-existing
"Seven of the nine" on line 11 is corrected the same way. The 184/27/993 counts
are now labelled as measured at f9457d6 and explained as pinning the DIFFERENCE
between two orders, which the behavioural test re-measures on the live tree.

Verification after merging origin/main (ef79163, #403):
tests/ideation-dashboard/test_hermeticity.py 31 passed; the fixed shape
`pytest tests/doc-health tests/avatar_runtime` 1017 passed (it aborted with 27
collection errors at base).

Co-Authored-By: Claude Opus 5 <[email protected]>
Copilot AI review requested due to automatic review settings August 27, 2026 04:15

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Suppressed comments (2)

tests/ideation-dashboard/test_hermeticity.py:443

  • The negative-control assertions match error text only in proc.stdout, so a pytest version/configuration that writes the ImportError details to stderr would make this pin fail (and would also hide useful failure context in the assertion message). Prefer matching against proc.stdout + proc.stderr.
        proc = _slot_run(root, *args)
        assert proc.returncode != 0, f"{args}: {proc.stdout}"
        assert f"cannot import name '{wanted}' from 'conftest'" in proc.stdout, proc.stdout
        assert f"{hijacker}/conftest.py" in proc.stdout, proc.stdout

tests/ideation-dashboard/test_hermeticity.py:581

  • This subprocess probe parses and error-checks only proc.stdout. Switching to a single output = proc.stdout + proc.stderr both simplifies the asserts and ensures the parse still works if pytest writes the collection summary to a different stream.
            proc = _repo_collect(*args)
            assert proc.returncode == 0, f"{args}: {proc.stdout[-4000:]}{proc.stderr}"
            assert " error" not in proc.stdout, f"{args}: {proc.stdout[-4000:]}"
            match = re.search(r"(\d+) tests collected", proc.stdout)
            assert match, proc.stdout[-2000:]

Comment on lines +416 to +423
for args in (("a", "b"), ("b", "a")):
proc = _slot_run(root, *args)
assert proc.returncode == 0, f"{args}: {proc.stdout}{proc.stderr}"
assert "4 passed" in proc.stdout, f"{args}: {proc.stdout}"

proc = _slot_run(root, ".")
assert proc.returncode == 0, proc.stdout + proc.stderr
assert "4 passed" in proc.stdout, proc.stdout
@brettheap
brettheap merged commit 8e9c075 into main Aug 27, 2026
3 checks passed
@brettheap
brettheap deleted the fix/conftest-slot-order-independence branch August 28, 2026 09:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

conftest flat-slot contention: multi-directory pytest invocations are order-dependent

2 participants