diff --git a/RUNLOG.md b/RUNLOG.md index 7c31d1a..ce62f10 100644 --- a/RUNLOG.md +++ b/RUNLOG.md @@ -246,3 +246,37 @@ state" resolved to France -> **KG hit: The Loire River (E2)** -> answer cites bo - dspy 3.4 `dspy.LM(...)` returns a list of AttributeDicts on raw call (`text` key) — wrapped in `floop/llm.py:active_lm`. - Tests at this point: 9 state + 5 machine + 3 knowledge = 17/17. + + +--- + +# Run D — cold-start fixed (2026-10-17) + +**Trigger:** Emili's home run failed on the same question that worked on the VPS. +The log was conclusive — and honest: the VPS success had been a warm-KG illusion; +the cold-start path had never been validated end-to-end. Reproduced 1:1 on the VPS +with a wiped KG (same queries, same articles, same UNKNOWN). + +Root causes (three, all in the gather): + +1. **Vertical wikitext tables unparsed.** 'Demographics of the European Union' holds + the ranking table with ONE CELL PER LINE; the parser assumed horizontal pipes. + The article was fetched, chunked, extracted — and its table was garbage rows. + Fix: `tables_as_text` handles both layouts + cell attributes (`_clean_cell`). + Verified live: `France | 69,112,309 | 15.29% | 638,475 | 15.1% | 107`. +2. **Quota eaten by per-query fetch order.** 'List of EU member states by + population' appeared in search results but never got a slot (quota spent on the + first query's generic articles). Fix: search ALL queries, dedupe, rank globally, + fetch one at a time with **early exit** when the KG starts answering. +3. **Pure title-relevance rank buried entity pages.** 'Loire' shares no word with + 'longest river in France' — lexical rank 0. Fix: hybrid order — each query's #1 + keeps a guaranteed slot (the engine's own relevance), the rest ranked by title + relevance. + +Cold-run result (KG empty at start): Q1 France (table row quote, source-verified) +-> Q2 The Loire (early exit after ONE article) -> final answer cites E1+E2. +Two bugs of my own found during the fix: a NameError from the refactor (caught by +the baseline fallback — the fallback layer earned its keep) and counter resets. + +Note for benchmarks: early exit cut Q1 from ~22 to ~3 articles-extracted and Q2 to +1 article; the gather now stops when the graph answers. diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index 994a120..f7fc7f5 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -55,6 +55,8 @@ class KnowledgeExpert: self.extract = dspy.Predict(ExtractSignature) self.answer = dspy.Predict(AnswerFromKG) self.translate = dspy.Predict(TranslateSignature) + self._checked = 0 + self._merged = 0 # ---- helpers ----------------------------------------------------------- def _log(self, text: str, think: bool = False) -> None: @@ -118,56 +120,111 @@ class KnowledgeExpert: if q.strip()][:2] if not queries: queries = [" ".join(kws[:3])] - self._log(f"translate -> queries {queries}", think=True) - pages: list[WikiPage] = [] - seen: set[str] = set() - for query in queries: - candidates = self.client.search(query, limit=self.cfg.max_search_results) - self._log(f"wiki search ({query!r}): {candidates}", think=True) - for title in candidates: - if len(pages) >= self.cfg.max_articles or title in seen: - continue - seen.add(title) - try: - pages.append(self.client.fetch_rich(title)) - except Exception as e: # noqa: BLE001 — network honesty: log and continue - self._log(f"fetch failed: {title}: {e}") + e_raw = (pred.entities or "").strip() + entity_terms = [t.strip() for t in + next((ln.split(":", 1)[1] for ln in e_raw.splitlines() + if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",") + if t.strip()][:4] + self._log(f"translate -> queries {queries} entities {entity_terms}", think=True) - # 5-7. chunk -> extract -> check -> merge (lexical gate on chunks) - checked = 0 - merged = 0 - for page in pages: - chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target, - cap=self.cfg.chunk_chars_cap) - gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted] - self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in") - for chunk in gated: - if charge_llm: - charge_llm() - raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) - for cand in parse_facts(raw.facts): - checked += 1 - ok, reason = check_candidate(cand, page.text) - if not ok: - self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") - continue - doc_id = self.store.add_document( - url=page.url, title=page.title, fetched_at=page.fetched_at, - sha256=hashlib.sha256(page.text.encode()).hexdigest()) - qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) - self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid) - merged += 1 + # search ALL queries first; merge + dedupe candidates; rank GLOBALLY + # by title relevance; then fetch one at a time with early exit + # (per-query quotas let generic articles eat the slots before the + # decisive article from a later query is even considered) + from .store import norm_name, stem + title_terms = {t for w in entity_terms + kws if len(w) > 2 + for t in (norm_name(w), stem(w))} + + def relevance(title: str) -> int: + tt = norm_name(title) + return sum(1 for t in title_terms if t and t in tt) + + candidates: list[str] = [] + seen_titles: set[str] = set() + per_query: list[list[str]] = [] + for query in queries: + found = self.client.search(query, limit=self.cfg.max_search_results) + per_query.append(found) + self._log(f"wiki search ({query!r}): {found}", think=True) + for title in found: + if title not in seen_titles: + seen_titles.add(title) + candidates.append(title) + # hybrid order: each query's #1 is guaranteed a slot (the engine's own + # relevance catches entity pages whose title shares no words with the + # question — e.g. 'Loire' for 'longest river in France'); the rest are + # ranked by title relevance (which pulls list articles up when they + # are the right source) + ordered: list[str] = [] + picked: set[str] = set() + for found in per_query: + if found and found[0] not in picked: + picked.add(found[0]) + ordered.append(found[0]) + for title in sorted((t for t in candidates if t not in picked), + key=relevance, reverse=True): + ordered.append(title) + self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True) + + pages: list[WikiPage] = [] + for title in ordered[: self.cfg.max_articles]: + try: + page = self.client.fetch_rich(title) + except Exception as e: # noqa: BLE001 — network honesty: log and continue + self._log(f"fetch failed: {title}: {e}") + continue + pages.append(page) + # EARLY EXIT: one article at a time; if the KG already answers, + # stop spending calls (the gather exists to fill the gap, not to + # hoover every candidate) + self._process_page(page, question, kws, charge_llm) + answer = self._answer_from_rows( + question, self.store.probe(probe_seeds), charge_llm) + if answer["value"] and answer["value"].upper() != "UNKNOWN": + self._log(f"early exit after {page.title}: " + f"{answer['value'][:60]}", think=True) + return {**answer, "source": "knowledge_graph", + "stats": {"pages": [p.title for p in pages]}} + + # 5-7. remaining pages already processed inline via _process_page + # (early exit); fall through to the final re-probe and answer. # 8. re-probe (same seeds) and answer from the merged KG rows = self.store.probe(probe_seeds) - self._log(f"merged {merged}/{checked} candidates; re-probe: {len(rows)} rows", think=True) + self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True) answer = self._answer_from_rows(question, rows, charge_llm) src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss" return {**answer, "source": src, - "stats": {"checked": checked, "merged": merged, + "stats": {"checked": self._checked, "merged": self._merged, "pages": [p.title for p in pages], "elapsed_s": round(time.time() - t0, 1)}} + def _process_page(self, page: WikiPage, question: str, kws: list[str], + charge_llm) -> int: + """Chunk -> gate -> extract -> check -> merge for ONE page. Returns + number of candidates merged this page. Counters ACCUMULATE on self.""" + chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target, + cap=self.cfg.chunk_chars_cap) + gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted] + self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in") + for chunk in gated: + if charge_llm: + charge_llm() + raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text) + for cand in parse_facts(raw.facts): + self._checked += 1 + ok, reason = check_candidate(cand, page.text) + if not ok: + self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") + continue + doc_id = self.store.add_document( + url=page.url, title=page.title, fetched_at=page.fetched_at, + sha256=hashlib.sha256(page.text.encode()).hexdigest()) + qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) + self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid) + self._merged += 1 + return self._merged + def _gate(self, chunk, keywords: list[str]) -> bool: """Lexical gate with stemming: chunk must mention a question stem.""" from .store import stem diff --git a/code/knowledge/wiki.py b/code/knowledge/wiki.py index 983c283..bbd8cb9 100644 --- a/code/knowledge/wiki.py +++ b/code/knowledge/wiki.py @@ -23,33 +23,51 @@ LANG = "en" def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str: - """Parse wikitext tables into plain text rows. Used by fetch_rich so - ranking/list articles (whose data lives in tables, not prose) carry - their facts; containment is checked against the ENRICHED text.""" + """Parse wikitext tables into one text line per row ('cell | cell | cell'). + + Handles BOTH layouts: horizontal rows ('| a || b || c') and vertical cells + (one cell per line, rows separated by '|-'). Cell attributes + ('| style=... | value') are dropped; links/templates resolved. Containment + is checked against the ENRICHED page text.""" out: list[str] = [] for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S): if len(out) >= max_tables: break rows: list[str] = [] + cells: list[str] = [] for line in m.group(1).splitlines(): line = line.strip() - if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell + if not line or line.startswith("|+"): # blank / caption continue - if line.startswith("!") or line.startswith("|"): - cells = [c.strip().lstrip("!|").strip() for c in line.split("||")] - cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells] - cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells] - cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells] - cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c] + if line.startswith("|-") or line.startswith("!-"): # row separator if cells: rows.append(" | ".join(cells)) - if len(rows) >= max_rows: - break + cells = [] + continue + if line.startswith("|") or line.startswith("!"): + body = line.lstrip("|!") + for cell in re.split(r"\|\||!!", body): + cell = _clean_cell(cell) + if cell: + cells.append(cell) + if cells: + rows.append(" | ".join(cells)) if rows: - out.append(chr(10).join(rows)) + out.append(chr(10).join(rows[:max_rows])) return (chr(10) * 2).join(out) +def _clean_cell(cell: str) -> str: + """Resolve links ([[a|b]]->b), templates ({{t|arg}}->arg), drop attrs and tags.""" + cell = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", cell) + cell = re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", cell) + cell = re.sub(r"\{\{[^}]*\}\}", "", cell) + if "|" in cell and "=" in cell.split("|")[0]: # '| attrs | value' -> value + cell = cell.split("|")[-1] + cell = re.sub(r"<[^>]+>", "", cell) + return cell.strip(" '\u201c\u201d") + + class WikiError(RuntimeError): pass