Compare commits

...
Author SHA1 Message Date
feder-cr cb2bb27c0b HUNT SCAFFOLDING, NEVER MERGED: slow listeners on the reader, Windows only, new code only (core pinned to 2ef06c7), 15 rounds x 4: every listener call timed (wall, CPU cycles), a sampler of the reader's stack while a call lasts over 20 ms, decode time with size, all in memory and written once at exit 2026-11-14 08:43:52 +01:00
feder-cr d56c473f22 HUNT SCAFFOLDING, NEVER MERGED: every stamp is a list in memory written once at exit; a no-patcher control pass (old and new) first, its misses counted defect vs not yet asked and put first in the summary 2026-11-14 00:49:45 +01:00
feder-cr 987b935727 HUNT SCAFFOLDING, NEVER MERGED: locks hunt on Windows, new arm only, 15 rounds x 4: times the reader's path (listeners, events gate, every lock, wall against CPU) between the pipe read and Lifecycle._on_event 2026-11-14 00:44:20 +01:00
feder-cr 08b35a6adb HUNT SCAFFOLDING, NEVER MERGED: noreader hunt on Windows only, old and new, 15 rounds x 4, with server, pipe-reader and lifecycle stamps of every /landed 2026-11-13 21:52:41 +01:00
feder-cr 5f7946f05f HUNT SCAFFOLDING, NEVER MERGED: goto(networkidle) and the typing test, old against new (no thread on the reader) against stock, Windows and Linux 2026-11-13 19:25:51 +01:00
feder-cr fc9161f812 server: no thread is started on the engine connection's reader; one long-lived starter does it
Thread.start waits until the new thread runs, and the reader is the thread every event of the engine waits behind. Browser.attachedToTarget
(one thread per adoption, _spawn_adoption) and Page.fileChooserOpened (one thread to announce the chooser) started a thread from the
reader. They now hand a Thread that is only built there to the browser's _ThreadStarter, one daemon thread made with the browser, which
starts it. The starter starts threads and does not run the work: an adoption waits for the engine without a limit, and a worker that ran
it would hold every later adoption (and new_page) behind a slow popup. The adoption keeps its own thread and its name.

Test: the real dispatchers over a scripted connection, events delivered from a thread of their own, Thread.start recorded; red on the old
code (two starts from the reader). The Page.eventFired(load) case is skipped with a core that still starts a Timer for networkidle.
2026-11-13 19:17:44 +01:00
13 changed files with 2207 additions and 6 deletions

No files matched your search

