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60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""Step 9: the systems behind the web app, and what the app shows of their work.

    engine = Engine.load()                            # once per process (models, tables)
    for event in engine.events("c", question, day):   # plain dicts, in order
        ...                                           # api.py sends each one to the browser

Plain Python, no FastAPI: api.py only carries these events over HTTP, so tests drive
the real System C graph through events() with fake clients. The systems are the frozen
ones the held-out test measured (same prompts, models, knobs); only their LLM differs:
an in-memory cache (visitors' questions never reach disk), a shorter timeout and fewer
retries, so a visitor never waits the evals' worst case of ~5.5 min per call.

Events (each a dict with "type"):
- start:    system, day, the steps to expect
- step:     one System C graph node finished: its name, wall time, what it found
- evidence: the passages the answer model reads (C: before the answer call; A/B: after)
- answer:   the answer, citations (each checked by Step 8's checker and located in its
            section for highlighting), usage, cost, latency
- error:    kind + a message fit for a visitor (details go to the server log)
"""

import logging
import threading
import time
from collections import OrderedDict
from collections.abc import Callable, Iterator, Sequence
from datetime import date

import pandas as pd

from coveragecheck import config
from coveragecheck.agent.schemas import AnswerFailed, Citation, Response
from coveragecheck.llm import LLM, LLMError, Usage
from coveragecheck.retrieve import naive, structured
from coveragecheck.text import match_map
from coveragecheck.verify.citations import Checker, CitationCheck, Located, locate
from coveragecheck.web.followup import HistoryTurn, standalone

log = logging.getLogger(__name__)

NOT_ADVICE = (
    "Answers come only from public FSRA forms and Ontario laws, and are not coverage "
    "advice: read the cited text before relying on it."
)
# What the progress view expects; C's research + judge_new run only when the judge
# finds a fact no passage states. A and B are one call each: nothing to report midway.
STEPS = {
    "a": ["search", "answer"],
    "b": ["search", "rerank", "expand", "answer"],
    "c": ["retrieve", "judge", "research", "judge_new", "select", "answer", "verify"],
}
FAILURES = {  # llm.FAILURE_KINDS -> what a visitor reads
    "api": "The language model could not be reached. Please try again in a minute.",
    "refusal": "The language model declined to answer this question.",
    "stopped": "The language model stopped before finishing its answer.",
    "truncated": "The answer was too long and was cut off.",
    "invalid": "The language model's reply did not have the expected form, twice.",
}
SEARCH_FAILED = "Retrieval failed. Please try again."


class MemoryCache:
    """llm.DiskCache's interface (get/put) in memory, least recently used dropped first.
    Visitors' questions are never written to disk (5b handoff), and a repeated question
    (a demo example clicked twice) is answered from memory at no cost."""

    def __init__(self, entries: int):
        self.entries, self.items, self.lock = entries, OrderedDict(), threading.Lock()

    def get(self, key: str) -> dict | None:
        with self.lock:
            record = self.items.get(key)
            if record is not None:
                self.items.move_to_end(key)
            return record

    def put(self, key: str, record: dict) -> bool:
        with self.lock:
            self.items[key] = record
            self.items.move_to_end(key)
            while len(self.items) > self.entries:
                self.items.popitem(last=False)
        return True


def app_llm() -> LLM:
    """The answer model as the evals use it (model, effort, max tokens, reasks), but with
    the app's cache, timeout and retries (config WEB_*)."""
    import anthropic

    model = config.llm_model()  # also loads ANTHROPIC_API_KEY from .env
    return LLM(
        anthropic.Anthropic(max_retries=0, timeout=config.WEB_LLM_TIMEOUT_S),
        model,
        MemoryCache(config.WEB_CACHE_ENTRIES),
        effort=config.LLM_EFFORT,
        max_tokens=config.LLM_MAX_TOKENS,
        max_reasks=config.LLM_MAX_REASKS,
        api_retries=config.WEB_LLM_API_RETRIES,
        retry_base_s=config.LLM_RETRY_BASE_S,
        retry_max_s=config.LLM_RETRY_MAX_S,
    )


def serialised[F: Callable](fn: F) -> F:
    """fn behind a lock: one call at a time. The app answers questions in threads; the
    embedder's first load isn't thread-safe (3b) and B's cross-encoder must be
    serialised (6b handoff). A query costs ~10 ms to embed, so the lock is cheap."""
    lock = threading.Lock()

    def call(*args, **kwargs):
        with lock:
            return fn(*args, **kwargs)

    return call  # type: ignore[return-value]


def missing(value) -> bool:
    """None or a pandas NaN (an int column with None reads back as float NaN)."""
    return value is None or (isinstance(value, float) and pd.isna(value))


def page_label(start, end) -> str | None:
    """'PDF page 7' / 'PDF pages 7-8' (Docling's PDF page indexes: OAP 1 prints its
    page numbers 7 lower, so the label says "PDF page"); None for laws (no pages)."""
    if missing(start):
        return None
    start, end = int(start), int(start if missing(end) else end)
    return f"PDF page {start}" if start == end else f"PDF pages {start}-{end}"


def section_meta(row) -> dict:
    """What the app shows about a cited section: where it is and which version."""
    clean = {k: (None if missing(v) else v) for k, v in row._asdict().items()}
    keep = ["source_id", "doc_id", "form_id", "title", "version", "effective_from"]
    keep += ["effective_to", "heading_path", "url"]
    return {k: clean.get(k) for k in keep} | {
        "pages": page_label(clean.get("page_start"), clean.get("page_end"))
    }


def verdict(check: CitationCheck) -> str:
    """The checker's verdict in one word for the app. "exact": word for word in the
    cited section and in the passages shown (C's verify standard). "not_shown": real
    text, but not from a passage the model was shown. "approximate": close but not word
    for word. "not_found": the checker could not ground it (or a guard failed)."""
    if not check.grounded:
        return "not_found"
    if check.in_shown is False:
        return "not_shown"
    return "exact" if check.exact else "approximate"


def widen(raw: str, low: int, high: int) -> tuple[int, int]:
    """A window widened to whole words (never starts or ends inside a word)."""
    while 0 < low and not raw[low - 1].isspace():
        low -= 1
    while high < len(raw) and not raw[high].isspace():
        high += 1
    return low, high


def excerpt(raw: str, found: Located | None, width: int) -> dict:
    """What to show of a section around a located quote: one part per highlighted span,
    `width` characters on each side, widened to whole words; parts that overlap are
    merged, so an ordinary quote is one part and an elision across a long law ("X ...
    Y", far apart) is two, with a gap between them (9a audit: one window from the first
    span to the last shipped all 185k characters of SABS). Spans are relative to their
    part. Not located: the start of the section, no highlight. `tier` is how locate
    placed the quote; whether the citation PASSES is the citation's verdict, which the
    app must show (an exact highlight can carry a failing verdict: a quote under 30
    characters)."""
    if found is None:  # the start of the section: twice the width
        windows = [(*widen(raw, 0, min(len(raw), 2 * width)), [])]
    else:
        windows = []
        for s, e in found.spans:  # in text order (locate finds fragments in order)
            low, high = widen(raw, max(0, s - width), min(len(raw), e + width))
            if windows and low <= windows[-1][1]:  # overlaps the previous part: merge
                first, last, spans = windows[-1]
                windows[-1] = (first, max(high, last), [*spans, (s, e)])
            else:
                windows.append((low, high, [(s, e)]))
    return {
        "parts": [
            {"text": raw[low:high], "spans": [[s - low, e - low] for s, e in spans]}
            for low, high, spans in windows
        ],
        "cut_start": windows[0][0] > 0,
        "cut_end": windows[-1][1] < len(raw),
        "tier": found.tier if found else None,
    }


def step_event(node: str, part: dict | None) -> dict:
    """A System C graph node's update (LangGraph stream_mode="updates") as a step event:
    its wall time and the part of its trace a visitor can follow (the facts the judge
    looked for and whether a passage states each, the second search's queries, what
    was kept), never raw grades or rows."""
    part = part or {}
    trace = part.get("trace", {})
    detail: dict = {}
    if node == "retrieve":
        detail = {"candidates": len(trace.get("candidates", []))}
    elif node in ("judge", "judge_new") and node in trace:
        reading = trace[node]
        detail = {
            "requirements": [
                {"need": r["need"], "found": bool(r["stated_by"])} for r in reading["requirements"]
            ],
            "graded": len(reading["grades"]),
            "sufficient": reading["sufficient"],
        }
    elif node == "research" and "research" in trace:
        research = trace["research"]
        detail = {"queries": research["queries"], "new_candidates": len(research["candidates"])}
    elif node == "select":
        detail = {
            "kept": len(trace.get("kept", [])),
            "expansions": len(trace.get("expansions", [])),
            "fallback": trace.get("fallback", False),
            "flagged": trace.get("flagged", []),
        }
    elif node == "verify" and "response" in part:
        detail = dict(part["response"].trace.get("verify", {}))
    return {"type": "step", "name": node, "ms": part.get("node_ms", {}).get(node), "detail": detail}


def usage_of(response: Response, extra: Usage | None = None) -> dict:
    """Tokens, calls and the model cost of this answer at Haiku's prices (config), as
    it cost when first produced (llm.Usage replays a cached reply's ORIGINAL tokens and
    calls, a reask included). cache_hits counts replies replayed from the cache (one per
    reply, however many calls it took), so "cached" = at least one was: 9b smoke found
    that comparing it with llm_calls called a fully cached C answer (2 replies, one with
    a reask: 3 calls) not cached. A and B make one reply each: cached means all of it.
    extra: calls made around the system (a follow-up's rewrite), added in."""
    extra = extra or Usage()  # never a shared default: Usage is mutable
    tokens_in = response.tokens_in + extra.tokens_in
    tokens_out = response.tokens_out + extra.tokens_out
    cost = (
        tokens_in * config.LLM_PRICE_IN_PER_MTOK + tokens_out * config.LLM_PRICE_OUT_PER_MTOK
    ) / 1e6
    return {
        "tokens_in": tokens_in,
        "tokens_out": tokens_out,
        "llm_calls": response.llm_calls + extra.calls,
        "cost_usd": round(cost, 5),
        "cache_hits": response.cache_hits + extra.cache_hits,
        "cached": response.cache_hits + extra.cache_hits > 0,
    }


def timings(name: str, trace: dict, cached: bool = False) -> dict:
    """Where the time went, from the system's own trace (ms): C per graph node (wall
    time), B the cross-encoder and the answer call, A the answer call. A cached answer
    of A/B has no answer time: its trace's llm_ms is the time the call took when it was
    first made (9a audit: timings then summed to more than the latency); C's node
    times are always this run's wall time."""
    if name == "c":
        return dict(trace.get("node_ms", {}))
    out = {"answer": None if cached else trace.get("llm_ms")}
    if "rerank_ms" in trace:
        out["rerank"] = trace["rerank_ms"]
    return {k: round(v, 1) for k, v in out.items() if v is not None}


class Engine:
    """The three systems, the citation checker and the tables the app reads. Build once
    (load(): ~15 s, the models warmed); events() is safe to call from several threads
    (the graph is stateless per invoke, the models are serialised)."""

    def __init__(
        self,
        systems: dict,
        checker: Checker,
        sections: pd.DataFrame,
        chunks: pd.DataFrame,
        windows: pd.DataFrame,
        llm: LLM | None = None,
    ):
        self.systems, self.checker, self.llm = systems, checker, llm  # llm: follow-ups
        self.meta = {row.source_id: section_meta(row) for row in sections.itertuples(index=False)}
        self.chunks, self.windows = chunks, windows
        self.chunk_rows = {cid: i for i, cid in enumerate(chunks.chunk_id)}
        self.window_rows = {cid: i for i, cid in enumerate(windows.chunk_id)}
        self.maps: dict[str, tuple[str, list[int]]] = {}  # source_id -> match_map(raw)

    @classmethod
    def load(cls, llm: LLM | None = None) -> "Engine":
        """A, B and C as the registry builds them, sharing one embedder and one LLM (the
        app's, unless given: the examples export passes one that only replays the evals'
        disk cache), with the models warmed so no visitor pays for loading them."""
        from coveragecheck.agent.graph import AgentSystem, no_reranker
        from coveragecheck.index import dense
        from coveragecheck.index.store import load_table

        embedder, llm = serialised(dense.fastembed_embedder()), llm or app_llm()
        windows = load_table(config.INDEX_DIR / "naive_chunks.parquet")
        windows = windows.drop(columns=["covers_sources"])  # EVAL ONLY (as naive.build)
        index = dense.load(config.DENSE_A_DIR, list(windows.chunk_id), texts=list(windows.text))
        reranker = serialised(structured.fastembed_reranker())
        b_retriever = structured.StructuredRetriever.load(embedder, reranker)
        checker = Checker.load()
        systems = {
            "a": naive.NaiveSystem(windows, index, embedder, llm),
            "b": structured.StructuredSystem(b_retriever, llm),
            "c": AgentSystem(
                structured.StructuredRetriever.load(embedder, no_reranker), llm, checker
            ),
        }
        for system in systems.values():
            system.warm_up()
        sections = load_table(config.INDEX_DIR / "sections.parquet")
        return cls(systems, checker, sections, b_retriever.retriever.chunks, windows, llm)

    @property
    def model(self) -> str | None:
        return next(iter(self.systems.values())).settings.get("llm_model")

    # --- events ----------------------------------------------------------------------------

    def events(
        self, name: str, question: str, day: date, history: Sequence[HistoryTurn] = ()
    ) -> Iterator[dict]:
        """Everything the app shows for one question, as it happens. With history (a
        follow-up), the question is first rewritten into a standalone one (rewrite
        event) and the system answers that. Never raises: an LLM failure is an error
        event with its kind; any other failure (retrieval) is a generic one, logged with
        its traceback."""
        started = time.perf_counter()
        yield {"type": "start", "system": name, "day": day.isoformat(), "steps": STEPS[name]}
        extra = Usage()  # the rewrite's call, counted in the answer's usage
        try:
            if history:
                asked = question
                question, extra = standalone(self.llm, list(history), question)
                yield {
                    "type": "rewrite",
                    "question": question,
                    "changed": question != asked,
                    "ms": round(extra.llm_ms),
                }
            if name == "c":
                response = yield from self.graph_events(question, day)
            else:
                response = self.systems[name].answer(question, day)
                yield self.evidence(response.retrieved_chunk_ids)
        except (AnswerFailed, LLMError) as failure:  # LLMError: the rewrite call
            # the kind only: an "invalid" failure's text can echo the visitor's question
            log.warning("system %s failed: %s", name, failure.kind)
            yield {"type": "error", "kind": failure.kind, "message": FAILURES.get(failure.kind)}
            return
        except Exception:
            log.exception("system %s failed outside the LLM", name)
            yield {"type": "error", "kind": "retrieval", "message": SEARCH_FAILED}
            return
        latency = (time.perf_counter() - started) * 1000
        yield {"type": "answer", **self.answer_payload(name, response, day, latency, extra)}

    def graph_events(self, question: str, day: date):
        """Run C's graph node by node (stream_mode="updates": one {node: update} per
        node), yielding a step event for each and the evidence as soon as select has
        chosen it, before the answer call. Returns the Response (verify's update)."""
        from coveragecheck.agent.graph import start_state

        system, response = self.systems["c"], None
        for update in system.graph.stream(start_state(question, day), stream_mode="updates"):
            for node, part in update.items():
                yield step_event(node, part)
                if node == "select":
                    yield self.evidence(system.ids(part["trace"]["shown_rows"]))
                if node == "verify":
                    response = part["response"]
        if response is None:
            raise RuntimeError("System C's graph ended without a response")
        return response

    def evidence(self, chunk_ids: list[str]) -> dict:
        return {"type": "evidence", "passages": [self.passage(c) for c in chunk_ids]}

    def passage(self, chunk_id: str) -> dict:
        """A shown passage exactly as the answer model read it (the systems' own
        passages(): label = title + in-force dates), with its pages when it has some."""
        if chunk_id in self.chunk_rows:
            table, row = self.chunks, self.chunk_rows[chunk_id]
            shown = structured.passages(table, [row])[0]
        else:
            table, row = self.windows, self.window_rows[chunk_id]
            shown = naive.passages(table, [row])[0]
        r = table.iloc[row]
        return {
            "chunk_id": chunk_id,
            "source_id": shown.source_id,
            "label": shown.label,
            "text": shown.text,
            "pages": page_label(r.get("page_start"), r.get("page_end")),
        }

    # --- the answer ------------------------------------------------------------------------

    def answer_payload(
        self,
        name: str,
        response: Response,
        day: date,
        latency_ms: float,
        extra: Usage | None = None,
    ):
        a, shown = response.answer, response.retrieved_chunk_ids
        usage = usage_of(response, extra)
        return {
            "system": name,
            "day": day.isoformat(),
            "answer": a.answer,
            "abstain": a.abstain,
            "missing_info": list(a.missing_info),
            "confidence": a.confidence,
            "citations": [self.citation(n, c, shown) for n, c in enumerate(a.citations, 1)],
            "usage": usage,
            "latency_ms": round(latency_ms),
            "timings": timings(name, response.trace, response.cache_hits > 0),
            "flagged": list(response.trace.get("flagged", [])),
            "not_advice": NOT_ADVICE,
        }

    def citation(self, n: int, cited: Citation, shown: list[str]) -> dict:
        """One numbered citation: the checker's verdict (against the cited section and
        the passages shown), the section's version and pages, and an excerpt with the
        quote highlighted."""
        check = self.checker.check(cited, shown)
        raw = self.checker.raw.get(cited.source_id)
        found = None
        if raw is not None:
            if cited.source_id not in self.maps:
                self.maps[cited.source_id] = match_map(raw)
            found = locate(cited.quote, raw, self.maps[cited.source_id])
        return {
            "n": n,
            "source_id": cited.source_id,
            "quote": cited.quote,
            "verdict": verdict(check),
            "problems": list(check.problems),
            "section": self.meta.get(cited.source_id),
            "excerpt": None if raw is None else excerpt(raw, found, config.WEB_EXCERPT_CHARS),
        }