knowledge: remove the TRANSLATE LLM — deterministic query composition

His 23/10 weights-tightness audit found the TRANSLATE step composing
search queries from its own knowledge of the entities: 'Pedro Sánchez
2018 investiture President of the Government of Spain' for a term-start
question (the '2018' IS the answer, steered into retrieval from weights),
'Po, Adige, Tiber' proposed as entities for a question that named only
Italy. Measured over every logged TRANSLATE call of runs 22-23/10: 5/10
calls carried untraceable query terms, 6/10 untraceable entity terms.

Probed against real Wikipedia before deciding: queries composed
deterministically from question ∪ evidence put the decisive article at
top-1/2 of the search in 8 of 9 cases — the LLM's world knowledge was
never load-bearing; the search engine's own relevance was. So the step
becomes code (the law: LLMs translate, fixed code composes — and here
nothing is left to translate).

- NEW knowledge/queries.py: compose_queries() + proper_nouns/keywords
  (moved here, single source — the expert delegates). Laws: every query
  token traces to the question or an evidence row; deterministic; never
  empty. Top-N asks slice the FIRST N evidence members by source order
  (never dump all members); enumerations with one subject NE get the
  list-article shape ('List of rivers of Italy'); sentence-initial
  capitals are dropped when other NEs exist ('During', 'Ranked').
- DELETED TranslateSignature + the Predict + the stage map entry;
  the gather charges one LLM call less.
- expert.py: COMPOSE at the gather head; the context var (rendered
  only for the dead prompt) removed — evidence feeds the probe seeds,
  the composer and the guards directly.
- Tests: knowledge/tests/queries.py (12) — the sonde's cases as the
  contract, incl. the traceback law over the logged questions.
- DESIGN.md §4 + code/README honest map updated.

