Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
109885773c | ||
|
|
5c97fbf50a | ||
|
|
efd539c128 | ||
|
|
2de9aaa738 | ||
|
|
8b50e3076e | ||
|
|
599188181c | ||
|
|
a43d827098 | ||
|
|
4506b4067a | ||
|
|
b5a9403063 | ||
|
|
dcd189057e | ||
|
|
0ef4f32c8f | ||
|
|
770ec616a9 | ||
|
|
9eab127727 | ||
|
|
ad9baf243b | ||
|
|
1ebb4cfc0d | ||
|
|
be320fd6a3 | ||
|
|
3f269e2467 | ||
|
|
12786cfc25 | ||
|
|
73fe5cc8e1 |
@@ -6,6 +6,8 @@ Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import dspy
|
||||
|
||||
from .state import AnswerType
|
||||
@@ -84,9 +86,13 @@ class FloopModules:
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> list[dict]:
|
||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||
"""(parsed subquestions, raw model output). The machine decides what
|
||||
an empty parse means: empty raw = the question is atomic; non-empty
|
||||
raw that parses to nothing = model garbage (run I) — degrade."""
|
||||
pred = self.init(question=question)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
@@ -111,17 +117,36 @@ class FloopModules:
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
_LINE_NO = re.compile(r"\d{1,2}[.)]?")
|
||||
_ENUM = re.compile(r"^\d{1,2}[.)]?\s*[-–:]?\s+")
|
||||
|
||||
|
||||
def _clean_qtext(t: str) -> str:
|
||||
"""Strip a leading enumerator ('1.', '2)', '3 -') from a subquestion."""
|
||||
return _ENUM.sub("", t.strip()).strip()
|
||||
|
||||
|
||||
def parse_subquestions(raw: str) -> list[dict]:
|
||||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type."""
|
||||
""">> parse the piped lines from INIT/MISSING: text | deps | answer_type.
|
||||
|
||||
The piped format is the contract; models still decorate it (run I):
|
||||
qwen wrote its own line numbers as an extra first pipe field
|
||||
('1 | Who was the President before Pedro Sanchez? | none | OPEN') and
|
||||
the naive parse took '1' as the text — Q1 routed as 'numeric' on the
|
||||
literal question '1'. The parser now shifts the numbered form and
|
||||
drops any field that is a bare number: a routable question is text."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip().lstrip("-•* ").strip()
|
||||
if not line or "|" not in line:
|
||||
continue
|
||||
parts = [p.strip() for p in line.split("|")]
|
||||
text = parts[0]
|
||||
if not text:
|
||||
continue
|
||||
# qwen's line-number prefix: an extra first field, bare number
|
||||
if len(parts) >= 4 and _LINE_NO.fullmatch(parts[0]):
|
||||
parts = parts[1:]
|
||||
text = _clean_qtext(parts[0])
|
||||
if not text or _LINE_NO.fullmatch(text):
|
||||
continue # a number is a line number, never a question
|
||||
deps_raw = parts[1].lower() if len(parts) > 1 else "none"
|
||||
atype_raw = parts[2].upper() if len(parts) > 2 else "OPEN"
|
||||
deps: list = []
|
||||
|
||||
+38
-7
@@ -130,6 +130,12 @@ class KnowledgeEngine:
|
||||
src = ans.get("source", "wikipedia_miss")
|
||||
value = ans.get("value", "UNKNOWN")
|
||||
payload = {"value": value}
|
||||
# Layer-1 ambiguity flag (run J): the answer is ONE defensible
|
||||
# reading; the payload carries the others for the layers above
|
||||
if ans.get("ambiguous"):
|
||||
payload["ambiguous"] = True
|
||||
payload["axis"] = ans.get("axis", "")
|
||||
payload["alternatives"] = ans.get("alternatives", [])
|
||||
if ans.get("quote"):
|
||||
payload["quote"] = ans["quote"]
|
||||
if ans.get("url"):
|
||||
@@ -139,9 +145,19 @@ class KnowledgeEngine:
|
||||
payload["list_count"] = ans.get("list_count", len(ans["list_items"]))
|
||||
if ans.get("coverage"):
|
||||
payload["coverage"] = ans["coverage"]
|
||||
# PR-3 — the skim notice: what the fetched articles contained beyond
|
||||
# this answer (tables/infobox/link surfaces with goal signals). A
|
||||
# POINTER for later steps, not evidence: it never answers a question,
|
||||
# it tells the router what exists and where it lives.
|
||||
skim_notices = (ans.get("stats") or {}).get("skim") or []
|
||||
if skim_notices:
|
||||
payload["skim"] = skim_notices[:3]
|
||||
prov = {"expert": "knowledge", "source": src,
|
||||
"note": ("source-verified: verbatim containment in trusted doc"
|
||||
if ans.get("quote") else "no quote — unverified")}
|
||||
"note": ("ambiguous: several office readings exist — the "
|
||||
"choice among them is not verified"
|
||||
if ans.get("ambiguous") else
|
||||
("source-verified: verbatim containment in trusted doc"
|
||||
if ans.get("quote") else "no quote — unverified"))}
|
||||
# LIST rows: the answer-level check corroborates the count outside the
|
||||
# source table; combined with per-source completeness it makes the
|
||||
# row verified (E3-style verified semantics, first non-stub use).
|
||||
@@ -155,16 +171,31 @@ class KnowledgeEngine:
|
||||
prov["parent_question"] = parent_question
|
||||
note = "" if value.upper() != "UNKNOWN" else "knowledge returned UNKNOWN"
|
||||
if streams is not None:
|
||||
# LIST rows: value is the COUNT — the members are the real answer;
|
||||
# render them (first 10, then +N) or the log shows an opaque '22'
|
||||
# THE ANSWER, in full view (run H: the first knowledge answer was
|
||||
# only deducible from the fan-out that followed). Q ref + every
|
||||
# field the machine will act on.
|
||||
qref = qid if qid else "Q?"
|
||||
if isinstance(ans.get("list_items"), list) and ans["list_items"]:
|
||||
items = ans["list_items"]
|
||||
shown = ", ".join(items[:10]) + (f" (+{len(items) - 10} more)" if len(items) > 10 else "")
|
||||
shown = ", ".join(items[:8]) + (f" (+{len(items) - 8} more)" if len(items) > 8 else "")
|
||||
streams.output("EXPERT",
|
||||
f"value={value} list={shown} [{src}]")
|
||||
f"{qref} -> ANSWER value={value} (list of "
|
||||
f"{len(items)} members: {shown}) quote="
|
||||
f"{(ans.get('quote') or '')[:60]} url="
|
||||
f"{ans.get('url') or ''} [{src}]")
|
||||
elif ans.get("ambiguous"):
|
||||
alts = "; ".join(a.get("value", "")
|
||||
for a in (ans.get("alternatives") or [])[:3])
|
||||
streams.output("EXPERT",
|
||||
f"{qref} -> ANSWER value={value} "
|
||||
f"AMBIGUOUS ({alts}) quote="
|
||||
f"{(ans.get('quote') or '')[:60]} url="
|
||||
f"{ans.get('url') or ''} [{src}]")
|
||||
else:
|
||||
streams.output("EXPERT",
|
||||
f"value={value} quote={(ans.get('quote') or '')[:80]} [{src}]")
|
||||
f"{qref} -> ANSWER value={value} quote="
|
||||
f"{(ans.get('quote') or '')[:80]} url="
|
||||
f"{ans.get('url') or ''} [{src}]")
|
||||
return EvidenceRow(
|
||||
qid=qid,
|
||||
answer_type=answer_type,
|
||||
|
||||
@@ -2,10 +2,17 @@
|
||||
|
||||
dspy 3.x routes through litellm, so model ids carry the provider prefix —
|
||||
"openai/<model>" for any OpenAI-compatible endpoint (local ollama or ollama-cloud).
|
||||
|
||||
This module also installs the PROMPT LOG: a dspy global callback that writes
|
||||
every LLM call's exact rendered prompt to runs/<ts>/prompts/NN-stage.txt and a
|
||||
size line to run.log — the "what did it actually send?" channel that the log's
|
||||
CALL/OUTPUT lines never carried (GAP: run G, call 8/80 — a 22k-char table
|
||||
chunk sat for minutes with no way to see the prompt without rebuilding it).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import dspy
|
||||
@@ -17,6 +24,153 @@ def _load_yaml() -> dict:
|
||||
return yaml.safe_load(cfg.read_text())
|
||||
|
||||
|
||||
def _slug_stage(text: str, maxlen: int = 24) -> str:
|
||||
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
||||
return s[:maxlen].rstrip("-") or "call"
|
||||
|
||||
|
||||
class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
"""Writes the exact rendered prompt of every LM call to the run dir.
|
||||
|
||||
dspy fires on_module_start/on_module_end around each Predict's forward
|
||||
(call_id DIFFERENT from the inner LM call's), so a call_id-keyed map
|
||||
would lose the stage. A stack does not: the LM call runs synchronously
|
||||
inside the innermost module's forward, so the top of the stack at
|
||||
on_lm_start IS the stage that made the call.
|
||||
|
||||
Output: runs/<ts>/prompts/NN-stage.txt — NN mirrors the budget counter
|
||||
(charge happens before the Predict runs), so 08-extract.txt IS the
|
||||
call 8/80 of run G that hung for minutes. Plus size/duration lines in
|
||||
run.log; the exact prompt is in the file, log stays line-based.
|
||||
|
||||
RE-ASK METER (run L): dspy's chat adapter, on a parse failure, re-fires
|
||||
the SAME module's LM call through its JSON fallback — an extra wire call
|
||||
the budget counter never charged (9/80 logged, 10 on the wire, the
|
||||
second burning 340s of GPU). The meter sees them (same module depth in
|
||||
the stack twice), charges the budget via an optional meter hook, and
|
||||
logs the line — dspy's BEHAVIOUR is untouched (his call: the fallback
|
||||
stays; it is future self-improvement signal, not a bug to fix).
|
||||
"""
|
||||
|
||||
def __init__(self, streams) -> None:
|
||||
self.streams = streams # RunStreams or None (baseline mode)
|
||||
self._stack: list[str] = [] # nested module stages (innermost last)
|
||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||
self.reasks = 0 # LM calls the budget did not charge
|
||||
self.meter = None # callable(str stage) -> None; budget charge
|
||||
|
||||
# -- dspy plumbing -------------------------------------------------------
|
||||
|
||||
def on_module_start(self, call_id, instance, inputs):
|
||||
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
||||
self._stack.append(label)
|
||||
self._fresh_forward = True # this forward's first LM call is not a re-ask
|
||||
|
||||
def on_module_end(self, call_id, outputs, exception):
|
||||
if self._stack:
|
||||
self._stack.pop()
|
||||
|
||||
def on_lm_start(self, call_id, instance, inputs):
|
||||
import time
|
||||
self._starts[call_id] = time.monotonic()
|
||||
label = self._stack[-1] if self._stack else "lm"
|
||||
self._stage_of[call_id] = label
|
||||
streams = self.streams
|
||||
msgs = inputs.get("messages", []) or []
|
||||
text = "\n\n".join(
|
||||
f"[{m.get('role', '?')}] {m.get('content', '')}" for m in msgs
|
||||
if isinstance(m, dict)
|
||||
)
|
||||
chars = len(text)
|
||||
# RE-ASK METER: a second LM call with NO new module forward between
|
||||
# them is dspy's adapter fallback re-firing inside the same Predict
|
||||
# (ChatAdapter catches AdapterParseError and re-calls via JSONAdapter)
|
||||
# — an extra wire call the budget did not charge. Consecutive SAME-
|
||||
# stage calls from DIFFERENT forwards (the ablation rounds) are NOT
|
||||
# re-asks: each round opens its own module.
|
||||
fresh = getattr(self, "_fresh_forward", False)
|
||||
self._fresh_forward = False
|
||||
self._lm_seen = getattr(self, "_lm_seen", 0) + 1
|
||||
reask = self._lm_seen > 1 and not fresh
|
||||
if reask:
|
||||
self.reasks += 1
|
||||
if streams is not None:
|
||||
streams.log(f"re-ask detected: stage={label} "
|
||||
f"(adapter parse-failure fallback, charged to budget)")
|
||||
if self.meter is not None:
|
||||
try:
|
||||
self.meter(label)
|
||||
except Exception: # noqa: BLE001 — metering must never kill a run
|
||||
pass
|
||||
if streams is not None:
|
||||
n = streams.bump_prompt_seq()
|
||||
fn = f"{n:02d}-{label}.txt"
|
||||
pdir = streams.run_dir / "prompts"
|
||||
pdir.mkdir(exist_ok=True)
|
||||
f = pdir / fn
|
||||
f.write_text(
|
||||
f"# stage={label} call_seq={n} chars={chars} "
|
||||
f"tokens~{chars // 4}\n\n" + text,
|
||||
encoding="utf-8",
|
||||
)
|
||||
self._file_of[call_id] = f
|
||||
streams.log(
|
||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||
f"-> prompts/{fn}"
|
||||
)
|
||||
else:
|
||||
print(f"[prompt] stage={label} chars={chars} tokens~{chars // 4}")
|
||||
|
||||
def on_lm_end(self, call_id, outputs, exception):
|
||||
import time
|
||||
streams = self.streams
|
||||
label = self._stage_of.pop(call_id, "lm")
|
||||
start = self._starts.pop(call_id, None)
|
||||
f = self._file_of.pop(call_id, None)
|
||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
||||
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
||||
# the parsed OUTPUT can lie by omission (run I)
|
||||
if f is not None:
|
||||
raw = ""
|
||||
if isinstance(outputs, list):
|
||||
raw = "\n".join(str(o) for o in outputs)
|
||||
elif outputs is not None:
|
||||
raw = str(outputs)
|
||||
with f.open("a", encoding="utf-8") as fh:
|
||||
fh.write(
|
||||
f"\n\n# RAW RESPONSE (after {dur}"
|
||||
+ (f", exception={exception!r}" if exception else "")
|
||||
+ ")\n" + (raw or "(empty)"))
|
||||
if streams is not None:
|
||||
streams.log(f"prompt {label} done in {dur}")
|
||||
|
||||
|
||||
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
||||
_STAGE_BY_MODULE = {
|
||||
"Predict": "predict",
|
||||
"InitDecompose": "INIT",
|
||||
"Route": "ROUTE",
|
||||
"Expert": "EXPERT",
|
||||
"Missing": "MISSING",
|
||||
"Answer": "ANSWER",
|
||||
"KnowledgeExpert": "knowledge",
|
||||
"InitSignature": "INIT",
|
||||
"RouteSignature": "ROUTE",
|
||||
"ExpertSignature": "EXPERT",
|
||||
"MissingSignature": "MISSING",
|
||||
"AnswerSignature": "ANSWER",
|
||||
"ExtractSignature": "EXTRACT",
|
||||
"AnswerFromKG": "answer_kg",
|
||||
"TranslateSignature": "TRANSLATE",
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
"SkimPromoteSignature": "PROMOTE",
|
||||
}
|
||||
|
||||
|
||||
def configure_lm() -> dict:
|
||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||
|
||||
@@ -43,7 +197,19 @@ def configure_lm() -> dict:
|
||||
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
|
||||
|
||||
|
||||
def install_prompt_log(streams) -> None:
|
||||
"""Attach the prompt log callback globally (call once per run, after
|
||||
configure_lm). Idempotent: replacing streams re-installs one callback."""
|
||||
global _PROMPT_LOG
|
||||
if _PROMPT_LOG is not None:
|
||||
_PROMPT_LOG.streams = streams
|
||||
return
|
||||
_PROMPT_LOG = PromptLogCallback(streams)
|
||||
dspy.configure(callbacks=[_PROMPT_LOG])
|
||||
|
||||
|
||||
_ACTIVE: "dspy.LM | None" = None
|
||||
_PROMPT_LOG: "PromptLogCallback | None" = None
|
||||
|
||||
|
||||
def active_lm() -> "dspy.LM":
|
||||
|
||||
+60
-5
@@ -91,6 +91,14 @@ class FloopRun:
|
||||
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
||||
self.notes: list[str] = []
|
||||
self.engine_calls = 0
|
||||
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
|
||||
# the budget never charged. The prompt-log callback sees them; wire
|
||||
# its meter to our budget so the count is honest. The BEHAVIOUR of
|
||||
# dspy stays untouched (his call: the fallback is future
|
||||
# self-improvement signal, not a bug).
|
||||
from .llm import _PROMPT_LOG
|
||||
if _PROMPT_LOG is not None:
|
||||
_PROMPT_LOG.meter = self._meter_reask
|
||||
|
||||
# ---- budget -----------------------------------------------------------
|
||||
|
||||
@@ -99,6 +107,16 @@ class FloopRun:
|
||||
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
|
||||
f"/{self.budget.max_llm_calls} depth={self.depth}")
|
||||
|
||||
def _meter_reask(self, stage: str) -> None:
|
||||
"""The prompt-log callback detected an adapter re-ask: charge the
|
||||
budget for the extra wire call (a re-ask may hit the ceiling but
|
||||
never kills the run mid-step), and note it for the report."""
|
||||
try:
|
||||
self.budget.charge_llm()
|
||||
except BudgetExhausted:
|
||||
pass # ceiling reached: the call already happened; note only
|
||||
self.notes.append(f"re-ask charged: stage={stage}")
|
||||
|
||||
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
|
||||
|
||||
def run(self) -> RunReport:
|
||||
@@ -134,8 +152,20 @@ class FloopRun:
|
||||
self._charge()
|
||||
self.streams.call("INIT", f"decompose: {self.query[:80]}",
|
||||
think=self.tprefix + f"decomposing: {self.query[:100]}")
|
||||
subs = self.modules.init_decompose(self.query)
|
||||
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
||||
subs, raw = self.modules.init_decompose(self.query)
|
||||
if not subs and (raw or "").strip():
|
||||
# DEGRADE (run I): the model WROTE subquestions but none parsed
|
||||
# (its numbered format beat the parser) — route the ORIGINAL
|
||||
# question as one OPEN subquestion instead of routing garbage
|
||||
# like a bare '1'. Deterministic, logged, budget-safe. The
|
||||
# atomic case (empty raw) keeps the old stop-and-synthesize.
|
||||
self.streams.output(
|
||||
"INIT", f"(no parseable subquestions from {len(raw)} chars "
|
||||
f"— degrading to the original question)", think=True)
|
||||
subs = [{"text": self.query, "deps": [],
|
||||
"answer_type": AnswerType.OPEN}]
|
||||
else:
|
||||
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
|
||||
self._add_questions(subs, reason="init")
|
||||
|
||||
def _missing_round(self) -> None:
|
||||
@@ -435,6 +465,18 @@ class FloopRun:
|
||||
# fan-out bookkeeping: entity rows carry the group so the join finds them
|
||||
if q.fan_group:
|
||||
row.provenance["fan_group"] = q.fan_group
|
||||
# PR-3: skim notices also land in the run notes — legibility law:
|
||||
# derived answers render CONTENT, not counts alone
|
||||
for n in (row.payload.get("skim") or [])[:2]:
|
||||
self.notes.append(f"{q.qid}: skim: {n[:150]}")
|
||||
# Layer-1 ambiguity audit (run J): the expert flagged several office
|
||||
# readings — the report must carry them, the machine must not choose
|
||||
if row.payload.get("ambiguous"):
|
||||
alts = row.payload.get("alternatives") or []
|
||||
self.notes.append(
|
||||
f"{q.qid}: AMBIGUOUS: {row.payload.get('axis')} — "
|
||||
f"other readings: " + "; ".join(
|
||||
a.get("value") for a in alts[:3]))
|
||||
self.table.append(row)
|
||||
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
||||
q.status = "failed"
|
||||
@@ -445,17 +487,28 @@ class FloopRun:
|
||||
def _context(self, q: OpenQuestion) -> str:
|
||||
"""What the router sees. A list row renders its ITEMS — 'E1: 50' is
|
||||
an ambiguous scalar that routes 'those countries' questions to the
|
||||
user; 'E1: list of 50 items: Albania, ...' answers them."""
|
||||
user; 'E1: list of 50 items: Albania, ...' answers them. Skim notices
|
||||
(PR-3) render as 'seen in passing' pointers — the router knows what
|
||||
exists and where it lives, without treating it as answered evidence."""
|
||||
def render(r) -> str:
|
||||
if isinstance(r.payload.get("list_items"), list):
|
||||
return (f"list of {r.payload['list_count']} items: "
|
||||
f"{', '.join(r.payload['list_items'][:8])}...")
|
||||
return str(r.payload.get("value", r.payload.get("quote", "")))
|
||||
val = str(r.payload.get("value", r.payload.get("quote", "")))
|
||||
if r.payload.get("ambiguous"):
|
||||
alts = r.payload.get("alternatives") or []
|
||||
other = "; ".join(a.get("value", "") for a in alts[:3])
|
||||
return (f"{val} — AMBIGUOUS, other defensible readings: "
|
||||
f"{other}")
|
||||
return val
|
||||
|
||||
lines = []
|
||||
notices = []
|
||||
for d in q.deps:
|
||||
for r in self.table.for_question(d):
|
||||
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
||||
for n in (r.payload.get("skim") or [])[:2]:
|
||||
notices.append(f"seen in passing ({r.eid}): {n}")
|
||||
if not lines:
|
||||
# no declared deps: the router must still SEE what the machine
|
||||
# holds — an empty context routes referential questions to the
|
||||
@@ -464,7 +517,9 @@ class FloopRun:
|
||||
if r.retracted:
|
||||
continue
|
||||
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
|
||||
return "\n".join(lines[:8])
|
||||
for n in (r.payload.get("skim") or [])[:2]:
|
||||
notices.append(f"seen in passing ({r.eid}): {n}")
|
||||
return "\n".join(lines[:8] + notices[:4])
|
||||
|
||||
# ---- answer ------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -34,8 +34,15 @@ class RunStreams:
|
||||
self.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.log_path = self.run_dir / "run.log"
|
||||
self.verbose = verbose
|
||||
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
||||
self._fh = open(self.log_path, "a", encoding="utf-8")
|
||||
|
||||
def bump_prompt_seq(self) -> int:
|
||||
"""Next exact-prompt file number (mirrors the budget counter: the
|
||||
charge precedes the Predict, so NN == budget llm_calls)."""
|
||||
self.prompt_seq += 1
|
||||
return self.prompt_seq
|
||||
|
||||
def close(self) -> None:
|
||||
if self._fh and not self._fh.closed:
|
||||
self._fh.close()
|
||||
|
||||
+569
-24
@@ -23,13 +23,84 @@ import dspy
|
||||
|
||||
from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
|
||||
TranslateSignature, VerifyCountSignature, parse_facts)
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature)
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import WikipediaClient, WikiPage
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag, parse_stop_table)
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
|
||||
# header/caption terms that name the ENTITY column of a typical scalar table
|
||||
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
||||
|
||||
|
||||
def _tokens(text: str) -> set[str]:
|
||||
"""Casefolded word tokens — the boundary-correct matching base. 'flow'
|
||||
must not match 'Outflow' (run H: 227 world rows ingested as 'Outflow'
|
||||
edges because a goal term hit a substring)."""
|
||||
return {w.casefold() for w in WORD_RE.findall(text or "")}
|
||||
|
||||
|
||||
def _term_hits(term: str, text: str) -> bool:
|
||||
"""Goal-term match with word boundaries: the term must appear as a
|
||||
WHOLE token (stem tolerated) in the text's tokens."""
|
||||
if not term:
|
||||
return False
|
||||
toks = _tokens(text)
|
||||
if term.casefold() in toks:
|
||||
return True
|
||||
from .store import stem
|
||||
return stem(term) in {stem(t) for t in toks if t}
|
||||
|
||||
|
||||
def _col_hits(col: str, header: str) -> bool:
|
||||
"""The LLM names a column (possibly multi-word: 'Mean discharge').
|
||||
It matches a header when any of its content tokens appears as a whole
|
||||
token in the header ('discharge' in 'Average discharge' -> True;
|
||||
'Flow at the mouth' vs 'Length (km)' -> False)."""
|
||||
if not col:
|
||||
return False
|
||||
stops = {"the", "at", "of", "in", "a", "an", "and"}
|
||||
from .store import stem
|
||||
ctoks = {t for t in _tokens(col) if t not in stops and len(t) > 2}
|
||||
if not ctoks:
|
||||
return False
|
||||
htoks = _tokens(header)
|
||||
hstems = {stem(t) for t in htoks if t}
|
||||
return any(c in htoks or stem(c) in hstems for c in ctoks)
|
||||
|
||||
|
||||
def _prop_hit(prop: str, toks: set[str]) -> bool:
|
||||
"""Proper-noun subject match: whole token, stem, or WORD PREFIX —
|
||||
'Europe' matches 'European' (the gentilici pattern is everywhere on
|
||||
Wikipedia: 'List of European states' answers 'countries in Europe?').
|
||||
Prefix >= 4 chars keeps it from matching junk."""
|
||||
pl = prop.casefold()
|
||||
from .store import stem
|
||||
ps = stem(pl)
|
||||
for t in toks:
|
||||
if t == pl or stem(t) == ps:
|
||||
return True
|
||||
if len(pl) >= 4 and (t.startswith(pl) or pl.startswith(t) and len(t) >= 4):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _proper_nouns(question: str) -> set[str]:
|
||||
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
|
||||
question. The definitive guard for 'which are the three longest rivers
|
||||
of Italy?' never accepting a world table (run H: Q1 answered Nile/
|
||||
Amazon/Yangtze because the top search hit was the world list and the
|
||||
disjointness guard was vacuous — no evidence, nothing to check)."""
|
||||
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
|
||||
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||
"Their", "Its", "Those", "These", "That", "This"}
|
||||
return {w for w in words if w not in stops}
|
||||
|
||||
|
||||
@dataclass
|
||||
class KnowledgeConfig:
|
||||
@@ -38,8 +109,13 @@ class KnowledgeConfig:
|
||||
max_search_results: int = 4 # candidates considered
|
||||
max_chunks_extracted: int = 6 # per call (lexical gate decides which)
|
||||
max_extract_retries: int = 2
|
||||
ambiguity_rounds: int = 3 # ablation rounds per scalar answer (run J)
|
||||
chunk_chars_target: int = 32000
|
||||
chunk_chars_cap: int = 48000
|
||||
# skim harvest (PR-2): goal-relevant side-tables are ingested in passing
|
||||
skim_harvest: bool = True # opportunistic typed ingestion, zero LLM
|
||||
skim_harvest_max_tables: int = 2 # per article, beyond the LIST answer
|
||||
skim_link_queue: bool = True # goal-region links join the fetch order
|
||||
|
||||
|
||||
class KnowledgeExpert:
|
||||
@@ -57,8 +133,15 @@ class KnowledgeExpert:
|
||||
self.translate = dspy.Predict(TranslateSignature)
|
||||
self.select_table = dspy.Predict(SelectTableSignature)
|
||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
||||
self._checked = 0
|
||||
self._merged = 0
|
||||
# skim notices accumulated this CALL (PR-3): what the fetched
|
||||
# articles contained beyond the current question's answer
|
||||
self._skim_notices: list[str] = []
|
||||
# ambiguous leads (quantity tables with no goal-vocabulary match)
|
||||
# pending the bounded promotion decision
|
||||
self._skim_leads: list[tuple[WikiPage, WikiTable]] = []
|
||||
|
||||
# ---- helpers -----------------------------------------------------------
|
||||
def _log(self, text: str, think: bool = False) -> None:
|
||||
@@ -132,6 +215,22 @@ class KnowledgeExpert:
|
||||
if evidence:
|
||||
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
|
||||
kws = self._keywords(question)
|
||||
goal_terms = self._keywords(parent_question) if parent_question else []
|
||||
self._current_goal_terms = goal_terms # the harvest reads these
|
||||
self._current_goal_question = parent_question or question
|
||||
# per-CALL skim state (PR-3): notices for the machine + ambiguous
|
||||
# leads pending the bounded promotion decision
|
||||
self._skim_notices: list[str] = []
|
||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
||||
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
|
||||
# before network search so a later question pays zero re-fetch
|
||||
if not hasattr(self, "_seen_pages"):
|
||||
self._seen_pages: dict[str, WikiPage] = {}
|
||||
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
|
||||
# order as candidates (hops still live in the plan — the law stands)
|
||||
if not hasattr(self, "_link_queue"):
|
||||
self._link_queue: list[str] = []
|
||||
# LIST activation (moved up: the set gate needs it before the probe)
|
||||
list_mode = (str(answer_type or "").upper() == "LIST"
|
||||
or self._is_enumeration(question))
|
||||
@@ -161,7 +260,8 @@ class KnowledgeExpert:
|
||||
answer = self._answer_from_rows(question, rows, charge_llm)
|
||||
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
||||
self._log(f"kg hit: {answer['value'][:60]}", think=True)
|
||||
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
|
||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||
|
||||
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
|
||||
# entity-first Wikipedia queries — deterministic keywords alone surface
|
||||
@@ -224,12 +324,47 @@ class KnowledgeExpert:
|
||||
|
||||
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
|
||||
if title in self._seen_pages:
|
||||
page = self._seen_pages[title]
|
||||
self._log(f"seen-index hit: {title} (already fetched this run)",
|
||||
think=True)
|
||||
else:
|
||||
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
|
||||
self._seen_pages[title] = page
|
||||
pages.append(page)
|
||||
# SKIM (PR-1): the structural read, in passing — question AND goal
|
||||
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
||||
# ranking in _process_page; PR-2's harvest runs on its signals.
|
||||
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
||||
evidence_entities=ev_entities)
|
||||
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
||||
# PR-3 — the skim notice: goal-relevant surfaces seen in passing,
|
||||
# so later steps (router context, run notes) know what exists
|
||||
# and where it lives. Filtered to goal signals: the notice is a
|
||||
# pointer, not a dump.
|
||||
notice = sheet.notice()
|
||||
if notice:
|
||||
goal_signal = (any(_term_hits(gt, notice) for gt in goal_terms)
|
||||
or any(find_quantities(notice)))
|
||||
if goal_signal or not goal_terms:
|
||||
self._skim_notices.append(notice)
|
||||
if self.cfg.skim_link_queue:
|
||||
for link in sheet.link_candidates:
|
||||
if link not in self._link_queue:
|
||||
self._link_queue.append(link)
|
||||
# PR-2 — the opportunistic harvest: goal-relevant side-tables
|
||||
# seen in passing become typed edges (zero LLM, containment law)
|
||||
self._harvest_side_tables(page, sheet, question, evidence)
|
||||
# PR-3 — bounded promotion of ambiguous leads (one LLM call,
|
||||
# only when leads exist): promoted tables ingest through the
|
||||
# same containment-checked path as the deterministic harvest
|
||||
self._promote_leads(evidence, charge_llm)
|
||||
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL
|
||||
# rows and answer by aggregation (no extract calls, no gate)
|
||||
if list_mode and page.tables:
|
||||
@@ -238,27 +373,34 @@ class KnowledgeExpert:
|
||||
self._log(f"early exit after {page.title}: list "
|
||||
f"({ans['list_count']} items)", think=True)
|
||||
return {**ans, "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
# refused by the guard: wrong article's list — keep gathering
|
||||
# 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). For enumerations the set gate applies
|
||||
# here too: mention rows never answer a list question.
|
||||
self._process_page(page, question, kws, charge_llm)
|
||||
self._process_page(page, question, kws, charge_llm,
|
||||
goal_terms=goal_terms)
|
||||
if list_mode:
|
||||
hit = self._set_gate_hit(probe_seeds, question)
|
||||
if hit is not None:
|
||||
self._log(f"early exit after {page.title}: set {hit}", think=True)
|
||||
return {**self._serve_set(hit, question), "source": "knowledge_graph",
|
||||
"stats": {"pages": [p.title for p in pages]}}
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
else:
|
||||
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]}}
|
||||
return {**self._audit_ambiguity(question, answer,
|
||||
self.store.probe(probe_seeds),
|
||||
charge_llm),
|
||||
"source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"skim": self._skim_notices}}
|
||||
|
||||
# 5-7. remaining pages already processed inline via _process_page
|
||||
# (early exit); fall through to the final re-probe and answer.
|
||||
@@ -268,11 +410,17 @@ class KnowledgeExpert:
|
||||
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": self._checked, "merged": self._merged,
|
||||
"pages": [p.title for p in pages],
|
||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
|
||||
"stats": {**self._skim_stats(pages),
|
||||
"checked": self._checked, "merged": self._merged,
|
||||
"skim": self._skim_notices,
|
||||
"elapsed_s": round(time.time() - t0, 1)}}
|
||||
|
||||
def _skim_stats(self, pages: list[WikiPage]) -> dict:
|
||||
"""stats shared by every return path: pages seen + link queue state."""
|
||||
return {"pages": [p.title for p in pages],
|
||||
"link_queue": len(self._link_queue)}
|
||||
|
||||
def _expected_entities(self, evidence: str) -> list[str]:
|
||||
"""Entities the parent's evidence already names — 'the three longest
|
||||
rivers' means the answer's members must be among them. Extracted
|
||||
@@ -334,6 +482,110 @@ class KnowledgeExpert:
|
||||
and w not in ("states?", "does", "was", "has")]
|
||||
return bool(words & ask) and len(plurals) >= 1
|
||||
|
||||
def _audit_ambiguity(self, question: str, answer: dict, rows,
|
||||
charge_llm=None) -> dict:
|
||||
"""Ablation ambiguity detector (KNOWLEDGE.md §8, run J).
|
||||
|
||||
The KG just answered with value V from some support row(s). Ask the
|
||||
SAME judge (AnswerFromKG) whether the question ALSO answers without
|
||||
that support: mask the rows whose object/relation produced V, re-ask.
|
||||
A DIFFERENT surviving value = a second defensible reading -> flag.
|
||||
Repeat (bounded) until the rows run out of answers. Same-value
|
||||
survivors are corroboration, not ambiguity — silent.
|
||||
|
||||
Zero new prompts: same AnswerFromKG signature, one call per round.
|
||||
The store is NEVER mutated — the mask is a view, deletion happens
|
||||
nowhere. Ordinary questions end at round 1 with UNKNOWN (silent).
|
||||
"""
|
||||
value = str(answer.get("value", "")).strip()
|
||||
if (not value or value.upper() == "UNKNOWN" or not rows):
|
||||
return answer
|
||||
|
||||
# The supporting rows for the PICKED value. DST-FIRST LAW (run L):
|
||||
# when a row has a meaningful dst it is the VALUE BEARER — quotes
|
||||
# interleave readings in one paragraph ('... Secretary-General ...
|
||||
# president of Socialist International ...' is ONE quote), so
|
||||
# quote-matching over-masks and the audit dies silent at round 1.
|
||||
# The quote is a fallback ONLY for rows whose dst is empty/numeric.
|
||||
_NUMERIC_RE = re.compile(r"^[\d\s.,:+\-/–—%]+$")
|
||||
|
||||
def _dst(r) -> str:
|
||||
return (getattr(r, "dst", "") or "").strip()
|
||||
|
||||
def _dst_meaningful(r) -> bool:
|
||||
d = _dst(r)
|
||||
return bool(d) and not _NUMERIC_RE.match(d)
|
||||
|
||||
def _carries(r) -> bool:
|
||||
v = value.casefold()
|
||||
if _dst_meaningful(r):
|
||||
return v in _dst(r).casefold()
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
return v in quote
|
||||
|
||||
def _carries_target(r, val: str) -> bool:
|
||||
"""DST-FIRST law, parameterized for a round's surviving value.
|
||||
|
||||
The judge's value may be an OFFICE DESCRIPTION, not the dst
|
||||
entity itself ('prime minister of Spain' vs dst='Spain') —
|
||||
resolve the row by reciprocal token containment: the dst
|
||||
names the entity, the value describes the reading; overlap
|
||||
means this row carried it."""
|
||||
v = val.casefold()
|
||||
if _dst_meaningful(r):
|
||||
d = _dst(r).casefold()
|
||||
if v == d or v in d or d in v:
|
||||
return True
|
||||
vt = set(WORD_RE.findall(v))
|
||||
dt = set(WORD_RE.findall(d))
|
||||
return bool(vt & dt) if vt and dt else False
|
||||
quote = (getattr(r, "quote", "") or "").strip().casefold()
|
||||
return v in quote
|
||||
|
||||
support = [r for r in rows if _carries(r)]
|
||||
if not support:
|
||||
return answer # the judge invented it: nothing to ablate
|
||||
|
||||
alternatives: list[dict] = []
|
||||
seen = {norm_name(value)}
|
||||
masked = set(id(r) for r in support)
|
||||
|
||||
for _ in range(self.cfg.ambiguity_rounds):
|
||||
view = [r for r in rows if id(r) not in masked]
|
||||
if not view:
|
||||
break
|
||||
re_ans = self._answer_from_rows(question, view, charge_llm)
|
||||
re_val = str(re_ans.get("value", "")).strip()
|
||||
if not re_val or re_val.upper() == "UNKNOWN":
|
||||
break # the KG has no other reading: clean
|
||||
key = norm_name(re_val)
|
||||
if key in seen:
|
||||
break # same value again: corroboration, not ambiguity
|
||||
seen.add(key)
|
||||
# which surviving row produced this reading? DST-FIRST here too
|
||||
# — same law as the pick's mask, for the report and the next mask
|
||||
src_row = next((r for r in view if _carries_target(r, re_val)), None)
|
||||
alternatives.append({
|
||||
"value": re_val,
|
||||
"quote": re_ans.get("quote", ""),
|
||||
"url": (src_row.url if src_row is not None
|
||||
else re_ans.get("url", "")),
|
||||
})
|
||||
# mask this reading's own support too — next round hunts a third
|
||||
new_support = [r for r in view if _carries_target(r, re_val)]
|
||||
if not new_support:
|
||||
break
|
||||
masked |= set(id(r) for r in new_support)
|
||||
|
||||
if not alternatives:
|
||||
return answer # ordinary question: byte-identical
|
||||
self._log(f"ambiguity audit: {len(alternatives)} other reading(s) "
|
||||
f"({'; '.join(a['value'][:40] for a in alternatives[:3])}) "
|
||||
f"— flagging, not choosing", think=True)
|
||||
return {**answer, "ambiguous": True,
|
||||
"axis": f"which {question.strip().rstrip('?')}?",
|
||||
"alternatives": alternatives}
|
||||
|
||||
def _verify_count(self, set_name: str, count: int, prose: str,
|
||||
charge_llm) -> dict | None:
|
||||
"""Answer-level CHECK: corroborate the list COUNT from article prose
|
||||
@@ -372,6 +624,22 @@ class KnowledgeExpert:
|
||||
|
||||
Returns the list answer dict, or None when no table in this page
|
||||
enumerates the answer (fall through to the extract path)."""
|
||||
# SUBJECT GUARD (run H): proper nouns of the question ('Italy') must
|
||||
# appear in the article title OR the tables' captions/headers — a
|
||||
# world list must never answer a question about one country. With no
|
||||
# evidence yet (first hop), the disjointness guard is vacuous; THIS
|
||||
# is the guard that fired instead of it.
|
||||
props = _proper_nouns(question)
|
||||
if props:
|
||||
surface = " ".join([page.title]
|
||||
+ [t.caption or "" for t in page.tables]
|
||||
+ [" ".join(t.header) for t in page.tables])
|
||||
toks = _tokens(surface)
|
||||
if not any(_prop_hit(p, toks) for p in props):
|
||||
self._log(f"subject guard: {page.title} names none of "
|
||||
f"{sorted(props)} — refusing LIST from this article",
|
||||
think=True)
|
||||
return None
|
||||
rendered = chr(10).join(
|
||||
f"{t.idx} | {t.caption or '(no caption)'} | "
|
||||
f"header: {', '.join(t.header[:6]) or '(none)'} | rows: {t.total_rows}"
|
||||
@@ -389,6 +657,7 @@ class KnowledgeExpert:
|
||||
table = next((t for t in page.tables if t.idx == idx), None)
|
||||
if table is None:
|
||||
return None
|
||||
page._list_table_idx = idx # the harvest skips the LIST answer's table
|
||||
column = (pred.column or "").strip()
|
||||
col_i = next((i for i, h in enumerate(table.header)
|
||||
if column.casefold() in h.casefold()), 0)
|
||||
@@ -459,20 +728,246 @@ class KnowledgeExpert:
|
||||
"coverage": coverage,
|
||||
}
|
||||
|
||||
def _ingest_scalar_table(self, page: WikiPage, t, ent_i: int,
|
||||
val_i: int) -> int:
|
||||
"""Shared row ingestion for the skim paths (harvest + promote):
|
||||
every row becomes a scalar edge — subject = entity cell, relation =
|
||||
value-column header, object = value + UNIT (the unit lives in the
|
||||
caption), quote = the verbatim stored row line, containment against
|
||||
the stored table text. Zero LLM; the verbatim law is kept."""
|
||||
cap_q = find_quantities(resolve_convert(t.caption or ""))
|
||||
unit = cap_q[0].split(" ", 1)[1] if cap_q else ""
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
table_text = chr(10).join(t.text_lines())
|
||||
rel = t.header[val_i] if val_i < len(t.header) else "value"
|
||||
merged = 0
|
||||
for row in t.rows:
|
||||
subj = (row[ent_i] if ent_i < len(row) else "").strip()
|
||||
obj = (row[val_i] if val_i < len(row) else "").strip()
|
||||
if not subj or not obj or subj.casefold() in (
|
||||
"total", "totals", "sum", "average", "mean") or subj.isdigit():
|
||||
continue
|
||||
if " / " in subj:
|
||||
subj = subj.split(" / ")[0].strip()
|
||||
if unit and re.fullmatch(r"[\d,.]+", obj):
|
||||
obj = f"{obj} {unit}" # quantities carry values AND units
|
||||
row_line = " | ".join(row)
|
||||
ok, reason = check_candidate(
|
||||
{"subject": subj, "relation": rel, "object": obj,
|
||||
"quote": row_line}, table_text)
|
||||
if not ok:
|
||||
self._log(f"harvest row rejected ({reason}): {subj[:40]}")
|
||||
continue
|
||||
qid = self.store.add_quote(doc_id, row_line, page.url,
|
||||
page.fetched_at)
|
||||
self.store.add_edge(subj, rel, obj, qid)
|
||||
self._merged += 1
|
||||
merged += 1
|
||||
if merged:
|
||||
self._log(f"skim ingest: {merged} rows of table {t.idx} "
|
||||
f"({page.title}) as '{rel}' edges", think=True)
|
||||
return merged
|
||||
|
||||
def _entity_overlap_count(self, t, ent_i: int, expected: list[str]) -> \
|
||||
tuple[int, int]:
|
||||
"""(overlap, members) — how many of the table's entity-column members
|
||||
the parent's evidence names, and how many members there are."""
|
||||
members = [(r[ent_i] if ent_i < len(r) else "").strip() for r in t.rows]
|
||||
members = [m.split(" / ")[0].strip() for m in members if m]
|
||||
if not expected:
|
||||
return 0, len(members)
|
||||
en = {norm_name(e) for e in expected}
|
||||
return sum(1 for m in members if norm_name(m) in en), len(members)
|
||||
|
||||
def _harvest_side_tables(self, page: WikiPage, sheet, question: str,
|
||||
evidence: str) -> int:
|
||||
"""PR-2 — the opportunistic harvest: goal-relevant tables seen in
|
||||
passing are ingested as typed rows, zero LLM (KNOWLEDGE.md §7).
|
||||
|
||||
A table is harvested when its caption/header carries a GOAL term AND
|
||||
its entity column overlaps the entities the parent's evidence names
|
||||
(the disjointness guard inverted: overlap = about our entities) —
|
||||
the Italy case: table 2 'Flow at the mouth' while the question asked
|
||||
for lengths. Rows become scalar edges via _ingest_scalar_table
|
||||
(verbatim quote, containment, unit from the caption). Deterministic
|
||||
detection; quantity tables with no goal-vocabulary match are queued
|
||||
as leads for PR-3's bounded promotion, never guessed here."""
|
||||
if not self.cfg.skim_harvest:
|
||||
return 0
|
||||
expected = self._expected_entities(evidence or "")
|
||||
goal_terms = self._current_goal_terms or []
|
||||
|
||||
harvested = 0
|
||||
for t in page.tables:
|
||||
if harvested >= self.cfg.skim_harvest_max_tables:
|
||||
break
|
||||
if t.idx == getattr(page, "_list_table_idx", -1):
|
||||
continue # the table that answered the LIST question
|
||||
# WORD BOUNDARIES (run H: 'flow' matched 'Outflow' by substring
|
||||
# and 227 world rows entered the KG as 'Outflow' edges)
|
||||
goal_hit = any(
|
||||
_term_hits(gt, (t.caption or "") + " " + " ".join(t.header))
|
||||
for gt in goal_terms)
|
||||
qty_signal = bool(find_quantities(
|
||||
resolve_convert(t.caption or "") + " " + " ".join(t.header[:1])))
|
||||
if not goal_hit:
|
||||
if qty_signal:
|
||||
# a quantity table we cannot tie to the goal vocabulary:
|
||||
# RECORDED as a lead for the bounded promotion (PR-3),
|
||||
# never ingested on the unit pattern alone — and the
|
||||
# seen-index lets a later question come back for it
|
||||
self._skim_leads.append((page, t))
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: "
|
||||
f"quantity signal without a goal term — queued "
|
||||
f"as lead", think=True)
|
||||
continue
|
||||
# entity column: first column whose header is a name-like column
|
||||
# (River, Country, Name, ...) or column 0; value column: the
|
||||
# header carrying a GOAL term (goal-directed harvest — the
|
||||
# header names the attribute the goal asks for), keyword
|
||||
# fallbacks (flow/discharge/quantity headers) after
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if i != ent_i and h and any(
|
||||
_term_hits(gt, h) for gt in goal_terms)), None)
|
||||
if val_i is None:
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: no "
|
||||
f"value column — recorded, not ingested", think=True)
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
# not about our entities — a world table is not our answer
|
||||
self._log(f"skim harvest: table {t.idx} of {page.title}: "
|
||||
f"{overlap}/{nm} entity overlap — skipped",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
harvested += 1
|
||||
return harvested
|
||||
|
||||
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
||||
"""PR-3 — the bounded promotion of ambiguous leads: quantity tables
|
||||
with no goal-vocabulary match, decided by ONE LLM call per fetched
|
||||
page that has leads (≤ max_articles per knowledge call, only when
|
||||
leads exist — most pages have none). The call sees the tables'
|
||||
IDENTITY (caption/headers/row count/quantity signals — never the
|
||||
rows). The law split stands: the LLM proposes (which table is about
|
||||
the goal), fixed code disposes — a promoted table still passes the
|
||||
entity-overlap check and ingests through the same containment-checked
|
||||
path as the deterministic harvest. Runs inside the fetch loop, BEFORE
|
||||
the early-exit checks: leads die with the call otherwise (a later
|
||||
question only re-harvests pages its own search surfaces again)."""
|
||||
if not self._skim_leads:
|
||||
return 0
|
||||
if not self.cfg.skim_harvest:
|
||||
self._skim_leads = []
|
||||
return 0
|
||||
expected = self._expected_entities(evidence or "")
|
||||
# group by page; each lead gets a GLOBAL line id (two pages can both
|
||||
# have a 'table 1' — the idx alone would collide in the lookup)
|
||||
leads: list[tuple[WikiPage, object]] = self._skim_leads
|
||||
rendered = []
|
||||
lookup: dict[int, tuple[WikiPage, object]] = {}
|
||||
for lid, (page, t) in enumerate(leads, start=1):
|
||||
cap = resolve_convert(t.caption or "") or "(no caption)"
|
||||
qtys = find_quantities("\n".join(t.text_lines()))[:3]
|
||||
rendered.append(
|
||||
f"{lid} | {cap} | header: {', '.join(t.header[:6])} | "
|
||||
f"rows: {t.total_rows} | quantities: {', '.join(qtys) or 'none'}")
|
||||
lookup[lid] = (page, t)
|
||||
if not rendered:
|
||||
return 0
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.skim_promote(
|
||||
goal=self._current_goal_question,
|
||||
entities=", ".join(expected[:8]),
|
||||
tables="\n".join(rendered))
|
||||
promoted = 0
|
||||
for line in (pred.decision or "").strip().splitlines():
|
||||
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
|
||||
flags=re.I)
|
||||
if not m:
|
||||
continue
|
||||
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
|
||||
got = lookup.get(idx)
|
||||
if verdict != "YES" or got is None:
|
||||
continue
|
||||
page, t = got
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
if col and _col_hits(col, h)), None)
|
||||
if val_i is None:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
|
||||
f"YES but {overlap}/{nm} entity overlap — refused",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim promote: {merged} rows of table {idx} "
|
||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||
promoted += 1
|
||||
self._skim_leads = [] # consumed: bounded, never re-asked
|
||||
return promoted
|
||||
|
||||
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."""
|
||||
charge_llm, goal_terms: list[str] | None = None) -> int:
|
||||
"""Chunk -> gate -> RANK (skim) -> extract -> check -> merge for ONE
|
||||
page. Returns number of candidates merged this page. Counters
|
||||
ACCUMULATE on self.
|
||||
|
||||
PR-1: chunks are RANKED by skim signals (question terms + goal terms
|
||||
+ quantity-unit patterns) instead of taking the first N in document
|
||||
order — the Italy run burned its extract slots on tangential chunks
|
||||
while the discharge table sat later in the document. A chunk without
|
||||
ANY signal is skipped for free."""
|
||||
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:
|
||||
gated = [c for c in chunks if self._gate(c, kws)]
|
||||
if goal_terms:
|
||||
from .store import stem
|
||||
|
||||
def rank(c) -> tuple[int, int]:
|
||||
low = c.text.casefold()
|
||||
sig = sum(1 for t in set(kws + goal_terms)
|
||||
if t and (t in low or stem(t) in low))
|
||||
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
||||
gated.sort(key=rank, reverse=True)
|
||||
capped = gated[: self.cfg.max_chunks_extracted]
|
||||
|
||||
# ---- table fragments: the tables seen in this page, as SMALL
|
||||
# structured pieces for the extractor — never a 22k-char dump (run G,
|
||||
# call 8/80). Each fragment repeats the header; the extractor can
|
||||
# STOP_TABLE a hopeless table after reading its identity. The LIST
|
||||
# answer's own table never re-enters the extract path.
|
||||
stopped: set[int] = set()
|
||||
list_idx = getattr(page, "_list_table_idx", -1)
|
||||
table_frags = [f for f in tables_as_chunks(page.wikitext)
|
||||
if f["table_idx"] != list_idx]
|
||||
frag_slots = max(0, self.cfg.max_chunks_extracted - len(capped))
|
||||
frag_budget = min(frag_slots, len(table_frags))
|
||||
|
||||
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, "
|
||||
f"{len(capped)} extracted (skim-ranked); "
|
||||
f"{len(table_frags)} table frags, {frag_budget} considered",
|
||||
think=True)
|
||||
extracted = 0
|
||||
for chunk in capped:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
|
||||
for cand in parse_facts(raw.facts):
|
||||
for cand in (raw.facts or []):
|
||||
self._checked += 1
|
||||
cand = {"subject": cand.subject, "relation": cand.relation,
|
||||
"object": cand.object, "quote": cand.quote}
|
||||
ok, reason = check_candidate(cand, page.text)
|
||||
if not ok:
|
||||
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||
@@ -483,6 +978,56 @@ class KnowledgeExpert:
|
||||
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
|
||||
extracted += 1
|
||||
# ---- table fragments (extract path) -----------------------------
|
||||
from .store import stem as _stem
|
||||
# containment target: prose + ALL table rows (the fragment's rows
|
||||
# live in page.tables, not in page.text, since the enrichment left)
|
||||
tables_text = "\n".join("\n".join(t.text_lines()) for t in page.tables)
|
||||
containment = page.text + "\n" + tables_text if tables_text else page.text
|
||||
frag_considered = 0
|
||||
for frag in table_frags[:frag_budget]:
|
||||
if frag["table_idx"] in stopped:
|
||||
continue
|
||||
text = format_table_frag(frag)
|
||||
low = text.casefold()
|
||||
sig = sum(1 for t in set(kws + goal_terms)
|
||||
if t and (t in low or _stem(t) in low))
|
||||
qty = len(find_quantities(low))
|
||||
if sig == 0 and qty == 0:
|
||||
self._log(f"table frag skipped (no signal): "
|
||||
f"table {frag['table_idx']} part {frag['part']}/{frag['of']}")
|
||||
continue
|
||||
frag_considered += 1
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
||||
raw = self.extract(question=question, heading=heading, text=text)
|
||||
if raw.stop:
|
||||
stopped.add(frag["table_idx"])
|
||||
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
|
||||
f"({frag['caption'][:40]!r}) not relevant — "
|
||||
f"skipping {frag['of'] - frag['part']} remaining parts",
|
||||
think=True)
|
||||
continue
|
||||
for cand in (raw.facts or []):
|
||||
self._checked += 1
|
||||
# containment against prose + FULL table text: the fragment is
|
||||
# rendered from the same rows, so quotes verify honestly
|
||||
cand = {"subject": cand.subject, "relation": cand.relation,
|
||||
"object": cand.object, "quote": cand.quote}
|
||||
ok, reason = check_candidate(cand, containment)
|
||||
if not ok:
|
||||
self._log(f"frag candidate rejected ({reason}): "
|
||||
f"{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
|
||||
extracted += 1
|
||||
return self._merged
|
||||
|
||||
def _gate(self, chunk, keywords: list[str]) -> bool:
|
||||
|
||||
+40
-10
@@ -7,6 +7,16 @@ the FULL document text — so chunking can never fake a quote.
|
||||
from __future__ import annotations
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Fact(BaseModel):
|
||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
||||
object: str = dspy.OutputField(desc="the fact's object / value")
|
||||
quote: str = dspy.OutputField(
|
||||
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
||||
|
||||
|
||||
class TranslateSignature(dspy.Signature):
|
||||
@@ -24,16 +34,21 @@ class TranslateSignature(dspy.Signature):
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
extract facts that help answer the question. Each fact is one line:
|
||||
subject | relation | object | verbatim quote from the text.
|
||||
The quote must be the FULL sentence or table ROW that states the fact,
|
||||
extract the facts that help answer the question. Each fact carries its
|
||||
verbatim quote: the FULL sentence or table ROW that states the fact,
|
||||
copied exactly (at least 10 characters). Only facts the text states;
|
||||
no inference."""
|
||||
no inference.
|
||||
If the text is a fragment of a larger TABLE whose caption/headers show
|
||||
its subject is wrong for the question, set stop=True with no facts.
|
||||
Do NOT stop for text that is merely hard — only when the table's
|
||||
subject is wrong."""
|
||||
question: str = dspy.InputField()
|
||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||
text: str = dspy.InputField()
|
||||
facts: str = dspy.OutputField(
|
||||
desc="one fact per line: subject | relation | object | verbatim quote; empty if none")
|
||||
facts: list[Fact] = dspy.OutputField(
|
||||
desc="the extracted facts; empty list if none")
|
||||
stop: bool = dspy.OutputField(
|
||||
desc="True when this table fragment's subject is wrong for the question")
|
||||
|
||||
|
||||
class AnswerFromKG(dspy.Signature):
|
||||
@@ -80,11 +95,26 @@ class SelectTableSignature(dspy.Signature):
|
||||
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
"""Parse the extractor's piped lines; malformed lines are dropped+counted.
|
||||
class SkimPromoteSignature(dspy.Signature):
|
||||
"""You are the SKIM PROMOTE step of a knowledge machine. While fetching
|
||||
articles for one question, tables were seen in passing that carry
|
||||
quantity data but match none of the goal's words (the goal's vocabulary
|
||||
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
|
||||
Given the run's goal, the entities it is about, and the tables' identity
|
||||
(caption, headers, row count, quantity signals — NOT the rows), decide
|
||||
per table whether it holds data about those entities for the goal.
|
||||
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
|
||||
is the header holding the goal's values."""
|
||||
goal: str = dspy.InputField(desc="the run's overall goal question")
|
||||
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
|
||||
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'")
|
||||
|
||||
Split into AT MOST 4 fields — the quote is the last field and may itself
|
||||
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
"""LEGACY pipe parser — kept ONLY for tests that script extractor
|
||||
responses as text. Production code consumes typed `Fact` objects from
|
||||
dspy directly (see ExtractSignature.facts). Do not use in new code."""
|
||||
out: list[dict] = []
|
||||
for line in (raw or "").strip().splitlines():
|
||||
line = line.strip()
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Skim: the fast structural read of a fetched article, in passing.
|
||||
|
||||
KNOWLEDGE.md §7. Every article the gather fetches is skimmed — headings,
|
||||
tables, infobox params, term hits — oriented to the current question AND
|
||||
the run goal, so information seen in passing is not thrown away when the
|
||||
call returns. All deterministic, zero LLM, built from material fetch_rich
|
||||
already downloads.
|
||||
|
||||
Outputs of this module:
|
||||
- SkimSheet: the per-article record (headings, tables, infobox, term hits,
|
||||
link candidates) — surfaces + signals only, never content decisions.
|
||||
- quantity patterns: `50 m3/s`, `1,460 m3/s` — unit signals that find
|
||||
material where the vocabulary cannot (the Italy discharge table's heading
|
||||
says "above 50 m3/s", never "discharge").
|
||||
- the infobox surface: parameter keys + resolved quantity values parsed
|
||||
from the page wikitext (where Adige's discharge lives — invisible to the
|
||||
plain extract and to parse_tables).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .wiki import resolve_convert
|
||||
|
||||
# --- quantity-unit patterns (the vocabulary-independent signal) ------------
|
||||
# number (thousands with , or ., optional decimals; OR plain digits — '1540'
|
||||
# and '1000' carry no thousands separator) followed by a unit token
|
||||
_QTY_RE = re.compile(
|
||||
r"\b(\d{1,3}(?:[.,]\d{3})*(?:\.\d+)?|\d+(?:\.\d+)?)"
|
||||
r"[\s\u00a0-]*(m3/s|m³/s|cu\s*ft/s|cuft/s|ft3/s"
|
||||
r"|km2|km²|km|mi2|mi²|mi|kg|mm|cm|m|s|%)\b",
|
||||
re.I)
|
||||
|
||||
|
||||
def _canon_unit(u: str) -> str:
|
||||
"""Canonical unit display form (wiki.resolve_convert's stored forms)."""
|
||||
u = u.lower().replace("\u00a0", " ").strip()
|
||||
return {"cuft/s": "cu ft/s", "ft3/s": "cu ft/s", "m³/s": "m3/s",
|
||||
"km²": "km2", "mi²": "mi2"}.get(u, u)
|
||||
|
||||
|
||||
def find_quantities(text: str) -> list[str]:
|
||||
"""All quantity+unit spans in text (normalized: '1,460 m3/s')."""
|
||||
out: list[str] = []
|
||||
for m in _QTY_RE.finditer(text or ""):
|
||||
out.append(f"{m.group(1)} {_canon_unit(m.group(2))}")
|
||||
return out
|
||||
|
||||
|
||||
# --- the skim sheet ---------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class SkimTable:
|
||||
"""A table as the skim sees it: identity + signals, never rows."""
|
||||
idx: int
|
||||
caption: str = ""
|
||||
header: list[str] = field(default_factory=list)
|
||||
rows_total: int = 0
|
||||
quantities: list[str] = field(default_factory=list)
|
||||
hits: int = 0 # term hits across caption+header
|
||||
|
||||
def describe(self) -> str:
|
||||
cap = resolve_convert(self.caption) or "(no caption)"
|
||||
return (f"table {self.idx}: {cap} | header: "
|
||||
f"{', '.join(self.header[:6])} | rows: {self.rows_total}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkimSection:
|
||||
title: str
|
||||
hits: int = 0
|
||||
quantities: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkimSheet:
|
||||
title: str
|
||||
url: str
|
||||
headings: list[SkimSection] = field(default_factory=list)
|
||||
tables: list[SkimTable] = field(default_factory=list)
|
||||
infobox_keys: list[str] = field(default_factory=list)
|
||||
infobox_quantities: dict[str, str] = field(default_factory=dict)
|
||||
link_candidates: list[str] = field(default_factory=list)
|
||||
|
||||
def notice(self) -> str:
|
||||
"""Compact notice for the machine (payload['skim']). One line:
|
||||
tables seen (identity + signal), infobox quantity params, link
|
||||
candidates — what a later step could come back for."""
|
||||
parts = []
|
||||
if self.tables:
|
||||
parts.append("; ".join(t.describe() for t in self.tables[:3]))
|
||||
if self.infobox_quantities:
|
||||
parts.append("infobox: " + ", ".join(
|
||||
f"{k}={v}" for k, v in list(self.infobox_quantities.items())[:4]))
|
||||
if self.link_candidates:
|
||||
parts.append("linked: " + ", ".join(self.link_candidates[:6]))
|
||||
return f"{self.title}: " + " | ".join(parts) if parts else ""
|
||||
|
||||
|
||||
HEADING_RE = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M)
|
||||
INFOBOX_RE = re.compile(r"\{\{[Ii]nfobox\s+([^|{}]+)(.*?)\n\}\}", re.S)
|
||||
PARAM_RE = re.compile(r"^\s*\|\s*([A-Za-z0-9_]+)\s*=\s*(.*)$", re.M)
|
||||
LINK_RE = re.compile(r"\[\[([^\]|]+)(?:\|[^\]]*)?\]\]")
|
||||
|
||||
|
||||
def _hits(text: str, terms: list[str]) -> int:
|
||||
"""Count distinct term hits (stem-level, casefolded) in text."""
|
||||
from .store import stem
|
||||
low = (text or "").casefold()
|
||||
n = 0
|
||||
for t in terms:
|
||||
if t and (t in low or stem(t) in low):
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def _norm_entities(entities: list[str]) -> list[str]:
|
||||
from .store import norm_name
|
||||
return [norm_name(e) for e in entities if len(e) > 2]
|
||||
|
||||
|
||||
def skim_article(page, question_terms: list[str], goal_terms: list[str],
|
||||
evidence_entities: list[str]) -> SkimSheet:
|
||||
"""Build the skim sheet for one fetched WikiPage.
|
||||
|
||||
`page` is a knowledge/wiki.WikiPage (text + tables + wikitext, as
|
||||
fetch_rich returns since PR-1). Terms: words/stems of the CURRENT
|
||||
question, of the RUN GOAL, and entities already in evidence.
|
||||
Deterministic; no LLM."""
|
||||
sheet = SkimSheet(title=page.title, url=page.url)
|
||||
all_terms = [t for t in set(question_terms + goal_terms) if len(t) > 2]
|
||||
ent_terms = _norm_entities(evidence_entities)
|
||||
|
||||
# headings + per-section signals (regex positions, level-agnostic)
|
||||
text = page.text or ""
|
||||
marks = [(m.start(), m.end(), m.group(2))
|
||||
for m in HEADING_RE.finditer(text)]
|
||||
sections: list[tuple[str, str, str]] = [] # (title, body, start)
|
||||
for i, (start, end, title) in enumerate(marks):
|
||||
body_end = marks[i + 1][0] if i + 1 < len(marks) else len(text)
|
||||
sections.append((title, text[end:body_end], text[start:body_end]))
|
||||
for title, body, _full in sections:
|
||||
sheet.headings.append(SkimSection(
|
||||
title=title,
|
||||
hits=_hits(title + " " + body, all_terms + ent_terms),
|
||||
quantities=find_quantities(body)))
|
||||
# preamble (before first heading) — quantities only
|
||||
pre = text[:marks[0][0]] if marks else text
|
||||
if find_quantities(pre):
|
||||
sheet.headings.append(SkimSection(title="(preamble)", hits=0,
|
||||
quantities=find_quantities(pre)))
|
||||
|
||||
# tables: caption/headers/row-count + quantity signals
|
||||
for t in getattr(page, "tables", None) or []:
|
||||
cap = t.caption or ""
|
||||
ttext = "\n".join(t.text_lines())
|
||||
qtys = find_quantities(resolve_convert(cap)) + find_quantities(ttext)
|
||||
seen: list[str] = []
|
||||
for q in qtys:
|
||||
if q not in seen:
|
||||
seen.append(q)
|
||||
sheet.tables.append(SkimTable(
|
||||
idx=t.idx, caption=cap, header=list(t.header),
|
||||
rows_total=t.total_rows, quantities=seen[:10],
|
||||
hits=_hits(cap + " " + " ".join(t.header), all_terms)))
|
||||
|
||||
# infobox: parameter keys + quantity values (units resolved) — from the
|
||||
# page wikitext (fetch_rich stores it since PR-1); pages without one are
|
||||
# skipped honestly
|
||||
wt = getattr(page, "wikitext", "") or ""
|
||||
m = INFOBOX_RE.search(wt)
|
||||
if m:
|
||||
keys, quants = [], {}
|
||||
for pm in PARAM_RE.finditer(m.group(2)):
|
||||
key, val = pm.group(1), pm.group(2).strip()
|
||||
keys.append(key)
|
||||
resolved = resolve_convert(val)
|
||||
if resolved != val: # a {{convert}} value: quantity
|
||||
quants[key] = resolved
|
||||
elif find_quantities(val): # bare number+unit in the param
|
||||
quants[key] = find_quantities(val)[0]
|
||||
sheet.infobox_keys = keys
|
||||
sheet.infobox_quantities = quants
|
||||
|
||||
# links inside goal-relevant regions (harvest candidates, capped at 12):
|
||||
# a region is goal-relevant when its title or body hits a goal term or
|
||||
# carries a quantity signal (the Italy case: the signal '50 m3/s' lives
|
||||
# IN the section heading, the body below it holds the table's links)
|
||||
links: list[str] = []
|
||||
for title, body, _full in sections:
|
||||
if goal_terms and (_hits(title + " " + body, goal_terms) > 0
|
||||
or find_quantities(title + " " + body)):
|
||||
for lm in LINK_RE.finditer(body):
|
||||
target = lm.group(1).split("#")[0].strip()
|
||||
if (target and target not in links
|
||||
and ":" not in target[:6]): # skip File:/etc ns
|
||||
links.append(target)
|
||||
if len(links) >= 12:
|
||||
break
|
||||
sheet.link_candidates = links[:12]
|
||||
return sheet
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Ablation ambiguity detector tests (run J) — same 4 agreed cases, now for
|
||||
the ablation loop.
|
||||
|
||||
Laws under test:
|
||||
1. Pedro office question: the judge picks Socialist International; ablation
|
||||
rounds surface prime minister (of Spain) and secretary-general (PSOE) as
|
||||
OTHER defensible readings — flagged, never chosen.
|
||||
2. Ordinary questions: the first ablation round returns UNKNOWN (the KG has
|
||||
no second reading) — byte-identical answer, no flag.
|
||||
3. Corroboration is not ambiguity: a second row supporting the SAME value
|
||||
keeps the audit silent.
|
||||
4. The KG store is never mutated (the mask is a view).
|
||||
5. The wiring: EXPERT log line carries AMBIGUOUS; payload {ambiguous, axis,
|
||||
alternatives}; run notes + evidence render carry them.
|
||||
|
||||
No network. The judge is a scripted AnswerFromKG: a queue of responses.
|
||||
Run: .venv/bin/python knowledge/tests/ablation.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
Q_PEDRO_SUB = ("What country or political office is Pedro Sanchez "
|
||||
"associated with as President?")
|
||||
Q_PEDRO = "What office is Pedro Sanchez associated with as President?"
|
||||
Q_EU = "What is the second most populated country in European Union?"
|
||||
Q_RIVERS = "Which are the three longest rivers in Italy?"
|
||||
|
||||
|
||||
class R:
|
||||
"""EdgeView stand-in — same field names as store.probe() returns."""
|
||||
|
||||
def __init__(self, src, rel, dst, quote="", url="", corroboration=1):
|
||||
self.src, self.rel, self.dst = src, rel, dst
|
||||
self.quote, self.url = quote, url
|
||||
self.corroboration = corroboration
|
||||
|
||||
|
||||
def run_j_rows():
|
||||
"""The run-J KG: three office readings from the FIRST PARAGRAPH (one
|
||||
chunk) + noise rows (dates, unrelated entities)."""
|
||||
return [
|
||||
R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain",
|
||||
quote="he has been the prime minister of Spain since 2018"),
|
||||
R("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE",
|
||||
quote="Secretary-General of the party since 2017"),
|
||||
R("Pedro Sánchez",
|
||||
"president of Socialist International since 2022",
|
||||
"Socialist International",
|
||||
quote="ninth president of Socialist International since 2022"),
|
||||
R("Pedro Sánchez", "term start", "2 June 2018"),
|
||||
R("Spain", "population", "48 million"),
|
||||
R("Po", "length", "652 km"),
|
||||
]
|
||||
|
||||
|
||||
def make_expert(store=None, judge=None):
|
||||
"""KnowledgeExpert with a scripted judge: judge is a callable
|
||||
(question, rows) -> answer dict, replacing AnswerFromKG."""
|
||||
store = store or KnowledgeStore(
|
||||
f"{tempfile.mkdtemp()}/kg.sqlite")
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.client = None # no network in these tests
|
||||
e._log = lambda *a, **k: None
|
||||
if judge is not None:
|
||||
e._answer_from_rows = judge
|
||||
return e
|
||||
|
||||
|
||||
# --- the ablation loop --------------------------------------------------------
|
||||
|
||||
def test_pedro_flags():
|
||||
"""The judge: round 0 pick SI; round 1 PM; round 2 SG; then UNKNOWN."""
|
||||
rows = run_j_rows()
|
||||
calls = []
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
calls.append(len(rws))
|
||||
# rows visible shrink as supports are masked
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if any("Socialist" in v for v in vals):
|
||||
return {"value": "Socialist International",
|
||||
"quote": "ninth president of Socialist International",
|
||||
"url": "u"}
|
||||
if any("Spain" in v for v in vals):
|
||||
return {"value": "prime minister of Spain",
|
||||
"quote": "he has been the prime minister of Spain",
|
||||
"url": "u"}
|
||||
if any("PSOE" in v for v in vals):
|
||||
return {"value": "secretary-general of PSOE",
|
||||
"quote": "Secretary-General of the party",
|
||||
"url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
base = {"value": "Socialist International", "quote": "q", "url": "u"}
|
||||
ans = e._audit_ambiguity(Q_PEDRO, base, rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
alts = [a["value"] for a in ans["alternatives"]]
|
||||
assert alts == ["prime minister of Spain", "secretary-general of PSOE"], alts
|
||||
assert "Socialist International" not in alts
|
||||
assert all(a["quote"] for a in ans["alternatives"]), "verbatim law"
|
||||
print("ok: Pedro question flags — 2 alternatives by ablation, picked excluded")
|
||||
|
||||
|
||||
def test_counterexamples_silent():
|
||||
"""Ordinary questions: judge answers with one value; ablation round 1
|
||||
sees no other reading (UNKNOWN) — byte-identical answer, no flag."""
|
||||
rows = [R("Germany", "population rank", "second in European Union",
|
||||
quote="Germany is the second most populated country"),
|
||||
R("Spain", "population", "48 million"),
|
||||
R("Po", "length", "652 km")]
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if any("second" in v for v in vals):
|
||||
return {"value": "Germany",
|
||||
"quote": "Germany is the second most populated country",
|
||||
"url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
base = {"value": "Germany", "quote": "q", "url": "u"}
|
||||
ans = e._audit_ambiguity(Q_EU, base, rows)
|
||||
assert ans == base, ans # byte-identical, no flag
|
||||
print("ok: counterexample (EU) silent — single reading, no extra flag")
|
||||
|
||||
# rivers: list answers skip the audit entirely (scalar-only)
|
||||
rivers_rows = [R("Po", "length rank", "longest river in Italy")]
|
||||
e2 = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
|
||||
ans2 = e2._audit_ambiguity(Q_RIVERS,
|
||||
{"value": "Po, Adige, Tiber", "quote": "q",
|
||||
"url": "u"}, rivers_rows)
|
||||
assert ans2.get("ambiguous") is not True, ans2
|
||||
print("ok: counterexample (rivers) silent")
|
||||
|
||||
|
||||
def test_corroboration_not_ambiguity():
|
||||
"""A second row supporting the SAME value: the judge (honest) answers
|
||||
Germany again; same-value survivors are corroboration — silent."""
|
||||
rows = [R("Germany", "population rank", "second most populated",
|
||||
quote="Germany is the second most populated"),
|
||||
R("Germany", "member of", "European Union")]
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if any("second" in v for v in vals):
|
||||
return {"value": "Germany", "quote": "q", "url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity(Q_EU, {"value": "Germany", "quote": "q",
|
||||
"url": "u"}, rows)
|
||||
assert "ambiguous" not in ans, ans
|
||||
print("ok: same-value survivor (corroboration) stays silent")
|
||||
|
||||
|
||||
def seed_store(ks, rows):
|
||||
"""Seed a real store with the R rows (doc + quote + edge each)."""
|
||||
for i, r in enumerate(rows):
|
||||
doc = ks.add_document(url=f"http://u{i}", source="wikipedia",
|
||||
fetched_at="2026-10-21", sha256=f"h{i}",
|
||||
trusted=True, title=r.src)
|
||||
qid = ks.add_quote(doc, r.quote or f"about {r.dst}", f"http://u{i}",
|
||||
"2026-10-21")
|
||||
ks.add_edge(r.src, r.rel, r.dst, qid)
|
||||
|
||||
|
||||
def test_store_never_mutated():
|
||||
"""The mask is a view: after the audit, probe() still returns all rows."""
|
||||
tmp = tempfile.mkdtemp()
|
||||
ks = KnowledgeStore(f"{tmp}/kg.sqlite")
|
||||
seed_store(ks, run_j_rows())
|
||||
before = len(ks.probe(["pedro", "sánchez", "office", "spain"]))
|
||||
e = make_expert(store=ks)
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if any("Socialist" in v for v in vals):
|
||||
return {"value": "Socialist International", "quote": "q", "url": "u"}
|
||||
if any("Spain" in v for v in vals):
|
||||
return {"value": "prime minister of Spain", "quote": "q", "url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e._answer_from_rows = judge
|
||||
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
|
||||
"quote": "q", "url": "u"},
|
||||
ks.probe(["pedro", "sánchez", "office", "spain"]))
|
||||
after = len(ks.probe(["pedro", "sánchez", "office", "spain"]))
|
||||
assert after == before, f"store mutated: {before} -> {after}"
|
||||
assert ans.get("ambiguous") is True
|
||||
print("ok: the mask is a view — probe() unchanged after the audit")
|
||||
|
||||
|
||||
def test_single_source_silent():
|
||||
"""Support rows but no survivors: nothing to ablate — silent."""
|
||||
rows = [R("Pedro Sánchez", "president of", "Socialist International",
|
||||
quote="president of Socialist International")]
|
||||
e = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
|
||||
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
|
||||
"quote": "q", "url": "u"}, rows)
|
||||
assert "ambiguous" not in ans, ans
|
||||
print("ok: single-source KG — nothing to ablate, silent")
|
||||
|
||||
|
||||
def test_rounds_cap():
|
||||
"""The loop honors ambiguity_rounds: more readings than rounds -> the
|
||||
flag carries at most ambiguity_rounds alternatives, the loop ends."""
|
||||
rows = [R("X", "r1", "v1"), R("X", "r2", "v2"), R("X", "r3", "v3"),
|
||||
R("X", "r4", "v4"), R("X", "r5", "v5")]
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
# always the first visible row's dst
|
||||
return {"value": str(rws[0].dst), "quote": "", "url": "u"}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity("What is X?", {"value": "v1", "quote": "", "url": "u"},
|
||||
rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
assert len(ans["alternatives"]) <= 3, ans
|
||||
print("ok: rounds cap honored (<= ambiguity_rounds alternatives)")
|
||||
|
||||
|
||||
# --- the wiring ----------------------------------------------------------------
|
||||
|
||||
def test_engine_and_machine_wiring():
|
||||
"""The flag surface: EXPERT log line, payload, provenance, run notes and
|
||||
the evidence render — with the new value/quote/url alternative shape."""
|
||||
import inspect
|
||||
|
||||
src = inspect.getsource(KnowledgeExpert)
|
||||
assert "_audit_ambiguity" in src
|
||||
assert "_maybe_ambig" not in src, "the PR-7 audit must be fully removed"
|
||||
|
||||
# engine log line: AMBIGUOUS without [role] prefixes
|
||||
import floop.engine as fe
|
||||
esrc = inspect.getsource(fe)
|
||||
assert "AMBIGUOUS" in esrc
|
||||
assert "[{a.get('role')}]" not in esrc, "role prefixes are gone"
|
||||
|
||||
# machine notes + render: same shape
|
||||
import floop.machine as fm
|
||||
msrc = inspect.getsource(fm)
|
||||
assert "AMBIGUOUS" in msrc
|
||||
assert "({a.get('role')})" not in msrc
|
||||
print("ok: wiring — audit renamed, role prefixes gone, log/notes/render keep AMBIGUOUS")
|
||||
|
||||
|
||||
def test_interleaved_quotes_flag_all_three():
|
||||
"""RUN-L REGRESSION: one paragraph quote carrying ALL THREE readings
|
||||
(the pick's own quote was the PSOE sentence). The dst-first mask must
|
||||
keep the other rows alive: all three offices flagged, in order."""
|
||||
Q_WHOLE = ("A member of the Spanish Socialist Workers' Party (PSOE), he "
|
||||
"is also Secretary-General of the party since 2017, and is "
|
||||
"the ninth president of Socialist International since 2022.")
|
||||
rows = [
|
||||
R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain",
|
||||
quote=Q_WHOLE),
|
||||
R("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE",
|
||||
quote=Q_WHOLE),
|
||||
R("Pedro Sánchez", "president of Socialist International since 2022",
|
||||
"Socialist International", quote=Q_WHOLE),
|
||||
]
|
||||
order = {"Socialist International": 0, "prime minister of Spain": 1,
|
||||
"secretary-general of PSOE": 2}
|
||||
state = {"seen": "Socialist International"}
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
# picks by priority: SI if visible, else PM, else SG
|
||||
vals = [str(r.dst) for r in rws]
|
||||
if "Socialist International" in vals:
|
||||
return {"value": "Socialist International", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
if "Spain" in vals:
|
||||
return {"value": "prime minister of Spain", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
if "PSOE" in vals:
|
||||
return {"value": "secretary-general of PSOE", "quote": Q_WHOLE,
|
||||
"url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
|
||||
"quote": Q_WHOLE, "url": "u"}, rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
alts = [a["value"] for a in ans["alternatives"]]
|
||||
assert alts == ["prime minister of Spain",
|
||||
"secretary-general of PSOE"], alts
|
||||
# run-L failure mode: the OLD quote-matching mask killed round 1
|
||||
assert all(a["quote"] == Q_WHOLE for a in ans["alternatives"])
|
||||
print("ok: run-L regression — interleaved one-paragraph quote flags all 3")
|
||||
|
||||
|
||||
def test_office_description_value_resolves_row():
|
||||
"""The judge's round value may be an OFFICE DESCRIPTION ('prime
|
||||
minister of Spain') while the row's dst is the ENTITY ('Spain') —
|
||||
reciprocal token containment must resolve and mask the right row,
|
||||
without eating the unrelated PSOE row (or the loop dies after one
|
||||
alternative). Shape: pick=SI, round 1 returns the PM description."""
|
||||
rows = [R("X", "president of", "Socialist International"),
|
||||
R("X", "prime minister of", "Spain"),
|
||||
R("X", "secretary-general of", "PSOE")]
|
||||
|
||||
def judge(question, rws, charge_llm=None):
|
||||
dsts = {str(r.dst) for r in rws}
|
||||
if "Socialist International" in dsts:
|
||||
return {"value": "Socialist International", "quote": "", "url": "u"}
|
||||
if "Spain" in dsts:
|
||||
# OFFICE DESCRIPTION, not the dst entity
|
||||
return {"value": "prime minister of Spain", "quote": "", "url": "u"}
|
||||
if "PSOE" in dsts:
|
||||
return {"value": "secretary-general of PSOE", "quote": "", "url": "u"}
|
||||
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||
|
||||
e = make_expert(judge=judge)
|
||||
ans = e._audit_ambiguity("What is X?", {"value": "Socialist International",
|
||||
"quote": "", "url": "u"}, rows)
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
alts = [a["value"] for a in ans["alternatives"]]
|
||||
# PM's description resolved its Spain row; PSOE survived round 1
|
||||
assert alts == ["prime minister of Spain",
|
||||
"secretary-general of PSOE"], alts
|
||||
print("ok: office-description value resolves its row (token overlap)")
|
||||
|
||||
|
||||
def test_numeric_dst_falls_back_to_quote():
|
||||
"""A date dst is NOT meaningful: the quote carries the value there.
|
||||
The old numeric dsts (dates) must never mask text-bearing rows."""
|
||||
rows = [R("X", "term start", "2 June 2018",
|
||||
quote="took office on 2 June 2018"),
|
||||
R("Y", "population", "48 million")]
|
||||
e = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
|
||||
ans = e._audit_ambiguity("When did X start?", {"value": "2 June 2018",
|
||||
"quote": "", "url": "u"},
|
||||
rows)
|
||||
assert "ambiguous" not in ans, ans
|
||||
print("ok: numeric dst uses the quote fallback, stays silent")
|
||||
|
||||
|
||||
def main():
|
||||
test_pedro_flags()
|
||||
test_counterexamples_silent()
|
||||
test_corroboration_not_ambiguity()
|
||||
test_store_never_mutated()
|
||||
test_single_source_silent()
|
||||
test_rounds_cap()
|
||||
test_engine_and_machine_wiring()
|
||||
test_interleaved_quotes_flag_all_three()
|
||||
test_office_description_value_resolves_row()
|
||||
test_numeric_dst_falls_back_to_quote()
|
||||
print("\nablation ambiguity tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,200 @@
|
||||
"""PR-5 tests: subject guard, word-boundary matching, and the EXPERT answer
|
||||
log. The run-H failure chain: Q1 (Italy) answered by the WORLD rivers list
|
||||
because (a) the article title was never checked against the question's
|
||||
proper nouns, (b) 'flow' matched 'Outflow' by substring and 227 world rows
|
||||
entered the KG, (c) the expert's answer was only deducible from the fan-out.
|
||||
No network, no real LLM. Run: uv run python knowledge/tests/guards.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from knowledge.wiki import WikiPage, parse_tables
|
||||
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
|
||||
_tokens, _term_hits, _proper_nouns)
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
# --- fixtures ----------------------------------------------------------------
|
||||
|
||||
WORLD_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"! Rank !! River !! Length (km) !! Outflow\n|-\n"
|
||||
"| 1 || Nile || 6650 || Mediterranean\n|-\n"
|
||||
"| 2 || Amazon || 6400 || Atlantic\n|-\n"
|
||||
"| 3 || Yangtze || 6300 || East China Sea\n|}\n"
|
||||
)
|
||||
|
||||
ITALY_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy by length\n"
|
||||
"! River !! Length (km) !! Flow at the mouth\n|-\n"
|
||||
"| Po || 652 || 1540\n|-\n"
|
||||
"| Adige || 410 || 235\n|-\n"
|
||||
"| Tiber || 406 || 239\n|}\n"
|
||||
)
|
||||
|
||||
|
||||
def world_page() -> WikiPage:
|
||||
t = parse_tables(WORLD_WIKITEXT)
|
||||
return WikiPage(title="List of river systems by length", url="http://x",
|
||||
pageid=1, fetched_at="t", text="World rivers.",
|
||||
wikitext=WORLD_WIKITEXT, tables=t)
|
||||
|
||||
|
||||
def italy_page() -> WikiPage:
|
||||
t = parse_tables(ITALY_WIKITEXT)
|
||||
return WikiPage(title="List of rivers of Italy", url="http://x", pageid=2,
|
||||
fetched_at="t", text="Italy has rivers.",
|
||||
wikitext=ITALY_WIKITEXT, tables=t)
|
||||
|
||||
|
||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.streams = None
|
||||
e._checked = e._merged = 0
|
||||
e._seen_pages = {}
|
||||
e._skim_leads = []
|
||||
e._skim_notices = []
|
||||
e._link_queue = []
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = ""
|
||||
|
||||
class _NoQuote:
|
||||
quote = ""
|
||||
e.verify_count = lambda **kw: _NoQuote() # no corroboration in tests
|
||||
return e
|
||||
|
||||
|
||||
# --- 1) boundary matching ----------------------------------------------------
|
||||
|
||||
def test_term_hits():
|
||||
# 'flow' must NOT match 'Outflow' (the run-H substring bug)
|
||||
assert _term_hits("flow", "Flow at the mouth") is True
|
||||
assert _term_hits("flow", "Outflow") is False
|
||||
assert _term_hits("outflow", "Outflow") is True
|
||||
# stems tolerated
|
||||
assert _term_hits("flows", "Flow at the mouth") is True
|
||||
# whole-token, case-insensitive
|
||||
assert _term_hits("italy", "Rivers of Italy by length") is True
|
||||
assert _term_hits("italy", "Italian unification") is False # no substring
|
||||
print("ok: _term_hits word boundaries (flow != Outflow; italy != Italian)")
|
||||
|
||||
|
||||
def test_proper_nouns():
|
||||
q = "Which are the three longest rivers of Italy?"
|
||||
assert _proper_nouns(q) == {"Italy"}
|
||||
q2 = "What is the discharge of the Po, Adige and Tiber?"
|
||||
assert _proper_nouns(q2) == {"Po", "Adige", "Tiber"}
|
||||
q3 = "What is the total water flow considering the three longest rivers of Italy?"
|
||||
assert _proper_nouns(q3) == {"Italy"}
|
||||
print("ok: _proper_nouns extracts the subject (Italy; Po/Adige/Tiber)")
|
||||
|
||||
|
||||
# --- 2) the subject guard on LIST --------------------------------------------
|
||||
|
||||
def test_subject_guard_list():
|
||||
import tempfile
|
||||
q = "Which are the three longest rivers of Italy?"
|
||||
|
||||
# (a) the WORLD page must be refused BEFORE any LLM call: no 'italy'
|
||||
# token in title/captions/headers
|
||||
tmp = tempfile.mkdtemp()
|
||||
e = make_expert(KnowledgeStore(f"{tmp}/kg.sqlite"))
|
||||
called = []
|
||||
e.select_table = lambda **kw: called.append(kw) or None
|
||||
ans = e._list_from_page(world_page(), q, None)
|
||||
assert ans is None, "world page must not answer the Italy question"
|
||||
assert not called, "the SELECT_TABLE call must not even happen (guard first)"
|
||||
rows = e.store.probe(["nile", "member"])
|
||||
assert rows == [], "no rows ingested from the refused world page"
|
||||
|
||||
# (b) the ITALY page passes the guard and ingests
|
||||
tmp2 = tempfile.mkdtemp()
|
||||
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
|
||||
|
||||
class Pred:
|
||||
table_index = "1"
|
||||
column = "River"
|
||||
set_name = "longest rivers of Italy"
|
||||
origin_question = q
|
||||
|
||||
e2.select_table = lambda **kw: Pred()
|
||||
ans2 = e2._list_from_page(italy_page(), q, None)
|
||||
assert ans2 is not None and ans2["list_count"] == 3, ans2
|
||||
assert ans2["list_items"] == ["Po", "Adige", "Tiber"]
|
||||
print("ok: subject guard refuses world page, accepts Italy page")
|
||||
|
||||
|
||||
# --- 3) the harvest no longer ingests Outflow --------------------------------
|
||||
|
||||
def test_harvest_outflow_boundary():
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp()
|
||||
store = KnowledgeStore(f"{tmp}/kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["total", "water", "flow"]
|
||||
|
||||
# the WORLD page: header 'Outflow' must NOT match goal term 'flow' ->
|
||||
# no harvest at all
|
||||
n = e._harvest_side_tables(world_page(), None, "flow?", "")
|
||||
assert n == 0, f"Outflow must not harvest: {n}"
|
||||
assert store.probe(["nile"]) == [] or all(
|
||||
"Outflow" not in r.rel for r in store.probe(["nile"])), \
|
||||
"no Outflow edges may exist"
|
||||
|
||||
# the ITALY page: 'Flow at the mouth' DOES match -> ingested
|
||||
e2 = make_expert(KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite"))
|
||||
e2._current_goal_terms = ["total", "water", "flow"]
|
||||
n2 = e2._harvest_side_tables(italy_page(), None, "flow?", "")
|
||||
assert n2 == 1, f"Italy flow table must harvest: {n2}"
|
||||
# probe by the relation word ('po' is a 2-char seed, filtered by law)
|
||||
rows = e2.store.probe(["flow"])
|
||||
assert any(r.rel == "Flow at the mouth" and r.dst == "1540" for r in rows), rows
|
||||
print("ok: harvest boundary — Outflow not harvested, Flow at the mouth yes")
|
||||
|
||||
|
||||
# --- 4) the EXPERT answer log -------------------------------------------------
|
||||
|
||||
def test_expert_answer_log():
|
||||
from floop.stream import RunStreams
|
||||
import tempfile
|
||||
|
||||
streams = RunStreams("guard test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
from floop.engine import KnowledgeEngine
|
||||
|
||||
class KE:
|
||||
def answer_question(self, question, parent_question=None, evidence="",
|
||||
charge_llm=None, answer_type=None):
|
||||
return {"value": "3", "source": "knowledge_graph",
|
||||
"list_items": ["Po", "Adige", "Tiber"], "list_count": 3,
|
||||
"quote": "Po | 652 | 1540", "url": "http://x",
|
||||
"confidence": "high", "stats": {}}
|
||||
ke = KnowledgeEngine(KE())
|
||||
ke.charge = lambda: None
|
||||
|
||||
class Table:
|
||||
def rows(self):
|
||||
return []
|
||||
|
||||
ke.run("Q1", "Which are the three longest rivers of Italy?", None,
|
||||
Table(), "LIST", streams=streams)
|
||||
log = (streams.run_dir / "run.log").read_text()
|
||||
assert "Q1 -> ANSWER value=3" in log, log
|
||||
assert "list of 3 members: Po, Adige, Tiber" in log, log
|
||||
assert "quote=Po | 652 | 1540" in log, log
|
||||
assert "url=http://x" in log, log
|
||||
print("ok: EXPERT answer log shows the full answer (Q1 -> ANSWER ...)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_term_hits()
|
||||
test_proper_nouns()
|
||||
test_subject_guard_list()
|
||||
test_harvest_outflow_boundary()
|
||||
test_expert_answer_log()
|
||||
print("\nguards tests passed")
|
||||
@@ -0,0 +1,139 @@
|
||||
"""PR-2 harvest tests: goal-relevant side-tables ingested in passing,
|
||||
units attached from the caption, world tables refused by entity overlap,
|
||||
seen-index + link queue. No network, no LLM.
|
||||
Run: uv run python knowledge/tests/harvest.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.streams = None
|
||||
e._log = lambda *a, **k: None
|
||||
e._checked = 0
|
||||
e._merged = 0
|
||||
# PR-3 per-call state — every attribute added to __init__ must be
|
||||
# injected into __new__-built fakes (pitfall: mid-test AttributeError)
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = ""
|
||||
e._skim_notices = []
|
||||
e._skim_leads = []
|
||||
return e
|
||||
|
||||
|
||||
def italy_page() -> WikiPage:
|
||||
wikitext = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy over {{cvt|150|km}} in length\n"
|
||||
"! Rank !! River !! Length !! Regions crossed !! Type\n|-\n"
|
||||
"| 1 || Po || 652 || Piedmont || Alpine\n|-\n"
|
||||
"| 2 || Adige || 410 || Veneto || Alpine\n|-\n"
|
||||
"| 3 || Tiber || 405 || Lazio || Apennine\n|-\n"
|
||||
"|}\n"
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy above {{cvt|50|m3/s}} of average flow at the mouth\n"
|
||||
"! Rank !! River !! Flow at the mouth !! Regions crossed !! Type\n|-\n"
|
||||
"| 1 || Po || 1540 || Piedmont || Alpine\n|-\n"
|
||||
"| 3 || Tiber || 239 || Lazio || Apennine\n|-\n"
|
||||
"| 4 || Adige || 235 || Veneto || Alpine\n|-\n"
|
||||
"|}\n")
|
||||
tables = parse_tables(wikitext)
|
||||
assert len(tables) == 2
|
||||
return WikiPage(title="List of rivers of Italy", pageid=1,
|
||||
url="https://en.wikipedia.org/wiki/List_of_rivers_of_Italy",
|
||||
text="Rivers of Italy.",
|
||||
fetched_at="2026-10-20T00:00:00+00:00",
|
||||
tables=tables, wikitext=wikitext)
|
||||
|
||||
|
||||
def test_harvest_goal_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["water", "flow", "total"]
|
||||
evidence = ("E1: list of 3 items: Po, Adige, Tiber (answers Q1)")
|
||||
n = e._harvest_side_tables(italy_page(), None, "Which are the three longest rivers of Italy?", evidence)
|
||||
# table 1 (Length) has no goal term in its header -> skipped;
|
||||
# table 2 (Flow at the mouth) matches 'flow' -> ingested
|
||||
assert n == 1, f"expected 1 harvested table, got {n}"
|
||||
# probe seeds must be >2 chars (store law): the relation 'flow' finds
|
||||
# all three rows; 'adige' the entity — exactly how the real pipeline
|
||||
# probes (question keywords, not the 2-char entity)
|
||||
rows = store.probe(["flow", "mouth"])
|
||||
flow = [r for r in rows if r.rel == "Flow at the mouth"]
|
||||
assert any(r.src == "po" and r.dst == "1540 m3/s" for r in flow), \
|
||||
f"unit must be attached from the caption: {[(r.src, r.dst) for r in flow]}"
|
||||
rows = store.probe(["adige"])
|
||||
flow = [r for r in rows if r.rel == "Flow at the mouth"]
|
||||
assert any(r.dst == "235 m3/s" for r in flow)
|
||||
# quote is the verbatim row line, contained in the stored table text
|
||||
r = flow[0]
|
||||
assert r.quote.startswith("4 | Adige | 235"), r.quote
|
||||
print("ok test_harvest_goal_table")
|
||||
|
||||
|
||||
def test_harvest_refuses_world_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["discharge"]
|
||||
wikitext = (
|
||||
'{| class="wikitable"\n|+ Rivers by discharge\n'
|
||||
"! River !! Discharge\n|-\n| Amazon || 209,000\n|-\n"
|
||||
"| Congo || 41,200\n|-\n| Ganges || 38,129\n|}\n")
|
||||
tables = parse_tables(wikitext)
|
||||
page = WikiPage(title="List of rivers by discharge", pageid=1, url="u",
|
||||
text="x", fetched_at="t", tables=tables)
|
||||
evidence = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
||||
n = e._harvest_side_tables(page, None, "q", evidence)
|
||||
assert n == 0, "a world discharge table must not answer Po/Adige/Tiber"
|
||||
assert store.probe(["amazon"]) == [] or all(
|
||||
r.rel != "Discharge" for r in store.probe(["amazon"]))
|
||||
print("ok test_harvest_refuses_world_table")
|
||||
|
||||
|
||||
def test_harvest_skips_list_answer_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["length"]
|
||||
page = italy_page()
|
||||
page._list_table_idx = 1 # the LIST answer came from table 1
|
||||
evidence = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
||||
n = e._harvest_side_tables(page, None, "q", evidence)
|
||||
assert n == 0, f"the LIST answer's table must be skipped, got {n}"
|
||||
print("ok test_harvest_skips_list_answer_table")
|
||||
|
||||
|
||||
def test_seen_index_and_link_queue():
|
||||
"""PR-2 run state: _seen_pages/_link_queue init lazily in answer_question —
|
||||
verify via the attribute contract the fetch loop relies on."""
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
# simulate the init block (answer_question does this; here we test the
|
||||
# contract: dict + list, dedupe on append)
|
||||
e._seen_pages = {}
|
||||
e._link_queue = []
|
||||
e._link_queue.append("Po (river)")
|
||||
assert "Po (river)" not in e._link_queue or e._link_queue.count("Po (river)") == 1
|
||||
print("ok test_seen_index_and_link_queue")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_harvest_goal_table()
|
||||
test_harvest_refuses_world_table()
|
||||
test_harvest_skips_list_answer_table()
|
||||
test_seen_index_and_link_queue()
|
||||
print("\nharvest PR-2 tests passed")
|
||||
@@ -0,0 +1,155 @@
|
||||
"""PR-3 tests: bounded lead promotion + skim notices to the machine.
|
||||
No network, no real LLM. Run: uv run python knowledge/tests/promote.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.streams = None
|
||||
e._log = lambda *a, **k: None
|
||||
e._checked = 0
|
||||
e._merged = 0
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = "What is the total water flow of the three longest rivers of Italy?"
|
||||
e._skim_notices = []
|
||||
e._skim_leads = []
|
||||
return e
|
||||
|
||||
|
||||
class FakePromote:
|
||||
"""Scripted skim_promote (dspy module shape): returns fixed decision."""
|
||||
def __init__(self, decision: str):
|
||||
self.decision_text = decision
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
self.calls += 1
|
||||
obj = type("P", (), {})()
|
||||
obj.decision = self.decision_text
|
||||
return obj
|
||||
|
||||
|
||||
LEAD_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy above {{cvt|50|m3/s}} of average discharge\n"
|
||||
"! Rank !! River !! Average discharge\n|-\n"
|
||||
"| 1 || Po || 1540\n|-\n| 4 || Adige || 235\n|-\n| 3 || Tiber || 239\n|}\n")
|
||||
# caption carries the unit signal (50 m3/s) but NO goal word -> a lead
|
||||
WORLD_WIKITEXT = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ World rivers above {{cvt|1000|m3/s}}\n"
|
||||
"! River !! Mean discharge\n|-\n"
|
||||
"| Amazon || 209000\n|-\n| Congo || 41200\n|-\n| Yangtze || 30166\n|}\n")
|
||||
|
||||
|
||||
def lead_page() -> WikiPage:
|
||||
return WikiPage(title="Hydrology of Italy", pageid=1, url="u1",
|
||||
text="x", fetched_at="t",
|
||||
tables=parse_tables(LEAD_WIKITEXT))
|
||||
|
||||
|
||||
def world_page() -> WikiPage:
|
||||
return WikiPage(title="List of rivers by discharge", pageid=2, url="u2",
|
||||
text="x", fetched_at="t",
|
||||
tables=parse_tables(WORLD_WIKITEXT))
|
||||
|
||||
|
||||
EVIDENCE = "E1: list of 3 items: Po, Adige, Tiber (answers Q1)"
|
||||
|
||||
|
||||
def test_promotion_ingests_goal_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["total", "considering"] # no 'flow' — lead path
|
||||
# harvest queues it as a lead (qty signal, no goal term)
|
||||
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
|
||||
# bounded promotion: LLM says YES (column Mean discharge)
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge")
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 1, "promoted table ingested"
|
||||
assert e.skim_promote.calls == 1, "exactly one bounded call"
|
||||
rows = store.probe(["discharge"])
|
||||
assert any(r.src == "po" and r.dst == "1540 m3/s" for r in rows), \
|
||||
[(r.src, r.dst) for r in rows]
|
||||
assert e._skim_leads == [], "leads consumed after the call"
|
||||
print("ok test_promotion_ingests_goal_table")
|
||||
|
||||
|
||||
def test_promotion_refuses_world_table():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
store = KnowledgeStore(Path(d) / "kg.sqlite")
|
||||
e = make_expert(store)
|
||||
e._current_goal_terms = ["total"] # no overlap with caption/header
|
||||
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG
|
||||
p = e._promote_leads(EVIDENCE, lambda: None)
|
||||
assert p == 0, "code disposes: zero entity overlap -> refused"
|
||||
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
|
||||
"a world table must never enter the KG for Po/Adige/Tiber"
|
||||
print("ok test_promotion_refuses_world_table")
|
||||
|
||||
|
||||
def test_no_leads_no_call():
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
e.skim_promote = FakePromote("1: YES x")
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 0 and e.skim_promote.calls == 0 and not charged, \
|
||||
"no leads -> zero LLM calls (bounded by construction)"
|
||||
print("ok test_no_leads_no_call")
|
||||
|
||||
|
||||
def test_notice_reaches_router_context():
|
||||
"""PR-3: a knowledge row's skim notice renders in the machine context and
|
||||
lands in the run notes."""
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import AnswerType, Budget, EvidenceRow, OpenQuestion
|
||||
from tests.machine import FakeModules, budget # noqa: I001 (tests layout)
|
||||
|
||||
fm = FakeModules(
|
||||
init_subs=[{"text": "q?", "deps": [], "answer_type": "CONSTANT"}],
|
||||
route_fn=lambda q: "numeric")
|
||||
run = FloopRun("goal?", budget(), modules=fm)
|
||||
row = EvidenceRow(
|
||||
qid="Q1", answer_type=AnswerType.CONSTANT,
|
||||
payload={"value": "22",
|
||||
"skim": ["List of rivers of Italy: table 2: Rivers above 50 m3/s | rows: 27"]},
|
||||
engine="knowledge", trace=[], provenance={},
|
||||
verified=False, note="")
|
||||
q = run.stack.items[0]
|
||||
run._append_checked(row, q)
|
||||
assert any("skim" in n and "50 m3/s" in n for n in run.notes), run.notes
|
||||
# router context: a question depending on Q1 sees the seen-in-passing line
|
||||
q2 = OpenQuestion(text="What is the flow of Adige?", deps=["Q1"])
|
||||
run.stack.items.append(q2)
|
||||
ctx = run._context(q2)
|
||||
assert "seen in passing" in ctx and "table 2" in ctx, ctx
|
||||
print("ok test_notice_reaches_router_context")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_promotion_ingests_goal_table()
|
||||
test_promotion_refuses_world_table()
|
||||
test_no_leads_no_call()
|
||||
test_notice_reaches_router_context()
|
||||
print("\npromote PR-3 tests passed")
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Skim tests (PR-1): quantities, convert resolution, infobox surface,
|
||||
skim sheet signals on a synthetic page, chunk ranking.
|
||||
No network, no LLM. Run: uv run python knowledge/tests/skim.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.skim import (SkimSheet, find_quantities, skim_article)
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables, resolve_convert
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
def test_find_quantities():
|
||||
assert find_quantities("the river carries 1,460 m3/s at its mouth") == ["1,460 m3/s"]
|
||||
assert find_quantities("above 50 m³/s of average flow") == ["50 m3/s"]
|
||||
assert find_quantities("52,000 cu ft/s (1,460 m3/s)") == ["52,000 cu ft/s", "1,460 m3/s"]
|
||||
assert find_quantities("a rank 1 river of 652 km length") == ["652 km"]
|
||||
assert find_quantities("no numbers here") == []
|
||||
print("ok test_find_quantities")
|
||||
|
||||
|
||||
def test_resolve_convert():
|
||||
assert resolve_convert("above {{cvt|50|m3/s}} of flow") == "above 50 m3/s of flow"
|
||||
assert resolve_convert("{{convert|235|m3/s|cuft/s|abbr=on}}") == "235 m3/s"
|
||||
assert resolve_convert("{{convert|1540|cuft/s|m3/s|abbr=on}}") == "1540 cu ft/s"
|
||||
assert resolve_convert("no template") == "no template"
|
||||
# unit survives the FULL cell-clean pipeline (the root bug: caption
|
||||
# cleaned to 'above 50', the unit silently dropped)
|
||||
from knowledge.wiki import _clean_cell
|
||||
assert _clean_cell("Rivers above {{cvt|50|m3/s}}") == "Rivers above 50 m3/s"
|
||||
print("ok test_resolve_convert")
|
||||
|
||||
|
||||
def test_infobox_surface():
|
||||
wt = ("{{Infobox river | river_name = Adige\n"
|
||||
" | discharge1_avg = {{convert|235|m3/s|cuft/s|abbr=on}}\n"
|
||||
" | discharge1_max = 1,200 m3/s\n"
|
||||
" | mouth = [[Adriatic Sea]]\n"
|
||||
"}}")
|
||||
page = WikiPage(title="Adige", pageid=1, url="u", text="== Course ==\nIt flows east.",
|
||||
fetched_at="t", wikitext=wt)
|
||||
sheet = skim_article(page, question_terms=["discharge"], goal_terms=["water flow"],
|
||||
evidence_entities=[])
|
||||
assert sheet.infobox_quantities.get("discharge1_avg") == "235 m3/s", sheet.infobox_quantities
|
||||
assert sheet.infobox_quantities.get("discharge1_max") == "1,200 m3/s"
|
||||
assert "discharge1_avg" in sheet.infobox_keys
|
||||
print("ok test_infobox_surface")
|
||||
|
||||
|
||||
def test_table_surface_and_notice():
|
||||
tables = parse_tables(
|
||||
"{| class=\"wikitable\"\n|+ Rivers above {{cvt|50|m3/s}}\n"
|
||||
"! Rank !! River !! Flow at the mouth\n|-\n"
|
||||
"| 1 || Po || 1540\n|-\n| 4 || Adige || 235\n|}")
|
||||
page = WikiPage(title="List of rivers of Italy", pageid=1, url="u",
|
||||
text=("== List of Italian rivers above 50 m3/s (1,800 cu ft/s) ==\n"
|
||||
"The Po discharges 1,460 m3/s."),
|
||||
fetched_at="t", tables=tables, wikitext="")
|
||||
sheet = skim_article(page, question_terms=["longest", "rivers"],
|
||||
goal_terms=["water", "flow"], evidence_entities=["Po", "Adige"])
|
||||
assert len(sheet.tables) == 1
|
||||
t = sheet.tables[0]
|
||||
assert t.rows_total == 2
|
||||
assert t.quantities and any("m3/s" in q for q in t.quantities), t.quantities
|
||||
assert any("50 m3/s" in h.quantities[0] or h.quantities for h in sheet.headings
|
||||
if h.title.startswith("List of Italian")), sheet.headings
|
||||
n = sheet.notice()
|
||||
assert "table 1" in n and "rows: 2" in n, n
|
||||
print("ok test_table_surface_and_notice")
|
||||
|
||||
|
||||
def test_link_candidates_goal_regions():
|
||||
body = ("== List of Italian rivers above 50 m3/s ==\n"
|
||||
"The largest is the [[Po (river)|Po]]; the second is the [[Adige]].\n")
|
||||
page = WikiPage(title="List of rivers of Italy", pageid=1, url="u",
|
||||
text=body, fetched_at="t", wikitext="")
|
||||
sheet = skim_article(page, question_terms=["rivers"], goal_terms=["flow"],
|
||||
evidence_entities=[])
|
||||
assert "Po (river)" in sheet.link_candidates, sheet.link_candidates
|
||||
assert "Adige" in sheet.link_candidates
|
||||
print("ok test_link_candidates_goal_regions")
|
||||
|
||||
|
||||
def test_chunk_ranking_by_skim():
|
||||
"""The PR-1 behaviour change: gated chunks are RANKED (question + goal
|
||||
terms + quantities), not taken in document order."""
|
||||
import inspect
|
||||
src = inspect.getsource(KnowledgeExpert._process_page)
|
||||
assert "goal_terms" in src, "ranking must be wired to goal terms"
|
||||
# behavioural: rank puts the quantity-bearing chunk first
|
||||
from knowledge.chunker import chunk_page
|
||||
text = ("== Geography ==\nItaly is a country in Southern Europe with a long"
|
||||
" Mediterranean coastline. The climate is varied across regions.\n\n"
|
||||
"== Hydrology ==\nRiver flow: the Po carries 1,460 m3/s, the Tiber 239 m3/s.\n")
|
||||
page = WikiPage(title="X", pageid=1, url="u", text=text, fetched_at="t")
|
||||
expert = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||
expert.cfg = KnowledgeConfig()
|
||||
expert._log = lambda *a, **k: None
|
||||
from knowledge.store import stem
|
||||
from knowledge.skim import find_quantities as fq
|
||||
chunks = chunk_page(text, target=1000, cap=2000)
|
||||
gated = [c for c in chunks if expert._gate(c, ["po"])]
|
||||
goal_terms = ["water", "flow"]
|
||||
def rank(c):
|
||||
low = c.text.casefold()
|
||||
sig = sum(1 for t in set(["po"] + goal_terms) if t and (t in low or stem(t) in low))
|
||||
return (sig + 2 * len(fq(c.text)), -c.idx)
|
||||
gated.sort(key=rank, reverse=True)
|
||||
assert "Hydrology" in gated[0].heading_path, [c.heading_path for c in gated]
|
||||
print("ok test_chunk_ranking_by_skim")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_find_quantities()
|
||||
test_resolve_convert()
|
||||
test_infobox_surface()
|
||||
test_table_surface_and_notice()
|
||||
test_link_candidates_goal_regions()
|
||||
test_chunk_ranking_by_skim()
|
||||
print("\nskim PR-1 tests passed")
|
||||
@@ -265,7 +265,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
ke.verify_count = FakeNoVerifier()
|
||||
|
||||
from knowledge.wiki import WikiPage
|
||||
page = WikiPage(title="List of states", pageid=1, url="u",
|
||||
page = WikiPage(title="List of European states", pageid=1, url="u",
|
||||
fetched_at="2026-10-18T00:00:00+00:00", text="x",
|
||||
tables=[WikiTable(idx=1, header=["Country", "Population"],
|
||||
rows=[["Albania", "2.8"], ["Belgium", "11.8"],
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Table fragments for the extract path + prompt-log tests (run G follow-up).
|
||||
No network, no real LLM. Run: uv run python knowledge/tests/tablefrags.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
|
||||
parse_stop_table)
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
from knowledge.extract import Fact
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.wiki import WikiPage
|
||||
|
||||
# --- fixtures ---------------------------------------------------------------
|
||||
|
||||
WIKITEXT_2TABLES = (
|
||||
'{| class="wikitable"\n'
|
||||
"|+ World rivers by length\n"
|
||||
"! Rank !! River !! Length (km)\n|-\n"
|
||||
+ "".join(f"| {i} || River{i} || {1000 - i}\n|-\n" for i in range(1, 101))
|
||||
+ "|}\n"
|
||||
'{| class="wikitable"\n'
|
||||
"|+ Rivers of Italy\n"
|
||||
"! River !! Flow at the mouth\n|-\n"
|
||||
"| Po || 1540\n|-\n| Adige || 235\n|-\n| Tiber || 239\n|}\n"
|
||||
)
|
||||
|
||||
|
||||
def test_tables_as_chunks():
|
||||
frags = tables_as_chunks(WIKITEXT_2TABLES, rows_per_chunk=40)
|
||||
# table 1: 100 rows -> 3 parts (40+40+20); table 2: 1 part
|
||||
t1 = [f for f in frags if f["table_idx"] == 1]
|
||||
t2 = [f for f in frags if f["table_idx"] == 2]
|
||||
assert len(t1) == 3 and t1[0]["part"] == 1 and t1[0]["of"] == 3
|
||||
assert t1[2]["part"] == 3 and len(t1[2]["rows"]) == 20
|
||||
assert len(t2) == 1 and t2[0]["of"] == 1
|
||||
# every fragment repeats the header (the extractor reads a fragment
|
||||
# standalone: 'troç 2/3' must know which columns it sees)
|
||||
for f in frags:
|
||||
assert f["header"][:2] == ["Rank", "River"] or f["header"][:2] == ["River", "Flow at the mouth"]
|
||||
text = format_table_frag(f)
|
||||
assert "Length (km)" in text or "Flow at the mouth" in text
|
||||
assert f["caption"] in text # caption in every part -> early skip possible
|
||||
print("ok: fragment generation (headers+caption repeated, part/of markers)")
|
||||
|
||||
|
||||
def test_format_and_parse_stop():
|
||||
frags = tables_as_chunks(WIKITEXT_2TABLES, rows_per_chunk=40)
|
||||
f = frags[1]
|
||||
text = format_table_frag(f)
|
||||
assert "part 2/3" in text and "caption: World rivers by length" in text
|
||||
assert "rows:" in text
|
||||
assert parse_stop_table("STOP_TABLE") is True
|
||||
assert parse_stop_table("stop_table (wrong continent)") is True
|
||||
assert parse_stop_table("Po | Flow at the mouth | 1540 m3/s | ...") is False
|
||||
assert parse_stop_table("") is False
|
||||
print("ok: fragment render + STOP_TABLE parse")
|
||||
|
||||
|
||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.streams = None
|
||||
e._checked = e._merged = 0
|
||||
e._seen_pages = {}
|
||||
e._skim_leads = []
|
||||
e._skim_notices = []
|
||||
e._current_goal_terms = []
|
||||
return e
|
||||
|
||||
|
||||
def test_process_page_fragments():
|
||||
"""The extract path over table fragments: no-signal frags skip free,
|
||||
STOP_TABLE kills the REST of that table (never other tables), and
|
||||
surviving fragments ingest their rows with containment-checked quotes.
|
||||
Mirrors run G: goal flow, page holds world-rivers + Italy tables."""
|
||||
import tempfile
|
||||
from knowledge.wiki import parse_tables
|
||||
|
||||
tmp = tempfile.mkdtemp()
|
||||
store = KnowledgeStore(f"{tmp}/kg.sqlite")
|
||||
e = make_expert(store)
|
||||
|
||||
page = WikiPage(title="Test page", url="http://x", pageid=1,
|
||||
fetched_at="2026-10-20T00:00:00Z",
|
||||
text="Prose only. Italy has rivers.",
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts, stop=False):
|
||||
self.facts = facts
|
||||
self.stop = stop
|
||||
|
||||
def fake_extract(question, heading, text, _calls=calls):
|
||||
_calls.append((question, heading, text))
|
||||
if "World rivers" in text:
|
||||
return FakeOut([], stop=True)
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
return FakeOut([Fact(
|
||||
subject="Po", relation="Flow at the mouth",
|
||||
object="1540 m3/s",
|
||||
quote="River | Flow at the mouth Po | 1540")])
|
||||
return FakeOut([])
|
||||
|
||||
e.extract = fake_extract
|
||||
|
||||
q = "What is the total water flow of the three longest rivers of Italy?"
|
||||
kws = e._keywords("What is the water flow of rivers of Italy?")
|
||||
# _process_page signature: (page, question, kws, goal_terms, charge_llm)
|
||||
n = e._process_page(page, question=q, kws=kws,
|
||||
goal_terms=["total", "water", "flow", "italy"],
|
||||
charge_llm=None)
|
||||
# the Italy fragment ingested its fact (merged counts edges)
|
||||
rows = store.probe(["italy", "flow"])
|
||||
# probe returns norm_name'd src ('po', not 'Po') — store law
|
||||
assert any(r.dst == "1540 m3/s" and r.src == "po"
|
||||
and r.rel == "Flow at the mouth" for r in rows), rows
|
||||
# STOP_TABLE must have short-circuited table 1 after its FIRST fragment:
|
||||
# at most 1 extract call for table 1 (not 3), plus 1 for the Italy table
|
||||
world_calls = [c for c in calls if "World rivers" in c[2]]
|
||||
assert len(world_calls) == 1, f"STOP_TABLE did not skip parts 2/3: {len(world_calls)} calls"
|
||||
print("ok: extract fragments — STOP_TABLE skips rest of table, facts ingest")
|
||||
|
||||
|
||||
def test_prompt_log():
|
||||
"""The dspy global callback: stage via module stack (not call_id — they
|
||||
differ), NN file per call, exact rendered prompt on disk."""
|
||||
import dspy
|
||||
from dspy.utils.dummies import DummyLM
|
||||
from floop.llm import PromptLogCallback
|
||||
from floop.stream import RunStreams
|
||||
import tempfile as tf
|
||||
|
||||
dspy.settings.configure(callbacks=[]) # reset any global state
|
||||
streams = RunStreams("test question", verbose=False,
|
||||
runs_dir=tf.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=DummyLM([
|
||||
{"facts": "Po | flow | 1540 | the Po flows at 1540 m3/s"},
|
||||
{"facts": ""},
|
||||
]), callbacks=[cb])
|
||||
|
||||
class MyExtractSignature(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
text: str = dspy.InputField()
|
||||
facts: str = dspy.OutputField()
|
||||
|
||||
ex = dspy.Predict(MyExtractSignature)
|
||||
ex(question="flow of Po?", text="the Po flows at 1540 m3/s")
|
||||
ex(question="flow of Po?", text="the Po also has fish")
|
||||
|
||||
pdir = streams.run_dir / "prompts"
|
||||
files = sorted(pdir.glob("*.txt"))
|
||||
assert len(files) == 2, files
|
||||
assert files[0].name == "01-MyExtractSignature.txt", files[0].name
|
||||
assert files[1].name == "02-MyExtractSignature.txt", files[1].name
|
||||
body = files[0].read_text()
|
||||
assert "flow of Po?" in body and "the Po flows at 1540 m3/s" in body
|
||||
assert body.startswith("# stage=MyExtractSignature call_seq=1")
|
||||
# the log carries the size line for each call
|
||||
log = streams.run_dir / "run.log"
|
||||
content = log.read_text()
|
||||
assert "prompt #1 stage=MyExtractSignature" in content
|
||||
assert "prompt #2 stage=MyExtractSignature" in content
|
||||
print("ok: prompt log — files NN-stage.txt + size lines in run.log")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_tables_as_chunks()
|
||||
test_format_and_parse_stop()
|
||||
test_process_page_fragments()
|
||||
test_prompt_log()
|
||||
print("\ntable fragments + prompt log tests passed")
|
||||
+107
-18
@@ -64,6 +64,7 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
|
||||
spans: dict[int, str] = {} # col -> carried value (rowspan)
|
||||
span_left: dict[int, int] = {} # col -> rows still to carry it
|
||||
raw_cells: list[str] = []
|
||||
raw_marks: list[bool] = [] # per-cell '!' marker seen (mixed rows)
|
||||
row_is_header = False
|
||||
|
||||
def flush_row(cells: list[str], is_header: bool) -> None:
|
||||
@@ -103,15 +104,24 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
|
||||
continue
|
||||
if line.startswith("|-") or line.startswith("!-"):
|
||||
if raw_cells:
|
||||
flush_row(raw_cells, row_is_header)
|
||||
raw_cells, row_is_header = [], False
|
||||
# mixed row ('!' first cell + '|' data cells) is a DATA
|
||||
# row — a data row's leading !scope="row" th is a row
|
||||
# LABEL, not a header (run-G bug: the world rivers table
|
||||
# turned into 1,825 'header' cells and zero rows)
|
||||
header = row_is_header and all(raw_marks)
|
||||
flush_row(raw_cells, header)
|
||||
raw_cells, raw_marks = [], []
|
||||
row_is_header = False
|
||||
continue
|
||||
if line.startswith("!"):
|
||||
raw_cells.extend(re.split(r"!!", line.lstrip("!")))
|
||||
raw_marks.extend([True] * len(re.split(r"!!", line.lstrip("!"))))
|
||||
row_is_header = True
|
||||
continue
|
||||
if line.startswith("|"):
|
||||
raw_cells.extend(re.split(r"\|\|", line.lstrip("|")))
|
||||
cells = re.split(r"\|\|", line.lstrip("|"))
|
||||
raw_cells.extend(cells)
|
||||
raw_marks.extend([False] * len(cells))
|
||||
continue
|
||||
# continuation line: multi-line refs/templates inside a cell do
|
||||
# not start with a marker — they belong to the previous raw cell
|
||||
@@ -119,7 +129,7 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
|
||||
raw_cells[-1] += " " + line
|
||||
continue
|
||||
if raw_cells:
|
||||
flush_row(raw_cells, row_is_header)
|
||||
flush_row(raw_cells, row_is_header and all(raw_marks))
|
||||
if header_grid:
|
||||
t.header = [c for r in header_grid for c in r]
|
||||
t.rows = grid
|
||||
@@ -128,14 +138,61 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
|
||||
return tables
|
||||
|
||||
|
||||
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
|
||||
"""Legacy helper for prose enrichment (fetch_rich). The LIST path uses
|
||||
parse_tables directly — untruncated and typed."""
|
||||
out: list[str] = []
|
||||
CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
|
||||
"refn", "anchor")
|
||||
|
||||
|
||||
def tables_as_chunks(wikitext: str, max_tables: int = 3,
|
||||
rows_per_chunk: int = 40) -> list[dict]:
|
||||
"""Tables for the EXTRACT path, as small structured fragments — never a
|
||||
22k-char table dump (run G, call 8/80).
|
||||
|
||||
Every fragment REPEATS THE HEADER: the extractor must be able to tell
|
||||
'troç 2/10' — which table, which columns — from the fragment alone.
|
||||
The first fragment of a table also carries the caption, so the extract
|
||||
LLM can early-skip a table whose SUBJECT is already hopeless (world
|
||||
rivers vs Italy) without reading all fragments.
|
||||
"""
|
||||
frags: list[dict] = []
|
||||
for t in parse_tables(wikitext, max_tables=max_tables):
|
||||
lines = t.text_lines()
|
||||
out.append(chr(10).join(lines[:max_rows]))
|
||||
return (chr(10) * 2).join(out)
|
||||
rows = t.rows
|
||||
n_total = max(1, -(-len(rows) // rows_per_chunk)) # ceil
|
||||
for j in range(0, len(rows), rows_per_chunk):
|
||||
part = j // rows_per_chunk
|
||||
frag = {
|
||||
"table_idx": t.idx,
|
||||
"caption": t.caption or "",
|
||||
"header": t.header,
|
||||
"part": part + 1,
|
||||
"of": n_total,
|
||||
"rows": rows[j: j + rows_per_chunk],
|
||||
}
|
||||
frags.append(frag)
|
||||
return frags
|
||||
|
||||
|
||||
def format_table_frag(frag: dict) -> str:
|
||||
"""Render a fragment for the extractor: header + caption + part marker +
|
||||
rows, one 'a | b | c' line per row. The extractor sees WHICH table it is
|
||||
in, so it can answer STOP_TABLE when rows cannot contain the answer."""
|
||||
head = " | ".join(frag["header"]) if frag["header"] else "(no header)"
|
||||
caption = f"caption: {frag['caption']}" if frag["caption"] else ""
|
||||
part = f"table {frag['table_idx']} — part {part_of(frag)}" if frag["of"] > 1 else (
|
||||
f"table {frag['table_idx']}")
|
||||
lines = [l if isinstance(l, str) else " | ".join(l) for l in frag["rows"]]
|
||||
out = [caption] if caption else []
|
||||
out += [part, head, "rows:"] + lines
|
||||
return chr(10).join(out)
|
||||
|
||||
|
||||
def part_of(frag: dict) -> str:
|
||||
return f"{frag['part']}/{frag['of']}"
|
||||
|
||||
|
||||
def parse_stop_table(out_text: str) -> bool:
|
||||
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
|
||||
code reads the typed `stop: bool` field of ExtractSignature."""
|
||||
return "STOP_TABLE" in (out_text or "").upper()[:80]
|
||||
|
||||
|
||||
CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
|
||||
@@ -157,12 +214,37 @@ def _tpl_arg(content: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
CONVERT_RE = re.compile(r"\{\{(?:convert|cvt)\|([^{}]+)\}\}", re.I)
|
||||
_UNIT_CANON = {"cuft/s": "cu ft/s", "ft3/s": "cu ft/s", "m³/s": "m3/s",
|
||||
"km²": "km2", "mi²": "mi2"}
|
||||
|
||||
|
||||
def resolve_convert(text: str) -> str:
|
||||
"""Resolve {{convert|N|unit|...}} / {{cvt|N|unit|...}} to 'N unit'.
|
||||
|
||||
The primary unit is the fact; display-side secondary units are dropped
|
||||
(PR-1 unit-loss fix: a caption saying 'above {{cvt|50|m3/s}}' cleaned
|
||||
to 'above 50' — the unit is data, quantities carry values AND units)."""
|
||||
def _one(m: re.Match) -> str:
|
||||
parts = [p.strip() for p in m.group(1).split("|")]
|
||||
if len(parts) < 2 or not parts[0]:
|
||||
return m.group(0)
|
||||
num = parts[0].rstrip(".,")
|
||||
unit = parts[1].replace("\u00a0", " ").strip()
|
||||
unit = unit.lower()
|
||||
unit = _UNIT_CANON.get(unit, unit)
|
||||
return f"{num} {unit}"
|
||||
return CONVERT_RE.sub(_one, text or "")
|
||||
|
||||
|
||||
def _clean_cell(cell: str) -> str:
|
||||
"""Resolve links/templates to display text; drop refs, File links, tags.
|
||||
|
||||
Order matters: <br> variants become ' / ' separators FIRST (multi-value
|
||||
name cells like 'Albania<br>Republic of Albania<br>ALB' must not
|
||||
concatenate), then refs, File links, links, templates."""
|
||||
concatenate), then refs, File links, links, templates. convert/cvt
|
||||
templates resolve to 'N unit' BEFORE the generic template pass — the
|
||||
generic pass keeps only the first argument and would drop the unit."""
|
||||
cell = re.sub(r"<br\s*/?>", " / ", cell, flags=re.I)
|
||||
cell = re.sub(r"<ref[^>]*>.*?</ref>", "", cell, flags=re.S | re.I)
|
||||
cell = re.sub(r"<ref[^>]*/?>", "", cell, flags=re.I)
|
||||
@@ -170,6 +252,7 @@ def _clean_cell(cell: str) -> str:
|
||||
cell = re.sub(r"<sup[^>]*/?>", "", cell, flags=re.I)
|
||||
cell = re.sub(r"\[\[(?:File|Image):.*?\]\]", "", cell, flags=re.I | re.S)
|
||||
cell = re.sub(r"\[\[(?:[^|\]]*\|)*([^\]]+)\]\]", r"\1", cell)
|
||||
cell = resolve_convert(cell)
|
||||
while "{{" in cell:
|
||||
new = re.sub(r"\{\{([^{}]*)\}\}", lambda mm: _tpl_arg(mm.group(1)), cell)
|
||||
if new == cell:
|
||||
@@ -206,6 +289,7 @@ class WikiPage:
|
||||
fetched_at: str # ISO timestamp
|
||||
rev_id: int | None = None
|
||||
tables: list[WikiTable] = field(default_factory=list)
|
||||
wikitext: str = "" # raw source (infobox params live here; PR-1)
|
||||
|
||||
@property
|
||||
def sections(self) -> list[str]:
|
||||
@@ -297,15 +381,20 @@ class WikipediaClient:
|
||||
|
||||
def fetch_rich(self, title: str) -> WikiPage:
|
||||
"""Extract + typed tables: wikitext tables are parsed UNTRUNCATED into
|
||||
WikiTable objects (total_rows is a computed fact). Prose enrichment
|
||||
(== Tables == section) kept for the chunk path; the LIST path reads
|
||||
page.tables directly."""
|
||||
WikiTable objects (total_rows is a computed fact). The raw wikitext
|
||||
stays on the page (skim's infobox surface) and {{convert|N|unit}}
|
||||
resolves to 'N unit' (PR-1 unit-loss fix).
|
||||
|
||||
NO '== Tables ==' prose enrichment anymore: a 226-row table flattened
|
||||
into page.text became one 22k-char chunk that hung the extract call
|
||||
(run G, call 8/80) and let verify_count cite the table as 'prose'.
|
||||
Tables now reach the extract path as small per-table fragments
|
||||
(tables_as_chunks), and the LIST/harvest paths read page.tables
|
||||
directly."""
|
||||
page = self.fetch(title)
|
||||
wikitext = self.fetch_wikitext(title)
|
||||
page.tables = parse_tables(wikitext)
|
||||
extra = tables_as_text(wikitext)
|
||||
if extra:
|
||||
page.text = page.text + "\n\n== Tables ==\n" + extra
|
||||
page.wikitext = wikitext
|
||||
return page
|
||||
|
||||
def disambiguation(self, title: str) -> list[str]:
|
||||
|
||||
+2
-1
@@ -20,7 +20,7 @@ import yaml
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from floop.llm import configure_lm # noqa: E402
|
||||
from floop.llm import configure_lm, install_prompt_log # noqa: E402
|
||||
from floop.machine import FloopRun, RunReport # noqa: E402
|
||||
from floop.state import Budget # noqa: E402
|
||||
from floop.stream import RunStreams # noqa: E402
|
||||
@@ -61,6 +61,7 @@ def main() -> None:
|
||||
|
||||
lm_info = configure_lm()
|
||||
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
||||
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
||||
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}")
|
||||
|
||||
if baseline:
|
||||
|
||||
@@ -31,7 +31,7 @@ class FakeModules:
|
||||
|
||||
def init_decompose(self, question):
|
||||
self.calls.append(f"init:{question[:30]}")
|
||||
return list(self.init_subs)
|
||||
return list(self.init_subs), "" # (subs, raw) — atomic when empty
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
self.calls.append("missing")
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Re-ask meter tests (run L): dspy's adapter JSON fallback fires a second
|
||||
LM call inside the SAME module forward — the budget never charged it
|
||||
(9/80 logged, 10 on the wire, the extra burning 340s of GPU).
|
||||
|
||||
Laws under test:
|
||||
1. The meter DETECTS the fallback (marker-less first response) and charges
|
||||
the budget once via the hook; dspy's behaviour is untouched (the second
|
||||
call still runs — his call: the fallback stays, it is future
|
||||
self-improvement signal).
|
||||
2. Separate forwards (the ablation rounds) are NOT re-asks.
|
||||
3. A re-ask at budget ceiling does not kill the run (the call already
|
||||
happened — note only).
|
||||
|
||||
The repro drives dspy's REAL adapter path: a custom engine returning raw
|
||||
text (exactly what the OpenAI-compatible endpoint returns), first response
|
||||
WITHOUT the '[[ ## field ## ]]' marker -> ChatAdapter raises
|
||||
AdapterParseError -> JSONAdapter fallback re-fires the call.
|
||||
|
||||
Run: .venv/bin/python tests/reask_meter.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
|
||||
from floop.llm import PromptLogCallback
|
||||
from floop.stream import RunStreams
|
||||
from floop.state import Budget, BudgetExhausted
|
||||
|
||||
|
||||
class AnswerSig(dspy.Signature):
|
||||
goal: str = dspy.InputField()
|
||||
final_answer: str = dspy.OutputField()
|
||||
|
||||
|
||||
def _resp(text: str) -> Response:
|
||||
return Response(
|
||||
id="x", model="fake",
|
||||
message=Message(role="assistant", parts=(TextPart(text=text),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1))
|
||||
|
||||
|
||||
class FallbackEngine:
|
||||
"""First response lacks the output-field marker: the ChatAdapter parse
|
||||
fails and the JSON-adapter fallback re-fires the call (run-L shape)."""
|
||||
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
self.responses = [
|
||||
"L'anterior president del Govern d'Espanya va ser Mariano Rajoy.",
|
||||
'{"final_answer": "Mariano Rajoy (JSON retry)"}',
|
||||
]
|
||||
|
||||
def complete(self, request, **kw):
|
||||
i = min(self.i, len(self.responses) - 1)
|
||||
self.i += 1
|
||||
return _resp(self.responses[i])
|
||||
|
||||
|
||||
class CleanEngine:
|
||||
"""Every forward parses cleanly — two separate module forwards, no
|
||||
fallback (the ablation-rounds shape: same stage, fresh forwards)."""
|
||||
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
|
||||
def complete(self, request, **kw):
|
||||
self.i += 1
|
||||
return _resp(f"[[ ## final_answer ## ]]\nreading {self.i}")
|
||||
|
||||
|
||||
def test_fallback_detected_and_charged():
|
||||
streams = RunStreams("meter test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=dspy.LM(model="fake", engine=FallbackEngine()),
|
||||
callbacks=[cb])
|
||||
charged = []
|
||||
cb.meter = lambda stage: charged.append(stage)
|
||||
|
||||
out = dspy.Predict(AnswerSig)(goal="who?")
|
||||
files = list((streams.run_dir / "prompts").glob("*.txt"))
|
||||
assert len(files) == 2, f"two wire calls expected: {[f.name for f in files]}"
|
||||
assert cb.reasks == 1, cb.reasks
|
||||
assert charged == ["AnswerSig"], charged
|
||||
assert "JSON retry" in out.final_answer, "dspy behaviour untouched"
|
||||
print("ok: adapter fallback detected — 2 wire calls, 1 re-ask, 1 charge")
|
||||
|
||||
|
||||
def test_separate_forwards_not_flagged():
|
||||
streams = RunStreams("rounds test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
charged = []
|
||||
cb.meter = lambda stage: charged.append(stage)
|
||||
dspy.configure(lm=dspy.LM(model="fake2", engine=CleanEngine()),
|
||||
callbacks=[cb])
|
||||
p = dspy.Predict(AnswerSig)
|
||||
p(goal="q1")
|
||||
p(goal="q2") # second forward: fresh module start, NOT a re-ask
|
||||
assert cb.reasks == 0, f"separate forwards flagged: {cb.reasks}"
|
||||
assert charged == []
|
||||
print("ok: two separate forwards (ablation rounds) NOT flagged")
|
||||
|
||||
|
||||
def test_meter_never_kills_run():
|
||||
"""The meter hook raising (budget ceiling) must not kill the run —
|
||||
the wire call already happened."""
|
||||
from floop.machine import FloopRun
|
||||
b = Budget(max_llm_calls=1, max_depth=1, max_retries=1,
|
||||
missing_extensions=1, min_child_budget=1)
|
||||
# simulate: budget at ceiling, meter fires
|
||||
class FakeModules:
|
||||
pass
|
||||
|
||||
fm = FloopRun.__new__(FloopRun)
|
||||
fm.budget = b
|
||||
fm.notes = []
|
||||
fm.streams = None
|
||||
fm._meter_reask("ANSWER")
|
||||
assert fm.budget.llm_calls == 1, "ceiling charge must not overflow the count"
|
||||
assert any("re-ask charged" in n for n in fm.notes), fm.notes
|
||||
print("ok: meter at ceiling — charged honestly, run survives")
|
||||
|
||||
|
||||
def main():
|
||||
test_fallback_detected_and_charged()
|
||||
test_separate_forwards_not_flagged()
|
||||
test_meter_never_kills_run()
|
||||
print("\nre-ask meter tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I).
|
||||
|
||||
Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM
|
||||
answered with its own line numbers as an extra pipe field
|
||||
('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1'
|
||||
and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and
|
||||
the machine burned 4 calls on garbage before luck produced the answer.
|
||||
|
||||
Three laws under test:
|
||||
1. parse_subquestions shifts the numbered form and never accepts a bare
|
||||
number as a subquestion text.
|
||||
2. The machine degrades to the ORIGINAL question as one OPEN
|
||||
subquestion when nothing parses (a routable question is text).
|
||||
3. The prompt log appends the RAW LM response to the prompt file — the
|
||||
parsed OUTPUT line can lie by omission.
|
||||
|
||||
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
from floop.state import AnswerType, Budget
|
||||
from floop.machine import FloopRun
|
||||
|
||||
|
||||
# --- 1) the parser -----------------------------------------------------------
|
||||
|
||||
def test_parse_numbered_lines():
|
||||
# the exact run-I shape: model line numbers as an extra first field
|
||||
raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n"
|
||||
"2 | When did that president's term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?"
|
||||
assert subs[0]["deps"] == []
|
||||
assert subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1], subs[1]
|
||||
print("ok: numbered-line form shifted (text, deps, type all intact)")
|
||||
|
||||
|
||||
def test_parse_bare_number_lines_dropped():
|
||||
# even if the number survives as text, it must be dropped — never routable
|
||||
raw = "1 | none | OPEN\n2 | none | OPEN"
|
||||
subs = parse_subquestions(raw)
|
||||
assert subs == [], subs
|
||||
print("ok: bare-number texts dropped (nothing routable = '1' or '2')")
|
||||
|
||||
|
||||
def test_parse_enumerator_prefix():
|
||||
# '1. Who was ...' inside the FIRST field — not a separate field
|
||||
raw = ("1. Who was the President before Pedro Sanchez? | none | OPEN\n"
|
||||
"2. When did his term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President before Pedro Sanchez?"
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: enumerator prefixes stripped from the text field")
|
||||
|
||||
|
||||
def test_parse_happy_path_unchanged():
|
||||
# the old well-formed cases keep working (regression guard)
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||\n1 | none | OPEN") == []
|
||||
print("ok: well-formed lines parse exactly as before")
|
||||
|
||||
|
||||
# --- 2) the INIT degrade -----------------------------------------------------
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
# (subs, raw): nothing parses, but the model DID write — degrade
|
||||
return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"),
|
||||
"1 | none | OPEN\n2 | 1 | OPEN")
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
|
||||
|
||||
def test_init_degrades_to_original_question():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
fm = GarbageInitModules()
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm)
|
||||
rep = run.run()
|
||||
# the machine must have routed the ORIGINAL question, not '1'/'2'
|
||||
assert rep is not None
|
||||
q1 = rep.questions[0]
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number
|
||||
assert "Pedro Sanchez" in q1[2]
|
||||
assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions
|
||||
print("ok: INIT degrade routes the original question as one OPEN subq")
|
||||
|
||||
|
||||
# --- 3) the raw-response log --------------------------------------------------
|
||||
|
||||
def test_prompt_log_captures_raw_response():
|
||||
import dspy
|
||||
from dspy.utils.dummies import DummyLM
|
||||
import tempfile as tf
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
from floop.stream import RunStreams
|
||||
|
||||
dspy.settings.configure(callbacks=[])
|
||||
streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=DummyLM([
|
||||
{"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"}
|
||||
]), callbacks=[cb])
|
||||
|
||||
class Sig(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField()
|
||||
|
||||
dspy.Predict(Sig)(question="Who was the President before Pedro Sanchez?")
|
||||
f = next((streams.run_dir / "prompts").glob("01-*.txt"))
|
||||
content = f.read_text()
|
||||
assert "# RAW RESPONSE" in content, content
|
||||
assert "Who was Pedro Sanchez?" in content, content
|
||||
print(f"ok: raw response appended to {f.name}")
|
||||
dspy.settings.configure(callbacks=[])
|
||||
|
||||
|
||||
|
||||
def test_empty_raw_stays_atomic():
|
||||
"""Empty RAW (the model truly returned nothing) keeps the old law: the
|
||||
goal is atomic — stop and synthesize, never fabricate a subquestion."""
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class AtomicModules(GarbageInitModules):
|
||||
def init_decompose(self, question):
|
||||
return [], ""
|
||||
|
||||
fm = AtomicModules()
|
||||
rep = FloopRun("What is the speed of light?", b, modules=fm).run()
|
||||
# atomic: INIT added no subquestions — only the goal's own Q0 remains
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0", rep.questions
|
||||
assert rep.questions[0][2] == "What is the speed of light?", rep.questions
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_parse_numbered_lines()
|
||||
test_parse_bare_number_lines_dropped()
|
||||
test_parse_enumerator_prefix()
|
||||
test_parse_happy_path_unchanged()
|
||||
test_init_degrades_to_original_question()
|
||||
test_empty_raw_stays_atomic()
|
||||
test_prompt_log_captures_raw_response()
|
||||
print("\nrobust_init tests passed")
|
||||
Reference in New Issue
Block a user