One implementation of the humanize pref contract, and the pin surface follows the core (#200)

* One implementation of the humanize pref contract, not two

`_cursor.humanize_prefs` was a second answer to "which stealthfox.humanize*
prefs does this session get", and no code in src/ called it. The live answer is
the core's `compose_session_prefs`, reached through `_session.build_prefs`,
which the two front doors share.

The two disagreed. The core emits `stealthfox.humanize.stepMs`; the deleted
duplicate did not, so two tests were green about a pref set the product has
never produced. That is the shape that makes a dead path look maintained: it
had tests, so it read as load-bearing.

The properties those tests asserted are real and they move to the live path -
the two front doors emit the same humanize prefs, and a cap is never written
without the toggle - now measured through `build_prefs`. A known-bad mutation
of the live decision (always pass the cap through, which is what the duplicate
effectively did) turns them red.

`max_seconds_for` stays: it has two callers in `_session.py` and is the only
thing left that knows what a `humanize=` value means in seconds.

* The shim test stops passing an argument that is going away

`generate_profile` loses `fixed_gpu_class=` in the next core: it was a second
spelling of `pin["gpu.class_tier"]`. It was incidental here - what this file
protects is that the shim path and the core path produce the same prefs - so
dropping it leaves the property intact and the test working against the
published core as well as the next one.

The `forced_gpu_class` import stays, and gains an assertion. The import SHAPE
is what this file exists to protect, and that name is still exported; it is a
query now rather than a knob.

* The pinning page and its gate follow two keys out of the pin table

`codec.webspeech_synth` and `screen.tier` stop being pinnable in the next core:
one was drawn and never read (the pref is a constant, so the sampled value only
made the profile disagree with the browser on about 12% of seeds), the other
could not work by construction, since pins land after the draw.

The page loses both rows and says where they went, because a reader who
remembers a key needs to be told rather than find it absent - the rule this
file's own `fonts` test already enforces.

The gate gains the third level of an idiom it already had twice:
`_NOT_PINNABLE` for top-level scalars, `_NOT_PINNABLE_GROUPS` for whole groups,
and now `_NOT_PINNABLE_FIELDS` for a field inside a group. Each carries a
reason, and each refuses an excuse that has gone stale - either because the
field came back to the pin table or because it left the profile entirely.

* The page and the gate follow screen.avail_* out of the pin table

* Pin invisible-core 30.21.0, and say what it removes

0.16.0 has not shipped, so these entries join it rather than inventing a
version: the three pin keys that could not work, the sampled codec field that
contradicted the browser, and the deleted duplicate of the humanize pref
contract.

* Two e2e modules stop pinning keys that no longer exist, and a gate that would have said so

`screen.avail_width` and `screen.avail_height` left the pin surface, and these
two modules kept pinning them. Both are marked `e2e`, so the default selection
deselects them: every local run was green and the failure appeared on the Linux
CI leg as 81 errors, four minutes in. The migration was not incomplete because
it was hard - it was incomplete because the only thing that would have noticed
needed a browser.

Nothing about the question needs one. A pin dict is a dict of strings and
`_validate_pin_key` is a pure function, so `test_pin_dicts_are_valid.py` reads
every pin dict in src/, tests/, scripts/ and examples/ and asks the real
validator. It finds the two shapes this repository writes - `pin=` inline and a
module-level PIN shared across an e2e module - and it is killed by both: a
removed key returning to an e2e PIN, and an invented key in an inline dict.

Its first draft was red on a healthy repository, which is the state where a gate
teaches people to ignore it. Two exclusions came out of that, both deliberate
and both documented in the file: dicts inside `with pytest.raises(...)` hold
keys that are SUPPOSED to be refused, and `_NOT_PINNABLE` is a table of reasons
whose name merely contains the letters PIN.

The assertions in the two e2e modules get stronger for the change: availWidth
and availHeight are now read as values the engine computed, not as values the
caller believed it had set.
This commit is contained in:
Federico authored and GitHub committed 2026-09-15 04:32:53 +02:00
1 parent 0c061e6410
commit 8ade6f90ad
10 files changed
+270 -34

No files matched your search

+18 -1
View File
@@ -34,8 +34,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
pinned a card no validated persona carries, so the snippet a reader copied did
nothing.
- **The pinning surface loses three keys that could not work.** `screen.tier`
could not condition the screen it named, because pins are applied after the
sampler has drawn. `screen.avail_width` and `screen.avail_height` were
page-contradicting: the engine derives the available rect from `width`,
`height` and `taskbar_px`, so pinning either moved a label on the profile and
nothing a page reads. Pin `screen.width`, `screen.height` and
`screen.taskbar_px`; the available rect follows from them.
- **`codec.webspeech_synth` is gone from the profile.**
`media.webspeech.synth.enabled` is emitted as a constant `true`, which is what
retail Firefox does on desktop, so the sampled field only ever made the profile
disagree with the browser - on about 12% of seeds.
### Internal
- Requires `invisible-core==30.20.0`.
- Requires `invisible-core==30.21.0`.
- `_cursor.humanize_prefs` is deleted. It was a second implementation of the
`stealthfox.humanize*` contract with no caller in `src/`, and it disagreed with
the live one: it never emitted `stealthfox.humanize.stepMs`. The two properties
its tests asserted now run through `_session.build_prefs`, which is the
function both front doors actually call.
## [0.15.2] - 2026-09-14
+20 -4
View File
@@ -82,14 +82,31 @@ Two consequences:
### `screen.*`
`screen.avail_width` and `screen.avail_height` left this table on 2026-09-15
for the same reason as the tier: the engine derives the available rect from
`width`, `height` and `taskbar_px`, and none of the three avail values is
emitted, so pinning one moved a label on the profile and nothing a page can
read. Pin `screen.width`, `screen.height` and `screen.taskbar_px`; availWidth
and availHeight follow from them, which is what keeps two properties of one
window from disagreeing.
`screen.tier` was in this table until the same day and is not a knob: pins are
applied after the sampler has drawn, so pinning the tier could not condition the
screen it names, and it emitted no preference. It is the sampler's own label for
the screen it chose, and it is still on the profile as one. Pin `screen.width`
and `screen.height` to choose a screen.
`codec.webspeech_synth` left the table the same day, and left the profile with
it. `media.webspeech.synth.enabled` is emitted as a constant `true`, which is
what retail Firefox does on desktop; the sampled field only ever made the
profile disagree with the browser, on about 12% of seeds.
| Key | Type | Example |
|-----|------|---------|
| `screen.width` | int | `2560` |
| `screen.height` | int | `1440` |
| `screen.avail_width` | int | `2560` |
| `screen.avail_height` | int | `1400` |
| `screen.dpr` | float | `1.0`, `1.25`, `1.5`, `2.0` |
| `screen.tier` | str | `"1080p"`, `"1440p"`, `"4k"`, ... |
| `screen.color_depth` | int | `24` | `screen.colorDepth` and `screen.pixelDepth`. Declared rather than read off the panel: the engine only returned a fixed 24 when resistFingerprinting was on, which we do not turn on because it is itself a tell, so before this it reported the real display - 30 on a wide-gamut monitor, and a persona claiming an office laptop with a 30-bit panel is a contradiction a page can read. |
### `hardware.*`
@@ -126,7 +143,6 @@ Two consequences:
| `codec.webm_encoder_enabled` | `MediaRecorder` advertises WebM support. |
| `codec.mediasource_webm` | `MediaSource.isTypeSupported('video/webm')`. |
| `codec.mediasource_mp4` | `MediaSource.isTypeSupported('video/mp4')`. |
| `codec.webspeech_synth` | `speechSynthesis.getVoices()` returns a fabricated voice list. |
### `webgl.*` - retired
+1 -1
View File
@@ -69,7 +69,7 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==30.20.0",
"invisible_core==30.21.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and the Node driver in
# src/invisible_playwright/_driver/. Reintroducing it would not visibly
-14
View File
@@ -327,19 +327,6 @@ def max_seconds_for(humanize: Any) -> float:
return value if value > 0 else _DEFAULT_MAX_SECONDS
def humanize_prefs(engine: str, humanize: Any) -> dict:
"""The browser prefs implied by the chosen engine.
One definition for both the sync and the async launcher, because getting
this wrong in one of them is a silent double expansion: the wrapper draws a
path, and the browser then draws a path between each pair of our waypoints.
"""
prefs: dict = {"stealthfox.humanize": engine == ENGINE_BINARY}
if engine == ENGINE_BINARY:
prefs["stealthfox.humanize.maxTime"] = str(max_seconds_for(humanize))
return prefs
def landing_enabled() -> bool:
"""Whether an action may be told to click somewhere other than the centre."""
return (os.environ.get(LANDING_ENV) or "").strip().lower() not in (
@@ -1607,7 +1594,6 @@ __all__ = [
"LANDING_ENV",
"MIN_EVENT_INTERVAL_MS",
"enable_for",
"humanize_prefs",
"landing_enabled",
"max_seconds_for",
"motion_available",
+9 -2
View File
@@ -67,8 +67,15 @@ def test_shim_output_matches_core_output():
from invisible_playwright.prefs import translate_profile_to_prefs as tp_pw
import invisible_core as ic
a = tp_pw(gp_pw(42, fixed_gpu_class=fgc_pw(42)))
b = ic.translate_profile_to_prefs(ic.generate_profile(42, fixed_gpu_class=ic.forced_gpu_class(42)))
# No `fixed_gpu_class=`: `generate_profile` lost that argument in core
# 30.21.0, where it was a second spelling of `pin["gpu.class_tier"]`. It was
# incidental here anyway - what this asserts is that the shim path and the
# core path produce the same prefs, and both still reach the same function.
# `forced_gpu_class` is still imported above, because the import SHAPE is
# what this file exists to protect; it is a query now rather than a knob.
assert fgc_pw(42) == ic.forced_gpu_class(42)
a = tp_pw(gp_pw(42))
b = ic.translate_profile_to_prefs(ic.generate_profile(42))
assert a == b
+30 -6
View File
@@ -271,16 +271,40 @@ def test_sync_and_async_agree_on_the_prefs(stub_motion):
sync = InvisiblePlaywright(seed=42, humanize=humanize)
asy = AsyncInvisiblePlaywright(seed=42, humanize=humanize)
assert sync._cursor_engine == asy._cursor_engine
assert (
_cursor.humanize_prefs(sync._cursor_engine, humanize)
== _cursor.humanize_prefs(asy._cursor_engine, humanize)
)
assert _humanize_subset(sync) == _humanize_subset(asy)
def _humanize_subset(session):
"""The `stealthfox.humanize*` prefs a session would actually launch with.
Through `build_prefs`, which is the function both front doors call and the
only thing that reaches the browser. These two assertions used to run
against `_cursor.humanize_prefs`, a second implementation of this contract
that no code in src/ called: it was missing `stealthfox.humanize.stepMs`,
which the live path emits, so the tests were green about a pref set the
product never produced. The function is gone; the properties move here.
"""
from invisible_playwright._session import build_prefs
from invisible_core import generate_profile
prefs = build_prefs(
profile=generate_profile(seed=42), locale="en-US", timezone="UTC",
extra_prefs=None, headless=False, virtual_display=False,
cursor_engine=session._cursor_engine, humanize=session._humanize,
show_cursor=None)
return {k: v for k, v in prefs.items() if k.startswith("stealthfox.humanize")}
@pytest.mark.unit
def test_humanize_prefs_never_sets_maxtime_without_the_toggle():
def test_maxtime_is_never_set_without_the_toggle():
"""A cap with the generator off would be a value nothing reads, and the
browser deciding it had a budget for a path the driver is already drawing."""
from invisible_playwright._session import build_prefs
from invisible_core import generate_profile
for engine in (_cursor.ENGINE_PYTHON, _cursor.ENGINE_OFF):
prefs = _cursor.humanize_prefs(engine, True)
prefs = build_prefs(
profile=generate_profile(seed=42), locale="en-US", timezone="UTC",
extra_prefs=None, headless=False, virtual_display=False,
cursor_engine=engine, humanize=True, show_cursor=None)
assert prefs["stealthfox.humanize"] is False
assert "stealthfox.humanize.maxTime" not in prefs
+6 -2
View File
@@ -33,8 +33,12 @@ from invisible_playwright import InvisiblePlaywright
PIN = {
"screen.width": 1920,
"screen.height": 1080,
"screen.avail_width": 1920,
"screen.avail_height": 1040,
# `screen.avail_width` / `screen.avail_height` were pinned here until
# 2026-09-15 and are no longer pin keys: the engine derives the available
# rect from width, height and taskbar_px, so pinning them moved a label on
# the profile and nothing a page reads. The assertions below get stronger
# for it - they now check a value the engine computed rather than one the
# caller thought it had set.
"screen.dpr": 1.0,
"hardware.concurrency": 8,
"audio.sample_rate": 48000,
+6 -2
View File
@@ -43,8 +43,12 @@ from invisible_playwright import InvisiblePlaywright
PIN = {
"screen.width": 1920,
"screen.height": 1080,
"screen.avail_width": 1920,
"screen.avail_height": 1040,
# `screen.avail_width` / `screen.avail_height` were pinned here until
# 2026-09-15 and are no longer pin keys: the engine derives the available
# rect from width, height and taskbar_px, so pinning them moved a label on
# the profile and nothing a page reads. The assertions below get stronger
# for it - they now check a value the engine computed rather than one the
# caller thought it had set.
"screen.dpr": 1.0,
"hardware.concurrency": 8,
"audio.sample_rate": 48000,
+149
View File
@@ -0,0 +1,149 @@
"""Every pin dict written anywhere in this repository is accepted by the validator.
WHY THIS EXISTS. On 2026-09-15 three keys left the pin surface in
`invisible_core`, and two test files here kept pinning two of them. Both files
are marked `e2e`, so the default selection - `-m 'not slow and not e2e'` -
deselects them: every local run was green, and the failure appeared on a CI leg
that launches a browser, as **81 errors** in a job that takes four minutes to
say so. The migration was not incomplete because it was hard. It was incomplete
because the only thing that would have noticed needed a browser.
Nothing here needs a browser. A pin dict is a dict of strings, and
`_validate_pin_key` is a pure function, so the question "does this key exist"
can be answered by reading the source and calling it. That is the whole gate.
It finds pin dicts two ways, because the repository writes them two ways:
* a dict passed as `pin=` to any call, anywhere;
* a module-level dict named `PIN`, `*_PIN` or `PIN_*`, which is the shape the
e2e files use so one profile can be shared by a module of tests.
And it skips two things on purpose, both found by the first draft going red on a
perfectly healthy repository - the state in which a gate teaches people to
ignore it:
* anything inside `with pytest.raises(...)`. Those dicts hold keys that are
SUPPOSED to be refused; flagging them would be flagging the test for
testing. Four files do this deliberately.
* names that merely contain the letters PIN. `_NOT_PINNABLE` is a table of
reasons, not a pin dict, and matching it read its explanations as keys.
Only STRING keys are checked. A key built at runtime is not something a reader
can check either, and there are none today.
"""
from __future__ import annotations
import ast
import pathlib
import pytest
from invisible_core._fpforge.profile import _validate_pin_key
pytestmark = pytest.mark.unit
_ROOT = pathlib.Path(__file__).resolve().parents[1]
_TREES = ("src", "tests", "scripts", "examples")
def _python_files():
for tree in _TREES:
d = _ROOT / tree
if not d.is_dir():
continue
for f in d.rglob("*.py"):
if "__pycache__" in str(f) or "/_pw/" in str(f).replace("\\", "/"):
continue
yield f
def _is_pin_name(name: str) -> bool:
u = name.upper()
return u == "PIN" or u.endswith("_PIN") or u.startswith("PIN_")
def _raising_lines(tree) -> set:
"""Every line inside a `with pytest.raises(...)` block."""
out = set()
for node in ast.walk(tree):
if not isinstance(node, (ast.With, ast.AsyncWith)):
continue
for item in node.items:
call = item.context_expr
if (isinstance(call, ast.Call)
and isinstance(call.func, ast.Attribute)
and call.func.attr == "raises"):
out.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))
return out
def _pin_dicts(path: pathlib.Path):
"""(line, [keys]) for every pin dict literal in one file."""
try:
tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
except SyntaxError: # not ours to judge
return
refused = _raising_lines(tree)
for node in ast.walk(tree):
if isinstance(node, ast.Call):
for kw in node.keywords:
if (kw.arg == "pin" and isinstance(kw.value, ast.Dict)
and kw.value.lineno not in refused):
yield kw.value.lineno, _string_keys(kw.value)
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):
names = [t.id for t in node.targets if isinstance(t, ast.Name)]
if any(_is_pin_name(n) for n in names):
yield node.value.lineno, _string_keys(node.value)
def _string_keys(d: ast.Dict):
return [k.value for k in d.keys
if isinstance(k, ast.Constant) and isinstance(k.value, str)]
def test_every_pin_dict_in_the_repository_uses_keys_that_exist():
bad = []
for path in _python_files():
for line, keys in _pin_dicts(path):
for key in keys:
try:
_validate_pin_key(key)
except ValueError as exc:
bad.append("%s:%d %r - %s"
% (path.relative_to(_ROOT), line, key,
str(exc).split(".")[0]))
assert not bad, (
"these pin dicts name keys the validator refuses, so every call that "
"uses them raises:\n " + "\n ".join(bad) +
"\nThe pin surface lives in invisible_core; a key that left it has to "
"leave here too.")
def test_the_scan_actually_finds_the_dicts_it_claims_to():
"""A gate that scanned nothing would pass this file forever.
Both shapes have to be found, because both exist: the e2e modules build a
module-level PIN and share it across a module of tests, while the unit tests
pass `pin=` inline. If either count goes to zero, the scan stopped matching
the way the repository is written rather than the repository becoming clean.
"""
inline = module_level = 0
for path in _python_files():
src = path.read_text(encoding="utf-8", errors="replace")
try:
tree = ast.parse(src)
except SyntaxError:
continue
for node in ast.walk(tree):
if isinstance(node, ast.Call):
inline += sum(1 for kw in node.keywords
if kw.arg == "pin" and isinstance(kw.value, ast.Dict))
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):
if any(_is_pin_name(t.id) for t in node.targets
if isinstance(t, ast.Name)):
module_level += 1
assert inline >= 5, f"only {inline} inline `pin=` dicts found; the scan is blind"
assert module_level >= 2, (
f"only {module_level} module-level PIN dicts found; the e2e modules use "
f"that shape and they are what this gate was written for")
+31 -2
View File
@@ -40,6 +40,25 @@ _NOT_PINNABLE = {
"_raw": "the pre-profile sample dict, not an axis",
}
#: Individual group FIELDS that exist on the profile and are deliberately not
#: pinnable. Third level of the same idea as the scalar list above and the group
#: list below: a field with no pin entry is either a decision or an omission, and
#: only one of those should pass.
_NOT_PINNABLE_FIELDS = {
"screen.tier": ("The sampler's own label for the screen it drew ('1440p'). "
"Pins are applied after the draw, so pinning the tier could "
"not condition the screen it names, and it emitted no "
"preference either. Removed from the pin table 2026-09-15; "
"the field stays because the label is honest."),
"screen.avail_width": ("Derived, not chosen. The engine computes the "
"available rect from width, height and taskbar_px, "
"and no avail value is emitted, so a pin moved the "
"label and nothing a page reads. Removed 2026-09-15."),
"screen.avail_height": ("Same as avail_width, and removing it also removed "
"the special case that let a pin beat the taskbar "
"re-derivation: there is no pin left to lose to."),
}
#: Profile GROUPS that exist but are deliberately not pinnable, with the reason.
#: Same idea as _NOT_PINNABLE one level up: a group with no pin table is either a
#: decision or an omission, and only one of those should pass.
@@ -164,9 +183,19 @@ def test_the_validators_key_table_matches_the_profile_it_pins():
for group, fields in sorted(model.items()):
if group in _NOT_PINNABLE_GROUPS:
continue
assert _PIN_GROUPS[group] == fields, (
excused = {f for f in fields if f"{group}.{f}" in _NOT_PINNABLE_FIELDS}
assert _PIN_GROUPS[group] == fields - excused, (
f"group {group!r}: the validator accepts {sorted(_PIN_GROUPS[group])}, "
f"the profile has {sorted(fields)}")
f"the profile has {sorted(fields)}, excused {sorted(excused)}")
stale_fields = sorted(k for k in _NOT_PINNABLE_FIELDS if k in _valid_keys())
assert not stale_fields, (
f"_NOT_PINNABLE_FIELDS still excuses {stale_fields}, which is pinnable "
f"again. A stale excuse reads as a decision that still holds.")
unknown_fields = sorted(
k for k in _NOT_PINNABLE_FIELDS
if k.split(".", 1)[0] not in model or k.split(".", 1)[1] not in model[k.split(".", 1)[0]])
assert not unknown_fields, (
f"_NOT_PINNABLE_FIELDS names fields the profile no longer has: {unknown_fields}")
def test_top_level_fields_are_either_pinnable_or_listed_as_deliberately_not():