Skip to content

Commit e626f53

Browse files
authored
Read a response body only once the browser has finished delivering it (#85)
## Problem Three `ci` runs on main have now spent the whole 45-minute step bound and left no failure to read: [33130006054](https://github.com/max-sixty/leaf/actions/runs/33130006054) (`45de22f`), [33130455313](https://github.com/max-sixty/leaf/actions/runs/33130455313) (`d4472ad`), [33131937176](https://github.com/max-sixty/leaf/actions/runs/33131937176) (`caa8460`). Under the `-v` #81 added, each names a different test that a worker picked up and never reported — `test_a_resolved_thread_can_be_reopened`, `test_a_sent_comment_is_revealed_in_the_panel`, `test_an_answer_carrying_an_older_pick_cannot_undo_a_newer_one` — so the wedge is not a test's, and the other worker stops minutes later in a module of its own. It is `Traffic`. [`_responded`](https://github.com/max-sixty/leaf/blob/3feb009d654af450fed766621909b1933f96e418/tests/render_harness.py#L629) queues a response when its **headers** arrive, and [`settle`](https://github.com/max-sixty/leaf/blob/3feb009d654af450fed766621909b1933f96e418/tests/render_harness.py#L648) then reads the body with [`response.json()`](https://github.com/max-sixty/leaf/blob/3feb009d654af450fed766621909b1933f96e418/tests/render_harness.py#L663). That call waits on the request's finished fact and takes no timeout in any binding. A page that abandons an answer it no longer wants leaves a request Chromium never reports finished, and the read then blocks for as long as the job lives. It is the one wait in this harness that cannot run out: `_until`'s own 30-second deadline guards `wait_for_event` and never gets a turn, so the worker stops inside a helper every render test calls, with no nodeid, no traceback and no Playwright timeout. This is measured, not inferred — the full suite was run locally under a call tracer and both workers were caught inside `Response.json`, unmoved across two snapshots a minute apart (below). ## Solution Settle a response only once `requestfinished` says the browser holds the whole body, and wake `_until` on that same fact rather than on arriving headers — a body is what the counters are read from, and that event is the browser saying it has one. `settle` keeps an unfinished response queued instead of reading it, so the shape that used to stop the run now lets `_until` reach its deadline and print its counters, which is the naming a wedge could never do. The counters themselves are untouched: `acked` and `heard` still move on the `response` event, so what a trip means to `round_trip` is what it meant before. This is at a different site from #84, which bounds `page.evaluate`'s frame promises on the same three runs' evidence and says of itself that it does not prove which wait wedged them. The two do not overlap in `render_harness.py`, and #84 still closes a real unbounded-wait class — it is just not the one that stopped these runs. ## Testing `uv run pytest tests --run-nightly` — **1357 passed, 6 skipped in 19:36**, on the machine that had just wedged twice in a row at 65% and 91% without the change. Rebased onto `dd42ddb`: `ruff check`, `ruff format`, `tests/test_render_conversations.py` and `tests/test_render_reactions.py` (48 passed), and the three traffic-wait gates. Bug-back: with `settle` restored to its unconditional drain, `test_traffic_leaves_a_body_the_browser_has_not_finished_handing_over` fails with `a body was read before the browser had all of it`. <details><summary>How the blocking call was identified</summary> The suite was run as CI runs it (`uv run pytest tests --run-nightly -v`) with a plugin wrapping the Playwright sync surface — `Page.close`, `Page.evaluate`, `Page.wait_for_function`, `Response.body/json/text`, `Locator.*`, `Mouse.*`, `Keyboard.*` — each writing the call it is inside to a per-worker file. A watchdog snapshotted those files after the log had been silent for 150 seconds, and again a minute later: ``` --- snapshot A 30159 1787884275.442 ENTER Response.json stack=['Response.json'] 27463 1787884129.338 ENTER Response.json stack=['Response.json'] --- snapshot B 30159 1787884275.442 ENTER Response.json stack=['Response.json'] 27463 1787884129.338 ENTER Response.json stack=['Response.json'] ``` Both workers, unmoved, with the report count frozen at 1315 of 1395. `py-spy` cannot reach these (the sandbox denies `ptrace`), and `faulthandler` names nothing here for the reason `pyproject.toml` records — the test's frames sit in a suspended greenlet. The wedge reproduces without instrumentation too. An earlier plain run stopped at 91% with `gw1` inside `test_a_resolved_thread_can_be_reopened` after `test_a_thread_the_agent_closed_names_who_closed_it` — the same pair, in the same order, as run 33130006054. Both wedges left their page server answering: the served page's `viewed.json` kept ticking every 30 seconds, and `ss` showed one established connection per server with empty queues, so nothing was stalled on the wire and no `flock` was held. Per-test pacing in the failed CI runs matches a green run's decile for decile, which rules out the machine slowing down before it stopped. </details> --- Automated fix for [failed run](https://github.com/max-sixty/leaf/actions/runs/33130006054) --------- Co-authored-by: leaf-agent <[email protected]>
1 parent 6045970 commit e626f53

2 files changed

Lines changed: 109 additions & 38 deletions

File tree

‎tests/render_harness.py‎

Lines changed: 55 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -599,9 +599,11 @@ def __init__(self, page):
599599
set()
600600
) # event posts in the air, each counted once whichever way it ends
601601
self._answered = set() # requests whose one response has entered the counters
602+
self._complete = set() # requests the browser has finished delivering
602603
self._responses = [] # bodies are read outside Playwright's response callback
603604
page.on("request", self._out)
604605
page.on("response", self._responded)
606+
page.on("requestfinished", self._delivered)
605607
page.on("requestfailed", self._back)
606608
# A navigation is the third way a trip ends, and the one the browser reports
607609
# for neither kind: a post the reload kills mid-flight gets no `response` and
@@ -642,26 +644,50 @@ def _responded(self, response):
642644
self._back(request)
643645
self._responses.append(response)
644646

645-
def settle_response(self, response):
646-
"""Account for the exact response a causal wait just consumed.
647+
def _delivered(self, request):
648+
"""The browser has the whole body, so reading it cannot block."""
649+
self._complete.add(request)
647650

648-
Playwright resolves `wait_for_event("response")` independently of ordinary
649-
response listeners. Under load the waiter can resume first; explicitly entering
650-
that response here closes the ordering without polling or sleeping. `_responded`
651-
deduplicates the later listener whichever one wins.
651+
def settle_finished(self, request):
652+
"""Account for the exact trip a causal wait just consumed.
653+
654+
Playwright resolves `wait_for_event("requestfinished")` independently of
655+
ordinary listeners. Under load the waiter can resume first; explicitly entering
656+
that trip here closes the ordering without polling or sleeping. `_responded`
657+
and `_delivered` deduplicate the later listeners whichever one wins.
652658
"""
653-
self._responded(response)
659+
self._delivered(request)
660+
response = request.response()
661+
if response is not None:
662+
self._responded(response)
654663
self.settle()
655664

656665
def settle(self):
657666
"""Read queued bodies from ordinary test control flow, never an event callback.
658667
659668
Playwright may yield while `response.json()` asks its driver for the body. Doing
660669
that inside `_responded` let the test re-enter between `acked` and `pending`,
661-
after the response event that could wake it had already fired."""
662-
while self._responses:
663-
responses, self._responses = self._responses, []
664-
for response in responses:
670+
after the response event that could wake it had already fired.
671+
672+
A body is read only once `requestfinished` says the browser holds all of it. The
673+
`response` event fires on the headers, and `Response.json` then waits on the
674+
finished fact with no deadline of its own — the one wait in this harness that
675+
cannot run out. A page that abandons an answer it no longer wants leaves a
676+
request the browser never finishes, and reading that body stopped a worker
677+
dead: a locally reproduced wedge was traced with both workers inside
678+
`Response.json`, and the runs on main that spend their whole 45-minute bound
679+
name no test and leave no traceback. A run reaches that bound only with both
680+
workers stopped, and on the CI runs parsed for it the second one was past this
681+
site, in teardown. Queued and unread, such a response instead lets `_until`
682+
reach its own deadline and print the counters."""
683+
while True:
684+
ready = [r for r in self._responses if r.request in self._complete]
685+
if not ready:
686+
return
687+
self._responses = [
688+
r for r in self._responses if r.request not in self._complete
689+
]
690+
for response in ready:
665691
self._settle(response)
666692

