Remove scripts that no test round runs
- scripts/check_unresolved_names.py: replaced by the ruff F821/F811/F601 step in .github/workflows/tests.yml. - scripts/bench_transport.py: one-off measurement that asserts nothing. - scripts/diff_protocol.py: needs the Node driver arm, which was removed. - scripts/judge_both_transports.py: needs the Node driver arm, which was removed. - tests/gates/prefs_byte_parity.py: compares with the removed driver's prefs writer. - tests/gates/driver_prefs_rules.json: frozen rules for that comparison, nothing else reads it. References to these files in comments, docstrings and THIRD_PARTY_FORK.md are reworded.
This commit is contained in:
1 parent
9d217c4911
commit
8d48c4a472
15 files changed
+24
-1171
No files matched your search
@@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- Comments, the fork notes and one test message no longer point at scripts that were deleted with this change (the transport
|
||||
comparison scripts and the prefs byte-parity gate: no round ran them). No behaviour changes.
|
||||
|
||||
## [0.52.0] - 2026-11-14
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
"""How much does answering the protocol IN PROCESS actually cost?
|
||||
|
||||
⛔ THE QUESTION IS NARROW ON PURPOSE. Not "is the Python path faster than the
|
||||
Node driver" - that comparison is dominated by the browser and would answer a
|
||||
different question. This measures ONLY the machinery this package adds between
|
||||
`Channel.send` and the code that talks to Juggler: building the message dict,
|
||||
the queue, the worker-thread hop, the reply, and `call_soon_threadsafe` back
|
||||
onto the loop.
|
||||
|
||||
That is the thing the owner asked about on 2026-08-28: inside one process,
|
||||
serialising to yourself looks like waste. Whether it IS waste depends on how it
|
||||
compares to the round trip it wraps, and this project decides that kind of
|
||||
question with a number.
|
||||
|
||||
⛔ NO BROWSER, and that is what makes this trustworthy. A fake server answers
|
||||
instantly, so what is left in the measurement is the transport and nothing
|
||||
else. It also means the result does not depend on the machine being quiet in
|
||||
the way a browser measurement does - though a loaded machine still widens the
|
||||
tail, which is why the median is reported next to the mean.
|
||||
|
||||
python scripts/bench_transport.py
|
||||
python scripts/bench_transport.py --giri 20000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import pathlib
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
|
||||
#: What a real Juggler round trip costs, measured on 2026-08-27 with the
|
||||
#: shipped binary. It is the denominator: the transport's cost only means
|
||||
#: something as a fraction of the work it wraps.
|
||||
#: ⛔ `Runtime.evaluate("1")` and NOT `Heap.collectGarbage`, which was used once
|
||||
#: as a "bare command" and actually collects garbage - 26,8 ms of browser work
|
||||
#: attributed to the transport.
|
||||
JUGGLER_ROUND_TRIP_MS = 2.4
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""Answers instantly, so only the transport is being timed."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.transport = None
|
||||
|
||||
def attach(self, transport) -> None:
|
||||
self.transport = transport
|
||||
|
||||
def shutdown(self) -> None:
|
||||
pass
|
||||
|
||||
def handle(self, message):
|
||||
return {"value": message["params"].get("n")}
|
||||
|
||||
|
||||
async def run(rounds: int) -> int:
|
||||
from invisible_playwright._juggler.transport import InProcessTransport
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
transport = InProcessTransport(loop, FakeServer())
|
||||
await transport.connect()
|
||||
|
||||
pending = {}
|
||||
|
||||
def on_message(message):
|
||||
future = pending.pop(message.get("id"), None)
|
||||
if future is not None and not future.done():
|
||||
future.set_result(message)
|
||||
|
||||
transport.on_message = on_message
|
||||
|
||||
async def one(index: int):
|
||||
future = loop.create_future()
|
||||
pending[index] = future
|
||||
transport.send({"id": index, "guid": "x", "method": "noop",
|
||||
"params": {"n": index},
|
||||
"metadata": {"apiName": "bench"}})
|
||||
return await future
|
||||
|
||||
# ⛔ A warm-up that is DISCARDED: the first calls pay for thread start-up
|
||||
# and for the first allocation of every structure, and folding those into
|
||||
# the average is how a microbenchmark reports a number nobody can reproduce.
|
||||
for i in range(200):
|
||||
await one(i)
|
||||
|
||||
samples = []
|
||||
for i in range(rounds):
|
||||
start = time.perf_counter()
|
||||
await one(200 + i)
|
||||
samples.append((time.perf_counter() - start) * 1000.0)
|
||||
|
||||
transport.request_stop()
|
||||
await transport.wait_until_stopped()
|
||||
|
||||
samples.sort()
|
||||
media = statistics.fmean(samples)
|
||||
mediana = samples[len(samples) // 2]
|
||||
p95 = samples[int(len(samples) * 0.95)]
|
||||
print("giri utili %d" % len(samples))
|
||||
print("media %.4f ms" % media)
|
||||
print("mediana %.4f ms" % mediana)
|
||||
print("p95 %.4f ms" % p95)
|
||||
print("p99 %.4f ms" % samples[int(len(samples) * 0.99)])
|
||||
print()
|
||||
print("un giro Juggler vero %.2f ms (misurato 2026-08-27)"
|
||||
% JUGGLER_ROUND_TRIP_MS)
|
||||
quota = 100.0 * mediana / JUGGLER_ROUND_TRIP_MS
|
||||
print("il transport pesa %.1f%% di una chiamata vera" % quota)
|
||||
print()
|
||||
if quota < 10:
|
||||
print("VERDETTO: il transport NON e' il costo. Togliere thread e coda "
|
||||
"andrebbe fatto per semplicita', se mai, non per velocita'.")
|
||||
else:
|
||||
print("VERDETTO: il transport pesa abbastanza da giustificare il "
|
||||
"refactor asincrono.")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--giri", type=int, default=5000)
|
||||
a = p.parse_args()
|
||||
return asyncio.run(run(a.giri))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -100,8 +100,8 @@ def _classes(tree: ast.AST) -> dict:
|
||||
#: next step. The failure it would cause is silent and backwards: an `async
|
||||
#: def` operation is absent from `_methods`, so `reachable` returns an EMPTY
|
||||
#: known-set for it, and every field that operation legitimately reads gets
|
||||
#: reported as ignored. Same tuple as `check_unresolved_names.py`'s
|
||||
#: `_FUNCTIONS`, for the same reason.
|
||||
#: reported as ignored. Both function kinds are listed for the same reason as in any
|
||||
#: AST walk over operations.
|
||||
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
"""A method that uses a name it never has: the NameError nobody ran into yet.
|
||||
|
||||
⛔ IT CAUGHT TWO REAL DEFECTS THE MOMENT IT WAS WRITTEN, both of the same shape
|
||||
and both invisible to every other check in this repo:
|
||||
|
||||
* `Actions._set_checked` passed `frame_id` to its retry loop without ever
|
||||
taking it as a parameter, while `check()` and `uncheck()` accepted the
|
||||
argument and dropped it. Every `page.check()` on the Python transport died
|
||||
with `Page.check: name 'frame_id' is not defined` - and the transport judge
|
||||
reported it as an ENGINE defect, because the test that exercises it pins the
|
||||
transport itself and therefore fails identically on both arms.
|
||||
* `Actions.drag_and_drop` did the same thing twice in one function.
|
||||
|
||||
⛔ WHY THE SUITE DID NOT SEE IT. A `NameError` inside a method is not a syntax
|
||||
error and not an import error: the module loads, the class builds, the name
|
||||
resolves at CALL time. So the whole file is green until somebody calls that one
|
||||
method, and the two above sat in a package with 500 passing tests.
|
||||
|
||||
**What it does NOT do.** It does not type-check, it does not follow
|
||||
`globals()`, `exec`, or a name injected by a decorator, and it deliberately
|
||||
treats every module-level assignment and import as available. The question it
|
||||
asks is the narrowest one that catches this: *does this function use a bare
|
||||
name that is neither its parameter, nor assigned in it, nor defined at module
|
||||
level?*
|
||||
|
||||
python scripts/check_unresolved_names.py
|
||||
python scripts/check_unresolved_names.py --selftest
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import builtins
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
#: ⛔ `scripts/` IS IN THE PERIMETER SINCE 2026-08-29, and leaving it out was
|
||||
#: not a scoping decision - it was a hole this gate exists to close. On that
|
||||
#: date `upstream_baseline.py:_per_file` was found returning `1 if morti else
|
||||
#: 0` with `morti` assigned nowhere: a guaranteed NameError, sitting in the
|
||||
#: repository, while this gate reported "none in 102 file(s)". Pointed at that
|
||||
#: one file by hand it named the fault correctly, so the LOGIC was never
|
||||
#: wrong; only the perimeter was.
|
||||
#:
|
||||
#: And the argument for scanning `scripts/` is STRONGER than for the package,
|
||||
#: not weaker. The reason this class of defect survives is that a NameError
|
||||
#: inside a function is invisible until someone calls it - and the package has
|
||||
#: 529 unit tests calling into it, while these scripts have none. `_per_file`
|
||||
#: is reached only by `--per-file`, on the async arm, forty minutes into a run
|
||||
#: nobody makes twice.
|
||||
#:
|
||||
#: Measured before widening: 22 files, zero findings besides the real one - so
|
||||
#: this costs no false positives to keep.
|
||||
SCANNED = [ROOT / "src" / "invisible_playwright", ROOT / "scripts"]
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
|
||||
def _module_names(tree: ast.AST) -> set:
|
||||
known = {n.name for n in ast.walk(tree)
|
||||
if isinstance(n, _FUNCTIONS + (ast.ClassDef,))}
|
||||
known |= {t.id for n in ast.walk(tree) if isinstance(n, ast.Assign)
|
||||
for t in n.targets if isinstance(t, ast.Name)}
|
||||
known |= {n.target.id for n in ast.walk(tree)
|
||||
if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)}
|
||||
known |= {a.asname or a.name.split(".")[0]
|
||||
for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))
|
||||
for a in n.names}
|
||||
# ⛔ THE MODULE DUNDERS, which are not builtins and are not imports:
|
||||
# Python puts them in the module namespace itself. They only became
|
||||
# reachable when this gate started walking module-level functions, and
|
||||
# `__file__` in a plain function is the commonest of them by far - it was
|
||||
# the first false positive the widening produced.
|
||||
known |= {"__file__", "__name__", "__doc__", "__package__", "__spec__",
|
||||
"__loader__", "__builtins__", "__path__"}
|
||||
return known | set(dir(builtins))
|
||||
|
||||
|
||||
def _bound_in(fn: ast.AST) -> set:
|
||||
"""Every name that exists inside this function by the time it runs.
|
||||
|
||||
⛔ Nested functions and lambdas contribute their PARAMETERS, because the
|
||||
outer body legitimately refers to them; comprehension targets and `except
|
||||
... as` names too. Leaving any of those out turns ordinary code into a
|
||||
fault, and a check that cries wolf is switched off after the third time.
|
||||
"""
|
||||
args = fn.args
|
||||
bound = {a.arg for a in list(args.args) + list(args.kwonlyargs)
|
||||
+ list(getattr(args, "posonlyargs", []))}
|
||||
if args.vararg:
|
||||
bound.add(args.vararg.arg)
|
||||
if args.kwarg:
|
||||
bound.add(args.kwarg.arg)
|
||||
for n in ast.walk(fn):
|
||||
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
|
||||
bound.add(n.id)
|
||||
elif isinstance(n, _FUNCTIONS + (ast.Lambda,)) and n is not fn:
|
||||
inner = n.args
|
||||
for a in (list(inner.args) + list(inner.kwonlyargs)
|
||||
+ list(getattr(inner, "posonlyargs", []))):
|
||||
bound.add(a.arg)
|
||||
# ⛔ `*args` and `**kw` OF THE NESTED FUNCTION TOO. Leaving these
|
||||
# out is not a small gap: the first run of this checker over the
|
||||
# real package reported 10 faults and every one of them was this -
|
||||
# `def patched(**kw)` inside a wrapper, which is the single most
|
||||
# common shape in the file it was scanning. A checker that is
|
||||
# wrong ten times out of ten teaches people to ignore it, and the
|
||||
# two REAL defects it had just found would have been ignored with
|
||||
# the rest.
|
||||
if inner.vararg:
|
||||
bound.add(inner.vararg.arg)
|
||||
if inner.kwarg:
|
||||
bound.add(inner.kwarg.arg)
|
||||
if not isinstance(n, ast.Lambda):
|
||||
bound.add(n.name)
|
||||
elif isinstance(n, ast.comprehension):
|
||||
for t in ast.walk(n.target):
|
||||
if isinstance(t, ast.Name):
|
||||
bound.add(t.id)
|
||||
elif isinstance(n, ast.ExceptHandler) and n.name:
|
||||
bound.add(n.name)
|
||||
elif isinstance(n, ast.Global):
|
||||
bound.update(n.names)
|
||||
elif isinstance(n, ast.Nonlocal):
|
||||
bound.update(n.names)
|
||||
return bound
|
||||
|
||||
|
||||
def unresolved(source: str, where: str = "<source>") -> list:
|
||||
tree = ast.parse(source)
|
||||
known = _module_names(tree)
|
||||
out = []
|
||||
|
||||
def scan(fn, owner):
|
||||
bound = _bound_in(fn)
|
||||
for n in ast.walk(fn):
|
||||
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load):
|
||||
if n.id not in bound and n.id not in known:
|
||||
out.append((where, owner, fn.name, n.id, n.lineno))
|
||||
|
||||
for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
|
||||
for fn in [n for n in cls.body if isinstance(n, _FUNCTIONS)]:
|
||||
scan(fn, cls.name)
|
||||
# ⛔ MODULE-LEVEL FUNCTIONS TOO, and they were invisible until
|
||||
# 2026-08-29. This gate was written against a file of dispatcher classes,
|
||||
# so it walked classes and nothing else; a plain function was never looked
|
||||
# at. It cost a real defect the day a refactor moved seventeen leaf helpers
|
||||
# into two new modules with no classes at all: one of them used `json`
|
||||
# without importing it, this gate reported "none in 103 files", and the
|
||||
# failure surfaced as a NameError out of one test - which is the exact
|
||||
# shape it exists to catch before a caller does.
|
||||
for fn in [n for n in tree.body if isinstance(n, _FUNCTIONS)]:
|
||||
scan(fn, "<module>")
|
||||
return out
|
||||
|
||||
|
||||
SELFTEST = [
|
||||
("the defect itself: used, never taken",
|
||||
"class A:\n def op(self, x):\n return self.go(frame_id)\n", 1),
|
||||
("a parameter is not a fault",
|
||||
"class A:\n def op(self, frame_id):\n return frame_id\n", 0),
|
||||
("a keyword-only parameter is not a fault",
|
||||
"class A:\n def op(self, *, frame_id=None):\n return frame_id\n", 0),
|
||||
("something assigned in the body is not a fault",
|
||||
"class A:\n def op(self):\n v = 1\n return v\n", 0),
|
||||
("a module-level name is not a fault",
|
||||
"H = 1\nclass A:\n def op(self):\n return H\n", 0),
|
||||
("a MODULE-LEVEL FUNCTION using a name nobody imported",
|
||||
"def helper(x):\n return json.dumps(x)\n", 1),
|
||||
("the same module-level function with the import present",
|
||||
"import json\ndef helper(x):\n return json.dumps(x)\n", 0),
|
||||
("__file__ in a module-level function is not a fault",
|
||||
"def where():\n return __file__\n", 0),
|
||||
("an import is not a fault",
|
||||
"import json\nclass A:\n def op(self):\n return json\n", 0),
|
||||
("a builtin is not a fault",
|
||||
"class A:\n def op(self):\n return len([])\n", 0),
|
||||
("a nested function's parameter is not a fault",
|
||||
"class A:\n def op(self):\n def run(p):\n return p\n"
|
||||
" return run\n", 0),
|
||||
("a comprehension target is not a fault",
|
||||
"class A:\n def op(self):\n return [i for i in range(3)]\n", 0),
|
||||
("an except-as name is not a fault",
|
||||
"class A:\n def op(self):\n try:\n pass\n"
|
||||
" except ValueError as e:\n return e\n", 0),
|
||||
("two in one function are both reported",
|
||||
"class A:\n def op(self):\n return (a_missing, b_missing)\n", 2),
|
||||
# ⛔ The two below are the shape that produced 10 false alarms on the first
|
||||
# real run. They are here so the next person who tightens `_bound_in` finds
|
||||
# out immediately instead of from a wall of noise.
|
||||
("a nested function's **kwargs is not a fault",
|
||||
"class A:\n def op(self):\n def patched(**kw):\n"
|
||||
" return kw\n return patched\n", 0),
|
||||
("a lambda's *args is not a fault",
|
||||
"class A:\n def op(self):\n return lambda *args: args\n", 0),
|
||||
]
|
||||
|
||||
|
||||
def selftest() -> int:
|
||||
bad = 0
|
||||
for name, source, expected in SELFTEST:
|
||||
got = len(unresolved(source))
|
||||
ok = got == expected
|
||||
bad += 0 if ok else 1
|
||||
print(" %-48s %s (%d, expected %d)"
|
||||
% (name, "ok" if ok else "BROKEN", got, expected))
|
||||
print("selftest: %d cases, %d broken" % (len(SELFTEST), bad))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--selftest", action="store_true")
|
||||
p.add_argument("paths", nargs="*",
|
||||
help="default: the package's own source, plus scripts/")
|
||||
a = p.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
|
||||
files = ([pathlib.Path(x) for x in a.paths]
|
||||
or sorted(f for root in SCANNED for f in root.rglob("*.py")))
|
||||
faults = []
|
||||
for f in files:
|
||||
try:
|
||||
faults += unresolved(f.read_text(encoding="utf-8"), str(f))
|
||||
except SyntaxError as bad:
|
||||
print(" %s: cannot be parsed (%s)" % (f, bad))
|
||||
return 2
|
||||
for where, cls, fn, name, line in faults:
|
||||
print(" %s :: %s.%s uses %r at line %d and never has it"
|
||||
% (pathlib.Path(where).name, cls, fn, name, line))
|
||||
if faults:
|
||||
print("UNRESOLVED NAMES: %d. Each one is a NameError waiting for the "
|
||||
"first caller of that method." % len(faults))
|
||||
return 1
|
||||
print("UNRESOLVED NAMES: none in %d file(s)." % len(files))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,318 +0,0 @@
|
||||
"""Do the two servers receive the same thing, and answer the same thing?
|
||||
|
||||
⛔ THIS IS THE QUESTION THAT DECIDES WHETHER THE NODE DRIVER CAN BE DELETED, and
|
||||
it is not the same question `judge_both_transports.py` answers. That one runs
|
||||
tests and reports which arm goes red - a behavioural check, and a coarse one: a
|
||||
field the client does not happen to read today is missing in complete silence,
|
||||
and shows up as a bug months later in a code path nobody exercised. This one
|
||||
compares the WIRE.
|
||||
|
||||
**What it compares, and why at this level.**
|
||||
|
||||
* **input**: every method the client SENDS, and the set of PARAMETER NAMES it
|
||||
sends with each. Both servers must accept the same vocabulary. A method
|
||||
present on one side and absent on the other is a hole; a method present on
|
||||
both but reached with different fields means the client is being driven
|
||||
differently, which makes the rest of the comparison meaningless.
|
||||
* **output**: every object TYPE the server creates, and the set of INITIALIZER
|
||||
FIELD NAMES for each; plus every EVENT name the server emits, per type. This
|
||||
is the half that reading `_impl` cannot give you: it tells you which fields
|
||||
are CONSUMED today, never which are SENT, and the difference is exactly the
|
||||
set a future code path will want.
|
||||
|
||||
⛔ **FIELD NAMES, NOT VALUES.** guids are allocated by whoever allocates them,
|
||||
ports are ephemeral, versions and build ids differ by construction. Comparing
|
||||
values would drown the real differences in noise that is not a difference at
|
||||
all. Where a VALUE matters it belongs in a test, not here.
|
||||
|
||||
⛔ **AND IT RUNS THE SAME SESSION TWICE, IN TWO SUBPROCESSES.** The transport is
|
||||
chosen once, at import time, from the environment: two transports in one process
|
||||
would mean one of the two arms was not the thing it claims to be.
|
||||
|
||||
python scripts/diff_protocol.py <firefox-binary>
|
||||
python scripts/diff_protocol.py <firefox-binary> --keep (leave the traces)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
#: Fields whose ABSENCE on one side is not a finding, because the two paths
|
||||
#: legitimately disagree about them. Kept short and each one argued: a long
|
||||
#: list here is how a comparison stops comparing.
|
||||
EXPECTED_DIFFERENCES = {
|
||||
# The driver reports the bundled Playwright's version string; we report the
|
||||
# engine's. Neither is wrong and no client behaviour depends on the text.
|
||||
("Playwright", "initializer", "preLaunchedBrowser"),
|
||||
# ⛔ `previewUpdated` is a REAL gap, listed here because it is argued and
|
||||
# not because it is small. The driver pushes a new preview string every
|
||||
# time a handle's value changes, and `_js_handle.py` does listen for it -
|
||||
# so on this server `repr(handle)` keeps the preview it was born with.
|
||||
# That is the whole consequence: it reaches error messages and the REPL,
|
||||
# never a page, never a decision, never a byte on the wire. Implementing it
|
||||
# would mean re-serialising every handle after every evaluation, which is
|
||||
# protocol traffic and parent-process work for a string a human reads.
|
||||
# If it ever stops being cosmetic - a client that BRANCHES on the preview -
|
||||
# this line is where to start.
|
||||
("ElementHandle", "event", "previewUpdated"),
|
||||
("JSHandle", "event", "previewUpdated"),
|
||||
}
|
||||
|
||||
|
||||
#: A checkout that still carries the Node driver, for the day this one does not.
|
||||
#: Same contract and same reason as in `judge_both_transports.py`: a worktree,
|
||||
#: not an installed release, because a published wrapper pins a published core
|
||||
#: and a sealed engine and cannot drive a locally built binary.
|
||||
#:
|
||||
#: git worktree add /tmp/judge <the last commit that carried _driver/>
|
||||
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/diff_protocol.py <binary>
|
||||
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
|
||||
|
||||
|
||||
def capture(binary: str, transport: str, out: pathlib.Path) -> None:
|
||||
"""Run the scripted session under one transport, writing its trace."""
|
||||
env = dict(os.environ)
|
||||
env["INVPW_TRANSPORT"] = transport
|
||||
env["INVPW_TRACE_OUT"] = str(out)
|
||||
tree = os.environ.get(DRIVER_TREE_ENV)
|
||||
if transport == "driver" and tree:
|
||||
# ⛔ The driver comes from the older tree; the RECORDER does not. The
|
||||
# capture script has to be this one, or the two traces are produced by
|
||||
# two different instruments and every difference between them measures
|
||||
# the instruments - which is the mistake this whole comparison exists
|
||||
# to avoid.
|
||||
src = str(pathlib.Path(tree) / "src")
|
||||
env["PYTHONPATH"] = os.pathsep.join(
|
||||
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
|
||||
script = ROOT / "scripts" / "capture_protocol.py"
|
||||
r = subprocess.run([sys.executable, str(script), binary, "-o", str(out)],
|
||||
env=env, capture_output=True, text=True)
|
||||
if r.returncode != 0 or not out.exists():
|
||||
raise RuntimeError("the %s arm did not produce a trace:\n%s\n%s"
|
||||
% (transport, r.stdout[-2000:], r.stderr[-2000:]))
|
||||
|
||||
|
||||
def sent_vocabulary(trace: list) -> dict:
|
||||
"""method -> the set of parameter names ever sent with it."""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "send":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
method = message.get("method")
|
||||
if not method:
|
||||
continue
|
||||
params = message.get("params") or {}
|
||||
out.setdefault(method, set()).update(params.keys())
|
||||
return out
|
||||
|
||||
|
||||
def created_shapes(trace: list) -> dict:
|
||||
"""type -> the set of initializer field names ever seen for it."""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "recv":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
if message.get("method") != "__create__":
|
||||
continue
|
||||
params = message.get("params") or {}
|
||||
kind = params.get("type")
|
||||
if not kind:
|
||||
continue
|
||||
out.setdefault(kind, set()).update(
|
||||
(params.get("initializer") or {}).keys())
|
||||
return out
|
||||
|
||||
|
||||
def events_by_owner(trace: list, shapes_of_guid: dict) -> dict:
|
||||
"""type -> the set of event names the server emitted on objects of it."""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "recv":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
method = message.get("method")
|
||||
if not method or method.startswith("__"):
|
||||
continue
|
||||
kind = shapes_of_guid.get(message.get("guid"), "?")
|
||||
out.setdefault(kind, set()).add(method)
|
||||
return out
|
||||
|
||||
|
||||
def parentage(trace: list, types: dict) -> dict:
|
||||
"""child TYPE -> the set of parent TYPES it was ever created under.
|
||||
|
||||
⛔ A FOURTH DIMENSION, ADDED BECAUSE ITS ABSENCE LET A REAL DEFECT
|
||||
THROUGH. This server created `ElementHandle` as a child of `Page`; the
|
||||
driver creates it under `Frame`. Types matched, initializer fields matched,
|
||||
events matched - and every call that reads a timeout off the handle's frame
|
||||
died with `'Page' object has no attribute '_timeout'`, because
|
||||
`_element_handle.py` learns its frame from the guid TREE and from nothing
|
||||
else. Parentage is protocol, not bookkeeping.
|
||||
"""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "recv":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
if message.get("method") != "__create__":
|
||||
continue
|
||||
params = message.get("params") or {}
|
||||
kind = params.get("type")
|
||||
if not kind:
|
||||
continue
|
||||
out.setdefault(kind, set()).add(types.get(message.get("guid"), "root"))
|
||||
return out
|
||||
|
||||
|
||||
def disposed_types(trace: list, types: dict) -> dict:
|
||||
"""type -> whether an object of it was ever disposed ("yes" or nothing).
|
||||
|
||||
⛔ A FIFTH DIMENSION, AND THE FOUR ABOVE ARE BLIND TO IT BY CONSTRUCTION:
|
||||
`events_by_owner` skips every method starting with `__`, so `__dispose__`
|
||||
was invisible to this comparison no matter how far the two servers drifted.
|
||||
It is not bookkeeping either - the client ACTS on it, dropping the object
|
||||
from its registry - so a server that never disposes anything grows the
|
||||
client's registry for the life of the browser, and a server that disposes
|
||||
something the client still holds hands back a dead reference.
|
||||
|
||||
It was added on 2026-08-28 to answer a question the PARITY verdict could
|
||||
not: this server never disposed a closed page, and the count of live
|
||||
objects grew by one per page (9 at page 0, 508 at page 499). Whether that
|
||||
is a defect or a difference depends entirely on what the driver does, and
|
||||
nothing here could see it.
|
||||
|
||||
The value is a one-element set rather than a bool so `report` can compare
|
||||
it like every other dimension.
|
||||
"""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "recv":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
if message.get("method") != "__dispose__":
|
||||
continue
|
||||
kind = types.get(message.get("guid"))
|
||||
if kind:
|
||||
out.setdefault(kind, set()).add("disposed")
|
||||
return out
|
||||
|
||||
|
||||
def guid_types(trace: list) -> dict:
|
||||
"""guid -> its type, so an event can be attributed to a KIND of object."""
|
||||
out: dict = {}
|
||||
for entry in trace:
|
||||
if entry["dir"] != "recv":
|
||||
continue
|
||||
message = entry["msg"]
|
||||
if message.get("method") != "__create__":
|
||||
continue
|
||||
params = message.get("params") or {}
|
||||
if params.get("guid"):
|
||||
out[params["guid"]] = params.get("type")
|
||||
return out
|
||||
|
||||
|
||||
def report(label: str, ours: dict, theirs: dict, kind: str) -> list:
|
||||
"""Differences in one dimension, as lines. Empty means parity."""
|
||||
faults = []
|
||||
|
||||
def kept(name, fields):
|
||||
"""⛔ The argued differences are filtered HERE TOO, and they were not.
|
||||
A field can be missing two ways: the key exists on both sides and one
|
||||
set is short, or the key is absent entirely. The first version only
|
||||
filtered the first, so an event type that appears on the driver and
|
||||
nowhere on ours stayed red forever no matter what was written about
|
||||
it - and a gate with a permanent red is a gate people stop reading."""
|
||||
return sorted(f for f in fields
|
||||
if (name, kind, f) not in EXPECTED_DIFFERENCES)
|
||||
|
||||
for name in sorted(set(theirs) - set(ours)):
|
||||
rest = kept(name, theirs[name])
|
||||
if rest:
|
||||
faults.append("%s %r reaches the DRIVER and not us: %s"
|
||||
% (label, name, rest))
|
||||
for name in sorted(set(ours) - set(theirs)):
|
||||
rest = kept(name, ours[name])
|
||||
if rest:
|
||||
faults.append("%s %r reaches US and not the driver: %s"
|
||||
% (label, name, rest))
|
||||
for name in sorted(set(ours) & set(theirs)):
|
||||
missing = theirs[name] - ours[name]
|
||||
extra = ours[name] - theirs[name]
|
||||
missing = {f for f in missing
|
||||
if (name, kind, f) not in EXPECTED_DIFFERENCES}
|
||||
extra = {f for f in extra
|
||||
if (name, kind, f) not in EXPECTED_DIFFERENCES}
|
||||
if missing:
|
||||
faults.append("%s %r: the driver carries %s and we do not"
|
||||
% (label, name, sorted(missing)))
|
||||
if extra:
|
||||
faults.append("%s %r: we carry %s and the driver does not"
|
||||
% (label, name, sorted(extra)))
|
||||
return faults
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("binary")
|
||||
p.add_argument("--keep", action="store_true",
|
||||
help="leave the two traces on disk for inspection")
|
||||
a = p.parse_args()
|
||||
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix="protocol_diff_"))
|
||||
driver_trace = work / "driver.json"
|
||||
ours_trace = work / "juggler.json"
|
||||
|
||||
print("recording the DRIVER arm ...", flush=True)
|
||||
capture(a.binary, "driver", driver_trace)
|
||||
print("recording the PYTHON arm ...", flush=True)
|
||||
capture(a.binary, "juggler", ours_trace)
|
||||
|
||||
driver = json.loads(driver_trace.read_text(encoding="utf-8"))
|
||||
ours = json.loads(ours_trace.read_text(encoding="utf-8"))
|
||||
print()
|
||||
print(" driver: %d messages python: %d messages"
|
||||
% (len(driver), len(ours)))
|
||||
|
||||
faults = []
|
||||
faults += report("method", sent_vocabulary(ours), sent_vocabulary(driver),
|
||||
"params")
|
||||
faults += report("object", created_shapes(ours), created_shapes(driver),
|
||||
"initializer")
|
||||
faults += report("events on", events_by_owner(ours, guid_types(ours)),
|
||||
events_by_owner(driver, guid_types(driver)), "event")
|
||||
faults += report("parent of", parentage(ours, guid_types(ours)),
|
||||
parentage(driver, guid_types(driver)), "parent")
|
||||
faults += report("disposal of", disposed_types(ours, guid_types(ours)),
|
||||
disposed_types(driver, guid_types(driver)), "dispose")
|
||||
|
||||
print()
|
||||
for line in faults:
|
||||
print(" " + line)
|
||||
if a.keep or faults:
|
||||
print()
|
||||
print(" traces: %s" % work)
|
||||
if faults:
|
||||
print("PROTOCOL DIFF: %d difference(s). The Node driver cannot be "
|
||||
"deleted while any of these stand, or a caller who reaches one "
|
||||
"gets silence instead of a browser." % len(faults))
|
||||
return 1
|
||||
print("PROTOCOL DIFF: PARITY - same methods with the same parameters in, "
|
||||
"same object types with the same initializer fields, the same "
|
||||
"events, the same parentage and the same disposals out.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,195 +0,0 @@
|
||||
"""Run the same e2e through BOTH transports and compare, test by test.
|
||||
|
||||
⛔ THIS IS THE JUDGEMENT ITEM 8 WAITS FOR. The Node driver and the Python
|
||||
server answer the same protocol, so the only honest way to know the second one
|
||||
is correct is to run the same session through both and compare the results
|
||||
name by name. Deleting the driver before this has run leaves the new path with
|
||||
nothing to be measured against - a build that agrees with itself.
|
||||
|
||||
⛔ AND A DIFFERENCE IS NOT AUTOMATICALLY OURS. In two days this comparison has
|
||||
already answered in both directions: `go_back` fails identically on both arms,
|
||||
so it is the engine ([B185]); an unanswered dialog failed only on ours, so it
|
||||
was ours. The table below keeps them apart instead of counting failures.
|
||||
|
||||
python scripts/judge_both_transports.py <firefox-binary>
|
||||
python scripts/judge_both_transports.py <binary> -k juggler # a subset
|
||||
|
||||
⛔ THE MACHINE MUST BE QUIET. Both arms launch real browsers, and this project
|
||||
has three recorded cases of measuring under load and reading the noise as a
|
||||
product defect. The script refuses to start if a firefox is already alive.
|
||||
|
||||
⛔ AND THE ARMS RUN INTERLEAVED PER FILE, never all-of-A then all-of-B. Machine
|
||||
load and disk cache drift over minutes; running one arm to completion first
|
||||
puts every one of its tests in a different window from the other's, which turns
|
||||
"this arm is worse" and "that minute was worse" into the same measurement.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
|
||||
#: The files worth running on both. ⛔ NOT the whole suite: most of it never
|
||||
#: touches a transport, so running it twice would double the time and add no
|
||||
#: information. These are the ones that drive a browser through the seam.
|
||||
FILES = [
|
||||
"tests/test_juggler_transport.py",
|
||||
"tests/test_hidden_desktop.py",
|
||||
"tests/test_new_page_defaults.py",
|
||||
"tests/test_cross_origin_iframe.py",
|
||||
"tests/test_file_chooser.py",
|
||||
]
|
||||
|
||||
ESITO = re.compile(r"^(tests[^\s:]+)::(\S+)\s+(PASSED|FAILED|ERROR|XFAIL|XPASS|SKIPPED)",
|
||||
re.M)
|
||||
|
||||
|
||||
def quiet_machine() -> int:
|
||||
r = subprocess.run(
|
||||
["powershell", "-NoProfile", "-Command",
|
||||
"(Get-Process firefox -ErrorAction SilentlyContinue | Measure-Object).Count"],
|
||||
capture_output=True, text=True)
|
||||
try:
|
||||
return int((r.stdout or "0").strip() or 0)
|
||||
except ValueError:
|
||||
return -1
|
||||
|
||||
|
||||
#: A checkout that still carries the Node driver, for the day this one does not.
|
||||
#:
|
||||
#: ⛔ THIS GATE EXISTS ONLY WHILE THERE ARE TWO ARMS, and the driver is on its
|
||||
#: way out of the tree. When it goes, the second arm comes from a git worktree
|
||||
#: at the last commit that carried it:
|
||||
#:
|
||||
#: git worktree add /tmp/judge <that commit>
|
||||
#: INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
|
||||
#:
|
||||
#: A worktree rather than an installed release, because a published wrapper
|
||||
#: pins a published core and a sealed engine and therefore cannot drive a
|
||||
#: locally built binary - which is the only kind worth judging.
|
||||
DRIVER_TREE_ENV = "INVPW_DRIVER_TREE"
|
||||
|
||||
|
||||
def run_one(transport: str, binary: str, path: str, extra: list) -> dict:
|
||||
import os
|
||||
env = dict(os.environ)
|
||||
env["INVPW_TRANSPORT"] = transport
|
||||
env["INVPW_BINARY_PATH"] = binary
|
||||
tree = os.environ.get(DRIVER_TREE_ENV)
|
||||
if transport == "driver" and tree:
|
||||
# ⛔ PREPENDED, so the older tree's package wins the import. The TESTS
|
||||
# still come from this checkout: what is being borrowed is the driver,
|
||||
# not the suite, and running the old suite would compare two different
|
||||
# sets of assertions and call it a transport difference.
|
||||
src = str(pathlib.Path(tree) / "src")
|
||||
env["PYTHONPATH"] = os.pathsep.join(
|
||||
[src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
|
||||
r = subprocess.run(
|
||||
[sys.executable, "-m", "pytest", path, "-o", "addopts=", "-v",
|
||||
"-p", "no:cacheprovider"] + extra,
|
||||
cwd=ROOT, env=env, capture_output=True, text=True, timeout=3600)
|
||||
return {name: verdict
|
||||
for _, name, verdict in ESITO.findall(r.stdout + r.stderr)}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("binary")
|
||||
p.add_argument("-k", dest="selection", default=None)
|
||||
p.add_argument("--allow-busy", action="store_true",
|
||||
help="run even with a browser already alive. ⛔ The result "
|
||||
"is then not a measurement, and the report says so.")
|
||||
a = p.parse_args()
|
||||
|
||||
alive = quiet_machine()
|
||||
if alive and not a.allow_busy:
|
||||
print("REFUSING: %d firefox processes are already alive. A run under "
|
||||
"load is not a measurement - this project has three recorded "
|
||||
"cases of reading that noise as a product defect. Close them, or "
|
||||
"pass --allow-busy and read the result as indicative." % alive)
|
||||
return 2
|
||||
if alive:
|
||||
print("WARNING: %d firefox alive, the result is INDICATIVE" % alive)
|
||||
|
||||
extra = ["-k", a.selection] if a.selection else []
|
||||
driver, juggler = {}, {}
|
||||
for path in FILES:
|
||||
if not (ROOT / path).exists():
|
||||
print(" (skipped, absent: %s)" % path)
|
||||
continue
|
||||
print("running %s ..." % path, flush=True)
|
||||
# ⛔ Interleaved per file: see the module docstring.
|
||||
driver.update(run_one("driver", a.binary, path, extra))
|
||||
juggler.update(run_one("juggler", a.binary, path, extra))
|
||||
|
||||
names = sorted(set(driver) | set(juggler))
|
||||
ok = both_fail = only_ours = only_theirs = not_run = 0
|
||||
rows = []
|
||||
for name in names:
|
||||
d = driver.get(name, "ABSENT")
|
||||
j = juggler.get(name, "ABSENT")
|
||||
good = ("PASSED", "XFAIL", "SKIPPED")
|
||||
# ⛔ A TEST THE OTHER ARM NEVER RAN IS NOT A TEST THE OTHER ARM
|
||||
# FAILED, and folding the two was making this gate lie in the
|
||||
# comfortable direction. The driver arm imports an OLD `src/`, so any
|
||||
# test file naming something added since that commit fails to COLLECT
|
||||
# there and every test in it comes back ABSENT. Counted as "only the
|
||||
# driver fails", they printed under "ours is BETTER here" - measured
|
||||
# 2026-08-28 at 32 of them, essentially all of that kind. The number
|
||||
# grows on its own as this tree moves, which is the property that
|
||||
# turns a gate into decoration.
|
||||
if "ABSENT" in (d, j) and not (d in good and j in good):
|
||||
not_run += 1
|
||||
rows.append(("NOT RUN", name, d, j))
|
||||
elif d in good and j in good:
|
||||
ok += 1
|
||||
elif d not in good and j not in good:
|
||||
both_fail += 1
|
||||
rows.append(("ENGINE?", name, d, j))
|
||||
elif d in good:
|
||||
only_ours += 1
|
||||
rows.append(("OURS", name, d, j))
|
||||
else:
|
||||
only_theirs += 1
|
||||
rows.append(("DRIVER", name, d, j))
|
||||
|
||||
print()
|
||||
print("=" * 78)
|
||||
print("%-8s %-46s %-10s %s" % ("verdict", "test", "driver", "juggler"))
|
||||
print("-" * 78)
|
||||
for kind, name, d, j in rows:
|
||||
print("%-8s %-46s %-10s %s" % (kind, name[:46], d, j))
|
||||
print("-" * 78)
|
||||
print("both green %d" % ok)
|
||||
print("BOTH fail -> the ENGINE %d" % both_fail)
|
||||
print("only OURS fails %d <- the ones that are ours to fix"
|
||||
% only_ours)
|
||||
print("only the DRIVER fails %d <- ours is BETTER here, verify why"
|
||||
% only_theirs)
|
||||
print("never ran on one arm %d <- NOT a comparison: the old arm "
|
||||
"could not collect these" % not_run)
|
||||
if not_run:
|
||||
print()
|
||||
print(" WARNING: %d of the rows above were never compared at all. The driver "
|
||||
"arm's `src/` is a worktree that ages: a test naming anything "
|
||||
"added since it was cut fails to collect there. When this number "
|
||||
"approaches the total, this gate has stopped answering its own "
|
||||
"question and the worktree needs re-cutting." % not_run)
|
||||
print()
|
||||
if only_ours:
|
||||
print("VERDICT: not ready to delete the driver. %d tests pass through "
|
||||
"it and fail through us." % only_ours)
|
||||
return 1
|
||||
print("VERDICT: no test passes on the driver and fails on us.")
|
||||
if both_fail:
|
||||
print(" (%d fail on BOTH: engine defects, not a reason to wait)"
|
||||
% both_fail)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -7,7 +7,7 @@ against anything of ours: its `conftest.py` imports the real `playwright`
|
||||
package, so it has only ever measured Microsoft's client.
|
||||
|
||||
The plan it serves: replacing the channel between our client and our server
|
||||
removes the boundary `diff_protocol.py` compares across, so the judgement has to
|
||||
removes the boundary the old protocol comparison compared across, so the judgement has to
|
||||
move up a level, from the PROTOCOL to the CONTRACT. This suite is that judge -
|
||||
but only if we know, before touching anything, which of those 2173 pass TODAY.
|
||||
A baseline taken afterwards proves nothing: every failure would be arguable.
|
||||
|
||||
@@ -52,14 +52,14 @@ did so on evidence rather than on the code looking finished:
|
||||
regenerating them. `injected.js` (the selector engines, actionability and
|
||||
`expect` that run in the page), `keylayout.py` (both in `invisible_core.juggler`
|
||||
since 0.30.0, with their extractors in the core's `scripts/`), and the four rules
|
||||
`prefs_byte_parity.py` compares our `user.js` writer against - now frozen in
|
||||
`tests/gates/driver_prefs_rules.json` with the sha of the bundle and of the
|
||||
exact window they came from.
|
||||
- ⛔ And the second arm. `judge_both_transports.py` and `diff_protocol.py` exist
|
||||
only while there are two implementations to compare. To get one back:
|
||||
the `user.js` writer was compared against (the comparison script and the frozen
|
||||
rules file were later deleted; they are in git history).
|
||||
- ⛔ And the second arm. A comparison between the two transports only exists
|
||||
while there are two implementations to compare, and the scripts that did it
|
||||
were deleted with the driver arm. To get one back:
|
||||
|
||||
git worktree add /tmp/judge <the last commit that carried _driver/>
|
||||
INVPW_DRIVER_TREE=/tmp/judge python scripts/judge_both_transports.py <bin>
|
||||
INVPW_DRIVER_TREE=/tmp/judge python scripts/capture_protocol.py <bin>
|
||||
|
||||
A worktree rather than an installed release, because a published wrapper pins
|
||||
a published core and a sealed engine and therefore cannot drive a locally
|
||||
|
||||
@@ -4342,9 +4342,10 @@ class PageDispatcher(Dispatcher):
|
||||
# too, because `_connection.py` only drops an object when it is told
|
||||
# to. The driver disposes Page, BrowserContext, Browser, ElementHandle
|
||||
# and APIRequestContext; the only one we were missing was Page, which
|
||||
# is why `diff_protocol.py` grew a fifth dimension to see it: the other
|
||||
# four compare `__create__`, initializers, events and parentage, and
|
||||
# the event comparison skips every method starting with `__`.
|
||||
# is why the protocol comparison that used to exist needed a fifth
|
||||
# dimension to see it: the other four compared `__create__`, initializers,
|
||||
# events and parentage, and the event comparison skips every method
|
||||
# starting with `__`.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -282,8 +282,8 @@ def make_transport(loop: asyncio.AbstractEventLoop) -> "InProcessTransport":
|
||||
"only transport - unset %s and it runs. To get the old arm back "
|
||||
"for a COMPARISON (the only thing it was still for): check out "
|
||||
"the last commit that carried it into a git worktree and point "
|
||||
"INVPW_DRIVER_TREE at it. Both `judge_both_transports.py` and "
|
||||
"`diff_protocol.py` read that variable." % CHOICE_ENV)
|
||||
"INVPW_DRIVER_TREE at it, which `scripts/capture_protocol.py` "
|
||||
"reads." % CHOICE_ENV)
|
||||
from .server import JugglerServer
|
||||
if (os.environ.get(WIRE_ENV) or "").strip().lower() == "json":
|
||||
return JsonWireTransport(loop, JugglerServer())
|
||||
|
||||
@@ -102,5 +102,5 @@ class Transport(ABC):
|
||||
#
|
||||
# ⛔ To get the old arm back for a comparison - which is the only thing it
|
||||
# was still for - check out the last commit that carried it into a git
|
||||
# worktree and point `INVPW_DRIVER_TREE` at it. `judge_both_transports.py`
|
||||
# and `diff_protocol.py` both read that variable.
|
||||
# worktree and point `INVPW_DRIVER_TREE` at it. `scripts/capture_protocol.py`
|
||||
# reads that variable.
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"_why": "The four rules the Node driver's user.js writer follows, FROZEN. Until 2026-08-28 prefs_byte_parity.py read them out of src/invisible_playwright/_driver/package/lib/coreBundle.js on every run, deliberately, so that an upstream change moved the gate with it instead of leaving it comparing against a stale transcription. The bundle is being deleted with the Node driver, so the derived fact becomes a recorded one - and this file exists to make that visible rather than silent.",
|
||||
"_how_to_verify": "While a bundle is still reachable, prefs_byte_parity.py re-extracts and compares against these values, and FAILS on a mismatch. To reach one after the deletion: git worktree add <dir> <the last commit that carried _driver/>, then point the gate at it with INVPW_DRIVER_BUNDLE=<dir>/src/invisible_playwright/_driver/package/lib/coreBundle.js.",
|
||||
"_what_a_stale_copy_would_cost": "The gate would compare our writer against our own idea of the driver, which always agrees. That is the failure mode the run-time read existed to prevent, and it is why the provenance below is recorded to the byte instead of just being dated.",
|
||||
"rules": {
|
||||
"sorts": false,
|
||||
"header": false,
|
||||
"separator": true,
|
||||
"integer_bare": true
|
||||
},
|
||||
"provenance": {
|
||||
"frozen_on": "2026-08-28",
|
||||
"file": "src/invisible_playwright/_driver/package/lib/coreBundle.js",
|
||||
"bundle_bytes": 2780363,
|
||||
"bundle_sha256_16": "97d55ec7f856966d",
|
||||
"marker": "__ipwLit",
|
||||
"marker_offset": 1775227,
|
||||
"window_bytes": 1200,
|
||||
"window_sha256_16": "4891de086d6625f6"
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
"""The two writers must produce the SAME `user.js`, byte for byte.
|
||||
|
||||
⛔ THIS IS THE CRITERION ITEM 1 WAS WRITTEN WITH, and it is stricter than
|
||||
"both work" on purpose. Two prefs files can each be valid, each configure the
|
||||
browser, and differ - a header comment, a different order, an integer written
|
||||
as a string. Every one of those differences is invisible in a running browser
|
||||
and every one of them means the Python path is configuring a browser the Node
|
||||
path never configured. The whole point of keeping the driver as a judge is that
|
||||
this comparison is possible; a looser check throws that away.
|
||||
|
||||
⛔ AND IT NEEDS NO BROWSER. Both writers are pure functions of the prefs dict:
|
||||
the driver's is a JavaScript literal builder inside `coreBundle.js`, ours is
|
||||
`invisible_core.launch.write_user_js`, the one writer since 0.30.0. The driver's rules are re-implemented here FROM ITS SOURCE,
|
||||
read at run time rather than copied - so if upstream's writer changes, this gate
|
||||
changes with it instead of silently comparing against a stale transcription.
|
||||
|
||||
python tests/gates/prefs_byte_parity.py
|
||||
python tests/gates/prefs_byte_parity.py --selftest # 6 mutations, 3 that must not fire
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
|
||||
BUNDLE = ROOT / "src/invisible_playwright/_driver/package/lib/coreBundle.js"
|
||||
|
||||
#: A prefs dict shaped like a real one: the four value kinds that matter, a
|
||||
#: name with a character JSON has to escape, and a deliberately unsorted order.
|
||||
#: ⛔ THE ORDER IS PART OF THE FIXTURE. The driver uses `Object.keys()`, so a
|
||||
#: writer that sorts produces a file that is equally correct and not identical,
|
||||
#: and that is precisely the class of difference this gate exists to catch.
|
||||
SAMPLE = {
|
||||
"zoom.stealth.screen.width": 1920,
|
||||
"app.update.auto": False,
|
||||
"layout.css.devPixelsPerPx": "1.25",
|
||||
"ui.textScaleFactor": 1.0,
|
||||
"general.useragent.override": 'Mozilla/5.0 "quoted" \\ backslash',
|
||||
"browser.startup.homepage": "about:blank",
|
||||
}
|
||||
|
||||
|
||||
class DriverRulesMissing(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
#: The frozen copy, with its provenance. See the file itself for why.
|
||||
FROZEN = pathlib.Path(__file__).resolve().parent / "driver_prefs_rules.json"
|
||||
|
||||
#: Where to find a bundle after the deletion: a git worktree at the last commit
|
||||
#: that carried `_driver/`. Named here so the gate can say it out loud instead
|
||||
#: of leaving the reader to work it out.
|
||||
BUNDLE_ENV = "INVPW_DRIVER_BUNDLE"
|
||||
|
||||
|
||||
def _bundle():
|
||||
"""A reachable bundle, or None. Never raises: absence is a state."""
|
||||
named = os.environ.get(BUNDLE_ENV)
|
||||
if named:
|
||||
candidate = pathlib.Path(named)
|
||||
return candidate if candidate.exists() else None
|
||||
return BUNDLE if BUNDLE.exists() else None
|
||||
|
||||
|
||||
def driver_rules() -> dict:
|
||||
"""The driver's literal rules: frozen, and re-checked whenever possible.
|
||||
|
||||
⛔ IT USED TO READ THE BUNDLE ON EVERY RUN, deliberately, so an upstream
|
||||
change moved this gate with it instead of leaving it comparing against a
|
||||
stale transcription. The bundle goes with the Node driver, so the rules are
|
||||
now RECORDED - in `driver_prefs_rules.json`, with the sha of the bundle and
|
||||
of the exact 1200-byte window they came from.
|
||||
|
||||
⛔ AND THE RE-CHECK IS THE WHOLE POINT OF FREEZING THEM THIS WAY. Whenever a
|
||||
bundle IS reachable - still in the tree, or named by `INVPW_DRIVER_BUNDLE`
|
||||
from a git worktree - the rules are extracted again and compared against the
|
||||
frozen copy, and a mismatch FAILS. A recorded fact nobody can re-derive is a
|
||||
transcription, and a transcription this gate cannot check is exactly what
|
||||
the original design refused to have.
|
||||
"""
|
||||
frozen = json.loads(FROZEN.read_text(encoding="utf-8"))["rules"]
|
||||
bundle = _bundle()
|
||||
if bundle is None:
|
||||
return frozen
|
||||
live = _extract(bundle.read_text(encoding="utf-8", errors="replace"))
|
||||
if live != frozen:
|
||||
raise DriverRulesMissing(
|
||||
"the frozen driver rules disagree with the bundle at %s.\n"
|
||||
" frozen: %s\n bundle: %s\n"
|
||||
"The frozen copy is stale: re-freeze it with the new provenance, "
|
||||
"rather than loosening this comparison." % (bundle, frozen, live))
|
||||
return frozen
|
||||
|
||||
|
||||
def _extract(text: str) -> dict:
|
||||
start = text.find("__ipwLit")
|
||||
if start < 0:
|
||||
raise DriverRulesMissing(
|
||||
"the driver's pref writer is not in the bundle: it was renamed or "
|
||||
"removed, and this gate cannot compare against something it "
|
||||
"cannot read")
|
||||
window = text[start:start + 1200]
|
||||
return {
|
||||
"sorts": "sort()" in window,
|
||||
"header": bool(re.search(r'"//[^"]*"\s*\+', window)),
|
||||
"separator": "String.fromCharCode(10)" in window or "\\n" in window,
|
||||
"integer_bare": "Number.isInteger" in window,
|
||||
}
|
||||
|
||||
|
||||
def driver_user_js(prefs: dict) -> str:
|
||||
"""What the driver writes, in Python, following the rules read above."""
|
||||
rules = driver_rules()
|
||||
names = sorted(prefs) if rules["sorts"] else list(prefs)
|
||||
lines = []
|
||||
for name in names:
|
||||
value = prefs[name]
|
||||
if isinstance(value, bool):
|
||||
literal = "true" if value else "false"
|
||||
elif isinstance(value, int):
|
||||
literal = str(value)
|
||||
elif isinstance(value, float):
|
||||
# ⛔ Not an integer, so the driver quotes it: Gecko has no float
|
||||
# pref type, and a bare fraction makes the parser fail and IGNORE
|
||||
# EVERY LINE AFTER IT.
|
||||
literal = json.dumps(str(value))
|
||||
else:
|
||||
literal = json.dumps(str(value))
|
||||
lines.append("user_pref(%s, %s);" % (json.dumps(name), literal))
|
||||
head = "// header\n" if rules["header"] else ""
|
||||
return head + "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def ours(prefs: dict) -> str:
|
||||
from invisible_core.launch import write_user_js
|
||||
directory = tempfile.mkdtemp(prefix="prefs_parity_")
|
||||
write_user_js(directory, prefs)
|
||||
return (pathlib.Path(directory) / "user.js").read_bytes().decode("utf-8")
|
||||
|
||||
|
||||
def compare(prefs: dict) -> list:
|
||||
theirs = driver_user_js(prefs)
|
||||
mine = ours(prefs)
|
||||
if theirs == mine:
|
||||
return []
|
||||
faults = []
|
||||
a, b = theirs.splitlines(), mine.splitlines()
|
||||
if len(a) != len(b):
|
||||
faults.append("line count: driver %d, ours %d" % (len(a), len(b)))
|
||||
for i, (x, y) in enumerate(zip(a, b)):
|
||||
if x != y:
|
||||
faults.append("line %d:\n driver: %s\n ours : %s"
|
||||
% (i + 1, x, y))
|
||||
if not faults:
|
||||
faults.append("same lines, different bytes: trailing newline or "
|
||||
"encoding")
|
||||
return faults
|
||||
|
||||
|
||||
# ── the selftest ────────────────────────────────────────────────────────────
|
||||
def selftest() -> int:
|
||||
bad = 0
|
||||
|
||||
def expect(name, produce, should_fire):
|
||||
nonlocal bad
|
||||
theirs = driver_user_js(SAMPLE)
|
||||
mine = produce(theirs)
|
||||
differs = theirs != mine
|
||||
if differs != should_fire:
|
||||
print(" %s: %s" % ("SURVIVED" if should_fire else "FALSE POSITIVE",
|
||||
name))
|
||||
bad += 1
|
||||
else:
|
||||
print(" %s: %s" % ("killed" if should_fire else "silent", name))
|
||||
|
||||
print("--- mutations that MUST fire ---")
|
||||
expect("a header comment is added",
|
||||
lambda t: "// written by us\n" + t, True)
|
||||
expect("the lines are sorted",
|
||||
lambda t: "\n".join(sorted(t.splitlines())) + "\n", True)
|
||||
expect("an integer is quoted",
|
||||
lambda t: t.replace("user_pref(\"zoom.stealth.screen.width\", 1920)",
|
||||
"user_pref(\"zoom.stealth.screen.width\", \"1920\")"),
|
||||
True)
|
||||
expect("a boolean becomes a string",
|
||||
lambda t: t.replace(", false)", ", \"false\")"), True)
|
||||
expect("the trailing newline is dropped",
|
||||
lambda t: t.rstrip("\n"), True)
|
||||
expect("one pref goes missing",
|
||||
lambda t: "\n".join(t.splitlines()[1:]) + "\n", True)
|
||||
|
||||
print("--- cases that must NOT fire ---")
|
||||
expect("the same text", lambda t: t, False)
|
||||
expect("the same text built twice", lambda t: driver_user_js(SAMPLE), False)
|
||||
expect("a float stays quoted",
|
||||
lambda t: t.replace('"1.0"', '"1.0"'), False)
|
||||
|
||||
print()
|
||||
print("selftest: %s" % ("ALL GOOD" if not bad else "%d PROBLEMS" % bad))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--selftest", action="store_true")
|
||||
a = p.parse_args()
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
try:
|
||||
rules = driver_rules()
|
||||
except DriverRulesMissing as failure:
|
||||
print("NOT COMPARABLE: %s" % failure)
|
||||
return 2
|
||||
# ⛔ IT SAYS WHICH SOURCE IT USED. The line used to read "driver rules read
|
||||
# from the bundle" unconditionally, and after the freeze that sentence was
|
||||
# simply false half the time - a gate that misreports where its own
|
||||
# reference came from is worse than one with no message, because the reader
|
||||
# stops looking.
|
||||
bundle = _bundle()
|
||||
print("driver rules %s: %s"
|
||||
% ("re-checked against %s" % bundle if bundle
|
||||
else "from the FROZEN copy (%s) - no bundle reachable, so nothing "
|
||||
"re-derived them this run" % FROZEN.name,
|
||||
", ".join("%s=%s" % kv for kv in sorted(rules.items()))))
|
||||
faults = compare(SAMPLE)
|
||||
if not faults:
|
||||
print("PREFS BYTE PARITY: identical (%d prefs)" % len(SAMPLE))
|
||||
return 0
|
||||
print("the two writers DISAGREE:")
|
||||
for f in faults:
|
||||
print(" " + f)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -189,7 +189,7 @@ def test_a_long_session_does_not_accumulate_subscribers(firefox_binary, first_ru
|
||||
assert leaked_objects == 0, (
|
||||
"forty open-and-close cycles left %d objects in the server's guid "
|
||||
"registry; a closed page must be disposed, which is also what the "
|
||||
"driver does and what diff_protocol's fifth dimension compares"
|
||||
"driver does and what the old protocol comparison's fifth dimension compared"
|
||||
% leaked_objects)
|
||||
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ def test_the_default_is_the_PYTHON_SERVER(monkeypatch):
|
||||
user session into an experiment. What flipped it is four measurements taken
|
||||
on one code state, not the code looking done: `run_e2e.py` 188 passed on
|
||||
BOTH transports; the transport judge 50 green on both with 0 red only on
|
||||
ours; `diff_protocol.py` at parity on methods, parameters, object types,
|
||||
ours; the protocol comparison at parity on methods, parameters, object types,
|
||||
initializer fields, events and parentage; and the realness gates green on
|
||||
this path for the first time.
|
||||
|
||||
@@ -108,7 +108,7 @@ def test_the_driver_is_still_reachable_by_name(monkeypatch):
|
||||
"""⛔ The way back has to keep working, or the flip above is one-way.
|
||||
|
||||
A user whose session behaves differently on the new path must be able to
|
||||
say so and get the old one, and `judge_both_transports.py` needs it to have
|
||||
say so and get the old one, and any comparison between the two arms needs it to have
|
||||
a second arm at all.
|
||||
"""
|
||||
monkeypatch.setenv(factory.CHOICE_ENV, "driver")
|
||||
|
||||
Reference in new issue
Block a user