Repository navigation
Let each fixture own what the tests were holding, and end what it lends - #823
Conversation
#800's preview slots were one instance of a shape: a resource whose owner never gets the chance to take it back. This is the sweep of `tests/` for the rest of it, and the two it found. ## A page nobody was listening to `watched` collects a page's console, its `pageerror`, and the window `error` events with no exception behind them, and until now each caller installed it. 38 test functions made a page and never did, so each of those tests was green about a page whose error channels nothing read. The `browser` fixture hands over a `WatchedBrowser`, whose `new_page` and `new_context` install the problem list, the `Traffic` ledger, and the interception arm in the call that makes the page. An init script has to precede the navigation it instruments, and a console entry from a page nobody listened to is gone, so none of the three can be added afterwards: where the page is made is the only place they fit. Turning it on found 21 pages that had been reporting into nothing. Each is a page its test deliberately broke, and each now says so where that happens — `consume_browser_errors` for a single fault, and `restarting` for the preview bootstraps, whose wording depends on which fetch was in flight when the service went away. A fault the page keeps meeting has no such point, so the two tests that refuse every `/api/state` consume after `page.close()`. `browser.unwatched` is the way past, for a page the product opens to read for itself: `render_version` collects that page's console and reports it as a finding, so a gate test whose page is meant to be faulty would otherwise assert the same errors twice. The context's own `page` event looked like the way to reach a popup, and it is not. Measured: a `page.route` inside that handler leaves the `add_init_script` after it without effect and says nothing about it. `opened_tab` remains how the suite meets a tab Chromium opened. ## The website adapter left its App Server behind `worker/server.py` starts a Codex App Server in a session of its own and closes it in a `finally`. uvicorn answers SIGTERM by stopping its loop, restoring the handler that preceded it, and re-raising, so the process dies before that `finally` runs. A container takes the App Server away with everything else. A host does not, and `scripts/verify_site.py local` runs this adapter on a host and stops it exactly that way: three App Servers were alive on a developer's machine 15 to 17 hours after the runs that started them, 95MB resident each, each having recreated the temporary directory its run had removed. `close_on_signal` closes the host on that path and then dies of the signal it was sent. The test that covered this boundary asserted the adapter's own death and nothing about what it started, so `test_the_adapter_takes_its_app_server_with_it_when_it_is_told_to_stop` runs the real adapter with a stand-in App Server and asserts both; without the fix it fails on the survivor. ## Two resources the tests were holding by hand `socket_dir` owns a directory short enough for `sun_path`, the one file that cannot live under `tmp_path`, since pytest has spent most of the 104 bytes before a test's own files begin. Two tests made their own under `/tmp`, and the new website test wanted a third. `app_server` owns the websocket stand-in the Codex observer connects to: the server, the thread serving it, and the stop that ends both. Four tests held those three by hand, and one ran the stop on the last line of the test body, which is the line a failing assertion never reaches. `test_the_resources_a_fixture_owns_are_taken_from_that_fixture` reads the suite for the calls these fixtures exist in place of, because a fixture cannot stop a test making its own. ## What the sweep found nothing to fix in - Nothing in `tests/` writes into the checkout: an AST sweep over every write call rooted at `ROOT`, `PLUGIN_ROOT`, `SKILL_ROOT`, `EXAMPLES`, or `DOCS` comes back empty. `scripts/preview.py` is still the only writer there, and `preview_slot` owns what it leaves. - A detached Codex adapter ends with the test that started it. Measured with a test that starts one and releases nothing: it is gone three seconds later, because `_no_page_outlives_its_test` stops its page's server and a watch pass with no live page exits. The claim release in those tests is an assertion about the adapter rather than ownership of it. - `spawn` is the only caller of `subprocess.Popen` under `tests/`, and the state home each run claims into is `tmp_path_factory`'s. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts: # tests/test_interact_session.py
The fixture already closed every context a test left open, and did it after reading what those pages reported, because closing cancels outstanding requests and stops event delivery. 89 tests closed their page or context themselves, in a `try/finally` around the whole body, which ran that close one step early: the reading it cut short was the test's own. They are gone, and with them the indentation they wrapped each body in. What a test now says about its page is what it asserts. The one page that still closes itself is the one that keeps making the fault its test is about: the two tests that refuse every `/api/state` read consume after `page.close()`, because the entries keep arriving for as long as the page is open. `test_the_resources_a_fixture_owns_are_taken_from_that_fixture` names those two and reads the suite for the rest, the way it already reads for the primitives these fixtures exist in place of. `arrival_findings` collects its own console, `pageerror`, response and window readings, and reports them as findings a test asserts on, so its page comes from `browser.unwatched` at both call sites rather than one. A page that is read for twice is reported twice. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
leaf-agent
left a comment
There was a problem hiding this comment.
test and lint are green on this head, and the adapter fix reads correctly: close_on_signal is installed before serve_forever, which is where uvicorn's capture_signals takes over, so the re-raise lands back on stop with the App Server still reachable.
Two things about the new ownership rule don't hold as stated.
The rule tests/CLAUDE.md now states is true only of the try/finally form. 86 test functions still end their body with a bare page.close() on a page the browser fixture lent — 18 in test_render_widgets.py, 13 in test_render_conversations.py, 12 in test_render_controls.py, 9 in test_render_export.py, all files this PR de-indented. Those closes run at exactly the point the 89 removed finally blocks ran, and the PR's own argument for removing them — closing stops event delivery, so the reading it cuts short is the test's own — applies unchanged. The new guard reads ast.Try nodes only, so none of the 86 is visible to it. Either they are the same defect and the sweep stopped one syntactic form short, or the trailing close is harmless and the 89 removals were cosmetic; the doc claims the first and the suite shows the second.
opened_tab hands back a page that was never made readable. It builds its controlled tab from page.context — the raw Playwright context, not the WatchedContext the fixture handed over — so the tab reaches seven call sites with no problem list, no Traffic ledger and no interception arm. That is the page the sweep set out to eliminate, at the helper the new WatchedContext docstring names as the way to meet a tab Chromium opened.
I can push both fixes if you want them in this PR: readable(tab) before the goto in opened_tab, and either the 86 closes removed with the guard widened to statement-level closes, or the tests/CLAUDE.md wording scoped to what the guard actually enforces.
How the 86 were counted
Over the merged tree, for every test_* function taking browser, the last statement of the body where the closed name was assigned from browser.new_page, browser.new_context, browser.unwatched…, open_page(…) or context.new_page:
import ast, pathlib
for p in sorted(pathlib.Path("tests").glob("*.py")):
tree = ast.parse(p.read_text())
for fn in (n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)):
if not fn.name.startswith("test_") or "browser" not in [a.arg for a in fn.args.args]:
continue
lent = {t.id: ast.unparse(s.value) for s in ast.walk(fn) if isinstance(s, ast.Assign)
for t in s.targets if isinstance(t, ast.Name)}
node = fn.body[-1]
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
call = ast.unparse(node.value)
held = lent.get(call.removesuffix(".close()"), "")
if call.endswith(".close()") and held.startswith(
("browser.new_page", "browser.new_context", "browser.unwatched",
"open_page(", "context.new_page")):
print(f"{p.name}:{node.lineno} {fn.name}")
leaf-agent
left a comment
There was a problem hiding this comment.
test is red at this head on one case, and the failure is this branch's own: test_the_resources_a_fixture_owns_are_taken_from_that_fixture now collects three entries and asserts on them.
E AssertionError: ['test_render_mcp.py:1124 host.close() — the browser fixture does',
'test_render_mcp.py:1185 host.close() — the browser fixture does',
'test_render_mcp.py:1243 host.close() — the browser fixture does']
They are three try/finally: host.close() blocks the sweep left behind, in test_the_snapshot_posts_the_passage_the_version_holds_not_the_one_it_paints, test_an_element_anchor_names_the_page_and_never_the_apps_own_shell, and test_a_refused_anchor_reaches_the_reader_with_their_draft_intact. Each wraps the open_snapshot_app(browser, page_dir) section, and each test goes on to open a separate page afterwards — so the test is finished with host at that finally, and the close is the early one this PR exists to remove. The guard's verdict is right; the three blocks should go the way the other 89 did.
The rule's reach stops at the parameter list
tests/CLAUDE.md now says the guard reads "a close in a finally, or a close as a test's last statement, on anything the browser fixture handed over". Two things sit outside that.
A test reaching the browser through another fixture is skipped whole, because the function filter is "browser" not in [argument.arg for argument in function.args.args]. held_events hands its browser over as browser, held = held_events, so four tests still end on a close of a page open_page(browser, …) gave them: test_a_settled_delivery_activates_one_fresh_document_with_continuity, test_a_failed_reopen_reveal_still_processes_its_durable_answer, test_pending_action_waits_for_the_ask_list_paint_before_retiring, and test_pending_action_waits_for_the_ask_banner_paint_before_retiring.
And a tab from opened_tab never enters lent, because the assigned value names page rather than browser. This commit is what makes that matter: readable(tab) puts the tab's problem list into the collector the fixture reads at teardown, so test_leaves_keep_focus_through_reordering_and_choose_a_neighbour_on_removal, test_an_external_link_says_and_opens_where_it_goes, and test_an_addressed_link_leaves_the_reader_at_its_destination now end on a tab.close() that cuts short a reading which did not exist before this commit.
I can push both if you want them here: the three finally blocks out of test_render_mcp.py, and the guard keyed on what a function obtains rather than on the names in its signature, with those seven remaining closes removed.
How the seven were found
Over the merged tree, the guard's own endings logic with the parameter filter dropped and lent widened to names assigned from an expression mentioning browser, held_events, or opened_tab:
INVISIBLE test_render_application_boundary.py:474 page.close()
GUARD-SEES test_render_controls.py:3061 tab.close()
INVISIBLE test_render_conversations.py:1687 page.close()
GUARD-SEES test_render_navigation.py:1300 tab.close()
GUARD-SEES test_render_navigation.py:1339 tab.close()
INVISIBLE test_render_widgets.py:8380 page.close()
INVISIBLE test_render_widgets.py:8428 page.close()
GUARD-SEES means the function takes browser and the guard walks it; the close still passes because tab is not in lent.
The guard walked only functions that named `browser` in their signature and only names assigned from an expression that mentioned it, so a page reached through `held_events` or `opened_tab` was never read for, and neither was the host page `open_snapshot_app` returns. It now follows every name assigned from something the browser fixture lends, until nothing new is reached, and skips only a fixture's own teardown. That found eleven more closes at a test's end: three `finally: host.close()` in `test_render_mcp.py`, five trailing closes on pages opened through `held_events`, and three `tab.close()` on the tab `opened_tab` now makes readable. They are gone for the same reason as the rest. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nine MCP tests made a `ProcessPageServer` and closed it in a `finally` of their own, four of them paired with a `page.close()` the browser fixture already does. `page_server` makes and closes it, so all nine `finally` blocks are gone. The one test whose subject is the server going away — the app falling back to its snapshot — still closes it where the next assertion reads that; `close` is idempotent. Thirty-nine website tests make a `WebsiteCodexHost`, and seven closed theirs. Closing stops the App Server a host started and releases the waiter lease it holds over a Codex thread. Measured at teardown, four of the other thirty-two still held one of the two, left for the collector to find: `test_the_website_task_is_a_scoped_leaf_codex_thread` and `test_a_lost_turn_start_ack_retries_after_idle_reconciliation` a lease, and two startup tests a process. `_no_host_outlives_its_test` closes every host a test made, as `_no_page_outlives_its_test` stops every page server. It sweeps rather than asking for a fixture because the host is these tests' subject, built in each body with the paths that test needs; a fixture parameter measured 51 lines of reflowed signatures for the same guarantee. The three tests whose subject is closing keep their close. `test_the_website_app_server_inherits_the_ready_leaf_cli` handed the host a stand-in process that could only be polled. The sweep stops it the way the host stops a real one, so the stand-in now answers `terminate` and `wait` too. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
leaf-agent
left a comment
There was a problem hiding this comment.
The close rule's reach is one spelling short again. tests/CLAUDE.md now says "a finally whose whole body is a close", so the prose and the branch agree — but that is the narrower half of the choice, and 18 tests still end by closing a page or context the browser fixture lent, a step before the fixture reads what those pages reported. They are the same defect as the 202, in the two spellings the guard cannot see:
A finally that also releases what the test held. for route in boot: route.continue_(), then page.unroute_all(behavior="wait"), then page.close() — len(node.finalbody) == 1 skips the block whole. Twelve of them, including test_an_example_paints_while_every_stage_of_site_startup_is_held and test_the_public_catalog_paints_in_its_final_position_before_leaf_loads in test_site.py, and test_authored_html_paints_while_runtime_startup_is_held in test_render_startup.py.
A close in the block a test ends on. endings.append(function.body[-1]) reads the last statement only where the close is that statement, so a test ending for tab in (first, second, third): tab.close() — test_a_decision_travels_between_tabs_and_the_log_has_the_last_word, test_a_moved_card_identifies_its_reader_origin_across_tabs — closes three watched pages unseen. Six end that way, and the list below is a floor rather than a count: in test_every_control_the_layer_offers_is_a_box_the_reader_can_hit the trailing if context: context.close() also pushes the page.close() above it out of body[-1].
Scoped to the shape rather than to the ending, the rule is cheapest to reintroduce by putting a second statement in the finally — which is what these twelve already are, so the gap is live rather than hypothetical. Reading every statement of each finalbody, and following function.body[-1] down through a trailing block, is the version that holds. It also reaches three closes in test_render_gate.py that want a decision instead of a removal: their page is browser.unwatched.new_page(), so there is no reading for the close to cut short, and lent admits any name whose value mentions browser and cannot tell them apart.
I can push the widened reading, the 18 removals, and whichever way you want the three unwatched ones settled.
The 21 closes a reading of the ending catches
Over the merged tree at 735073c, the guard's own logic with endings widened to every finalbody statement and to function.body[-1] followed through a trailing block:
finally with more than one statement
test_render_gate.py:211 test_a_module_the_page_never_receives_names_the_wait_that_stopped page.close() (unwatched)
test_render_gate.py:244 test_a_wait_before_the_entry_is_released_names_only_the_page_s_own_request page.close() (unwatched)
test_render_gate.py:294 test_a_released_entry_that_never_arrives_is_named_like_any_other_file page.close() (unwatched)
test_render_navigation.py:1784 test_a_failed_ask_reveal_does_not_register_an_arrival page.close()
test_render_projection.py:407 test_pr_review_disconnect_during_markdown_load_is_safe page.close()
test_render_projection.py:1241 test_visual_review_ignores_a_late_load_from_detached_evidence context.close()
test_render_projection.py:3574 test_an_old_document_state_request_cannot_update_the_new_revision page.close()
test_render_startup.py:456 test_authored_html_paints_while_runtime_startup_is_held context.close()
test_render_startup.py:515 test_a_restored_auxiliary_surface_has_final_geometry_before_runtime_loads context.close()
test_render_startup.py:2281 test_comment_focus_waits_for_the_lazy_placement_module page.close()
test_render_widgets.py:1517 test_a_detached_board_releases_and_restores_its_lifecycle context.close()
test_site.py:700 test_session_activation_reaches_other_tabs context.close()
test_site.py:864 test_the_public_catalog_paints_in_its_final_position_before_leaf_loads page.close()
test_site.py:1504 test_interaction_gallery_waits_for_slow_contained_page_state context.close()
test_site.py:1688 test_an_example_paints_while_every_stage_of_site_startup_is_held page.close()
last statement of a trailing block
test_render_controls.py:6399 test_every_control_the_layer_offers_is_a_box_the_reader_can_hit context.close()
test_render_conversations.py:3943 test_a_settlement_in_a_reply_leaves_its_own_anchor_on_the_page page.close()
test_render_options.py:2225 test_the_specimen_gutter_is_painted_in_both_schemes page.close()
test_render_projection.py:5902 test_a_moved_card_identifies_its_reader_origin_across_tabs tab.close()
test_render_widgets.py:6681 test_a_decision_travels_between_tabs_and_the_log_has_the_last_word tab.close()
test_render_widgets.py:9149 test_no_two_of_a_chart_s_words_land_in_the_same_place page.close()
The two names in closes_to_stop_a_repeating_fault are excluded, as the guard excludes them. The four test_render_mcp.py blocks this list held before 35f3f7c are gone with the page_server fixture.
The guard read a `finally` only when its whole body was one close, and a test's last statement only when the close was that statement. So the rule was dodged by the fifteen `finally` blocks that release a held route before closing, and by six tests that end inside a loop or a branch — `for tab in (first, second, third): tab.close()`, `if context: context.close()`. It now reads every statement of a `finally` and follows the last line down through the block it ends in, and names reached through `for` and `with` are followed the way assignments were. The 21 closes it finds are gone. The hold section had the release path end by closing the page, and dropping that close was the part worth measuring: a released route's request finishes after the `finally` that let it go, so its noise could now reach a reading the close used to cut off. Run five times at six workers, the 21 changed tests passed every time, so the section now says the fixture closes the page after the release. A decorator counted as a fixture's when its text contained "fixture", which a `parametrize` id can. It is now read by what it calls. Planted, the guard catches a close after a release in a `finally`, a close in a trailing loop, and a close in a test whose parametrize ids say "fixture". Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
#800's preview slots were one instance of a shape: a resource whose owner never
gets the chance to take it back. This is the sweep of
tests/for the rest ofit, and what it found.
A page nobody was listening to
watchedcollects a page's console, itspageerror, and the windowerrorevents with no exception behind them, and until now each caller installed it. 38
test functions made a page and never did, so each of those tests was green about
a page whose error channels nothing read.
The
browserfixture hands over aWatchedBrowser, whosenew_pageandnew_contextinstall the problem list, theTrafficledger, and theinterception arm in the call that makes the page. An init script has to precede
the navigation it instruments, and a console entry from a page nobody listened
to is gone, so none of the three can be added afterwards: where the page is made
is the only place they fit.
Turning it on found 21 pages that had been reporting into nothing. Each is a
page its test deliberately broke, and each now says so where that happens —
consume_browser_errorsfor a single fault, andrestartingfor the previewbootstraps, whose wording depends on which fetch was in flight when the service
went away. A fault the page keeps meeting has no such point, so the two tests
that refuse every
/api/stateconsume afterpage.close().browser.unwatchedis the way past, for a page that is read for by whoeveropened it:
render_versioncollects its page's console and reports it as afinding, and
arrival_findingsdoes the same for the restore cases it walks, soa page either of them opens would otherwise be reported on twice.
The context's own
pageevent looked like the way to reach a popup, and it isnot. Measured: a
page.routeinside that handler leaves theadd_init_scriptafter it without effect and says nothing about it.
opened_tabremains how thesuite meets a tab Chromium opened, and it makes that tab readable itself:
Page.contexthands back Playwright's own context rather than the one thefixture wrapped, so the tab seven tests assert on had none of the readings.
The pages the tests were ending themselves
That fixture ends a page as well as making one. It closes every context a test
left open, and does it after reading what those pages reported, because closing
cancels outstanding requests and stops event delivery. The tests closed their own
page or context where they ended with it 227 times — in a
finally, on the lastline, or at the end of a loop the test ended in — which ran that close one step
early: the reading it cut short was the test's own.
They are gone, and with them the indentation the
trywrapped each body in. Aclose inside a test stays, because there it is the gesture under test — a second
tab shut to show what the first one still holds — and the assertions after it are
what read it. So the rule is the ending rather than the call, and the guard reads
every spelling of one — anywhere in a
finally, and the line a test ends on,followed down through the block it ends in — on anything the browser fixture
lent, following a page through whatever handed it over (
held_events,opened_tab, a helper that returns one, aforover several) rather than keyingon the names in a test's signature. Its single exception is the page that keeps
making the fault its test is about, where the consume has to follow a close of its
own.
Fifteen of those
finallyblocks released a held route before closing, which isthe case worth measuring: the released request finishes after the block that let
it go, so its noise could reach a reading the close used to cut off. The fifteen
passed five runs out of five at six workers without it, so the hold section now
ends its release path at
unrouteand leaves the close to the fixture.The website adapter left its App Server behind
worker/server.pystarts a Codex App Server in a session of its own and closesit in a
finally. uvicorn answers SIGTERM by stopping its loop, restoring thehandler that preceded it, and re-raising, so the process dies before that
finallyruns. A container takes the App Server away with everything else. Ahost does not, and
scripts/verify_site.py localruns this adapter on a hostand stops it exactly that way: three App Servers were alive on a developer's
machine 15 to 17 hours after the runs that started them, 95MB resident each,
each having recreated the temporary directory its run had removed.
close_on_signalcloses the host on that path and then dies of the signal itwas sent. The test that covered this boundary asserted the adapter's own death
and nothing about what it started, so
test_the_adapter_takes_its_app_server_with_it_when_it_is_told_to_stopruns thereal adapter with a stand-in App Server and asserts both; without the fix it
fails on the survivor.
Resources the tests were holding by hand
socket_dirowns a directory short enough forsun_path, the one file thatcannot live under
tmp_path, since pytest has spent most of the 104 bytesbefore a test's own files begin. Two tests made their own under
/tmp, and thenew website test wanted a third.
app_serverowns the websocket stand-in the Codex observer connects to: theserver, the thread serving it, and the stop that ends both. Four tests held
those three by hand, and one ran the stop on the last line of the test body,
which is the line a failing assertion never reaches.
page_serverowns theProcessPageServeran MCP host reads a run's pagesthrough. Nine tests made one and closed it in a
finallyof their own, four ofthem beside a
page.close()the browser fixture already does. The one test whosesubject is the server going away — the app falling back to its snapshot — still
closes it where the next assertion reads that.
_no_host_outlives_its_testcloses everyWebsiteCodexHosta test made, as_no_page_outlives_its_teststops every page server. Thirty-nine website testsmake a host and seven closed theirs; measured at teardown, four of the other
thirty-two still held an App Server or the waiter lease over a Codex thread. It
sweeps rather than asking for a fixture because the host is these tests' subject,
built in each body with the paths that test needs. The three tests whose subject
is closing keep their close.
test_the_resources_a_fixture_owns_are_taken_from_that_fixturereads the suitefor the calls these fixtures exist in place of, and for a
finallythat closeswhat the browser fixture will close, because a fixture cannot stop a test making
or ending its own.
What the sweep found nothing to fix in
tests/writes into the checkout: an AST sweep over every writecall rooted at
ROOT,PLUGIN_ROOT,SKILL_ROOT,EXAMPLES, orDOCScomes back empty.
scripts/preview.pyis still the only writer there, andpreview_slotowns what it leaves.test that starts one and releases nothing: it is gone three seconds later,
because
_no_page_outlives_its_teststops its page's server and a watch passwith no live page exits. The claim release in those tests is an assertion
about the adapter rather than ownership of it.
spawnis the only caller ofsubprocess.Popenundertests/, and the statehome each run claims into is
tmp_path_factory's.Co-Authored-By: Claude Opus 5 (1M context) [email protected]