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
+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")