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:
@@ -28,7 +28,8 @@ from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature, parse_facts)
|
||||
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']+")
|
||||
|
||||
@@ -760,8 +761,24 @@ class KnowledgeExpert:
|
||||
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)", 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:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
@@ -778,6 +795,54 @@ 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 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
|
||||
|
||||
def _gate(self, chunk, keywords: list[str]) -> bool:
|
||||
|
||||
Reference in New Issue
Block a user