Add exact and semantic evidence admission, measured calibration, bounded tool execution, and independent held-out evaluation preparation with regression coverage and operator guides. Real-provider quality gates remain pending. Validation: 1300 provider-free tests passed; 3 Windows symlink skips. PostgreSQL acceptance not rerun because TEST_DATABASE_URL is unset.
296 lines
12 KiB
Python
296 lines
12 KiB
Python
"""Deterministic shutdown races through actual LangChain sync/async entrypoints."""
|
|
import asyncio
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from threading import Event
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from app.modules.knowledge import langchain_tool as adapter
|
|
from tests.unit.test_search_phase3 import authority, context, tool
|
|
|
|
|
|
def invoke(value, asynchronous):
|
|
return asyncio.run(value.ainvoke({"query": "q"})) if asynchronous else value.invoke({"query": "q"})
|
|
|
|
|
|
def assert_cancelled(result):
|
|
assert result["status"] == "error" and result["sources"] == []
|
|
assert result["error"]["code"] == "SEARCH_CANCELLED"
|
|
assert result["error"]["retryable"] is False
|
|
|
|
|
|
@pytest.fixture
|
|
def runner():
|
|
value = adapter.SearchToolRunner(running=1, waiting=1, timeout=10)
|
|
yield value
|
|
value.close()
|
|
|
|
|
|
def shutdown_barrier(monkeypatch, runner):
|
|
"""Signal after close has set closure but before executor join."""
|
|
entered = Event()
|
|
original = runner._pool.shutdown
|
|
def shutdown(*args, **kwargs):
|
|
entered.set()
|
|
return original(*args, **kwargs)
|
|
monkeypatch.setattr(runner._pool, "shutdown", shutdown)
|
|
return entered
|
|
|
|
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
def test_shutdown_drains_queued_call_and_retains_running_slot(
|
|
asynchronous, runner, authority, monkeypatch):
|
|
started, release, queued = Event(), Event(), Event()
|
|
calls, releases = [], []
|
|
original_submit, original_release = runner._submit, runner._release
|
|
def submit(*args):
|
|
future = original_submit(*args)
|
|
if future is None:
|
|
queued.set()
|
|
return future
|
|
def record_release(*, active=False):
|
|
releases.append(active)
|
|
original_release(active=active)
|
|
monkeypatch.setattr(runner, "_submit", submit)
|
|
monkeypatch.setattr(runner, "_release", record_release)
|
|
closing = shutdown_barrier(monkeypatch, runner)
|
|
def search(*_):
|
|
calls.append("running")
|
|
started.set()
|
|
assert release.wait(5)
|
|
return dict(status="ok", sources=[dict(text="late")])
|
|
service = SimpleNamespace(engine=None, search=search)
|
|
running_ctx, queued_ctx = context(10), context(10)
|
|
with ThreadPoolExecutor(max_workers=4) as callers:
|
|
first = callers.submit(invoke, tool(service, running_ctx, runner), asynchronous)
|
|
second = close = repeated = None
|
|
try:
|
|
assert started.wait(2)
|
|
second = callers.submit(invoke, tool(service, queued_ctx, runner), asynchronous)
|
|
assert queued.wait(2)
|
|
assert (runner._active, runner._admitted) == (1, 2)
|
|
close = callers.submit(runner.close)
|
|
assert closing.wait(2)
|
|
assert_cancelled(second.result(timeout=2))
|
|
assert_cancelled(first.result(timeout=2))
|
|
# The running provider is still blocked, despite caller cancellation.
|
|
assert (runner._active, runner._admitted) == (1, 1)
|
|
assert not close.done()
|
|
repeated = callers.submit(runner.close)
|
|
assert_cancelled(invoke(tool(service, context(10), runner), asynchronous))
|
|
assert calls == ["running"]
|
|
release.set()
|
|
close.result(timeout=2)
|
|
repeated.result(timeout=2)
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
assert sorted(releases) == [False, True]
|
|
assert calls == ["running"]
|
|
finally:
|
|
running_ctx.cancelled.set()
|
|
queued_ctx.cancelled.set()
|
|
release.set()
|
|
for future in (first, second, close, repeated):
|
|
if future:
|
|
future.result(timeout=3)
|
|
|
|
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
@pytest.mark.parametrize("expired", [False, True])
|
|
def test_invocation_after_repeated_close_is_nonretryable_cancellation(
|
|
asynchronous, expired, runner, authority):
|
|
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
|
runner.close()
|
|
runner.close()
|
|
result = invoke(tool(service, context(-1 if expired else 10), runner), asynchronous)
|
|
assert_cancelled(result)
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
|
|
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
def test_close_between_initial_stop_check_and_admission(
|
|
asynchronous, runner, authority, monkeypatch):
|
|
entered, proceed = Event(), Event()
|
|
original = runner._admit
|
|
def admit():
|
|
entered.set()
|
|
assert proceed.wait(5)
|
|
return original()
|
|
monkeypatch.setattr(runner, "_admit", admit)
|
|
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
|
ctx = context(10)
|
|
with ThreadPoolExecutor(max_workers=1) as callers:
|
|
call = callers.submit(invoke, tool(service, ctx, runner), asynchronous)
|
|
try:
|
|
assert entered.wait(2)
|
|
# No admission yet, so close must finish without waiting for this call.
|
|
runner.close()
|
|
proceed.set()
|
|
assert_cancelled(call.result(timeout=2))
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
finally:
|
|
ctx.cancelled.set()
|
|
proceed.set()
|
|
call.result(timeout=3)
|
|
|
|
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
def test_submission_wins_lock_but_closed_worker_starts_no_io(
|
|
asynchronous, runner, authority, monkeypatch):
|
|
submitting, submit_allowed, worker_entered, work_allowed = (Event() for _ in range(4))
|
|
attempted = Event()
|
|
closing = shutdown_barrier(monkeypatch, runner)
|
|
original_submit, original_work = runner._pool.submit, runner._work
|
|
def submit(*args, **kwargs):
|
|
submitting.set() # _submit owns the runner lock here.
|
|
assert submit_allowed.wait(5)
|
|
return original_submit(*args, **kwargs)
|
|
def work(*args):
|
|
worker_entered.set()
|
|
assert work_allowed.wait(5)
|
|
return original_work(*args)
|
|
def close():
|
|
attempted.set()
|
|
runner.close()
|
|
monkeypatch.setattr(runner._pool, "submit", submit)
|
|
monkeypatch.setattr(runner, "_work", work)
|
|
monkeypatch.setattr(adapter, "transaction", lambda *_: pytest.fail("Closed worker database work"))
|
|
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
|
ctx = context(10)
|
|
with ThreadPoolExecutor(max_workers=2) as callers:
|
|
call = callers.submit(invoke, tool(service, ctx, runner), asynchronous)
|
|
shutdown = None
|
|
try:
|
|
assert submitting.wait(2)
|
|
shutdown = callers.submit(close)
|
|
assert attempted.wait(2)
|
|
submit_allowed.set()
|
|
assert worker_entered.wait(2)
|
|
assert closing.wait(2)
|
|
assert_cancelled(call.result(timeout=2))
|
|
assert (runner._active, runner._admitted) == (1, 1)
|
|
assert not shutdown.done()
|
|
work_allowed.set()
|
|
shutdown.result(timeout=2)
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
finally:
|
|
ctx.cancelled.set()
|
|
submit_allowed.set()
|
|
work_allowed.set()
|
|
call.result(timeout=3)
|
|
if shutdown:
|
|
shutdown.result(timeout=3)
|
|
|
|
|
|
@pytest.mark.parametrize("closure_first", [False, True])
|
|
def test_close_racing_worker_completion_and_callback(
|
|
closure_first, runner, authority, monkeypatch):
|
|
computed, finish, callback_entered, release_callback = (Event() for _ in range(4))
|
|
closing = shutdown_barrier(monkeypatch, runner)
|
|
original_work, original_release = runner._work, runner._release
|
|
releases = []
|
|
def work(*args):
|
|
result = original_work(*args)
|
|
computed.set()
|
|
assert finish.wait(5)
|
|
return result
|
|
def callback(*, active=False):
|
|
if active:
|
|
callback_entered.set()
|
|
assert release_callback.wait(5)
|
|
releases.append(active)
|
|
original_release(active=active)
|
|
monkeypatch.setattr(runner, "_work", work)
|
|
monkeypatch.setattr(runner, "_release", callback)
|
|
service = SimpleNamespace(engine=None, search=lambda *_: dict(status="ok", sources=[]))
|
|
ctx = context(10)
|
|
with ThreadPoolExecutor(max_workers=2) as callers:
|
|
call = callers.submit(invoke, tool(service, ctx, runner), False)
|
|
shutdown = None
|
|
try:
|
|
assert computed.wait(2)
|
|
if closure_first:
|
|
shutdown = callers.submit(runner.close)
|
|
assert closing.wait(2)
|
|
assert_cancelled(call.result(timeout=2))
|
|
finish.set()
|
|
else:
|
|
finish.set()
|
|
assert callback_entered.wait(2)
|
|
assert call.result(timeout=2)["status"] == "ok"
|
|
shutdown = callers.submit(runner.close)
|
|
assert closing.wait(2)
|
|
assert callback_entered.wait(2)
|
|
assert (runner._active, runner._admitted) == (1, 1)
|
|
assert not shutdown.done()
|
|
release_callback.set()
|
|
shutdown.result(timeout=2)
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
assert releases == [True]
|
|
runner.close()
|
|
finally:
|
|
ctx.cancelled.set()
|
|
finish.set()
|
|
release_callback.set()
|
|
call.result(timeout=3)
|
|
if shutdown:
|
|
shutdown.result(timeout=3)
|
|
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
def test_close_waits_for_queued_release_after_worker_has_finished(
|
|
asynchronous, runner, authority, monkeypatch):
|
|
started, release_work, queued, releasing_queue = (Event() for _ in range(4))
|
|
allow_queue_release, worker_released = Event(), Event()
|
|
closing = shutdown_barrier(monkeypatch, runner)
|
|
original_submit, original_release = runner._submit, runner._release
|
|
releases = []
|
|
def submit(*args):
|
|
future = original_submit(*args)
|
|
if future is None:
|
|
queued.set()
|
|
return future
|
|
def release(*, active=False):
|
|
if not active:
|
|
releasing_queue.set()
|
|
assert allow_queue_release.wait(5)
|
|
releases.append(active)
|
|
original_release(active=active)
|
|
if active:
|
|
worker_released.set()
|
|
monkeypatch.setattr(runner, "_submit", submit)
|
|
monkeypatch.setattr(runner, "_release", release)
|
|
def search(*_):
|
|
started.set()
|
|
assert release_work.wait(5)
|
|
return dict(status="ok", sources=[])
|
|
service = SimpleNamespace(engine=None, search=search)
|
|
running_ctx, queued_ctx = context(10), context(10)
|
|
with ThreadPoolExecutor(max_workers=3) as callers:
|
|
first = callers.submit(invoke, tool(service, running_ctx, runner), asynchronous)
|
|
second = shutdown = None
|
|
try:
|
|
assert started.wait(2)
|
|
second = callers.submit(invoke, tool(service, queued_ctx, runner), asynchronous)
|
|
assert queued.wait(2)
|
|
shutdown = callers.submit(runner.close)
|
|
assert closing.wait(2)
|
|
assert releasing_queue.wait(2)
|
|
release_work.set()
|
|
assert worker_released.wait(2)
|
|
assert (runner._active, runner._admitted) == (0, 1)
|
|
assert not shutdown.done()
|
|
allow_queue_release.set()
|
|
assert_cancelled(second.result(timeout=2))
|
|
assert_cancelled(first.result(timeout=2))
|
|
shutdown.result(timeout=2)
|
|
assert (runner._active, runner._admitted) == (0, 0)
|
|
assert sorted(releases) == [False, True]
|
|
finally:
|
|
running_ctx.cancelled.set()
|
|
queued_ctx.cancelled.set()
|
|
release_work.set()
|
|
allow_queue_release.set()
|
|
for future in (first, second, shutdown):
|
|
if future:
|
|
future.result(timeout=3)
|