knowledge: deterministic ambiguity audit for office questions (run J)

Run J answered 'What office is Pedro Sanchez associated with as
President?' with Socialist International — a literally defensible
reading, but the KG ALSO held prime minister of Spain and
secretary-general of PSOE, and the machine never learned they existed.
The fix is not prompt tuning: it is a data type the pipeline could not
express — 'this answer is one of several defensible readings'.

Layer 1 (this PR) — knowledge/ambiguity.py, zero LLM, zero network:
- GATE: role_in_text(question) — only questions naming an office-class
  role (president, prime minister, secretary general, chancellor, ...)
  enter the audit. 'second most populated country in European Union'
  and 'three longest rivers in Italy' never even run it.
- ref_entity: the question's proper-noun run, broken at lowercase words
  and role words — 'Pedro Sanchez' (not 'President'), 'France' in
  'Who is the President of France?'.
- audit_role_multiplicity: rows about the entity whose role lives in
  the relation OR the object (extraction shape varies); dates and bare
  numbers never become alternatives; same office in two shapes merges
  by token containment (quote kept, corroboration summed); the PICKED
  reading is excluded from the report. Fires only at >= 2 alternatives.
- _maybe_ambig wires the audit at the three scalar return paths of
  answer_question; a clean answer is byte-identical (gate is cheap and
  the single-reading path changes nothing).

Propagation up (flag, never choose):
- payload carries {ambiguous, axis, alternatives[{value, role, quote,
  url}]}; provenance note says the choice among readings is NOT
  verified.
- OUTPUT EXPERT line: 'Q1 -> ANSWER value=... AMBIGUOUS ([prime
  minister] Spain; [secretary-general] PSOE) quote=...'.
- machine: run notes carry the axis + other readings; the evidence
  render shows them so the ANSWER step (and later the user) can decide.

Tests: knowledge/tests/ambiguity.py — the two agreed positives (both
Pedro phrasings), the two agreed counterexamples (silent), single
office, dates-as-values, duplicate shapes, role-in-object, wiring
(expert flags + clean untouched), engine log/payload/provenance,
machine notes/render. Suite 70/70. Live smoke: the full pipeline over
a run-J-shaped page flags the 3 offices; the rivers question over the
same KG stays silent.
This commit is contained in:
2026-10-21 17:42:24 +02:00
parent 4506b4067a
commit a43d827098
5 changed files with 531 additions and 6 deletions
+32 -3
View File
@@ -27,6 +27,7 @@ from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
SkimPromoteSignature, TranslateSignature,
VerifyCountSignature, parse_facts)
from .ambiguity import audit_role_multiplicity, ref_entity, role_in_text
from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag, parse_stop_table)
@@ -259,7 +260,8 @@ class KnowledgeExpert:
answer = self._answer_from_rows(question, rows, charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"kg hit: {answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
return {**self._maybe_ambig(question, answer),
"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
@@ -393,7 +395,8 @@ class KnowledgeExpert:
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"early exit after {page.title}: "
f"{answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph",
return {**self._maybe_ambig(question, answer),
"source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
@@ -405,7 +408,7 @@ class KnowledgeExpert:
self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True)
answer = self._answer_from_rows(question, rows, charge_llm)
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
return {**answer, "source": src,
return {**self._maybe_ambig(question, answer), "source": src,
"stats": {**self._skim_stats(pages),
"checked": self._checked, "merged": self._merged,
"skim": self._skim_notices,
@@ -477,6 +480,32 @@ class KnowledgeExpert:
and w not in ("states?", "does", "was", "has")]
return bool(words & ask) and len(plurals) >= 1
def _maybe_ambig(self, question: str, answer: dict) -> dict:
"""Layer-1 ambiguity audit (KNOWLEDGE.md §8): after a scalar answer,
check the KG for OTHER office-class readings of the same question
(run J: 'president of Pedro Sanchez' legitimately resolved to
Socialist International while the KG also held prime minister of
Spain and secretary-general of PSOE). Zero LLM, zero network —
rows the KG already holds. Flags the answer; never chooses."""
if (not answer.get("value")
or str(answer["value"]).upper() == "UNKNOWN"):
return answer
if not role_in_text(question):
return answer # ordinary question: audit stays quiet
ent = ref_entity(question)
if not ent:
return answer
rows = self.store.probe([ent] + ent.split())
audit = audit_role_multiplicity(question, rows, answer["value"])
if not audit:
return answer # single reading: byte-identical answer
self._log(f"ambiguity audit: {len(audit['alternatives'])} other "
f"office readings for {ent!r} ({'; '.join(
a['value'] for a in audit['alternatives'][:3])}) — "
f"flagging, not choosing", think=True)
return {**answer, "ambiguous": True, "axis": audit["axis"],
"alternatives": audit["alternatives"]}
def _verify_count(self, set_name: str, count: int, prose: str,
charge_llm) -> dict | None:
"""Answer-level CHECK: corroborate the list COUNT from article prose