@@ -0,0 +1,151 @@
# reader-slow-listeners-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/reader-slow-listeners**` branch.
# With the reader fix in place (no Thread.start on the core's pipe reader: core #263, wrapper fc9161f) a few listener calls on the reader
# thread are still slow (measured before: BrowserDispatcher._route_browser_event up to 318 ms, PageDispatcher._route_juggler_event 217 ms,
# Lifecycle._route 106 / 79 ms, a message decode 154 ms). WHICH LINE OF CODE is the call on while it is slow?
# Windows only, 15 rounds x 4 processes at once, ONE arm (the new code), in memory only (nothing is opened or written on the reader during a
# run; one write per process at exit), see scripts/hunt_slow_runtime.py:
# (1) every listener call on the reader: wall, CPU (cycle counter), event, listener (totals for all, a row from 2 ms);
# (2) a sampler thread: while a listener call (or a decode) has lasted over 20 ms, sys._current_frames()[reader] every 2 ms, the
# innermost 12 frames;
# (3) the json.loads of a message over 20 ms, with its size;
# (4) off-CPU per call = wall - CPU.
# The core is pinned to oss-invisible/core commit 2ef06c7 (#263, the reader fix); the wrapper is this checkout (the 0.51.1 line) with
# server.py overlaid from the wrapper's reader-fix branch when it still exists, else from origin/main if that has the fix.
name: reader slow listeners hunt
on:
push:
branches: ['hunt/reader-slow-listeners**']
permissions:
contents: read
concurrency:
group: reader-slow-listeners-hunt-${{ github.ref }}
cancel-in-progress: true
env:
GITHUB_TOKEN: ${{ github.token }}
PYTHONUNBUFFERED: "1"
CORE_SHA: 2ef06c776bef5cf1d90b887df7251b72e792200b
WRAPPER_FIX_BRANCH: fix/no-thread-started-on-the-reader
jobs:
hunt:
name: slow listeners hunt windows
runs-on: windows-2022
timeout-minutes: 120
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The wrapper side of the reader fix (server.py), and the pins
run: |
set -e
mkdir -p evidence
SERVER=src/invisible_playwright/_juggler/server.py
{
echo "wrapper checkout: $(git rev-parse HEAD)"
echo "core pin: $CORE_SHA"
} | tee evidence/pins.txt
if timeout 300 git fetch --depth 50 origin "+refs/heads/$WRAPPER_FIX_BRANCH:refs/remotes/origin/$WRAPPER_FIX_BRANCH"; then
SRC="origin/$WRAPPER_FIX_BRANCH"
SRC_WHY="the branch $WRAPPER_FIX_BRANCH still exists"
else
# the branch is gone: main must carry the fix
timeout 300 git fetch --depth 200 origin main
if git log --oneline origin/main | grep -i "no thread is started on the engine connection"; then
SRC="origin/main"
SRC_WHY="the branch $WRAPPER_FIX_BRANCH is gone and origin/main has the fix"
else
echo "neither the branch $WRAPPER_FIX_BRANCH nor origin/main has the wrapper side of the reader fix"
exit 1
fi
fi
# blob ids, not bytes: the runner's checkout may carry CRLF
if [ "$(git rev-parse "$SRC:$SERVER")" = "$(git rev-parse "HEAD:$SERVER")" ]; then
CHANGED="identical to this checkout's, nothing overlaid"
else
git show "$SRC:$SERVER" > "$SERVER"
CHANGED="DIFFERENT from this checkout's, overlaid"
fi
echo "server.py from $SRC ($(git rev-parse "$SRC")): $SRC_WHY; $CHANGED" | tee -a evidence/pins.txt
- name: One environment, and the core of commit 2ef06c7
run: |
set -e
NEWPY="$RUNNER_TEMP/venv-new/Scripts/python.exe"
echo "NEWPY=$NEWPY" >> "$GITHUB_ENV"
timeout 300 python -m venv "$RUNNER_TEMP/venv-new"
timeout 300 "$NEWPY" -m pip install --quiet --upgrade pip
timeout 300 "$NEWPY" -m pip install --quiet ".[dev]"
timeout 300 "$NEWPY" -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
# the core: clone, check out the pin, install over the wheel the wrapper pulled in
timeout 300 git clone --quiet https://github.com/oss-invisible/core.git "$RUNNER_TEMP/core"
git -C "$RUNNER_TEMP/core" checkout --quiet "$CORE_SHA"
GOT="$(git -C "$RUNNER_TEMP/core" rev-parse HEAD)"
test "$GOT" = "$CORE_SHA" || { echo "the core is at $GOT, not $CORE_SHA"; exit 1; }
echo "core commit: $(git -C "$RUNNER_TEMP/core" log -1 --format='%H %s')" | tee -a evidence/pins.txt
timeout 300 "$NEWPY" -m pip install --quiet --force-reinstall --no-deps "$RUNNER_TEMP/core"
CONN="$("$NEWPY" -c "import importlib.util as u; print(u.find_spec('invisible_core.juggler.connection').origin)")"
cmp "$CONN" "$RUNNER_TEMP/core/src/invisible_core/juggler/connection.py"
echo "installed connection.py is the one of the pin" | tee -a evidence/pins.txt
"$NEWPY" -m pip list 2>/dev/null | grep -iE "^(invisible|playwright)" | tee -a evidence/pins.txt || true
"$NEWPY" -c "import invisible_core, invisible_playwright as w; print('core', invisible_core.__version__, invisible_core.__file__); print('wrapper', w.__file__)" | tee -a evidence/pins.txt
- name: The browser, the lab GeoIP database
run: |
set -e
timeout 300 "$NEWPY" scripts/ci_lab_geoip.py build
echo "FF_NEW=$(cd "$RUNNER_TEMP" && timeout 300 "$NEWPY" -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
- name: The instrumentation (in memory, one write per process at exit)
run: |
set -e
timeout 300 "$NEWPY" scripts/hunt_trace_slow.py
# the patched module imports and the hooks are in place, before fifteen rounds are spent on them
HUNT_SLOW_TRACE="$RUNNER_TEMP/selftest.jsonl" "$NEWPY" -c "import invisible_core._hunt_slow as h, invisible_core.juggler.connection as c, invisible_playwright._juggler.server; assert c.Connection.dispatch_event is h.dispatch_event; assert h.ENABLED and h.STATE['cyc_per_s'], h.STATE; print('hooks ok, cycles per second', h.STATE['cyc_per_s'])"
- name: HUNT - the new code, four processes at once, fifteen rounds
run: |
set +e
echo "binary: $FF_NEW"
for n in $(seq 1 15); do
for c in 1 2 3 4; do
HUNT_SLOW_TRACE="evidence/slow_${n}_$c.jsonl" timeout 300 "$NEWPY" -u scripts/hunt_netidle.py ours "$FF_NEW" \
> "evidence/netidle_${n}_$c.log" 2>&1 &
done
wait
taskkill //F //T //IM firefox.exe > /dev/null 2>&1 || true
echo "round $n done"
done
exit 0
- name: Step summary
if: always()
run: |
set +e
{
echo '```'
cat evidence/pins.txt
echo '```'
echo
timeout 300 "$NEWPY" scripts/hunt_slow_summary.py windows-2022 evidence 50 20
echo
echo "### Tracebacks and errors in the netidle logs"
echo '```'
grep -ahE "Traceback|Error" evidence/netidle_*.log | cut -c1-160 | sort | uniq -c | sort -rn | head -12
echo '```'
} 2>&1 | tee -a "$GITHUB_STEP_SUMMARY"
exit 0
- name: Close every Firefox left
if: always()
run: |
taskkill //F //T //IM firefox.exe > /dev/null 2>&1 || true
exit 0
- name: Upload the evidence
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: reader-slow-listeners-${{ github.run_id }}
path: evidence
if-no-files-found: warn
retention-days: 14
+482
View File
@@ -0,0 +1,482 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the runtime that scripts/hunt_trace_locks.py copies into the installed invisible_core as
invisible_core/_hunt_locks.py. It times, on the connection's READER thread only, where a message spends the time between the pipe read and
the lifecycle:
(a) every listener call of Connection.dispatch_event (row k=lst: name, event, wall ms, cpu ms),
(b) the wrapper's gated_dispatch wait on the events gate (row k=gate, with who held it),
(c) every lock / condition the reader takes or waits on; a wait of 5 ms or more is a row k=lock (name, ms, holder, where it was taken),
(d) per message: wall against CPU time of the thread (row k=msg), so wall - cpu - lock waits - gate = time off the CPU (GIL, preemption).
One JSON line per row, to $HUNT_LOCKS_TRACE (one file per process), WRITTEN ONCE, at process exit (atexit): during the run every row is only
appended to a list in memory, there is no file open, no write and no thread of the hunt's own on the run. The rows of everything small are not written but are counted in a
{"k": "totals"} row written at the end (and the rows of the messages of a chunk that carries /landed are all written). Times in rows are
time.time() of the END of the span, "ms" its length (time.perf_counter()), so a row is [t - ms/1000, t] on the wall clock of the other stamps.
Nothing here may break the engine: every hook swallows its own failure.
"""
import atexit
import json
import os
import sys
import threading
import time
LOCK_ROW_MS = 5.0 # a wait this long or longer is a row
LST_ROW_MS = 0.5 # a listener call this long or longer is a row (all of them in a /landed chunk)
MSG_ROW_MS = 1.0 # a message this long or longer is a row (all of them in a /landed chunk)
GATE_ROW_MS = 1.0
_pc = time.perf_counter
READERS: set = set()
_TL = threading.local()
ROWS: list = []
TOTALS: dict = {} # item -> [n, sum ms, max ms]
MSGS = {"n": 0, "wall_ms": 0.0, "cpu_ts_ms": 0.0, "cpu_cyc_ms": 0.0, "chunks": 0, "bytes": 0}
_state = {"started": False, "cyc_per_s": None, "pid": os.getpid()}
# ── cpu time of the calling thread ────────────────────────────────────────────────────────────────────────────────────────────────
# time.thread_time() on Windows is GetThreadTimes: accounted per scheduler tick (~15.6 ms), too coarse for a message. The cycle counter
# of the thread (QueryThreadCycleTime) is exact; its rate is measured once, in short slices, taking the best slice (a slice that was
# not preempted), because the cycles tick only while the thread runs.
_cycles = None
if sys.platform == "win32":
try:
import ctypes
_k32 = ctypes.windll.kernel32
_k32.GetCurrentThread.restype = ctypes.c_void_p
_k32.QueryThreadCycleTime.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulonglong)]
_k32.QueryThreadCycleTime.restype = ctypes.c_int
_cyc_box = threading.local()
def _cycles():
box = getattr(_cyc_box, "v", None)
if box is None:
box = _cyc_box.v = ctypes.c_ulonglong()
_k32.QueryThreadCycleTime(_k32.GetCurrentThread(), ctypes.byref(box))
return box.value
except Exception:
_cycles = None
def _calibrate():
"""cycles per second of a thread that runs, from the best of 25 slices of about 3 ms of busy work. None if there is no counter."""
if _cycles is None:
return None
best = 0.0
for _ in range(25):
c0, t0 = _cycles(), _pc()
while _pc() - t0 < 0.003:
pass
c1, t1 = _cycles(), _pc()
if t1 > t0 and c1 > c0:
best = max(best, (c1 - c0) / (t1 - t0))
return best or None
def _cpu_ms_cycles(c0, c1):
rate = _state["cyc_per_s"]
if _cycles is None or not rate:
return None
return (c1 - c0) / rate * 1000.0
def _mark_cpu():
return (time.thread_time(), _cycles() if _cycles is not None else 0)
# ── rows and totals ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def _path():
return os.environ.get("HUNT_LOCKS_TRACE")
def _row(**r):
if _path():
ROWS.append(r)
def _count(item, ms):
t = TOTALS.get(item)
if t is None:
TOTALS[item] = [1, ms, ms]
else:
t[0] += 1
t[1] += ms
if ms > t[2]:
t[2] = ms
def flush(final=True):
"""Once, at exit: every row, then the totals."""
path = _path()
if not path:
return
try:
n = len(ROWS)
batch = ROWS[:n]
del ROWS[:n]
lines = [json.dumps(r, default=str) for r in batch]
if final:
lines.append(json.dumps({"k": "totals", "pid": _state["pid"], "cyc_per_s": _state["cyc_per_s"], "msgs": MSGS,
"items": {k: [v[0], round(v[1], 3), round(v[2], 3)] for k, v in TOTALS.items()}}))
if lines:
with open(path, "a", encoding="utf-8") as fh:
fh.write("\n".join(lines) + "\n")
except Exception:
pass
def _start():
"""From the thread that builds a Connection, never from the reader: the CPU calibration, and the one write at exit."""
if _state["started"] or not _path():
return
_state["started"] = True
try:
_state["cyc_per_s"] = _calibrate()
atexit.register(flush)
except Exception:
pass
def _on_reader():
return threading.get_ident() in READERS
def _ev():
return getattr(_TL, "method", None)
def _site(frame):
try:
return "%s:%d" % (os.path.basename(frame.f_code.co_filename), frame.f_lineno)
except Exception:
return None
# ── a lock that says who holds it and how long the reader waited for it ────────────────────────────────────────────────────────────
class Timed:
"""Stands in for a Lock, RLock or Condition (what they have of acquire / release / with / wait / notify). It delegates to the real one."""
def __init__(self, real, name, quiet=False):
self._real = real
self._name = name
self._quiet = quiet
self._depth = 0
self.owner_name = None
self.owner_t = 0.0
self.owner_site = None
# who holds it now (read without a lock: a hint, and said so)
def _snap(self):
n = self.owner_name
if n is None:
return None
return (n, self.owner_t, self.owner_site)
def _mark(self, frame):
self._depth += 1
self.owner_name = threading.current_thread().name
self.owner_t = _pc()
self.owner_site = _site(frame)
def _waited(self, kind, ms, snap, got=True):
"""Called on the reader only. The events gate (quiet) is timed by gate_end instead."""
if self._quiet:
return
_TL.lock_ms = getattr(_TL, "lock_ms", 0.0) + ms
_count("%s:%s" % (kind, self._name), ms)
if ms >= LOCK_ROW_MS and not self._quiet:
held_ms = None
if snap is not None:
held_ms = round((_pc() - snap[1]) * 1000, 1)
_row(k="lock", op=kind, name=self._name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev(), got=got,
holder=snap[0] if snap else None, held_at=snap[2] if snap else None, held_so_far_ms=held_ms)
def acquire(self, *args, **kw):
frame = sys._getframe(1)
return self._acq(args, kw, frame)
def _acq(self, args, kw, frame):
try:
reader = threading.get_ident() in READERS
except Exception:
reader = False
if reader:
snap = self._snap()
t0 = _pc()
ok = self._real.acquire(*args, **kw)
ms = (_pc() - t0) * 1000.0
if ok:
self._mark(frame)
try:
self._waited("lock", ms, snap, ok)
except Exception:
pass
return ok
ok = self._real.acquire(*args, **kw)
if ok:
self._mark(frame)
return ok
def release(self):
if self._depth > 0:
self._depth -= 1
if self._depth == 0:
self.owner_name = None
return self._real.release()
def __enter__(self):
self._acq((), {}, sys._getframe(1))
return self
def __exit__(self, *exc):
self.release()
return None
def locked(self):
return self._real.locked()
def _is_owned(self):
return self._real._is_owned()
# Condition
def wait(self, timeout=None):
depth = self._depth
self._depth = 0
self.owner_name = None
reader = _on_reader()
snap = None
t0 = _pc()
try:
return self._real.wait(timeout)
finally:
ms = (_pc() - t0) * 1000.0
self._depth = depth
self.owner_name = threading.current_thread().name
self.owner_t = _pc()
self.owner_site = _site(sys._getframe(1))
if reader:
try:
# a wait is a pause the caller asked for; it is counted apart, and not into the lock waits of the message
_count("wait:%s" % self._name, ms)
if ms >= LOCK_ROW_MS and not self._quiet:
_row(k="lock", op="wait", name=self._name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev(), got=True,
holder=snap, held_at=None, held_so_far_ms=None)
except Exception:
pass
def wait_for(self, predicate, timeout=None):
endtime = None
waittime = timeout
result = predicate()
while not result:
if waittime is not None:
if endtime is None:
endtime = time.monotonic() + waittime
else:
waittime = endtime - time.monotonic()
if waittime <= 0:
break
self.wait(waittime)
result = predicate()
return result
def notify(self, n=1):
return self._real.notify(n)
def notify_all(self):
return self._real.notify_all()
notifyAll = notify_all
def __getattr__(self, name):
return getattr(self._real, name)
def timed(real, name, quiet=False):
if isinstance(real, Timed):
return real
return Timed(real, name, quiet)
def hook_class(cls, names, prefix=""):
"""After cls.__init__, each attribute of `names` that exists on the instance is replaced by a Timed over the real object."""
original = cls.__init__
if getattr(original, "_hunt_wrapped", False):
return
def __init__(self, *a, **k):
original(self, *a, **k)
try:
for n in names:
v = self.__dict__.get(n)
if v is not None and not isinstance(v, Timed):
self.__dict__[n] = Timed(v, prefix + n)
except Exception:
pass
__init__._hunt_wrapped = True
__init__.__qualname__ = original.__qualname__
cls.__init__ = __init__
def timed_fn(fn, name):
"""A function whose duration, on the reader, is counted as `name` (a row from 1 ms)."""
def wrapper(*a, **k):
if not _on_reader():
return fn(*a, **k)
t0 = _pc()
try:
return fn(*a, **k)
finally:
ms = (_pc() - t0) * 1000.0
_count(name, ms)
if ms >= 1.0:
_row(k="io", name=name, ms=round(ms, 3), t=round(time.time(), 4), ev=_ev())
return wrapper
# ── the connection ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def _listener_name(fn):
try:
owner = getattr(fn, "__self__", None)
q = getattr(fn, "__qualname__", None) or getattr(fn, "__name__", None) or repr(fn)
if owner is not None and "." not in q:
q = "%s.%s" % (type(owner).__name__, q)
return q
except Exception:
return "?"
def _core_dispatch_event(self, method, params, session):
"""Connection.dispatch_event with each listener timed on the reader. Same loop as the core's."""
self.delivered += 1
with self._listeners_lock:
subscribers = list(self._listeners)
reader = _on_reader()
if reader:
_TL.method = method
verbose = getattr(_TL, "verbose", False)
for fn in subscribers:
if reader:
t0 = _pc()
u0, c0 = _mark_cpu()
try:
fn(method, params, session)
except Exception as failure:
if len(self.handler_errors) < 32:
self.handler_errors.append("%s: %s" % (method, failure))
if reader:
try:
ms = (_pc() - t0) * 1000.0
u1, c1 = _mark_cpu()
name = _listener_name(fn)
_count("lst:" + name, ms)
_TL.lst_ms = getattr(_TL, "lst_ms", 0.0) + ms
if ms >= LST_ROW_MS or verbose:
cyc = _cpu_ms_cycles(c0, c1)
_row(k="lst", name=name, ev=method, ms=round(ms, 3), t=round(time.time(), 4),
cpu_ts=round((u1 - u0) * 1000, 3), cpu_cyc=None if cyc is None else round(cyc, 3))
except Exception:
pass
def _wrap_deliver(orig):
def _deliver(self, raw):
if not _on_reader():
return orig(self, raw)
_TL.lock_ms = 0.0
_TL.gate_ms = 0.0
_TL.lst_ms = 0.0
_TL.method = None
t0 = _pc()
u0, c0 = _mark_cpu()
try:
return orig(self, raw)
finally:
try:
wall = (_pc() - t0) * 1000.0
u1, c1 = _mark_cpu()
cpu_ts = (u1 - u0) * 1000.0
cyc = _cpu_ms_cycles(c0, c1)
MSGS["n"] += 1
MSGS["wall_ms"] += wall
MSGS["cpu_ts_ms"] += cpu_ts
if cyc is not None:
MSGS["cpu_cyc_ms"] += cyc
landed = b"/landed" in raw and b"requestWillBeSent" in raw
if wall >= MSG_ROW_MS or landed or getattr(_TL, "verbose", False):
_row(k="msg", t=round(time.time(), 4), ms=round(wall, 3), cpu_ts=round(cpu_ts, 3),
cpu_cyc=None if cyc is None else round(cyc, 3), lock=round(_TL.lock_ms, 3), gate=round(_TL.gate_ms, 3),
lst=round(_TL.lst_ms, 3), ev=_ev(), landed=landed, n=len(raw))
except Exception:
pass
return _deliver
def chunk_begin():
return _pc()
def on_chunk(chunk, t_begin):
"""In _read_loop, right after the pipe read (and the older stamp of /landed): every message of a chunk with /landed is written."""
try:
if not _on_reader():
READERS.add(threading.get_ident())
MSGS["chunks"] += 1
MSGS["bytes"] += len(chunk)
landed = b"requestWillBeSent" in chunk and b"/landed" in chunk
_TL.verbose = landed
if landed:
io_ms = (_pc() - t_begin) * 1000.0
_count("hunt_pipe_stamp", io_ms)
_row(k="chunk", t=round(time.time(), 4), n=len(chunk), stamp_ms=round(io_ms, 3))
except Exception:
pass
def gate_begin():
return _pc()
def gate_end(t0, gate, got, waiting, snap=None):
"""In gated_dispatch, after `gate.acquire`: the reader's wait for the events gate."""
try:
if not _on_reader():
return
ms = (_pc() - t0) * 1000.0
_TL.gate_ms = getattr(_TL, "gate_ms", 0.0) + ms
_count("gate", ms)
if ms >= GATE_ROW_MS:
holder = snap
_row(k="gate", t=round(time.time(), 4), ms=round(ms, 3), ev=_ev(), got=bool(got), waiting=bool(waiting),
holder=holder[0] if holder else None, held_at=holder[2] if holder else None,
held_so_far_ms=round((t0 - holder[1]) * 1000, 1) if holder else None)
except Exception:
pass
def gate_snap(gate):
try:
return gate._snap()
except Exception:
return None
def hook_connection(cls):
"""Called at the end of invisible_core.juggler.connection with the Connection class."""
cls.dispatch_event = _core_dispatch_event
cls._deliver = _wrap_deliver(cls._deliver)
original = cls.__init__
def __init__(self, *a, **k):
original(self, *a, **k)
try:
for n in ("_lock", "_write_lock", "_listeners_lock"):
v = self.__dict__.get(n)
if v is not None and not isinstance(v, Timed):
self.__dict__[n] = Timed(v, "Connection." + n)
READERS.add(self._reader.ident)
_start()
except Exception:
pass
__init__._hunt_wrapped = True
cls.__init__ = __init__
+366
View File
@@ -0,0 +1,366 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of windows-flakes-locks-hunt.yml.
Usage: python scripts/hunt_locks_summary.py <label> <evidence dir> [threshold ms, default 100]
Per process of the arm `new` it reads
evidence/netidle_new_<round>_<proc>.log HUNT-ROW lines (the server's time of /landed, landed_t),
evidence/pipe_new_<round>_<proc>.txt when the core's pipe reader read the chunk that carries /landed,
evidence/lc_new_<round>_<proc>.jsonl when the lifecycle applied Network.requestWillBeSent of /landed,
evidence/locks_new_<round>_<proc>.jsonl the rows of scripts/hunt_locks_runtime.py (listeners, locks, gate, messages, totals).
For every /landed whose pipe -> lifecycle is over the threshold it cuts the interval [pipe, lifecycle] into the items below and prints markdown:
(a) the listener calls of Connection.dispatch_event (the part of a listener that is not a lock or gate wait is its "own" time),
(b) the wait of gated_dispatch on the events gate (with the holder it saw when it began to wait),
(c) the waits of the reader on every lock / condition that was timed (rows of 5 ms or more),
(d) per message, wall against CPU: wall - cpu - lock waits - gate = off the CPU (the GIL, or the OS not running the thread),
and the rest: time outside any _deliver (buffer, split) and inside a message but outside a listener (decode).
Then the totals per item over every process, and the longest stalls of the reader whether or not they sit in a delayed interval.
The stamps and rows are lists in memory written once at process exit, so a process that did not exit normally has no stamp file.
FIRST of all, the CONTROL: evidence/control_<arm>_<round>_<proc>.log (arms old and new, run with no patcher at all) gives, per arm, the
misses of networkidle (not on /landed when goto returned) split into "defect" (the server got /landed BEFORE goto returned) and
"not yet asked" (the page had not asked for it yet), from the server times in the HUNT-ROW lines only.
"""
import glob
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import hunt_noreader_summary as base # noqa: E402
ARM = "new"
def read_locks(path):
rows = []
if os.path.exists(path):
with open(path, errors="replace") as f:
for line in f:
try:
rows.append(json.loads(line))
except ValueError:
pass
return rows
def ov(row, a, b):
"""Seconds of the row's span [t - ms, t] inside [a, b]."""
end = row["t"]
start = end - row["ms"] / 1000.0
return max(0.0, min(end, b) - max(start, a))
def cpu_of(row):
c = row.get("cpu_cyc")
return c if c is not None else (row.get("cpu_ts") or 0.0)
def breakdown(rows, p, l):
"""The interval [p, l] cut into items. Everything in ms."""
iv = (l - p) * 1000.0
out = {"interval": iv, "gate": 0.0, "lock": 0.0, "cpu": 0.0, "off": 0.0, "outside": 0.0, "msg_other": 0.0, "stamp_io": 0.0, "lc_io": 0.0,
"locks": {}, "listeners": {}, "gates": [], "io": {}}
in_msgs = 0.0
for r in rows:
k = r["k"]
if k == "totals" or "t" not in r or r.get("ms") is None and k != "chunk":
continue
if k == "msg":
o = ov(r, p, l)
if o <= 0:
continue
frac = o / (r["ms"] / 1000.0)
wall = r["ms"]
cpu = cpu_of(r)
off = max(0.0, wall - cpu - r["lock"] - r["gate"])
in_msgs += o * 1000.0
out["gate"] += frac * r["gate"]
out["lock"] += frac * r["lock"]
out["cpu"] += frac * min(cpu, wall)
out["off"] += frac * off
out["msg_other"] += frac * max(0.0, wall - r["lst"])
elif k == "lock":
o = ov(r, p, l) * 1000.0
if o > 0:
d = out["locks"].setdefault((r["op"], r["name"]), {"ms": 0.0, "n": 0, "holders": {}})
d["ms"] += o
d["n"] += 1
h = "%s at %s" % (r.get("holder"), r.get("held_at"))
d["holders"][h] = d["holders"].get(h, 0) + 1
elif k == "gate":
o = ov(r, p, l) * 1000.0
if o > 0:
out["gates"].append((o, r))
elif k == "io":
o = ov(r, p, l) * 1000.0
if o > 0:
out["io"][r["name"]] = out["io"].get(r["name"], 0.0) + o
elif k == "chunk":
# the stamp's own file write, which sits between the pipe read and the first message
out["stamp_io"] += r.get("stamp_ms", 0.0)
# listeners, with what is nested in them (a lock or gate wait or the stamp write inside the call) taken out
nested = [r for r in rows if r["k"] in ("lock", "gate", "io") and "t" in r and r.get("ms") is not None]
for r in rows:
if r["k"] != "lst":
continue
o = ov(r, p, l)
if o <= 0:
continue
a = max(r["t"] - r["ms"] / 1000.0, p)
b = min(r["t"], l)
inner = sum(ov(n, a, b) for n in nested if n["t"] >= a and n["t"] - n["ms"] / 1000.0 <= b) * 1000.0
own = max(0.0, o * 1000.0 - inner)
frac = o / (r["ms"] / 1000.0)
d = out["listeners"].setdefault((r["name"]), {"own": 0.0, "total": 0.0, "n": 0, "cpu": 0.0, "events": {}})
d["own"] += own
d["total"] += o * 1000.0
d["n"] += 1
d["cpu"] += frac * cpu_of(r)
d["events"][r["ev"]] = d["events"].get(r["ev"], 0) + 1
out["outside"] = max(0.0, iv - in_msgs)
out["lc_io"] = out["io"].get("hunt_lc_write", 0.0)
return out
def dominant(b):
cand = {}
if b["gate"] > 0:
cand["gate"] = b["gate"]
for (op, name), d in b["locks"].items():
cand["%s %s" % (op, name)] = d["ms"]
for name, d in b["listeners"].items():
cand["listener %s (own)" % name] = d["own"]
cand["inside a message, outside a listener (decode, ends_waits)"] = max(0.0, b["msg_other"] - sum(d["total"] for d in b["listeners"].values()))
cand["outside any message (buffer, split, stamp write)"] = b["outside"]
name = max(cand, key=lambda k: cand[k])
return name, cand[name]
def collect():
out = []
logs = sorted(glob.glob(os.path.join(EV, "netidle_%s_*.log" % ARM)))
for log in logs:
tag = os.path.basename(log)[len("netidle_"):-len(".log")]
pipes = base.read_pipe(os.path.join(EV, "pipe_%s.txt" % tag))
lcs = base.read_lc(os.path.join(EV, "lc_%s.jsonl" % tag))
locks = read_locks(os.path.join(EV, "locks_%s.jsonl" % tag))
out.append({"tag": tag, "rows": base.read_rows(log), "pipes": pipes, "lcs": lcs, "locks": locks})
return out
def miss_counts(prefix, arm):
"""(rows, misses, defect, not yet asked, goto errors, processes with no row, processes, misses by path) of control_<arm>_*.log."""
rows = []
dead = 0
logs = sorted(glob.glob(os.path.join(EV, "%s_%s_*.log" % (prefix, arm))))
for log in logs:
got = base.read_rows(log)
if not got:
dead += 1
rows.extend(got)
miss = [r for r in rows if not r["landed_at_return"]]
defect = [r for r in miss if r.get("landed_t") is not None and r["landed_t"] < r["t1"]]
by = {}
for r in miss:
by[r["path"]] = by.get(r["path"], 0) + 1
return len(rows), len(miss), len(defect), len(miss) - len(defect), sum(r["error"] is not None for r in rows), dead, len(logs), by
def control():
print("### CONTROL, no patcher at all: networkidle misses, old against new")
print()
print("Fifteen rounds x four processes per arm, the order of the arms alternating, from the HUNT-ROW lines of `hunt_netidle.py` only. A miss is "
"a row that was not on /landed when goto returned: a **defect** when the server got /landed before goto returned, **not yet asked** when "
"the page had not asked for it yet.")
print()
print("| arm | misses | defect | not yet asked | rows | goto errors | processes with no row | misses by path |")
print("|---|---|---|---|---|---|---|---|")
for arm in ("old", "new"):
n, m, d, ny, err, dead, nlogs, by = miss_counts("control", arm)
print("| %s | %d | %d | %d | %d | %d | %d of %d | %s |" % (
arm, m, d, ny, n, err, dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
n, m, d, ny, err, dead, nlogs, by = miss_counts("netidle", ARM)
print("| %s, stamped (the patched pass, for comparison only) | %d | %d | %d | %d | %d | %d of %d | %s |" % (
ARM, m, d, ny, n, err, dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
print()
print("Expected 1200 rows per arm (4 processes x 15 rounds x 20 rows).")
print()
def main(label, threshold):
procs = collect()
print("## %s" % label)
print()
control()
print("## The stamped pass: where the time goes between the pipe and the lifecycle")
print()
n_rows = n_landed = n_both = 0
delayed = []
p2ls = []
for pr in procs:
for r in pr["rows"]:
n_rows += 1
srv = r.get("landed_t")
if srv is None:
continue
n_landed += 1
p = base.nearest(pr["pipes"], srv)
l = base.nearest(pr["lcs"], p) if p is not None else None
if p is None or l is None:
continue
n_both += 1
p2l = (l - p) * 1000.0
p2ls.append(p2l)
if p2l > threshold:
delayed.append((pr, r, p, l, p2l))
with_totals = sum(any(x["k"] == "totals" for x in pr["locks"]) for pr in procs)
print("Arm `%s`: %d processes (%d with a totals row, %d with lock rows), %d rows, %d with /landed on the server, %d with the pipe and the lifecycle stamp, "
"**%d with pipe -> lifecycle over %g ms**." % (
ARM, len(procs), with_totals, sum(bool(pr["locks"]) for pr in procs), n_rows, n_landed, n_both, len(delayed), threshold))
print()
print("pipe -> lifecycle over every row: p50 %s ms, p95 %s ms, max %s ms." % (
base.fmt(base.pct(p2ls, 0.5)), base.fmt(base.pct(p2ls, 0.95)), base.fmt(max(p2ls) if p2ls else None)))
# ── the delayed events ────────────────────────────────────────────────────────────────────────────────────────────────────────
print()
print("### every /landed whose pipe -> lifecycle is over %g ms, the interval cut by item (ms)" % threshold)
print()
print("Resource view, a partition of the messages the reader handled inside the interval: gate (b) + locks (c) + on CPU + off CPU (d) = time inside "
"messages; `outside` is the rest of the interval (no `_deliver` running). `off CPU` is wall - cpu - lock waits - gate, i.e. the GIL or the OS "
"not running the thread.")
print()
hist = {}
details = []
if not delayed:
print("None.")
else:
print("| process | path #round | goto ms | pipe -> lifecycle | gate | locks | on CPU | off CPU | outside | dominant item (ms) |")
print("|---|---|---|---|---|---|---|---|---|---|")
for pr, r, p, l, p2l in delayed:
b = breakdown(pr["locks"], p, l)
name, ms = dominant(b)
hist[name] = hist.get(name, 0) + 1
details.append((pr, r, b))
print("| %s | %s #%d | %d | %.0f | %.0f | %.0f | %.0f | %.0f | %.0f | %s (%.0f) |" % (
pr["tag"], r["path"], r["round"], r["goto_ms"], p2l, b["gate"], b["lock"], b["cpu"], b["off"], b["outside"], name, ms))
print()
print("### dominant item over the delayed events")
print()
print("| item | delayed events |")
print("|---|---|")
for k, v in sorted(hist.items(), key=lambda kv: -kv[1]):
print("| %s | %d |" % (k, v))
print()
print("### the delayed events one by one (the first 25): what ran on the reader in the interval, items of 1 ms or more")
for pr, r, b in details[:25]:
print()
print("**%s, %s #%d**: interval %.0f ms; gate %.0f, locks %.0f, on CPU %.0f, off CPU %.0f, outside any message %.0f, "
"decode/ends_waits %.0f, lifecycle stamp write %.1f, pipe stamp write %.1f" % (
pr["tag"], r["path"], r["round"], b["interval"], b["gate"], b["lock"], b["cpu"], b["off"], b["outside"],
max(0.0, b["msg_other"] - sum(d["total"] for d in b["listeners"].values())), b["lc_io"], b["stamp_io"]))
items = []
for (op, name), d in b["locks"].items():
holders = ", ".join("%s x%d" % (h, c) for h, c in sorted(d["holders"].items(), key=lambda kv: -kv[1])[:2])
items.append((d["ms"], "- %s `%s`: %.1f ms in %d wait(s); held by %s" % (op, name, d["ms"], d["n"], holders)))
for name, d in b["listeners"].items():
ev = ", ".join("%s x%d" % kv for kv in sorted(d["events"].items(), key=lambda kv: -kv[1])[:3])
items.append((d["total"], "- listener `%s`: %.1f ms in %d call(s) (own %.1f, cpu %.1f); events: %s" % (
name, d["total"], d["n"], d["own"], d["cpu"], ev)))
for o, g in b["gates"]:
items.append((o, "- gate: %.1f ms, got=%s, holder when it began to wait: %s at %s (held %s ms so far); event %s" % (
o, g.get("got"), g.get("holder"), g.get("held_at"), g.get("held_so_far_ms"), g.get("ev"))))
for nme, o in b["io"].items():
items.append((o, "- instrumentation `%s`: %.1f ms" % (nme, o)))
for _, line in sorted(items, key=lambda it: -it[0]):
print(line)
if not items:
print("- nothing of 1 ms or more is on the reader in this interval")
if len(details) > 25:
print()
print("(%d more delayed events not listed)" % (len(details) - 25))
# ── totals per item ───────────────────────────────────────────────────────────────────────────────────────────────────────────
items = {}
msgs = {"n": 0, "wall_ms": 0.0, "cpu_ts_ms": 0.0, "cpu_cyc_ms": 0.0, "chunks": 0, "bytes": 0}
for pr in procs:
for r in pr["locks"]:
if r["k"] != "totals":
continue
for k, v in r["items"].items():
d = items.setdefault(k, [0, 0.0, 0.0])
d[0] += v[0]
d[1] += v[1]
d[2] = max(d[2], v[2])
for k in msgs:
msgs[k] += r["msgs"].get(k, 0)
rowcount = {}
for pr in procs:
for r in pr["locks"]:
if r["k"] in ("lock", "gate", "io") and r.get("ms") is not None:
key = {"lock": "%s:%s" % ("wait" if r.get("op") == "wait" else "lock", r.get("name")), "gate": "gate", "io": r.get("name")}[r["k"]]
rowcount[key] = rowcount.get(key, 0) + 1
print()
print("### totals per item, every process of the arm, every message the reader handled (ms)")
print()
print("`lock:` = a wait to take it, `wait:` = a Condition.wait on the reader (a pause the code asked for), `lst:` = a listener call (it holds the lock "
"waits and the gate wait inside it), `gate` = gated_dispatch's wait, `hunt_pipe_stamp` = the pipe stamp's append to a list in memory.")
print()
print("| item | n | sum | mean | max | rows of the wait kind (5 ms+; gate, io 1 ms+) |")
print("|---|---|---|---|---|---|")
for k, (n, s, mx) in sorted(items.items(), key=lambda kv: -kv[1][1])[:45]:
print("| %s | %d | %.1f | %.3f | %.1f | %s |" % (k, n, s, s / max(n, 1), mx, rowcount.get(k, "-")))
print()
print("### off the CPU, per message (d)")
print()
cpu_total = msgs["cpu_cyc_ms"] if msgs["cpu_cyc_ms"] else msgs["cpu_ts_ms"]
print("Messages handled: %d (%d chunks, %d bytes). Wall in `_deliver`: %.1f ms; CPU of the reader thread: %.1f ms by the cycle counter (%.1f ms by "
"time.thread_time, ticks of about 15.6 ms on Windows). CPU / wall = %.3f." % (
msgs["n"], msgs["chunks"], msgs["bytes"], msgs["wall_ms"], msgs["cpu_cyc_ms"], msgs["cpu_ts_ms"],
(cpu_total / msgs["wall_ms"]) if msgs["wall_ms"] else 0.0))
stalls = []
off_big = 0
for pr in procs:
for r in pr["locks"]:
if r["k"] == "msg":
off = max(0.0, r["ms"] - cpu_of(r) - r["lock"] - r["gate"])
if off >= 5.0:
off_big += 1
stalls.append((r["ms"], off, pr["tag"], r))
print()
print("Messages of 1 ms or more written as rows: %d; of them %d spent 5 ms or more off the CPU outside lock and gate waits." % (len(stalls), off_big))
print()
print("### the longest messages of the reader (any time, delayed or not)")
print()
print("| process | message ms | event | on CPU | locks | gate | listeners | off CPU | landed |")
print("|---|---|---|---|---|---|---|---|---|")
for ms, off, tag, r in sorted(stalls, key=lambda x: -x[0])[:20]:
print("| %s | %.1f | %s | %.1f | %.1f | %.1f | %.1f | %.1f | %s |" % (tag, ms, r.get("ev"), min(cpu_of(r), ms), r["lock"], r["gate"], r["lst"], off, r["landed"]))
print()
print("### every lock wait of 5 ms or more, by lock (any time)")
print()
by = {}
for pr in procs:
for r in pr["locks"]:
if r["k"] == "lock":
d = by.setdefault((r["op"], r["name"]), {"n": 0, "ms": 0.0, "max": 0.0, "holders": {}})
d["n"] += 1
d["ms"] += r["ms"]
d["max"] = max(d["max"], r["ms"])
h = "%s at %s" % (r.get("holder"), r.get("held_at"))
d["holders"][h] = d["holders"].get(h, 0) + 1
if not by:
print("None: the reader never waited 5 ms or more for a lock.")
else:
print("| op | lock | waits | sum ms | max ms | holder when the wait began |")
print("|---|---|---|---|---|---|")
for (op, name), d in sorted(by.items(), key=lambda kv: -kv[1]["ms"]):
print("| %s | %s | %d | %.0f | %.0f | %s |" % (op, name, d["n"], d["ms"], d["max"],
", ".join("%s x%d" % (h, c) for h, c in sorted(d["holders"].items(), key=lambda kv: -kv[1])[:3])))
print()
print("The instrumentation runs on the reader too, but it only appends to lists in memory (nothing is opened or written until the process exits); "
"compare the stamped pass's misses with the control's above to see whether it changes the result.")
if __name__ == "__main__":
EV = sys.argv[2]
main(sys.argv[1], float(sys.argv[3]) if len(sys.argv) > 3 else 100.0)
+82
View File
@@ -0,0 +1,82 @@
"""HUNT SCAFFOLDING, NEVER MERGED: goto(networkidle) on pages that replace themselves after load, ours against stock Playwright Firefox.
Usage: python scripts/hunt_netidle.py ours|stock [binary]. Prints one JSON line per round: the URL when goto returned, how long goto took, and
when the server saw the request of /landed relative to goto's return (negative = the replacement was already on the wire when goto said idle).
"""
import http.server
import json
import os
import sys
import threading
import time
ENGINE = sys.argv[1]
if len(sys.argv) > 3:
os.environ["HUNT_LC_TRACE"] = sys.argv[3]
if len(sys.argv) > 4:
os.environ["HUNT_PIPE_TRACE"] = sys.argv[4]
REQS = []
def _page(ms, cross):
target = "location.origin.replace('127.0.0.1','localhost')+'/landed'" if cross else "'/landed'"
return ("<!doctype html><html><body><p id=p>first</p><script>addEventListener('load', () => setTimeout(() => "
"location.replace(%s), %d))</script></body></html>" % (target, ms)).encode()
PAGES = {"/landed": b"<!doctype html><html><body><p id=p>landed</p></body></html>"}
for ms in (0, 50):
PAGES["/r%d" % ms] = _page(ms, False)
PAGES["/x%d" % ms] = _page(ms, True)
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
REQS.append((time.time(), self.path))
body = PAGES.get(self.path.split("?")[0], PAGES["/landed"])
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
site = "http://127.0.0.1:%d" % srv.server_address[1]
def rounds(page, Error):
for path in ("/r0", "/r50", "/x0", "/x50"):
for i in range(5):
t0 = time.time()
err = None
try:
page.goto("%s%s?n=%d" % (site, path, i), wait_until="networkidle", timeout=15000)
except Error as e:
err = str(e).splitlines()[0][:100]
t1 = time.time()
url = page.url
landed = [t for t, p in REQS if p.startswith("/landed") and t >= t0]
print("HUNT-ROW " + json.dumps({
"engine": ENGINE, "path": path, "round": i, "landed_at_return": url.endswith("/landed"), "goto_ms": round((t1 - t0) * 1000),
"landed_request_ms_from_return": round((landed[0] - t1) * 1000) if landed else None, "error": err,
"t0": round(t0, 4), "t1": round(t1, 4), "landed_t": round(landed[0], 4) if landed else None}), flush=True)
if ENGINE == "stock":
from playwright.sync_api import sync_playwright, Error
with sync_playwright() as p:
b = p.firefox.launch(headless=True)
rounds(b.new_page(), Error)
b.close()
else:
from invisible_playwright import InvisiblePlaywright
from invisible_playwright.sync_api import Error
with InvisiblePlaywright(seed=4321, binary_path=sys.argv[2], headless=True) as browser:
rounds(browser.new_page(), Error)
srv.shutdown()
+162
View File
@@ -0,0 +1,162 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of windows-flakes-noreader-hunt.yml.
Usage: python scripts/hunt_noreader_summary.py <label> <evidence dir>
Per arm (old, new) and per process it reads evidence/netidle_<arm>_<round>_<proc>.log (HUNT-ROW json lines of scripts/hunt_netidle.py),
evidence/pipe_<arm>_<round>_<proc>.txt (the time, seconds, the core's pipe reader read a chunk with the /landed request) and
evidence/lc_<arm>_<round>_<proc>.jsonl (the lifecycle's events, Network.requestWillBeSent among them). For every row that has a /landed
request on the server it takes the nearest pipe stamp and then the nearest lifecycle stamp of /landed, and prints markdown:
- per arm the misses (not on /landed when goto returned) split into "defect" (the server got /landed BEFORE goto returned) and
"not yet asked" (the page had not asked for /landed yet), with server->pipe and pipe->lifecycle in ms for each defect miss;
- per arm p50 / p95 / max of server->pipe and pipe->lifecycle over every row of every round.
"""
import glob
import json
import os
import sys
ARMS = ("old", "new")
NEAR = 3.0 # seconds: a stamp farther than this from the request it is matched to is not its stamp
def read_rows(log):
rows = []
with open(log, errors="replace") as f:
for line in f:
if line.startswith("HUNT-ROW "):
try:
rows.append(json.loads(line[len("HUNT-ROW "):]))
except ValueError:
pass
return rows
def read_pipe(path):
out = []
if os.path.exists(path):
with open(path, errors="replace") as f:
for line in f:
try:
out.append(float(line.strip()))
except ValueError:
pass
return out
def read_lc(path):
"""Times of the lifecycle's Network.requestWillBeSent events of /landed."""
out = []
if os.path.exists(path):
with open(path, errors="replace") as f:
for line in f:
try:
r = json.loads(line)
except ValueError:
continue
if str(r.get("ev", "")).endswith("requestWillBeSent") and "/landed" in str(r.get("url") or ""):
out.append(r["t"])
return out
def nearest(stamps, at):
best = None
for s in stamps:
if abs(s - at) <= NEAR and (best is None or abs(s - at) < abs(best - at)):
best = s
return best
def pct(vals, q):
v = sorted(vals)
if not v:
return None
return v[min(len(v) - 1, int(round(q * (len(v) - 1))))]
def fmt(x):
return "-" if x is None else "%.1f" % x
def collect(ev, arm):
"""Every row of the arm, with s2p (server -> pipe) and p2l (pipe -> lifecycle) in ms, None when a stamp is missing, and its miss kind."""
out = []
dead = 0
logs = sorted(glob.glob(os.path.join(ev, "netidle_%s_*.log" % arm)))
for log in logs:
rows = read_rows(log)
if not rows:
dead += 1
tag = os.path.basename(log)[len("netidle_"):-len(".log")]
pipes = read_pipe(os.path.join(ev, "pipe_%s.txt" % tag))
lcs = read_lc(os.path.join(ev, "lc_%s.jsonl" % tag))
for r in rows:
srv = r.get("landed_t")
r["tag"] = tag
r["s2p"] = r["p2l"] = None
if srv is not None:
p = nearest(pipes, srv)
if p is not None:
r["s2p"] = (p - srv) * 1000
l = nearest(lcs, p)
if l is not None:
r["p2l"] = (l - p) * 1000
r["miss"] = not r["landed_at_return"]
r["kind"] = None
if r["miss"]:
r["kind"] = "defect" if (srv is not None and srv < r["t1"]) else "not yet asked"
out.append(r)
return out, dead, len(logs)
def netidle(ev):
data = {arm: collect(ev, arm) for arm in ARMS}
print("### network idle rows: misses (not on /landed when goto returned) out of the rows made")
print()
print("A miss is a **defect** when the server got /landed before goto returned, **not yet asked** when the page had not asked for it yet.")
print()
print("| arm | misses | defect | not yet asked | rows | goto errors | processes with no row | misses by path |")
print("|---|---|---|---|---|---|---|---|")
for arm in ARMS:
rows, dead, nlogs = data[arm]
miss = [r for r in rows if r["miss"]]
by = {}
for r in miss:
by[r["path"]] = by.get(r["path"], 0) + 1
print("| %s | %d | %d | %d | %d | %d | %d of %d | %s |" % (
arm, len(miss), sum(r["kind"] == "defect" for r in miss), sum(r["kind"] == "not yet asked" for r in miss), len(rows),
sum(r["error"] is not None for r in rows), dead, nlogs, ", ".join("%s %d" % kv for kv in sorted(by.items())) or "-"))
print()
print("Expected 1200 rows per arm (4 processes x 15 rounds x 20 rows).")
print()
print("### defect misses: server -> pipe and pipe -> lifecycle, ms")
for arm in ARMS:
defects = [r for r in data[arm][0] if r["kind"] == "defect"]
print()
print("**%s**: %d defect misses" % (arm, len(defects)))
if defects:
print()
print("| process | path | goto ms | server -> pipe | pipe -> lifecycle |")
print("|---|---|---|---|---|")
for r in defects:
print("| %s | %s #%d | %d | %s | %s |" % (r["tag"], r["path"], r["round"], r["goto_ms"], fmt(r["s2p"]), fmt(r["p2l"])))
print()
print("### server -> pipe and pipe -> lifecycle over every row of every round, ms")
print()
print("| arm | step | rows with both stamps | p50 | p95 | max |")
print("|---|---|---|---|---|---|")
for arm in ARMS:
rows = data[arm][0]
for name, key in (("server -> pipe", "s2p"), ("pipe -> lifecycle", "p2l")):
vals = [r[key] for r in rows if r[key] is not None]
print("| %s | %s | %d | %s | %s | %s |" % (arm, name, len(vals), fmt(pct(vals, 0.5)), fmt(pct(vals, 0.95)), fmt(max(vals) if vals else None)))
print()
print("Rows without a /landed request on the server, or whose pipe or lifecycle stamp is missing, are left out of the percentiles.")
if __name__ == "__main__":
label, evidence = sys.argv[1], sys.argv[2]
print("## %s" % label)
print()
netidle(evidence)
+306
View File
@@ -0,0 +1,306 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the runtime that scripts/hunt_trace_slow.py copies into the installed invisible_core as
invisible_core/_hunt_slow.py. It names the line of code behind the few slow listener calls left on the connection's READER thread.
(1) every listener call of Connection.dispatch_event made ON THE READER: wall time, CPU time of the thread (cycle counter, exact; see
below), the event method and the listener. All calls go into per-(listener, event) totals; a call of 2 ms or more is also a row
{"k": "lst"} (id, listener, event, wall, cpu, end time).
(2) a sampler thread (started by the thread that builds the Connection, never by the reader): while a listener call (or a decode) on the
reader has lasted more than 20 ms it takes sys._current_frames()[reader] every 2 ms and keeps the innermost 12 frames as
"file:line:function" (innermost first), a row {"k": "smp"} (call id, ms into the call, ms since the previous sample, stack).
(3) the decode of a message (json.loads of the raw bytes, in Connection._deliver): a row {"k": "dec"} when it took more than 20 ms, with
the message size, wall and CPU; the event method is added when the message turns out to be an event.
(4) off-CPU per call = wall - CPU (cycle counter): what a call spent waiting for the GIL, a lock, or being preempted.
Everything stays in memory and is written ONCE, at process exit (atexit), to $HUNT_SLOW_TRACE, one JSON line per row, last row {"k": "totals"}.
The sampler needs the GIL to sample: while the reader holds it inside one C call (a big json.loads, say) the sampler cannot run, so the gap
between samples (field "dt") is itself a measure, and the first sample after such a gap shows where the call was when the GIL came free.
Nothing here may break the engine: every hook swallows its own failure.
"""
import atexit
import json
import os
import sys
import threading
import time
SAMPLE_AFTER_MS = 20.0 # the sampler starts on a call that has lasted this long
SAMPLE_EVERY_S = 0.002
STACK_DEPTH = 12
LST_ROW_MS = 2.0 # a listener call this long or longer is a row (all of them are in the totals)
DEC_ROW_MS = 20.0 # a decode this long or longer is a row
MAX_SAMPLES = 40000 # per process
MAX_SAMPLES_PER_CALL = 600
_pc = time.perf_counter
ROWS: list = []
TOTALS: dict = {} # "listener | event" -> [n, wall ms sum, cpu ms sum, wall ms max]
STATE = {"started": False, "cyc_per_s": None, "pid": os.getpid(), "calls": 0, "samples": 0, "stop": False, "sampler_ticks": 0,
"sampler_error": None}
_TL = threading.local()
#: What the reader is doing right now: (call id, perf_counter at the start, kind "lst" or "dec", reader thread ident), or None.
_CUR = None
_ID = [0]
def _path():
return os.environ.get("HUNT_SLOW_TRACE")
#: read once, at import: no environment lookup on the reader's path
ENABLED = bool(_path())
# ── cpu time of the calling thread ────────────────────────────────────────────────────────────────────────────────────────────────
# time.thread_time() on Windows is GetThreadTimes, accounted per scheduler tick (~15.6 ms): too coarse for one call. The cycle counter of
# the thread (QueryThreadCycleTime) is exact; its rate is measured once, in short slices, taking the best slice (one that was not
# preempted), because the cycles tick only while the thread runs.
_cycles = None
if sys.platform == "win32":
try:
import ctypes
_k32 = ctypes.windll.kernel32
_k32.GetCurrentThread.restype = ctypes.c_void_p
_k32.QueryThreadCycleTime.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulonglong)]
_k32.QueryThreadCycleTime.restype = ctypes.c_int
_cyc_box = threading.local()
def _cycles():
box = getattr(_cyc_box, "v", None)
if box is None:
box = _cyc_box.v = ctypes.c_ulonglong()
_k32.QueryThreadCycleTime(_k32.GetCurrentThread(), ctypes.byref(box))
return box.value
except Exception:
_cycles = None
def _calibrate():
"""cycles per second of a thread that runs, from the best of 25 slices of about 3 ms of busy work. None if there is no counter."""
if _cycles is None:
return None
best = 0.0
for _ in range(25):
c0, t0 = _cycles(), _pc()
while _pc() - t0 < 0.003:
pass
c1, t1 = _cycles(), _pc()
if t1 > t0 and c1 > c0:
best = max(best, (c1 - c0) / (t1 - t0))
return best or None
def _cpu_ms(c0, c1):
rate = STATE["cyc_per_s"]
if _cycles is None or not rate:
return None
return (c1 - c0) / rate * 1000.0
def _now_cyc():
return _cycles() if _cycles is not None else 0
# ── names ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def _listener_name(fn):
try:
owner = getattr(fn, "__self__", None)
q = getattr(fn, "__qualname__", None) or getattr(fn, "__name__", None) or repr(fn)
if owner is not None and "." not in q:
q = "%s.%s" % (type(owner).__name__, q)
mod = getattr(fn, "__module__", None) or ""
return "%s:%s" % (mod.rsplit(".", 1)[-1], q) if mod else q
except Exception:
return "?"
def _short(path):
"""site-packages/invisible_core/juggler/lifecycle.py -> invisible_core/juggler/lifecycle.py; a stdlib or other path -> its last two parts."""
p = path.replace("\\", "/")
i = p.rfind("site-packages/")
if i >= 0:
return p[i + len("site-packages/"):]
parts = p.split("/")
return "/".join(parts[-2:])
def _stack(frame):
out = []
f = frame
while f is not None and len(out) < STACK_DEPTH:
c = f.f_code
if not c.co_filename.endswith("_hunt_slow.py"): # the hunt's own frames are not the code under test
out.append("%s:%d:%s" % (_short(c.co_filename), f.f_lineno, c.co_name))
f = f.f_back
return out
# ── the one write ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def flush():
"""Once, at exit: stop the sampler, write every row, then the totals."""
STATE["stop"] = True
path = _path()
if not path:
return
try:
n = len(ROWS)
batch = ROWS[:n]
lines = [json.dumps(r, default=str) for r in batch]
lines.append(json.dumps({"k": "totals", "pid": STATE["pid"], "cyc_per_s": STATE["cyc_per_s"], "calls": STATE["calls"],
"samples": STATE["samples"], "sampler_ticks": STATE["sampler_ticks"],
"sampler_error": STATE["sampler_error"],
"items": {k: [v[0], round(v[1], 3), round(v[2], 3), round(v[3], 3)] for k, v in TOTALS.items()}}))
with open(path, "a", encoding="utf-8") as fh:
fh.write("\n".join(lines) + "\n")
except Exception:
pass
# ── the sampler ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def _sampler():
last_id = None
last_t = 0.0
taken = 0
try:
while not STATE["stop"]:
time.sleep(SAMPLE_EVERY_S)
STATE["sampler_ticks"] += 1
cur = _CUR
if cur is None:
last_id = None
continue
cid, t0, kind, ident = cur
now = _pc()
if (now - t0) * 1000.0 <= SAMPLE_AFTER_MS:
continue
if cid != last_id:
last_id, last_t, taken = cid, t0, 0
if taken >= MAX_SAMPLES_PER_CALL or STATE["samples"] >= MAX_SAMPLES:
continue
frame = sys._current_frames().get(ident)
if frame is None or _CUR is not cur:
continue # the call ended while the frames were taken
st = _stack(frame)
ROWS.append({"k": "smp", "id": cid, "kind": kind, "at": round((now - t0) * 1000.0, 1),
"dt": round((now - last_t) * 1000.0, 1), "st": st})
last_t = now
taken += 1
STATE["samples"] += 1
except Exception as e: # never break the run
STATE["sampler_error"] = repr(e)[:200]
def _start():
"""From the thread that builds a Connection, never from the reader: the sampler and the one write at exit (the CPU calibration was
made at import, before any Connection existed)."""
if STATE["started"] or not ENABLED:
return
STATE["started"] = True
try:
atexit.register(flush)
threading.Thread(target=_sampler, name="hunt-slow-sampler", daemon=True).start()
except Exception:
pass
# ── the hooks ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
def _on_reader(conn):
try:
return threading.get_ident() == conn._reader.ident
except Exception:
return False
def decode(conn, raw):
"""In Connection._deliver: json.loads(raw.decode("utf-8")), timed on the reader. Raises what json.loads raises, as the original does."""
global _CUR
if not ENABLED or not _on_reader(conn):
return json.loads(raw.decode("utf-8"))
_ID[0] += 1
cid = _ID[0]
t0 = _pc()
c0 = _now_cyc()
_CUR = (cid, t0, "dec", threading.get_ident())
try:
return json.loads(raw.decode("utf-8"))
finally:
_CUR = None
try:
ms = (_pc() - t0) * 1000.0
_TL.dec = None
if ms >= DEC_ROW_MS:
cpu = _cpu_ms(c0, _now_cyc())
row = {"k": "dec", "id": cid, "ms": round(ms, 3), "cpu": None if cpu is None else round(cpu, 3), "n": len(raw),
"t": round(time.time(), 4), "ev": None}
ROWS.append(row)
_TL.dec = row
except Exception:
pass
def dispatch_event(self, method, params, session):
"""Connection.dispatch_event with each listener timed on the reader. The same loop as the core's."""
global _CUR
self.delivered += 1
with self._listeners_lock:
subscribers = list(self._listeners)
reader = ENABLED and _on_reader(self)
if reader:
dec = getattr(_TL, "dec", None)
if dec is not None:
dec["ev"] = method
_TL.dec = None
ident = threading.get_ident()
for fn in subscribers:
if reader:
_ID[0] += 1
cid = _ID[0]
t0 = _pc()
c0 = _now_cyc()
_CUR = (cid, t0, "lst", ident)
try:
fn(method, params, session)
except Exception as failure:
if len(self.handler_errors) < 32:
self.handler_errors.append("%s: %s" % (method, failure))
if reader:
_CUR = None
try:
c1 = _now_cyc()
ms = (_pc() - t0) * 1000.0
cpu = _cpu_ms(c0, c1)
name = _listener_name(fn)
STATE["calls"] += 1
key = "%s | %s" % (name, method)
t = TOTALS.get(key)
if t is None:
TOTALS[key] = [1, ms, cpu or 0.0, ms]
else:
t[0] += 1
t[1] += ms
t[2] += cpu or 0.0
if ms > t[3]:
t[3] = ms
if ms >= LST_ROW_MS:
ROWS.append({"k": "lst", "id": cid, "name": name, "ev": method, "ms": round(ms, 3),
"cpu": None if cpu is None else round(cpu, 3), "t": round(time.time(), 4)})
except Exception:
pass
def hook_connection(cls):
"""Called at the end of invisible_core.juggler.connection with the Connection class."""
cls.dispatch_event = dispatch_event
if ENABLED and STATE["cyc_per_s"] is None:
STATE["cyc_per_s"] = _calibrate()
original = cls.__init__
if getattr(original, "_hunt_wrapped", False):
return
def __init__(self, *a, **k):
original(self, *a, **k)
try:
_start()
except Exception:
pass
__init__._hunt_wrapped = True
cls.__init__ = __init__
+185
View File
@@ -0,0 +1,185 @@
"""HUNT SCAFFOLDING, NEVER MERGED: the step summary of the slow-listener hunt (markdown on stdout).
Usage: python scripts/hunt_slow_summary.py <label> <evidence dir> [call_ms=50] [decode_ms=20]
Reads <dir>/slow_*.jsonl (rows of scripts/hunt_slow_runtime.py, one file per process) and prints:
1. what was measured (processes, listener calls, how many over 2 / 20 / 50 / 100 / 200 ms, the sampler's own work);
2. every listener call over call_ms: event, listener, wall, CPU, off-CPU (wall - CPU: the GIL, a lock, preemption), the number of samples
and the most frequent innermost frames (file:line function) of its samples, and the first frame in our own code;
3. the calls over call_ms grouped by innermost frame, and by first frame in our own code (invisible_core / invisible_playwright);
4. the same calls grouped by listener and event;
5. every decode over decode_ms with the size of the message.
A frame is "file:line:function"; a sample is taken only when the sampler gets the GIL, so a sample after a long gap is where the call was
when the GIL came free (field dt), not where the gap began.
"""
import collections
import glob
import json
import os
import statistics
import sys
LABEL = sys.argv[1] if len(sys.argv) > 1 else "run"
DIR = sys.argv[2] if len(sys.argv) > 2 else "evidence"
CALL_MS = float(sys.argv[3]) if len(sys.argv) > 3 else 50.0
DEC_MS = float(sys.argv[4]) if len(sys.argv) > 4 else 20.0
OWN = ("invisible_core/", "invisible_playwright/")
def load():
procs = []
for path in sorted(glob.glob(os.path.join(DIR, "slow_*.jsonl"))):
p = {"file": os.path.basename(path)[len("slow_"):-len(".jsonl")], "lst": {}, "smp": collections.defaultdict(list), "dec": [],
"totals": None}
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except ValueError:
continue
k = r.get("k")
if k == "lst":
p["lst"][r["id"]] = r
elif k == "smp":
p["smp"][r["id"]].append(r)
elif k == "dec":
p["dec"].append(r)
elif k == "totals":
p["totals"] = r
except OSError:
continue
procs.append(p)
return procs
def f1(x):
return "-" if x is None else "%.1f" % x
def md(s):
return str(s).replace("|", "\\|")
def innermost(smp):
return smp["st"][0] if smp.get("st") else None
def own_frame(smp):
for fr in smp.get("st", []):
if fr.startswith(OWN):
return fr
return None
def top(counter, n):
return "<br>".join("%d x `%s`" % (c, md(k)) for k, c in counter.most_common(n))
def main():
procs = load()
print("## Slow listener calls on the reader - %s" % LABEL)
print()
if not procs:
print("No slow_*.jsonl in %s: the instrumentation wrote nothing (the run did not start or the patch did not load)." % DIR)
return
with_totals = [p for p in procs if p["totals"]]
calls = sum(p["totals"]["calls"] for p in with_totals)
ticks = sum(p["totals"].get("sampler_ticks", 0) for p in with_totals)
samples = sum(p["totals"].get("samples", 0) for p in with_totals)
errs = [p["totals"].get("sampler_error") for p in with_totals if p["totals"].get("sampler_error")]
cyc = sorted({round(p["totals"]["cyc_per_s"] / 1e9, 2) for p in with_totals if p["totals"].get("cyc_per_s")})
all_calls = [(p, r) for p in procs for r in p["lst"].values()]
print("%d processes with a trace (%d wrote their totals), %d listener calls on the reader, %d sampler ticks, %d samples, "
"cycle counter rates (GHz) %s, sampler errors: %s" % (len(procs), len(with_totals), calls, ticks, samples, cyc or "none",
errs[:3] or "none"))
print()
print("Listener calls (rows are written from 2 ms): " + ", ".join(
"over %d ms: **%d**" % (t, sum(1 for _, r in all_calls if r["ms"] > t)) for t in (2, 20, 50, 100, 200)))
print()
slow = sorted(((p, r) for p, r in all_calls if r["ms"] > CALL_MS), key=lambda pr: -pr[1]["ms"])
print("### Calls over %g ms: %d" % (CALL_MS, len(slow)))
print()
if slow:
print("| proc | event | listener | wall ms | cpu ms | off-CPU ms | samples (median dt ms) | innermost frames of the samples | first frame in our code |")
print("|---|---|---|---:|---:|---:|---|---|---|")
for p, r in slow[:70]:
sm = p["smp"].get(r["id"], [])
off = None if r["cpu"] is None else r["ms"] - r["cpu"]
inner = collections.Counter(innermost(s) for s in sm if innermost(s))
own = collections.Counter(own_frame(s) for s in sm if own_frame(s))
dts = [s["dt"] for s in sm]
print("| %s | %s | %s | %.1f | %s | %s | %d (%s) | %s | %s |" % (
md(p["file"]), md(r["ev"]), md(r["name"]), r["ms"], f1(r["cpu"]), f1(off), len(sm),
f1(statistics.median(dts)) if dts else "-", top(inner, 3) or "none", top(own, 2) or "none"))
if len(slow) > 70:
print()
print("(%d more calls not listed)" % (len(slow) - 70))
print()
no_smp = sum(1 for p, r in slow if not p["smp"].get(r["id"]))
cpu_bound = sum(1 for _, r in slow if r["cpu"] is not None and r["cpu"] >= 0.7 * r["ms"])
print("Of these: %d with no sample at all (the sampler never got the GIL during the call), %d CPU-bound (cpu >= 70%% of wall), "
"%d mostly off-CPU." % (no_smp, cpu_bound, sum(1 for _, r in slow if r["cpu"] is not None and r["cpu"] < 0.7 * r["ms"])))
print()
for title, fn in (("innermost frame", innermost), ("first frame in our code (invisible_core / invisible_playwright)", own_frame)):
groups = collections.defaultdict(lambda: {"calls": set(), "n": 0, "names": collections.Counter(), "wall": 0.0})
total = 0
for pi, (p, r) in enumerate(slow):
for s in p["smp"].get(r["id"], []):
fr = fn(s)
if fr is None:
continue
g = groups[fr]
g["n"] += 1
total += 1
if (pi, r["id"]) not in g["calls"]:
g["calls"].add((pi, r["id"]))
g["wall"] += r["ms"]
g["names"][r["name"] + " / " + r["ev"]] += 1
print("### Calls over %g ms grouped by %s" % (CALL_MS, title))
print()
if not groups:
print("No samples.")
print()
continue
print("| frame | calls | samples | share of samples | wall ms of those calls | listener / event |")
print("|---|---:|---:|---:|---:|---|")
for fr, g in sorted(groups.items(), key=lambda kv: -kv[1]["n"])[:25]:
print("| `%s` | %d | %d | %.0f%% | %.0f | %s |" % (md(fr), len(g["calls"]), g["n"], 100.0 * g["n"] / total, g["wall"],
top(g["names"], 3)))
print()
by = collections.defaultdict(lambda: [0, 0.0, 0.0, 0.0])
for p, r in slow:
b = by[(r["name"], r["ev"])]
b[0] += 1
b[1] += r["ms"]
b[2] += r["cpu"] or 0.0
b[3] = max(b[3], r["ms"])
print("### Calls over %g ms by listener and event" % CALL_MS)
print()
print("| listener | event | calls | max ms | wall sum ms | cpu sum ms |")
print("|---|---|---:|---:|---:|---:|")
for (name, ev), b in sorted(by.items(), key=lambda kv: -kv[1][3]):
print("| %s | %s | %d | %.1f | %.0f | %.0f |" % (md(name), md(ev), b[0], b[3], b[1], b[2]))
print()
decs = sorted(((p, r) for p in procs for r in p["dec"] if r["ms"] > DEC_MS), key=lambda pr: -pr[1]["ms"])
print("### Decodes (json.loads) over %g ms: %d" % (DEC_MS, len(decs)))
print()
if decs:
print("| proc | event | size bytes | wall ms | cpu ms | off-CPU ms | samples |")
print("|---|---|---:|---:|---:|---:|---:|")
for p, r in decs[:40]:
off = None if r["cpu"] is None else r["ms"] - r["cpu"]
print("| %s | %s | %d | %.1f | %s | %s | %d |" % (md(p["file"]), md(r.get("ev") or "?"), r["n"], r["ms"], f1(r["cpu"]), f1(off),
len(p["smp"].get(r["id"], []))))
print()
main()
+66
View File
@@ -0,0 +1,66 @@
"""HUNT SCAFFOLDING, NEVER MERGED: patch the installed invisible_core lifecycle to trace what decides networkidle.
Every event the lifecycle applies (Page.* and Network.*) and every networkidle it gives is written as a JSON line, with time.time(),
to a list in memory, written ONCE at process exit (atexit) to the file named by $HUNT_LC_TRACE (no file is opened or written on the reader
during the run). Run once after the install: python scripts/hunt_trace_lifecycle.py
"""
import importlib.util
import io
path = importlib.util.find_spec("invisible_core.juggler.lifecycle").origin
s = io.open(path, encoding="utf-8").read()
old = """ def _on_event(self, method: str, p: dict) -> None:
with self._cv:
"""
new = """ def _on_event(self, method: str, p: dict) -> None:
with self._cv:
if method.startswith(("Page.", "Network.")):
_hunt_lc(ev=method, frame=p.get("frameId"), nav=p.get("navigationId"), url=(p.get("url") or "")[:90],
rid=p.get("requestId"), name=p.get("name"), open=len(self._open),
states={k: sorted(v.states) for k, v in self.frames.items()})
"""
assert s.count(old) == 1, "_on_event"
s = s.replace(old, new, 1)
old = """ for f in waiting:
f.states.add(state)
self._tell(state, f.id)
"""
new = """ for f in waiting:
if state == "networkidle":
_hunt_lc(ev="GIVE networkidle", frame=f.id, nav=f.navigation, url=(f.url or "")[:90], open=len(self._open),
quiet=round(quiet_for, 3))
f.states.add(state)
self._tell(state, f.id)
"""
assert s.count(old) == 1, "_settle"
s = s.replace(old, new, 1)
s = s.rstrip(chr(10)) + '''
_HUNT_LC = []
def _hunt_lc(**row):
import os as _o, time as _t
if not _o.environ.get("HUNT_LC_TRACE"):
return
row["t"] = round(_t.time(), 4)
_HUNT_LC.append(row)
def _hunt_lc_dump():
import json as _j, os as _o
path = _o.environ.get("HUNT_LC_TRACE")
if path and _HUNT_LC:
try:
with open(path, "w", encoding="utf-8") as fh:
fh.write("".join(_j.dumps(r, default=str) + chr(10) for r in _HUNT_LC))
except Exception:
pass
import atexit as _hunt_atexit
_hunt_atexit.register(_hunt_lc_dump)
'''
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
print("patched", path)
+107
View File
@@ -0,0 +1,107 @@
"""HUNT SCAFFOLDING, NEVER MERGED: time the reader's path in the installed invisible_core and invisible_playwright.
Run once per venv, AFTER scripts/hunt_trace_pipes.py and scripts/hunt_trace_lifecycle.py (it builds on their stamps):
python scripts/hunt_trace_locks.py
It copies scripts/hunt_locks_runtime.py into the core as invisible_core/_hunt_locks.py and patches, by exact text (an assert if the text
is not there once):
core connection.py Connection.dispatch_event (each listener timed), Connection._deliver (wall against CPU), the locks of the
connection, and the chunk hook in _read_loop;
core lifecycle.py Lifecycle._cv;
core injected.py InjectedScript._contexts_changed;
core instance.py Browser._sessions_ready, _buffer_lock;
wrapper server.py the events gate (who holds it, how long gated_dispatch waits), PageDispatcher._close_lock / _held_lock /
_frames_lock / _announce_lock, BrowserDispatcher._sessions_ready / _buffer_lock / _targets_lock / _pages_ready.
Rows go to $HUNT_LOCKS_TRACE, one JSON file per process, written once at exit (see the head of hunt_locks_runtime.py).
"""
import importlib.util
import io
import os
import shutil
HERE = os.path.dirname(os.path.abspath(__file__))
def origin(name):
return importlib.util.find_spec(name).origin
def read(path):
return io.open(path, encoding="utf-8").read()
def write(path, text):
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(text)
def once(text, old, new, what):
assert text.count(old) == 1, "%s: expected the text once, found %d" % (what, text.count(old))
return text.replace(old, new, 1)
IMPORT = "\n\nfrom invisible_core import _hunt_locks as _hunt_h # HUNT\n"
# ── the runtime, inside the core ──────────────────────────────────────────────────────────────────────────────────────────────────
conn_path = origin("invisible_core.juggler.connection")
core_dir = os.path.dirname(os.path.dirname(conn_path))
shutil.copyfile(os.path.join(HERE, "hunt_locks_runtime.py"), os.path.join(core_dir, "_hunt_locks.py"))
print("copied the runtime to", os.path.join(core_dir, "_hunt_locks.py"))
# ── core: connection ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
s = read(conn_path)
assert "_HUNT_PIPE.append" in s, "run scripts/hunt_trace_pipes.py first"
s = once(s, """ if not chunk:
break
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
""", """ if not chunk:
break
_hunt_t0 = _hunt_h.chunk_begin()
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
""", "core _read_loop (before the stamp)")
s = once(s, """ _HUNT_PIPE.append(_ht.time())
""", """ _HUNT_PIPE.append(_ht.time())
_hunt_h.on_chunk(chunk, _hunt_t0)
""", "core _read_loop (after the stamp)")
for needle in ("for fn in subscribers:", "fn(method, params, session)", "with self._listeners_lock:", "self.delivered += 1"):
assert needle in s, "core dispatch_event changed: " + needle
s = s.rstrip(chr(10)) + IMPORT + "_hunt_h.hook_connection(Connection)\n"
write(conn_path, s)
print("patched", conn_path)
# ── core: lifecycle, injected, instance ─────────────────────────────────────────────────────────────────────────────────────────────
path = origin("invisible_core.juggler.lifecycle")
s = read(path)
assert "_HUNT_LC = []" in s, "run scripts/hunt_trace_lifecycle.py first"
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(Lifecycle, ["_cv"], "Lifecycle.")\n'
write(path, s)
print("patched", path)
path = origin("invisible_core.juggler.injected")
s = read(path)
assert "class InjectedScript" in s
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(InjectedScript, ["_contexts_changed"], "InjectedScript.")\n'
write(path, s)
print("patched", path)
path = origin("invisible_core.juggler.instance")
s = read(path)
assert "class Browser" in s
s = s.rstrip(chr(10)) + IMPORT + '_hunt_h.hook_class(Browser, ["_sessions_ready", "_buffer_lock"], "core.Browser.")\n'
write(path, s)
print("patched", path)
# ── wrapper: server.py ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
path = origin("invisible_playwright._juggler.server")
s = read(path)
s = once(s, " gate = threading.RLock()\n",
' gate = _hunt_h.timed(threading.RLock(), "events_gate", quiet=True)\n', "wrapper gate")
s = once(s, """ got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
""", """ _hg = (_hunt_h.gate_begin(), _hunt_h.gate_snap(gate))
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
_hunt_h.gate_end(_hg[0], gate, got, waiting, _hg[1])
""", "wrapper gated_dispatch")
assert "class PageDispatcher(" in s and "class BrowserDispatcher(" in s
s = s.rstrip(chr(10)) + IMPORT + (
'_hunt_h.hook_class(PageDispatcher, ["_close_lock", "_held_lock", "_frames_lock", "_announce_lock"], "PageDispatcher.")\n'
'_hunt_h.hook_class(BrowserDispatcher, ["_sessions_ready", "_buffer_lock", "_targets_lock", "_pages_ready"], "BrowserDispatcher.")\n')
write(path, s)
print("patched", path)
+47
View File
@@ -0,0 +1,47 @@
"""HUNT SCAFFOLDING, NEVER MERGED: stamp the moment the browser pipe delivers a /landed request, in the installed invisible_core.
invisible_core.juggler.connection _read_loop, on every chunk read from the browser. A chunk that carries "requestWillBeSent" and "/landed"
appends a wall-clock time (seconds) to a list in memory; the list is written ONCE, at process exit (atexit), to the file named by $HUNT_PIPE_TRACE
(no file is opened or written on the reader during the run). Run once per venv after the install: python scripts/hunt_trace_pipes.py
(only the core part of the original in the trace worktree: the arms here are ours only).
"""
import importlib.util
import io
import os
path = importlib.util.find_spec("invisible_core.juggler.connection").origin
s = io.open(path, encoding="utf-8").read()
old = """ chunk = os.read(self._from_browser, 65536)
if not chunk:
break
"""
new = """ chunk = os.read(self._from_browser, 65536)
if not chunk:
break
if b"requestWillBeSent" in chunk and b"/landed" in chunk and os.environ.get("HUNT_PIPE_TRACE"):
import time as _ht
_HUNT_PIPE.append(_ht.time())
"""
assert s.count(old) == 1, "core _read_loop"
s = s.replace(old, new, 1).rstrip(chr(10)) + '''
_HUNT_PIPE = []
def _hunt_pipe_dump():
import os as _o
path = _o.environ.get("HUNT_PIPE_TRACE")
if path and _HUNT_PIPE:
try:
with open(path, "w") as fh:
fh.write("".join("%.4f" % t + chr(10) for t in _HUNT_PIPE))
except Exception:
pass
import atexit as _hunt_atexit
_hunt_atexit.register(_hunt_pipe_dump)
'''
io.open(path, "w", encoding="utf-8", newline=chr(10)).write(s)
print("patched", path)
+35
View File
@@ -0,0 +1,35 @@
"""HUNT SCAFFOLDING, NEVER MERGED: put the slow-listener instrumentation into the installed invisible_core.
Run once per venv, after the install:
python scripts/hunt_trace_slow.py
It copies scripts/hunt_slow_runtime.py into the core as invisible_core/_hunt_slow.py and patches invisible_core/juggler/connection.py by
exact text (an assert if the text is not there exactly once): the decode in Connection._deliver goes through _hunt_slow.decode, and
Connection.dispatch_event is replaced at the end of the module by the timed twin (see the head of hunt_slow_runtime.py). Nothing else
of the core or the wrapper is touched. Rows go to $HUNT_SLOW_TRACE, one file per process, written once at exit.
"""
import importlib.util
import io
import os
import shutil
HERE = os.path.dirname(os.path.abspath(__file__))
def once(text, old, new, what):
assert text.count(old) == 1, "%s: expected the text once, found %d" % (what, text.count(old))
return text.replace(old, new, 1)
conn_path = importlib.util.find_spec("invisible_core.juggler.connection").origin
core_dir = os.path.dirname(os.path.dirname(conn_path))
shutil.copyfile(os.path.join(HERE, "hunt_slow_runtime.py"), os.path.join(core_dir, "_hunt_slow.py"))
print("copied the runtime to", os.path.join(core_dir, "_hunt_slow.py"))
s = io.open(conn_path, encoding="utf-8").read()
assert "_hunt_slow" not in s, "already patched"
s = once(s, 'msg = json.loads(raw.decode("utf-8"))', "msg = _hunt_slow.decode(self, raw)", "core _deliver decode")
for needle in ("for fn in subscribers:", "fn(method, params, session)", "with self._listeners_lock:", "self.delivered += 1"):
assert needle in s, "core dispatch_event changed: " + needle
s = s.rstrip(chr(10)) + "\n\n\nfrom invisible_core import _hunt_slow # HUNT\n_hunt_slow.hook_connection(Connection)\n"
io.open(conn_path, "w", encoding="utf-8", newline=chr(10)).write(s)
print("patched", conn_path)
+60 -6
View File
@@ -33,6 +33,7 @@ import contextlib
import json
import os
import pathlib
import queue
import sys
import tempfile
import threading
@@ -3414,9 +3415,10 @@ class PageDispatcher(Dispatcher):
# is a command whose answer only that same read loop can deliver.
# Doing it here would block the reader waiting for a message the
# reader is the one who has to receive.
threading.Thread(
target=self._announce_file_chooser, args=(params,),
daemon=True).start()
# ⛔ AND NOT STARTED HERE EITHER: `Thread.start` waits for the new thread to run, and this is the reader.
# The browser's thread starter does it (`_ThreadStarter`).
self.context.browser.thread_starter.start(
target=self._announce_file_chooser, args=(params,))
elif method == "Page.crashed":
self.emit("crash")
# ⛔ `Page.frameAttached` / `Page.frameDetached` ARE NOT READ HERE: the
@@ -4777,6 +4779,51 @@ NO_OVERRIDE = "no-override"
NO_OVERRIDE_OPTIONS = ("colorScheme", "reducedMotion", "forcedColors")
class _ThreadStarter:
"""The ONE long-lived thread that starts the other threads the engine's events ask for.
⛔ NO `Thread.start` ON THE CONNECTION'S READER THREAD. `Thread.start` does not return until the new thread is running
(`self._started.wait()`), and on Windows under load that wait is milliseconds long: it was the larger part of the reader's delay, and
every millisecond the reader is late is a millisecond a `networkidle` quiet is measured late (7 misses in 400 with four browsers at
once, none in 400 when the start did not wait). A listener that runs on the reader and needs work done elsewhere hands it to `start`
here: a `Thread` that is only BUILT on the reader (building waits for nothing) goes into a queue, and this thread starts it.
It starts threads and does not run the work itself, on purpose: an adoption waits for the engine as long as the engine takes (a popup
whose destination never answers is waited for without a limit), and a worker that ran it would hold every later adoption behind it,
`new_page()` included. Each piece of work keeps the thread of its own and the name it always had.
"""
def __init__(self, on_error: Callable[[str], None]) -> None:
self._queue: "queue.SimpleQueue" = queue.SimpleQueue()
self._on_error = on_error
self._stopped = False
self._thread = threading.Thread(target=self._run, daemon=True, name="invpw-thread-starter")
self._thread.start()
def start(self, **thread_arguments: Any) -> None:
"""Called from any thread, the reader's included: builds the thread and queues it. Never waits."""
if self._stopped:
return
self._queue.put(threading.Thread(daemon=True, **thread_arguments))
def stop(self) -> None:
self._stopped = True
self._queue.put(None)
def _run(self) -> None:
while True:
thread = self._queue.get()
if thread is None:
return
try:
thread.start()
except Exception as failure:
try:
self._on_error("%s could not be started: %s" % (thread.name, failure))
except Exception:
pass
class BrowserDispatcher(Dispatcher):
TYPE = "Browser"
METHODS = {"newContext": "op_new_context", "close": "op_close",
@@ -4965,6 +5012,9 @@ class BrowserDispatcher(Dispatcher):
# subscriber seeing an event before this one records the session, and
# recording earlier can only shorten the window in which `session_for`
# is waiting for something that has already arrived.
self._starter = _ThreadStarter(
lambda why: conn.handler_errors.append(why) if len(conn.handler_errors) < 32 else None)
conn.add_close_listener(self._starter.stop)
conn.add_listener(self._route_browser_event)
# The last step of starting the browser, under what is left of the
# caller's `launch(timeout=)` (`Connection.startup_send`), not a
@@ -4988,6 +5038,11 @@ class BrowserDispatcher(Dispatcher):
# the target map): recorded for its session, never built into a page.
self._adopt_enabled = True
@property
def thread_starter(self) -> "_ThreadStarter":
"""The one thread that starts threads on behalf of the engine's reader (`_ThreadStarter`)."""
return self._starter
def require_interception(self, what: str) -> None:
"""Refuse a route this browser cannot honour, instead of ignoring it.
@@ -5189,11 +5244,10 @@ class BrowserDispatcher(Dispatcher):
else:
self._strays += 1
number = popup_number(None, self._strays)
thread = threading.Thread(
self._starter.start(
target=self._adopt_target,
args=(target_id, session_id, browser_context_id, opener, number),
daemon=True, name="invpw-adopt-%s" % target_id[:8])
thread.start()
name="invpw-adopt-%s" % target_id[:8])
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
# between any two of them and deliver an event of the engine there.
@@ -0,0 +1,158 @@
"""No thread is started on the engine connection's reader thread.
`Thread.start` does not return until the new thread is running. On the reader that wait is the reader's own delay: measured on Windows with
four browsers at once, it was 75% of the reader's lag, and it made `networkidle` miss 7 times in 400 (none in 400 once the start no longer
waited). Two listeners of this package started a thread from the reader: `Browser.attachedToTarget` (one thread per adoption) and
`Page.fileChooserOpened` (one thread to announce the chooser). Both now hand the thread to the browser's ONE long-lived starter
(`_ThreadStarter`, made with the browser), which starts it.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and every event of the engine delivered FROM A THREAD OF ITS OWN
(the reader's stand-in), the way the connection delivers them. `Thread.start` is replaced by a recorder of the thread that called it.
`Page.eventFired(load)` goes through the core's lifecycle, which started a `threading.Timer` for the silence of `networkidle` until the core
made one thread of deadlines for the connection (`DeadlineClock`): that case is skipped with a core that does not have it.
Known-bad input: the thread started in `_spawn_adoption` / `_route_juggler_event` -> two starts from the reader (the adoption and the
chooser), named in the failure.
"""
from __future__ import annotations
import queue
import threading
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import LocalUtilsDispatcher
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _wait
from test_no_event_of_any_family_is_lost_by_the_hand_over import ChooserEngine
pytestmark = pytest.mark.unit
READER = "the-engine-reader"
class _Reader:
"""A thread that delivers the events it is handed, one at a time and in order, as the connection's reader does."""
def __init__(self):
self._work: "queue.Queue" = queue.Queue()
self.thread = threading.Thread(target=self._run, name=READER, daemon=True)
self.thread.start()
def _run(self):
while True:
job = self._work.get()
if job is None:
return
fn, done = job
try:
fn()
finally:
done.set()
def deliver(self, fn):
done = threading.Event()
self._work.put((fn, done))
assert done.wait(10), "the reader is stuck inside a listener"
def stop(self):
self._work.put(None)
@pytest.fixture
def starts(monkeypatch):
"""Every `Thread.start` from now on, as (the name of the thread that called it, the name of the thread started)."""
calls = []
original = threading.Thread.start
def recording(self):
calls.append((threading.current_thread().name, self.name))
return original(self)
monkeypatch.setattr(threading.Thread, "start", recording)
return calls
def _from_reader(starts):
return [c for c in starts if c[0] == READER]
def _a_popup_is_announced(conn, reader, browser, context_id, opener_target):
reader.deliver(lambda: conn.attach(opener_target, context_id))
reader.deliver(conn.frame)
reader.deliver(conn.commit)
reader.deliver(conn.ready)
assert _wait(lambda: browser._page_targets.get(TARGET) is not None, 5), "the popup was never announced (%s)" % (conn.handler_errors,)
def _world(starts):
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = ChooserEngine()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(t for t in conn.sessions if t != TARGET)
return server, conn, browser, context, opener_target
def test_an_attached_target_and_a_file_chooser_start_no_thread_on_the_reader(starts):
server, conn, browser, context, opener_target = _world(starts)
reader = _Reader()
chooser = []
try:
del starts[:]
_a_popup_is_announced(conn, reader, browser, context.context_id, opener_target)
assert [c[1] for c in starts if c[1].startswith("invpw-adopt-")], "the adoption never started (%s)" % (starts,)
page = browser._page_targets[TARGET]
original_emit = type(page).emit
def spy(self, method, params=None):
if method == "fileChooser":
chooser.append(params)
return original_emit(self, method, params)
type(page).emit = spy
try:
reader.deliver(lambda: conn.dispatch_event(
"Page.fileChooserOpened", {"element": {"objectId": "input-1"}, "executionContextId": "e"}, SESSION))
assert _wait(lambda: chooser, 5), "the chooser never reached the client (%s)" % (conn.handler_errors,)
finally:
type(page).emit = original_emit
assert _from_reader(starts) == [], "the reader started %s" % (_from_reader(starts),)
assert conn.handler_errors == []
finally:
reader.stop()
server.shutdown()
@pytest.mark.skipif(not hasattr(EventListeners, "deadlines"), reason="the installed core still starts a Timer for the silence of networkidle")
def test_a_load_delivered_on_the_reader_starts_no_thread(starts):
server, conn, browser, context, opener_target = _world(starts)
reader = _Reader()
try:
_a_popup_is_announced(conn, reader, browser, context.context_id, opener_target)
del starts[:]
reader.deliver(lambda: conn.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "load"}, SESSION))
assert _from_reader(starts) == [], "the reader started %s" % (_from_reader(starts),)
assert conn.handler_errors == []
finally:
reader.stop()
server.shutdown()
def test_the_starter_of_a_browser_ends_with_its_connection(starts):
server, conn, browser, context, opener_target = _world(starts)
try:
starter = browser.thread_starter
starter.start(target=lambda: None, name="invpw-test-started")
assert _wait(lambda: ("invpw-thread-starter", "invpw-test-started") in starts, 3)
conn.announce_closed()
starter._thread.join(5)
assert not starter._thread.is_alive(), "the starter outlived the connection"
starter.start(target=lambda: None, name="invpw-test-after-the-end") # after the end: nothing is started, nothing raises
assert all(c[1] != "invpw-test-after-the-end" for c in starts)
finally:
server.shutdown()