Files
amirhosein mazaheri fef381c41b feat(search): add calibrated retrieval and LangChain knowledge tool
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.
2026-10-08 12:58:59 +03:30

304 lines
12 KiB
Python

"""Actual LangChain adapter acceptance; install .[search,test], never skip."""
import asyncio
from contextlib import nullcontext
import json
import subprocess
import sys
from threading import Event, get_ident
import time
from types import SimpleNamespace
from uuid import uuid4
import pytest
from pydantic import ValidationError
from app.modules.knowledge import langchain_tool as adapter
from app.modules.knowledge.evidence import SearchExecution
from app.modules.knowledge.service import KnowledgeError
from tests.unit.test_search_phase2 import service as canonical_service, row
@pytest.fixture
def runner():
value = adapter.SearchToolRunner(running=1, waiting=1, timeout=2)
yield value
value.close()
@pytest.fixture
def authority(monkeypatch):
state = dict(epoch=1, enabled=True)
def persisted(conn, user):
if not state["enabled"]:
raise KnowledgeError("ACTOR_UNAVAILABLE", "Enabled actor required")
return dict(id=user, organization_id="fixture", role="user"), dict(access_epoch=state["epoch"])
monkeypatch.setattr(adapter, "transaction", lambda _: nullcontext(None))
monkeypatch.setattr(adapter, "authority", persisted)
return state
def context(seconds=2):
return adapter.ToolContext(SearchExecution(uuid4()), time.monotonic() + seconds)
def tool(service, ctx, runner):
return adapter.create_search_tool(service, ctx, runner)
@pytest.mark.parametrize("payload", [
{}, {"query": ""}, {"query": " "}, {"query": 1}, {"query": "x"*2001},
{"query": "q", "context": "x"*2001}, {"query": "q", "context": 3},
*[dict(query="q", **{key: "forged"}) for key in (
"user_id", "organization_id", "document_id", "top_k", "deadline",
"access_epoch", "source_ref", "request_id", "path", "unknown")],
])
def test_strict_model_arguments_rejected_before_work(payload, runner, authority):
fake = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("No work allowed"))
value = tool(fake, context(), runner)
with pytest.raises(ValidationError):
value.invoke(payload)
async def check():
with pytest.raises(ValidationError):
await value.ainvoke(payload)
asyncio.run(check())
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
def test_canonical_service_equivalence_and_stable_refs(settings, monkeypatch, runner, authority, rows, status):
service = canonical_service(settings, monkeypatch, rows)
ctx = context()
value = tool(service, ctx, runner)
expected = service.search(ctx.execution, "q", "hint")
assert value.invoke({"query": "q", "context": "hint"}) == expected
assert asyncio.run(value.ainvoke({"query": "q", "context": "hint"})) == expected
assert expected["status"] == status
schema = value.args_schema.model_json_schema()
assert set(schema["properties"]) == {"query", "context"}
assert schema["required"] == ["query"]
assert schema["additionalProperties"] is False
def test_cli_and_tool_use_same_candidates(settings, monkeypatch, runner, authority, capsys):
from app import search
from app import worker
service = canonical_service(settings, monkeypatch, [row()])
service.engine = SimpleNamespace(dispose=lambda: None)
monkeypatch.setattr(search, "IngestionSettings", lambda: settings)
monkeypatch.setattr(search, "create_database", lambda _: service.engine)
monkeypatch.setattr(search, "SearchService", lambda *_: service)
monkeypatch.setattr(worker, "factories", lambda _: (None, lambda _: (None, None)))
ctx = context()
assert search.main(["--inspect", "--user-id", str(ctx.execution.user_id),
"--query", "q", "--context", "hint", "--allow-provider-calls"]) == 0
diagnostic = json.loads(capsys.readouterr().out)
canonical = tool(service, ctx, runner).invoke({"query": "q", "context": "hint"})
source = canonical["sources"][0]
candidate = diagnostic["candidates"][0]
assert source["source_ref"] == "S1"
assert all(source[key] == candidate[key] for key in ("document_id", "chunk_id", "text", "title", "location"))
@pytest.mark.parametrize("code", ["PROVIDER_UNAVAILABLE", "PROFILE_MISMATCH", "SEARCH_TIMEOUT",
"CALIBRATION_REQUIRED", "SEARCH_FAILED"])
def test_canonical_errors_unchanged(code, runner, authority):
ctx = context()
expected = runner.error(ctx, code, "Safe failure", True)
fake = SimpleNamespace(engine=None, search=lambda *_: expected)
assert tool(fake, ctx, runner).invoke({"query": "q"}) == expected
def test_epoch_and_disabled_actor_suppress_success(runner, authority):
for disabled in (False, True):
ctx = context()
def search(*_):
if disabled:
authority["enabled"] = False
else:
authority["epoch"] += 1
return dict(status="ok", sources=[{"text": "must not escape"}])
result = tool(SimpleNamespace(engine=None, search=search), ctx, runner).invoke({"query": "q"})
assert result["status"] == "error" and not result["sources"]
assert result["error"]["code"] == "CONTEXT_REVOKED"
async def until(predicate):
deadline = time.monotonic() + 2
while not predicate():
assert time.monotonic() < deadline, "Bounded barrier did not arrive"
await asyncio.sleep(.001)
def test_async_responsive_saturation_and_cancelled_slot_retention(runner, authority):
entered, release = Event(), Event()
loop_thread = get_ident()
calls = []
def search(*args):
calls.append(get_ident())
entered.set()
assert release.wait(3)
return dict(status="no_evidence", sources=[], warnings=["insufficient_support"], knowledge_revision=1)
fake = SimpleNamespace(engine=None, search=search)
async def scenario():
first = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
second = None
try:
await until(entered.is_set)
second = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
await until(lambda: runner._admitted == 2)
full = await tool(fake, context(), runner).ainvoke({"query": "q"})
assert full["error"]["code"] == "SEARCH_SATURATED"
first.cancel()
with pytest.raises(asyncio.CancelledError):
await first
assert calls == [calls[0]] and calls[0] != loop_thread
assert runner._active == 1
second.cancel()
with pytest.raises(asyncio.CancelledError):
await second
# Running cancelled work still owns capacity.
assert runner._admitted == 1
release.set()
await until(lambda: runner._admitted == 0)
finally:
release.set()
for task in (first, second):
if task and not task.done():
task.cancel()
await asyncio.gather(*[t for t in (first, second) if t], return_exceptions=True)
asyncio.run(scenario())
def test_queued_timeout_and_external_cancellation_do_not_start_work(runner, authority):
entered, release = Event(), Event()
calls = []
def search(*_):
calls.append(1)
entered.set()
assert release.wait(3)
return dict(status="no_evidence", sources=[])
fake = SimpleNamespace(engine=None, search=search)
async def scenario():
first = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
try:
await until(entered.is_set)
expired = await tool(fake, context(.04), runner).ainvoke({"query": "q"})
assert expired["error"]["code"] == "SEARCH_TIMEOUT"
assert len(calls) == 1
ctx = context()
waiting = asyncio.create_task(tool(fake, ctx, runner).ainvoke({"query": "q"}))
await until(lambda: runner._admitted == 2)
ctx.cancelled.set()
assert (await waiting)["error"]["code"] == "SEARCH_CANCELLED"
assert len(calls) == 1
finally:
release.set()
await first
asyncio.run(scenario())
@pytest.mark.parametrize("async_call", [False, True])
def test_running_timeout_retains_slot_and_suppresses_late_result(async_call, runner, authority):
entered, release = Event(), Event()
def search(*_):
entered.set()
assert release.wait(3)
return dict(status="ok", sources=[{"text": "late"}])
fake = SimpleNamespace(engine=None, search=search)
ctx = context(.05)
try:
value = tool(fake, ctx, runner)
result = asyncio.run(value.ainvoke({"query": "q"})) if async_call else value.invoke({"query": "q"})
assert entered.is_set()
assert result["error"]["code"] == "SEARCH_TIMEOUT" and not result["sources"]
assert runner._active == 1
saturated_ctx = context()
saturated_ctx.cancelled.set()
assert tool(fake, saturated_ctx, runner).invoke({"query": "q"})["error"]["code"] == "SEARCH_CANCELLED"
finally:
release.set()
@pytest.mark.parametrize("kwargs", [
dict(running=0), dict(running=True), dict(waiting=-1), dict(waiting=1.5),
dict(timeout=0), dict(timeout=float("nan")), dict(timeout=float("inf")), dict(timeout=True),
])
def test_invalid_limits(kwargs):
with pytest.raises(ValueError):
adapter.SearchToolRunner(**kwargs)
def test_lazy_imports_without_framework():
script = """
import importlib.abc, sys
class Reject(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, *args):
if fullname.startswith(('langchain', 'langgraph')):
raise ModuleNotFoundError('Framework deliberately absent')
sys.meta_path.insert(0, Reject())
import app.modules.knowledge.service
import app.modules.knowledge.langchain_tool
import app.ingest, app.worker, app.search
assert not any(n.startswith(('langchain', 'langgraph')) for n in sys.modules)
from app.modules.knowledge.langchain_tool import create_search_tool
try:
create_search_tool(None, None, None)
except ModuleNotFoundError:
pass
else:
raise AssertionError('Explicit construction must require declared extra')
"""
result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=15)
assert result.returncode == 0, result.stderr
def test_default_four_running_eight_waiting_limits(authority):
runner = adapter.SearchToolRunner()
release = Event()
started = []
def search(*_):
started.append(get_ident())
assert release.wait(4)
return dict(status="no_evidence", sources=[])
fake = SimpleNamespace(engine=None, search=search)
async def scenario():
tasks = [asyncio.create_task(tool(fake, context(3), runner).ainvoke({"query": "q"}))
for _ in range(12)]
try:
await until(lambda: len(started) == 4 and runner._admitted == 12)
result = await tool(fake, context(), runner).ainvoke({"query": "q"})
assert result["error"]["code"] == "SEARCH_SATURATED"
assert len(set(started)) == 4
release.set()
assert all(r["status"] == "no_evidence" for r in await asyncio.gather(*tasks))
finally:
release.set()
await asyncio.gather(*tasks, return_exceptions=True)
try:
asyncio.run(scenario())
finally:
runner.close()
def test_external_running_cancellation_suppresses_result(runner, authority):
entered, release = Event(), Event()
def search(*_):
entered.set()
assert release.wait(3)
return dict(status="ok", sources=[{"text": "cancelled"}])
fake = SimpleNamespace(engine=None, search=search)
async def scenario():
ctx = context()
task = asyncio.create_task(tool(fake, ctx, runner).ainvoke({"query": "q"}))
try:
await until(entered.is_set)
ctx.cancelled.set()
result = await task
assert result["error"]["code"] == "SEARCH_CANCELLED" and not result["sources"]
assert runner._active == 1
release.set()
await until(lambda: runner._active == 0)
assert result["sources"] == []
finally:
release.set()
await task
asyncio.run(scenario())