Skip to content

~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.

test(queue): pin reviewer follow-up guarantees (#6078)

LearningCircuit5c490422bf46
diff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.py
index b382bc0cc7..7abdf25c58 100644
--- a/tests/web/queue/test_processor_v2_real.py
+++ b/tests/web/queue/test_processor_v2_real.py
@@ -15,7 +15,6 @@ Tests cover:
- process_pending_operations_for_user: progress/error updates, rollback
"""
-import time
import threading
from unittest.mock import Mock, MagicMock, patch
@@ -33,6 +32,113 @@ def _make_processor():
return QueueProcessorV2(check_interval=1)
+def _stop_loop_after_call(processor, fn=None):
+ """Wrap a ``_process_user_queue`` replacement so the FIRST call it
+ receives deterministically stops ``_process_queue_loop`` after the
+ current iteration, with no thread and no sleep.
+
+ ``_process_queue_loop`` captures the whole ``_users_to_check`` set at
+ the top of each iteration and processes all of it before re-checking
+ ``while self.running:`` -- flipping ``running`` mid-iteration does not
+ cut that iteration short, it only prevents a *second* iteration from
+ starting. Setting ``_stop_event`` too makes the loop's tail
+ ``self._stop_event.wait(self.check_interval)`` return immediately
+ instead of blocking for up to ``check_interval`` seconds. Together
+ that guarantees the loop runs exactly one full iteration and returns
+ right away, deterministically, regardless of how many users are in
+ ``_users_to_check`` or how the machine happens to be scheduled.
+
+ ``fn`` is the real per-call behavior (return value or side effect);
+ it is called first so its result/exception is preserved.
+ """
+
+ def _wrapped(*args, **kwargs):
+ try:
+ if fn is not None:
+ return fn(*args, **kwargs)
+ finally:
+ processor.running = False
+ processor._stop_event.set()
+
+ return _wrapped
+
+
+def test_constructor_is_inert_until_explicit_start():
+ """Construction initializes state without leaving behind any new
+ thread that is still alive when this function's second snapshot is
+ taken.
+
+ Regression guard: snapshots the set of live thread objects before
+ constructing QueueProcessorV2, then asserts no thread present after
+ construction was absent before. This catches a constructor that spawns
+ a worker thread that is still running at that point, even if that
+ thread is never assigned to ``processor.thread`` (a plain
+ ``processor.thread is None`` check alone would miss an
+ unreferenced/leaked thread).
+
+ KNOWN BLIND SPOT (deliberate, not an oversight): ``threading.enumerate()``
+ lists only CURRENTLY-LIVE threads. A constructor that spawned a
+ short-lived, fire-and-forget thread which both starts AND finishes
+ before the ``set(threading.enumerate())`` line below runs would leave
+ ``new_threads`` empty, and this test would pass even though a thread
+ was spawned. A hook that fires on every thread's bootstrap --
+ ``threading.setprofile``/``settrace`` -- would close that gap:
+ confirmed against the installed CPython's ``threading.py``
+ (``Thread._bootstrap_inner``), the profile hook is installed via
+ ``sys.setprofile(_profile_hook)`` *before* ``self.run()`` is invoked,
+ so it fires even for a thread that starts and dies immediately.
+ That mechanism was deliberately NOT adopted here: ``setprofile``
+ installs process-wide for the duration of the constructor call, so it
+ would also fire for the same unrelated anyio worker threads this test
+ already has to tolerate (see below) -- turning "starts during the
+ window" into a new source of exactly the flakiness this test's
+ one-directional design exists to avoid, to close a gap
+ (QueueProcessorV2.__init__ spawning a fire-and-forget thread) that is
+ not a pattern this constructor actually uses. If __init__ ever grows
+ one, prefer a targeted assertion (e.g. patching ``threading.Thread``
+ itself for the duration of this test) over broadening a process-wide
+ hook.
+
+ Deliberately a ONE-DIRECTIONAL set difference (``after - before``),
+ not an equality/count comparison: this test runs inside a shared
+ pytest process alongside ~100+ modules that use FastAPI's TestClient,
+ which spins up anyio "AnyIO worker thread" workers that anyio prunes
+ lazily on a later, unrelated ``run_sync`` call once they've been idle
+ for a while -- so unrelated threads can legitimately start or die in
+ the same few lines as the constructor call, for reasons that have
+ nothing to do with QueueProcessorV2. An equality check on
+ ``active_count()`` or the ``enumerate()`` name set spuriously fails on
+ that unrelated churn (and a simultaneous start+death can even leave
+ ``active_count()`` unchanged while a new thread genuinely appeared, so
+ active_count() alone is not a safe substitute either). Threads that
+ disappeared during the call (``before - after``) are not a defect in
+ the constructor and must not fail this test -- only a thread the
+ constructor itself introduced should.
+
+ Note: this test does NOT verify that app startup replacing the module
+ singleton (``processor_v2.queue_processor``) is observable — doing so
+ would require exercising the startup code path, and an independent
+ re-derivation of the module attribute (e.g. via importlib.reload) risks
+ re-running module-level side effects shared with the rest of the test
+ session. The previous ``processor_v2.queue_processor is singleton``
+ assertion was dropped because it only re-read the same attribute it had
+ just cached and could only fail if __init__ itself rebound the module
+ global -- not the "singleton survives startup" claim it was labeled as.
+ """
+ from local_deep_research.web.queue import processor_v2
+
+ threads_before = set(threading.enumerate())
+
+ processor = processor_v2.QueueProcessorV2(check_interval=1)
+
+ assert processor.running is False
+ assert processor.thread is None
+ new_threads = set(threading.enumerate()) - threads_before
+ assert new_threads == set(), (
+ f"constructor introduced new thread(s): {new_threads}"
+ )
+
+
# ---------------------------------------------------------------------------
# notify_research_queued — direct vs queue mode branching
# ---------------------------------------------------------------------------
@@ -399,16 +505,11 @@ class TestProcessQueueLoop:
processor._users_to_check.add(("alice", "sess-abc"))
with patch.object(
- processor, "_process_user_queue", return_value=True
+ processor,
+ "_process_user_queue",
+ side_effect=_stop_loop_after_call(processor, lambda u, s: True),
) as mock_pq:
- # Run one iteration then stop
processor.running = True
-
- def stop_after_one():
- time.sleep(0.05)
- processor.running = False
-
- threading.Thread(target=stop_after_one).start()
processor._process_queue_loop()
mock_pq.assert_called_with("alice", "sess-abc")
@@ -423,15 +524,11 @@ class TestProcessQueueLoop:
return username == "alice" # alice's queue is empty
with patch.object(
- processor, "_process_user_queue", side_effect=side_effect
+ processor,
+ "_process_user_queue",
+ side_effect=_stop_loop_after_call(processor, side_effect),
):
processor.running = True
-
- def stop_after_one():
- time.sleep(0.05)
- processor.running = False
-
- threading.Thread(target=stop_after_one).start()
processor._process_queue_loop()
assert ("alice", "sess1") not in processor._users_to_check
@@ -442,18 +539,15 @@ class TestProcessQueueLoop:
processor = _make_processor()
processor._users_to_check.add(("alice", "sess1"))
+ def raise_transient(username, session_id):
+ raise RuntimeError("transient")
+
with patch.object(
processor,
"_process_user_queue",
- side_effect=RuntimeError("transient"),
+ side_effect=_stop_loop_after_call(processor, raise_transient),
):
processor.running = True
-
- def stop_after_one():
- time.sleep(0.05)
- processor.running = False
-
- threading.Thread(target=stop_after_one).start()
processor._process_queue_loop()
assert ("alice", "sess1") in processor._users_to_check
diff --git a/tests/web/test_research_lifecycle_states.py b/tests/web/test_research_lifecycle_states.py
index d400b56e74..a8079c1ec4 100644
--- a/tests/web/test_research_lifecycle_states.py
+++ b/tests/web/test_research_lifecycle_states.py
@@ -151,6 +151,8 @@ class ParkedWorker:
from local_deep_research.web.research_state import cleanup_research
cleanup_research(research_id)
+ # ``let_go`` relies on this ordering when it inspects global state:
+ # the event is visible only after final cleanup has returned.
self.exited.set()
# -- test-side driving -------------------------------------------------
@@ -161,7 +163,7 @@ class ParkedWorker:
self.entered.clear()
def let_go(self, timeout=20.0):
- """Release the parked worker and wait for it to record its check."""
+ """Release the worker and block through its checkpoint and cleanup."""
self.release.set()
assert self.exited.wait(timeout), "worker never finished"
self.exited.clear()