Compare commits

...
Author SHA1 Message Date
feder-crandClaude Sonnet 5.5 bcd945e985 The worker/back-forward-cache test counts the refusals it repeated, and two tests cannot hide behind a repeat
A repeated gesture can hide a regression of the cache, so:
* the refusals met by the repeat loop are counted over the whole file, printed, and more than 2 in one run fail it, naming them ("the back-forward
  cache refuses too often");
* a page without a worker comes back from the cache at once, and a page whose started worker is in a frame of another site comes back: no repeat,
  no retry. The frame's worker is asked once first: a worker that has not started keeps any page out of the cache (its script fetch is in the load
  group; measured here, leaving the moment the frame is listed restored 0 of 2), which is why the "at once" of the frame case is the started worker.
* the unit test of the loop keeps its own count: it is not a refusal of Firefox.

11 passed locally.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 06:12:22 +01:00
feder-crandClaude Sonnet 5.5 0a3a2e5ba3 The worker/back-forward-cache test leaves only when the page can be cached, and does not fail on Firefox's refusal
One run in 29 of the e2e on GitHub failed "the page was loaded again instead of restored from the back-forward cache". Whether a document goes into the
cache is Firefox's decision at the start of the next navigation, and a refusal is for good: anything in flight in the document's load group refuses it
(Document::CanSavePresentation, CanonicalBrowsingContext::AllowedInBFCache) and so does a `pageshow` that has not run (it clears the loading mark). A
dedicated worker's script fetch is in the load group: measured here, leaving right after `load` with a worker that has not started restores 0 of 8,
after one round trip to the worker 8 of 8, with no worker 8 of 8, and no request is in flight in the protocol's view (the worker's fetch is not announced), so
no network event can say it.

