tests: the worker/back-forward-cache test writes down what happened before it asserts, holds the cache's two host inputs still, and asserts the worker's contract for the outcome of a goto (restored, or built again)
The e2e of the hunt of 2026-11-12 was red once in 30 runs for [top-other-site-goto] with only 'the page was loaded again'. With the evidence
written before the assertion and the SHIPBFCache log, the cause is Firefox's: for a navigation the PARENT starts (goto, to the same site or another)
the parent's CanonicalBrowsingContext::AllowedInBFCache can find the navigation's own DocumentChannel as the single request of the old document's
loadgroup ('* requests in the loadgroup'): 15 of 56 goto sessions in a container on the candidate, never for the page's own navigation (location).
* the page must be cacheable before the test leaves it (every document has had its pageshow), and the lab fixes browser.sessionhistory.max_total_viewers and
the low-commit-space thresholds so that the memory of the runner does not decide whether the cache holds;
* the evidence (__shown, the type of the navigation entry, the readyState, the protocol events since go_back) is written before the assertion;
* for a goto the test says which outcome happened and asserts the contract of THAT outcome whole: restored (same worker id once, no workerDestroyed, the page's
count), or built again (the old worker ended once before the new commit, exactly one new worker with a new id, the only live one, answering 1);
a restore the engine announced that the page did not see fails in both; the page's own navigation must restore. No repeat, no skip.
Unit tests (no browser): the evidence is written before the assertion and carried by the message, a reload is accepted only for a goto, the lab holds the
two host inputs, the test file has no repeat or skip.
This commit is contained in:
1 parent
b14d1deacd
commit
1d7204ffe6
3 files changed
+264
-3
No files matched your search
@@ -0,0 +1,114 @@
|
||||
"""What a test that expects a page back from the back-forward cache writes down BEFORE it asserts anything, and the wait that leaves it
|
||||
a page the cache can take.
|
||||
|
||||
The test used to read `window.__shown` after `go_back()` and assert on it with nothing else saved: a red said "the page was loaded again" and
|
||||
nobody could tell whether the engine had announced a restore (and the page was loaded again anyway), or Firefox had refused or evicted the page.
|
||||
`read_after_go_back` takes, in one place and before any assertion, what tells them apart:
|
||||
|
||||
* `__shown`: `[False, True]` is a `pageshow` with `persisted` after the first one; `[False]` alone is a document that was built again;
|
||||
* the type of the navigation entry and the `readyState` of the document that answers;
|
||||
* the protocol events since `go_back()`: a restore is announced by the engine with a navigation id that starts with `nav-bfcache-` (and
|
||||
`Page.frameDocumentRestored`); a document that loaded again comes with a `Page.eventFired` `load` and new execution contexts.
|
||||
|
||||
`decide_outcome` writes that down FIRST (stdout, which pytest prints with the failure) and then says which of the two outcomes happened:
|
||||
the page was `restored` from the cache, or the document was built again (`reloaded`). The second is accepted ONLY where Firefox itself may
|
||||
not use the cache: a navigation the PARENT starts (`Page.navigate`, `goto`, to the same site or to another) is checked by the parent against the
|
||||
requests in the old document's loadgroup, and the navigation's own DocumentChannel may still be there when the check runs (measured 2026-11-12,
|
||||
SHIPBFCache log: `AllowedInBFCache` found "requests in the loadgroup" in 15 of 56 goto sessions, never after the page's own navigation). The test then asserts the worker's contract for the outcome that happened, whole, and says which it was.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, List
|
||||
|
||||
#: The navigation id of a restore: Juggler's FrameTree.announceRestoredDocument gives it `nav-bfcache-<n>`; a document loaded again has the id of its load.
|
||||
RESTORE_PREFIX = "nav-bfcache-"
|
||||
|
||||
#: The protocol events that say what the engine did with the document, and the one parameter that names each.
|
||||
_SAID = {
|
||||
"Page.navigationStarted": "navigationId",
|
||||
"Page.navigationCommitted": "navigationId",
|
||||
"Page.eventFired": "name",
|
||||
"Page.frameDocumentRestored": "frameId",
|
||||
"Runtime.executionContextsCleared": None,
|
||||
"Runtime.executionContextCreated": None,
|
||||
"Page.workerCreated": "workerId",
|
||||
"Page.workerDestroyed": "workerId",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Evidence:
|
||||
shown: object
|
||||
navigation_type: object
|
||||
ready_state: object
|
||||
events: List[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def restored(self) -> bool:
|
||||
return self.shown == [False, True]
|
||||
|
||||
@property
|
||||
def engine_announced_a_restore(self) -> bool:
|
||||
return any(e.startswith("Page.navigationCommitted " + RESTORE_PREFIX) for e in self.events)
|
||||
|
||||
def text(self) -> str:
|
||||
return ("[bfcache] after go_back: __shown=%r navigation entry type=%r readyState=%r; the engine announced a restore: %s; events: %s"
|
||||
% (self.shown, self.navigation_type, self.ready_state, "yes" if self.engine_announced_a_restore else "no",
|
||||
self.events))
|
||||
|
||||
def why_not(self) -> str:
|
||||
if self.engine_announced_a_restore:
|
||||
return ("the engine announced a restore (%s...) but the page did not run a pageshow with persisted after its first one"
|
||||
% RESTORE_PREFIX)
|
||||
return ("the page was built again instead of restored from the back-forward cache (no restore was announced by the engine), "
|
||||
"so this test proves nothing")
|
||||
|
||||
|
||||
def summarize_events(events, start: int) -> List[str]:
|
||||
"""The events since ``start`` that say what became of the document, one short string each, in order."""
|
||||
said = []
|
||||
for method, params in events[start:]:
|
||||
if method not in _SAID:
|
||||
continue
|
||||
key = _SAID[method]
|
||||
said.append(method if key is None else "%s %s" % (method, params.get(key)) + (
|
||||
" %s" % params.get("url") if method == "Page.navigationCommitted" else ""))
|
||||
return said
|
||||
|
||||
|
||||
def read_after_go_back(page, events, start: int) -> Evidence:
|
||||
"""Everything the test knows right after ``go_back()``, taken before any assertion."""
|
||||
return Evidence(
|
||||
shown=page.evaluate("window.__shown"),
|
||||
navigation_type=page.evaluate("() => { const e = performance.getEntriesByType('navigation')[0]; return e ? e.type : null; }"),
|
||||
ready_state=page.evaluate("document.readyState"),
|
||||
events=summarize_events(events, start),
|
||||
)
|
||||
|
||||
|
||||
def decide_outcome(evidence: Evidence, may_reload: bool, write: Callable[[str], None] = print) -> str:
|
||||
"""Write the evidence down (always, first), then say what happened: ``"restored"``, or ``"reloaded"`` when the document was built again
|
||||
and ``may_reload`` (the case where Firefox may refuse the cache); anything else fails, naming why and carrying the evidence. A restore
|
||||
the engine announced that the page did not see fails even where a reload is accepted: that is a defect of ours, not of the cache."""
|
||||
outcome = "restored" if evidence.restored else (
|
||||
"reloaded" if may_reload and not evidence.engine_announced_a_restore else "failed")
|
||||
write(evidence.text() + " => outcome: " + outcome)
|
||||
assert outcome != "failed", "%s: %s" % (evidence.why_not(), evidence.text())
|
||||
return outcome
|
||||
|
||||
|
||||
def wait_cacheable(page, seconds: float = 10.0) -> None:
|
||||
"""Until every document of the page that records `pageshow` has had it. A document whose `pageshow` has not run is still marked as
|
||||
loading and Firefox will not cache it (Document::OnPageShow clears the mark): the lab does not leave before that, however slow the
|
||||
machine is. The worker has started and answered before this: the callers asked it twice."""
|
||||
def shown() -> bool:
|
||||
return all(frame.evaluate("(window.__shown || [0]).length >= 1") for frame in page.frames)
|
||||
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if shown():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
assert shown(), "a document of the page never ran its pageshow: %r" % [f.url for f in page.frames]
|
||||
@@ -28,6 +28,7 @@ from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _bfcache_evidence import decide_outcome, read_after_go_back, wait_cacheable
|
||||
from _servers import LocalServer
|
||||
|
||||
STRATEGY_1 = {
|
||||
@@ -37,6 +38,21 @@ STRATEGY_1 = {
|
||||
"network.dns.localDomains": "a.test,b.test,c.test",
|
||||
}
|
||||
|
||||
# The lab holds still the two things of the HOST that decide whether a page the cache took is still there when the test goes back, so that the
|
||||
# memory of the runner does not decide whether the cache holds (a red then would say something about the machine, not about the engine):
|
||||
# * how many pages the cache keeps: by default `nsSHistory` computes it from the PHYSICAL memory of the machine (at most 8; nsSHistory.cpp
|
||||
# CalcMaxTotalViewers), here it is 8;
|
||||
# * the low-memory watcher: on Linux Firefox reads /proc/meminfo every second and, when what is available is under 5% of the total or under 200 MB,
|
||||
# sends memory-pressure, which evicts EVERY page of the cache (AvailableMemoryWatcherLinux.cpp, nsSHistory.cpp). Both thresholds at 0 here
|
||||
# (they are static prefs; the percent one exists on Linux only and is ignored elsewhere).
|
||||
# Nothing of this is in the product: a user's Firefox keeps both defaults, and so does ours.
|
||||
LAB_PREFS = {
|
||||
**STRATEGY_1,
|
||||
"browser.sessionhistory.max_total_viewers": 8,
|
||||
"browser.low_commit_space_threshold_percent": 0,
|
||||
"browser.low_commit_space_threshold_mb": 0,
|
||||
}
|
||||
|
||||
# What a document with a worker runs: the worker answers every message with its count.
|
||||
OWNER = """<script>
|
||||
window.__shown = [];
|
||||
@@ -144,7 +160,7 @@ def test_a_worker_leaves_with_its_page_for_the_cache_and_comes_back_the_same(fir
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False,
|
||||
headless=True, extra_prefs=STRATEGY_1) as browser:
|
||||
headless=True, extra_prefs=LAB_PREFS) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_default_timeout(10000)
|
||||
page.goto(sites[where]["page"], wait_until="load")
|
||||
@@ -159,6 +175,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) # the cache takes a page only after the `pageshow` of every document of it, however slow the machine is
|
||||
|
||||
# 2. the top goes forward: the worker ends for the client, before the new page commits
|
||||
forward = len(events)
|
||||
@@ -176,8 +193,14 @@ 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")
|
||||
# What it knows is written down BEFORE anything is asserted. A goto is started by the PARENT and Firefox may refuse the cache for it,
|
||||
# to the same site or to another (measured: the navigation's own channel is still in the old document's loadgroup when the parent
|
||||
# checks: SHIPBFCache log, CanonicalBrowsingContext::AllowedInBFCache); then the document is built again and the contract is the one
|
||||
# of a new page, asserted whole. The page's own navigation (`location`) is never refused: a restore is required there.
|
||||
outcome = decide_outcome(read_after_go_back(page, events, back), may_reload=(how == "goto"))
|
||||
if outcome == "reloaded":
|
||||
_assert_a_new_page_with_a_new_worker(page, events, where, wid, back)
|
||||
return
|
||||
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 +236,27 @@ 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"))]
|
||||
|
||||
|
||||
def _assert_a_new_page_with_a_new_worker(page, events, where, old, back):
|
||||
"""The document was built again after go_back (the cache was not used): the contract of a page that loads. The old worker has been told
|
||||
ended once (asserted before), ONE new worker is announced with a NEW id, it is not told ended, it is the only live one, and it is a fresh
|
||||
worker (it answers 1)."""
|
||||
def created():
|
||||
return [p["workerId"] for m, p in events[back:] if m == "Page.workerCreated" and p["url"].endswith("/worker.js")]
|
||||
|
||||
assert _wait(lambda: bool(created())), "the page built again did not announce its worker: %r" % _methods(events, back)
|
||||
time.sleep(1.0) # what comes in excess comes now
|
||||
new = created()
|
||||
assert len(new) == 1 and new[0] != old, "expected one NEW worker, got %r (the old one was %s): %r" % (new, old, _methods(events, back))
|
||||
assert not [p for m, p in events[back:] if m == "Page.workerDestroyed" and p["workerId"] == new[0]], (
|
||||
"the new worker was told ended: %r" % _methods(events, back))
|
||||
live = {}
|
||||
for m, p in events:
|
||||
if m == "Page.workerCreated":
|
||||
live[p["workerId"]] = p
|
||||
elif m == "Page.workerDestroyed":
|
||||
live.pop(p["workerId"], None)
|
||||
assert list(live) == [new[0]], "live workers after the page was built again: %r" % list(live.values())
|
||||
assert _wait(lambda: where == "top" or any(f.url.endswith("/frame-worker") for f in page.frames)), "the frame of the new page is missing"
|
||||
assert _ask(page, where) == 1, "the worker of the page built again is not a fresh worker"
|
||||
@@ -0,0 +1,100 @@
|
||||
"""The back-forward-cache test writes down what it knows BEFORE it asserts, and the lab holds the host's two inputs of the cache still. No browser.
|
||||
|
||||
A red of tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py used to be the single sentence "the page was loaded again instead of
|
||||
restored from the back-forward cache" (hunt of 2026-11-12, one run of 15, [top-other-site-goto]) and nothing else was left of the run, so nobody could say whether the
|
||||
engine had announced a restore, or Firefox had refused or evicted the page. These tests hold what that red now carries, and that the lab no
|
||||
longer lets the memory of the machine decide whether the cache holds.
|
||||
"""
|
||||
import _bfcache_evidence as bfc
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
RESTORED = [("Page.navigationStarted", {"navigationId": "nav-bfcache-1"}),
|
||||
("Page.navigationCommitted", {"navigationId": "nav-bfcache-1", "url": "http://a.test:1/top-worker"}),
|
||||
("Runtime.executionContextsCleared", {}),
|
||||
("Page.frameDocumentRestored", {"frameId": "f1"}),
|
||||
("Page.workerCreated", {"workerId": "w1"}),
|
||||
("Page.eventFired", {"name": "pageshow"})]
|
||||
LOADED_AGAIN = [("Page.navigationStarted", {"navigationId": "nav-7"}),
|
||||
("Page.navigationCommitted", {"navigationId": "nav-7", "url": "http://a.test:1/top-worker"}),
|
||||
("Runtime.executionContextsCleared", {}),
|
||||
("Page.eventFired", {"name": "load"}),
|
||||
("Page.workerCreated", {"workerId": "w2"})]
|
||||
|
||||
|
||||
class _Page:
|
||||
def __init__(self, shown, entry="back_forward", state="complete"):
|
||||
self._answers = [shown, entry, state]
|
||||
|
||||
def evaluate(self, expression):
|
||||
return self._answers.pop(0)
|
||||
|
||||
|
||||
def test_the_evidence_is_read_from_the_page_and_the_events_since_go_back():
|
||||
prefix = [("Page.workerCreated", {"workerId": "old"})] # before go_back: not part of the evidence
|
||||
ev = bfc.read_after_go_back(_Page([False, True]), prefix + RESTORED, len(prefix))
|
||||
assert ev.restored and ev.engine_announced_a_restore
|
||||
assert ev.navigation_type == "back_forward" and ev.ready_state == "complete"
|
||||
assert ev.events == ["Page.navigationStarted nav-bfcache-1",
|
||||
"Page.navigationCommitted nav-bfcache-1 http://a.test:1/top-worker",
|
||||
"Runtime.executionContextsCleared", "Page.frameDocumentRestored f1", "Page.workerCreated w1",
|
||||
"Page.eventFired pageshow"]
|
||||
|
||||
|
||||
def test_a_red_writes_the_evidence_down_before_it_asserts_and_the_message_carries_it():
|
||||
written = []
|
||||
ev = bfc.read_after_go_back(_Page([False]), LOADED_AGAIN, 0)
|
||||
with pytest.raises(AssertionError) as red:
|
||||
bfc.decide_outcome(ev, False, written.append)
|
||||
assert len(written) == 1, "the evidence was not written before the assertion"
|
||||
assert "__shown=[False]" in written[0] and "the engine announced a restore: no" in written[0] and "outcome: failed" in written[0]
|
||||
assert "Page.eventFired load" in written[0] and "nav-7" in written[0]
|
||||
assert "built again instead of restored" in str(red.value) and ev.text() in str(red.value) and written[0].startswith(ev.text())
|
||||
|
||||
|
||||
def test_a_restore_the_engine_announced_but_the_page_did_not_see_is_a_defect_even_where_a_reload_is_accepted():
|
||||
ev = bfc.read_after_go_back(_Page([False]), RESTORED, 0)
|
||||
assert ev.engine_announced_a_restore and not ev.restored
|
||||
for may_reload in (False, True):
|
||||
with pytest.raises(AssertionError) as red:
|
||||
bfc.decide_outcome(ev, may_reload, lambda _line: None)
|
||||
assert "the engine announced a restore" in str(red.value) and "pageshow with persisted" in str(red.value)
|
||||
|
||||
|
||||
def test_a_restored_page_is_said_restored_and_written_down_too():
|
||||
written = []
|
||||
assert bfc.decide_outcome(bfc.read_after_go_back(_Page([False, True]), RESTORED, 0), False, written.append) == "restored"
|
||||
assert len(written) == 1 and "__shown=[False, True]" in written[0] and "outcome: restored" in written[0]
|
||||
assert bfc.decide_outcome(bfc.read_after_go_back(_Page([False, True]), RESTORED, 0), True, lambda _l: None) == "restored"
|
||||
|
||||
|
||||
def test_a_document_built_again_is_said_reloaded_only_where_firefox_may_refuse_the_cache():
|
||||
written = []
|
||||
ev = bfc.read_after_go_back(_Page([False]), LOADED_AGAIN, 0)
|
||||
assert bfc.decide_outcome(ev, True, written.append) == "reloaded"
|
||||
assert "outcome: reloaded" in written[0]
|
||||
with pytest.raises(AssertionError):
|
||||
bfc.decide_outcome(ev, False, lambda _l: None)
|
||||
|
||||
|
||||
def test_the_lab_holds_the_two_host_inputs_of_the_cache_still():
|
||||
import test_a_worker_comes_back_with_its_page_from_the_cache_e2e as e2e
|
||||
|
||||
prefs = e2e.LAB_PREFS
|
||||
assert prefs["browser.sessionhistory.max_total_viewers"] == 8
|
||||
assert prefs["browser.low_commit_space_threshold_percent"] == 0 and prefs["browser.low_commit_space_threshold_mb"] == 0
|
||||
assert all(prefs[k] == v for k, v in e2e.STRATEGY_1.items()), "the lab's prefs are the strategy's plus the two"
|
||||
|
||||
|
||||
def test_the_test_has_no_repeat_no_skip_and_asks_for_the_evidence_and_the_cacheable_page():
|
||||
import pathlib
|
||||
|
||||
source = (pathlib.Path(__file__).resolve().parent.parent / "test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py").read_text("utf-8")
|
||||
for word in ("ATTEMPTS", "REFUSALS", "_NotRestored", "pytest.skip", "pytest.xfail", "reruns", "flaky"):
|
||||
assert word not in source, "%s: a refusal of the cache is a red with its evidence, never a repeat or a skip" % word
|
||||
assert "extra_prefs=LAB_PREFS" in source
|
||||
assert source.index("wait_cacheable(page)") < source.index("page.go_back("), "the page must be cacheable before the test leaves it"
|
||||
assert source.index("decide_outcome(") < source.index("Page.workerCreated", source.index("decide_outcome(")), \
|
||||
"the evidence is read and written before anything is asserted about the worker"
|
||||
assert 'may_reload=(how == "goto")' in source, "a reload is accepted for a navigation the parent starts (goto) and for nothing else"
|
||||
Reference in new issue
Block a user