knowledge: table fragments for extract + exact prompt log (run G fixes)

Run G hung at call 8/80 for minutes with no way to see what was sent.
Reproducing it found TWO root causes, both fixed here:

1. THE 22K TABLE CHUNK WAS A PARSER BUG, not just a size problem. The
   world-rivers table marks each data row's leading cell with
   '!scope="row"|' (a row-label th); parse_tables flagged any row that
   touched a '!' as a header row, so all 227 data rows collapsed into ONE
   header of 1,825 cells and zero rows. tables_as_text then flattened
   that monster into a single 22,021-char prose chunk. Fix: a row is a
   header row only if ALL its cells are '!' cells; mixed rows are data
   rows. Live: the world table now parses as 8 cols x 227 rows.

2. NO PROMPT OBSERVABILITY. The log's CALL/OUTPUT lines never carried
   what the LM actually received. floop/llm.py now installs a dspy global
   callback (PromptLogCallback): every LM call's exact rendered prompt
   lands in runs/<ts>/prompts/NN-stage.txt (NN mirrors the budget counter
   -- 08-EXTRACT.txt IS call 8/80), plus size/duration lines in run.log.
   Stage comes from a module stack (dspy fires on_module_start with a
   DIFFERENT call_id than the inner LM call -- verified with DummyLM
   probes), not a call_id map.

Plus the design Emili steered (tables reach the extractor as typed
fragments, never prose dumps):
- tables_as_chunks: per-table fragments of <=40 rows, EVERY fragment
  repeats header + caption, part i/N markers; the extractor always knows
  which table ('troç 2/10') it is reading.
- STOP_TABLE: the extractor may early-skip a table whose subject is
  wrong for the question after one fragment; fixed code skips the rest
  of THAT table. ExtractSignature teaches the protocol.
- fetch_rich no longer appends the '== Tables ==' enrichment to prose
  (the giant chunk's birthplace; also let verify_count cite the table as
  'prose'). Tables reach the extract path only as fragments; LIST and
  harvest keep reading page.tables directly.
- fragment candidates pass the same containment check against prose +
  full table text; LIST answer's table never re-enters extract.