* The test leaves only when every document of the page has had its `pageshow` and the worker has answered (the round trips it already made).
* A run whose page was still loaded again is not a result of ours: the gesture is repeated, on a fresh browser and a fresh event list, up to 3 times;
  3 refusals in a row fail, naming each. A failure of ours (the worker's ids, the order of the events) is never repeated.
* Unit test of the loop: refused twice then restored passes; refused every time fails with "proves nothing"; a verdict of ours is not retried.

Locally 8 of 8 on the release engine, twice.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:58:46 +01:00
@@ -19,6 +19,15 @@ its process: only the back-forward cache can end the worker, which is the case J
another site (with strategy 1 the top changes process), by `page.goto` (Page.navigate gives the top a new browsing
context even on the same site) or by the page's own `location.href` (the same browsing context). Hosts a.test / b.test / c.test resolve to one local server
(`network.dns.localDomains`): two hosts are two sites, one port.
THE PRECONDITION IS FIREFOX'S, NOT OURS. Whether a document goes into the back-forward cache is Firefox's decision, taken when the
next navigation starts (nsDocShell::InternalLoad -> Document::CanSavePresentation, CanonicalBrowsingContext::AllowedInBFCache), and
a document that is refused is refused for good: it is loaded again on the way back. What refuses it is anything in flight in the
document's load group at that moment (a dedicated worker's script fetch is one: a worker that has not started yet makes the page
non-restorable, measured 0 of 8 restored when leaving right after `load`, 8 of 8 after one round trip to the worker) and the
page's `pageshow` not yet run (it clears the loading mark). So the test leaves only when every document it holds has had its
`pageshow` and its worker has answered, and a run whose page was still loaded again is not a result of ours: the gesture is
repeated on a fresh browser, up to ATTEMPTS times, and only ATTEMPTS refusals in a row fail, loudly.
"""
from __future__ import annotations
@@ -30,6 +39,20 @@ import pytest
from _servers import LocalServer
#: How many times the whole gesture may be started again because Firefox did not put the page in the cache (see above).
ATTEMPTS = 3
#: More repeated gestures than this in one run of this file and the cache is refusing too often: the run fails, naming them.
MOST_REFUSALS_IN_A_RUN = 2
#: Every refusal of Firefox met by `_until_restored`, in this process, in order.
REFUSALS = []
class _NotRestored(Exception):
"""Firefox loaded the page again instead of restoring it: the precondition of the test, not a verdict on it."""
STRATEGY_1 = {
"fission.autostart": True,
"fission.webContentIsolationStrategy": 1,
@@ -89,8 +112,12 @@ def sites():
"<script>window.__shown = []; addEventListener('pageshow', e => window.__shown.push(e.persisted));"
"</script><iframe id=f src='%s' width=300 height=150></iframe>" % at("b.test", "/frame-worker"))
routes["/other"] = ("text/html", "<!doctype html><title>other</title><p>other")
routes["/top-plain"] = ("text/html", "<!doctype html><title>plain</title>"
"<script>window.__shown = []; addEventListener('pageshow', e => window.__shown.push(e.persisted));"
"</script><p>no worker here")
try:
yield {"top": {"page": at("a.test", "/top-worker")}, "oop-frame": {"page": at("a.test", "/top-frame")},
"plain": at("a.test", "/top-plain"),
"same-site": at("a.test", "/other"), "other-site": at("c.test", "/other")}
finally:
server.shutdown()
@@ -129,6 +156,15 @@ def _index(events, start, method, pred=lambda p: True):
return None
def _wait_cacheable(page):
"""Until every document of the page that records `pageshow` has had it: a document whose `load` handlers are still running,
or whose `pageshow` has not run, is still marked as loading and Firefox will not cache it (Document::OnPageShow clears
the mark). The worker's own start is the round trips the caller made before."""
def shown():
return all(frame.evaluate("(window.__shown || [0]).length >= 1") for frame in page.frames)
assert _wait(shown, 10.0), "a document of the page never ran its pageshow: %r" % [f.url for f in page.frames]
def _ask(page, where):
target = page if where == "top" else next(f for f in page.frames if f.url.endswith("/frame-worker"))
return target.evaluate("window.__ask()")
@@ -141,6 +177,54 @@ def _ask(page, where):
def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(firefox_binary, sites, events, where,
away, how, engine_at_least):
engine_at_least("firefox-62")
def attempt():
del events[:] # the events of this attempt only: the ids and the order are read from them
_gesture(firefox_binary, sites, events, where, away, how)
_until_restored(attempt)
def _until_restored(attempt, attempts=ATTEMPTS, record=None):
"""Run `attempt` until Firefox has put the page in the cache. A verdict of ours (any other failure) ends it at once."""
record = REFUSALS if record is None else record # the unit test of this loop keeps its own: it is not a refusal of Firefox
refused = []
for _ in range(attempts):
try:
attempt()
return
except _NotRestored as why:
refused.append(str(why))
record.append(str(why))
print("\n[bfcache] the page was refused by the cache (%d so far in this run): %s" % (len(record), why))
raise AssertionError(
"Firefox did not put the page in the back-forward cache in %d attempts out of %d, so this test proves nothing: %r"
% (len(refused), attempts, refused))
def test_a_refused_page_is_tried_again_and_only_attempts_refusals_in_a_row_fail():
calls = []
def refused_twice():
calls.append(1)
if len(calls) < ATTEMPTS:
raise _NotRestored("loaded again")
_until_restored(refused_twice, record=[])
assert len(calls) == ATTEMPTS
calls.clear()
with pytest.raises(AssertionError, match="proves nothing"):
_until_restored(lambda: (calls.append(1), (_ for _ in ()).throw(_NotRestored("loaded again"))), record=[])
assert len(calls) == ATTEMPTS
calls.clear() # a verdict of ours is not retried
with pytest.raises(ValueError):
_until_restored(lambda: (calls.append(1), (_ for _ in ()).throw(ValueError("ours"))), record=[])
assert len(calls) == 1
def _gesture(firefox_binary, sites, events, where, away, how):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
@@ -159,6 +243,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
assert _ask(page, where) == 1
assert _ask(page, where) == 2
_wait_cacheable(page)
# 2. the top goes forward: the worker ends for the client, before the new page commits
forward = len(events)
@@ -176,8 +261,8 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
# 3. back from the cache: the same worker, told once, after the restored document's contexts are cleared
back = len(events)
page.go_back(wait_until="load")
assert page.evaluate("window.__shown") == [False, True], (
"the page was loaded again instead of restored from the back-forward cache, so this test proves nothing")
if page.evaluate("window.__shown") != [False, True]:
raise _NotRestored("the page was loaded again instead of restored: __shown = %r" % page.evaluate("window.__shown"))
if not _wait(lambda: _index(events, back, "Page.workerCreated", lambda p: p["workerId"] == wid) is not None):
other = [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated"]
raise AssertionError(("the restored worker was announced under a NEW id %s, not %s: " % (other, wid)
@@ -213,3 +298,59 @@ def _methods(events, start):
for m, p in events[start:] if m.startswith(("Page.worker", "Page.navigationCommitted", "Page.frameDocument",
"Runtime.executionContextsCleared", "Page.frameDetached",
"Page.frameAttached"))]
@pytest.fixture(scope="module", autouse=True)
def the_cache_does_not_refuse_too_often():
"""A repeated gesture hides a refusal of Firefox, and a regression of the cache would hide the same way: so the repeats are
counted over the whole file, printed, and more than MOST_REFUSALS_IN_A_RUN of them fail the run, loudly."""
del REFUSALS[:]
yield
print("\n[bfcache] refusals met in this run: %d (at most %d allowed)" % (len(REFUSALS), MOST_REFUSALS_IN_A_RUN))
assert len(REFUSALS) <= MOST_REFUSALS_IN_A_RUN, (
"the back-forward cache refuses too often: %d gestures had to be repeated in one run (at most %d): %r"
% (len(REFUSALS), MOST_REFUSALS_IN_A_RUN, REFUSALS))
def _leave_and_come_back(page, away_url):
"""Leave the page at once (no wait of any kind) and come back: what the page recorded of its own `pageshow`."""
page.goto(away_url, wait_until="load")
page.go_back(wait_until="load")
return page.evaluate("window.__shown")
@pytest.mark.e2e
def test_a_page_without_a_worker_comes_back_from_the_cache(firefox_binary, sites, engine_at_least):
"""No repeat, no wait: the cache has to take a plain page the moment it has loaded. If the cache breaks, this one says so."""
engine_at_least("firefox-62")
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
headless=True, extra_prefs=STRATEGY_1) as browser:
page = browser.new_context().new_page()
page.set_default_timeout(10000)
page.goto(sites["plain"], wait_until="load")
assert _leave_and_come_back(page, sites["same-site"]) == [False, True], (
"a page with no worker was loaded again instead of restored from the back-forward cache")
@pytest.mark.e2e
def test_a_page_whose_started_worker_is_in_a_frame_of_another_site_comes_back_from_the_cache(firefox_binary, sites, engine_at_least):
"""No repeat: a page with a started worker in a frame of another site (its own process) is taken by the cache. The worker is
asked once first, because a worker that has not started keeps ANY page out of the cache (its script fetch is in the load group:
leaving right after the frame is listed, 0 of 2 restored here). If the cache breaks for pages with frames in other processes,
this one says so."""
engine_at_least("firefox-62")
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
headless=True, extra_prefs=STRATEGY_1) as browser:
page = browser.new_context().new_page()
page.set_default_timeout(10000)
page.goto(sites["oop-frame"]["page"], wait_until="load")
assert _wait(lambda: any(f.url.endswith("/frame-worker") for f in page.frames)), (
"the frame of the worker is not listed with its url: %r" % [f.url for f in page.frames])
assert _ask(page, "oop-frame") == 1
_wait_cacheable(page)
assert _leave_and_come_back(page, sites["same-site"]) == [False, True], (
"a page with a worker in a frame of another site was loaded again instead of restored from the back-forward cache")