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
+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")