feat: two-pass EXTRACT (claims -> typed Facts) for prose chunks
His diagnosis accepted (26/10): the single-pass EXTRACT's giant typed JSON array (verbatim quotes + temporal restrictions + sibling orders) is the output budget behind the 40-minute arithmetic on slow local models. Two-pass shortens EVERY output: - Pass 1 ExtractClaims: plain claim strings, coreferences resolved (entities named, never pronouns) — near-zero format tax. - Pass 2 TypeClaim: ONE claim -> one typed Fact per call (same Fact schema the store eats; temporal fields optional, containment-checked downstream as always). Orders NEVER produced here: one claim at a time has no siblings — the legacy Fact keeps orders for the single-pass path and table frags, untouched. - extract_mode: two_pass (default) | single (legacy) — config-driven, read from config.yaml's knowledge block by run_app. - Budget: Pass 1 charges once per chunk; Pass 2 charges once per claim. Table frags keep the legacy single-pass call. - Prompt log: CLAIMS/TYPE stage labels added. TDD: two_pass_extract 5/5 (signatures, coref law, honest empties) + two_pass_wiring 2/2 (end-to-end on a real store: two_pass ingests typed facts with windows kept; single-pass control green). Suite: 29 test files green. The router from #26 makes the upcoming extraction-model swap a pure config edit.
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
"""The two-pass pipeline wiring test: prose chunks flow claims->facts->store.
|
||||
|
||||
End-to-end on a REAL store (tmp kg.sqlite): _process_page in two_pass
|
||||
mode ingests the typed facts from Pass 2 exactly as the legacy path
|
||||
did — same _ingest_candidate, same containment checks, same merge; the
|
||||
single-pass path keeps working (control). No network: the expert's
|
||||
claims/typeclaim/extract modules are scripted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.extract import Fact
|
||||
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.wiki import WikiPage
|
||||
|
||||
|
||||
PAGE_TEXT = (
|
||||
"Pedro Sanchez is a Spanish politician who has been the prime "
|
||||
"minister of Spain since 2018. He is also Secretary-General of the "
|
||||
"Spanish Socialist Workers' Party (PSOE) since 2017."
|
||||
)
|
||||
|
||||
|
||||
def make_page() -> WikiPage:
|
||||
return WikiPage(title="Pedro Sanchez", pageid=1,
|
||||
url="https://en.wikipedia.org/wiki/P",
|
||||
fetched_at="2026-10-26", text=PAGE_TEXT, tables=[])
|
||||
|
||||
|
||||
class ScriptedClaims:
|
||||
def __call__(self, **kw):
|
||||
class Out:
|
||||
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
|
||||
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
|
||||
return Out()
|
||||
|
||||
|
||||
class ScriptedTypeClaim:
|
||||
def __init__(self, facts):
|
||||
self.facts = facts
|
||||
self.i = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
f = self.facts[self.i]
|
||||
self.i += 1
|
||||
class Out:
|
||||
fact = f
|
||||
return Out()
|
||||
|
||||
|
||||
def test_two_pass_ingests_typed_facts():
|
||||
tmp = tempfile.mkdtemp()
|
||||
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
|
||||
e = KnowledgeExpert(config=KnowledgeConfig(
|
||||
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="two_pass"),
|
||||
store=store)
|
||||
e.claims = ScriptedClaims()
|
||||
e.typeclaim = ScriptedTypeClaim([
|
||||
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
||||
object="Spain",
|
||||
quote="has been the prime minister of Spain since 2018",
|
||||
start="2018", end=None, point=None, granularity="year"),
|
||||
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
||||
object="PSOE",
|
||||
quote="Secretary-General of the Spanish Socialist Workers' "
|
||||
"Party (PSOE) since 2017",
|
||||
start="2017", end=None, point=None, granularity="year"),
|
||||
])
|
||||
# per-call state that answer_question initializes (the wiring test
|
||||
# drives _process_page directly)
|
||||
e._extract_entities = []
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = "the question"
|
||||
n = e._process_page(make_page(), "the question", kws=["pedro", "prime"],
|
||||
charge_llm=None, goal_terms=[])
|
||||
assert n >= 2, f"two_pass should merge both facts (merged={n})"
|
||||
rows = store.db.execute(
|
||||
"SELECT n.norm_name, e.rel, e.dst_value, e.t_start FROM edges e "
|
||||
"JOIN nodes n ON n.id=e.src_node "
|
||||
"WHERE n.norm_name='pedro sanchez' ORDER BY e.id").fetchall()
|
||||
assert len(rows) == 2, rows
|
||||
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
|
||||
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
|
||||
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
|
||||
|
||||
|
||||
def test_single_pass_still_works():
|
||||
"""Control: extract_mode='single' -> the legacy one-call path."""
|
||||
tmp = tempfile.mkdtemp()
|
||||
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
|
||||
e = KnowledgeExpert(config=KnowledgeConfig(
|
||||
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="single"),
|
||||
store=store)
|
||||
from knowledge.extract import Fact
|
||||
|
||||
class ScriptedExtract:
|
||||
def __call__(self, **kw):
|
||||
class Out:
|
||||
facts = [Fact(subject="Pedro Sanchez",
|
||||
relation="prime minister of", object="Spain",
|
||||
quote="has been the prime minister of Spain "
|
||||
"since 2018",
|
||||
start="2018", end=None, point=None,
|
||||
granularity="year")]
|
||||
return Out()
|
||||
|
||||
e.extract = ScriptedExtract()
|
||||
e._extract_entities = []
|
||||
e._current_goal_terms = []
|
||||
e._current_goal_question = "the question"
|
||||
n = e._process_page(make_page(), "the question", kws=["pedro"],
|
||||
charge_llm=None, goal_terms=[])
|
||||
assert n >= 1, n
|
||||
rows = store.db.execute(
|
||||
"SELECT COUNT(*) FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||
"WHERE n.norm_name='pedro sanchez'"
|
||||
).fetchone()[0]
|
||||
assert rows == 1, rows
|
||||
print("ok: single-pass legacy path untouched (control)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_two_pass_ingests_typed_facts()
|
||||
test_single_pass_still_works()
|
||||
print("\ntwo_pass_wiring: 2/2 ok")
|
||||
Reference in New Issue
Block a user