From 3f72a3930e7cc71202d957ba2c058f4961eac0c1 Mon Sep 17 00:00:00 2001 From: Muhammad Mehdi Date: Wed, 18 Nov 2026 11:09:59 +0500 Subject: [PATCH] chat system fix phase 1 --- backend/app/config.py | 25 ++ backend/app/corpus.py | 167 ++++++++-- backend/app/llm/provider.py | 15 +- backend/app/llm/signatures.py | 7 +- backend/app/observability/__init__.py | 0 backend/app/observability/langfuse_client.py | 98 ++++++ backend/app/pipeline/cards.py | 140 +++++++++ backend/app/pipeline/chat_judge.py | 120 ++++++++ backend/app/pipeline/context_router.py | 147 +++++++++ backend/app/pipeline/prefetch.py | 148 +++++++-- backend/app/pipeline/research.py | 284 +++++++++++++++-- backend/app/pipeline/trace.py | 170 ++++++++++- backend/app/pipeline/writer.py | 2 + backend/app/routers/notebooks.py | 123 ++++++-- backend/app/routers/sources.py | 8 + backend/app/services/jev.py | 23 +- backend/app/services/storage.py | 9 +- backend/app/worker.py | 26 ++ backend/requirements.txt | 2 + backend/scripts/build_post_cards.py | 67 ++++ backend/scripts/chat_eval.py | 54 +++- backend/tests/conftest.py | 14 + backend/tests/evals/test_chat_tool_use.py | 3 +- backend/tests/test_chat_observability.py | 272 +++++++++++++++++ backend/tests/test_chat_recall.py | 2 +- backend/tests/test_chat_retrieval.py | 302 +++++++++++++++++++ backend/tests/test_chat_speed.py | 2 +- backend/tests/test_chat_trace.py | 12 +- backend/tests/test_corpus.py | 39 ++- backend/tests/test_memory.py | 2 +- backend/tests/test_outbound_mcp.py | 2 +- 31 files changed, 2159 insertions(+), 126 deletions(-) create mode 100644 backend/app/observability/__init__.py create mode 100644 backend/app/observability/langfuse_client.py create mode 100644 backend/app/pipeline/cards.py create mode 100644 backend/app/pipeline/chat_judge.py create mode 100644 backend/app/pipeline/context_router.py create mode 100644 backend/scripts/build_post_cards.py create mode 100644 backend/tests/test_chat_observability.py create mode 100644 backend/tests/test_chat_retrieval.py diff --git a/backend/app/config.py b/backend/app/config.py index 824affb..5868b54 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -126,6 +126,10 @@ class Settings(BaseSettings): llm_max_concurrent: int = 6 # model calls in flight at once across all jobs: quizzes and flashcards run two at a time per job # GLM-5.x always reasons (it cannot be disabled); this sets how hard. low | high | max llm_reasoning_effort: str = "low" + # Seconds before a model request is given up (LiteLLM's own default is 600). Chat calls use the shorter ones. + llm_timeout_seconds: float = 300.0 + chat_llm_timeout_seconds: float = 90.0 # research agent and answer writer + chat_fast_timeout_seconds: float = 25.0 # triage, query expansion # Corpus: posts as markdown files. R2 is the source of truth; each process keeps a disk cache. corpus_cache_dir: str = ".corpus-cache" @@ -159,6 +163,27 @@ class Settings(BaseSettings): # then hold writers' text, so it is on only in development unless CHAT_CONTEXT_LOG=true. None follows ENV. chat_context_log: bool | None = None + # Langfuse tracing for the notebook chat (app/observability/langfuse.py): one trace per message with every stage, + # the outcome code, user ratings and judge scores. Empty keys = off. LANGFUSE_HOST: cloud or a self-hosted URL. + langfuse_public_key: str = "" + langfuse_secret_key: str = "" + langfuse_host: str = "" + # Send only sizes, never writers' text (questions, answers, passages), unless this is false. Turn it off only + # with a self-hosted Langfuse. + langfuse_mask_text: bool = True + # Share of archive answers scored by the LLM judge in the worker (relevance, faithfulness, false refusals). + chat_judge_sample_rate: float = 0.2 + + # Retrieval (docs/plan: post cards + long context). CHAT_ROUTER replaces the keyword prefetch / fast path with + # tiers: Tier A puts the whole notebook in the prompt when it fits CHAT_FULL_NOTEBOOK_TOKENS, Tier B picks posts + # with card + passage BM25 up to CHAT_EVIDENCE_TOKENS, Tier C is the research agent when neither is answered. + chat_router: bool = False + chat_full_notebook_tokens: int = 60_000 + chat_evidence_tokens: int = 30_000 + chat_query_expansion: bool = True + # Post cards: one fast-model call per post at ingest (summary, topics, names, synonyms, questions it answers). + post_cards_enabled: bool = True + # ElevenLabs (premade voices by default; a consented clone can replace host A) elevenlabs_api_key: str = "" elevenlabs_model: str = "eleven_multilingual_v2" diff --git a/backend/app/corpus.py b/backend/app/corpus.py index 21c1587..b1c1fc0 100644 --- a/backend/app/corpus.py +++ b/backend/app/corpus.py @@ -15,23 +15,59 @@ import hashlib import json +import logging import re import threading import time import unicodedata import uuid +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime from pathlib import Path, PurePosixPath +from sqlalchemy import text as sql + from app.config import settings +from app.db import engine +from app.services.storage import is_not_found from app.services.storage import storage as default_storage +log = logging.getLogger(__name__) + MANIFEST = "manifest.json" INDEX = "INDEX.md" MAX_READ_LINES = 160 +MAX_READ_CHARS = 12_000 # one read() result: a "line" is a whole paragraph, so lines alone do not bound it MAX_SEARCH_HITS = 40 -MAX_LINE_CHARS = 240 +MAX_LINE_CHARS = 240 # a search hit shows this much of its line, centred on the match +LONG_LINE_CHARS = 1_500 # a paragraph longer than this is stored as several lines (cut at sentence ends) +CARDS_DIR = "cards" # post cards (app/pipeline/cards.py): cards/.json, never citable + + +def card_rel(post_rel: str) -> str: + return f"{CARDS_DIR}/{post_rel}.json" + + +_SENTENCE_END = re.compile(r"(?<=[.!?])\s+") + + +def split_long(paragraph: str, limit: int = LONG_LINE_CHARS) -> list[str]: + """A long paragraph as several lines of at most about `limit` characters, cut at sentence ends, so a citation + points at a few sentences instead of a whole page (PDFs and transcripts often have no paragraph breaks). + Code blocks and anything already on several lines are kept as they are.""" + if len(paragraph) <= limit or "\n" in paragraph or paragraph.startswith("```"): + return [paragraph] + out, piece = [], "" + for sentence in _SENTENCE_END.split(paragraph): + if piece and len(piece) + len(sentence) + 1 > limit: + out.append(piece) + piece = "" + piece = f"{piece} {sentence}" if piece else sentence + if piece: + out.append(piece) + return out _locks: dict[tuple[uuid.UUID, str], threading.Lock] = {} # Posts only: when this process last brought a corpus in line with R2, and the manifest it saw (root -> (time, manifest)). @@ -70,7 +106,7 @@ def render_post(*, title: str, url: str, published_at: datetime | None, source: if heading: lines += [f"## {heading}", ""] for para in text.split("\n\n"): - lines += [para.strip(), ""] + lines += [*split_long(para.strip()), ""] # the pieces stay one paragraph (no blank line between) return "\n".join(lines).rstrip() + "\n" @@ -134,28 +170,70 @@ def _write_manifest(self, manifest: dict[str, str]) -> None: self.root.mkdir(parents=True, exist_ok=True) (self.root / MANIFEST).write_text(data, "utf-8") + @contextmanager + def _manifest_lock(self) -> Iterator[None]: + """Serialise manifest read-modify-writes across processes. The API (deletes) and the worker (imports, cards, + chat memory) both rewrite manifest.json; `self._lock` only covers one process, and without this a writer that + read the manifest before another's delete wrote it back with the deleted files still listed. A Postgres + transaction advisory lock (works through Neon's transaction pooler) keyed on workspace + area; released when + the transaction ends. SQLite (tests, local dev) has one writer process anyway, so it is skipped there. + Callers hold `self._lock` first.""" + if engine.dialect.name != "postgresql": + yield + return + digest = hashlib.blake2b(f"corpus:{self.workspace_id}:{self.area}".encode(), digest_size=8).digest() + with engine.begin() as conn: + conn.execute(sql("SET LOCAL lock_timeout = '60s'")) + conn.execute(sql("SELECT pg_advisory_xact_lock(:k)"), {"k": int.from_bytes(digest, "big", signed=True)}) + yield + # Writes (worker) def write_files(self, files: dict[str, str], remove: set[str] | None = None) -> None: - """Write/replace files and update the manifest once. Values are file contents.""" - with self._lock: + """Write/replace files and update the manifest once. Values are file contents. + + Objects are uploaded before the manifest lock is taken (a big import does not hold up a delete), then the + manifest is re-read and updated under the lock. Removed objects are deleted after the manifest stops listing + them, so a reader never sees a listed file that is already gone.""" + written: dict[str, str] = {} + for rel, body in files.items(): + rel = self.clean_rel(rel) + self.store.put_text(self._key(rel), body, "text/markdown; charset=utf-8") + written[rel] = body + with self._lock, self._manifest_lock(): manifest = self._read_manifest(remote=True) - for rel, text in files.items(): - rel = self.clean_rel(rel) - self.store.put_text(self._key(rel), text, "text/markdown; charset=utf-8") + for rel, body in written.items(): local = self._local(rel) local.parent.mkdir(parents=True, exist_ok=True) - local.write_text(text, "utf-8") - manifest[rel] = hashlib.sha256(text.encode()).hexdigest() - for rel in remove or set(): - rel = self.clean_rel(rel) + local.write_text(body, "utf-8") + manifest[rel] = hashlib.sha256(body.encode()).hexdigest() + removing = {self.clean_rel(rel) for rel in remove or set()} + if self.area == "corpus": # a removed post takes its card with it + removing |= {card_rel(rel) for rel in removing if card_rel(rel) in manifest} + for rel in removing: manifest.pop(rel, None) + self._write_manifest(manifest) + for rel in removing: self.store.delete(self._key(rel)) self._local(rel).unlink(missing_ok=True) - self._write_manifest(manifest) if self.area == "corpus": _synced[str(self.root)] = (time.monotonic(), dict(manifest)) + def _drop_missing(self, missing: set[str]) -> dict[str, str]: + """Take entries whose object is gone out of the remote manifest (left there by an older lost update, or a + delete outside the app). Re-checked under the lock: an entry a writer has since fixed is kept.""" + with self._manifest_lock(): + manifest = self._read_manifest(remote=True) + gone = {rel for rel in missing if rel in manifest and not self.store.exists(self._key(rel))} + if gone: + for rel in gone: + manifest.pop(rel) + self.store.put_text(self._key(MANIFEST), json.dumps(manifest, sort_keys=True, indent=0), + "application/json") + log.warning("corpus %s/%s: dropped %d manifest entries with no object: %s", + self.workspace_id, self.area, len(gone), sorted(gone)) + return manifest + # Sync (API / any reader) def sync(self, need: tuple[str, ...] | list[str] = ()) -> dict[str, str]: @@ -170,12 +248,24 @@ def sync(self, need: tuple[str, ...] | list[str] = ()) -> dict[str, str]: with self._lock: remote = self._read_manifest(remote=True) local = self._read_manifest(remote=False) + missing: set[str] = set() for rel, digest in remote.items(): path = self._local(rel) if local.get(rel) == digest and path.exists(): continue + try: + data = self.store.get_bytes(self._key(rel)) + except Exception as exc: + if not is_not_found(exc): + raise + missing.add(rel) # one listed-but-gone file must not fail every read in the workspace + continue path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(self.store.get_bytes(self._key(rel))) + path.write_bytes(data) + if missing: + self._drop_missing(missing) + # Not on disk now: leave them out of the local manifest so a later sync fetches any a writer restored. + remote = {rel: digest for rel, digest in remote.items() if rel not in missing} for rel in set(local) - set(remote): self._local(rel).unlink(missing_ok=True) self.root.mkdir(parents=True, exist_ok=True) @@ -196,6 +286,16 @@ def read_lines(self, rel: str) -> list[str]: return path.read_text("utf-8").splitlines() +def _snippet(line: str, match: re.Match) -> str: + """MAX_LINE_CHARS of the line around the match: a line can be a long paragraph whose match is far from its start.""" + line = line.strip() if len(line) <= MAX_LINE_CHARS else line + if len(line) <= MAX_LINE_CHARS: + return line + start = max(0, min(match.start() - MAX_LINE_CHARS // 3, len(line) - MAX_LINE_CHARS)) + text = line[start:start + MAX_LINE_CHARS].strip() + return ("..." if start > 0 else "") + text + ("..." if start + MAX_LINE_CHARS < len(line) else "") + + class ScopedTools: """The agent's tools, restricted to an allowlist of files (a notebook's posts). @@ -234,27 +334,36 @@ def list_files(self, contains: str = "") -> str: def search(self, pattern: str, path: str = "") -> str: """Search post text with a case insensitive regular expression (like grep). Use `|` for alternatives, e.g. `pric(e|ing)|paid tier|subscription cost`. Optionally limit to one `path`. - Returns `path:line: text` matches.""" + Returns `path:line: text` matches, the posts with the most matches first.""" self.on_step("search", pattern) try: rx = re.compile(pattern, re.IGNORECASE) except re.error: rx = re.compile(re.escape(pattern), re.IGNORECASE) targets = [self._check(path)] if path else list(self.allowed) - hits: list[Hit] = [] - total = 0 + by_post: dict[str, list[tuple[int, int, Hit]]] = {} # path -> (matches on the line, line, hit) + unavailable = 0 for rel in targets: - for n, line in enumerate(self.corpus.read_lines(rel), start=1): - if rx.search(line): - total += 1 - if len(hits) < MAX_SEARCH_HITS: - hits.append(Hit(rel, n, line.strip()[:MAX_LINE_CHARS])) - if not hits: - return "No matches. Try synonyms or a broader pattern." + try: + lines = self.corpus.read_lines(rel) + except CorpusError: # one missing file must not fail the search over every other post + unavailable += 1 + continue + for n, line in enumerate(lines, start=1): + found = list(rx.finditer(line)) + if found: + by_post.setdefault(rel, []).append((len(found), n, Hit(rel, n, _snippet(line, found[0])))) + total = sum(len(v) for v in by_post.values()) + note = f"\n({unavailable} post(s) could not be read right now)" if unavailable else "" + if not total: + return "No matches. Try synonyms or a broader pattern." + note + # Posts with more matching lines first (a post about the subject beats one that mentions it), lines in order. + ranked = sorted(by_post.values(), key=lambda v: (-len(v), -sum(m for m, _, _ in v))) + hits = [h for post in ranked for _, _, h in post][:MAX_SEARCH_HITS] out = "\n".join(f"{h.path}:{h.line}: {h.text}" for h in hits) if total > len(hits): out += f"\n... {total - len(hits)} more matches. Narrow the pattern or pass a path." - return out + return out + note def read(self, path: str, start_line: int = 1, end_line: int = 0) -> str: """Read a post with line numbers. Reads at most 160 lines per call; pass start_line and @@ -264,8 +373,16 @@ def read(self, path: str, start_line: int = 1, end_line: int = 0) -> str: start = max(1, start_line) end = min(len(lines), end_line if end_line >= start else start + MAX_READ_LINES - 1) end = min(end, start + MAX_READ_LINES - 1) + rows, used = [], 0 + for n in range(start, end + 1): + row = f"{n}| {lines[n - 1]}" + if rows and used + len(row) > MAX_READ_CHARS: # stop before the result gets too big; page on from here + end = n - 1 + break + rows.append(row[:MAX_READ_CHARS]) + used += len(row) + 1 self.on_step("read", f"{self.allowed.get(rel, rel)} (lines {start} to {end})") - body = "\n".join(f"{n}| {lines[n - 1]}" for n in range(start, end + 1)) + body = "\n".join(rows) more = f"\n[{len(lines) - end} more lines]" if end < len(lines) else "" return f"{rel} ({len(lines)} lines)\n{body}{more}" diff --git a/backend/app/llm/provider.py b/backend/app/llm/provider.py index d013138..c6286a4 100644 --- a/backend/app/llm/provider.py +++ b/backend/app/llm/provider.py @@ -29,14 +29,17 @@ def _extra_kwargs(effort: str | None) -> dict: return {"extra_body": {"thinking": {"type": "enabled"}, "reasoning_effort": effort}} -def _build(model: str, *, effort: str | None, temperature: float | None, max_tokens: int | None) -> dspy.LM: +def _build(model: str, *, effort: str | None, temperature: float | None, max_tokens: int | None, + cache: bool = True, timeout: float | None = None) -> dspy.LM: + # timeout: LiteLLM's default is 600s, so one stuck request used to hold a chat for ten minutes. return dspy.LM( model, api_base=settings.llm_api_base or None, api_key=settings.llm_api_key or None, temperature=settings.llm_temperature if temperature is None else temperature, max_tokens=max_tokens or settings.llm_max_tokens, - cache=True, + cache=cache, + timeout=timeout or settings.llm_timeout_seconds, **_extra_kwargs(effort), ) @@ -47,6 +50,14 @@ def main_lm(effort: str | None = None) -> dspy.LM: return _build(settings.llm_model, effort=effort, temperature=None, max_tokens=None) +@lru_cache +def agent_lm() -> dspy.LM: + """The chat research agent: the main model, never cached (a retried question must not replay the same failing + steps) and with the chat's own timeout.""" + return _build(settings.llm_model, effort=None, temperature=None, max_tokens=None, cache=False, + timeout=settings.chat_llm_timeout_seconds) + + @lru_cache def fast_lm() -> dspy.LM: return _build(settings.llm_fast_model, effort="low", temperature=None, max_tokens=settings.llm_fast_max_tokens) diff --git a/backend/app/llm/signatures.py b/backend/app/llm/signatures.py index ae1113b..0aa5777 100644 --- a/backend/app/llm/signatures.py +++ b/backend/app/llm/signatures.py @@ -159,9 +159,10 @@ class CleanAndSegment(dspy.Signature): class ResearchArchive(dspy.Signature): __doc__ = """You are a research assistant working inside a writer's archive, which is a folder of markdown - posts. Find the answer by exploring the files, in this order. First call list_files to see which posts - exist; a post whose title matches the topic is often the best source. Then call search across the whole - archive (leave path empty; try several phrasings and synonyms) to locate relevant lines. Pass path to + posts. Start from the prefetched passages: when they answer the question, cite them directly. Otherwise call + search across the whole archive (leave path empty; try several phrasings and synonyms) to locate relevant + lines. Call list_files when you need to see which posts exist; a post whose title matches the topic is often + the best source. Pass path to search only when the writer explicitly asks you to use one named post (for example "in the Neo4j post" or "in that article"); otherwise never limit a search to one post, because a different post may be the best source. Then read the surrounding lines before relying on them. When more than one post covers the topic, diff --git a/backend/app/observability/__init__.py b/backend/app/observability/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/observability/langfuse_client.py b/backend/app/observability/langfuse_client.py new file mode 100644 index 0000000..e4b6a19 --- /dev/null +++ b/backend/app/observability/langfuse_client.py @@ -0,0 +1,98 @@ +"""Langfuse for the notebook chat: one trace per message, scores from ratings and the judge. + +Optional in every way. With no LANGFUSE_PUBLIC_KEY/SECRET_KEY, or the `langfuse` package missing, every helper here +does nothing and the chat runs as before. A Langfuse failure is logged and never reaches the writer. + +Writers' text (questions, answers, passages, search patterns) leaves our stack only when LANGFUSE_MASK_TEXT=false: +by default `text()` sends its size instead. Ids are hashed before they are sent.""" + +import hashlib +import logging +import threading +from typing import Any + +from app.config import settings + +log = logging.getLogger(__name__) + +_client: Any = None +_lock = threading.Lock() +_broken = False # the package is missing or the client could not start: stay off for this process + + +def configured() -> bool: + return bool(settings.langfuse_public_key and settings.langfuse_secret_key) + + +def client() -> Any: + """The process's Langfuse client, or None when off.""" + global _client, _broken + if _broken or not configured(): + return None + if _client is None: + with _lock: + if _client is None and not _broken: + try: + from langfuse import Langfuse + + _client = Langfuse(public_key=settings.langfuse_public_key, + secret_key=settings.langfuse_secret_key, + base_url=settings.langfuse_host or None, + environment=settings.env.lower() or None) + except Exception: + log.warning("Langfuse could not start; chat tracing is off in this process", exc_info=True) + _broken = True + return None + return _client + + +def enabled() -> bool: + return client() is not None + + +def text(value: str | None) -> Any: + """What may be sent for a piece of writers' text: the text itself only when masking is off.""" + if value is None: + return None + return {"chars": len(value)} if settings.langfuse_mask_text else value + + +def pseudonym(value: Any) -> str: + """A stable, non-reversible id for a user or workspace.""" + return hashlib.sha256(f"notestack:{value}".encode()).hexdigest()[:24] + + +def score(trace_id: str | None, name: str, value: float | str, comment: str | None = None, + data_type: str | None = None, score_id: str | None = None) -> bool: + """Attach a score to a chat message's trace. False when off, when the message has no trace, or on failure. + A fixed score_id replaces the earlier score with that id (a writer who rates again).""" + lf = client() + if lf is None or not trace_id: + return False + try: + kwargs: dict[str, Any] = {"name": name, "value": value, "trace_id": trace_id} + if comment: + kwargs["comment"] = comment[:1000] + if data_type: + kwargs["data_type"] = data_type + if score_id: + kwargs["score_id"] = score_id + lf.create_score(**kwargs) + return True + except Exception: + log.warning("Could not send the Langfuse score %s", name, exc_info=True) + return False + + +def flush() -> None: + lf = client() + if lf is not None: + try: + lf.flush() + except Exception: + log.warning("Could not flush Langfuse", exc_info=True) + + +def reset_for_tests() -> None: + global _client, _broken + _client, _broken = None, False diff --git a/backend/app/pipeline/cards.py b/backend/app/pipeline/cards.py new file mode 100644 index 0000000..fa8fbea --- /dev/null +++ b/backend/app/pipeline/cards.py @@ -0,0 +1,140 @@ +"""Post cards: a short description of every post, written once by the fast model when the post is added or changed. + +Keyword search only finds a post when the question uses the post's own words. A card adds the other words a reader +might use (topics, names with spelling variants, synonyms, the questions the post answers), and the chat's BM25 +indexes them with the post (app/pipeline/prefetch.py), so "how do I get more paid subscribers" can find a post that +only says "converting free readers into paying members". It is the alternative to embeddings: no vector store, and +a card is rebuilt only when its post changes. + +Cards live in the corpus next to the posts, as cards/.json (see corpus.card_rel), so they sync through the +same R2 manifest and go when their post is removed. They are never citable: answers still cite the posts' lines.""" + +import json +import logging +import uuid +from concurrent.futures import ThreadPoolExecutor + +import dspy +from sqlalchemy import select +from sqlalchemy.orm import Session + +from app.config import settings +from app.corpus import Corpus, CorpusError, card_rel +from app.llm.provider import fast_lm +from app.models import Document +from app.pipeline.passages import _body_start + +log = logging.getLogger(__name__) + +CARD_VERSION = 1 +HEAD_CHARS = 9_000 # the post given to the model: its start (where the argument usually is) ... +TAIL_CHARS = 3_000 # ... and its end (the conclusion) +WRITE_BATCH = 20 # cards written to the corpus per manifest update +MAX_PARALLEL = 4 +LIMITS = {"topics": 8, "entities": 12, "synonyms": 20, "questions": 5} + + +class PostCard(dspy.Signature): + """Describe one post from a writer's archive so that a keyword search finds it when a reader asks about it in + their own words. Use only what the post says. Prefer the plain words a reader would type over the post's jargon, + and include common spelling variants of names (for example "Arsalan" for "Arslan").""" + + title: str = dspy.InputField() + post: str = dspy.InputField() + summary: str = dspy.OutputField(desc="2 to 3 sentences: what the post says and its main claims") + topics: list[str] = dspy.OutputField(desc="Up to 8 subjects, 1 to 4 words each") + entities: list[str] = dspy.OutputField(desc="Up to 12 names: people, companies, products, tools, places") + synonyms: list[str] = dspy.OutputField(desc="Up to 20 other words or short phrases a reader might use for the " + "post's subjects") + questions: list[str] = dspy.OutputField(desc="3 to 5 questions this post answers, in a reader's words") + + +def post_text(lines: list[str]) -> str: + body = "\n".join(line for line in lines[_body_start(lines):] if line.strip()) + if len(body) <= HEAD_CHARS + TAIL_CHARS: + return body + return body[:HEAD_CHARS] + "\n[...]\n" + body[-TAIL_CHARS:] + + +def _clean(values, limit: int) -> list[str]: + out = [] + for v in values or []: + v = " ".join(str(v).split())[:120] + if v and v.lower() not in {x.lower() for x in out}: + out.append(v) + return out[:limit] + + +def make_card(title: str, text: str) -> dict: + with dspy.context(lm=fast_lm()): + pred = dspy.Predict(PostCard)(title=title, post=text, config={"timeout": settings.llm_timeout_seconds}) + return {"version": CARD_VERSION, "title": title, "summary": " ".join((pred.summary or "").split())[:800], + **{field: _clean(getattr(pred, field, None), limit) for field, limit in LIMITS.items()}} + + +def read_card(corpus: Corpus, post: str) -> dict | None: + try: + return json.loads("\n".join(corpus.read_lines(card_rel(post)))) + except (CorpusError, ValueError, OSError): + return None + + +def load_cards(corpus: Corpus, posts) -> dict[str, dict]: + """The cards on local disk for these posts (call corpus.sync first). Posts without a card are left out.""" + return {p: card for p in posts if (card := read_card(corpus, p)) is not None} + + +def card_terms(card: dict) -> str: + """The card's text for the keyword index.""" + return " ".join([card.get("summary", ""), *[" ".join(card.get(f) or []) for f in LIMITS]]) + + +def build_cards(corpus: Corpus, posts: dict[str, str], force: bool = False) -> dict: + """Write cards for posts whose card is missing or was made from an older version of the post. + posts: path -> title. Returns counts. One failed card never stops the others.""" + manifest = corpus.sync(tuple(posts)) + todo = [] + for path, title in posts.items(): + if path not in manifest: + continue + old = read_card(corpus, path) + if force or not old or old.get("post_hash") != manifest[path] or old.get("version") != CARD_VERSION: + todo.append((path, title)) + made = failed = 0 + pending: dict[str, str] = {} + + def one(item: tuple[str, str]) -> tuple[str, dict | None]: + path, title = item + try: + card = make_card(title, post_text(corpus.read_lines(path))) + return path, {**card, "post_hash": manifest[path]} + except Exception: + log.warning("Could not make the card for %s", path, exc_info=True) + return path, None + + workers = max(1, min(MAX_PARALLEL, settings.llm_max_concurrent)) + with ThreadPoolExecutor(max_workers=workers) as pool: + for path, card in pool.map(one, todo): + if card is None: + failed += 1 + continue + pending[card_rel(path)] = json.dumps(card, ensure_ascii=False) + made += 1 + if len(pending) >= WRITE_BATCH: + corpus.write_files(pending) + pending = {} + if pending: + corpus.write_files(pending) + return {"made": made, "failed": failed, "up_to_date": len(posts) - len(todo)} + + +def cards_for_documents(db: Session, workspace_id: uuid.UUID, document_ids: list[str] | None, + force: bool = False) -> dict: + """The worker's entry point: cards for these documents, or for every post in the workspace when ids is None.""" + q = select(Document.path, Document.title).where(Document.workspace_id == workspace_id, Document.path.is_not(None)) + if document_ids is not None: + q = q.where(Document.id.in_([uuid.UUID(str(i)) for i in document_ids])) + posts = {path: title or path for path, title in db.execute(q).all()} + if not posts: + return {"made": 0, "failed": 0, "up_to_date": 0} + return build_cards(Corpus(workspace_id), posts, force) diff --git a/backend/app/pipeline/chat_judge.py b/backend/app/pipeline/chat_judge.py new file mode 100644 index 0000000..d4fe683 --- /dev/null +++ b/backend/app/pipeline/chat_judge.py @@ -0,0 +1,120 @@ +"""The chat judge: scores a sample of notebook-chat answers in the worker, after they were sent, and records the +scores on the message (recall_json["judge"]) and on its Langfuse trace. + +- An answer gets `relevance` (does it answer what was asked) and `faithfulness` (is every claim in the passages it + cites), each 1 to 5. +- A refusal ("could not find support", or the model saying the posts do not cover it) gets `false_refusal`: a wide + keyword search over the notebook plus the full post list go to the judge, which says whether the notebook did hold + the answer. This is the score for "it failed although the notebook covers it". + +Queued by the chat router (should_judge in app/routers/notebooks.py) for CHAT_JUDGE_SAMPLE_RATE of answers.""" + +import logging +import uuid + +import dspy +from sqlalchemy import select +from sqlalchemy.orm import Session, load_only + +from app.corpus import Corpus +from app.llm.provider import fast_lm +from app.models import Chat, Document, Message, NotebookDocument +from app.observability import langfuse_client as lf +from app.pipeline.prefetch import prefetch + +log = logging.getLogger(__name__) + +WIDE_TOP_K = 20 +WIDE_PER_POST = 3 +TITLES_SHOWN = 300 +REFUSAL_OUTCOMES = {"writer_uncovered", "refused_no_cites", "cites_dropped"} + + +class JudgeAnswer(dspy.Signature): + """Grade an answer from a research assistant that must answer only from a writer's own posts. + relevance: 5 = answers exactly what was asked, 3 = partly or vaguely, 1 = about something else. + faithfulness: 5 = every factual claim is stated in the cited passages, 3 = some claims are not in them, + 1 = mostly unsupported or contradicted. Judge only against the cited passages, not your own knowledge.""" + + question: str = dspy.InputField() + answer: str = dspy.InputField() + cited_passages: str = dspy.InputField() + relevance: int = dspy.OutputField(desc="1 to 5") + faithfulness: int = dspy.OutputField(desc="1 to 5") + reason: str = dspy.OutputField(desc="One sentence: the main problem, or 'fine'") + + +class JudgeRefusal(dspy.Signature): + """A research assistant told a writer that their notebook does not cover their question. Decide whether that + was wrong: do the passages below, or a post whose title clearly matches the question, hold the answer? Answer + true only when the material really answers the question, not when it is merely on a nearby subject.""" + + question: str = dspy.InputField() + post_titles: str = dspy.InputField(desc="Every post in the notebook") + passages: str = dspy.InputField(desc="The best passages a wide keyword search found, with their paths") + evidence_existed: bool = dspy.OutputField() + best_path: str = dspy.OutputField(desc="The post path that answers it, or empty") + reason: str = dspy.OutputField(desc="One sentence") + + +def _question_for(db: Session, msg: Message) -> str: + return db.scalar(select(Message.content).where(Message.chat_id == msg.chat_id, Message.role == "user", + Message.created_at <= msg.created_at) + .order_by(Message.created_at.desc()).limit(1)) or "" + + +def _clamp(value, low: int = 1, high: int = 5) -> int: + try: + return max(low, min(high, int(value))) + except (TypeError, ValueError): + return low + + +def judge_message(db: Session, message_id: uuid.UUID) -> dict: + msg = db.get(Message, message_id) + if msg is None or msg.role != "assistant": + return {"skipped": "message gone"} + chat = db.get(Chat, msg.chat_id) + recall = dict(msg.recall_json or {}) + outcome = recall.get("outcome", "") + question = _question_for(db, msg) + if not question or chat is None: + return {"skipped": "no question"} + result: dict + with dspy.context(lm=fast_lm()): + if outcome in REFUSAL_OUTCOMES: + result = _judge_refusal(db, chat, question) + else: + quotes = "\n\n".join(f"[{c.marker}] {c.path} lines {c.line_start}-{c.line_end}\n{c.span or ''}" + for c in sorted(msg.citations, key=lambda c: c.marker)) or "(no citations)" + pred = dspy.Predict(JudgeAnswer)(question=question, answer=msg.content, cited_passages=quotes) + result = {"relevance": _clamp(pred.relevance), "faithfulness": _clamp(pred.faithfulness), + "reason": (pred.reason or "").strip()[:300]} + trace_id = recall.get("trace_id") + for name in ("relevance", "faithfulness"): + if name in result: + lf.score(trace_id, name, float(result[name]), comment=result.get("reason") or None, + score_id=f"{msg.id}-{name}") + if "evidence_existed" in result: + lf.score(trace_id, "false_refusal", 1.0 if result["evidence_existed"] else 0.0, data_type="BOOLEAN", + comment=result.get("reason") or None, score_id=f"{msg.id}-false_refusal") + lf.flush() + msg.recall_json = {**recall, "judge": result} + db.commit() + return result + + +def _judge_refusal(db: Session, chat: Chat, question: str) -> dict: + docs = db.scalars(select(Document).join(NotebookDocument, NotebookDocument.document_id == Document.id) + .where(NotebookDocument.notebook_id == chat.notebook_id, Document.path.is_not(None)) + .options(load_only(Document.id, Document.path, Document.title))).all() + allowed = {d.path: d.title for d in docs} + if not allowed: + return {"evidence_existed": False, "best_path": "", "reason": "the notebook has no posts"} + corpus = Corpus(chat.workspace_id) + manifest = corpus.sync(tuple(allowed)) + found = prefetch(corpus, allowed, manifest, question, WIDE_TOP_K, WIDE_PER_POST) + titles = "\n".join(f"{path} | {title}" for path, title in list(allowed.items())[:TITLES_SHOWN]) + pred = dspy.Predict(JudgeRefusal)(question=question, post_titles=titles, passages=found.text) + return {"evidence_existed": bool(pred.evidence_existed), "best_path": (pred.best_path or "").strip()[:300], + "reason": (pred.reason or "").strip()[:300], "wide_search_passages": len(found.passages)} diff --git a/backend/app/pipeline/context_router.py b/backend/app/pipeline/context_router.py new file mode 100644 index 0000000..c19dce5 --- /dev/null +++ b/backend/app/pipeline/context_router.py @@ -0,0 +1,147 @@ +"""What the answer writer reads, decided by the notebook's size (CHAT_ROUTER). + +Tier A: the notebook fits CHAT_FULL_NOTEBOOK_TOKENS, so every post goes into the prompt with its line numbers. There + is nothing to search, so nothing can be missed. +Tier B: a bigger notebook. The question and a few rewordings (one fast-model call) are ranked against the posts' + passages and cards (prefetch.retrieve), and the best posts go in whole while they fit CHAT_EVIDENCE_TOKENS, + otherwise their matching sections. A question about the notebook as a whole gets every post's card instead. +Tier C: the research agent (research.py), only when the writer could not answer from A or B. + +Everything here reads the local disk cache (sync first) and makes at most one model call (expand_query).""" + +import logging +from dataclasses import dataclass, field +from pathlib import PurePosixPath + +import dspy + +from app.config import settings +from app.corpus import Corpus, CorpusError +from app.llm.provider import fast_lm, track_usage +from app.pipeline.passages import _body_start +from app.pipeline.prefetch import Passage, Retrieval, _render, openings + +log = logging.getLogger(__name__) + +CHARS_PER_TOKEN = 4 # a rough English average: the budgets are guards, not exact counts +MAX_POSTS = 10 # Tier B never sends more posts than this, however small they are +WHOLE_POST_SHARE = 0.5 # a post is sent whole only if it takes at most this share of the budget +MIN_ROOM_CHARS = 600 # stop filling when less than this is left +AGENT_PREFETCH_CHARS = 12_000 # what of Tier B's evidence the agent is handed when it takes over + + +def newest_first(allowed: dict[str, str]) -> list[tuple[str, str]]: + """Posts by the date in their file name (sources//-.md), newest first.""" + return sorted(allowed.items(), key=lambda item: PurePosixPath(item[0]).name, reverse=True) + + +def notebook_tokens(corpus: Corpus, allowed: dict[str, str]) -> int: + total = 0 + for path in allowed: + try: + total += corpus._local(path).stat().st_size + except (OSError, CorpusError): + continue + return total // CHARS_PER_TOKEN + + +def numbered_post(corpus: Corpus, path: str, title: str) -> str: + """One post as the writer reads it: a FILE line, then its body with real line numbers (citable).""" + try: + lines = corpus.read_lines(path) + except CorpusError: + return "" + first = _body_start(lines) + body = "\n".join(f"{n}| {line}" for n, line in enumerate(lines, start=1) if n > first and line.strip()) + return f"FILE {path} ({title})\n{body}" + + +def tier_a_evidence(corpus: Corpus, allowed: dict[str, str]) -> str: + """Every post, newest first. The notebook text comes first in the prompt so a provider's prefix cache can reuse + it for the next question in the same notebook.""" + posts = [numbered_post(corpus, path, title) for path, title in newest_first(allowed)] + return "All posts in this notebook (citable, with line numbers):\n\n" + "\n\n".join(p for p in posts if p) + + +@dataclass +class Evidence: + text: str = "" + posts: list[str] = field(default_factory=list) # posts that went in, in order + whole: int = 0 # how many of them went in whole + + +def tier_b_evidence(corpus: Corpus, allowed: dict[str, str], found: Retrieval, budget_chars: int) -> Evidence: + """The best posts, whole while they fit; otherwise each one's matching sections (with the passages around).""" + out = Evidence() + parts: list[str] = [] + room = budget_chars + for path in found.posts[:MAX_POSTS]: + if room < MIN_ROOM_CHARS: + break + title = allowed.get(path, path) + whole = numbered_post(corpus, path, title) + if whole and len(whole) <= room and len(whole) <= budget_chars * WHOLE_POST_SHARE: + parts.append(whole) + room -= len(whole) + out.posts.append(path) + out.whole += 1 + continue + sections: list[str] = [] + seen: set[int] = set() + for p in found.passages.get(path, []): + run: list[Passage] = [q for q in (p.section or [p]) if id(q) not in seen] + text = _render(run) if run else "" + if not text: + continue + if len(text) > room: # a long section: the match and its neighbour only + run = [q for q in [p, p.next] if q is not None and id(q) not in seen] + text = _render(run) + if len(text) > room: + continue + sections.append(text) + seen.update(id(q) for q in run) + room -= len(text) + if sections: + parts.append(f"From {path} ({title}):\n" + "\n\n".join(sections)) + out.posts.append(path) + out.text = "\n\n".join(parts) + return out + + +def overview_evidence(corpus: Corpus, allowed: dict[str, str], cards: dict[str, dict], budget_chars: int) -> str: + """For a question about the notebook as a whole: every post's card (to see what each post is about) and the + openings of the newest posts (what an answer can cite).""" + rows = [] + for path, title in newest_first(allowed): + card = cards.get(path) + if card: + rows.append(f"- {path} | {title} | {card.get('summary', '')} | topics: {', '.join(card.get('topics') or [])}") + else: + rows.append(f"- {path} | {title}") + listing = "\n".join(rows)[: budget_chars // 2] + room = max(budget_chars - len(listing), MIN_ROOM_CHARS) + return ("What every post is about (post cards: NOT citable, use them to see the whole notebook):\n" + listing + + "\n\nThe opening passage of the newest posts (citable, with line numbers):\n\n" + + openings(corpus, newest_first(allowed), room)) + + +class ExpandQuery(dspy.Signature): + """Turn a writer's chat message into searches over their own posts. standalone: the message as a full question + (resolve "it", "that" or "why" from the conversation). keywords: 3 to 5 short searches in other words a post might + use for the same thing: synonyms, the plain-language version, related terms, spelling variants of names.""" + + message: str = dspy.InputField() + conversation: str = dspy.InputField() + standalone: str = dspy.OutputField() + keywords: list[str] = dspy.OutputField() + + +def expand_query(message: str, conversation: str) -> tuple[list[str], int, int]: + """[standalone question, keyword searches...], with the tokens used. Raises on failure; the caller then searches + with the message alone.""" + lm = fast_lm() + with track_usage(lm) as usage, dspy.context(lm=lm): + pred = dspy.Predict(ExpandQuery)(message=message, conversation=conversation, + config={"timeout": settings.chat_fast_timeout_seconds}) + queries = [(pred.standalone or "").strip(), *[str(k).strip() for k in (pred.keywords or [])][:5]] + return [q for q in dict.fromkeys(queries) if q], usage.prompt_tokens, usage.completion_tokens diff --git a/backend/app/pipeline/prefetch.py b/backend/app/pipeline/prefetch.py index 1a55fb3..f20017c 100644 --- a/backend/app/pipeline/prefetch.py +++ b/backend/app/pipeline/prefetch.py @@ -11,7 +11,7 @@ from dataclasses import dataclass, field from app.chat_memory.search import Bm25, tokenize -from app.corpus import Corpus, CorpusError +from app.corpus import Corpus, CorpusError, card_rel from app.pipeline.passages import _body_start # Passages follow the post's sections and are sized by characters, not lines: a line here is anything from a heading @@ -21,7 +21,7 @@ TAIL_CHARS = 300 # a leftover this small joins the passage before it; a section this small joins the next one CONTEXT_BUDGET_CHARS = 12_000 # the passages handed over, with the rest of their sections added, stay under this SECTION_WHOLE_CHARS = 6_000 # a matching section up to this size is sent whole; a longer one, the match and its neighbours -BLOCKS_VERSION = 2 # in the index cache key: a change to how passages are cut never reuses an old index +BLOCKS_VERSION = 3 # in the index cache key: a change to how passages are cut never reuses an old index TOP_K = 6 PER_POST = 2 # at most this many passages from one post, so a long post cannot crowd out the others DEEP_TOP_K = 10 # a synthesis question gets more evidence @@ -29,7 +29,9 @@ OVERVIEW_BUDGET_CHARS = 24_000 # opening passages for a question about the whole notebook OVERVIEW_LIST_CHARS = 12_000 # the post list given with them # Words that say what kind of question it is, not what it is about. They would make coverage look worse than it is. -_QUESTION_WORDS = frozenset("written write wrote writing think thought post blog article tell explain mean view take " +# "write", "writing" and "intro" are left out on purpose: for writers they are often the subject ("how do I write +# a better intro"). +_QUESTION_WORDS = frozenset("written wrote think thought post blog article tell explain mean view take " "opinion summarize summarise summary talk talked mention mentioned any ever how why often " "much many where who whom whose can could would should will just really also mine myself " "give show list find".split()) @@ -37,7 +39,7 @@ # A question made only of these has no subject to search for: it gets the overview instead. _GENERIC = frozenset("strongest strong best main key biggest important interesting ideas idea themes theme topics " "topic across overall general common recurring archive notebook these those all everything most " - "brief intro introduction short quick detail detailed overview".split()) + "brief short quick detail detailed overview".split()) # Words too vague to say what the question is about. Left in, they lower coverage without finding anything. _WEAK = frozenset("into help use using used make made get got thing way lot really very also".split()) _HEADING = re.compile(r"^#{2,6}\s") @@ -221,7 +223,7 @@ def _blocks(body: list[Line]) -> list[list[Line]]: return blocks -def _passage(rel: str, title: str, heading: str, block: list[Line]) -> Passage: +def _passage(rel: str, title: str, heading: str, block: list[Line], extra: list[str] | None = None) -> Passage: text: dict[int, str] = {} for n, t in block: # pieces of one long line become that line again text[n] = f"{text[n]} {t}" if n in text else t @@ -229,18 +231,28 @@ def _passage(rel: str, title: str, heading: str, block: list[Line]) -> Passage: lines = [text.get(n, "") for n in range(first, last + 1)] # The title and the heading on every passage: the details under "## Getting featured" are about getting featured # even when their own lines never say so. - tokens = _terms(" ".join(t for _, t in block)) + _terms(title) + _terms(heading) + # extra: the post card's topics, names and synonyms (document expansion), so a question in other words still lands. + tokens = _terms(" ".join(t for _, t in block)) + _terms(title) + _terms(heading) + (extra or []) return Passage(rel, first, last, title, lines, tokens, heading=heading) -def passages_of(corpus: Corpus, rel: str, title: str) -> list[Passage]: +def card_expansion(card: dict | None) -> list[str]: + """The card words added to every passage of its post: topics, names and synonyms (not the summary, which would + make every passage of a post look alike).""" + if not card: + return [] + return _terms(" ".join(" ".join(card.get(f) or []) for f in ("topics", "entities", "synonyms"))) + + +def passages_of(corpus: Corpus, rel: str, title: str, card: dict | None = None) -> list[Passage]: try: lines = corpus.read_lines(rel) except CorpusError: return [] out: list[Passage] = [] + extra = card_expansion(card) for heading, body in _sections(lines, _body_start(lines)): - section = [_passage(rel, title, heading, b) for b in _blocks(body) if any(t.strip() for _, t in b)] + section = [_passage(rel, title, heading, b, extra) for b in _blocks(body) if any(t.strip() for _, t in b)] for a, b in zip(section, section[1:], strict=False): a.next = b # only within the section: the next section is another topic for a in section: @@ -259,24 +271,126 @@ def search(self, query: str, since: str = "") -> list[tuple[float, Passage]]: _cache: dict[str, _PostIndex] = {} -def _index(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str]) -> _PostIndex: - """One index per notebook and file version: rebuilt only when a post in it changes.""" - sig = "\n".join(f"{p}\t{manifest.get(p, '')}" for p in sorted(allowed)) - key = hashlib.sha1(f"v{BLOCKS_VERSION}\n{corpus.root}\n{sig}".encode()).hexdigest() +def _signature(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], cards: dict | None, + kind: str) -> str: + """Cache key: the notebook's posts and cards at their current versions.""" + sig = "\n".join(f"{p}\t{manifest.get(p, '')}\t{manifest.get(card_rel(p), '') if p in (cards or {}) else ''}" + for p in sorted(allowed)) + return hashlib.sha1(f"{kind}v{BLOCKS_VERSION}\n{corpus.root}\n{sig}".encode()).hexdigest() + + +def _cached(key: str, build): if key not in _cache: if len(_cache) >= 16: _cache.pop(next(iter(_cache))) - _cache[key] = _PostIndex([p for rel, title in allowed.items() for p in passages_of(corpus, rel, title)]) + _cache[key] = build() return _cache[key] +def _index(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], + cards: dict[str, dict] | None = None) -> _PostIndex: + """One index per notebook and file version: rebuilt only when a post (or its card) in it changes.""" + cards = cards or {} + return _cached(_signature(corpus, allowed, manifest, cards, "posts"), + lambda: _PostIndex([p for rel, title in allowed.items() + for p in passages_of(corpus, rel, title, cards.get(rel))])) + + +# "What did I write about X", "have I ever written": the writer's own writing, not a subject. "How do I write X" keeps +# "write", because there writing is the subject. +_SELF_WRITE = re.compile(r"\b((did|have|had)\s+i\s+(ever\s+)?(write|written)|i\s*('ve|\s+have|\s+had)?\s*(ever\s+)?" + r"(written|wrote))\b", re.IGNORECASE) + + +def content_words(question: str) -> list[str]: + """The question's subject words, stemmed: what is searched for. Empty for a question about the whole notebook.""" + words = [t for t in tokenize(_SELF_WRITE.sub(" ", question)) + if t not in _QUESTION_WORDS and t not in _GENERIC and t not in _WEAK] + return list(dict.fromkeys(_stem(t) for t in words)) + + +def notebook_mentions(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], question: str, + cards: dict[str, dict] | None = None) -> list[str]: + """The question's subject words that occur somewhere in the notebook's posts (or their cards). Milliseconds, no + model: used to overrule an "off topic" triage that only saw the post titles.""" + words = content_words(question) + if not words or not allowed: + return [] + index = _index(corpus, allowed, manifest, cards) + return [t for t in words if t in index.idf] + + +@dataclass +class CardUnit: + path: str + title: str + tokens: list[str] + last: str = "" + + +def _card_index(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], cards: dict[str, dict]) -> Bm25: + """BM25 over whole posts, each one its title plus its card: finds a post by what it is about.""" + from app.pipeline.cards import card_terms + + return _cached(_signature(corpus, allowed, manifest, cards, "cards"), + lambda: Bm25([CardUnit(p, allowed[p], _terms(f"{allowed[p]} {card_terms(c)}")) + for p, c in cards.items() if p in allowed])) + + +RRF_K = 60 + + +@dataclass +class Retrieval: + posts: list[str] = field(default_factory=list) # best post first (card and passage rankings fused) + passages: dict[str, list[Passage]] = field(default_factory=dict) # per post, its matching passages, best first + queries: int = 0 + terms: int = 0 # content words, over all queries, that occur in the notebook + + @property + def passage_count(self) -> int: + return sum(len(v) for v in self.passages.values()) + + +def retrieve(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], cards: dict[str, dict], + queries: list[str], per_query: int = 30) -> Retrieval: + """Rank posts for a question and its rewordings: BM25 over passages (with card words) and BM25 over cards, one + ranking per query and index, fused by reciprocal rank (a post high in several rankings wins).""" + index = _index(corpus, allowed, manifest, cards) + card_index = _card_index(corpus, allowed, manifest, cards) if cards else None + score: dict[str, float] = {} + best: dict[int, tuple[float, Passage]] = {} + found: set[str] = set() + queries = list(dict.fromkeys(q for q in queries if q and q.strip())) + for q in queries: + words = content_words(q) + terms = [t for t in words if t in index.idf] + found.update(terms) + ranked = index.search_terms(terms)[:per_query] if terms else [] + for rank, path in enumerate(dict.fromkeys(p.path for _, p in ranked)): + score[path] = score.get(path, 0.0) + 1 / (RRF_K + rank + 1) + for sc, p in ranked: + if id(p) not in best or best[id(p)][0] < sc: + best[id(p)] = (sc, p) + card_words = [t for t in words if card_index is not None and t in card_index.idf] + found.update(card_words) + if card_words: + for rank, (_, unit) in enumerate(card_index.search_terms(card_words)[:per_query]): + score[unit.path] = score.get(unit.path, 0.0) + 1 / (RRF_K + rank + 1) + by_post: dict[str, list[tuple[float, Passage]]] = {} + for sc, p in best.values(): + by_post.setdefault(p.path, []).append((sc, p)) + return Retrieval(sorted(score, key=lambda p: -score[p]), + {p: [x for _, x in sorted(v, key=lambda e: -e[0])] for p, v in by_post.items()}, + len(queries), len(found)) + + def prefetch(corpus: Corpus, allowed: dict[str, str], manifest: dict[str, str], question: str, - k: int = TOP_K, per_post_max: int = PER_POST) -> Prefetch: - words = [t for t in tokenize(question) if t not in _QUESTION_WORDS and t not in _GENERIC and t not in _WEAK] - asked = list(dict.fromkeys(_stem(t) for t in words)) + k: int = TOP_K, per_post_max: int = PER_POST, cards: dict[str, dict] | None = None) -> Prefetch: + asked = content_words(question) if not asked or not allowed: return Prefetch(asked=asked) - index = _index(corpus, allowed, manifest) + index = _index(corpus, allowed, manifest, cards) # A word that occurs in no post (a typo like "waht", or a word the writer never used) cannot be found, so it # neither counts against coverage nor is searched for. terms = [t for t in asked if t in index.idf] diff --git a/backend/app/pipeline/research.py b/backend/app/pipeline/research.py index 5e6413d..744b201 100644 --- a/backend/app/pipeline/research.py +++ b/backend/app/pipeline/research.py @@ -34,9 +34,9 @@ from app.chat_memory.logs import context_log, text_enabled from app.chat_memory.tools import ChatTools, is_chat_path from app.config import settings -from app.corpus import Corpus, ScopedTools +from app.corpus import Corpus, CorpusError, ScopedTools from app.llm.postprocess import strip_em_dashes -from app.llm.provider import fast_lm, main_lm, track_usage, triage_lm +from app.llm.provider import agent_lm, fast_lm, track_usage, triage_lm, writer_lm from app.llm.signatures import ( ResearchArchive, ResearchArchiveWithMemory, @@ -45,7 +45,18 @@ TriageMessage, TriageWithMemory, ) +from app.observability import langfuse_client as lf from app.pipeline import writer +from app.pipeline.cards import load_cards +from app.pipeline.context_router import ( + AGENT_PREFETCH_CHARS, + CHARS_PER_TOKEN, + expand_query, + notebook_tokens, + overview_evidence, + tier_a_evidence, + tier_b_evidence, +) from app.pipeline.create_intent import parse_create from app.pipeline.external_delivery import adapter_for_tools from app.pipeline.internal_artifact_tools import TRANSFERABLE_ARTIFACTS, start_from_chat @@ -54,9 +65,12 @@ DEEP_TOP_K, OVERVIEW_BUDGET_CHARS, OVERVIEW_LIST_CHARS, + content_words, + notebook_mentions, openings, passages_of, prefetch, + retrieve, ) from app.pipeline.trace import MEMORY_GIVES, ChatTrace, arguments_shape, current_trace, probs_text from app.services import jev @@ -129,6 +143,7 @@ class VerifiedCitation: line_start: int line_end: int quote: str + repaired: bool = False # the model's line numbers were off; the lines were found again from the cited sentence def _route_info(route: "Triage") -> dict: @@ -156,6 +171,31 @@ class ResearchResult: background_action: dict | None = None +def outcome_of(result: "ResearchResult") -> str: + """Why this message ended the way it did: one of trace.OUTCOMES (cache hits and exceptions are set by the router).""" + if result.kind == "error": + return "agent_malformed" + if result.kind == "off_topic": + return "triage_off_topic" + if result.kind in {"chitchat", "about_app", "create"}: + return "triage_other" + if result.kind == "external_action": + return "external_failed" if result.unsupported else "external_done" + recall = result.recall or {} + if recall.get("refused"): + return "cites_dropped" if recall.get("proposed_cites") else "refused_no_cites" + if result.unsupported or not result.citations: + return "writer_uncovered" + return "answered" + + +def writer_model() -> str: + try: + return str(writer_lm().model) + except Exception: + return "" + + @dataclass class Turn: role: str # user | assistant @@ -167,7 +207,7 @@ class Turn: HISTORY_CHARS = 700 # per older message: half from the start, half from the end RECENT_TURNS = 2 # the newest messages (the last question and answer) are kept whole, up to RECENT_CHARS RECENT_CHARS = 4000 # safety ceiling for those, the same as the longest question a writer can send -QUICK_STEPS = 4 +QUICK_STEPS = 6 # a lookup: a search, a read or two, and room for one more phrasing _CHITCHAT = SMALL_TALK # greetings and thanks: the same pattern chat memory uses to decide what may be skipped _GREETING = re.compile(r"^\s*(hi|hey|hello|yo|hiya|good (morning|afternoon|evening))", re.IGNORECASE) @@ -468,9 +508,22 @@ def asks_to_rewrite(message: str) -> bool: r"articles?|essays?|newsletters?|writing)\b", re.IGNORECASE) +_LEADING_REF = re.compile(r"^\s*(and |but |so |ok(ay)?,? |also )?(what about|how about|why|it|its|that|this|these|" + r"those|they|them|their|he|she|him|his|her)\b", re.IGNORECASE) +_EXPLICIT_REF = re.compile(r"\b(you (said|mentioned|wrote)|that (post|one|point|answer|part|article)|the (last|previous|" + r"first|second|third) (one|point|answer|post|part)|above|earlier|again|more on|tell me more|" + r"say more|go on)\b", re.IGNORECASE) +REFERS_SHORT_WORDS = 7 + + def refers_back(message: str) -> bool: - """The message only makes sense with the conversation ("explain how to use it", "a brief intro of him").""" - return bool(_REFERS.search(_NOTEBOOK_WORDS.sub(" ", message))) + """The message only makes sense with the conversation ("explain how to use it", "a brief intro of him", "why?"). + A pronoun inside a longer, self-contained question ("how do I price it when I have 1,000 readers") is not + enough: such a question used to get the previous question mixed into its search and was never cached.""" + text = _NOTEBOOK_WORDS.sub(" ", message) + if _EXPLICIT_REF.search(text) or _LEADING_REF.match(text): + return True + return len(re.findall(r"[\w']+", text)) <= REFERS_SHORT_WORDS and bool(_REFERS.search(text)) _NOTESTACK_NAME = re.compile( @@ -597,7 +650,8 @@ def _phrase_rules(route: Triage, message: str, history: list[Turn]) -> Triage: return route -def triage(message: str, history: list[Turn], notebook: str, mem: ChatMemory | None = None) -> Triage: +def triage(message: str, history: list[Turn], notebook: str, mem: ChatMemory | None = None, + fresh: bool = False) -> Triage: """Decide whether a message is worth researching. Jev when configured (fast, typed, no generation), otherwise one cheap call on the triage LLM.""" why = "Jev is not configured (no TYPESAFE_API_KEY)" @@ -607,22 +661,25 @@ def triage(message: str, history: list[Turn], notebook: str, mem: ChatMemory | N except jev.JevError as exc: log.warning("Jev triage failed, falling back to the LLM", exc_info=True) why = f"Jev failed: {exc}" - route = triage_llm(message, history, notebook, mem) + route = triage_llm(message, history, notebook, mem, **({"fresh": True} if fresh else {})) route.engine = f"llm triage ({why})" return _phrase_rules(route, message, history) -def triage_llm(message: str, history: list[Turn], notebook: str, mem: ChatMemory | None = None) -> Triage: - """One cheap LLM call: is this worth researching, and what exactly should be researched?""" +def triage_llm(message: str, history: list[Turn], notebook: str, mem: ChatMemory | None = None, + fresh: bool = False) -> Triage: + """One cheap LLM call: is this worth researching, and what exactly should be researched? `fresh` (a retried + question) skips the LM cache so the same reply is not replayed.""" lm = triage_lm() + config = {"timeout": settings.chat_fast_timeout_seconds, **({"cache": False} if fresh else {})} try: with track_usage(lm) as usage, dspy.context(lm=lm): if mem is not None: pred = dspy.Predict(TriageWithMemory)(conversation=conversation_text(history), message=message, - notebook=notebook, topics=topics_digest(mem.tf)) + notebook=notebook, topics=topics_digest(mem.tf), config=config) else: pred = dspy.Predict(TriageMessage)(conversation=conversation_text(history), message=message, - notebook=notebook) + notebook=notebook, config=config) except Exception as exc: # If triage fails, fall back to researching the raw message rather than failing the chat. log.warning("LLM triage failed, researching the raw message", exc_info=True) @@ -660,14 +717,19 @@ def notebook_brief(title: str, allowed: dict[str, str]) -> str: ) -def notebook_brief_full(title: str, allowed: dict[str, str], corpus: Corpus) -> str: - """Every post title, each with the first two paragraphs of the post (until the budget is used).""" +def notebook_brief_full(title: str, allowed: dict[str, str], corpus: Corpus, + cards: dict[str, dict] | None = None) -> str: + """Every post title, each with its card (what the whole post is about: a post's opening often is not) and the + first two paragraphs of the post (until the budget is used).""" lines, used = [], 0 for rel, post_title in allowed.items(): opening = "" if used < RECHECK_BUDGET_CHARS: + card = (cards or {}).get(rel) + about = (f"about: {card.get('summary', '')} names: {', '.join(card.get('entities') or [])}; topics: " + f"{', '.join(card.get('topics') or [])}. " if card else "") paragraphs = [" ".join(t.strip() for t in p.lines if t.strip()) for p in passages_of(corpus, rel, post_title)[:2]] - opening = shorten(" ".join(x for x in paragraphs if x), RECHECK_OPENING_CHARS) + opening = about + shorten(" ".join(x for x in paragraphs if x), RECHECK_OPENING_CHARS) used += len(opening) lines.append(f"- {post_title}" + (f": {opening}" if opening else "")) return f"Notebook: {title}. {len(allowed)} posts:\n" + "\n".join(lines) @@ -721,16 +783,20 @@ def verify_citations(tools: ScopedTools, answer: str, citations, for c in sorted(citations, key=lambda c: c.marker): if c.marker in remap: continue + start, end, repaired = c.line_start, c.line_end, False if is_chat_path(c.path): - quote = chat_tools.quote(c.path, c.line_start, c.line_end) if chat_tools else None + quote = chat_tools.quote(c.path, start, end) if chat_tools else None else: - quote = tools.quote(c.path, c.line_start, c.line_end) + quote = tools.quote(c.path, start, end) + if not quote and (found := repair_lines(tools, answer, c)): + (start, end), repaired = found, True + quote = tools.quote(c.path, start, end) if not quote: continue new = len(verified) + 1 remap[c.marker] = new - end = max(c.line_start, min(c.line_end, c.line_start + 40)) - verified.append(VerifiedCitation(new, c.path, c.line_start, end, quote[:600])) + end = max(start, min(end, start + 40)) + verified.append(VerifiedCitation(new, c.path, start, end, quote[:600], repaired)) def swap(m: re.Match) -> str: n = remap.get(int(m.group(1))) @@ -751,6 +817,36 @@ def _words(text: str) -> set[str]: return {w for w in _WORD.findall(text.lower()) if w not in _STOP} +REPAIR_MIN_WORDS = 3 # content words a cited sentence must share with a line of the post +REPAIR_MIN_SHARE = 0.3 # and the share of the sentence's content words that line must hold +_CLAIMS = re.compile(r"(?<=[.!?])\s+|\n+") + + +def repair_lines(tools: ScopedTools, answer: str, c) -> tuple[int, int] | None: + """New lines for a citation whose path is right but whose line numbers do not exist (a common slip on long posts): + the line of that post that shares the most words with the sentences carrying its [n] marker. None when nothing + matches well enough, so a wrong source is never invented.""" + corpus = getattr(tools, "corpus", None) + if corpus is None: + return None + try: + lines = corpus.read_lines(tools._check(c.path)) + except CorpusError: + return None + marker = f"[{c.marker}]" + claim = _words(" ".join(_MARKER.sub(" ", part) for part in _CLAIMS.split(answer) if marker in part)) + if len(claim) < REPAIR_MIN_WORDS: + return None + best, at = 0, -1 + for i, line in enumerate(lines): + shared = len(claim & _words(line)) + if shared > best: + best, at = shared, i + if best < REPAIR_MIN_WORDS or best / len(claim) < REPAIR_MIN_SHARE: + return None + return at + 1, at + 1 + + def ensure_markers(text: str, cites: list[VerifiedCitation]) -> str: """Every verified citation is shown in the answer as a [n] marker. The model sometimes writes none, or writes numbers that do not match its citations and the verifier drops them. Whatever is missing is put back on the @@ -858,6 +954,7 @@ def __init__(self, on_delta: Callable[[str | None], None] | None, trace: ChatTra self.sent = False self.prompt_tokens = self.completion_tokens = 0 self.topic = "" # from the last write that succeeded + self.last_failure = "" # why the last write returned None: uncovered | context | error def _emit(self, text: str) -> None: self.sent = True @@ -875,14 +972,26 @@ def write(self, inputs: dict, evidence: str, length: str, label: str, prompt is over the context window (it raises ValueError when there is nothing left to cut). stop_if_uncovered: a one-call path stops at the model's first line when it says the material does not answer the question.""" why = "unknown" - for _ in range(3): + self.last_failure = "error" + for attempt in range(3): try: - res = writer.stream_answer(inputs, evidence, self._emit, length, stop_if_uncovered) + with self.trace.observe(f"writer: {label}", as_type="generation", model=writer_model(), + input=lf.text(evidence), + metadata={"answer_length": length, "attempt": attempt + 1, + "stop_if_uncovered": stop_if_uncovered, + "evidence_chars": len(evidence)}) as gen: + res = writer.stream_answer(inputs, evidence, self._emit, length, stop_if_uncovered) + gen.update(output=lf.text(res.answer), + usage_details={"input": res.prompt_tokens, "output": res.completion_tokens}, + metadata={"citations": len(res.citations), "unsupported": res.unsupported, + "chunks": res.chunks}) except writer.WriterUncovered: why = "the model's first line said these passages do not answer it, so it stopped before any text" + self.last_failure = "uncovered" break except ContextWindowExceededError: why = "over the context window" + self.last_failure = "context" if self.sent or shrink is None: break try: @@ -1052,6 +1161,7 @@ def research( external_destinations: list[dict] | None = None, workspace_id=None, notebook_id=None, + fresh: bool = False, ) -> ResearchResult: """on_delta gets the answer text as it is written (None = take back what was sent, a different path writes it). The returned text is the verified answer, which replaces whatever was streamed.""" @@ -1124,14 +1234,33 @@ def research( synced = pool.submit(contextvars.copy_context().run, corpus.sync, tuple(allowed)) pool.shutdown(wait=False) with trace.stage("triage"): - route = triage(question, history, notebook_brief(notebook_title, allowed), chat_memory) + route = triage(question, history, notebook_brief(notebook_title, allowed), chat_memory, + **({"fresh": True} if fresh else {})) + early_cards: dict[str, dict] = {} + if route.kind == "off_topic" and allowed: + # Triage saw only the post titles. If the question's own subject words occur anywhere in the posts (a resume + # titled "Muhammad Mehdi Resume" that mentions Blog2Video), it is about the notebook: research it. + with trace.stage("off-topic-guard"): + try: + manifest_now = synced.result() or {} + early_cards = load_cards(corpus, allowed) if settings.post_cards_enabled else {} + mentioned = notebook_mentions(corpus, allowed, manifest_now, f"{question} {route.question}", + early_cards or None) + except Exception: + logging.getLogger(__name__).warning("The off topic keyword check failed", exc_info=True) + mentioned = [] + if mentioned: + route.notes.append(f"off_topic, but the posts mention {', '.join(mentioned[:6])} -> archive " + "(keyword check over the whole notebook)") + route.kind, route.reply = "archive", "" if route.kind == "off_topic" and route.engine == "jev": with trace.stage("recheck-off-topic"): try: synced.result() # the openings are read from the synced posts except Exception: logging.getLogger(__name__).warning("Posts sync failed before the off topic recheck", exc_info=True) - route = recheck_off_topic(route, question, history, notebook_brief_full(notebook_title, allowed, corpus)) + route = recheck_off_topic(route, question, history, + notebook_brief_full(notebook_title, allowed, corpus, early_cards)) named_external_app = ( names_external_app(question, external_aliases or set()) if route.kind in {"create", "external_action"} and external_tools else None @@ -1359,7 +1488,7 @@ def log(kind: str, detail: str) -> None: signature, inputs["chat_memory"] = ResearchArchiveWithMemory, notes or "(nothing filed yet)" else: signature = ResearchArchive - lm = main_lm() + lm = agent_lm() # uncached: a retried question researches again instead of replaying the same steps recall = { "route": _route_info(route), "triage_detail": _triage_detail(route), @@ -1423,7 +1552,9 @@ def finish(answer: str, proposed_cites, model_unsupported: bool, path: str, agen steps=steps, kind="external_action" if external_only else "archive", question=route.question, - recall={**recall, "path": path}, + recall={**recall, "path": path, "refused": refused, "model_unsupported": bool(model_unsupported), + "proposed_cites": len(proposed), "verified_cites": len(cites), + "repaired_cites": sum(1 for c in cites if c.repaired)}, topic=(stream.topic if stream and not refused else ""), external_sources=used_external, external_widgets=used_widgets, @@ -1449,24 +1580,117 @@ def finish(answer: str, proposed_cites, model_unsupported: bool, path: str, agen trace.sections.pop("citations", None) trace.sections.pop("result", None) - # 2. Keyword prefetch: the best passages go to the agent (and the writer) before any model call. A follow up - # ("explain how to use it") is searched together with the question before it, which names what "it" is. + # Post cards (app/pipeline/cards.py): their topics, names and synonyms go into the keyword index with the posts. + cards: dict[str, dict] = {} + if not external_only and settings.post_cards_enabled and allowed: + with trace.stage("load-cards"): + try: + cards = load_cards(corpus, allowed) + except Exception: + logging.getLogger(__name__).warning("Could not load the post cards", exc_info=True) + trace.add("context", f"post cards: {len(cards)} of {len(allowed)} posts have one") + trace.tag("cards:" + ("all" if cards and len(cards) == len(allowed) else "some" if cards else "none")) query = route.question earlier = next((t.text for t in reversed(history) if t.role == "user"), "") if earlier and refers_back(route.question): query = f"{route.question} {earlier}" + + # 2r. The router (CHAT_ROUTER): Tier A reads the whole notebook when it fits, Tier B the best posts found by + # keyword and card search. A miss goes on to the research agent (Tier C, step 6); steps 2 to 5 are skipped. + use_router = settings.chat_router and stream is not None and not external_only and chat_tools is None and allowed + if use_router: + tokens = notebook_tokens(corpus, allowed) + router: dict = {"notebook_tokens": tokens, "cards": len(cards), "posts": len(allowed), "tier": "B"} + recall["router"] = router + if tokens <= settings.chat_full_notebook_tokens: + router["tier"] = "A" + recall["prefetch"] = {"passages": len(allowed), "tier": "A"} + trace.tag("tier:A") + log("think", f"Reading all {len(allowed)} posts") + with trace.stage("tier A"): + res = stream.write(inputs, tier_a_evidence(corpus, allowed), route.detail, "tier A (whole notebook)", + stop_if_uncovered=True) + if res is not None and not res.unsupported: + result = finish(res.answer, res.citations, res.unsupported, "tier A") + if result.citations: + return result + trace.sections.pop("citations", None) + trace.sections.pop("result", None) + miss = "no citation survived verification" + elif stream.last_failure == "uncovered" or res is not None: + # The model read every post and none of them answers it: say so plainly, no agent needed. + stream.reset() + trace.add("writer", "tier A: the whole notebook was read and does not cover the question") + return finish("The posts in this notebook do not cover that.", [], True, "tier A") + else: + miss = f"the writer failed ({stream.last_failure})" + stream.reset() + trace.add("writer", f"tier A: miss ({miss}) -> tier B") + router["tier"] = "A>B" + trace.tag("tier:B") + queries = [route.question] + ([query] if query != route.question else []) + if settings.chat_query_expansion: + with trace.stage("expand-query"): + try: + more, p_tok, c_tok = expand_query(route.question, conversation_text(history, limit=4)) + queries += more + extra_prompt, extra_completion = extra_prompt + p_tok, extra_completion + c_tok + except Exception as exc: + trace.add("context", f"query expansion failed ({type(exc).__name__}): the message alone is searched") + with trace.stage("retrieve"): + found = retrieve(corpus, allowed, manifest, cards, queries) + overview = not content_words(route.question) + budget_chars = settings.chat_evidence_tokens * CHARS_PER_TOKEN + if overview: + evidence, label = overview_evidence(corpus, allowed, cards, budget_chars), "tier B overview" + else: + picked = tier_b_evidence(corpus, allowed, found, budget_chars) + evidence, label = picked.text, "tier B" + router.update(evidence_posts=len(picked.posts), whole_posts=picked.whole) + router["queries"] = len(queries) + recall["prefetch"] = {"passages": found.passage_count, "posts": len(found.posts), "queries": len(queries), + "terms": found.terms} + trace.add("context", f"{label}: {len(queries)} search(es), {len(found.posts)} post(s) ranked, " + f"{found.passage_count} passage(s) matched, evidence {len(evidence)} chars" + f" [BM25 over passages + post cards, fused]") + if evidence: + log("think", "Found matching posts" if found.posts else "Looking across the notebook") + with trace.stage(label): + res = stream.write(inputs, evidence, route.detail, label, stop_if_uncovered=True) + if res is not None and not res.unsupported: + result = finish(res.answer, res.citations, res.unsupported, label) + if result.citations: + return result + trace.sections.pop("citations", None) + trace.sections.pop("result", None) + stream.reset() + inputs["prefetched"] = evidence[:AGENT_PREFETCH_CHARS] + trace.add("writer", f"{label}: miss ({stream.last_failure or 'no verified citation'}) -> research agent " + "(tier C)") + router["tier"] += ">C" + trace.tag("tier:C") + + # 2. Keyword prefetch: the best passages go to the agent (and the writer) before any model call. A follow up + # ("explain how to use it") is searched together with the question before it, which names what "it" is. deep = route.depth == "deep" pre = None - if not external_only: + if use_router: + pass # the router above already gathered the evidence + elif not external_only: with trace.stage("prefetch"): try: - pre = prefetch(corpus, allowed, manifest, query, *((DEEP_TOP_K, DEEP_PER_POST) if deep else ())) + pre = prefetch(corpus, allowed, manifest, query, *((DEEP_TOP_K, DEEP_PER_POST) if deep else ()), + **({"cards": cards} if cards else {})) except Exception: # a ranking problem only costs the head start logging.getLogger(__name__).warning("Prefetch failed", exc_info=True) pre = None else: trace.add("context", "archive prefetch skipped: Jev classified the request as an external action, " "so only enabled external tools are available") + if not use_router: + recall["prefetch"] = ({"passages": len(pre.passages), "posts": len({p.path for _, p in pre.passages}), + "coverage": round(pre.coverage, 2), "terms": len(pre.terms), "asked": len(pre.asked)} + if pre is not None else {"passages": 0, "skipped": external_only}) if pre is not None: inputs["prefetched"] = pre.text trace.add("context", f"prefetch: {len(pre.passages)} passage(s) from " @@ -1518,7 +1742,7 @@ def finish(answer: str, proposed_cites, model_unsupported: bool, path: str, agen # 3. Overview: a question about the notebook as a whole (no subject to search for) is answered in one call from # the post list and the opening passage of the newest posts. one_call = (not external_only and stream is not None and settings.chat_fast_path - and route.detail != "in_depth" and chat_tools is None) + and route.detail != "in_depth" and chat_tools is None and not use_router) if one_call and pre is not None and pre.overview: listing = tools.list_files() # shows as the one step: scanning the archive listed = [(row.split("|")[1].strip(), row.split("|")[2].strip()) for row in listing.splitlines() @@ -1559,7 +1783,7 @@ def finish(answer: str, proposed_cites, model_unsupported: bool, path: str, agen f"chat tools {'given' if chat_tools else 'not given'})") # 5. A question about several separate subjects: research the parts at once, then write one answer. - if (stream and settings.chat_parallel_parts and route.depth == "deep" and chat_tools is None + if (stream and settings.chat_parallel_parts and route.depth == "deep" and chat_tools is None and not use_router and not external_tools and looks_multipart(route.question)): with trace.stage("split"): diff --git a/backend/app/pipeline/trace.py b/backend/app/pipeline/trace.py index ec8a4cf..d8634e3 100644 --- a/backend/app/pipeline/trace.py +++ b/backend/app/pipeline/trace.py @@ -4,14 +4,21 @@ Logger `notestack.chat_trace`. The structure is always logged. Writers' text (the message, the note values) is added only when text logging is on (the same switch as `notestack.chat_context`: CHAT_CONTEXT_LOG, or development). -`notestack.chat_context` still holds the full text of everything the agent was given, for when you need to read it.""" +`notestack.chat_context` still holds the full text of everything the agent was given, for when you need to read it. + +The same trace also goes to Langfuse when it is configured (app/observability/langfuse_client.py): the message is the +root observation, every stage() a span, every agent step an event, every answer-writer call a generation, and the +outcome code (why an answer did or did not come out) a trace tag. Without Langfuse all of that is a no-op.""" import logging import time from contextlib import contextmanager from contextvars import ContextVar +from typing import Any from app.chat_memory.logs import text_enabled +from app.config import settings +from app.observability import langfuse_client as lf trace_log = logging.getLogger("notestack.chat_trace") @@ -34,6 +41,56 @@ "result": "7 RESULT", "save": "8 SAVED", "notes": "9 AFTER THE ANSWER"} +# Why a message ended the way it did. Saved as recall_json["outcome"] and sent to Langfuse as the tag outcome:. +OUTCOMES = { + "answered": "an archive answer with verified citations", + "cache_hit": "an earlier identical answer was reused", + "writer_uncovered": "the model said the material it was given does not answer the question", + "refused_no_cites": "the model answered without any citation, so the 'could not find support' reply was sent", + "cites_dropped": "the model cited lines, none passed verification, so the 'could not find support' reply was sent", + "triage_off_topic": "triage called the message off topic, so no research ran", + "triage_other": "small talk, app help or a create request: no research needed", + "external_done": "a connected app did the work", + "external_failed": "a connected app was asked but nothing usable came back", + "agent_malformed": "the research agent's replies could not be read", + "exception": "the chat raised; no answer was saved", + "timeout": "a model request took longer than CHAT_LLM_TIMEOUT_SECONDS; no answer was saved", +} + +# What each outcome means for whoever reads Langfuse: pass (the question got what it needed), fail (it did not: no +# answer, an unsupported answer, a crash) or review (turned away as off topic: right for "capital of France", wrong +# when the notebook did cover it). Shown as the trace name, its level (fail = ERROR, review = WARNING) and a score. +VERDICTS = {"answered": "pass", "cache_hit": "pass", "external_done": "pass", "triage_other": "pass", + "triage_off_topic": "review"} + + +def verdict_of(outcome: str) -> str: + return VERDICTS.get(outcome, "fail") if outcome else "" + + +# Trace sections that never hold writers' text: sent to Langfuse even when text is masked. +_SAFE_SECTIONS = ("route", "triage", "writer", "result") + + +class _NoObservation: + """What stage() and observe() yield when Langfuse is off: accepts any update and does nothing.""" + + def update(self, **_kwargs) -> "_NoObservation": + return self + + +_NONE = _NoObservation() + + +def _safe(fn, *args, **kwargs): + """A Langfuse call that must never break a chat.""" + try: + return fn(*args, **kwargs) + except Exception: + logging.getLogger(__name__).warning("Langfuse call failed", exc_info=True) + return None + + def ms(value: float) -> str: return f"{value:.0f}ms" if value < 1000 else f"{value / 1000:.1f}s" @@ -47,20 +104,122 @@ def __init__(self, chat_id: str = "", notebook: str = "", message: str = ""): self.marks: dict[str, float] = {} self.agent_started: float | None = None self.error = "" + # Langfuse (all empty when it is off) + self.trace_id = "" + self.outcome = "" + self.tags: list[str] = [] + self.output: str | None = None + self._root: Any = None + + # Langfuse + + def start_langfuse(self, *, user: Any = None, session: str = "", metadata: dict | None = None) -> str: + """Open this message's Langfuse trace. Returns its id ("" when Langfuse is off).""" + client = lf.client() + if client is None or self._root is not None: + return self.trace_id + trace_id = _safe(client.create_trace_id) + if not trace_id: + return "" + root = _safe(client.start_observation, trace_context={"trace_id": trace_id}, name="notebook-chat", + as_type="chain", input=lf.text(self.message), metadata=metadata or {}) + if root is None: + return "" + self.trace_id, self._root = trace_id, root + attrs = {"langfuse.trace.name": "notebook-chat", "session.id": session} + if user is not None: + attrs["user.id"] = lf.pseudonym(user) + for key, value in attrs.items(): + if value: + _safe(root._otel_span.set_attribute, key, value) + return trace_id + + def tag(self, *tags: str) -> None: + self.tags += [t for t in tags if t and t not in self.tags] + + def set_outcome(self, outcome: str) -> None: + self.outcome = outcome + self.tag(f"outcome:{outcome}") + + @contextmanager + def observe(self, name: str, as_type: str = "span", **kwargs): + """A child observation of the message (a span, or a generation for a model call). Yields an object with + update(); the observation ends when the block does, marked as an error if the block raised.""" + obs = _safe(self._root.start_observation, name=name, as_type=as_type, **kwargs) if self._root else None + try: + yield obs or _NONE + except BaseException as exc: + if obs is not None: + _safe(obs.update, level="ERROR", status_message=f"{type(exc).__name__}: {exc}"[:500]) + raise + finally: + if obs is not None: + _safe(obs.end) + + def _event(self, name: str, detail: str) -> None: + if self._root is None: + return + event = _safe(self._root.start_observation, name=name, as_type="event", input=lf.text(detail)) + if event is not None: + _safe(event.end) + + def _finish_langfuse(self) -> None: + root, self._root = self._root, None + if root is None: + return + safe_only = settings.langfuse_mask_text + sections = {k: v for k, v in self.sections.items() if not safe_only or k in _SAFE_SECTIONS} + metadata = {"stages_ms": {name: round(took) for name, took in self.stages}, + "marks_ms": {name: round(at) for name, at in self.marks.items()}, + "outcome": self.outcome, "sections": sections} + verdict = verdict_of(self.outcome) or ("fail" if self.error else "") + name = f"{verdict.upper()} · {self.outcome or 'error'}" if verdict else "notebook-chat" + if verdict: + self.tag(f"verdict:{verdict}") + update: dict[str, Any] = {"name": name, "output": lf.text(self.output), "metadata": metadata, + "status_message": (self.error or OUTCOMES.get(self.outcome, ""))[:500]} + if verdict == "fail": + update["level"] = "ERROR" + elif verdict == "review": + update["level"] = "WARNING" + _safe(root.update, **update) + _safe(root._otel_span.set_attribute, "langfuse.trace.name", name) + if self.tags: + _safe(root._otel_span.set_attribute, "langfuse.trace.tags", list(self.tags)) + _safe(root.end) + if verdict: + lf.score(self.trace_id, "verdict", verdict, data_type="CATEGORICAL", + comment=OUTCOMES.get(self.outcome, self.error)[:500] or None, score_id=f"{self.trace_id}-verdict") # Recording @contextmanager def stage(self, name: str): + """A timed stage of the message: a line in the log's TIMING row, and a span in Langfuse.""" start = time.perf_counter() try: - yield + with self.observe(name) as obs: + yield obs finally: self.stages.append((name, (time.perf_counter() - start) * 1000)) def mark(self, name: str) -> None: - """A moment on the clock, in ms since the message arrived (e.g. when the answer was sent).""" + """A moment on the clock, in ms since the message arrived (e.g. when the answer was sent). In Langfuse it is an + event, so the tree shows when the first words and the full answer reached the writer.""" self.marks[name] = (time.perf_counter() - self.t0) * 1000 + label = {"first-delta": "first answer text sent", "answer": "answer sent"}.get(name, name) + self._event(f"{label} ({ms(self.marks[name])})", name) + + def begin(self, name: str): + """A stage that cannot be a `with` block (it spans code that yields): call the returned function to end it.""" + start = time.perf_counter() + obs = _safe(self._root.start_observation, name=name, as_type="span") if self._root else None + + def end() -> None: + self.stages.append((name, (time.perf_counter() - start) * 1000)) + if obs is not None: + _safe(obs.end) + return end def add(self, section: str, *lines: str) -> None: self.sections.setdefault(section, []).extend(lines) @@ -72,6 +231,7 @@ def step(self, kind: str, detail: str) -> None: offset = (time.perf_counter() - (self.agent_started or self.t0)) * 1000 source = STEP_SOURCE.get(kind, "") self.add("steps", f"+{ms(offset):>6} {kind:<6} {detail}" + (f" [{source}]" if source else "")) + self._event(f"step:{kind}", detail) # Output @@ -81,6 +241,9 @@ def render(self) -> str: head = f"CHAT TRACE chat={self.chat_id[:8] or '-'} notebook={self.notebook!r}" shown = f" {self.message[:140]!r}" if text_enabled() else "" lines = [head, f" message : {len(self.message)} chars{shown}"] + if self.outcome: + lines.append(f" outcome : {self.outcome} ({OUTCOMES.get(self.outcome, '?')})" + + (f" langfuse trace {self.trace_id}" if self.trace_id else "")) first = self.marks.get("first-delta") if answered is not None: lines.append(" clock : " + (f"first answer text after {ms(first)}, " if first is not None else "") @@ -102,6 +265,7 @@ def emit(self) -> None: trace_log.info(self.render()) except Exception: # a log line must never break a chat logging.getLogger(__name__).warning("Could not write the chat trace", exc_info=True) + self._finish_langfuse() # research() runs in a worker thread (asyncio.to_thread copies the context), so the request hands its trace over diff --git a/backend/app/pipeline/writer.py b/backend/app/pipeline/writer.py index aa3a684..2da66fb 100644 --- a/backend/app/pipeline/writer.py +++ b/backend/app/pipeline/writer.py @@ -18,6 +18,7 @@ import litellm +from app.config import settings from app.llm.postprocess import strip_em_dashes from app.llm.provider import writer_lm from app.llm.signatures import ANSWER_INSTRUCTIONS, ANSWER_LENGTHS, FileCitation @@ -198,6 +199,7 @@ def stream_answer(inputs: dict, evidence: str, on_delta: Callable[[str], None], it), and LiteLLM's errors (ContextWindowExceededError included) as they are.""" lm = writer_lm() kwargs = dict(lm.kwargs) + kwargs["timeout"] = settings.chat_llm_timeout_seconds cap = WRITER_MAX_TOKENS.get(answer_length if answer_length in ANSWER_LENGTHS else "standard") if cap: key = "max_completion_tokens" if "max_completion_tokens" in kwargs else "max_tokens" diff --git a/backend/app/routers/notebooks.py b/backend/app/routers/notebooks.py index b31c4ca..8967877 100644 --- a/backend/app/routers/notebooks.py +++ b/backend/app/routers/notebooks.py @@ -2,6 +2,7 @@ import hashlib import json import logging +import random import re import time import uuid @@ -40,8 +41,17 @@ Source, Topic, ) +from app.observability import langfuse_client as lf from app.pipeline.generate import ideas_fresh -from app.pipeline.research import LastAnswer, ResearchResult, Turn, VerifiedCitation, refers_back, research +from app.pipeline.research import ( + LastAnswer, + ResearchResult, + Turn, + VerifiedCitation, + outcome_of, + refers_back, + research, +) from app.pipeline.trace import ChatTrace, use_trace from app.routers.sources import list_columns, serialize_list_rows from app.services import report_suggestions @@ -501,6 +511,9 @@ def rate_message(message_id: uuid.UUID, body: FeedbackIn, ctx: Ctx = Depends(get row.comment = (body.comment or "").strip() or None row.question, row.answer, row.sources, row.recall = question, msg.content, sources, msg.recall_json or {} db.commit() + note = ", ".join(reasons) + (f": {row.comment}" if row.comment and not settings.langfuse_mask_text else "") + lf.score((msg.recall_json or {}).get("trace_id"), "user_feedback", float(row.rating), comment=note or None, + score_id=f"{msg.id}-user_feedback") return {"feedback": _feedback_out(row)} @@ -545,7 +558,8 @@ def _sse(event: str, data: dict) -> str: _detached_streams: set[asyncio.Task] = set() # the loop only holds tasks weakly: these must not be collected mid-answer -def _detached(stream: AsyncIterator[str], keepalive: float = CHAT_KEEPALIVE_SECONDS) -> AsyncIterator[str]: +def _detached(stream: AsyncIterator[str], keepalive: float = CHAT_KEEPALIVE_SECONDS, + on_leave=None) -> AsyncIterator[str]: """Runs a stream on its own, so a phone that locks or loses signal stops only the reading: the answer is still researched and saved, for the app to find when it comes back. Long silences send an SSE comment, which clients ignore, so that nothing along the way takes the quiet connection for a dead one.""" @@ -563,15 +577,21 @@ async def pump() -> None: task.add_done_callback(_detached_streams.discard) async def read() -> AsyncIterator[str]: - while True: - try: - chunk = await asyncio.wait_for(chunks.get(), timeout=keepalive) - except TimeoutError: - yield ": keepalive\n\n" - continue - if chunk is None: - return - yield chunk + finished = False + try: + while True: + try: + chunk = await asyncio.wait_for(chunks.get(), timeout=keepalive) + except TimeoutError: + yield ": keepalive\n\n" + continue + if chunk is None: + finished = True + return + yield chunk + finally: + if not finished and on_leave is not None: # the client stopped reading before the stream ended + on_leave() return read() @@ -616,12 +636,18 @@ def _saved_step_messages(recall: dict | None) -> list[str]: return messages +# Part of every answer cache key: raise it when retrieval changes, so answers from the old pipeline are not reused. +PIPELINE_VERSION = "2" + + def answer_cache_key(notebook_id: uuid.UUID, question: str, docs: list[Document], profile: str) -> str: - """Same notebook, same question (case, spacing and end punctuation aside), same post versions, same writer notes.""" + """Same notebook, same question (case, spacing and end punctuation aside), same post versions, same writer notes, + same retrieval pipeline (PIPELINE_VERSION and whether the router is on).""" q = re.sub(r"\s+", " ", question.lower()).strip().rstrip("?!. ") posts = "\n".join(sorted(f"{d.path}\t{d.content_hash or ''}\t{d.updated_at.isoformat() if d.updated_at else ''}" for d in docs)) - return hashlib.sha256(f"{notebook_id}\n{q}\n{posts}\n{profile}".encode()).hexdigest() + pipeline = f"{PIPELINE_VERSION}:{'router' if settings.chat_router else 'prefetch'}" + return hashlib.sha256(f"{notebook_id}\n{q}\n{posts}\n{profile}\n{pipeline}".encode()).hexdigest() def _cached_answer(db, key: str) -> tuple[Message, ResearchResult] | None: @@ -687,6 +713,19 @@ async def _learn(db, workspace_id: uuid.UUID, message_id: uuid.UUID, kind: str, return [] +def _size_bucket(posts: int) -> str: + return "0" if posts == 0 else "1-10" if posts <= 10 else "11-50" if posts <= 50 else "51-200" if posts <= 200 else "200+" + + +JUDGED_OUTCOMES = {"answered", "writer_uncovered", "refused_no_cites", "cites_dropped"} + + +def should_judge(outcome: str) -> bool: + """A sample of archive answers (and of refusals, to catch false ones) is scored by the LLM judge in the worker.""" + return (outcome in JUDGED_OUTCOMES and lf.enabled() and bool(settings.llm_api_key) + and random.random() < settings.chat_judge_sample_rate) + + @router.post("/{notebook_id}/chat") async def chat(notebook_id: uuid.UUID, body: ChatIn, ctx: Ctx = Depends(get_ctx)): nb = _get(ctx, notebook_id) @@ -727,14 +766,20 @@ async def _run(): body.retry_message_id, chat_row.id) chat_row.updated_at = datetime.now(UTC) # keeps the history list newest first trace.chat_id = str(chat_row.id) + trace.start_langfuse(user=ctx.user.id, session=str(chat_row.id), + metadata={"notebook_id": str(nb.id), "retry": retrying}) yield _sse("status", {"chat_id": str(chat_row.id), "message": "Preparing research"}) # Memory: the chat so far (before this message), oldest first, capped to the last few turns. - with trace.stage("db-history+notes"): + # Two stages, not one: the first query of the stream also waits for a database connection (the request's own + # was given back before the stream started), so a slow "db-history" next to a fast "db-notes" means the time + # went on connecting (network distance, a database waking up), not on the queries. + with trace.stage("db-history"): prior = db.scalars( select(Message).where(Message.chat_id == chat_row.id).order_by(Message.created_at.desc()).limit(8) ).all() history = [Turn(m.role, m.content, (m.recall_json or {}).get("background_status")) for m in reversed(prior)] + with trace.stage("db-notes"): facts = list_facts(db, ctx.workspace.id) profile = profile_text(facts) # Chat memory (topic summaries and exact quotes from earlier in this notebook's chats), loaded here so the @@ -753,6 +798,7 @@ async def _run(): ).all() allowed = {d.path: d.title for d in docs} by_path = {d.path: d for d in docs} + trace.tag(f"posts:{_size_bucket(len(docs))}") corpus = Corpus(ctx.workspace.id) last_answer = _last_answer(db, prior) external_bundle = load_external_tools(ctx.workspace.id, ctx.user.id, db, notebook_id=nb.id) @@ -812,6 +858,7 @@ def on_delta(text: str | None) -> None: external_destinations=[destination.as_dict() for destination in external_bundle.destinations], workspace_id=ctx.workspace.id, notebook_id=nb.id, + fresh=retrying, **({"chat_memory": chat_memory} if chat_memory is not None else {}))) await asyncio.sleep(0) # let the research thread start before the commit below holds this loop with trace.stage("save-question(while research runs)"): @@ -831,13 +878,23 @@ def on_delta(text: str | None) -> None: yield _sse("step", {"kind": kind, "message": _step_message(kind, detail)}) try: result = task.result() - except Exception: + except Exception as exc: log.exception("Research failed for chat %s: %r", chat_row.id, body.question[:200]) # cause, not just "lost signal" - trace.error = "research raised (see the traceback above); no answer was saved" - yield _sse("error", {"message": "Something went wrong while researching. Try again."}) + timed_out = "timeout" in type(exc).__name__.lower() + trace.error = ("a model request timed out" if timed_out + else "research raised (see the traceback above)") + "; no answer was saved" + trace.set_outcome("timeout" if timed_out else "exception") + yield _sse("error", {"message": "That took too long to answer. Try again in a moment." if timed_out + else "Something went wrong while researching. Try again."}) return - save_started = time.perf_counter() + end_save = trace.begin("save-answer") + outcome = "cache_hit" if cached is not None else outcome_of(result) + trace.set_outcome(outcome) + trace.tag(f"kind:{result.kind}", f"path:{'cache' if cached is not None else (result.recall or {}).get('path') or result.kind}") + if result.kind == "archive" and cached is None and not ((result.recall or {}).get("prefetch") or {}).get("passages"): + trace.tag("retrieval_empty") + trace.output = result.text cacheable = result.kind == "archive" and not result.unsupported and bool(result.citations) initial_background = ({ "state": "working", @@ -846,7 +903,8 @@ def on_delta(text: str | None) -> None: msg = Message(chat_id=chat_row.id, role="assistant", content=result.text, cache_key=cache_key if cacheable else None, recall_json={**result.recall, "kind": result.kind, "unsupported": result.unsupported, - "topic": result.topic, + "topic": result.topic, "outcome": outcome, + **({"trace_id": trace.trace_id} if trace.trace_id else {}), "external_sources": result.external_sources, "external_widgets": result.external_widgets, "created_artifacts": result.created_artifacts, @@ -909,6 +967,13 @@ def on_delta(text: str | None) -> None: log.warning("Could not queue chat memory", exc_info=True) db.rollback() trace.add("save", "chat-memory filing job: could not be queued (see the warning above)") + if cached is None and should_judge(outcome): + try: + create_job(db, ctx.workspace.id, "chat_judge", {"message_id": str(msg.id)}, max_attempts=1) + trace.add("save", "judge job queued: relevance, faithfulness or false refusal goes to Langfuse") + except Exception: # scoring is a bonus: never cost the writer their answer + log.warning("Could not queue the chat judge", exc_info=True) + db.rollback() if result.prompt_tokens or result.completion_tokens: record_usage( db, @@ -919,8 +984,9 @@ def on_delta(text: str | None) -> None: quantity=result.prompt_tokens + result.completion_tokens, unit="tokens", ) - trace.stages.append(("save-answer", (time.perf_counter() - save_started) * 1000)) + end_save() trace.mark("answer") + answer_sent["yes"] = True # set first: from here on a failure must never replace the answer on screen yield _sse("answer", { "message_id": str(msg.id), "text": result.text, @@ -935,13 +1001,15 @@ def on_delta(text: str | None) -> None: # How many questions the plan has left ({used, limit, left}), or None when chat is unlimited. "quota": chat_quota(db, ctx.workspace) if plan.chat_messages >= 0 else None, }) - wait_started = time.perf_counter() + end_wait = trace.begin("notes-wait(after answer)") saved = await _learn(db, ctx.workspace.id, user_msg.id, result.kind, trace) - trace.stages.append(("notes-wait(after answer)", (time.perf_counter() - wait_started) * 1000)) + end_wait() if saved: yield _sse("memory", {"saved": saved}) yield _sse("done", {}) + answer_sent = {"yes": False} + async def stream(): try: async for chunk in _run(): @@ -950,11 +1018,18 @@ async def stream(): log.exception("Chat failed for notebook %s: %r", nb.id, body.question[:200]) trace.error = trace.error or "the chat stream raised (see the traceback above)" db.rollback() - yield _sse("error", {"message": "Something went wrong while researching. Try again."}) + if answer_sent["yes"]: # the answer is saved and shown: only the after-answer extras failed + trace.tag("error_after_answer") + yield _sse("done", {}) + else: + if not trace.outcome: + trace.set_outcome("exception") + yield _sse("error", {"message": "Something went wrong while researching. Try again."}) finally: trace.emit() # one block per message, also when the client left or research failed db.commit() # gives the connection back: this outlives the request, whose cleanup ran before the stream began # X-Accel-Buffering: nginx would otherwise hold the streamed answer back until the response ends. - return StreamingResponse(_detached(stream()), media_type="text/event-stream", + return StreamingResponse(_detached(stream(), on_leave=lambda: trace.tag("client_left")), + media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) diff --git a/backend/app/routers/sources.py b/backend/app/routers/sources.py index f449fdd..f910f72 100644 --- a/backend/app/routers/sources.py +++ b/backend/app/routers/sources.py @@ -1,5 +1,6 @@ import hashlib import json +import logging import uuid from datetime import datetime from typing import Literal @@ -28,6 +29,8 @@ from app.services.storage import storage from app.services.url_policy import classify_url +log = logging.getLogger(__name__) + router = APIRouter(prefix="/api/sources", tags=["sources"]) @@ -423,6 +426,8 @@ def _queue_notebooklm_processing(ctx: Ctx, changed: list[uuid.UUID]) -> None: ids = [str(doc_id) for doc_id in changed] create_job(ctx.db, ctx.workspace.id, "topics", {"document_ids": ids}, max_attempts=2) create_job(ctx.db, ctx.workspace.id, "ideas", {"document_ids": ids}, max_attempts=2) + if settings.post_cards_enabled: + create_job(ctx.db, ctx.workspace.id, "post_cards", {"document_ids": ids}, max_attempts=2) if not pending_job(ctx.db, ctx.workspace.id, "resurface_scan"): create_job(ctx.db, ctx.workspace.id, "resurface_scan", {}, max_attempts=2) @@ -655,6 +660,9 @@ def get_document(document_id: uuid.UUID, ctx: Ctx = Depends(get_ctx)): lines = corpus.read_lines(doc.path) except CorpusError: lines = [] + except Exception: # storage trouble: the post's own text is in the database, show that instead of a 500 + log.exception("document %s: corpus read failed, showing clean_text", doc.id) + lines = [] if not lines: lines = [f"# {doc.title}", "", *(doc.clean_text or "").splitlines()] return {**serialize_document(doc, source), "lines": lines} diff --git a/backend/app/services/jev.py b/backend/app/services/jev.py index 48bd80e..3597897 100644 --- a/backend/app/services/jev.py +++ b/backend/app/services/jev.py @@ -5,12 +5,16 @@ question id with "choice", "confidence" and "probabilities". https://docs.typesafe.ai/primitives/choice """ +import time from dataclasses import dataclass import httpx from app.config import settings +ATTEMPTS = 2 +RETRY_DELAY = 0.3 + class JevError(RuntimeError): pass @@ -36,11 +40,20 @@ def decide(state: str | dict, questions: dict[str, dict], timeout: float = 6.0) "model": settings.typesafe_model, "questions": {qid: {"type": "choice", **q} for qid, q in questions.items()}, } - try: - resp = httpx.post(f"{settings.typesafe_url.rstrip('/')}/v1/systemone", json=body, timeout=timeout, - headers={"Authorization": f"Bearer {settings.typesafe_api_key}"}) - except httpx.HTTPError as exc: - raise JevError(f"Jev unreachable: {exc}") from exc + resp = None + for attempt in range(1, ATTEMPTS + 1): # a dropped connection or a 5xx gets one more try before the LLM fallback + try: + resp = httpx.post(f"{settings.typesafe_url.rstrip('/')}/v1/systemone", json=body, timeout=timeout, + headers={"Authorization": f"Bearer {settings.typesafe_api_key}"}) + except httpx.HTTPError as exc: + if attempt < ATTEMPTS: + time.sleep(RETRY_DELAY) + continue + raise JevError(f"Jev unreachable: {exc}") from exc + if resp.status_code >= 500 and attempt < ATTEMPTS: + time.sleep(RETRY_DELAY) + continue + break if resp.status_code >= 400: raise JevError(f"Jev {resp.status_code}: {resp.text[:300]}") answers = resp.json().get("answers") or {} diff --git a/backend/app/services/storage.py b/backend/app/services/storage.py index 9a9fa9c..09e6289 100644 --- a/backend/app/services/storage.py +++ b/backend/app/services/storage.py @@ -56,6 +56,13 @@ def workspace_owns_key(workspace_id: uuid.UUID, key: str) -> bool: return key.startswith(f"ws/{workspace_id}/") and ".." not in key +def is_not_found(exc: BaseException) -> bool: + """True when a read failed because the object does not exist (R2 or the local stand in).""" + if isinstance(exc, FileNotFoundError): + return True + return isinstance(exc, ClientError) and exc.response.get("Error", {}).get("Code") in {"404", "NoSuchKey", "NotFound"} + + class Storage: def __init__(self, bucket: str | None = None): self.bucket = bucket or settings.r2_bucket @@ -101,7 +108,7 @@ def head(self, key: str) -> dict | None: try: return self.client.head_object(Bucket=self.bucket, Key=self._k(key)) except ClientError as exc: - if exc.response.get("Error", {}).get("Code") in {"404", "NoSuchKey", "NotFound"}: + if is_not_found(exc): return None raise diff --git a/backend/app/worker.py b/backend/app/worker.py index 81cb9d1..677c090 100644 --- a/backend/app/worker.py +++ b/backend/app/worker.py @@ -49,6 +49,8 @@ WorkspaceMember, ) from app.pipeline import compound_action, flashcards, generate, infographic, launchkit, media, quiz, report, slides +from app.pipeline.cards import cards_for_documents +from app.pipeline.chat_judge import judge_message from app.pipeline.generate import NothingToDo from app.pipeline.ingest import FeedNotFound, UnreadableFile, entry_from_upload, extract_article, ingest_source, store_entries from app.pipeline.memory import learn_from_message @@ -94,6 +96,8 @@ def _after_import(db: Session, job: Job, workspace_id: uuid.UUID, changed: list[ return create_job(db, workspace_id, "topics", {"document_ids": changed}, max_attempts=2) create_job(db, workspace_id, "ideas", {"document_ids": changed}, max_attempts=2) + if settings.post_cards_enabled: + create_job(db, workspace_id, "post_cards", {"document_ids": changed}, max_attempts=2) if not pending_job(db, workspace_id, "resurface_scan"): create_job(db, workspace_id, "resurface_scan", {}, max_attempts=2) vp = db.scalar(select(VoiceProfile).where(VoiceProfile.workspace_id == workspace_id)) @@ -164,6 +168,26 @@ def handle_chat_memory(db: Session, job: Job): return Done(result, f"Filed {result['rounds']} rounds" if result["rounds"] else "Nothing new to file") +def handle_post_cards(db: Session, job: Job): + """Write post cards (app/pipeline/cards.py). Params: document_ids (omit for every post in the workspace), force.""" + ids = job.params.get("document_ids") + result = cards_for_documents(db, job.workspace_id, ids, bool(job.params.get("force"))) + if result["failed"] and not result["made"]: + raise RuntimeError(f"no post card could be made ({result['failed']} failed)") # retried by the queue + return Done(result, f"Post cards: {result['made']} new, {result['up_to_date']} up to date" + + (f", {result['failed']} failed" if result["failed"] else "")) + + +def handle_chat_judge(db: Session, job: Job): + """Score one chat answer (relevance, faithfulness) or refusal (false_refusal) for Langfuse. Params: message_id.""" + msg = db.get(Message, uuid.UUID(job.params["message_id"])) + chat = db.get(Chat, msg.chat_id) if msg else None + if not msg or not chat or chat.workspace_id != job.workspace_id: + return Done({"skipped": "message gone"}, "Message no longer exists") + result = judge_message(db, msg.id) + return Done(result, "Answer scored") + + def handle_chat_memory_rebuild(db: Session, job: Job): """Rebuild chat memory from the messages. Params: notebook_id, and optionally chat_id for just one chat.""" notebook_id = uuid.UUID(job.params["notebook_id"]) @@ -345,6 +369,8 @@ def handle_compound_action(db: Session, job: Job): "memory_update": handle_memory, "chat_memory": handle_chat_memory, "chat_memory_rebuild": handle_chat_memory_rebuild, + "chat_judge": handle_chat_judge, + "post_cards": handle_post_cards, "chat_memory_cleanup": handle_chat_memory_cleanup, "voice_profile": handle_voice_profile, "voice_clone": handle_voice_clone, diff --git a/backend/requirements.txt b/backend/requirements.txt index 88b2c77..ca68961 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -24,6 +24,8 @@ stripe==13.* jinja2==3.* cryptography>=44,<51 composio>=0.22.1,<1 +# Chat tracing and evaluation (app/observability/langfuse.py). Optional at runtime: no keys = no-op. +langfuse==5.1.0 # Dev tools (tests, lint) pytest==8.* diff --git a/backend/scripts/build_post_cards.py b/backend/scripts/build_post_cards.py new file mode 100644 index 0000000..5b0e657 --- /dev/null +++ b/backend/scripts/build_post_cards.py @@ -0,0 +1,67 @@ +"""Build post cards (app/pipeline/cards.py) for posts that were added before cards existed. + +New and changed posts get a card automatically after every import. Run this once per environment for the rest: + + .venv/bin/python scripts/build_post_cards.py --workspace # queue a job for one workspace + .venv/bin/python scripts/build_post_cards.py --all # queue a job for every workspace + .venv/bin/python scripts/build_post_cards.py --notebook --now # build here and wait (for a test notebook) + +--force rebuilds cards that are already up to date (after changing the PostCard prompt). Queued jobs run in the +worker; their progress shows in the jobs table (kind post_cards). One fast-model call per post.""" + +import argparse +import sys +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from sqlalchemy import select # noqa: E402 + +from app.corpus import Corpus # noqa: E402 +from app.db import SessionLocal # noqa: E402 +from app.models import Document, Notebook, NotebookDocument, Workspace # noqa: E402 +from app.pipeline.cards import build_cards, cards_for_documents # noqa: E402 +from app.services.jobs import create_job # noqa: E402 + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + target = ap.add_mutually_exclusive_group(required=True) + target.add_argument("--workspace") + target.add_argument("--notebook") + target.add_argument("--all", action="store_true") + ap.add_argument("--now", action="store_true", help="build in this process instead of queueing a worker job") + ap.add_argument("--force", action="store_true", help="rebuild cards that are already up to date") + args = ap.parse_args() + db = SessionLocal() + try: + if args.notebook: + nb = db.get(Notebook, uuid.UUID(args.notebook)) + if nb is None: + sys.exit("No such notebook") + rows = db.execute(select(Document.id, Document.path, Document.title) + .join(NotebookDocument, NotebookDocument.document_id == Document.id) + .where(NotebookDocument.notebook_id == nb.id, Document.path.is_not(None))).all() + if args.now: + result = build_cards(Corpus(nb.workspace_id), {p: t or p for _, p, t in rows}, args.force) + print(f"Notebook {nb.title!r}: {result}") + else: + job = create_job(db, nb.workspace_id, "post_cards", + {"document_ids": [str(i) for i, _, _ in rows], "force": args.force}, max_attempts=2) + print(f"Queued post_cards job {job.id} for {len(rows)} posts of notebook {nb.title!r}") + return + workspaces = ([uuid.UUID(args.workspace)] if args.workspace + else list(db.scalars(select(Workspace.id)))) + for ws in workspaces: + if args.now: + print(f"Workspace {ws}: {cards_for_documents(db, ws, None, args.force)}") + else: + job = create_job(db, ws, "post_cards", {"force": args.force}, max_attempts=2) + print(f"Queued post_cards job {job.id} for workspace {ws}") + finally: + db.close() + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/chat_eval.py b/backend/scripts/chat_eval.py index 2174ebb..62c7d96 100644 --- a/backend/scripts/chat_eval.py +++ b/backend/scripts/chat_eval.py @@ -10,12 +10,17 @@ 1. A labelled question set (each question written by GLM from one passage, so the right lines are known): .venv/bin/python scripts/chat_eval.py make-questions --notebook --n 40 --out eval/synthetic.csv + Add --paraphrase to also write each question in other words (ids p...): the wording-gap set, compared by the + same metrics. A post found for s007 but not for p007 is a miss caused by vocabulary, not by the question. Read it and delete bad or ambiguous questions: this matters more than anything else for a trustworthy result. 2. A smoke test (a few minutes): .venv/bin/python scripts/chat_eval.py run --notebook --questions eval/questions.csv --limit 3 --repeats 1 \\ --no-judge --no-ragas +Router vs today's chat (post cards must exist: scripts/build_post_cards.py): + .venv/bin/python scripts/chat_eval.py run --notebook --questions eval/synthetic.csv --baseline current --router + 3. The full run (about 1 to 1.5 hours, real GLM tokens; run at a quiet time and do not chat meanwhile): .venv/bin/python scripts/chat_eval.py run --notebook --questions eval/questions.csv eval/synthetic.csv --repeats 3 @@ -60,6 +65,11 @@ from app.services.memory import list_facts, profile_text # noqa: E402 MODES = ("old", "new") +# What "old" and "new" mean (set from the run arguments). BASELINE "agent": old is the research agent alone (the +# original comparison). BASELINE "current": old is the chat as it runs today (keyword prefetch, fast path). ROUTER: +# new runs with CHAT_ROUTER on (tiers A/B/C, post cards, query expansion). +BASELINE = "agent" +ROUTER = False NO_RESEARCH = ("chitchat", "off_topic", "about_app", "error") # replies that never touch the posts FIELDS = ("id", "group", "question", "expected_fact", "reference_answer", "gold_path", "gold_lines") log = logging.getLogger("chat_eval") @@ -169,6 +179,17 @@ class WriteQuestion(dspy.Signature): answer: str = dspy.OutputField(desc="One or two sentences, only from the passage") +class ParaphraseQuestion(dspy.Signature): + """Rewrite a writer's question so it asks for exactly the same thing in different words: replace the passage's + key terms with synonyms or plain descriptions a reader would use (e.g. "pricing" -> "what to charge"), keep any + proper names. This tests whether the assistant finds the answer when the question does not share the post's + vocabulary. Return only the rewritten question.""" + + question: str = dspy.InputField() + passage: str = dspy.InputField(desc="The passage that answers it: avoid its distinctive words") + paraphrase: str = dspy.OutputField() + + def make_questions(args) -> None: models_without_cache() _, allowed, corpus, manifest, _, _ = load_notebook(args.notebook) @@ -182,6 +203,7 @@ def make_questions(args) -> None: seen_posts.add(p.path) picked += [p for p in passages if p not in picked] rows, lm = [], provider.main_lm() + paraphrases: list[dict] = [] for p in picked: if len(rows) >= args.n: break @@ -198,12 +220,25 @@ def make_questions(args) -> None: rows.append({"id": f"s{i:03d}", "group": f"s{i:03d}", "question": q, "expected_fact": "", "reference_answer": a, "gold_path": p.path, "gold_lines": f"{p.start}-{p.end}"}) print(f" {i:3d}. {q}") + if args.paraphrase: + try: + with dspy.context(lm=lm): + para = (dspy.Predict(ParaphraseQuestion)(question=q, passage="\n".join(p.lines)).paraphrase + or "").strip() + except Exception as exc: + print(f" paraphrase skipped: {type(exc).__name__}") + para = "" + if para and para.lower() != q.lower(): + # Its own group: a paraphrase is a separate first question, not a follow up in the same chat. + paraphrases.append({**rows[-1], "id": f"p{i:03d}", "group": f"p{i:03d}", "question": para}) + print(f" ~ {para}") Path(args.out).parent.mkdir(parents=True, exist_ok=True) with open(args.out, "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=FIELDS) w.writeheader() - w.writerows(rows) - print(f"Wrote {len(rows)} questions to {args.out}. Read them and delete bad or ambiguous ones before a run.") + w.writerows(rows + paraphrases) + print(f"Wrote {len(rows)} questions" + (f" and {len(paraphrases)} paraphrases (ids p...)" if paraphrases else "") + + f" to {args.out}. Read them and delete bad or ambiguous ones before a run.") # Instrumentation: what each run did @@ -222,7 +257,8 @@ def __init__(self): def watch(self, mode: str): saved = {"completion": writer._completion, "stream": writer.stream_answer, "decide": jev.decide, "read": ScopedTools.read, "prefetch": rs.prefetch, - "flags": (settings.chat_fast_path, settings.chat_stream_answers, settings.chat_parallel_parts)} + "flags": (settings.chat_fast_path, settings.chat_stream_answers, settings.chat_parallel_parts), + "router": settings.chat_router} probe = self def completion(**kw): @@ -251,11 +287,13 @@ def prefetch(*a, **k): return probe.prefetch writer._completion, writer.stream_answer, jev.decide, ScopedTools.read = completion, stream_answer, decide, read - if mode == "old": + if mode == "old" and BASELINE == "agent": settings.chat_fast_path = settings.chat_stream_answers = settings.chat_parallel_parts = False + settings.chat_router = False rs.prefetch = lambda *a, **k: pf.Prefetch() else: settings.chat_fast_path = settings.chat_stream_answers = settings.chat_parallel_parts = True + settings.chat_router = ROUTER and mode == "new" rs.prefetch = prefetch try: yield self @@ -263,6 +301,7 @@ def prefetch(*a, **k): writer._completion, writer.stream_answer, jev.decide = saved["completion"], saved["stream"], saved["decide"] ScopedTools.read, rs.prefetch = saved["read"], saved["prefetch"] settings.chat_fast_path, settings.chat_stream_answers, settings.chat_parallel_parts = saved["flags"] + settings.chat_router = saved["router"] def history_entries(clear: bool = False) -> int: @@ -478,6 +517,8 @@ def mean(xs: list) -> float | str: def run(args) -> None: + global BASELINE, ROUTER + BASELINE, ROUTER = args.baseline, args.router models_without_cache() rows = read_questions(args.questions, args.limit) nb, allowed, corpus, manifest, profile, setup = load_notebook(args.notebook) @@ -679,6 +720,8 @@ def main() -> None: mq.add_argument("--n", type=int, default=40) mq.add_argument("--seed", type=int, default=7) mq.add_argument("--out", default="eval/synthetic.csv") + mq.add_argument("--paraphrase", action="store_true", + help="also write each question in different words (ids p...), to measure the wording gap") rn = sub.add_parser("run", help="run old and new on the questions and write the CSVs") rn.add_argument("--notebook") rn.add_argument("--questions", nargs="+", default=["eval/questions.csv"]) @@ -686,6 +729,9 @@ def main() -> None: rn.add_argument("--limit", type=int, help="only the first N question groups (a smoke test)") rn.add_argument("--no-judge", action="store_true") rn.add_argument("--no-ragas", action="store_true") + rn.add_argument("--baseline", choices=("agent", "current"), default="agent", + help="what 'old' is: the research agent alone, or the chat as it runs today") + rn.add_argument("--router", action="store_true", help="run 'new' with CHAT_ROUTER on (tiers, cards, expansion)") rn.add_argument("--out", help="results folder (default chat_eval_results/)") args = ap.parse_args() {"notebooks": list_notebooks, "make-questions": make_questions, "run": run}[args.cmd](args) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 33339c6..e1d6fa5 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -96,6 +96,20 @@ def blocked(*_args, **_kwargs): monkeypatch.setattr(stripe, "StripeClient", blocked) +@pytest.fixture(autouse=True) +def never_reach_langfuse(monkeypatch): + """No test sends traces or scores to a real Langfuse project, even when .env holds LANGFUSE keys. A test that needs + Langfuse swaps in a fake client (tests/test_chat_observability.py).""" + from app.config import settings + from app.observability import langfuse_client + + monkeypatch.setattr(settings, "langfuse_public_key", "") + monkeypatch.setattr(settings, "langfuse_secret_key", "") + langfuse_client.reset_for_tests() + yield + langfuse_client.reset_for_tests() + + @pytest.fixture(autouse=True) def offline_dns(monkeypatch): """Names resolve to a public address and nothing touches the network: tests use hosts like ada.example.com.""" diff --git a/backend/tests/evals/test_chat_tool_use.py b/backend/tests/evals/test_chat_tool_use.py index 02ed6b5..5eacc4f 100644 --- a/backend/tests/evals/test_chat_tool_use.py +++ b/backend/tests/evals/test_chat_tool_use.py @@ -325,7 +325,8 @@ def test_the_recorder_writes_down_calls_and_keeps_what_the_agent_is_shown(tmp_pa def test_the_prompts_tell_the_agent_to_look_wide(): base = " ".join(ResearchArchive.__doc__.split()) - assert "First call list_files to see which posts exist" in base + assert "Start from the prefetched passages: when they answer the question, cite them directly" in base + assert "Call list_files when you need to see which posts exist" in base assert "call search across the whole archive (leave path empty" in base assert "Pass path to search only when the writer explicitly asks you to use one named post" in base assert "otherwise never limit a search to one post" in base diff --git a/backend/tests/test_chat_observability.py b/backend/tests/test_chat_observability.py new file mode 100644 index 0000000..634962b --- /dev/null +++ b/backend/tests/test_chat_observability.py @@ -0,0 +1,272 @@ +"""Chat observability: the Langfuse trace of a message (stages, steps, writer generations, outcome tags), outcome codes, +ratings and judge scores sent as Langfuse scores, and that everything is a no-op when Langfuse is off.""" + +import asyncio +import json +import re +from types import SimpleNamespace + +import pytest + +from app.config import settings +from app.observability import langfuse_client as lf +from app.pipeline import research as r +from app.pipeline.research import ResearchResult, VerifiedCitation, outcome_of +from app.pipeline.trace import OUTCOMES, ChatTrace +from tests.test_buildout import auth, connect, docs, feed # noqa: F401 (fixtures and helpers) + + +class FakeSpan: + def __init__(self, store, name, as_type, kwargs): + self.store, self.name, self.as_type, self.kwargs = store, name, as_type, kwargs + self.updates: list[dict] = [] + self.attributes: dict = {} + self.ended = False + self._otel_span = SimpleNamespace(set_attribute=lambda k, v: self.attributes.__setitem__(k, v)) + + def start_observation(self, *, name, as_type="span", **kwargs): + child = FakeSpan(self.store, name, as_type, kwargs) + self.store.append(child) + return child + + def update(self, **kwargs): + self.updates.append(kwargs) + return self + + def end(self): + self.ended = True + + +class FakeLangfuse: + def __init__(self): + self.observations: list[FakeSpan] = [] + self.scores: list[dict] = [] + self.flushed = 0 + + def create_trace_id(self): + return "a" * 32 + + def start_observation(self, *, trace_context, name, as_type="span", **kwargs): + root = FakeSpan(self.observations, name, as_type, {**kwargs, "trace_context": trace_context}) + self.observations.append(root) + return root + + def create_score(self, **kwargs): + self.scores.append(kwargs) + + def flush(self): + self.flushed += 1 + + +@pytest.fixture() +def langfuse(monkeypatch): + fake = FakeLangfuse() + monkeypatch.setattr(lf, "client", lambda: fake) + monkeypatch.setattr(settings, "langfuse_mask_text", True) + return fake + + +def test_without_langfuse_the_trace_works_as_before(monkeypatch): + monkeypatch.setattr(settings, "langfuse_public_key", "") + lf.reset_for_tests() + trace = ChatTrace(notebook="nb", message="what about pricing?") + assert trace.start_langfuse(user="u1", session="c1") == "" + with trace.stage("triage") as obs: + obs.update(metadata={"ignored": True}) + with trace.observe("writer", as_type="generation") as gen: + gen.update(output="x") + trace.step("search", "pricing") + trace.set_outcome("answered") + trace.emit() + assert trace.stages[0][0] == "triage" and "outcome:answered" in trace.tags + assert "outcome : answered" in trace.render() + assert lf.score("t" * 32, "user_feedback", 1.0) is False + + +def test_the_message_trace_has_stages_steps_generations_and_outcome_tags(langfuse): + trace = ChatTrace(chat_id="c1", notebook="nb", message="what about pricing?") + assert trace.start_langfuse(user="user-1", session="c1", metadata={"notebook_id": "n1"}) == "a" * 32 + root = langfuse.observations[0] + assert root.name == "notebook-chat" and root.kwargs["input"] == {"chars": 19} # masked: size, not text + assert root.attributes["session.id"] == "c1" + assert root.attributes["user.id"] == lf.pseudonym("user-1") != "user-1" + + with trace.stage("prefetch"): + pass + trace.step("search", "pric(e|ing)") + with pytest.raises(RuntimeError), trace.observe("writer: fast path", as_type="generation", model="m"): + raise RuntimeError("stream broke") + trace.add("triage", "FINAL : kind=archive") + trace.add("steps", "search pric(e|ing)") # writers' words: not sent while text is masked + trace.set_outcome("cites_dropped") + trace.tag("retrieval_empty") + trace.output = "I could not find support" + trace.emit() + + by_name = {o.name: o for o in langfuse.observations} + assert by_name["prefetch"].as_type == "span" and by_name["prefetch"].ended + assert by_name["step:search"].as_type == "event" and by_name["step:search"].kwargs["input"] == {"chars": 11} + writer = by_name["writer: fast path"] + assert writer.as_type == "generation" and writer.ended and writer.updates[-1]["level"] == "ERROR" + assert root.ended and root.attributes["langfuse.trace.tags"] == ["outcome:cites_dropped", "retrieval_empty", + "verdict:fail"] + final = root.updates[-1] + assert final["name"] == "FAIL · cites_dropped" == root.attributes["langfuse.trace.name"] + assert final["level"] == "ERROR" and "none passed verification" in final["status_message"] + assert langfuse.scores[-1]["name"] == "verdict" and langfuse.scores[-1]["value"] == "fail" + assert final["output"] == {"chars": len("I could not find support")} + assert final["metadata"]["outcome"] == "cites_dropped" and "prefetch" in final["metadata"]["stages_ms"] + assert "triage" in final["metadata"]["sections"] and "steps" not in final["metadata"]["sections"] + + +@pytest.mark.parametrize("outcome, name, level", [ + ("answered", "PASS · answered", None), ("triage_off_topic", "REVIEW · triage_off_topic", "WARNING"), + ("writer_uncovered", "FAIL · writer_uncovered", "ERROR"), ("timeout", "FAIL · timeout", "ERROR"), +]) +def test_every_trace_says_pass_fail_or_review(langfuse, outcome, name, level): + trace = ChatTrace(message="q") + trace.start_langfuse() + trace.set_outcome(outcome) + trace.emit() + final = langfuse.observations[0].updates[-1] + assert final["name"] == name and final.get("level") == level + assert langfuse.scores[-1]["value"] == name.split(" · ")[0].lower() + + +def test_unmasked_text_is_sent_only_when_masking_is_off(langfuse, monkeypatch): + monkeypatch.setattr(settings, "langfuse_mask_text", False) + trace = ChatTrace(notebook="nb", message="what about pricing?") + trace.start_langfuse() + trace.add("steps", "search pricing") + trace.emit() + root = langfuse.observations[0] + assert root.kwargs["input"] == "what about pricing?" + assert "steps" in root.updates[-1]["metadata"]["sections"] + + +def _cite(): + return VerifiedCitation(1, "sources/a/x.md", 3, 4, "q") + + +@pytest.mark.parametrize("result, expected", [ + (ResearchResult("ok", False, [_cite()], kind="archive", recall={"refused": False}), "answered"), + (ResearchResult("no", True, [], kind="archive", recall={"refused": False, "model_unsupported": True}), + "writer_uncovered"), + (ResearchResult("no", True, [], kind="archive", recall={"refused": True, "proposed_cites": 0}), "refused_no_cites"), + (ResearchResult("no", True, [], kind="archive", recall={"refused": True, "proposed_cites": 3}), "cites_dropped"), + (ResearchResult("bye", False, [], kind="off_topic"), "triage_off_topic"), + (ResearchResult("hi", False, [], kind="chitchat"), "triage_other"), + (ResearchResult("x", False, [], kind="create"), "triage_other"), + (ResearchResult("done", False, [], kind="external_action"), "external_done"), + (ResearchResult("fail", True, [], kind="external_action"), "external_failed"), + (ResearchResult(r.FAILED_REPLY, True, [], kind="error"), "agent_malformed"), +]) +def test_every_result_gets_a_known_outcome_code(result, expected): + assert outcome_of(result) == expected and expected in OUTCOMES + + +def test_a_refusal_records_how_many_citations_were_proposed_and_dropped(): + class Tools: + allowed = {"sources/a/x.md": "X"} + + def quote(self, *_): + return None # every proposed line range fails verification + + cites = [SimpleNamespace(marker=1, path="sources/a/x.md", line_start=900, line_end=901)] + text, kept = r.verify_citations(Tools(), "Claim [1].", cites) + assert kept == [] and text == "Claim." # no corpus to repair from: dropped, never invented + + +def test_a_client_that_leaves_early_is_tagged(monkeypatch): + from app.routers import notebooks as nbr + + left: list[str] = [] + + async def stream(): + for i in range(5): + yield f"chunk {i}" + await asyncio.sleep(0) + + async def main(): + reader = nbr._detached(stream(), keepalive=1.0, on_leave=lambda: left.append("gone")) + first = await reader.__anext__() + await reader.aclose() # the phone locked + return first + + assert asyncio.run(main()) == "chunk 0" and left == ["gone"] + + async def whole(): + reader = nbr._detached(stream(), keepalive=1.0, on_leave=lambda: left.append("again")) + return [c async for c in reader] + + assert len(asyncio.run(whole())) == 5 and left == ["gone"] # read to the end: not a leave + + +def test_chat_saves_outcome_and_trace_id_and_rating_becomes_a_score(client, auth, run_jobs, feed, monkeypatch, # noqa: F811 + db_session, langfuse): + from app.models import Job, Message + from app.routers import notebooks as nbr + + connect(client, auth, run_jobs) + doc = docs(client, auth)[0] + nb = client.post("/api/notebooks", json={"title": "N", "document_ids": [doc["id"]]}, headers=auth).json() + + def fake_research(corpus, allowed, question, *a, **k): + return ResearchResult("I could not find support", True, [], kind="archive", + recall={"path": "fast path", "refused": True, "proposed_cites": 2, + "prefetch": {"passages": 0}}) + + monkeypatch.setattr(nbr, "research", fake_research) + monkeypatch.setattr(settings, "llm_api_key", "sk-test") + monkeypatch.setattr(settings, "chat_judge_sample_rate", 1.0) + body = client.post(f"/api/notebooks/{nb['id']}/chat", json={"question": "What about pricing?"}, + headers=auth).text + msg_id = json.loads(re.search(r"event: answer\ndata: (.*)", body).group(1))["message_id"] + msg = db_session.get(Message, __import__("uuid").UUID(msg_id)) + db_session.refresh(msg) + assert msg.recall_json["outcome"] == "cites_dropped" and msg.recall_json["trace_id"] == "a" * 32 + root = langfuse.observations[0] + tags = root.attributes["langfuse.trace.tags"] + assert {"outcome:cites_dropped", "kind:archive", "path:fast path", "retrieval_empty", "posts:1-10"} <= set(tags) + assert db_session.query(Job).filter_by(kind="chat_judge").count() == 1 + + client.put(f"/api/notebooks/messages/{msg_id}/feedback", json={"rating": "down", "reasons": ["missed"]}, + headers=auth) + score = langfuse.scores[-1] + assert score == {"name": "user_feedback", "value": -1.0, "trace_id": "a" * 32, "comment": "missed", + "score_id": f"{msg_id}-user_feedback"} + + +def test_no_judge_job_without_langfuse(client, auth, run_jobs, feed, monkeypatch, db_session): # noqa: F811 + from app.models import Job + from app.routers import notebooks as nbr + + monkeypatch.setattr(settings, "langfuse_public_key", "") + lf.reset_for_tests() + connect(client, auth, run_jobs) + doc = docs(client, auth)[0] + nb = client.post("/api/notebooks", json={"title": "N", "document_ids": [doc["id"]]}, headers=auth).json() + monkeypatch.setattr(nbr, "research", lambda *a, **k: ResearchResult("ok", False, [_cite()], kind="archive")) + monkeypatch.setattr(settings, "chat_judge_sample_rate", 1.0) + client.post(f"/api/notebooks/{nb['id']}/chat", json={"question": "What about pricing?"}, headers=auth) + assert db_session.query(Job).filter_by(kind="chat_judge").count() == 0 + + +def test_the_judge_scores_a_refusal_as_false_when_the_notebook_held_the_answer(db_session, monkeypatch, langfuse): + import uuid + + from app.pipeline import chat_judge + + msg = SimpleNamespace(id=uuid.uuid4(), role="assistant", chat_id=uuid.uuid4(), content="I could not find it", + citations=[], recall_json={"outcome": "refused_no_cites", "trace_id": "b" * 32}) + chat = SimpleNamespace(notebook_id=uuid.uuid4(), workspace_id=uuid.uuid4()) + db = SimpleNamespace(get=lambda model, _id: msg if model.__name__ == "Message" else chat, + commit=lambda: None) + monkeypatch.setattr(chat_judge, "_question_for", lambda *_: "how do I get paid subscribers?") + monkeypatch.setattr(chat_judge, "_judge_refusal", lambda *_: {"evidence_existed": True, + "best_path": "sources/a/x.md", "reason": "it does"}) + monkeypatch.setattr(chat_judge, "fast_lm", lambda: None) + out = chat_judge.judge_message(db, msg.id) + assert out["evidence_existed"] is True and msg.recall_json["judge"]["best_path"] == "sources/a/x.md" + assert langfuse.scores == [{"name": "false_refusal", "value": 1.0, "trace_id": "b" * 32, "comment": "it does", + "data_type": "BOOLEAN", "score_id": f"{msg.id}-false_refusal"}] diff --git a/backend/tests/test_chat_recall.py b/backend/tests/test_chat_recall.py index 2ee9879..b25de82 100644 --- a/backend/tests/test_chat_recall.py +++ b/backend/tests/test_chat_recall.py @@ -344,7 +344,7 @@ def __call__(self, **inputs): def agent(monkeypatch, tmp_path): FakeReAct.built, FakeReAct.cite = [], None monkeypatch.setattr(r.dspy, "ReAct", FakeReAct) - monkeypatch.setattr(r, "main_lm", lambda *a: dspy.LM("openai/x", api_key="k")) + monkeypatch.setattr(r, "agent_lm", lambda *a: dspy.LM("openai/x", api_key="k")) @contextmanager def usage(lm): diff --git a/backend/tests/test_chat_retrieval.py b/backend/tests/test_chat_retrieval.py new file mode 100644 index 0000000..0b24272 --- /dev/null +++ b/backend/tests/test_chat_retrieval.py @@ -0,0 +1,302 @@ +"""Chat retrieval: the search tool's robustness fixes, long paragraphs, citation repair, post cards, and the router +(Tier A whole notebook, Tier B cards + passages, Tier C agent).""" + +import json +import uuid +from types import SimpleNamespace + +import httpx +import pytest + +from app.config import settings +from app.corpus import Corpus, ScopedTools, card_rel, render_post, split_long +from app.llm.signatures import FileCitation +from app.pipeline import cards as cards_mod +from app.pipeline import context_router as cr +from app.pipeline import prefetch as pf +from app.pipeline import research as r +from app.pipeline import writer as w +from app.pipeline.trace import ChatTrace +from app.services import jev +from tests.test_chat_speed import _archive, _corpus, _no_agent, _writer + +LONG = "x " * 400 + "the paid tier is generous " + "y " * 400 + + +# The search tool + + +def test_one_missing_post_does_not_fail_the_whole_search(tmp_path): + c, allowed = _corpus(tmp_path) + tools = ScopedTools(c, {**allowed, "sources/x/gone.md": "Gone"}) + out = tools.search("raise prices") + assert "sources/x/pricing.md:7" in out and "1 post(s) could not be read" in out + + +def test_a_hit_deep_in_a_long_line_shows_the_match(tmp_path): + c = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) + c.write_files({"sources/x/long.md": f"# T\n\n{LONG}\n"}) + out = ScopedTools(c, {"sources/x/long.md": "T"}).search("paid tier") + assert "the paid tier is generous" in out and out.count("...") >= 1 + + +def test_posts_with_more_matches_come_first(tmp_path): + c = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) + c.write_files({"sources/x/a.md": "# A\n\npricing once\n", "sources/x/b.md": "# B\n\npricing\n\npricing again\n"}) + out = ScopedTools(c, {"sources/x/a.md": "A", "sources/x/b.md": "B"}).search("pricing") + assert out.splitlines()[0].startswith("sources/x/b.md") + + +def test_read_is_capped_by_characters_too(tmp_path): + c = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) + c.write_files({"sources/x/big.md": "\n".join("z" * 5000 for _ in range(10))}) + out = ScopedTools(c, {"sources/x/big.md": "Big"}).read("sources/x/big.md") + assert len(out) < 13_000 and "more lines" in out + + +def test_long_paragraphs_are_stored_as_several_lines_of_one_paragraph(): + para = " ".join(f"Sentence number {i} says something useful." for i in range(120)) + pieces = split_long(para) + assert len(pieces) > 1 and all(len(p) <= 1_500 for p in pieces) and " ".join(pieces) == para + text = render_post(title="T", url="u", published_at=None, source="s", sections=[(None, para)]) + body = text.split("# T\n\n", 1)[1].rstrip("\n").split("\n") + assert body == pieces # consecutive lines, no blank line between: still one paragraph + assert split_long("```py\n" + "a" * 3000 + "\n```") == ["```py\n" + "a" * 3000 + "\n```"] + + +@pytest.mark.parametrize("message, expected", [ + ("explain how to use it", True), ("give me a brief intro of him", True), ("why?", True), + ("what about hiring?", True), ("tell me more about the second point", True), ("you said it was yearly", True), + ("what is bloghub?", False), ("What are the strongest ideas across these posts?", False), + ("How do I price my newsletter when it has fewer than a thousand readers?", False), + ("What did I write about pricing and why it matters for creators?", False), +]) +def test_refers_back_only_for_real_follow_ups(message, expected): + assert r.refers_back(message) is expected + + +def test_writing_about_writing_keeps_the_word_write(): + assert pf.content_words("what did I write?") == [] + assert pf.content_words("have I ever written about it") == [] + assert "writ" in pf.content_words("how do I write a better intro?") + assert "intro" in pf.content_words("how do I write a better intro?") + + +# Citation repair + + +def test_a_citation_with_wrong_line_numbers_is_repaired_from_the_cited_sentence(tmp_path): + c, allowed = _corpus(tmp_path) + tools = ScopedTools(c, allowed) + cites = [SimpleNamespace(marker=1, path="sources/x/pricing.md", line_start=90, line_end=92)] + text, kept = r.verify_citations(tools, "A paid tier works best when the free tier stays generous [1].", cites) + assert kept and kept[0].line_start == 8 and kept[0].repaired and text.endswith("[1].") + + +def test_a_citation_that_matches_nothing_is_still_dropped(tmp_path): + c, allowed = _corpus(tmp_path) + cites = [SimpleNamespace(marker=1, path="sources/x/pricing.md", line_start=90, line_end=92)] + _, kept = r.verify_citations(ScopedTools(c, allowed), "Kubernetes clusters scale horizontally [1].", cites) + assert kept == [] + + +# Jev + + +def test_jev_tries_once_more_when_the_connection_drops(monkeypatch): + monkeypatch.setattr(settings, "typesafe_api_key", "k") + monkeypatch.setattr(jev, "RETRY_DELAY", 0) + calls = [] + + def post(*a, **k): + calls.append(1) + if len(calls) == 1: + raise httpx.ConnectError("[SSL: UNEXPECTED_EOF_WHILE_READING]") + return httpx.Response(200, json={"answers": {"intent": {"choice": "archive", "confidence": 0.9}}}) + + monkeypatch.setattr(jev.httpx, "post", post) + assert jev.decide({}, {"intent": {}})["intent"].choice == "archive" and len(calls) == 2 + + +# Post cards + +CARD = {"version": 1, "title": "On Pricing", "summary": "How to charge readers.", "topics": ["monetization"], + "entities": ["Substack"], "synonyms": ["what to charge", "subscription cost", "paying members"], + "questions": ["How much should I charge?"]} + + +def _with_cards(c, cards): + manifest = c.sync() + c.write_files({card_rel(p): json.dumps({**card, "post_hash": manifest[p]}) for p, card in cards.items()}) + return c.sync() + + +def test_build_cards_writes_a_card_per_post_and_skips_up_to_date_ones(monkeypatch, tmp_path): + c, allowed = _corpus(tmp_path) + made = [] + monkeypatch.setattr(cards_mod, "make_card", lambda title, text: made.append(title) or {**CARD, "title": title}) + assert cards_mod.build_cards(c, allowed) == {"made": 2, "failed": 0, "up_to_date": 0} + assert cards_mod.load_cards(c, allowed)["sources/x/pricing.md"]["synonyms"][0] == "what to charge" + assert cards_mod.build_cards(c, allowed) == {"made": 0, "failed": 0, "up_to_date": 2} and len(made) == 2 + + +def test_a_removed_post_takes_its_card_with_it(tmp_path): + c, allowed = _corpus(tmp_path) + _with_cards(c, {"sources/x/pricing.md": CARD}) + c.write_files({}, remove={"sources/x/pricing.md"}) + assert card_rel("sources/x/pricing.md") not in c.sync() + + +def test_a_question_in_other_words_finds_the_post_through_its_card(tmp_path): + c, allowed = _corpus(tmp_path) + question = "what subscription cost should paying members see?" + assert pf.prefetch(c, allowed, c.sync(), question).passages == [] # the post never says these words + manifest = _with_cards(c, {"sources/x/pricing.md": CARD}) + cards = cards_mod.load_cards(c, allowed) + got = pf.prefetch(c, allowed, manifest, question, cards=cards) + assert got.passages and got.passages[0][1].path == "sources/x/pricing.md" + found = pf.retrieve(c, allowed, manifest, cards, [question]) + assert found.posts[0] == "sources/x/pricing.md" + + +# The router + + +def _router(monkeypatch, full_tokens=60_000): + _archive(monkeypatch) + monkeypatch.setattr(settings, "chat_router", True) + monkeypatch.setattr(settings, "chat_query_expansion", False) + monkeypatch.setattr(settings, "chat_full_notebook_tokens", full_tokens) + + +def test_a_small_notebook_is_read_whole_in_one_call(monkeypatch, tmp_path): + c, allowed = _corpus(tmp_path) + _router(monkeypatch) + calls = _writer(monkeypatch, "Hire slowly [1].", + [FileCitation(marker=1, path="sources/x/hiring.md", line_start=7, line_end=7)]) + _no_agent(monkeypatch) + t = ChatTrace() + res = r.research(c, allowed, "What is my advice on bringing people onto the team?", on_delta=lambda x: None, + trace=t) + assert res.recall["path"] == "tier A" and res.recall["router"]["tier"] == "A" and len(calls) == 1 + assert "7| Hire slowly" in calls[0]["evidence"] and "7| Raise prices" in calls[0]["evidence"] + assert "tier:A" in t.tags and r.outcome_of(res) == "answered" + + +def test_when_the_whole_notebook_does_not_cover_it_the_answer_says_so_without_the_agent(monkeypatch, tmp_path): + c, allowed = _corpus(tmp_path) + _router(monkeypatch) + + def uncovered(*a, **k): + raise w.WriterUncovered("no") + + monkeypatch.setattr(w, "stream_answer", uncovered) + _no_agent(monkeypatch) + res = r.research(c, allowed, "What is my take on Kubernetes?", on_delta=lambda x: None, trace=ChatTrace()) + assert res.unsupported and "do not cover" in res.text and r.outcome_of(res) == "writer_uncovered" + + +def test_a_big_notebook_sends_the_posts_its_cards_point_to(monkeypatch, tmp_path): + c, allowed = _corpus(tmp_path) + _with_cards(c, {"sources/x/pricing.md": CARD}) + _router(monkeypatch, full_tokens=1) # everything is "too big": Tier B + calls = _writer(monkeypatch, "Charge for depth [1].", + [FileCitation(marker=1, path="sources/x/pricing.md", line_start=8, line_end=8)]) + _no_agent(monkeypatch) + t = ChatTrace() + res = r.research(c, allowed, "what subscription cost should paying members see?", on_delta=lambda x: None, + trace=t) + assert res.recall["path"] == "tier B" and res.recall["router"]["tier"] == "B" + assert calls[0]["evidence"].startswith("FILE sources/x/pricing.md") and "hiring" not in calls[0]["evidence"] + assert res.recall["prefetch"]["posts"] >= 1 and "cards:some" in t.tags + + +def test_a_tier_b_miss_hands_its_evidence_to_the_agent(monkeypatch, tmp_path): + c, allowed = _corpus(tmp_path) + _router(monkeypatch, full_tokens=1) + _writer(monkeypatch, "Not covered.", [], unsupported=True) + ran = [] + + def fake_react(signature, tools, max_iters): + def run(**inputs): + ran.append(inputs["prefetched"]) + return SimpleNamespace(answer="Raise prices yearly [1].", unsupported=False, + citations=[SimpleNamespace(marker=1, path="sources/x/pricing.md", line_start=7, + line_end=7)]) + return run + + monkeypatch.setattr(r.dspy, "ReAct", fake_react) + t = ChatTrace() + res = r.research(c, allowed, "how often do I raise prices?", on_delta=lambda x: None, trace=t) + assert ran and "Raise prices" in ran[0] and res.recall["path"] == "research agent" + assert res.recall["router"]["tier"] == "B>C" and "tier:C" in t.tags + + +def test_tier_b_evidence_fits_the_budget(tmp_path): + c, allowed = _corpus(tmp_path) + found = pf.retrieve(c, allowed, c.sync(), {}, ["raise prices paid tier", "hire slowly"]) + ev = cr.tier_b_evidence(c, allowed, found, budget_chars=10_000) + assert ev.posts and ev.whole == len(ev.posts) and len(ev.text) <= 10_000 + small = cr.tier_b_evidence(c, allowed, found, budget_chars=150) + assert len(small.text) <= 150 + + +def test_the_answer_cache_changes_with_the_pipeline(monkeypatch): + from app.routers import notebooks as nbr + + nid = uuid.uuid4() + monkeypatch.setattr(settings, "chat_router", False) + off = nbr.answer_cache_key(nid, "q", [], "") + monkeypatch.setattr(settings, "chat_router", True) + assert nbr.answer_cache_key(nid, "q", [], "") != off + + +# Off topic triage that only saw the titles + +RESUME = """--- +title: Muhammad Mehdi Resume +--- + +# Muhammad Mehdi Resume + +Software Engineer with experience in full-stack development across multiple technology stacks. + +## Experience + +Engineered AI-driven content-to-video pipelines for Blog2Video using DSPy, enabling automated video generation. +""" + + +def _resume(tmp_path): + c = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) + c.write_files({"sources/u/resume.md": RESUME}) + return c, {"sources/u/resume.md": "Muhammad Mehdi Resume"} + + +def _off_topic(monkeypatch): + _archive(monkeypatch) + monkeypatch.setattr(r, "triage", lambda *a, **k: r.Triage("off_topic", a[0], "quick", "", engine="jev")) + rechecked = [] + monkeypatch.setattr(r, "recheck_off_topic", lambda route, *a: rechecked.append(1) or route) + return rechecked + + +def test_an_off_topic_call_is_overruled_when_the_posts_mention_the_subject(monkeypatch, tmp_path): + c, allowed = _resume(tmp_path) + rechecked = _off_topic(monkeypatch) + monkeypatch.setattr(settings, "chat_fast_path", True) + _writer(monkeypatch, "Blog2Video is built with DSPy [1].", + [FileCitation(marker=1, path="sources/u/resume.md", line_start=11, line_end=11)]) + _no_agent(monkeypatch) + res = r.research(c, allowed, "what is the tech stack for blog2video?", on_delta=lambda x: None, trace=ChatTrace()) + assert res.kind == "archive" and res.citations and "DSPy" in res.text + assert any("the posts mention" in n and "blog2video" in n for n in res.recall["triage_detail"]["notes"]) + assert rechecked == [] # the keyword check settled it: no second Jev call + + +def test_a_really_off_topic_question_still_gets_the_brush_off(monkeypatch, tmp_path): + c, allowed = _resume(tmp_path) + rechecked = _off_topic(monkeypatch) + _no_agent(monkeypatch) + res = r.research(c, allowed, "What is the capital of France?", on_delta=lambda x: None, trace=ChatTrace()) + assert res.kind == "off_topic" and rechecked == [1] diff --git a/backend/tests/test_chat_speed.py b/backend/tests/test_chat_speed.py index 4656ef1..9ebcc0a 100644 --- a/backend/tests/test_chat_speed.py +++ b/backend/tests/test_chat_speed.py @@ -227,7 +227,7 @@ def _no_usage(lm): def _archive(monkeypatch, depth="quick", detail="standard", reuse="new_research"): monkeypatch.setattr(r, "triage", lambda *a: r.Triage("archive", a[0], depth, "", detail=detail, reuse=reuse, engine="jev")) - monkeypatch.setattr(r, "main_lm", lambda: SimpleNamespace(model="glm-test")) + monkeypatch.setattr(r, "agent_lm", lambda: SimpleNamespace(model="glm-test")) monkeypatch.setattr(r, "track_usage", _no_usage) monkeypatch.setattr(settings, "chat_stream_answers", True) monkeypatch.setattr(settings, "chat_memory_read", False) diff --git a/backend/tests/test_chat_trace.py b/backend/tests/test_chat_trace.py index 9e1d0b1..1e6952e 100644 --- a/backend/tests/test_chat_trace.py +++ b/backend/tests/test_chat_trace.py @@ -102,7 +102,7 @@ def run(**inputs): return run monkeypatch.setattr(r.dspy, "ReAct", fake_react) - monkeypatch.setattr(r, "main_lm", lambda: SimpleNamespace(model="glm-test")) + monkeypatch.setattr(r, "agent_lm", lambda: SimpleNamespace(model="glm-test")) monkeypatch.setattr(r, "track_usage", no_usage) monkeypatch.setattr(r, "triage", lambda *a: r.Triage("archive", "q", "quick", "", engine="jev")) corpus = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) @@ -114,7 +114,7 @@ def run(**inputs): history=[r.Turn("user", "hi there"), r.Turn("assistant", "hello")], trace=t) text = t.render() assert "ARCHIVE: the message needs the writer's posts" in text - assert "signature: ResearchArchive | model glm-test | up to 4 reasoning steps (quick)" in text + assert "signature: ResearchArchive | model glm-test | up to 6 reasoning steps (quick)" in text assert "tools : list_files, search, read" in text assert "conversation: 2 turn(s)" in text and "writer notes: 2 line(s)" in text assert "chat memory: OFF (CHAT_MEMORY_READ=false)" in text @@ -133,7 +133,7 @@ def no_usage(_lm): yield SimpleNamespace(prompt_tokens=0, completion_tokens=0) def fake_react(_signature, tools, max_iters): - assert len(tools) == 1 and max_iters == 4 + assert len(tools) == 1 and max_iters == 6 return lambda **_inputs: SimpleNamespace(answer="not run", citations=[], unsupported=True) tool = CompactExternalTool( @@ -144,7 +144,7 @@ def fake_react(_signature, tools, max_iters): required_args={"channel", "message"}, ) monkeypatch.setattr(r.dspy, "ReAct", fake_react) - monkeypatch.setattr(r, "main_lm", lambda: SimpleNamespace(model="glm-test")) + monkeypatch.setattr(r, "agent_lm", lambda: SimpleNamespace(model="glm-test")) monkeypatch.setattr(r, "track_usage", no_usage) monkeypatch.setattr(r, "triage", lambda *a: r.Triage("external_action", "send it", "quick", "", engine="jev")) corpus = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) @@ -186,7 +186,7 @@ def fake_research(corpus, allowed, question, on_step=None, history=None, noteboo assert "[2 PATH]" in text and "ARCHIVE: fake" in text assert "answer sent after" in text and "assistant message saved to Postgres" in text assert "workspace notes: not updated (no LLM_API_KEY)" in text - assert "[TIMING] db-history+notes" in text and "save-answer" in text + assert "[TIMING] db-history" in text and "db-notes" in text and "save-answer" in text def test_the_trace_hides_the_message_when_text_logging_is_off(client, monkeypatch, caplog): @@ -300,7 +300,7 @@ def no_usage(lm): yield SimpleNamespace(prompt_tokens=0, completion_tokens=0) monkeypatch.setattr(r.dspy, "ReAct", fake_react) - monkeypatch.setattr(r, "main_lm", lambda: SimpleNamespace(model="m")) + monkeypatch.setattr(r, "agent_lm", lambda: SimpleNamespace(model="m")) monkeypatch.setattr(r, "track_usage", no_usage) monkeypatch.setattr(r, "triage", lambda *a: r.Triage("archive", "q", "quick", "", engine="jev")) corpus = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) diff --git a/backend/tests/test_corpus.py b/backend/tests/test_corpus.py index d1711a5..ad0c969 100644 --- a/backend/tests/test_corpus.py +++ b/backend/tests/test_corpus.py @@ -19,6 +19,8 @@ def put_text(self, key, text, content_type=None): return key def get_bytes(self, key): + if key not in self.objects: + raise FileNotFoundError(key) # as LocalStorage does; R2 raises NoSuchKey return self.objects[key] def exists(self, key): @@ -66,6 +68,41 @@ def test_sync_mirrors_r2_into_a_fresh_cache(corpus_pair): assert "# On pricing" in reader.read_lines(p1) +def test_sync_skips_and_drops_manifest_entries_with_no_object(tmp_path): + """A lost update left a deleted post listed in the manifest (prod, 2026-11-18): reads must not 500 on it.""" + store = MemoryStore() + ws = uuid.uuid4() + writer = Corpus(ws, store=store, cache_dir=str(tmp_path / "worker")) + writer.write_files({"sources/a/keep.md": "# Keep\n", "sources/a/gone.md": "# Gone\n", INDEX: "index\n"}) + store.delete(writer._key("sources/a/gone.md")) # object gone, manifest still lists it + + reader = Corpus(ws, store=store, cache_dir=str(tmp_path / "api")) + synced = reader.sync() + + assert reader.exists("sources/a/keep.md") and not reader.exists("sources/a/gone.md") + assert "sources/a/gone.md" not in synced + assert "sources/a/gone.md" not in reader._read_manifest(remote=True) # healed for every process + assert "sources/a/keep.md" in reader._read_manifest(remote=True) + assert reader.sync() == synced # stable: nothing left to trip over + + +def test_removed_files_leave_the_manifest_before_their_objects(tmp_path): + """A reader that syncs between the two steps must never see a listed file whose object is already gone.""" + store = MemoryStore() + ws = uuid.uuid4() + corpus = Corpus(ws, store=store, cache_dir=str(tmp_path / "c")) + corpus.write_files({"sources/a/x.md": "# X\n"}) + order: list[str] = [] + put, delete = store.put_text, store.delete + store.put_text = lambda key, *a, **k: (order.append(f"put {key.rsplit('/', 1)[-1]}"), put(key, *a, **k))[1] + store.delete = lambda key: (order.append(f"delete {key.rsplit('/', 1)[-1]}"), delete(key))[1] + + corpus.write_files({INDEX: "index\n"}, remove={"sources/a/x.md"}) + + assert order.index("put manifest.json") < order.index("delete x.md") + assert "sources/a/x.md" not in corpus._read_manifest(remote=True) + + def test_tools_search_read_and_scope(corpus_pair): reader, p1, p2 = corpus_pair steps = [] @@ -123,7 +160,7 @@ def test_react_agent_end_to_end_with_scripted_model(corpus_pair, monkeypatch): "citations": [{"marker": 1, "path": p1, "line_start": line, "line_end": line}], "unsupported": False}, ]) - monkeypatch.setattr(research_mod, "main_lm", lambda: lm) + monkeypatch.setattr(research_mod, "agent_lm", lambda: lm) monkeypatch.setattr(research_mod, "track_usage", _no_usage) monkeypatch.setattr(research_mod, "triage", lambda *a: research_mod.Triage("archive", "What did I charge?", "deep", "")) diff --git a/backend/tests/test_memory.py b/backend/tests/test_memory.py index 55728e7..6a0e2f1 100644 --- a/backend/tests/test_memory.py +++ b/backend/tests/test_memory.py @@ -132,7 +132,7 @@ def no_usage(lm): yield SimpleNamespace(prompt_tokens=0, completion_tokens=0) monkeypatch.setattr(r.dspy, "ReAct", fake_react) - monkeypatch.setattr(r, "main_lm", lambda: None) + monkeypatch.setattr(r, "agent_lm", lambda: None) monkeypatch.setattr(r, "track_usage", no_usage) monkeypatch.setattr(r, "triage", lambda *a: r.Triage("archive", "q", "quick", "")) corpus = Corpus(uuid.uuid4(), cache_dir=str(tmp_path)) diff --git a/backend/tests/test_outbound_mcp.py b/backend/tests/test_outbound_mcp.py index a0f6ce5..d88c1dd 100644 --- a/backend/tests/test_outbound_mcp.py +++ b/backend/tests/test_outbound_mcp.py @@ -385,7 +385,7 @@ def remote_call(url, token, tool, arguments): research_module, "triage", lambda *a: research_module.Triage("external_action", "find GitHub issues", "quick", ""), ) - monkeypatch.setattr(research_module, "main_lm", lambda: SimpleNamespace(model="test")) + monkeypatch.setattr(research_module, "agent_lm", lambda: SimpleNamespace(model="test")) @contextmanager def usage(_lm):