tests: the census counts a ThreadStarter from its construction, not from its thread

ThreadStarter now begins its own thread without waiting for it
(_thread.start_new_thread running Thread.start), so right after the constructor
the starter can be in no threading.enumerate(). The census of live
"invpw-thread-starter" threads then saw 0 leaks where a module built 2 (Linux
runner, 3 of 3 jobs: the inner pytest passed). Not a rename, not a wrong
count: a census of threads cannot see a thread that has not begun.

Fix at the source of the count: ThreadStarter keeps the set of starters built
and not yet ended (open_starters()), and the census counts that. The "no
Thread.start on the caller" guarantee is untouched.

Test, red on the old census (Thread.start slowed to 300 ms: the census sees 0
right after the constructor, expected 1): the census counts a starter whose
thread has not begun.
This commit is contained in:
feder-cr committed 2026-11-14 23:30:58 +01:00
1 parent 05190ed5e9
commit 65b7a3c3bc
3 files changed
+56 -5

No files matched your search

@@ -27,7 +27,20 @@ class ThreadStarter:
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
#: Every starter built and not yet ended (from the constructor, which returns before its thread runs, to the end of that thread).
#: Without it a starter whose thread has not begun yet is in no `threading.enumerate()` and nobody can count it: the census of
#: tests/_browser_census.py missed the leaked starters on a machine where the raw thread was late to run.
_open: "set" = set()
_open_lock = threading.Lock()
@classmethod
def open_starters(cls) -> list:
with cls._open_lock:
return list(cls._open)
def __init__(self, on_error: Callable[[str], None]) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.add(self)
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
@@ -38,8 +51,13 @@ class ThreadStarter:
try:
self._thread.start()
except BaseException as failure:
self._ended()
self._report("%s could not be started: %s" % (self._thread.name, failure))
def _ended(self) -> None:
with ThreadStarter._open_lock:
ThreadStarter._open.discard(self)
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's and the loop's included: builds a daemon thread and queues it. Never waits."""
if self._stopped:
@@ -63,6 +81,12 @@ class ThreadStarter:
pass
def _run(self) -> None:
try:
self._loop()
finally:
self._ended()
def _loop(self) -> None:
while True:
thread = self._queue.get()
if thread is None:
+6 -5
View File
@@ -7,7 +7,6 @@ left 635). So the number of live starters, counted when the last test of a modul
Module level and not per test: a module-scoped browser (the e2e ones) is legitimately open between its tests and closed at the end.
"""
import threading
import time
import pytest
@@ -18,18 +17,20 @@ _JOIN_SECONDS = 5.0
def starters_alive():
return [t for t in threading.enumerate() if t.name == STARTER_NAME and t.is_alive()]
"""The starters built and not ended, counted from their construction: `ThreadStarter` begins its thread without waiting for it, so
one that has not run yet is in no `threading.enumerate()` (a census of live threads missed 2 leaks on a Linux runner)."""
from invisible_playwright._juggler._threads import ThreadStarter
return ThreadStarter.open_starters()
def wait_until_back_to(before, seconds=_JOIN_SECONDS):
"""The starters still alive after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
"""The starters still open after `seconds` beyond the `before` that were there already (0 when the module closed everything)."""
deadline = time.monotonic() + seconds
while True:
extra = len(starters_alive()) - before
if extra <= 0 or time.monotonic() >= deadline:
return max(extra, 0)
for t in starters_alive():
t.join(0.05)
time.sleep(0.05)
@pytest.fixture(scope="module", autouse=True)
@@ -81,3 +81,29 @@ def test_a_browser_shared_by_the_tests_of_a_module_may_stay_open_until_the_modul
out = done.stdout + done.stderr
assert done.returncode == 0, out
assert "2 passed" in out, out
def test_the_census_counts_a_starter_whose_thread_has_not_begun(monkeypatch):
"""The starter's thread is begun without waiting for it, so right after the constructor it can be in no `threading.enumerate()`:
the census must still count it (it missed both leaks of a module on a Linux runner, 3 of 3 jobs)."""
import threading
import time
sys.path.insert(0, TESTS)
import _browser_census as census
from invisible_playwright._juggler._threads import ThreadStarter
original = threading.Thread.start
def slow_start(self):
time.sleep(0.3)
return original(self)
monkeypatch.setattr(threading.Thread, "start", slow_start)
before = len(census.starters_alive())
starter = ThreadStarter(on_error=lambda message: None)
try:
assert len(census.starters_alive()) == before + 1
finally:
starter.stop()
assert census.wait_until_back_to(before) == 0