Repository navigation
Each directory conftest claims the ambient conftest slot for its own subtree (#305) - #406
Conversation
…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]>
There was a problem hiding this comment.
Hi @brettheap! 👋
Your private repo does not have access to Sourcery.
Please upgrade to continue using Sourcery ✨
There was a problem hiding this comment.
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 intests/hermeticity.pythat installs two path-scoped hooks to reassert the correct ambientconftestmodule 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.iniand thepytest-suiteworkflow 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. Joiningstdout + stderravoids 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.
| # 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 |
| 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 |
…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]>
There was a problem hiding this comment.
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 tostderrwould make this pin fail (and would also hide useful failure context in the assertion message). Prefer matching againstproc.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 singleoutput = proc.stdout + proc.stderrboth 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:]
| 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 |
The mechanism, proved rather than assumed
conftestis an ambient top-level module name with exactly onesys.modulesentry.
tests/doc-health/,tests/ideation-dashboard/andtests/avatar_runtime/each carry a rootlessconftest.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:
_importconftestdeletessys.modules["conftest"]before importing each rootless conftest, so the last one loaded owns the slot_pytest/config/__init__.py:733,:753(guarded byresolve_package_path(conftestpath) is None)_set_initial_conftestsloads every path ARGUMENT's conftest before collection begins_pytest/config/__init__.py:615-667pytest_collectstartis dispatched through the node'sihook, immediately beforecollect()— which for aModuleis where the test module is imported_pytest/runner.py:587-588pytest_runtest_setupis dispatched through the item'sihook_pytest/runner.py:239-241Node.ihook→Session.gethookproxy(path)→FSHookProxywithremove_plugins = _conftest_plugins − _getconftestmodules(path), i.e. conftest hooks are path-scoped_pytest/nodes.py:227-230,_pytest/main.py:731-745So 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.pycannot 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)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())intests/hermeticity.py— a closure factorythat installs two path-scoped hooks into the calling conftest's namespace:
Called from the bottom of all three directory conftests.
pytest.iniisuntouched 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
tests/hermeticity.py, besideCONFTEST_HOOKUPS. Every directoryconftest 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.pywould need its own hookup pin to stay honest, andtests/hermeticity.pymust stay importable without pytest — the helper is,it touches only
sys.)claim_conftest_slot. "Claim", not "restore" or "fix": the slot hasa legitimate single occupant at any moment and each subtree asserts ownership
of it for its own nodes.
claim_conftest_slot(globals()). A re-exported hook paircannot work: one shared function object cannot know which module to install, so
the hooks have to be closures the calling conftest owns. Passing
globals()isthe shortest way to hand over both the module identity (
__name__) and thenamespace the hooks must land in. It raises
RuntimeErrorif__name__is notthe flat
conftest, because claiming from a package-qualified conftest wouldinstall the wrong module for everyone, silently.
tests/avatar_runtime/claims even though no test there imports fromconftest. An unclaiming directory still poisons its siblings when it isthe 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.pymust NOT claim, and that is load-bearing. pluggy callshook 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 bstraight back into two collection errors. Pinned by a test.tests/hermes_runtime_contracts/needs nothing. Its directories carry__init__.py, soresolve_package_pathis non-None and pytest never clears theflat slot for them; probed live — they import as
hermes_runtime_contracts.conftestandhermes_runtime_contracts.postgres.conftest.Pinned too (the exemption asserts the
__init__.py).Before / after (
--collect-only -q, this worktree)tests/doc-health tests/avatar_runtimetests/avatar_runtime tests/doc-healthtests/doc-health tests/ideation-dashboardtests/ideation-dashboard tests/doc-healthtests/doc-health tests/avatar_runtime tests/ideation-dashboardtests/(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 subprocessprobes with
cwdset, and it is where the conftest set is pinned):test_a_directory_conftest_owns_the_ambient_slot_for_its_own_subtree— buildsthe two-rootless-directory tree in
tmp_path(each conftest imports theshipped
claim_conftest_slot, so mutating the helper reds this), runspytest a b,pytest b aandpytest .as subprocesses, asserts4 passedeach time.
test_without_the_claim_the_same_tree_reproduces_the_slot_collision— thenegative control: the identical tree with the claim removed must fail with
cannot import name 'A_ONLY' from 'conftest'naming the other directory'sconftest, and the single-argument run must show
1 failed, 3 passed. This iswhat makes the pin prove the mechanism rather than an outcome.
test_every_flat_conftest_claims_the_slot_and_the_suite_wide_one_does_not—every entry in
CONFTEST_HOOKUPSexceptconftest.pycarriesclaim_conftest_slot(globals());tests/conftest.pycarries none; everyCONFTEST_EXEMPT_HOOKUPSdirectory has an__init__.py.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:
(the negative control passes RED and GREEN alike, by construction).
The four tests add ~3.5 s.
Mutation round — both mutants died
pytest_collectstartfrom the helper('a','b'):ImportError: cannot import name 'A_ONLY' from 'conftest' (…/b/conftest.py), 2 collection errorspytest_runtest_setupfrom the helpera/test_a.py::test_a_runtime_import_sees_its_own_conftestfails:1 failed, 3 passedThat 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 plainpytest tests/those readthe 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 stopsthat 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
pytest tests/ideation-dashboard/test_hermeticity.py -qpytest tests/doc-health -qpytest tests/ideation-dashboard -qpytest tests/doc-health tests/avatar_runtime tests/ideation-dashboard -q5556 + 16 = 5572, i.e. every test the three-directory invocation now collectsalso 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-suitepass,wallet-validationpass.Prose
tests/hermeticity.pyCONFTEST_HOOKUPSblock — a new closing paragraph: thehijack has a repair, adding a conftest.py is still not free,
tests/conftest.pyis the one entry that must not claim.
pytest.ini— a new closing paragraph: the per-directory-conftest paragraphstill 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: thetwo-directory shape is no longer order-dependent and is pinned by the new test;
--import-mode=importlibwas never available (option-freepytest.ini) andwould break every
from conftest import …site besides. Norun:stepchanged.
tests/ideation-dashboard/test_hermeticity.py— a new closing paragraph ontest_every_conftest_under_tests_registers_the_guard's docstring.Review round (second commit,
5782e367)origin/mainmerged in (ef791639, #403) — no conflicts. Five findings closed.The three deferred prose edits are applied on top of #403's wording; its
validate-docs.shsentences are byte-identical (git diff | grep validate-docsis 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=importliba ROOTLESS conftest gets
__name__ == "a.conftest"— so the guard would haveraised 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_moderuns the scratch tree under both
--import-mode=importliband-o consider_namespace_packages=trueand requires rc=0 with no refusal in theoutput (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_slotnow returns the hookpair 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_CLAIMtuple —demonstrated: appending
def pytest_collectstarttotests/avatar_runtime/conftest.pyreds 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_ordernowruns the real
pytest --co -qover two directory PAIRS, both orders each, andrequires the orders to agree. 11.06 s, four child collections (budget was
~15 s, so both orders and both pairs stay). Mutation:
tests/doc-health/conftest.pytests/ideation-dashboard/conftest.pytests/avatar_runtime/conftest.pyconftest. 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 noconftest of their own, 10 of those rootless (3 are packages). The measuring
command sits in
pytest.inibeside the number, and the pre-existingpytest.ini:11"Seven of the nine" is corrected the same way. The 184/27/993counts 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
pytest tests/ideation-dashboard/test_hermeticity.py -qpytest tests/doc-health tests/avatar_runtime -q--coboth orders, doc-health/avatar_runtime--coboth orders, ideation-dashboard/doc-health--co tests/Closes #305
🤖 Generated with Claude Code