Tests: knowledge/tests/tablefrags.py (fragment generation/render,
STOP_TABLE skipping, fragment extraction with containment, prompt log
files + log lines). Live smoke: world article 10 chunks none >5k; world
table = 6 fragments (max 5,787c); Italy discharge fragment intact
(Po/1540). Full suite 47/47.
This commit is contained in:
2026-10-20 20:22:29 +02:00
parent ad9baf243b
commit 9eab127727
7 changed files with 461 additions and 24 deletions
+118
View File
@@ -2,10 +2,17 @@
dspy 3.x routes through litellm, so model ids carry the provider prefix — 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). "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 from __future__ import annotations
import os import os
import re
from pathlib import Path from pathlib import Path
import dspy import dspy
@@ -17,6 +24,105 @@ def _load_yaml() -> dict:
return yaml.safe_load(cfg.read_text()) 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.
"""
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
# -- 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)
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)
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)
(pdir / fn).write_text(
f"# stage={label} call_seq={n} chars={chars} "
f"tokens~{chars // 4}\n\n" + text,
encoding="utf-8",
)
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)
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
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: def configure_lm() -> dict:
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override. """Configure dspy's default LM from config.yaml + FLOOP_LM env override.
@@ -43,7 +149,19 @@ def configure_lm() -> dict:
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]} 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 _ACTIVE: "dspy.LM | None" = None
_PROMPT_LOG: "PromptLogCallback | None" = None
def active_lm() -> "dspy.LM": def active_lm() -> "dspy.LM":
+7
View File
@@ -34,8 +34,15 @@ class RunStreams:
self.run_dir.mkdir(parents=True, exist_ok=True) self.run_dir.mkdir(parents=True, exist_ok=True)
self.log_path = self.run_dir / "run.log" self.log_path = self.run_dir / "run.log"
self.verbose = verbose self.verbose = verbose
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
self._fh = open(self.log_path, "a", encoding="utf-8") 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: def close(self) -> None:
if self._fh and not self._fh.closed: if self._fh and not self._fh.closed:
self._fh.close() self._fh.close()
+67 -2
View File
@@ -28,7 +28,8 @@ from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
SkimPromoteSignature, TranslateSignature, SkimPromoteSignature, TranslateSignature,
VerifyCountSignature, parse_facts) VerifyCountSignature, parse_facts)
from .store import KnowledgeStore, norm_name from .store import KnowledgeStore, norm_name
from .wiki import WikipediaClient, WikiPage, WikiTable, resolve_convert 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']+") WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
@@ -760,8 +761,24 @@ class KnowledgeExpert:
return (sig + 2 * len(find_quantities(c.text)), -c.idx) return (sig + 2 * len(find_quantities(c.text)), -c.idx)
gated.sort(key=rank, reverse=True) gated.sort(key=rank, reverse=True)
capped = gated[: self.cfg.max_chunks_extracted] 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, " self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated, "
f"{len(capped)} extracted (skim-ranked)", think=True) f"{len(capped)} extracted (skim-ranked); "
f"{len(table_frags)} table frags, {frag_budget} considered",
think=True)
extracted = 0
for chunk in capped: for chunk in capped:
if charge_llm: if charge_llm:
charge_llm() charge_llm()
@@ -778,6 +795,54 @@ class KnowledgeExpert:
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) 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.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
self._merged += 1 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 parse_stop_table(raw.facts):
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 parse_facts(raw.facts):
self._checked += 1
# containment against prose + FULL table text: the fragment is
# rendered from the same rows, so quotes verify honestly
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 return self._merged
def _gate(self, chunk, keywords: list[str]) -> bool: def _gate(self, chunk, keywords: list[str]) -> bool:
+7 -2
View File
@@ -28,12 +28,17 @@ class ExtractSignature(dspy.Signature):
subject | relation | object | verbatim quote from the text. subject | relation | object | verbatim quote from the text.
The quote must be the FULL sentence or table ROW that states the fact, The quote must be the FULL sentence or table ROW that states the fact,
copied exactly (at least 10 characters). Only facts the text states; 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 and you can already tell
from its caption/headers that this table cannot contain anything
relevant to the question (wrong subject entirely), reply with the
single word STOP_TABLE and no facts. Do NOT use STOP_TABLE for text
that is merely hard — only when the table's subject is wrong."""
question: str = dspy.InputField() question: str = dspy.InputField()
heading: str = dspy.InputField(desc="section path of this chunk; context only") heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField() text: str = dspy.InputField()
facts: str = dspy.OutputField( facts: str = dspy.OutputField(
desc="one fact per line: subject | relation | object | verbatim quote; empty if none") desc="one fact per line: subject | relation | object | verbatim quote; empty if none; or STOP_TABLE if this table fragment's subject is wrong for the question")
class AnswerFromKG(dspy.Signature): class AnswerFromKG(dspy.Signature):
+180
View File
@@ -0,0 +1,180 @@
"""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.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_TABLE; Italy table -> one fact
calls = []
class FakeOut:
def __init__(self, facts):
self.facts = facts
def fake_extract(question, heading, text, _calls=calls):
_calls.append((question, heading, text))
if "World rivers" in text:
return FakeOut("STOP_TABLE")
if "Rivers of Italy" in text:
# quote = the full rendered row context (header + row), verbatim
# from the fragment the extractor saw
return FakeOut("Po | Flow at the mouth | 1540 m3/s | "
"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")
+80 -19
View File
@@ -64,6 +64,7 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
spans: dict[int, str] = {} # col -> carried value (rowspan) spans: dict[int, str] = {} # col -> carried value (rowspan)
span_left: dict[int, int] = {} # col -> rows still to carry it span_left: dict[int, int] = {} # col -> rows still to carry it
raw_cells: list[str] = [] raw_cells: list[str] = []
raw_marks: list[bool] = [] # per-cell '!' marker seen (mixed rows)
row_is_header = False row_is_header = False
def flush_row(cells: list[str], is_header: bool) -> None: 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 continue
if line.startswith("|-") or line.startswith("!-"): if line.startswith("|-") or line.startswith("!-"):
if raw_cells: if raw_cells:
flush_row(raw_cells, row_is_header) # mixed row ('!' first cell + '|' data cells) is a DATA
raw_cells, row_is_header = [], False # 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 continue
if line.startswith("!"): if line.startswith("!"):
raw_cells.extend(re.split(r"!!", line.lstrip("!"))) raw_cells.extend(re.split(r"!!", line.lstrip("!")))
raw_marks.extend([True] * len(re.split(r"!!", line.lstrip("!"))))
row_is_header = True row_is_header = True
continue continue
if line.startswith("|"): 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 continue
# continuation line: multi-line refs/templates inside a cell do # continuation line: multi-line refs/templates inside a cell do
# not start with a marker — they belong to the previous raw cell # 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 raw_cells[-1] += " " + line
continue continue
if raw_cells: if raw_cells:
flush_row(raw_cells, row_is_header) flush_row(raw_cells, row_is_header and all(raw_marks))
if header_grid: if header_grid:
t.header = [c for r in header_grid for c in r] t.header = [c for r in header_grid for c in r]
t.rows = grid t.rows = grid
@@ -128,14 +138,63 @@ def parse_tables(wikitext: str, max_tables: int = 4) -> list[WikiTable]:
return tables return tables
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str: CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
"""Legacy helper for prose enrichment (fetch_rich). The LIST path uses "refn", "anchor")
parse_tables directly — untruncated and typed."""
out: list[str] = []
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): for t in parse_tables(wikitext, max_tables=max_tables):
lines = t.text_lines() rows = t.rows
out.append(chr(10).join(lines[:max_rows])) n_total = max(1, -(-len(rows) // rows_per_chunk)) # ceil
return (chr(10) * 2).join(out) 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:
"""True when the extractor's output names this table as not relevant for
the question. The extractor may write STOP_TABLE for a fragment's table
after seeing its identity (caption/header) — fixed code then skips all
remaining fragments of THAT table (never other tables)."""
return "STOP_TABLE" in (out_text or "").upper()[:80]
CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note", CITATION_TPL = ("cref", "cref2", "efn", "sfn", "fn", "citation", "cite", "note",
@@ -324,18 +383,20 @@ class WikipediaClient:
def fetch_rich(self, title: str) -> WikiPage: def fetch_rich(self, title: str) -> WikiPage:
"""Extract + typed tables: wikitext tables are parsed UNTRUNCATED into """Extract + typed tables: wikitext tables are parsed UNTRUNCATED into
WikiTable objects (total_rows is a computed fact). Prose enrichment WikiTable objects (total_rows is a computed fact). The raw wikitext
(== Tables == section) kept for the chunk path; the LIST path reads stays on the page (skim's infobox surface) and {{convert|N|unit}}
page.tables directly. The raw wikitext stays on the page (skim's resolves to 'N unit' (PR-1 unit-loss fix).
infobox surface) and the '== Tables ==' prose block keeps units:
{{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) page = self.fetch(title)
wikitext = self.fetch_wikitext(title) wikitext = self.fetch_wikitext(title)
page.tables = parse_tables(wikitext) page.tables = parse_tables(wikitext)
page.wikitext = wikitext page.wikitext = wikitext
extra = tables_as_text(wikitext)
if extra:
page.text = page.text + "\n\n== Tables ==\n" + extra
return page return page
def disambiguation(self, title: str) -> list[str]: def disambiguation(self, title: str) -> list[str]:
+2 -1
View File
@@ -20,7 +20,7 @@ import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent)) 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.machine import FloopRun, RunReport # noqa: E402
from floop.state import Budget # noqa: E402 from floop.state import Budget # noqa: E402
from floop.stream import RunStreams # noqa: E402 from floop.stream import RunStreams # noqa: E402
@@ -61,6 +61,7 @@ def main() -> None:
lm_info = configure_lm() lm_info = configure_lm()
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs") 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}") streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}")
if baseline: if baseline: