juggler: the gate of the events belongs to the connection, looks the delivery up at each event, and bounds the hold, not each event (DRAFT, 0.51.1)

From the review of 80bc478:
- the wrapper froze the bound `dispatch_event` of the connection: a patch of the class made after the browser was built (the e2e fixtures that
  record the events) was bypassed. It looks the delivery up at each event, as the reader did.
- the 5 s bound was per event: a holder that never lets go made the reader pay 5 s for every event. After one timeout the reader delivers ungated
  for 30 s, and the connection records it (`handler_errors`).
- the gate is kept on the connection, so a second dispatcher over the same connection shares the one the wrapper takes.
Tests: a utility context created while the replay goes on is not undone by an older event (the injected script half), the class patch, the
hold bound; wrapper.unit.page 67 -> 71.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
feder-crandClaude Sonnet 5.5 committed 2026-11-12 17:32:09 +01:00
1 parent 80bc4788ef
commit 15d18917ec
3 files changed
+100 -10

No files matched your search

+1 -1
View File
@@ -7,5 +7,5 @@
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 219, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 67, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "67 = 44 + 3+9+5+1+5 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 71, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "71 = 44 + 3+9+5+1+9 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
]
+32 -6
View File
@@ -4797,21 +4797,47 @@ class BrowserDispatcher(Dispatcher):
# middle of the replay of its first events, and the replay then went on with older ones (the initial about:blank, the
# `navigationStarted` of the same navigation) - the lifecycle ended at about:blank, or with the navigation pending again. The
# reader takes the gate for each event of a session; the page takes it for the whole of "subscribe, then replay" (`events_gate`).
self._events_gate = threading.RLock()
# The gate belongs to the CONNECTION (one wrapper, one gate, whoever builds a dispatcher over it).
gate = getattr(conn, "_events_gate", None)
if gate is None:
gate = threading.RLock()
try:
conn._events_gate = gate
except Exception:
pass
self._events_gate = gate
self._gate_timeouts = 0
if not getattr(conn, "_events_gate_installed", False):
raw_dispatch = conn.dispatch_event
#: The delivery the reader would have made: an override on the instance if there is one, else the class's method looked up
#: at each event (a patch of the class made after this dispatcher was built still applies).
own = conn.__dict__.get("dispatch_event")
stuck = {"until": 0.0}
owner = self
def raw_dispatch(method, params, session):
if own is not None:
return own(method, params, session)
return type(conn).dispatch_event(conn, method, params, session)
def gated_dispatch(method, params, session):
if not session:
return raw_dispatch(method, params, session)
if self._events_gate.acquire(timeout=self.GATE_WAIT_S):
waiting = time.monotonic() >= stuck["until"]
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
if got:
try:
return raw_dispatch(method, params, session)
finally:
self._events_gate.release()
# whoever holds the gate does not let go: the event is delivered all the same (the old, unordered way) and counted
self._gate_timeouts += 1
gate.release()
# ⛔ WHOEVER HOLDS THE GATE DOES NOT LET GO: the event is delivered all the same (the old, unordered way), and the reader does
# not wait again for a while (the bound is on the hold, not on each event). Said once per hold, where the connection records
# what its handlers failed at.
if waiting:
stuck["until"] = time.monotonic() + 30.0
owner._gate_timeouts += 1
errors = getattr(conn, "handler_errors", None)
if isinstance(errors, list) and len(errors) < 32:
errors.append("events gate: held more than %.1fs, events delivered ungated for 30s" % owner.GATE_WAIT_S)
return raw_dispatch(method, params, session)
conn.dispatch_event = gated_dispatch
try:
@@ -34,8 +34,9 @@ from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME
pytestmark = pytest.mark.unit
def _case(stop_after):
"""The replay is stopped after `stop_after` of its events; the destination's commit is delivered by another thread (the reader)."""
def _case(stop_after, scenario="commit"):
"""The replay is stopped after `stop_after` of its events; the live event of the scenario is delivered by another thread (the reader):
the destination's commit, or (`context`) the creation of a new utility context after the old one was destroyed."""
parked, go, delivered = threading.Event(), threading.Event(), []
with pytest.MonkeyPatch.context() as mp:
original = server_mod.BrowserDispatcher.replay
@@ -73,9 +74,13 @@ def _case(stop_after):
conn.frame()
conn.commit() # the initial about:blank (navigation n1)
conn.start() # the navigation to the destination starts (n2)
if scenario == "context":
conn.dispatch_event("Runtime.executionContextDestroyed", {"executionContextId": "eutility"}, SESSION)
begin.set() # the page is built now, and the replay hands it those events
assert parked.wait(5), "the replay never delivered %d event(s): %s" % (stop_after, delivered)
reader = threading.Thread(target=conn.commit_dest, daemon=True, name="engine-reader")
live = conn.commit_dest if scenario == "commit" else (lambda: conn.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "eutility2", "auxData": {"frameId": FRAME, "name": "utility"}}, SESSION))
reader = threading.Thread(target=live, daemon=True, name="engine-reader")
reader.start()
reader.join(0.3) # with the replay ordered, the reader waits behind it; unordered, it is through
go.set()
@@ -85,6 +90,8 @@ def _case(stop_after):
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
page = world.browser._page_targets.get(TARGET)
known = page.lifecycle.frames[FRAME]
if scenario == "context":
return page.injected.contexts.get((FRAME, "utility"))
return known.url, known.navigation, sorted(known.states), page.frame.url
finally:
begin.set()
@@ -99,3 +106,60 @@ def test_the_destination_commit_delivered_while_the_replay_goes_on_is_the_last_w
assert navigation == "n2", "the frame's navigation is %r" % navigation
assert "commit" in states
assert told == DEST, "the client's frame is at %r" % told
@pytest.mark.parametrize("stop_after", [1, 2])
def test_a_context_created_while_the_replay_goes_on_is_not_undone_by_an_older_event(stop_after):
"""The same race for the injected script: the replay brings the creation of the utility context and its destruction, the engine creates a
new one meanwhile. The new one is the context the injected script must end with."""
context = _case(stop_after, "context")
assert context == "eutility2", "the injected script ended with the utility context %r" % (context,)
def test_a_patch_of_the_class_made_after_the_browser_was_built_still_sees_the_events():
"""The reader looked the delivery up on the class at each event; the gate keeps doing so (the e2e fixtures that record the events patch
`EventListeners.dispatch_event` after the browser exists)."""
from invisible_core.juggler.connection import EventListeners
world = World()
try:
seen = []
original = EventListeners.dispatch_event
with pytest.MonkeyPatch.context() as mp:
mp.setattr(EventListeners, "dispatch_event", lambda self, method, params, session: seen.append((method, session)))
world.conn.dispatch_event("Page.x", {}, "S-patched")
assert seen == [("Page.x", "S-patched")]
assert EventListeners.dispatch_event is original
finally:
world.close()
def test_a_gate_that_is_never_let_go_costs_the_reader_one_wait_and_is_said():
"""The bound is on the hold, not on each event: the first event waits GATE_WAIT_S, the next ones are delivered at once, and the
connection records it."""
import time
world = World()
held, release, got = threading.Event(), threading.Event(), []
try:
world.browser.GATE_WAIT_S = 0.2
def holder():
with world.browser.events_gate():
held.set()
release.wait(10)
t = threading.Thread(target=holder, daemon=True)
t.start()
assert held.wait(5)
world.conn.add_listener(lambda m, p, s: got.append(m) if s == "S-stuck" else None)
began = time.monotonic()
for n in range(3):
world.conn.dispatch_event("Page.e%d" % n, {}, "S-stuck")
took = time.monotonic() - began
assert got == ["Page.e0", "Page.e1", "Page.e2"], got
assert took < 1.0, "the reader waited %.2fs for three events: the bound is per event" % took
assert world.browser._gate_timeouts == 1
assert any("events gate" in str(e) for e in world.conn.handler_errors), world.conn.handler_errors
finally:
release.set()
world.close()