The version this reports describes the code, not the install record (#230)

`__version__` said 0.16.2 from a tree declaring 0.22.1, minutes after that
checkout had been brought to zero commits behind origin/main.

It came from `importlib.metadata.version("invisible-playwright")`, which answers
about the distribution the installer put there. For a wheel that is the same
artifact as the code. For `pip install -e` the metadata is written once and the
code keeps moving, and nothing says the two have parted. Pulling does not touch
the record, so this is a defect in the code and not a stale checkout.

This is the package a measurement names. Every bench that drives a browser
reports "measured against invisible-playwright X", and read from the program X
was the moment somebody ran `pip install -e`, not the code under test. A finding
was about to be written with a version six releases wrong; it survived because
its author had read the number off the tree instead, which is luck rather than
method.

So the version of the code is now: the install record for a normal install,
because the metadata and the code came out of the same build; the version the
source tree declares for an editable one, plus a `+editable` local segment so a
tree that can carry uncommitted work is never read as the published release of
the same number. Which of the two an install is comes from what the installer
wrote (PEP 610 `direct_url.json`), not from a guess about `__file__`.

The record stays, under a name that cannot be mistaken for the version, the way
`invisible_core` already names it. This is deliberately not a shared module: the
core derives from the seal it PACKAGES, which is a different reading, and
`aihawk` carries this same one for the same reason, noted in both so a
correction to one is looked at in the other.

Three tests moved, and why matters more than that they did.

`test_version_matches_installed_package_metadata` asserted the equality that is
now wrong, under a docstring saying the point was that the version can never
drift from the `pyproject.toml` field. The assertion never held that. It was
true of the install record all along, which is the fact it was really about, so
it now asserts that under the record's own name, and what the docstring wanted
is held against real `pip` installs in the new file.

The `--version` and `-V` arms spawned a subprocess, which does not inherit
pytest's `pythonpath`, so they tested whatever was installed rather than the
code under test. In CI the two coincide because the workflow installs this
repository editable; from a worktree they do not, and the arms went red against
a checkout they were never meant to measure. They now put this package's `src`
on the subprocess path.

0.22.2, and the repository had to tell me: I first left the number alone so the
drag regression being fixed in parallel could have it. That is not an option
here. `test_the_declared_version_is_not_already_published` refuses a change to a
file that goes into the wheel while `pyproject` still names a version the index
already serves, because a release from there publishes nothing: `publish.yml`
sees the version, reports a no-op rather than a failure, and skips everything
below it. Keeping the number free would have made this unreleasable instead.

Six known-bad mutations, six killed, including the whole previous
implementation put back and a wheel arm that keeps the remedy from consulting a
tree that is not what runs.
This commit is contained in:
Federico authored and GitHub committed 2026-09-18 21:07:27 +02:00
1 parent 314b9b6cc9
commit 7f2f42310d
6 files changed
+461 -25

No files matched your search

+30
View File
@@ -6,6 +6,36 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.22.2] - 2026-09-18
### Fixed
- **`__version__` describes the code, not the install record.** It came from
`importlib.metadata`, which answers about the distribution the installer put
there. For a wheel that is the same artifact as the code. For
`pip install -e` the metadata is written once while the code keeps moving,
and pulling does not touch it. Measured minutes after the checkout had been
brought to zero commits behind `origin/main`: the record said 0.16.2 while
the tree declared 0.22.1, six releases apart.
That matters here more than in most packages, because this is the one a
measurement names. Read from the program, the X in "measured against
invisible-playwright X" was the moment somebody ran `pip install -e`, not the
code under test.
The version is now the install record for a normal install, and for an
editable one the version the source tree declares plus a `+editable` local
segment, so a tree that can carry uncommitted work is never read as the
published release of the same number. Which of the two an install is comes
from what `pip` itself wrote in `direct_url.json` (PEP 610), not from a guess
about `__file__`. The record is still reported, under
`__install_record_version__`, the way `invisible_core` already names it.
- **Two tests were exercising whatever was installed rather than this code.**
The `--version` and `-V` arms spawned a subprocess, and a subprocess does not
inherit pytest's `pythonpath`. In CI the two coincide, because the workflow
installs this repository editable; from a worktree they do not, and the arms
went red against a checkout they were never meant to measure.
## [0.22.1] - 2026-09-18
### Fixed
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.22.1"
version = "0.22.2"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
+8 -8
View File
@@ -69,14 +69,13 @@ from invisible_core import GeoTimezoneError, resolve_session_timezone
from invisible_core import ensure_binary, ensure_geoip_mmdb
from .launcher import InvisiblePlaywright
from importlib.metadata import PackageNotFoundError, version as _pkg_version
try:
__version__ = _pkg_version("invisible-playwright")
except PackageNotFoundError:
# Editable / source checkout without an install record: fall back to a
# marker rather than risk shipping a stale hardcoded string.
__version__ = "0.0.0+unknown"
# `__version__` describes the CODE that is about to run; the install record is
# a different fact and keeps a name that says so, the way `invisible_core` does.
# ⛔ It used to be `importlib.metadata.version("invisible-playwright")`, which
# describes the INSTALL: an editable one freezes that number and the code keeps
# moving, measured here at 0.16.2 against a tree declaring 0.22.1 with the
# checkout up to date. See `_version.py`.
from ._version import __install_record_version__, __version__
__all__ = [
"InvisiblePlaywright",
@@ -89,4 +88,5 @@ __all__ = [
"BINARY_VERSION",
"FIREFOX_UPSTREAM_VERSION",
"__version__",
"__install_record_version__",
]
+139
View File
@@ -0,0 +1,139 @@
"""What version the code being imported actually is.
⛔ AN INSTALL RECORD IS NOT A DESCRIPTION OF THE CODE, AND FOR AN EDITABLE
INSTALL IT STOPS BEING ONE THE MOMENT SOMEBODY PULLS. `importlib.metadata`
answers about the DISTRIBUTION the installer put there. For a wheel that is the
same artifact as the code, so the number is right and there is nothing truer to
read. For `pip install -e` the metadata is written once and the code keeps
moving, and nothing says the two have parted.
Measured on the machine this is developed on, minutes after the checkout was
brought to zero commits behind `origin/main`: the record said 0.16.2 while the
tree said 0.22.1, six releases apart. Pulling does not touch the record, which
is what makes this a defect in the code rather than a stale checkout.
⛔ AND THE NUMBER IS WHAT A MEASUREMENT NAMES. This package is the thing under
test in every bench that drives a browser, so "measured against
invisible-playwright X" is the sentence that carries the result. Read from the
program, X was the moment somebody ran `pip install -e`, not the code being
measured. A finding was about to be written with a version six releases wrong;
it survived because its author had read the number off the TREE instead, which
is luck rather than method. The rule those benches already carry - a red against
an old dependency is not evidence about the product - keeps being broken because
nothing answered "which version am I measuring?" truthfully.
The version of the code is:
- a normal install: the install record, because the metadata and the code
came out of the same build;
- an editable install: the version the SOURCE TREE declares, because that is
the code that will run, plus a `+editable` local segment (PEP 440) so it
can never be read as the published release of the same number. An editable
tree can carry uncommitted work, so a bare `0.22.1` would invite a report
against a release that does not contain the code being run.
Which of the two an install is comes from what the installer WROTE, not from a
guess about `__file__`: PEP 610 puts `direct_url.json` beside the metadata,
carrying `dir_info.editable` and the source directory. A wheel install has no
such file at all.
The install record stays, under a name that cannot be mistaken for the version.
`invisible_core` made this split first and names it the same way, deriving its
own `__version__` from the seal it ships; it is not a shared implementation and
must not become one by copying, because the core derives from an artifact it
PACKAGES while this reads the tree an install points at. `aihawk` carries the
same reading as this module for the same reason, so a correction here is worth
looking at there.
"""
from __future__ import annotations
import json
import tomllib
from importlib.metadata import Distribution, PackageNotFoundError, distribution
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import url2pathname
#: What this package is called on the index.
DISTRIBUTION = "invisible-playwright"
#: What a version says when there is nothing at all to read.
UNKNOWN = "0.0.0+unknown"
#: PEP 440 local segment marking a tree that is not a published artifact.
EDITABLE = "+editable"
def source_tree(dist: Distribution) -> Path | None:
"""The directory an EDITABLE install points at, or None for a normal one.
Everything here is read from the record the installer wrote. The absence of
`direct_url.json` is how a wheel install says it is one.
"""
written = dist.read_text("direct_url.json")
if not written:
return None
try:
record = json.loads(written)
except ValueError:
return None
if not isinstance(record, dict):
return None
if not (record.get("dir_info") or {}).get("editable"):
return None
url = record.get("url") or ""
if not url.startswith("file:"):
# An editable install of something fetched over the network leaves no
# directory here to read, so the record is still the best there is.
return None
return Path(url2pathname(urlparse(url).path))
def declared_by(tree: Path) -> str | None:
"""The version that source tree declares, or None when it does not say one.
`pyproject.toml` is where the version lives and the metadata is a copy of it
taken at build time, so this goes back to the source of the copy rather than
adding a second source. A tree declaring `dynamic = ["version"]` says
nothing readable without running its build backend, and answering None there
falls back to the record, which is the same answer as before this module.
"""
try:
parsed = tomllib.loads(
(tree / "pyproject.toml").read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
declared = (parsed.get("project") or {}).get("version")
return declared if isinstance(declared, str) and declared else None
def versions(name: str = DISTRIBUTION) -> tuple[str, str]:
"""(the version of the CODE, the version in the install record).
The two differ exactly when the install is editable and the tree has moved
since it was installed, which on a machine where this is developed is most
of the time. `name` is a parameter so the behaviour can be tested against a
real editable install of a real distribution rather than against a double.
"""
try:
dist = distribution(name)
except PackageNotFoundError:
# A checkout on `sys.path` with nothing installed: no record to be
# stale, and no recorded tree to read.
return UNKNOWN, ""
record = dist.version
tree = source_tree(dist)
if tree is None:
return record, record
declared = declared_by(tree)
if declared is None:
return record, record
# Marked even when the two numbers agree: an editable tree is not the
# published artifact whatever it declares, and that is what the marker says.
return declared + EDITABLE, record
__version__, __install_record_version__ = versions()
__all__ = ["__version__", "__install_record_version__", "versions",
"source_tree", "declared_by", "DISTRIBUTION", "EDITABLE", "UNKNOWN"]
@@ -0,0 +1,250 @@
"""The version this package reports describes the code, not the install record.
⛔ THE DEFECT THESE HOLD. `__version__` came from
`importlib.metadata.version("invisible-playwright")`, which answers about the
DISTRIBUTION the installer put there. An editable install writes that metadata
once and the code keeps moving, so on the machine this is developed on the
record said 0.16.2 while the tree said 0.22.1, six releases apart, minutes after
that checkout had been brought to zero commits behind `origin/main`. Pulling
does not touch the record, which is why this is a defect in the code and not a
stale checkout.
⛔ AND THIS IS THE PACKAGE A MEASUREMENT NAMES. Every bench that drives a
browser reports "measured against invisible-playwright X", and read from the
program X was the moment somebody ran `pip install -e`. A finding was about to
be written with a version six releases wrong; it survived only because its
author happened to read the number off the tree instead. The CI installs with
`pip install -e .`, so the broken install mode is the one the suite runs in.
⛔ THESE TESTS USE REAL `pip` INSTALLS OF A REAL DISTRIBUTION, AND THAT IS NOT
CEREMONY. The claim has two halves - that an editable install freezes its
metadata while recording the source tree (PEP 610), and that this code reads
the tree when it does - and a half tested against a double leaves the joint
tested by nobody. A hand-written `.dist-info` would assert what I believe pip
does instead of what pip does. Measured cost of the two installs: about 40
seconds for the file, once, in module-scoped fixtures.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
from invisible_playwright._version import (EDITABLE, declared_by, source_tree,
versions)
PKG = "tinydist"
PYPROJECT = """[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "%s"
version = "%%s"
""" % PKG
def _tree(at: Path, version: str) -> Path:
"""A real, minimal, installable distribution declaring `version`."""
root = at / PKG
(root / "src" / PKG).mkdir(parents=True, exist_ok=True)
(root / "pyproject.toml").write_bytes((PYPROJECT % version).encode("utf-8"))
(root / "src" / PKG / "__init__.py").write_bytes(b"")
return root
def _declare(root: Path, version: str) -> None:
"""Move what the tree says, the way a `git pull` does: the files change and
nothing reinstalls."""
root.joinpath("pyproject.toml").write_bytes(
(PYPROJECT % version).encode("utf-8"))
def _venv(at: Path) -> Path:
subprocess.run([sys.executable, "-m", "venv", str(at)], check=True,
capture_output=True)
if sys.platform == "win32":
return at / "Scripts" / "python.exe"
return at / "bin" / "python"
# ⛔ LOADED BY PATH, NOT IMPORTED, AND THAT IS PART OF THE CLAIM. Importing
# `invisible_playwright` runs the package `__init__`, which pulls in the core
# and refuses when the engine configuration it ships does not match the
# environment - in a bare venv that is every time, and the failure would look
# like this module's. `_version` imports nothing but the standard library on
# purpose, so loading the file alone is both what the test needs and a check
# that the module really is free-standing.
ASK = """
import importlib.util, json, sys
import importlib.metadata as md
spec = importlib.util.spec_from_file_location("_v", %r)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
print(json.dumps({"record": md.version(%r), "versions": mod.versions(%r)}))
"""
def _asks(python: Path) -> dict:
"""Run the question INSIDE that environment and hand back what it printed.
It has to be asked from in there: `importlib.metadata` answers about the
interpreter that is running, so asking from here would describe this
environment instead of that one.
"""
module = Path(__file__).resolve().parents[1] / "src" / "invisible_playwright" / "_version.py"
done = subprocess.run([str(python), "-c", ASK % (str(module), PKG, PKG)],
capture_output=True, text=True, env=dict(os.environ))
assert done.returncode == 0, done.stderr
return json.loads(done.stdout)
@pytest.fixture(scope="module")
def editable(tmp_path_factory):
"""A real editable install, made at 1.0.0 and then left behind by its tree.
This is the situation exactly: installed once, and the source moves after.
"""
at = tmp_path_factory.mktemp("editable")
root = _tree(at, "1.0.0")
python = _venv(at / "venv")
subprocess.run([str(python), "-m", "pip", "install", "-q", "--no-deps",
"-e", str(root)], check=True, capture_output=True)
return python, root
@pytest.fixture(scope="module")
def wheel(tmp_path_factory):
"""A real NORMAL install: the code that runs is the installed copy, so the
tree moving afterwards must change nothing."""
at = tmp_path_factory.mktemp("wheel")
root = _tree(at, "1.0.0")
python = _venv(at / "venv")
subprocess.run([str(python), "-m", "pip", "install", "-q", "--no-deps",
str(root)], check=True, capture_output=True)
return python, root
def test_an_editable_install_reports_what_its_tree_says(editable):
"""⛔ THE KNOWN-BAD, ON THE REAL PACKAGING SYSTEM. Install at 1.0.0, move
the tree to 2.0.0, reinstall nothing. The old code answered 1.0.0 here,
because that is what the record says and the record is what it read.
The record is asserted to be STALE in the same breath, because without that
the test cannot tell "it read the tree" from "pip quietly updated the
record", and an assertion that cannot separate the two answers of its
instrument is not asserting anything.
"""
python, root = editable
_declare(root, "2.0.0")
got = _asks(python)
assert got["record"] == "1.0.0", (
"pip updated the install record on its own, so this test is not "
"measuring what it claims to measure")
code, record = got["versions"]
assert code == "2.0.0" + EDITABLE, (
"the version reported is %r, but the code that runs declares 2.0.0" % code)
assert record == "1.0.0", "the install record must still be reported as it is"
def test_the_two_facts_stay_separate_and_named(editable):
"""The record is kept, not discarded: `pip`, `pip check` and anything
reading `.dist-info` see that number, and diagnosing the skew needs both.
What changed is which of the two is called the version."""
python, root = editable
_declare(root, "3.0.0")
got = _asks(python)
code, record = got["versions"]
assert code != record, "the two facts collapsed back into one"
assert code.startswith("3.0.0"), code
assert record == "1.0.0", record
def test_an_editable_tree_is_never_mistaken_for_the_release(editable):
"""Even when the two numbers agree, an editable tree is not the published
artifact of that number: it can carry uncommitted work. The local segment
says so, and it is PEP 440 so it parses and sorts."""
python, root = editable
_declare(root, "1.0.0")
got = _asks(python)
code, record = got["versions"]
assert code == "1.0.0" + EDITABLE, code
assert code != record, (
"an editable tree reported itself as the released version")
def test_a_normal_install_is_not_second_guessed(wheel):
"""⛔ THE ARM THAT KEEPS THE REMEDY FROM OVERREACHING. For a wheel the
metadata and the code came out of the same build, so the record IS the
description of the code and there is nothing truer to read. A tree sitting
next to it is not what runs, and must not be consulted: a remedy that read
it would report a version the running code does not have."""
python, root = wheel
_declare(root, "9.9.9")
got = _asks(python)
code, record = got["versions"]
assert code == "1.0.0", (
"a normal install reported %r, taking it from a source tree that is "
"not the code being run" % code)
assert record == "1.0.0"
assert EDITABLE not in code
def test_nothing_installed_at_all_says_so_instead_of_guessing():
"""A checkout on `sys.path` with no install record has nothing to read, and
says that rather than inventing a number."""
code, record = versions("this-distribution-does-not-exist")
assert code == "0.0.0+unknown", code
assert record == "", record
def test_a_tree_that_declares_nothing_readable_falls_back(tmp_path):
"""`dynamic = ["version"]` says nothing without running a build backend, so
the record stays the answer. That is the same answer as before this module,
which is the point: the fallback is a known state, not a guess."""
root = tmp_path / "dyn"
root.mkdir()
root.joinpath("pyproject.toml").write_bytes(
b'[project]\nname = "dyn"\ndynamic = ["version"]\n')
assert declared_by(root) is None
assert declared_by(tmp_path / "there-is-nothing-here") is None
def test_no_module_in_this_package_types_a_version():
"""Derived, never typed. The fallbacks and the local segment are not version
numbers, and nothing else may be one."""
import re
import invisible_playwright
typed = [p.name for p in Path(invisible_playwright.__file__).parent.rglob("*.py")
if re.search(r'__version__\s*=\s*["\']\d+\.\d+',
p.read_text(encoding="utf-8"))]
assert not typed, "a version literal is back in %s" % typed
def test_the_running_install_is_described_by_what_it_reports():
"""Whatever mode this suite is running in, the report has to match it. The
CI runs `pip install -e`, so the editable branch is the one under the
suite; a wheel run takes the other."""
from importlib.metadata import distribution
import invisible_playwright
dist = distribution("invisible-playwright")
tree = source_tree(dist)
if tree is None:
assert invisible_playwright.__version__ == dist.version
assert EDITABLE not in invisible_playwright.__version__
else:
declared = declared_by(tree)
assert declared is not None, (
"this tree is installed editable and declares no readable version")
assert invisible_playwright.__version__ == declared + EDITABLE
assert invisible_playwright.__install_record_version__ == dist.version
+33 -16
View File
@@ -15,6 +15,7 @@ import re
import subprocess
import sys
from contextlib import redirect_stdout
from pathlib import Path
import pytest
@@ -24,12 +25,37 @@ from invisible_playwright import __version__, cli
pytestmark = pytest.mark.unit
# ⛔ A SUBPROCESS DOES NOT INHERIT pytest's `pythonpath`, SO WITHOUT THIS IT
# TESTS WHATEVER IS INSTALLED INSTEAD OF THE CODE UNDER TEST. In CI the two are
# the same thing, because the workflow installs this repository with
# `pip install -e .`; from a worktree they are not, and the arms below went red
# against a checkout they were never meant to measure. Being inside a
# repository is not evidence that a test is testing that repository.
def _run(*args):
import os
env = dict(os.environ)
here = str(Path(__file__).resolve().parents[1] / "src")
env["PYTHONPATH"] = here + os.pathsep + env.get("PYTHONPATH", "")
return subprocess.run([sys.executable, "-m", "invisible_playwright", *args],
capture_output=True, text=True, timeout=15, env=env)
def test_version_matches_installed_package_metadata():
"""__version__ must come from importlib.metadata, not a hardcoded literal,
so it can never drift from the pyproject.toml `version` field."""
def test_the_install_record_is_still_reported_under_its_own_name():
"""This asserted `__version__ == importlib.metadata.version(...)`,
with a docstring saying the point was that the version can never
drift from the `pyproject.toml` field. The assertion did not hold that: an
editable install freezes the metadata while the tree keeps moving, measured
here at 0.16.2 against a tree declaring 0.22.1. The equality was true of the
INSTALL RECORD all along, which is the fact this line was really about, and
that fact now has a name of its own.
What the docstring wanted - never drifting from the tree - is held by
`test_the_version_describes_the_code.py` against real `pip` installs.
"""
from importlib.metadata import version as pkg_version
assert __version__ == pkg_version("invisible-playwright")
assert invisible_playwright.__install_record_version__ == pkg_version(
"invisible-playwright")
def test_version_is_not_the_stale_010_string():
@@ -73,10 +99,7 @@ def test_dash_dash_version_flag_works():
no top-level --version flag, only the `version` subcommand. Now the
Python convention works too."""
# argparse's --version action calls sys.exit(0) directly, so use subprocess.
r = subprocess.run(
[sys.executable, "-m", "invisible_playwright", "--version"],
capture_output=True, text=True, timeout=15,
)
r = _run("--version")
assert r.returncode == 0, f"--version returned {r.returncode}, stderr={r.stderr!r}"
# argparse may emit on stdout or stderr depending on version
combined = r.stdout + r.stderr
@@ -87,10 +110,7 @@ def test_dash_dash_version_flag_works():
def test_no_args_prints_help_not_traceback():
"""`python -m invisible_playwright` with no args should be graceful
(print help, exit non-zero) rather than crashing with a traceback."""
r = subprocess.run(
[sys.executable, "-m", "invisible_playwright"],
capture_output=True, text=True, timeout=15,
)
r = _run()
# Either prints help (rc=2) or shows usage. Must NOT contain a traceback.
assert "Traceback" not in (r.stdout + r.stderr)
assert "usage:" in (r.stdout + r.stderr).lower()
@@ -98,10 +118,7 @@ def test_no_args_prints_help_not_traceback():
def test_dash_V_short_flag_works():
"""Alias `-V` for `--version` (Python convention)."""
r = subprocess.run(
[sys.executable, "-m", "invisible_playwright", "-V"],
capture_output=True, text=True, timeout=15,
)
r = _run("-V")
assert r.returncode == 0
assert __version__ in (r.stdout + r.stderr)