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