Files
floop/code/knowledge/tests/tablefrags.py
T
onibot 872d4b9d42 research(knowledge): semantic KG retrieval + question-blind extraction
Implements his design (RESEARCH-semantic-kg.md) on the research branch:

1. EMBEDDINGS (knowledge/embeddings.py): local ollama /api/embed,
   nomic-embed-text 768d — the only proven endpoint (ollama.com has
   NO embeddings API). Honest failure: EmbedderDown -> lexical probe
   fallback, never a dead run.

2. SEMANTIC PROBE: edge_vectors cache in the store (keyed edge_id +
   model + text_hash; upsert, last model wins), cosine rank over all
   cached edges, tau=0.45 from real calibration (rivers 0.49-0.52 must
   pass; cross-question Pedro-vs-rivers 0.35-0.38 must not). Hybrid
   _probe: lexical UNION semantic, dedup by eid. EdgeView gains eid.

3. QUESTION-BLIND EXTRACTION: ExtractSignature loses 'question' and
   stop_table — it receives ENTITIES only (from TRANSLATE + evidence
   + proper nouns) and transcribes their facts, capped per chunk
   (max_facts_per_chunk=12). Facts cache vectors at ingest. The KG
   fattens per-entity, reusable across questions (his cacheability
   argument).

4. STOP MOVES TO THE SKIM: SkimTableSignature decides per table from
   caption+header+row count+first rows (one LLM call per page) BEFORE
   any extraction spend; tables that literally name an entity skip the
   call. The extractor itself never judges relevance.

VERIFIED: knowledge suite 8/8 (semantic.py new 4/4: lexical-missed edge
surfaced, hybrid dedup, embedder-down degradation, cache upsert;
tablefrags adapted: skim kills tables pre-extract). floop suite 9/9.
Live E2E (glm): semantic probe fires live (+1 lexical-missed edge);
blind extractor ingests 12-fact chunks; Pedro run answers 'himself'
(3rd gov succeeded his 2nd — a reading trap, NOT a retrieval failure;
INIT degraded honestly on garbage); rivers run burned budget on
fan-out ROUTE calls (22x2) — both findings logged as open work on the
research doc, not regressions of this PR.
2026-10-23 08:44:36 +02:00

202 lines
7.9 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 = []
e._extract_entities = []
e._embed_ok = True
e._qvec_cache = {}
return e
def test_process_page_fragments():
"""The extract path over table fragments: no-signal frags skip free,
the TABLE SKIM (question-aware, pre-extraction) kills hopeless tables
BEFORE any extract spend, 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 TABLE SKIM: world table not relevant; Italy table relevant
class Decision:
def __init__(self, idx, relevant, reason=""):
self.table_index = idx
self.relevant = relevant
self.reason = reason
class SkimOut:
def __init__(self, decisions):
self.decisions = decisions
e.skim_tables = lambda question, entities, tables: SkimOut([
Decision(1, False, "world rivers, not Italy"),
Decision(2, True, "rivers of Italy with flow"),
])
# scripted extractor: facts for whichever table the skim lets through
calls = []
class FakeOut:
def __init__(self, facts):
self.facts = facts
def fake_extract(entities, heading, text, _calls=calls):
_calls.append((entities, heading, text))
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?")
e._extract_entities = ["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
# the skim must have killed the world table BEFORE extraction: zero
# extract calls touch it (parts 1-3 all skipped, zero spend)
world_calls = [c for c in calls if "World rivers" in c[2]]
assert len(world_calls) == 0, f"skim did not kill table 1 pre-extract: {len(world_calls)} calls"
print("ok: table skim kills hopeless tables pre-extract; surviving frags 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")