merge main (phase 0: K5 fix, --no-cache, import assert) into research/semantic-kg

Conflict resolutions, the honest way:
- extract/expert gap-step: main's deterministic COMPOSE wins over the
  branch's TRANSLATE LLM (main removed it 23/10 with measurement: the
  model was putting the ANSWER into retrieval queries). The branch's
  _extract_entities contract (question-blind extractor) is fed from
  compose's entities.
- tablefrags/semantic tests: restored the branch's adapted versions +
  fixed their single-insert sys.path bug (parent.parent resolved to
  knowledge/, not code/ — the tests were silently importing MAIN's
  expert.py through the venv pth; same class as the run-085457 trap).
This commit is contained in:
2026-10-25 20:04:47 +01:00
20 changed files with 1705 additions and 97 deletions
+19 -9
View File
@@ -118,8 +118,13 @@ One routed knowledge question = one internal pipeline run, bounded by budget:
```
question instantiate (already done by the machine)
│
▼ TRANSLATE (LLM): question + answer_type → retrieval focus:
│ keywords, entry entities, what shape of fact closes the gap
▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
│ evidence → queries + entity terms. Every token traces to the
│ question or an evidence row; the model's own knowledge of the
│ entities can no longer steer retrieval (it was putting the
│ ANSWER into queries). Top-N asks slice the first N evidence
│ members by source order; enumerations get the list-article
│ shape ('List of rivers of Italy').
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
│ gap report: is the question's answer_type coverable from what's found?
│ YES → skip gather, go to SELECT
@@ -135,10 +140,14 @@ question instantiate (already done by the machine)
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
```
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the
probe, search, chunking, checking, merging, selecting are all engines. That is
the law compliance: the LLM translates; deterministic code decides what is
valid, what is dedupe, what is ranked.
LLM calls: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
composition, probe, search, chunking, checking, merging, selecting are
all engines. That is the law compliance: the LLM translates; deterministic
code decides what is valid, what is dedupe, what is ranked — and since
23/10 even the retrieval focus is code (the old TRANSLATE LLM became
`knowledge/queries.py`: every query token traces to question ∪ evidence,
so no model weight ever steers retrieval).
## 5. Context budget & chunking (the 16–32k constraint)
@@ -307,9 +316,10 @@ against the stored table text — the same string the parser produced — so the
check stays verbatim and deterministic. The wikitext raw form is kept in the
document artifact for audit.
**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM
calls (2 + retries); ingestion and aggregation are free. A 500-row table
costs the same LLM budget as a 5-row one — the cost of an enumeration is
**Budget law in the LIST path.** SELECT TABLE (and the optional VERIFY
COUNT) are the only LLM calls; ingestion and aggregation are free (the
query composition is engine since 23/10). A 500-row table costs the
same LLM budget as a 5-row one — the cost of an enumeration is
O(1) in the size of the list.
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
+63 -43
View File
@@ -1,7 +1,7 @@
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
Per question (one routed knowledge call):
1. TRANSLATE: question -> search queries + resolved entities [LLM, cheap]
1. COMPOSE: question + evidence -> queries/entities (deterministic) [engine]
2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine]
3. gap? -> SEARCH en.wikipedia (official search) [engine]
4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which
@@ -31,14 +31,54 @@ from .chunker import chunk_page
from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, SkimTableSignature,
TranslateSignature, VerifyCountSignature)
VerifyCountSignature)
from .embeddings import EmbedderDown, embed
from .queries import compose_queries, keywords, proper_nouns
from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag)
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
# no citation output field, so the model cites in the only field it has).
# Three live shapes, stripped at the judge's output boundary — BEFORE the
# evidence payload and the ablation audit see the value:
# "... (K5)" — row-id citation suffix
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
# cleans the model's proposal (LLMs propose, code decides — the audit's
# _carries then finds the support rows and the ambiguity audit can run).
_ROW_CITATION_RE = re.compile(
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
re.IGNORECASE)
_ROW_CITED_GLOSS_RE = re.compile(
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
re.IGNORECASE)
_LIST_GLOSS_RE = re.compile(
r"\s*\(\s*list of\b[^()]*\)\s*$",
re.IGNORECASE)
def _clean_value(value: str) -> str:
"""Strip trailing citation/gloss parentheticals from a judge value.
The boundary law: only TRAILING shapes with a citation/list marker are
touched; mid-value text and legitimate parentheticals are the model's
own words and stay. Idempotent by construction (a cleaned value ends
clean). UNKNOWN and empty pass through untouched.
"""
v = (value or "").strip()
if not v or v.upper() == "UNKNOWN":
return v
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
v = rx.sub("", v).rstrip()
return v.strip()
# header/caption terms that name the ENTITY column of a typical scalar table
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
@@ -96,16 +136,10 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
def _proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
question. The definitive guard for 'which are the three longest rivers
of Italy?' never accepting a world table (run H: Q1 answered Nile/
Amazon/Yangtze because the top search hit was the world list and the
disjointness guard was vacuous — no evidence, nothing to check)."""
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
"Their", "Its", "Those", "These", "That", "This"}
return {w for w in words if w not in stops}
"""The subject guard's noun extractor — delegates to knowledge/queries.py
(single source: the query composer and the guards share the NE law).
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
return proper_nouns(question)
@dataclass
@@ -142,7 +176,6 @@ class KnowledgeExpert:
self.streams = streams
self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
self.select_table = dspy.Predict(SelectTableSignature)
self.verify_count = dspy.Predict(VerifyCountSignature)
self.skim_promote = dspy.Predict(SkimPromoteSignature)
@@ -210,16 +243,10 @@ class KnowledgeExpert:
@staticmethod
def _keywords(question: str, k: int = 6) -> list[str]:
"""Deterministic lexical focus: content words of the question (draft)."""
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
words = [w.lower() for w in WORD_RE.findall(question)]
seen: list[str] = []
for w in words:
if w not in stops and len(w) > 2 and w not in seen:
seen.append(w)
return seen[:k]
"""Deterministic lexical focus — delegates to knowledge/queries.py
(single source: the probe seeds and the query composer share the
same keyword law)."""
return keywords(question, k)
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
"""The membership set (if any) this question may be served from.
@@ -271,9 +298,9 @@ class KnowledgeExpert:
question + parent + referenced rows in). References like 'that state'
resolve against them."""
t0 = time.time()
context = (f"Original question: {parent_question}" if parent_question else "")
if evidence:
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
# parent_question/evidence ARE the machine's context (design §4) —
# consumed directly by the probe seeds, the query composer and the
# guards; no prompt ever renders them into a TRANSLATE call anymore.
kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these
@@ -325,23 +352,16 @@ class KnowledgeExpert:
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
# entity-first Wikipedia queries — deterministic keywords alone surface
# list articles and miss demographics pages.
if charge_llm:
charge_llm()
pred = self.translate(question=question, context=context)
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
if not queries:
queries = [" ".join(kws[:3])]
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
# the extractor's entities: TRANSLATE's resolved names + evidence
# entities + (fallback) the question's proper nouns — the
# question-blind extractor transcribes facts about THESE
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
# the model's own knowledge of the entities can no longer steer
# retrieval) + the branch's extract-entities contract: the
# question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode)
self._extract_entities = list(dict.fromkeys(
e for e in (entity_terms + ev_entities
+ sorted(_proper_nouns(question))) if e))
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}",
think=True)
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
# by title relevance; then fetch one at a time with early exit
@@ -1145,7 +1165,7 @@ class KnowledgeExpert:
for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered)
return {
"value": pred.value.strip(),
"value": _clean_value(pred.value),
"quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
and r.quote.strip() in pred.quote.strip()), rows[0].url),
+2 -14
View File
@@ -28,19 +28,6 @@ class Fact(BaseModel):
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
class TranslateSignature(dspy.Signature):
"""You are the TRANSLATE step of a knowledge machine. Turn the question
into Wikipedia search queries AND resolved entity terms. Resolve
references ('that state', 'the same river') using the context: the original
question and the evidence rows already gathered."""
question: str = dspy.InputField()
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
queries: list[str] = dspy.OutputField(
desc="1-2 Wikipedia search queries, most specific first")
entities: list[str] = dspy.OutputField(
desc="the resolved entity names the answer is about")
class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text,
extract facts about the NAMED ENTITIES: biographical facts, positions
@@ -63,7 +50,8 @@ class AnswerFromKG(dspy.Signature):
rows by id. If the rows do not answer it, say UNKNOWN."""
question: str = dspy.InputField()
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
value: str = dspy.OutputField(
desc="the answer, or UNKNOWN — the value ONLY, no row citations, no parenthetical explanations")
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
confidence: Confidence = dspy.OutputField(
desc="high: rows settle it; medium: plausible but partial; low: weak support")
+167
View File
@@ -0,0 +1,167 @@
"""Deterministic query composition — the old TRANSLATE step as fixed code.
His 23/10 weights-tightness call: the TRANSLATE LLM was composing search
queries from its OWN knowledge of the entities — 'Pedro Sánchez 2018
investiture President of the Government of Spain' (the '2018' IS the
answer to that term-start question, steered into retrieval from
weights), 'Po, Adige, Tiber' proposed for a question that named only
Italy. Probed against real Wikipedia over every logged TRANSLATE call of
runs 22-23/10: queries composed from the question's named entities and
keywords (+ the evidence's resolved entities) put the decisive article at
top-1/2 in 8 of 9 cases — the LLM's world knowledge was never the
load-bearing part; the search engine's own relevance was. So the step
becomes code.
Laws:
- Material: question ∪ evidence only. Every token of every query traces
to the question or an evidence row — the weights-tightness law, now
structural instead of prompted.
- Deterministic: same inputs -> same queries, same order, every time.
- Never empty: a question with no NEs still gets its keyword join.
- Top-N over a list row in evidence slices the FIRST N members by source
order (the ranked-list law) — never dumps all members into one query
('Ranked Italy Maira K1 K2' retrieved nothing when a naive composer
tried exactly that).
"""
from __future__ import annotations
import re
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
_CAP_RE = re.compile(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?")
# capitalized words that are question machinery, not subjects
_CAP_STOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
"Their", "Its", "Those", "These", "That", "This"}
# content-word stoplist (single source: probe seeds and composer share it)
_KW_STOPS = {"what", "which", "who", "when", "where", "is", "are", "was",
"were", "the", "of", "in", "on", "at", "a", "an", "and", "or",
"to", "for", "does", "do", "did", "by", "its", "it", "that",
"this", "most", "second"}
_N_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
"seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,
"twelve": 12}
def _caps_in_order(question: str) -> list[str]:
"""Capitalized words in question order, deduped."""
return list(dict.fromkeys(_CAP_RE.findall(question or "")))
def proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
question. The definitive guard for 'which are the three longest rivers
of Italy?' never accepting a world table (run H: Q1 answered Nile/
Amazon/Yangtze because the top search hit was the world list and the
disjointness guard was vacuous — no evidence, nothing to check)."""
return {w for w in _caps_in_order(question) if w not in _CAP_STOPS}
def _subjects(question: str) -> list[str]:
"""NEs in question order. The SENTENCE-INITIAL word is dropped when
other NEs exist: it is capitalized by sentence rules, not because it
names an entity ('During what years…', 'Ranked by length…'). When it
is the ONLY capitalized word it is kept — it may be the subject
('Po length?')."""
ne_set = proper_nouns(question)
nes = [w for w in _caps_in_order(question) if w in ne_set]
first = (question or "").strip().split(" ")[0] if question else ""
if len(nes) > 1 and nes and nes[0] == first:
nes = nes[1:]
return nes
def keywords(question: str, k: int = 6) -> list[str]:
"""Deterministic lexical focus: content words of the question."""
words = [w.lower() for w in WORD_RE.findall(question)]
seen: list[str] = []
for w in words:
if w not in _KW_STOPS and len(w) > 2 and w not in seen:
seen.append(w)
return seen[:k]
def _plural_head(kws: list[str]) -> str:
"""The enumeration's head noun: first plural content word ('rivers',
'countries'). Questions with no plural get no list variant."""
return next((w for w in kws if w.endswith("s") and len(w) > 4), "")
def _top_n(question: str) -> int | None:
"""The N of a top-N ask ('which three of these…', 'top 5 …'), if any.
Only meaningful when the evidence names a list to slice."""
for w in WORD_RE.findall(question.casefold()):
if w in _N_WORDS:
return _N_WORDS[w]
if w.isdigit() and 1 <= int(w) <= 12:
return int(w)
return None
def compose_queries(question: str,
evidence_entities: list[str] | None = None,
list_mode: bool = False) -> tuple[list[str], list[str]]:
"""Wikipedia search queries + entity terms from question ∪ evidence.
Returns (queries, entities), both deterministic. Queries (≤ 2, the
per-gather search cost of the LLM step this replaces):
[0] top-N ask over evidence members -> the FIRST N by source order
('Po Adige Tiber' — the members themselves retrieve their
articles); enumeration with a subject NE -> subject + head
noun ('Italy rivers'); multi-NE -> the join ('Pedro Sanchez
President'); single NE -> NE + salient keywords ('Po length');
no NE but evidence -> the evidence's entities ('that state' +
E1:France -> 'France'); else keyword join
[1] enumeration with exactly ONE subject NE -> the Wikipedia
list-article shape ('List of rivers of Italy'); else the
attribute variant ('Pedro term begin'). A second NE makes the
list shape ambiguous ('List of countries of Union') — skipped.
entities: sliced evidence members (top-N) or question NEs, then the
rest of the evidence entities, question order first.
Every token of every query traces to the question or the evidence.
"""
nes = _subjects(question)
kws = keywords(question)
ev = [e for e in (evidence_entities or []) if e]
ne_lower = {n.casefold() for n in nes}
salient = [w for w in kws if w not in ne_lower]
n_ask = _top_n(question)
queries: list[str] = []
if ev and n_ask:
# top-N over a list row in evidence: the first N members by source
# order carry the query (a ranked list ranks; unranked order is
# still the source's own). Never all members at once.
queries.append(" ".join(ev[:n_ask]))
elif list_mode and nes and (plural := _plural_head(kws)):
queries.append(" ".join(nes[:2] + [plural]))
elif len(nes) >= 2:
queries.append(" ".join(nes[:3]))
elif nes and salient:
queries.append(" ".join([nes[0], *salient[:2]]))
elif nes:
queries.append(nes[0])
elif ev:
queries.append(" ".join(ev[:3]))
elif kws:
queries.append(" ".join(kws[:3]))
else:
queries.append(question.strip()[:60] or "wikipedia")
variant = ""
if list_mode and len(nes) == 1 and (plural := _plural_head(kws)):
variant = f"List of {plural} of {nes[0]}"
if not variant and salient:
base = nes[0] if nes else (ev[0] if ev else "")
if base and base.casefold() not in [q.casefold() for q in queries]:
variant = " ".join([base, *salient[:2]])
if variant and variant not in queries:
queries.append(variant)
entities = list(dict.fromkeys((ev[:n_ask] if ev and n_ask else [])
+ nes + ev))[:8]
return queries[:2], entities
+160
View File
@@ -0,0 +1,160 @@
"""Deterministic query composition (the old TRANSLATE LLM, removed 23/10).
Laws under test (his weights-tightness call):
1. Every token of every query traces to the question or the evidence —
the model's own knowledge of the entities can no longer steer
retrieval. The 22/10 logs caught the LLM putting the ANSWER into
queries ('Pedro Sánchez 2018 investiture…' for a term-start question).
2. Deterministic: same inputs -> same queries, same order, every time.
3. Never empty: a question with no entities still gets its keyword join.
4. Top-N over a list row in evidence slices the FIRST N members by source
order — never dumps all members into one query.
5. The subject NE + plural head noun surface the Wikipedia list article
('List of rivers of Italy'), the source enumerations actually live in.
No network, no LLM. Run: uv run python knowledge/tests/queries.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root
from knowledge.queries import compose_queries, keywords, proper_nouns
def test_single_entity_with_attribute():
q, e = compose_queries("What is the length of Po?")
assert q == ["Po length"], q
assert e == ["Po"], e
print("ok single entity: NE + salient keywords ('Po length')")
def test_multi_entity_join():
q, e = compose_queries("What is the discharge of the Po, Adige and Tiber?")
assert q[0].startswith("Po"), q
assert "Adige" in q[0] and "Tiber" in q[0], q
print("ok multi-NE join:", q)
def test_enumeration_list_variant():
q, e = compose_queries("What are the three longest rivers of Italy?",
list_mode=True)
assert q == ["Italy rivers", "List of rivers of Italy"], q
print("ok enumeration: subject + plural, then the list-article shape")
def test_evidence_entities_carry_reference_resolution():
# 'that state' + E1: France — the evidence resolves the reference,
# not the model's knowledge of anything
q, e = compose_queries("What is the longest river in that state?",
evidence_entities=["France"])
assert q == ["France"], q
assert e == ["France"], e
print("ok reference resolution from evidence, zero weights")
def test_top_n_slices_evidence_by_source_order():
# the case the LLM 'helped' with by guessing Po/Adige/Tiber from its
# weights — the members are now sliced from the evidence row itself
ev = ["Po", "Adige", "Tiber", "Dora", "Reno", "Ticino"]
q, e = compose_queries(
"Ranked by length, which three of these rivers are the longest in Italy?",
evidence_entities=ev)
assert q[0] == "Po Adige Tiber", q
assert e[:3] == ["Po", "Adige", "Tiber"], e
assert len(e) <= 8, e
print("ok top-N ask: first N evidence members by source order")
def test_top_n_never_dumps_all_members():
ev = [f"R{i}" for i in range(22)]
q, e = compose_queries("which three of these rivers are longest?",
evidence_entities=ev)
assert q[0].split() == ["R0", "R1", "R2"], q
print("ok 22-member list: query carries only the sliced 3")
def test_two_subject_ne_gets_no_list_shape():
# 'List of countries of Union' would be garbage — with 2+ NEs the
# list-article shape is skipped
q, e = compose_queries(
"Which countries in the continent of Europe are not members of the European Union?",
list_mode=True)
assert not any(x.startswith("List of") for x in q), q
print("ok two subject NEs: no ambiguous list shape:", q)
def test_no_entities_keyword_join():
q, e = compose_queries("What is the speed of light?")
assert q == ["speed light"], q
assert e == [], e
print("ok no NEs: keyword join, never empty")
def test_sentence_initial_capital_not_a_subject():
# 'During'/'Ranked' are capitalized by sentence rules; with other NEs
# present they must not steer the query
q, e = compose_queries("During what years did Pedro Sanchez serve as President?")
assert q[0].startswith("Pedro"), q
assert "During" not in q[0], q
print("ok sentence-initial capital dropped when other NEs exist:", q)
def test_weights_never_enter_queries():
# the regression the audit found: model knowledge injected into
# retrieval ('2018 investiture', 'Prime Minister of Spain' for a
# question that says neither). Compose the same logged questions and
# assert every query token traces to question ∪ evidence.
cases = [
("When did Pedro Sanchez's term as President begin (the start date of their presidency)?", []),
("Which country's government does Pedro Sanchez lead as President?", []),
("What are the three longest rivers of Italy?", []),
("What is the length of Po?", []),
]
for question, ev in cases:
qs, _ = compose_queries(question, evidence_entities=ev)
material = set(keywords(question)) | {
w.casefold() for w in
__import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", question)} | {
w.casefold() for w in ev}
for query in qs:
for tok in __import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", query):
assert tok.casefold() in material, \
f"untraceable token {tok!r} in {query!r} for {question!r}"
print("ok every query token traces to question ∪ evidence (logged cases)")
def test_deterministic():
args = ("What are the three longest rivers of Italy?", None, True)
r1 = compose_queries(*args)
r2 = compose_queries(*args)
assert r1 == r2
print("ok same inputs -> same outputs")
def test_proper_nouns_unchanged():
# the guards depend on these exact semantics (guards.py contract)
assert proper_nouns("Which are the three longest rivers of Italy?") == {"Italy"}
assert proper_nouns("What is the discharge of the Po, Adige and Tiber?") == {"Po", "Adige", "Tiber"}
assert keywords("Which are the three longest rivers of Italy?") == \
["three", "longest", "rivers", "italy"]
print("ok proper_nouns/keywords semantics unchanged for the guards")
if __name__ == "__main__":
test_single_entity_with_attribute()
test_multi_entity_join()
test_enumeration_list_variant()
test_evidence_entities_carry_reference_resolution()
test_top_n_slices_evidence_by_source_order()
test_top_n_never_dumps_all_members()
test_two_subject_ne_gets_no_list_shape()
test_no_entities_keyword_join()
test_sentence_initial_capital_not_a_subject()
test_weights_never_enter_queries()
test_deterministic()
test_proper_nouns_unchanged()
print("\nqueries tests passed")
+2 -1
View File
@@ -21,7 +21,8 @@ from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
import knowledge.embeddings as emb
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
+2 -1
View File
@@ -6,7 +6,8 @@ from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
parse_stop_table)
+114
View File
@@ -0,0 +1,114 @@
"""Judge value cleanup tests (the (K5) bug, run 085457 / 24-25/10 session).
glm-5.3-flash glues row citations and glosses onto the value field because
AnswerFromKG says "cite rows by id" but has no citation output field. Three
live shapes, verbatim from the runs:
"Socialist International (K5)" — row id
"2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., ...)" — parenthetical gloss
"15 (list of 15 members: 17 november 2023, ...)" — LIST gloss
Laws under test:
1. Trailing citation shapes are STRIPPED from the value, at the judge's
output boundary (_clean_value), BEFORE the payload and the audit see it.
2. Legitimate parentheticals SURVIVE: "(PSOE)" inside a name,
"(Presidente del Gobierno)" inside an office title.
3. A cleaned value lets the ablation audit RUN where the raw value killed
it silently ("the judge invented it: nothing to ablate").
4. The clean is idempotent and does not touch UNKNOWN/empty.
No network. No LLM: the cleaner is fixed code; the tests call it directly
plus one scripted-judge pass through _answer_from_rows.
Run: .venv/bin/python knowledge/tests/value_clean.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.expert import KnowledgeExpert, _clean_value
def test_row_id_suffix_stripped():
assert _clean_value("Socialist International (K5)") == "Socialist International"
assert _clean_value("Rajoy (K12)") == "Rajoy"
print("ok: row-id citation suffix stripped")
def test_cited_from_rows_gloss_stripped():
v = ("2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., "
"President of the Government — since 2018; cited from rows K16 and K30)")
assert _clean_value(v) == "2018", _clean_value(v)
print("ok: 'cited from rows' parenthetical stripped, year kept")
def test_list_gloss_stripped():
v = "15 (list of 15 members: 17 november 2023, 28 november 2023, 24 september 2024)"
assert _clean_value(v) == "15", _clean_value(v)
print("ok: LIST-members gloss stripped, count kept")
def test_legitimate_parentheticals_survive():
assert _clean_value("Spanish Socialist Workers' Party (PSOE)") == \
"Spanish Socialist Workers' Party (PSOE)"
assert _clean_value("Prime Minister of Spain (Presidente del Gobierno)") == \
"Prime Minister of Spain (Presidente del Gobierno)"
# a parenthetical that merely mentions a number is NOT a citation
assert _clean_value("Prime Minister of Spain (since 2018)") == \
"Prime Minister of Spain (since 2018)"
print("ok: legitimate parentheticals untouched")
def test_unknown_and_empty_untouched():
assert _clean_value("UNKNOWN") == "UNKNOWN"
assert _clean_value("") == ""
assert _clean_value(" Spain ") == "Spain"
print("ok: UNKNOWN/empty/whitespace handled")
def test_idempotent_and_mid_value_citations():
v = _clean_value("Socialist International (K5)")
assert _clean_value(v) == v
# a citation in the MIDDLE is not the live bug shape — leave it (no
# aggressive surgery on the judge's sentence), the boundary law strips
# only the TRAILING gloss
assert _clean_value("Per (K2) the answer is Spain") == \
"Per (K2) the answer is Spain"
print("ok: idempotent; mid-value text untouched (boundary law: trailing only)")
def test_answer_from_rows_boundary():
"""The hook: _answer_from_rows cleans pred.value before the payload is
built. Scripted dspy-style Predict object; no network."""
e = KnowledgeExpert.__new__(KnowledgeExpert)
e.cfg = __import__("knowledge.expert", fromlist=["KnowledgeConfig"]).KnowledgeConfig()
e._log = lambda *a, **k: None
class Pred:
value = "Socialist International (K5)"
quote = "ninth president of Socialist International since 2022"
class confidence:
value = "high"
class Row:
src = rel = dst = quote = url = "u"
conflict = False
e.answer = lambda question, rows: Pred()
out = e._answer_from_rows("which office?", [Row()])
assert out["value"] == "Socialist International", out["value"]
print("ok: _answer_from_rows boundary cleans the value")
if __name__ == "__main__":
test_row_id_suffix_stripped()
test_cited_from_rows_gloss_stripped()
test_list_gloss_stripped()
test_legitimate_parentheticals_survive()
test_unknown_and_empty_untouched()
test_idempotent_and_mid_value_citations()
test_answer_from_rows_boundary()
print("\nvalue_clean: 7/7 ok")