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
+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)
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,63 @@ 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:
"""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",
@@ -324,18 +383,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. The raw wikitext stays on the page (skim's
infobox surface) and the '== Tables ==' prose block keeps units:
{{convert|N|unit}} resolves to 'N unit' (PR-1 unit-loss fix)."""
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)
page.wikitext = wikitext
extra = tables_as_text(wikitext)
if extra:
page.text = page.text + "\n\n== Tables ==\n" + extra
return page
def disambiguation(self, title: str) -> list[str]: