~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(extraction): bound the Readability.js Node subprocess (#6218)
LearningCircuit8b2bf4da3b22
diff --git a/changelog.d/6218.bugfix.md b/changelog.d/6218.bugfix.mdnew file mode 100644index 0000000000..1fcb52760e--- /dev/null+++ b/changelog.d/6218.bugfix.md@@ -0,0 +1 @@+Bound the Readability.js extraction step, which shells out to a Node subprocess with no timeout of its own: a slow or wedged `node` could stall a research run indefinitely. It now falls back to the pure-Python parser after 20 seconds, admits at most 8 Node calls that are merely in flight and stops reaching for Node once 3 of them are stuck on it (starting again as soon as they clear) — since a stuck call stops counting against the in-flight cap once it strands, the true ceiling on Node processes alive at once is 8 + 3 - 1 = 10, not 8 — and skips the bound entirely when Node is not installed (where readabilipy already runs in-process). The one Node invocation left unbounded is the availability probe itself (`have_node()`), which readabilipy exposes no way to bound; it runs at most once per process and not at all when the budget is disabled.diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.pyindex fb1e100cd3..f16f20e24d 100644--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py@@ -147,10 +147,11 @@ def extract_content(if not html or not html.strip():return None- # Run trafilatura and newspaper4k in parallel, pick the better result.- # newspaper4k is strong on news front pages and multi-answer threads- # where trafilatura sometimes extracts less content.- # 5s timeout per extractor — covers P95 of pages, cuts off outliers.+ # Run trafilatura and newspaper4k, pick the better result. newspaper4k is+ # strong on news front pages and multi-answer threads where trafilatura+ # sometimes extracts less content.+ # No time bound here: the extractors run sequentially in-process (see+ # _run_extractors_parallel — the ThreadPoolExecutor was removed).trafilatura_content, newspaper_content = _run_extractors_parallel(html, url)traf_score = _quality_score(trafilatura_content)diff --git a/src/local_deep_research/research_library/downloaders/extraction/readability_extractor.py b/src/local_deep_research/research_library/downloaders/extraction/readability_extractor.pyindex 2504d33076..73b44c7f9d 100644--- a/src/local_deep_research/research_library/downloaders/extraction/readability_extractor.py+++ b/src/local_deep_research/research_library/downloaders/extraction/readability_extractor.py@@ -9,12 +9,336 @@ Uses Node.js for full Readability.js support when available;readabilipy falls back to pure-Python mode automatically."""-from typing import Optional+import threading+from typing import Any, Callable, Optionalfrom loguru import loggerfrom .base import BaseExtractor+# Readability.js does not run in-process: readabilipy shells out to a Node+# subprocess (ExtractArticle.js) and exposes no timeout, so a slow or wedged+# node blocks the calling thread for as long as it takes. That is unbounded+# for a research run, and under pytest-timeout it costs a whole xdist worker+# rather than a single test (#6209). Bound the Node path instead and fall+# back to readabilipy's pure-Python parser, which is lower quality but does+# not leave a process behind.+#+# Seconds to allow the Node extraction. At <= 0 the pure-Python parser is+# used and the availability probe below is skipped too, so no node process is+# started at all. The test suite sets 0 (tests/conftest.py) so unit tests+# never shell out.+NODE_TIMEOUT_SECONDS = 20.0++# How many node calls may be IN FLIGHT at once. This is a resource bound, not+# a health signal. A research run extracts several pages concurrently (one+# worker thread per page — see lxml_thread_safety), and node is healthy on+# the overwhelming majority of them, so this has to sit above the normal+# fan-out: every caller turned away here is silently downgraded to the+# lower-quality pure-Python parser. What it buys is a ceiling on a single+# burst — if node wedges while these are all running, at most this many+# calls strand at once.+NODE_MAX_CONCURRENT_CALLS = 8++# How many STRANDED calls — timed out, and still blocked on their node+# process — may pile up before we stop reaching for node at all. This is the+# health signal, and it is deliberately much tighter than the concurrency+# bound above. Gate on threads that are STILL RUNNING rather than on a count+# of past timeouts: the budget is wall-clock, so under concurrent extraction+# a merely BUSY node can blow it on every thread at once. Those threads+# finish shortly afterwards and drop out of the list; a genuinely wedged+# node's threads never do. Counting live threads therefore measures the thing+# we actually care about — stranded process/thread pairs — and recovers on+# its own once they clear, instead of latching off permanently the first time+# the machine is busy.+NODE_MAX_STRANDED_CALLS = 3++_node_state_lock = threading.Lock()+# Threads whose node call overran the budget and that we stopped waiting for.+_stranded_calls: list[threading.Thread] = []+# Node calls admitted but not yet resolved; see _acquire_node_slot.+_node_calls_in_flight = 0++_have_node_lock = threading.Lock()+_have_node_cache: Optional[bool] = None+++def _node_is_available() -> bool:+ """Whether readabilipy can actually run Readability.js on this machine.++ Probed once and cached, because the probe is expensive and unbounded:+ readabilipy's ``have_node()`` shells out to ``node -v`` with no timeout of+ its own and, on a first run with no bundled ``node_modules``, goes on to+ run ``npm install`` under a process-wide ``os.chdir``. Running that per+ page is exactly the cost this module exists to avoid.++ Caching is therefore a trade-off, not a free win: the answer *can* change,+ because ``have_node()`` returns False on a transient failure (a busy+ machine, a failed or half-finished ``npm install``) as readily as on a+ genuinely node-less host. A False cached that way disables Readability.js+ for the rest of the process — until a restart, there is no re-probe. We+ accept that over an unbounded shell-out on every page.++ Getting False right matters beyond saving the probe: the published+ runtime image installs Node only in the build stage, so the shipped+ container has no ``node``. There, ``use_readability=True`` is downgraded+ to ``False`` inside readabilipy and the "node worker" is really a+ pure-Python html5lib parse. Bounding *that* is worse than useless — an+ overrun abandons the parse and re-runs the identical work on the caller's+ thread, doubling both CPU and peak memory for no timeout benefit. When+ node is absent we therefore take the pure-Python path directly, with no+ worker thread and no budget.++ A probe that raises is treated as "node may be present", which keeps the+ bounded path (and therefore the timeout protection) rather than silently+ dropping it.+ """+ global _have_node_cache+ with _have_node_lock:+ if _have_node_cache is None:+ try:+ from readabilipy.simple_json import have_node++ _have_node_cache = bool(have_node())+ except Exception:+ logger.debug(+ "readabilipy node probe failed; assuming node may be "+ "present and keeping the bounded path"+ )+ _have_node_cache = True+ return _have_node_cache+++def _stranded_call_count() -> int:+ """Timed-out calls whose thread is still blocked on its node process."""+ with _node_state_lock:+ _stranded_calls[:] = [t for t in _stranded_calls if t.is_alive()]+ return len(_stranded_calls)+++def _acquire_node_slot() -> bool:+ """Reserve one live node slot, if both bounds allow it.++ Prune, count and reserve happen under a single hold of the lock. Checking+ a count and then starting a thread as two steps is a check-then-act race:+ sixteen concurrent callers would each read "0 stranded" and each start a+ worker, so a node that wedges while they run strands sixteen threads.+ Reserving here makes both ceilings hold no matter how wide the caller+ fan-out is.++ The two bounds are separate on purpose and compose:++ * ``NODE_MAX_CONCURRENT_CALLS`` caps calls that are merely *running*, so+ healthy concurrency is not throttled down to the stranded budget, and+ one burst against a node that wedges mid-flight can strand at most that+ many calls;+ * ``NODE_MAX_STRANDED_CALLS`` caps calls that already timed out and are+ still stuck, and once it is reached nothing new is admitted until they+ clear.+ """+ global _node_calls_in_flight+ with _node_state_lock:+ _stranded_calls[:] = [t for t in _stranded_calls if t.is_alive()]+ if len(_stranded_calls) >= NODE_MAX_STRANDED_CALLS:+ return False+ if _node_calls_in_flight >= NODE_MAX_CONCURRENT_CALLS:+ return False+ _node_calls_in_flight += 1+ return True+++def _release_node_slot(+ stranded_worker: Optional[threading.Thread], settled: list+) -> None:+ """Give the slot back, or hand it over to the stranded-thread list.++ ``settled`` is a one-element list (``[False]``) owned by the caller and+ shared across every exit path of a single call. Checking and setting+ ``settled[0]`` happens under the same lock hold as the release itself,+ which is what makes this idempotent: a call's slot settles exactly once+ no matter how many of the caller's exit paths try to release it.++ That matters because a caller can legitimately reach for this more than+ once for the same call — the ordinary release after ``join()`` returns,+ and a ``finally`` backstop below it for exits nobody asked for. Those+ two used to be "release, then note it happened" as two separate+ statements, which left a window: an asynchronous exception (e.g. a+ ``KeyboardInterrupt`` delivered to the main thread) landing between them+ made the backstop believe the slot was never settled and release it+ again — decrementing the live count twice (drifting the effective+ concurrency bound up by one admission) and, when the call was stranded,+ appending the same still-alive thread to ``_stranded_calls`` twice.+ Moving the check-and-set inside this lock hold closes that window: the+ second call in such a race sees ``settled[0]`` already ``True`` and is a+ no-op.++ Both the settle and the stranded-list handoff happen under one hold of+ the lock so the live count never dips and lets an extra caller through+ in between.++ The count is clamped at zero. It should never go negative — every+ admitted call settles exactly once — but a release against an+ already-zero counter would otherwise buy admissions *above* the bound,+ which is the wrong way to fail.+ """+ global _node_calls_in_flight+ with _node_state_lock:+ if settled[0]:+ return+ settled[0] = True+ _node_calls_in_flight = max(0, _node_calls_in_flight - 1)+ if stranded_worker is None:+ return+ _stranded_calls.append(stranded_worker)+ stranded = sum(1 for t in _stranded_calls if t.is_alive())+ if stranded >= NODE_MAX_STRANDED_CALLS:+ logger.warning(+ f"{stranded} Readability.js calls are still stuck on node — "+ "using pure-Python extraction until they clear"+ )+++def _reset_node_breaker() -> None:+ """Test hook: forget the stranded calls and the cached node probe.++ It deliberately leaves ``_node_calls_in_flight`` alone. That counter is+ owned by the calls themselves, each of which releases it in a ``finally``;+ zeroing it underneath a call that is still running made the eventual+ release drive it negative, which handed out slots above the bound. A test+ that strands workers must drain them, not reset the count out from under+ them.+ """+ global _have_node_cache+ with _node_state_lock:+ _stranded_calls.clear()+ with _have_node_lock:+ _have_node_cache = None+++def _extract_json(+ simple_json_from_html_string: Callable[..., Any],+ html: str,+ *,+ node_available: bool,+) -> Any:+ """Run readabilipy, keeping the Node subprocess on a leash.++ Only the Node path is bounded, and only when node is actually installed+ (``node_available``); otherwise readabilipy's pure-Python parser runs+ inline on this thread, because there is no subprocess to leash and+ abandoning an in-process parse only duplicates the work.++ The Node call runs on a daemon thread: if it overruns the budget we stop+ waiting and take the pure-Python result instead. ``daemon=True`` keeps+ the abandoned thread from blocking interpreter shutdown, but it does not+ kill anything — a timed-out call leaves three things behind:++ * the stray ``node`` process (readabilipy owns the handle and gives us no+ way to signal it), which is reparented and outlives this interpreter;+ * the thread itself, which is not parked but blocked inside+ ``subprocess.run`` and can only exit when that process does;+ * readabilipy's ``NamedTemporaryFile(delete=False)`` copy of the full+ page, which it unlinks only after node returns *successfully*. On a+ ``subprocess.CalledProcessError`` — node exits non-zero rather than+ merely running long — readabilipy re-raises without unlinking either+ the input or the output temp file (``readabilipy/simple_json.py``,+ around the ``except subprocess.CalledProcessError`` block), so a node+ crash leaks both regardless of whether the call was one we timed out+ on.++ ``daemon=True`` bounds none of those; it only stops them delaying exit.+ Bounding *how many* accumulate is what ``NODE_MAX_STRANDED_CALLS``,+ ``NODE_MAX_CONCURRENT_CALLS`` and :func:`_acquire_node_slot` are for.++ A reserved slot settles — is released, or handed to the stranded list —+ exactly once, on every exit, including one taken by an exception that is+ not ours, such as a ``KeyboardInterrupt`` delivered to the main thread+ while it is parked in ``join()``. That path hands the slot *over* rather+ than releasing it: the worker is still running, so its node process is+ still outstanding and must keep being counted. Leaking the reservation+ instead was a silent, permanent loss of capacity — three interrupted+ joins and node was off for the life of the process, with nothing logged.+ The "exactly once" is enforced by :func:`_release_node_slot` itself: it+ takes a one-element ``settled`` list shared across every exit path below+ and checks-and-sets it under the same lock hold as the release, so a+ second call for the same reservation — e.g. this function's ``finally``+ backstop running after the ordinary release already did — is a no-op+ rather than a double release.++ Note the budget is wall-clock, not CPU: under concurrent extraction the+ node calls contend, so a busy machine falls back more often. That is+ working as intended — the fallback still returns content — and it no+ longer disables node, because only calls that are still running count.+ """+ timeout = NODE_TIMEOUT_SECONDS+ if timeout <= 0 or not node_available:+ return simple_json_from_html_string(html, use_readability=False)++ if not _acquire_node_slot():+ return simple_json_from_html_string(html, use_readability=False)++ outcome: dict[str, Any] = {}++ def _run() -> None:+ try:+ outcome["article"] = simple_json_from_html_string(+ html, use_readability=True+ )+ except Exception as exc: # re-raised on the calling thread+ # Deliberately not BaseException: re-raising a SystemExit or a+ # KeyboardInterrupt raised on *this* thread would unwind an+ # unrelated caller.+ outcome["error"] = exc++ worker: Optional[threading.Thread] = None+ # Shared with _release_node_slot, which checks-and-sets settled[0] under+ # its own lock hold so the slot below settles exactly once no matter how+ # many of the paths below try to release it — see its docstring.+ settled = [False]+ try:+ try:+ worker = threading.Thread(+ target=_run, name="readability-node", daemon=True+ )+ worker.start()+ except RuntimeError:+ # Thread exhaustion or interpreter shutdown. Extraction still has+ # a working answer available, so fall back rather than fail the+ # page. Nothing was started, so the slot is simply given back.+ _release_node_slot(None, settled)+ logger.warning(+ "could not start the Readability.js worker thread — "+ "falling back to pure-Python extraction"+ )+ return simple_json_from_html_string(html, use_readability=False)++ worker.join(timeout)+ overran = worker.is_alive()+ _release_node_slot(worker if overran else None, settled)+ finally:+ # A no-op whenever one of the releases above already ran — see+ # _release_node_slot. It only does real work when this finally is+ # reached WITHOUT either of them having run: an interrupt or an+ # asynchronous exception unwinding through the constructor, start(),+ # or join() before the ordinary release got a chance to run. A+ # worker that is still running at that point is stranded, not+ # finished, so hand the slot over instead of releasing it.+ _release_node_slot(+ worker if worker is not None and worker.is_alive() else None,+ settled,+ )++ if overran:+ logger.warning(+ f"Readability.js (node) exceeded {timeout}s — "+ "falling back to pure-Python extraction"+ )+ return simple_json_from_html_string(html, use_readability=False)++ if "error" in outcome:+ raise outcome["error"]+ return outcome.get("article")+class ReadabilityExtractor(BaseExtractor):"""Extract content using Mozilla Readability.js via readabilipy.@@ -36,9 +360,14 @@ class ReadabilityExtractor(BaseExtractor):return Nonetry:- # readabilipy checks for Node.js internally and falls back- # to pure-Python mode automatically if it's not available.- article = simple_json_from_html_string(html, use_readability=True)+ article = _extract_json(+ simple_json_from_html_string,+ html,+ # The probe itself shells out (see _node_is_available), so+ # don't pay for it when the Node path is switched off anyway.+ node_available=NODE_TIMEOUT_SECONDS > 0+ and _node_is_available(),+ )except Exception:logger.exception("readabilipy extraction failed")return Nonediff --git a/src/local_deep_research/utilities/lxml_thread_safety.py b/src/local_deep_research/utilities/lxml_thread_safety.pyindex 9d5deb5b92..4682480cbb 100644--- a/src/local_deep_research/utilities/lxml_thread_safety.py+++ b/src/local_deep_research/utilities/lxml_thread_safety.py@@ -58,7 +58,12 @@ import lxml.htmlfrom loguru import logger# One parser per thread, per configuration. Parsers are cheap; a worker thread-# builds its two parsers once and reuses them for its lifetime.+# builds its two parsers once and reuses them for its lifetime. The+# short-lived per-call threads used to bound the Readability.js subprocess+# (see downloaders/extraction/readability_extractor) do not add to that: they+# run only readabilipy's ``use_readability=True`` branch, which shells out to+# node and never reaches ``lxml.html.fromstring`` — that call lives in the+# pure-Python branch, which runs on the caller's own thread._local = threading.local()_install_lock = threading.Lock()diff --git a/tests/conftest.py b/tests/conftest.pyindex bdae82cf2c..111cd418e6 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -217,6 +217,35 @@ def pytest_configure(config):os.environ["LDR_TESTING_WITH_MOCKS"] = "true"[email protected](scope="session", autouse=True)+def no_readability_node_subprocess():+ """Keep Readability.js (a Node subprocess) out of the test suite.++ readabilipy shells out to node for every extraction — ~2.9s per call,+ with no timeout of its own. Content-extraction tests exercise our+ parsing branches, not Readability.js, and under xdist one slow+ subprocess costs the whole worker at the 180s pytest-timeout rather+ than failing a single test (#6209).++ A budget of 0 skips both the per-page node call and the availability+ probe — itself an unbounded ``node -v``, plus an ``npm install`` on+ every install, since the wheel ships no ``node_modules`` of its own; it+ is not a first-run edge case. Tests that need the Node path restore the+ budget themselves; the probe then does run — cached for the rest of the+ process in general, though ``test_readability_node_timeout.py``'s own+ autouse fixture resets that cache before and after each of its tests, so+ within that module the probe can run again per test.+ """+ from local_deep_research.research_library.downloaders.extraction import (+ readability_extractor,+ )++ original = readability_extractor.NODE_TIMEOUT_SECONDS+ readability_extractor.NODE_TIMEOUT_SECONDS = 0+ yield+ readability_extractor.NODE_TIMEOUT_SECONDS = original++@pytest.fixture(autouse=True)def skip_if_no_real_llm(request):"""Skip tests marked with @pytest.mark.requires_llm when running with mocks."""diff --git a/tests/research_library/downloaders/test_readability_node_timeout.py b/tests/research_library/downloaders/test_readability_node_timeout.pynew file mode 100644index 0000000000..1ad534524e--- /dev/null+++ b/tests/research_library/downloaders/test_readability_node_timeout.py@@ -0,0 +1,514 @@+"""The Readability.js (Node) path must be bounded — see #6209.++readabilipy shells out to a Node subprocess and exposes no timeout, so a+slow or wedged node blocks its caller indefinitely: an unbounded stall for+a research run, and a killed xdist worker under pytest-timeout in CI.++The bound only makes sense when node is actually installed. Without it+readabilipy silently downgrades to its in-process html5lib parser, and+abandoning *that* on overrun just runs the same parse twice, so the+node-absent case must short-circuit instead.+"""++import sys+import threading+import types++import pytest++from local_deep_research.research_library.downloaders.extraction import (+ readability_extractor as re_mod,+)++[email protected](autouse=True)+def reset_breaker():+ """The breaker is process-global; never let it leak between tests."""+ re_mod._reset_node_breaker()+ yield+ re_mod._reset_node_breaker()+++def node_timeout(monkeypatch):+ """Set the Node budget for one test."""++ def _set(value):+ monkeypatch.setattr(re_mod, "NODE_TIMEOUT_SECONDS", value)++ return _set+++def _extract(fake, html="<html></html>", node_available=True):+ return re_mod._extract_json(fake, html, node_available=node_available)+++class _WedgedNode:+ """A readabilipy stand-in whose node path never returns on its own.++ Every handshake is an :class:`threading.Event`, so tests wait for the+ state they need instead of sleeping for a guessed interval.+ """++ def __init__(self):+ self.release = threading.Event()+ self.entered = threading.Event()+ self.finished = threading.Event()+ self.attempts = []+ self.workers = []+ self._lock = threading.Lock()++ def __call__(self, html, use_readability=False):+ with self._lock:+ self.attempts.append(use_readability)+ if use_readability:+ self.workers.append(threading.current_thread())+ if use_readability:+ self.entered.set()+ # Released by the test; the bound must fire long before this.+ self.release.wait(30)+ self.finished.set()+ return {"content": "<p>too late</p>"}+ return {"content": "<p>pure</p>"}++ @property+ def node_attempts(self):+ return sum(1 for a in self.attempts if a)++ def drain(self, timeout=10):+ """Let every started worker run to completion and join it."""+ self.release.set()+ for worker in list(self.workers):+ worker.join(timeout)+ assert not worker.is_alive(), "wedged worker never finished"+++class TestNodeIsBounded:+ def test_zero_budget_never_invokes_node(self, node_timeout):+ """The suite-wide default: no subprocess, pure-Python only."""+ node_timeout(0)+ seen = []++ def fake(html, use_readability=False):+ seen.append(use_readability)+ return {"content": "<p>pure</p>"}++ assert _extract(fake) == {"content": "<p>pure</p>"}+ assert seen == [False], "node path must not be taken at budget 0"++ def test_node_used_when_budget_allows(self, node_timeout):+ node_timeout(30)+ seen = []++ def fake(html, use_readability=False):+ seen.append(use_readability)+ return {"content": "<p>node</p>"}++ assert _extract(fake) == {"content": "<p>node</p>"}+ assert seen == [True]++ def test_overrun_falls_back_instead_of_blocking(self, node_timeout):+ """A slow node must not hold the caller past the budget."""+ node_timeout(0.2)+ fake = _WedgedNode()++ try:+ result = _extract(fake)++ assert result == {"content": "<p>pure</p>"}+ assert fake.attempts == [True, False]+ assert fake.entered.is_set(), "the node path was never entered"+ assert not fake.finished.is_set(), (+ "the caller waited for the wedged node instead of falling "+ "back — this is the #6209 hang"+ )+ finally:+ fake.drain()++ def test_node_errors_still_surface(self, node_timeout):+ """Failures must propagate, not be swallowed by the wrapper."""+ node_timeout(30)++ def fake(html, use_readability=False):+ raise RuntimeError("node exploded")++ with pytest.raises(RuntimeError, match="node exploded"):+ _extract(fake)++ def test_thread_exhaustion_falls_back(self, node_timeout, monkeypatch):+ """``Thread.start`` can raise; that must not fail the extraction."""+ node_timeout(30)+ seen = []++ class Unstartable(threading.Thread):+ def start(self):+ raise RuntimeError("can't start new thread")++ # Shim the module's own ``threading`` reference rather than patching+ # ``threading.Thread`` process-wide, which would break every other+ # thread started while this test runs.+ monkeypatch.setattr(+ re_mod, "threading", types.SimpleNamespace(Thread=Unstartable)+ )++ def fake(html, use_readability=False):+ seen.append(use_readability)+ return {"content": "<p>pure</p>"}++ assert _extract(fake) == {"content": "<p>pure</p>"}+ assert seen == [False]+ # The reserved slot must be handed back, or the cap leaks.+ assert re_mod._node_calls_in_flight == 0++ def test_an_interrupted_join_hands_the_slot_over(+ self, node_timeout, monkeypatch+ ):+ """Ctrl-C while parked in ``join()`` must not eat the reservation.++ The interrupt lands on the caller, not on the worker, so the worker+ is still sitting on its node process: the call has to be recorded+ stranded rather than quietly released. Leaking the reservation+ instead is silent and permanent — enough interrupted joins and+ admission is refused for the rest of the process, with nothing+ logged.+ """+ node_timeout(5)+ fake = _WedgedNode()++ class InterruptedJoin(threading.Thread):+ # Only the join inside the extractor is interrupted; ``drain``+ # still needs a working one to reap the worker afterwards.+ interrupt = True++ def join(self, timeout=None):+ if InterruptedJoin.interrupt:+ InterruptedJoin.interrupt = False+ raise KeyboardInterrupt("ctrl-c while parked in join")+ return super().join(timeout)++ monkeypatch.setattr(+ re_mod, "threading", types.SimpleNamespace(Thread=InterruptedJoin)+ )++ try:+ with pytest.raises(KeyboardInterrupt):+ _extract(fake)++ assert fake.entered.wait(10), "the node path was never entered"+ assert re_mod._node_calls_in_flight == 0, (+ "the reserved slot leaked; enough of these and node is "+ "refused for the life of the process"+ )+ assert len(re_mod._stranded_calls) == 1, (+ "the worker is still on its node process, so the call must "+ "be handed to the stranded list, not released"+ )+ finally:+ fake.drain()+++class TestNodeAbsentShortCircuits:+ """Without node, readabilipy's "node" path *is* the pure-Python parser.++ Bounding it would abandon an in-process html5lib parse and immediately+ redo it on the caller's thread: twice the CPU and twice the peak memory+ for no timeout benefit. The published runtime image has no node, so this+ is the shipped configuration, not a corner case.+ """++ def test_no_thread_is_spawned_when_node_is_absent(+ self, node_timeout, monkeypatch+ ):+ node_timeout(30)+ seen = []+ constructed = []++ class RecordingThread(threading.Thread):+ def __init__(self, *args, **kwargs):+ constructed.append(kwargs.get("name"))+ super().__init__(*args, **kwargs)++ # Shim the module's own ``threading`` reference rather than reading+ # ``threading.active_count()``, which is process-global: a daemon+ # left behind by an unrelated test can expire mid-assertion.+ monkeypatch.setattr(+ re_mod, "threading", types.SimpleNamespace(Thread=RecordingThread)+ )++ def fake(html, use_readability=False):+ seen.append((use_readability, threading.current_thread()))+ return {"content": "<p>pure</p>"}++ result = _extract(fake, node_available=False)++ assert result == {"content": "<p>pure</p>"}+ assert seen == [(False, threading.current_thread())], (+ "without node the pure-Python parse must run inline on the "+ "caller's thread, with use_readability=False"+ )+ assert constructed == [], (+ "a worker thread was constructed for a call that cannot use node"+ )++ def test_availability_is_probed_via_have_node_and_cached(self, monkeypatch):+ calls = []++ def have_node():+ calls.append(1)+ return False++ stub = types.ModuleType("readabilipy.simple_json")+ stub.have_node = have_node+ monkeypatch.setitem(sys.modules, "readabilipy.simple_json", stub)++ assert re_mod._node_is_available() is False+ assert re_mod._node_is_available() is False+ assert len(calls) == 1, "have_node() must be probed once, then cached"++ def test_a_failing_probe_keeps_the_bounded_path(self, monkeypatch):+ stub = types.ModuleType("readabilipy.simple_json")++ def have_node():+ raise OSError("no /proc")++ stub.have_node = have_node+ monkeypatch.setitem(sys.modules, "readabilipy.simple_json", stub)++ assert re_mod._node_is_available() is True, (+ "an unreadable probe must not silently drop the timeout"+ )+++class TestExtractorStillWorks:+ def test_extract_returns_content_without_node(self, node_timeout):+ node_timeout(0)+ html = (+ "<html><body><article><p>"+ + "A" * 200+ + "</p></article></body></html>"+ )++ result = re_mod.ReadabilityExtractor().extract(html)++ assert result is not None+ assert "A" * 50 in result++ def test_extract_falls_back_when_node_wedges(+ self, node_timeout, monkeypatch+ ):+ """End-to-end through ``extract()``, not just ``_extract_json``.++ Reverting the bound makes this hang for 30s (the fake's own ceiling)+ instead of returning, so it pins the caller-visible behaviour.+ """+ node_timeout(0.2)+ fake = _WedgedNode()+ stub = types.ModuleType("readabilipy")+ stub.simple_json_from_html_string = fake+ monkeypatch.setitem(sys.modules, "readabilipy", stub)+ monkeypatch.setattr(re_mod, "_node_is_available", lambda: True)++ try:+ result = re_mod.ReadabilityExtractor().extract("<html>hi</html>")++ assert result == "<p>pure</p>"+ assert fake.attempts == [True, False]+ assert not fake.finished.is_set()+ finally:+ fake.drain()++ def test_empty_html_short_circuits(self, monkeypatch):+ """Blank input must not reach readabilipy at all.++ Characterisation of the pre-existing guard in ``extract()``: it is+ unchanged by this PR and holds on either side of it. It is kept so+ that a future rework of the node plumbing cannot quietly start+ shelling out for whitespace.+ """+ calls = []+ stub = types.ModuleType("readabilipy")++ def fake(html, use_readability=False):+ calls.append(html)+ return {"content": "<p>x</p>"}++ stub.simple_json_from_html_string = fake+ monkeypatch.setitem(sys.modules, "readabilipy", stub)++ assert re_mod.ReadabilityExtractor().extract(" ") is None+ assert calls == []+++class TestBreakerBoundsAccumulation:+ """Each timeout strands a node process AND the thread blocked on it, so+ enough stuck calls must stop us reaching for node at all."""++ def test_wedged_calls_stop_spawning_more(self, node_timeout):+ node_timeout(0.1)+ fake = _WedgedNode()++ try:+ for _ in range(re_mod.NODE_MAX_STRANDED_CALLS + 4):+ assert _extract(fake) == {"content": "<p>pure</p>"}++ assert fake.node_attempts == re_mod.NODE_MAX_STRANDED_CALLS, (+ f"node was attempted {fake.node_attempts}x; should stop after "+ f"{re_mod.NODE_MAX_STRANDED_CALLS} calls are stuck"+ )+ finally:+ fake.drain()++ def test_concurrent_callers_cannot_exceed_the_cap(self, node_timeout):+ """Admission must be atomic, not check-then-act.++ Reading the counts and then starting a thread as two steps lets+ every caller through the gate at once: sixteen concurrent callers+ would strand sixteen threads no matter what the bound says.+ """+ node_timeout(0.2)+ width = re_mod.NODE_MAX_CONCURRENT_CALLS * 2+ fake = _WedgedNode()+ barrier = threading.Barrier(width)+ results = []+ results_lock = threading.Lock()++ def caller():+ barrier.wait(10)+ value = _extract(fake)+ with results_lock:+ results.append(value)++ callers = [+ threading.Thread(target=caller, name=f"caller-{i}")+ for i in range(width)+ ]+ try:+ for thread in callers:+ thread.start()+ for thread in callers:+ thread.join(30)+ assert not thread.is_alive(), "a caller blocked on wedged node"++ assert len(results) == width+ assert results == [{"content": "<p>pure</p>"}] * width+ assert fake.node_attempts <= re_mod.NODE_MAX_CONCURRENT_CALLS, (+ f"{width} concurrent callers started {fake.node_attempts} "+ f"node workers; the cap is "+ f"{re_mod.NODE_MAX_CONCURRENT_CALLS}"+ )+ finally:+ fake.drain()+ for thread in callers:+ thread.join(10)++ def test_a_slow_but_finishing_node_does_not_latch_it_off(+ self, node_timeout+ ):+ """Under concurrency every call can blow a wall-clock budget while+ node is merely busy. Those threads finish, so they must not count as+ stranded."""+ node_timeout(0.05)+ rounds = re_mod.NODE_MAX_STRANDED_CALLS + 3+ node_attempts = 0++ for _ in range(rounds):+ # One fake per round: it overruns the budget, then completes+ # before the next admission — a busy node, not a wedged one.+ fake = _WedgedNode()+ try:+ assert _extract(fake) == {"content": "<p>pure</p>"}+ assert fake.entered.wait(10), "node path was never entered"+ node_attempts += fake.node_attempts+ finally:+ fake.drain()++ assert node_attempts == rounds, (+ f"node was attempted only {node_attempts}x; a busy-but-working "+ "node must not disable the path"+ )++ def test_healthy_concurrency_is_not_capped_by_the_stranded_budget(+ self, node_timeout+ ):+ """A healthy node must serve the whole extraction fan-out.++ The stranded budget is a health signal, not a concurrency limit.+ Charging live calls against it throttled healthy concurrency down to+ three, so most of a wide run was silently downgraded to the+ lower-quality pure-Python parser while node was perfectly fine.+ """+ node_timeout(30)+ width = re_mod.NODE_MAX_CONCURRENT_CALLS+ assert width > re_mod.NODE_MAX_STRANDED_CALLS, (+ "the two bounds must differ, or this test proves nothing"+ )++ # Every admitted caller has to be inside the node path at the same+ # time, otherwise a cap of one would satisfy the assertion below.+ together = threading.Barrier(width)+ attempts = []+ results = []+ failures = []+ lock = threading.Lock()++ def fake(html, use_readability=False):+ with lock:+ attempts.append(use_readability)+ if use_readability:+ together.wait(10)+ return {"content": "<p>node</p>"}+ return {"content": "<p>pure</p>"}++ def caller():+ try:+ value = re_mod._extract_json(+ fake, "<html></html>", node_available=True+ )+ except BaseException as exc: # reported, not swallowed+ with lock:+ failures.append(exc)+ return+ with lock:+ results.append(value)++ callers = [+ threading.Thread(target=caller, name=f"healthy-{i}")+ for i in range(width)+ ]+ try:+ for thread in callers:+ thread.start()+ for thread in callers:+ thread.join(30)+ assert not thread.is_alive(), "a caller never returned"+ finally:+ together.abort()++ node_attempts = sum(1 for a in attempts if a)+ assert not failures, f"callers failed: {failures}"+ assert node_attempts == width, (+ f"only {node_attempts} of {width} concurrent callers reached "+ "Readability.js; a healthy node must not be rationed by the "+ "stranded budget"+ )+ assert results == [{"content": "<p>node</p>"}] * width+ assert re_mod._node_calls_in_flight == 0++ def test_it_recovers_once_stuck_calls_clear(self, node_timeout):+ """A latch that never lifts is the wrong shape for a long-lived+ process that hit a busy patch."""+ node_timeout(0.05)+ fake = _WedgedNode()++ try:+ for _ in range(re_mod.NODE_MAX_STRANDED_CALLS):+ _extract(fake)+ assert (+ re_mod._stranded_call_count() >= re_mod.NODE_MAX_STRANDED_CALLS+ )+ finally:+ fake.drain()++ assert re_mod._stranded_call_count() < re_mod.NODE_MAX_STRANDED_CALLS, (+ "stranded calls finished but the breaker stayed latched"+ )