667693
def _settle(self, response):
@@ -732,22 +758,24 @@ def _until(page, fact, wanted):
732758
"""Block until `fact` holds of the page's traffic.
733759
734760
The events the counters are built from arrive while the client is blocked inside a
735-
Playwright call, so this blocks on each next response and asks again — no polling
736-
interval to pick, and nothing added to the page. The response returned by that wait
737-
is entered into Traffic directly because Playwright does not order the waiter after
738-
ordinary response listeners; the delivery fact therefore changes before this caller
739-
asks again.
740-
741-
It wakes on responses alone, where the counters answer to failures too, so a fact that
742-
came true through a failed request waits for the next poll that is answered to be
743-
noticed. A page with every poll routed to `abort` has no such next, and a wait on one
744-
runs its timeout out and says so rather than passing.
761+
Playwright call, so this blocks on each next finished trip and asks again — no
762+
polling interval to pick, and nothing added to the page. The request returned by that
763+
wait is entered into Traffic directly because Playwright does not order the waiter
764+
after ordinary listeners; the delivery fact therefore changes before this caller asks
765+
again.
766+
767+
It wakes on finished trips rather than on arriving headers, because a body is what
768+
the counters are read from and `requestfinished` is the browser saying it has one.
769+
The counters answer to failures too, so a fact that came true through a failed
770+
request waits for the next trip that finishes to be noticed. A page with every poll
771+
routed to `abort` has no such next, and a wait on one runs its timeout out and says
772+
so rather than passing.
745773
746774
A wait that runs out names the caller's wanted fact and prints its starting and final
747-
counters. The final reading comes after the timeout because the response listener may
748-
settle the fact as the timeout is delivered. No response preserves Playwright's
749-
timeout as the cause; a busy response stream reaches the same explicit deadline
750-
instead of waking this loop forever."""
775+
counters. The final reading comes after the timeout because the page's own
776+
`requestfinished` listener may settle the fact as the timeout is delivered. No
777+
finished trip preserves Playwright's timeout as the cause; a busy stream reaches the
778+
same explicit deadline instead of waking this loop forever."""
751779
if fact(_traffic(page)):
752780
return
753781
began = str(_traffic(page))
@@ -757,8 +785,8 @@ def _until(page, fact, wanted):
757785
remaining = int((deadline - time.monotonic()) * 1000)
758786
if remaining <= 0:
759787
raise PlaywrightTimeout("responses outlived the wait deadline")
760-
response = page.wait_for_event("response", timeout=remaining)
761-
page.lf_traffic.settle_response(response)
788+
request = page.wait_for_event("requestfinished", timeout=remaining)
789+
page.lf_traffic.settle_finished(request)
762790
except PlaywrightTimeout as ran_out:
763791
ended = _traffic(page)
764792
if fact(ended):

‎tests/test_render_gate.py‎

Lines changed: 54 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
UNANSWERED_CODE_PAGE,
4949
UNMARKABLE_PAGE,
5050
WIDE_TABLE_PAGE,
51+
Traffic,
5152
_traffic,
5253
_until,
5354
arrange_return,
@@ -1718,17 +1719,17 @@ def test_the_render_gate_reports_code_the_reader_cannot_tell_from_its_block(
17181719
)
17191720

17201721

1721-
def test_a_traffic_wait_accounts_for_the_response_it_consumes():
1722-
"""The waiter may resume before Traffic's ordinary response listener under load."""
1722+
def test_a_traffic_wait_accounts_for_the_trip_it_consumes():
1723+
"""The waiter may resume before Traffic's ordinary listeners under load."""
17231724

