The field's purpose was unclear from its name; stop_table says what it stops. Renamed across the signature, its desc/docstring, the caller (raw.stop_table), the wiki.py legacy note, and the test fakes.
184 lines
7.4 KiB
Python
184 lines
7.4 KiB
Python
"""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_table=True; Italy table -> one Fact
|
|
calls = []
|
|
|
|
class FakeOut:
|
|
def __init__(self, facts, stop_table=False):
|
|
self.facts = facts
|
|
self.stop_table = stop_table
|
|
|
|
def fake_extract(question, heading, text, _calls=calls):
|
|
_calls.append((question, heading, text))
|
|
if "World rivers" in text:
|
|
return FakeOut([], stop_table=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") |