|
| 1 | +"""API-facing query layer (plan v2.4 Phase 7): request/response schemas and |
| 2 | +the ONE shared query orchestration used by both the ``/query`` endpoint and |
| 3 | +the CLI. |
| 4 | +
|
| 5 | +Design constraints honored here: |
| 6 | +
|
| 7 | +- **No second pipeline.** :func:`run_query` composes the existing Phase 5 |
| 8 | + ``HybridRetriever`` and the Phase 6 ``answer_query`` orchestration - the |
| 9 | + API and CLI are surfaces over the same canonical ``AnswerResponse``; |
| 10 | + neither surface re-implements retrieval, abstention, or citation logic. |
| 11 | +- **No model, no socket (I3).** The retriever is constructed lexical-only |
| 12 | + (``embedder=None, store=None``): FTS5 search over SQLite. Dense retrieval |
| 13 | + requires the MiniLM embedder and vector store, which stay gated behind |
| 14 | + the BG-1a/D3 verdict - the API never loads a model or opens a network |
| 15 | + connection, asserted by the egress suite. ``sentence_transformers`` and |
| 16 | + ``qdrant_client`` are never imported by this module. |
| 17 | +- **Bounded input (I7).** ``query`` is a required string (schema |
| 18 | + ``min_length=1``), additionally bounded by the configured |
| 19 | + ``retrieval_query_max_chars`` cap, and the request BODY size is bounded |
| 20 | + before parsing by the content-length guard in ``main.py``. Caps may only |
| 21 | + be tightened by configuration, never raised by the API. |
| 22 | +- **Safe errors (I6).** Errors are a fixed envelope |
| 23 | + ``{"error": {"category", "detail"}}`` with category-specific, constant |
| 24 | + detail strings. Raw prompts, retrieved content, filesystem paths, |
| 25 | + exception messages, and tracebacks NEVER appear in an error body - |
| 26 | + unexpected failures log the exception CLASS name only. |
| 27 | +- **Truthful outcomes.** Every completed query returns HTTP 200 with the |
| 28 | + canonical response, including retrieval-only and abstention outcomes: a |
| 29 | + ``UNAVAILABLE`` generation result is a valid truthful result, never an |
| 30 | + HTTP 500 (Z11/section 5.4). Only rejected input (4xx) and operational |
| 31 | + storage/internal failures (5xx) are errors. |
| 32 | +- **Tracing at the boundary (section 4.2).** Each completed query writes |
| 33 | + one trace via :mod:`rag_platform.tracing` on the same SQLite database. |
| 34 | + Trace persistence is best-effort: a trace failure is logged (class name |
| 35 | + only) and never blocks, alters, or fabricates the response. |
| 36 | +
|
| 37 | +Known Phase 7 boundaries (documented, not silently expanded): no |
| 38 | +authentication (M2), no cache (M4), no ledger (M3), lexical-only |
| 39 | +retrieval at the API (dense awaits BG-1a/D3), and rejected requests are |
| 40 | +not traced (full trace completeness belongs to the Phase 8 recorder). |
| 41 | +""" |
| 42 | + |
| 43 | +from __future__ import annotations |
| 44 | + |
| 45 | +import dataclasses |
| 46 | +import logging |
| 47 | +import sqlite3 |
| 48 | +import time |
| 49 | +from dataclasses import dataclass |
| 50 | +from pathlib import Path |
| 51 | +from secrets import token_hex |
| 52 | +from typing import Literal |
| 53 | + |
| 54 | +from pydantic import BaseModel, ConfigDict, Field |
| 55 | + |
| 56 | +from rag_platform.config import Settings |
| 57 | +from rag_platform.db import StorageError, initialize, open_db |
| 58 | +from rag_platform.generation import AnswerResponse, answer_query |
| 59 | +from rag_platform.observability import Observer, StageEvent |
| 60 | +from rag_platform.retrieval import HybridRetriever, QueryValidationError |
| 61 | +from rag_platform.tracing import record_query_trace |
| 62 | + |
| 63 | +logger = logging.getLogger("rag_platform") |
| 64 | + |
| 65 | +#: Hard bound on the raw request body for POST /query (I7). The query |
| 66 | +#: itself is capped much lower (``retrieval_query_max_chars`` <= 2000); |
| 67 | +#: this bound rejects oversized/absurd bodies BEFORE pydantic parses them. |
| 68 | +MAX_QUERY_BODY_BYTES = 16 * 1024 |
| 69 | + |
| 70 | + |
| 71 | +def default_db_path(settings: Settings) -> Path: |
| 72 | + """Canonical application database location (under ``data_dir``, on D:). |
| 73 | +
|
| 74 | + Containment is re-enforced by :func:`~rag_platform.db.sqlite.open_db` |
| 75 | + at open time (Z9). |
| 76 | + """ |
| 77 | + return settings.data_dir / "sqlite" / "rag.db" |
| 78 | + |
| 79 | + |
| 80 | +class ApiError(Exception): |
| 81 | + """A mapped, client-safe API failure: fixed envelope, no internals.""" |
| 82 | + |
| 83 | + def __init__(self, status_code: int, category: str, detail: str) -> None: |
| 84 | + super().__init__(category) |
| 85 | + self.status_code = status_code |
| 86 | + self.category = category |
| 87 | + self.detail = detail |
| 88 | + |
| 89 | + def as_body(self) -> dict[str, dict[str, str]]: |
| 90 | + return {"error": {"category": self.category, "detail": self.detail}} |
| 91 | + |
| 92 | + |
| 93 | +def translate_query_error(exc: Exception) -> ApiError: |
| 94 | + """Map a pipeline exception to a safe envelope - never echo messages.""" |
| 95 | + if isinstance(exc, QueryValidationError): |
| 96 | + return ApiError( |
| 97 | + 422, |
| 98 | + "invalid_request", |
| 99 | + "query is invalid for the configured retrieval bounds", |
| 100 | + ) |
| 101 | + if isinstance(exc, (StorageError, sqlite3.Error)): |
| 102 | + logger.warning("storage failure during query (class=%s)", type(exc).__name__) |
| 103 | + return ApiError( |
| 104 | + 503, |
| 105 | + "storage_unavailable", |
| 106 | + "storage is unavailable; no result was produced", |
| 107 | + ) |
| 108 | + logger.warning("unexpected query failure (class=%s)", type(exc).__name__) |
| 109 | + return ApiError(500, "internal_error", "unexpected internal error") |
| 110 | + |
| 111 | + |
| 112 | +# --- request schema ------------------------------------------------------- |
| 113 | + |
| 114 | + |
| 115 | +class QueryRequest(BaseModel): |
| 116 | + """POST /query body: one required, bounded query string. |
| 117 | +
|
| 118 | + ``extra="forbid"`` makes unrecognized fields a predictable 422 instead |
| 119 | + of a silent ignore - the request means exactly what it says. |
| 120 | + """ |
| 121 | + |
| 122 | + model_config = ConfigDict(extra="forbid") |
| 123 | + |
| 124 | + query: str = Field(min_length=1) |
| 125 | + |
| 126 | + |
| 127 | +# --- response schema (explicit projection of the canonical AnswerResponse) - |
| 128 | + |
| 129 | + |
| 130 | +class PassageModel(BaseModel): |
| 131 | + """One retrieved passage: citation-grade provenance, relative paths.""" |
| 132 | + |
| 133 | + model_config = ConfigDict(extra="forbid") |
| 134 | + |
| 135 | + chunk_id: str |
| 136 | + doc_id: str |
| 137 | + ordinal: int |
| 138 | + source_path: str # project-relative POSIX (never absolute, I16) |
| 139 | + content: str |
| 140 | + char_start: int |
| 141 | + char_end: int |
| 142 | + rank: int |
| 143 | + fused_score: float |
| 144 | + dense_cosine_similarity: float | None |
| 145 | + lexical_bm25: float | None |
| 146 | + injection_quarantined: bool |
| 147 | + injection_finding_count: int |
| 148 | + |
| 149 | + |
| 150 | +class RetrievalModel(BaseModel): |
| 151 | + """Retrieval report metadata plus its results (the canonical shape).""" |
| 152 | + |
| 153 | + model_config = ConfigDict(extra="forbid") |
| 154 | + |
| 155 | + mode: Literal["hybrid", "lexical_only"] |
| 156 | + lexical_only_reason: str | None |
| 157 | + outcome: Literal["ok", "no_candidates", "insufficient_evidence"] |
| 158 | + top_k: int |
| 159 | + lexical_hits: int |
| 160 | + dense_hits: int |
| 161 | + fused_candidates: int |
| 162 | + below_floor_excluded: int |
| 163 | + unhydrated_skipped: int |
| 164 | + post_verify_dropped: int |
| 165 | + score_floor: float | None |
| 166 | + results: list[PassageModel] |
| 167 | + |
| 168 | + |
| 169 | +class GenerationModel(BaseModel): |
| 170 | + """Generation result: provider/model labels, outcome, typed category.""" |
| 171 | + |
| 172 | + model_config = ConfigDict(extra="forbid") |
| 173 | + |
| 174 | + provider: str | None |
| 175 | + model: str | None |
| 176 | + text: str | None |
| 177 | + outcome: Literal["answered", "abstained", "unavailable"] |
| 178 | + failure_category: str | None |
| 179 | + latency_s: float |
| 180 | + attempts: int |
| 181 | + |
| 182 | + |
| 183 | +class AbstentionModel(BaseModel): |
| 184 | + """Abstention as a first-class response object (never an error).""" |
| 185 | + |
| 186 | + model_config = ConfigDict(extra="forbid") |
| 187 | + |
| 188 | + reason: str |
| 189 | + detail: str |
| 190 | + |
| 191 | + |
| 192 | +class CitationModel(BaseModel): |
| 193 | + """One validated citation resolved from served evidence.""" |
| 194 | + |
| 195 | + model_config = ConfigDict(extra="forbid") |
| 196 | + |
| 197 | + index: int |
| 198 | + chunk_id: str |
| 199 | + doc_id: str |
| 200 | + char_start: int |
| 201 | + char_end: int |
| 202 | + |
| 203 | + |
| 204 | +class QueryResponse(BaseModel): |
| 205 | + """The canonical Phase 6 response shape on the wire, plus the request |
| 206 | + correlation ID (section 4.2).""" |
| 207 | + |
| 208 | + model_config = ConfigDict(extra="forbid") |
| 209 | + |
| 210 | + request_id: str |
| 211 | + retrieval: RetrievalModel |
| 212 | + passages: list[PassageModel] |
| 213 | + generation: GenerationModel |
| 214 | + abstention: AbstentionModel | None |
| 215 | + citations: list[CitationModel] |
| 216 | + |
| 217 | + @classmethod |
| 218 | + def from_run(cls, run: "QueryRun") -> "QueryResponse": |
| 219 | + """Project the canonical dataclass response into the wire schema. |
| 220 | +
|
| 221 | + Field-for-field: every ``AnswerResponse``/``RetrievalReport``/ |
| 222 | + ``RetrievedChunk`` field appears with the same name and value |
| 223 | + (enums serialized by value) - the API never invents, drops, or |
| 224 | + renames contract data; ``request_id`` is the one additive field. |
| 225 | + """ |
| 226 | + response = run.response |
| 227 | + return cls( |
| 228 | + request_id=run.request_id, |
| 229 | + retrieval=RetrievalModel( |
| 230 | + mode=response.retrieval.mode, |
| 231 | + lexical_only_reason=response.retrieval.lexical_only_reason, |
| 232 | + outcome=response.retrieval.outcome, |
| 233 | + top_k=response.retrieval.top_k, |
| 234 | + lexical_hits=response.retrieval.lexical_hits, |
| 235 | + dense_hits=response.retrieval.dense_hits, |
| 236 | + fused_candidates=response.retrieval.fused_candidates, |
| 237 | + below_floor_excluded=response.retrieval.below_floor_excluded, |
| 238 | + unhydrated_skipped=response.retrieval.unhydrated_skipped, |
| 239 | + post_verify_dropped=response.retrieval.post_verify_dropped, |
| 240 | + score_floor=response.retrieval.score_floor, |
| 241 | + results=[ |
| 242 | + PassageModel(**dataclasses.asdict(chunk)) |
| 243 | + for chunk in response.retrieval.results |
| 244 | + ], |
| 245 | + ), |
| 246 | + passages=[ |
| 247 | + PassageModel(**dataclasses.asdict(chunk)) for chunk in response.passages |
| 248 | + ], |
| 249 | + generation=GenerationModel( |
| 250 | + provider=response.generation.provider, |
| 251 | + model=response.generation.model, |
| 252 | + text=response.generation.text, |
| 253 | + outcome=response.generation.outcome.value, |
| 254 | + failure_category=( |
| 255 | + response.generation.failure_category.value |
| 256 | + if response.generation.failure_category |
| 257 | + else None |
| 258 | + ), |
| 259 | + latency_s=response.generation.latency_s, |
| 260 | + attempts=response.generation.attempts, |
| 261 | + ), |
| 262 | + abstention=( |
| 263 | + AbstentionModel( |
| 264 | + reason=response.abstention.reason.value, |
| 265 | + detail=response.abstention.detail, |
| 266 | + ) |
| 267 | + if response.abstention is not None |
| 268 | + else None |
| 269 | + ), |
| 270 | + citations=[ |
| 271 | + CitationModel( |
| 272 | + index=citation.index, |
| 273 | + chunk_id=citation.chunk_id, |
| 274 | + doc_id=citation.doc_id, |
| 275 | + char_start=citation.char_start, |
| 276 | + char_end=citation.char_end, |
| 277 | + ) |
| 278 | + for citation in response.citations |
| 279 | + ], |
| 280 | + ) |
| 281 | + |
| 282 | + |
| 283 | +@dataclass(frozen=True) |
| 284 | +class QueryRun: |
| 285 | + """One completed query: the canonical response plus correlation data.""" |
| 286 | + |
| 287 | + response: AnswerResponse |
| 288 | + request_id: str |
| 289 | + total_ms: float |
| 290 | + |
| 291 | + |
| 292 | +def run_query( |
| 293 | + settings: Settings, |
| 294 | + query: str, |
| 295 | + *, |
| 296 | + db_path: Path, |
| 297 | + request_id: str | None = None, |
| 298 | + observer: Observer | None = None, |
| 299 | +) -> QueryRun: |
| 300 | + """Execute one bounded query end to end - the single orchestration |
| 301 | + shared by the API endpoint and the CLI. |
| 302 | +
|
| 303 | + Opens the contained SQLite database (schema initialized idempotently if |
| 304 | + this is its first use - migrations are the trusted Phase 2/4 registry), |
| 305 | + retrieves (lexical-only), runs the Phase 6 generation orchestration, |
| 306 | + writes the best-effort trace on the same database, and closes the |
| 307 | + connection before returning. Raises the typed retrieval/storage |
| 308 | + exceptions untranslated; surfaces map them to safe envelopes/exit codes. |
| 309 | +
|
| 310 | + *observer* (Phase 8, optional): receives the same stage events that |
| 311 | + feed the trace recorder. With the default ``None`` the trace is |
| 312 | + byte-identical to Phase 7 (retrieval timing NULL, three stages). With |
| 313 | + an observer attached (the eval harness), the measured ``retrieval`` |
| 314 | + timing and one optional ``context_build`` row are recorded in |
| 315 | + ``trace_stages`` and forwarded to the caller. Observer failures are |
| 316 | + contained: the response and the trace are produced regardless. |
| 317 | + """ |
| 318 | + started = time.perf_counter() |
| 319 | + correlation_id = request_id or token_hex(8) # server-derived (I2) |
| 320 | + stage_events: list[StageEvent] = [] |
| 321 | + |
| 322 | + def _collect_and_forward(event: StageEvent) -> None: |
| 323 | + stage_events.append(event) |
| 324 | + if observer is not None: |
| 325 | + observer(event) |
| 326 | + |
| 327 | + conn = open_db(db_path) |
| 328 | + try: |
| 329 | + initialize(conn) |
| 330 | + retriever = HybridRetriever(conn, settings=settings, embedder=None, store=None) |
| 331 | + response = answer_query( |
| 332 | + settings, |
| 333 | + retriever, |
| 334 | + query, |
| 335 | + observer=_collect_and_forward if observer is not None else None, |
| 336 | + ) |
| 337 | + total_ms = (time.perf_counter() - started) * 1000.0 |
| 338 | + try: |
| 339 | + record_query_trace( |
| 340 | + conn, |
| 341 | + request_id=correlation_id, |
| 342 | + query=query, |
| 343 | + response=response, |
| 344 | + total_ms=total_ms, |
| 345 | + stage_events=stage_events, |
| 346 | + ) |
| 347 | + except Exception as exc: # trace persistence is best-effort by policy |
| 348 | + logger.warning( |
| 349 | + "trace write failed (class=%s); response unaffected", |
| 350 | + type(exc).__name__, |
| 351 | + ) |
| 352 | + return QueryRun(response=response, request_id=correlation_id, total_ms=total_ms) |
| 353 | + finally: |
| 354 | + conn.close() |
0 commit comments