17241725
class LateTraffic:
17251726
done = False
17261727

17271728
def settle(self):
17281729
pass
17291730

1730-
def settle_response(self, response):
1731-
assert response == "answer"
1731+
def settle_finished(self, request):
1732+
assert request == "trip"
17321733
self.done = True
17331734

17341735
def __str__(self):
@@ -1738,14 +1739,56 @@ class EarlyPage:
17381739
lf_traffic = LateTraffic()
17391740

17401741
def wait_for_event(self, event, **_kwargs):
1741-
assert event == "response"
1742-
return "answer"
1742+
assert event == "requestfinished"
1743+
return "trip"
17431744

1744-
_until(EarlyPage(), lambda traffic: traffic.done, "accounted for the response")
1745+
_until(EarlyPage(), lambda traffic: traffic.done, "accounted for the trip")
1746+
1747+
1748+
def test_traffic_leaves_a_body_the_browser_has_not_finished_handing_over():
1749+
"""`Response.json` waits on the finished fact with no deadline of its own, so a
1750+
body read before the browser has one is the single wait here that cannot run out —
1751+
the one that spent a whole CI run's bound and named no test. A response settles
1752+
when its trip finishes and waits in the queue until then."""
1753+
1754+
class Request:
1755+
url = "http://page/api/state"
1756+
1757+
class Unfinished:
1758+
ok = True
1759+
read = False
1760+
request = Request()
1761+
1762+
def json(self):
1763+
self.read = True
1764+
return {"events": []}
1765+
1766+
class Page:
1767+
"""The page's own event surface, which is all Traffic asks of one."""
1768+
1769+
def __init__(self):
1770+
self.listeners = {}
1771+
1772+
def on(self, event, handler):
1773+
self.listeners[event] = handler
1774+
1775+
page = Page()
1776+
traffic = Traffic(page)
1777+
response = Unfinished()
1778+
1779+
page.listeners["response"](response)
1780+
traffic.settle()
1781+
assert not response.read, "a body was read before the browser had all of it"
1782+
assert traffic.heard == 1, "the headers stopped counting as a state answer"
1783+
1784+
page.listeners["requestfinished"](response.request)
1785+
traffic.settle()
1786+
assert response.read, "the finished body never settled, so the queue only grows"
17451787

17461788

17471789
def test_a_traffic_wait_accepts_completion_delivered_with_its_timeout():
1748-
"""The ordinary response listener can settle the trip as the waiter times out."""
1790+
"""Traffic's own requestfinished listener can settle the trip as the waiter times
1791+
out, so the final reading is taken after the deadline rather than before it."""
17491792

17501793
class EdgeTraffic:
17511794
done = False
@@ -1760,11 +1803,11 @@ class EdgePage:
17601803
lf_traffic = EdgeTraffic()
17611804

17621805
def wait_for_event(self, event, **_kwargs):
1763-
assert event == "response"
1806+
assert event == "requestfinished"
17641807
self.lf_traffic.done = True
1765-
raise PlaywrightTimeout("response met its deadline")
1808+
raise PlaywrightTimeout("the trip met its deadline")
17661809

1767-
_until(EdgePage(), lambda traffic: traffic.done, "accounted for the response")
1810+
_until(EdgePage(), lambda traffic: traffic.done, "accounted for the trip")
17681811

17691812

17701813
def test_an_authored_project_widget_loads_through_the_real_layer(

0 commit comments

Comments
 (0)