Suite 17/17. Live probe (real Wikipedia): rivers/Pedro/France/Po all
fetch the decisive article at top-1.
This commit is contained in:
2026-10-23 15:15:02 +02:00
parent 30d0a48f7a
commit dec1fccb53
7 changed files with 370 additions and 62 deletions
+1 -1
View File
@@ -48,7 +48,7 @@ Compare: `--baseline` vs the loop's many small directed calls.
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` | | MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` | | ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` | | Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> TRANSLATE (queries+entities from context) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` | | **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` | | Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` | | Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
| `user` expert | not wired — explicit failure row | `floop/engine.py` | | `user` expert | not wired — explicit failure row | `floop/engine.py` |
-1
View File
@@ -165,7 +165,6 @@ _STAGE_BY_MODULE = {
"AnswerSignature": "ANSWER", "AnswerSignature": "ANSWER",
"ExtractSignature": "EXTRACT", "ExtractSignature": "EXTRACT",
"AnswerFromKG": "answer_kg", "AnswerFromKG": "answer_kg",
"TranslateSignature": "TRANSLATE",
"SelectTableSignature": "SELECT_TABLE", "SelectTableSignature": "SELECT_TABLE",
"VerifyCountSignature": "VERIFY_COUNT", "VerifyCountSignature": "VERIFY_COUNT",
"SkimPromoteSignature": "PROMOTE", "SkimPromoteSignature": "PROMOTE",
+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) question instantiate (already done by the machine)
│ │
▼ TRANSLATE (LLM): question + answer_type → retrieval focus: ▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
│ keywords, entry entities, what shape of fact closes the gap │ 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 ▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
│ gap report: is the question's answer_type coverable from what's found? │ gap report: is the question's answer_type coverable from what's found?
│ YES → skip gather, go to SELECT │ 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} ▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
``` ```
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the LLM calls: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
probe, search, chunking, checking, merging, selecting are all engines. That is COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
the law compliance: the LLM translates; deterministic code decides what is composition, probe, search, chunking, checking, merging, selecting are
valid, what is dedupe, what is ranked. 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) ## 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 check stays verbatim and deterministic. The wikitext raw form is kept in the
document artifact for audit. document artifact for audit.
**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM **Budget law in the LIST path.** SELECT TABLE (and the optional VERIFY
calls (2 + retries); ingestion and aggregation are free. A 500-row table COUNT) are the only LLM calls; ingestion and aggregation are free (the
costs the same LLM budget as a 5-row one — the cost of an enumeration is 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. O(1) in the size of the list.
## 12. Answer-level verification — the CHECK step for answers (2026-10-19) ## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
+23 -38
View File
@@ -1,7 +1,7 @@
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked. """The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
Per question (one routed knowledge call): Per question (one routed knowledge call):
1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap] 1. COMPOSE: question + evidence -> queries/entities [engine]
2. KG PROBE: lexical seed match + BFS depth-1 [engine] 2. KG PROBE: lexical seed match + BFS depth-1 [engine]
3. gap? -> SEARCH en.wikipedia (official search) [engine] 3. gap? -> SEARCH en.wikipedia (official search) [engine]
4. FETCH top articles, CHUNK by sections [engine] 4. FETCH top articles, CHUNK by sections [engine]
@@ -25,8 +25,8 @@ from .checks import check_candidate, quote_containment
from .chunker import chunk_page from .chunker import chunk_page
from .skim import find_quantities, skim_article from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature, from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, TranslateSignature, SkimPromoteSignature, VerifyCountSignature)
VerifyCountSignature) from .queries import compose_queries, keywords, proper_nouns
from .store import KnowledgeStore, norm_name 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) tables_as_chunks, format_table_frag, parse_stop_table)
@@ -90,16 +90,10 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
def _proper_nouns(question: str) -> set[str]: def _proper_nouns(question: str) -> set[str]:
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the """The subject guard's noun extractor — delegates to knowledge/queries.py
question. The definitive guard for 'which are the three longest rivers (single source: the query composer and the guards share the NE law).
of Italy?' never accepting a world table (run H: Q1 answered Nile/ Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
Amazon/Yangtze because the top search hit was the world list and the return proper_nouns(question)
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}
@dataclass @dataclass
@@ -130,7 +124,6 @@ class KnowledgeExpert:
self.streams = streams self.streams = streams
self.extract = dspy.Predict(ExtractSignature) self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG) self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
self.select_table = dspy.Predict(SelectTableSignature) self.select_table = dspy.Predict(SelectTableSignature)
self.verify_count = dspy.Predict(VerifyCountSignature) self.verify_count = dspy.Predict(VerifyCountSignature)
self.skim_promote = dspy.Predict(SkimPromoteSignature) self.skim_promote = dspy.Predict(SkimPromoteSignature)
@@ -150,16 +143,10 @@ class KnowledgeExpert:
@staticmethod @staticmethod
def _keywords(question: str, k: int = 6) -> list[str]: def _keywords(question: str, k: int = 6) -> list[str]:
"""Deterministic lexical focus: content words of the question (draft).""" """Deterministic lexical focus — delegates to knowledge/queries.py
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were", (single source: the probe seeds and the query composer share the
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for", same keyword law)."""
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"} return keywords(question, k)
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]
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None: def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
"""The membership set (if any) this question may be served from. """The membership set (if any) this question may be served from.
@@ -211,9 +198,9 @@ class KnowledgeExpert:
question + parent + referenced rows in). References like 'that state' question + parent + referenced rows in). References like 'that state'
resolve against them.""" resolve against them."""
t0 = time.time() t0 = time.time()
context = (f"Original question: {parent_question}" if parent_question else "") # parent_question/evidence ARE the machine's context (design §4) —
if evidence: # consumed directly by the probe seeds, the query composer and the
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}" # guards; no prompt ever renders them into a TRANSLATE call anymore.
kws = self._keywords(question) kws = self._keywords(question)
goal_terms = self._keywords(parent_question) if parent_question else [] goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_terms = goal_terms # the harvest reads these
@@ -263,17 +250,15 @@ class KnowledgeExpert:
return {**self._audit_ambiguity(question, answer, rows, charge_llm), return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)} "source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes # 3-4. gap -> search + fetch. COMPOSE (deterministic — the old
# entity-first Wikipedia queries — deterministic keywords alone surface # TRANSLATE LLM, 23/10): queries from question ∪ evidence only;
# list articles and miss demographics pages. # the model's own knowledge of the entities can no longer steer
if charge_llm: # retrieval (it was putting the ANSWER into queries: 'Pedro
charge_llm() # Sánchez 2018 investiture…' for a term-start question).
pred = self.translate(question=question, context=context) queries, entity_terms = compose_queries(
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2] question, evidence_entities=ev_entities, list_mode=list_mode)
if not queries: self._log(f"compose -> queries {queries} entities {entity_terms}",
queries = [" ".join(kws[:3])] think=True)
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY # search ALL queries first; merge + dedupe candidates; rank GLOBALLY
# by title relevance; then fetch one at a time with early exit # by title relevance; then fetch one at a time with early exit
-13
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)") 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): class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text, """You are the EXTRACT step of a knowledge machine. From the given text,
extract the facts that help answer the question. Each fact carries its extract the facts that help answer the question. Each fact carries its
+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")