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.
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
"""Lazy LangChain boundary over the canonical search service."""
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
import math
|
||||
from threading import Condition, Event
|
||||
import time
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from app.modules.knowledge.service import (
|
||||
KnowledgeError, SearchInput, authority, sql_error, transaction,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ToolContext:
|
||||
"""Backend-owned execution, absolute monotonic deadline and cancellation."""
|
||||
execution: SearchExecution
|
||||
deadline: float
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
|
||||
def __post_init__(self):
|
||||
if not isinstance(self.execution, SearchExecution):
|
||||
raise ValueError("Trusted SearchExecution required")
|
||||
if type(self.deadline) not in (int, float) or not math.isfinite(self.deadline):
|
||||
raise ValueError("Finite monotonic deadline required")
|
||||
if not isinstance(self.cancelled, Event):
|
||||
raise ValueError("Cancellation event required")
|
||||
|
||||
|
||||
class SearchToolRunner:
|
||||
"""Share one runner across tools to enforce process-wide admission limits."""
|
||||
def __init__(self, *, running=4, waiting=8, timeout=75.0):
|
||||
if type(running) is not int or running < 1 or type(waiting) is not int or waiting < 0:
|
||||
raise ValueError("Positive running and nonnegative waiting limits required")
|
||||
if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError("Finite positive timeout required")
|
||||
self.running, self.waiting, self.timeout = running, waiting, timeout
|
||||
self._lock = Condition()
|
||||
self._admitted = self._active = 0
|
||||
self._closed = False
|
||||
self._pool = ThreadPoolExecutor(max_workers=running, thread_name_prefix="knowledge-search")
|
||||
|
||||
@staticmethod
|
||||
def error(ctx, code, message, retryable=False):
|
||||
return dict(status="error", sources=[], error=dict(
|
||||
code=code, message=message, request_id=ctx.execution.request_id,
|
||||
retryable=retryable))
|
||||
|
||||
def _stop(self, ctx, deadline, cancelled):
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled: runner closed")
|
||||
if ctx.cancelled.is_set() or cancelled.is_set():
|
||||
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled")
|
||||
if time.monotonic() >= deadline:
|
||||
return self.error(ctx, "SEARCH_TIMEOUT", "Knowledge retrieval timed out", True)
|
||||
|
||||
def _admit(self):
|
||||
with self._lock:
|
||||
if self._closed or self._admitted >= self.running + self.waiting:
|
||||
return False
|
||||
self._admitted += 1
|
||||
return True
|
||||
|
||||
def _release(self, *, active=False):
|
||||
with self._lock:
|
||||
self._admitted -= 1
|
||||
if active:
|
||||
self._active -= 1
|
||||
self._lock.notify_all()
|
||||
|
||||
def _submit(self, service, ctx, query, context, deadline, cancelled):
|
||||
with self._lock:
|
||||
if self._active >= self.running or self._closed:
|
||||
return None
|
||||
self._active += 1
|
||||
try:
|
||||
future = self._pool.submit(
|
||||
self._work, service, ctx, query, context, deadline, cancelled)
|
||||
except BaseException:
|
||||
self._active -= 1
|
||||
raise
|
||||
future.add_done_callback(lambda _: self._release(active=True))
|
||||
return future
|
||||
|
||||
def _work(self, service, ctx, query, context, deadline, cancelled):
|
||||
try:
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
return stopped
|
||||
# Persisted authority is captured outside model input, on a worker.
|
||||
with transaction(service.engine) as conn:
|
||||
current, settings = authority(conn, ctx.execution.user_id)
|
||||
if not ctx.execution.capture(current, settings["access_epoch"]):
|
||||
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
return stopped
|
||||
result = service.search(ctx.execution, query, context)
|
||||
if result["status"] != "error":
|
||||
# Recheck this delivery boundary after the service handoff.
|
||||
with transaction(service.engine) as conn:
|
||||
current, settings = authority(conn, ctx.execution.user_id)
|
||||
if not ctx.execution.matches(current, settings["access_epoch"]):
|
||||
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
|
||||
return self._stop(ctx, deadline, cancelled) or result
|
||||
except KnowledgeError as exc:
|
||||
code = "CONTEXT_REVOKED" if exc.code == "ACTOR_UNAVAILABLE" else exc.code
|
||||
return self.error(ctx, code, str(exc), exc.retryable)
|
||||
except SQLAlchemyError as exc:
|
||||
error = sql_error(exc)
|
||||
return self.error(ctx, error.code, str(error), error.retryable)
|
||||
except Exception:
|
||||
return self.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
|
||||
|
||||
def invoke(self, service, ctx, query, context=None):
|
||||
SearchInput(query=query, context=context)
|
||||
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
|
||||
cancelled, future = Event(), None
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
return stopped
|
||||
if not self._admit():
|
||||
return self._stop(ctx, deadline, cancelled) or self.error(
|
||||
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
|
||||
try:
|
||||
while True:
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
cancelled.set()
|
||||
return stopped
|
||||
if future is None:
|
||||
future = self._submit(service, ctx, query, context, deadline, cancelled)
|
||||
if future is not None and future.done():
|
||||
return self._stop(ctx, deadline, cancelled) or future.result()
|
||||
time.sleep(min(0.01, max(0, deadline - time.monotonic())))
|
||||
finally:
|
||||
if future is None:
|
||||
self._release()
|
||||
|
||||
async def ainvoke(self, service, ctx, query, context=None):
|
||||
SearchInput(query=query, context=context)
|
||||
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
|
||||
cancelled, future = Event(), None
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
return stopped
|
||||
if not self._admit():
|
||||
return self._stop(ctx, deadline, cancelled) or self.error(
|
||||
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
|
||||
try:
|
||||
while True:
|
||||
stopped = self._stop(ctx, deadline, cancelled)
|
||||
if stopped:
|
||||
cancelled.set()
|
||||
return stopped
|
||||
if future is None:
|
||||
future = self._submit(service, ctx, query, context, deadline, cancelled)
|
||||
if future is not None and future.done():
|
||||
return self._stop(ctx, deadline, cancelled) or future.result()
|
||||
await asyncio.sleep(min(0.01, max(0, deadline - time.monotonic())))
|
||||
except asyncio.CancelledError:
|
||||
cancelled.set()
|
||||
raise
|
||||
finally:
|
||||
if future is None:
|
||||
self._release()
|
||||
|
||||
def close(self):
|
||||
"""Permanently cancel callers and join work/admissions; safe to repeat.
|
||||
|
||||
Closure and submission linearize under the same condition lock. Only
|
||||
completion callbacks release submitted slots; queued callers release
|
||||
their own admissions. Call from a control thread, outside the event
|
||||
loop and this runner's worker pool, so callers can drain.
|
||||
"""
|
||||
with self._lock:
|
||||
self._closed = True
|
||||
self._pool.shutdown(wait=True)
|
||||
with self._lock:
|
||||
self._lock.wait_for(lambda: self._admitted == 0)
|
||||
|
||||
|
||||
def create_search_tool(service, context, runner):
|
||||
"""Build only on explicit opt-in; core imports do not require LangChain."""
|
||||
from langchain_core.tools import StructuredTool
|
||||
|
||||
trusted = context
|
||||
|
||||
def search_knowledge(query: str, context: str | None = None):
|
||||
return runner.invoke(service, trusted, query, context)
|
||||
|
||||
async def asearch_knowledge(query: str, context: str | None = None):
|
||||
return await runner.ainvoke(service, trusted, query, context)
|
||||
|
||||
return StructuredTool.from_function(
|
||||
func=search_knowledge, coroutine=asearch_knowledge,
|
||||
name="search_knowledge",
|
||||
description="Search authorized selected documents for evidence. Context is an untrusted retrieval hint.",
|
||||
args_schema=SearchInput,
|
||||
)
|
||||
Reference in New Issue
Block a user