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:
+19
-2
@@ -130,6 +130,12 @@ class KnowledgeEngine:
|
||||
src = ans.get("source", "wikipedia_miss")
|
||||
value = ans.get("value", "UNKNOWN")
|
||||
payload = {"value": value}
|
||||
# Layer-1 ambiguity flag (run J): the answer is ONE defensible
|
||||
# reading; the payload carries the others for the layers above
|
||||
if ans.get("ambiguous"):
|
||||
payload["ambiguous"] = True
|
||||
payload["axis"] = ans.get("axis", "")
|
||||
payload["alternatives"] = ans.get("alternatives", [])
|
||||
if ans.get("quote"):
|
||||
payload["quote"] = ans["quote"]
|
||||
if ans.get("url"):
|
||||
@@ -147,8 +153,11 @@ class KnowledgeEngine:
|
||||
if skim_notices:
|
||||
payload["skim"] = skim_notices[:3]
|
||||
prov = {"expert": "knowledge", "source": src,
|
||||
"note": ("source-verified: verbatim containment in trusted doc"
|
||||
if ans.get("quote") else "no quote — unverified")}
|
||||
"note": ("ambiguous: several office readings exist — the "
|
||||
"choice among them is not verified"
|
||||
if ans.get("ambiguous") else
|
||||
("source-verified: verbatim containment in trusted doc"
|
||||
if ans.get("quote") else "no quote — unverified"))}
|
||||
# LIST rows: the answer-level check corroborates the count outside the
|
||||
# source table; combined with per-source completeness it makes the
|
||||
# row verified (E3-style verified semantics, first non-stub use).
|
||||
@@ -174,6 +183,14 @@ class KnowledgeEngine:
|
||||
f"{len(items)} members: {shown}) quote="
|
||||
f"{(ans.get('quote') or '')[:60]} url="
|
||||
f"{ans.get('url') or ''} [{src}]")
|
||||
elif ans.get("ambiguous"):
|
||||
alts = "; ".join(f"[{a.get('role')}] {a.get('value')}"
|
||||
for a in (ans.get("alternatives") or [])[:3])
|
||||
streams.output("EXPERT",
|
||||
f"{qref} -> ANSWER value={value} "
|
||||
f"AMBIGUOUS ({alts}) quote="
|
||||
f"{(ans.get('quote') or '')[:60]} url="
|
||||
f"{ans.get('url') or ''} [{src}]")
|
||||
else:
|
||||
streams.output("EXPERT",
|
||||
f"{qref} -> ANSWER value={value} quote="
|
||||
|
||||
+16
-1
@@ -451,6 +451,14 @@ class FloopRun:
|
||||
# derived answers render CONTENT, not counts alone
|
||||
for n in (row.payload.get("skim") or [])[:2]:
|
||||
self.notes.append(f"{q.qid}: skim: {n[:150]}")
|
||||
# Layer-1 ambiguity audit (run J): the expert flagged several office
|
||||
# readings — the report must carry them, the machine must not choose
|
||||
if row.payload.get("ambiguous"):
|
||||
alts = row.payload.get("alternatives") or []
|
||||
self.notes.append(
|
||||
f"{q.qid}: AMBIGUOUS: {row.payload.get('axis')} — "
|
||||
f"other readings: " + "; ".join(
|
||||
f"{a.get('value')} ({a.get('role')})" for a in alts[:3]))
|
||||
self.table.append(row)
|
||||
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
||||
q.status = "failed"
|
||||
@@ -468,7 +476,14 @@ class FloopRun:
|
||||
if isinstance(r.payload.get("list_items"), list):
|
||||
return (f"list of {r.payload['list_count']} items: "
|
||||
f"{', '.join(r.payload['list_items'][:8])}...")
|
||||
return str(r.payload.get("value", r.payload.get("quote", "")))
|
||||
val = str(r.payload.get("value", r.payload.get("quote", "")))
|
||||
if r.payload.get("ambiguous"):
|
||||
alts = r.payload.get("alternatives") or []
|
||||
other = "; ".join(f"{a.get('value')} ({a.get('role')})"
|
||||
for a in alts[:3])
|
||||
return (f"{val} — AMBIGUOUS, other defensible readings: "
|
||||
f"{other}")
|
||||
return val
|
||||
|
||||
lines = []
|
||||
notices = []
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Deterministic ambiguity audit for attribute-of-entity answers (layer 1).
|
||||
|
||||
Run J taught the shape: 'What office is Pedro Sánchez associated with as
|
||||
President?' has THREE defensible readings in the KG (prime minister of
|
||||
Spain, secretary-general of PSOE, president of Socialist International);
|
||||
the answer step picked one literally and the machine never learned the
|
||||
other two existed. The fix is not prompt tuning — it is a data type the
|
||||
pipeline could not express: 'this answer is one of several'.
|
||||
|
||||
LAW: the audit runs AFTER a value is picked, over rows the KG already
|
||||
holds, zero LLM, zero network. The single-candidate path stays
|
||||
byte-identical: an audit that flags nothing changes nothing.
|
||||
|
||||
LAW: a role word in the question gates the whole audit. 'as President'
|
||||
-> office-class roles; a question about population or river length
|
||||
never enters the audit (no ambiguity detection everywhere — the audit
|
||||
must stay quiet on ordinary questions).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .store import norm_name
|
||||
|
||||
_WORD = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
|
||||
|
||||
def _toks(text: str) -> set[str]:
|
||||
return {w.casefold() for w in _WORD.findall(text or "")}
|
||||
|
||||
|
||||
# curated, closed vocabulary — ROLE WORDS that make a relation an
|
||||
# office/position claim. Multiword entries match as phrases (both
|
||||
# spellings listed); single words match on token boundaries ('chairman'
|
||||
# never matches 'chairmanship' by substring).
|
||||
_ROLE_WORDS = (
|
||||
# head-of-state / head-of-government
|
||||
"president", "prime minister", "premier", "chancellor",
|
||||
# party / organisation leadership
|
||||
"secretary general", "secretary-general", "chairman", "chairperson",
|
||||
"chair", "leader", "secretary",
|
||||
# legislature / local
|
||||
"speaker", "governor", "mayor", "minister",
|
||||
)
|
||||
|
||||
# question words never part of an entity name
|
||||
_QSTOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||
"Their", "Its", "Those", "These", "That", "This"}
|
||||
|
||||
_MONTHS = {"january", "february", "march", "april", "may", "june", "july",
|
||||
"august", "september", "october", "november", "december"}
|
||||
|
||||
|
||||
def role_in_text(text: str) -> str | None:
|
||||
"""The ROLE named in a question, relation or object, if any:
|
||||
'president of the government' -> 'president'; 'population' -> None.
|
||||
Longest phrase wins; single words need a token boundary."""
|
||||
low = (text or "").casefold()
|
||||
for r in sorted(_ROLE_WORDS, key=len, reverse=True):
|
||||
if " " in r:
|
||||
if r in low:
|
||||
return r
|
||||
elif re.search(rf"\b{re.escape(r)}\b", low):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def ref_entity(question: str) -> str | None:
|
||||
"""The entity the question is about: the longest capitalized RUN that
|
||||
is not itself a role phrase. Runs break at any lowercase word, so
|
||||
'What office is Pedro Sanchez associated with as President?' yields
|
||||
runs [Pedro Sanchez] and [President]; the role run is dropped and
|
||||
'Pedro Sanchez' wins. 'Who is the President of France?' -> 'France'."""
|
||||
runs: list[list[str]] = []
|
||||
run: list[str] = []
|
||||
for w in _WORD.findall(question or ""):
|
||||
if w[0].isupper() and w not in _QSTOPS:
|
||||
run.append(w)
|
||||
elif run:
|
||||
runs.append(run)
|
||||
run = []
|
||||
if run:
|
||||
runs.append(run)
|
||||
entity_runs = [r for r in runs if not role_in_text(" ".join(r))]
|
||||
pool = entity_runs or [r for r in runs if len(r) > 1]
|
||||
if not pool:
|
||||
return None
|
||||
return " ".join(max(pool, key=len))
|
||||
|
||||
|
||||
def _is_roleish_value(val: str) -> bool:
|
||||
"""A candidate alternative must NAME something: a bare number, year or
|
||||
date is a quantity row, not an office ('president since' | '2 June
|
||||
2018' must never become an alternative). Month names are dates in
|
||||
disguise."""
|
||||
words = [w.casefold() for w in re.findall(r"[A-Za-zÀ-ÿ]+", val or "")
|
||||
if len(w) >= 3 and w.casefold() not in _MONTHS]
|
||||
return bool(words) and sum(len(w) for w in words) >= 4
|
||||
|
||||
|
||||
def _ent_row_match(ent: str, src: str) -> bool:
|
||||
"""Same-entity law: every entity token present in the row's subject
|
||||
(question names 'pedro sanchez', node says 'pedro sanchez perez
|
||||
castejon'), or the reverse when the node is the shorter form and
|
||||
still >= 2 tokens. Single-token shortcuts never match."""
|
||||
etoks = set(norm_name(ent).split())
|
||||
stoks = set(norm_name(src).split())
|
||||
if not etoks or not stoks:
|
||||
return False
|
||||
if etoks <= stoks:
|
||||
return True
|
||||
return len(stoks) >= 2 and stoks <= etoks
|
||||
|
||||
|
||||
def _merge_alternatives(cands: list[dict]) -> list[dict]:
|
||||
"""Same role + token-containment values = ONE office in two
|
||||
extraction shapes ('prime minister of' | 'Spain' and 'office' |
|
||||
'Prime Minister of Spain'). Keep the longer value — it loses no
|
||||
verbatim information; keep the best quote (verbatim law); sum
|
||||
corroboration."""
|
||||
out: list[dict] = []
|
||||
for a in sorted(cands, key=lambda c: len(c["value"]), reverse=True):
|
||||
merged = False
|
||||
for b in out:
|
||||
if b["role"] != a["role"]:
|
||||
continue
|
||||
at = set(norm_name(a["value"]).split())
|
||||
bt = set(norm_name(b["value"]).split())
|
||||
if at <= bt or bt <= at:
|
||||
b["corroboration"] += a["corroboration"]
|
||||
if a["quote"] and not b["quote"]:
|
||||
b["quote"] = a["quote"]
|
||||
merged = True
|
||||
break
|
||||
if not merged:
|
||||
out.append(dict(a))
|
||||
return out
|
||||
|
||||
|
||||
def audit_role_multiplicity(
|
||||
question: str, rows: list, picked_value: str,
|
||||
max_alternatives: int = 5) -> dict | None:
|
||||
"""Layer-1 audit: does the KG hold MORE THAN ONE office-class role for
|
||||
the question's entity? Returns None when there is nothing to report
|
||||
(no role word in the question, no entity, single office) — the
|
||||
caller's answer stays exactly as it was.
|
||||
|
||||
When it fires, returns {"axis": ..., "alternatives": [...]} where
|
||||
each alternative is {value, role, quote, url} — every field verbatim
|
||||
from the KG, no inference. The PICKED reading is not repeated among
|
||||
the alternatives: the report says the OTHER defensible readings."""
|
||||
# GATE 1: the question must name a role ('as President', 'which
|
||||
# office ... as premier'). Population/length questions never enter.
|
||||
q_role = role_in_text(question)
|
||||
if not q_role:
|
||||
return None
|
||||
|
||||
# GATE 2: an entity to audit. No entity -> nothing to compare.
|
||||
ent = ref_entity(question)
|
||||
if not ent:
|
||||
return None
|
||||
|
||||
# GATE 3: only rows ABOUT the entity, only office-class roles. The
|
||||
# role may live in the relation ('president of' | 'Socialist
|
||||
# International') or in the object ('office' | 'Prime Minister of
|
||||
# Spain') — extraction shape varies, the audit must not care.
|
||||
by_key: dict[tuple[str, str], dict] = {}
|
||||
for r in rows:
|
||||
if not _ent_row_match(ent, r.src or ""):
|
||||
continue
|
||||
role = role_in_text(r.rel) or role_in_text(r.dst)
|
||||
if not role:
|
||||
continue
|
||||
val = (r.dst or "").strip()
|
||||
if (not val or not _is_roleish_value(val)
|
||||
or norm_name(val) == norm_name(ent)
|
||||
or norm_name(val) == norm_name(picked_value or "")):
|
||||
continue
|
||||
key = (role, val)
|
||||
if key not in by_key or r.corroboration > by_key[key]["corroboration"]:
|
||||
by_key[key] = {"value": val, "role": role, "quote": r.quote,
|
||||
"url": r.url, "corroboration": r.corroboration}
|
||||
|
||||
merged = _merge_alternatives(list(by_key.values()))
|
||||
if len(merged) < 2:
|
||||
return None
|
||||
|
||||
alts = sorted(merged, key=lambda c: -c["corroboration"])[:max_alternatives]
|
||||
return {
|
||||
"axis": f"which office does '{q_role}' refer to?",
|
||||
"alternatives": [{"value": c["value"], "role": c["role"],
|
||||
"quote": (c["quote"] or "")[:160], "url": c["url"]}
|
||||
for c in alts]}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Layer-1 ambiguity audit tests (run J) — the two agreed positives, the two
|
||||
agreed counterexamples, and the shape hazards.
|
||||
|
||||
Laws under test:
|
||||
1. The Pedro Sanchez office questions flag: the KG holds 3 office-class
|
||||
readings; the answer carries the other two (the picked one excluded).
|
||||
2. The ordinary questions (EU population, Italy rivers) stay silent —
|
||||
no role word in the question, the audit never even runs.
|
||||
3. Single office, dates-as-values, duplicate shapes: never flagged.
|
||||
4. The wiring: an ambiguous answer surfaces in the EXPERT log line, the
|
||||
evidence render, and the run notes; a clean answer is byte-identical
|
||||
to pre-audit behaviour.
|
||||
|
||||
No network, no real LLM. Run: .venv/bin/python knowledge/tests/ambiguity.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.ambiguity import (audit_role_multiplicity, ref_entity,
|
||||
role_in_text)
|
||||
|
||||
Q_PEDRO_SUB = ("What country or political office is Pedro Sanchez "
|
||||
"associated with as President?")
|
||||
Q_PEDRO = "What office is Pedro Sanchez associated with as President?"
|
||||
Q_EU = "What is the second most populated country in European Union?"
|
||||
Q_RIVERS = "Which are the three longest rivers in Italy?"
|
||||
|
||||
|
||||
class R:
|
||||
"""EdgeView stand-in — same field names as store.probe() returns."""
|
||||
|
||||
def __init__(self, src, rel, dst, quote="", url="", corroboration=1):
|
||||
self.src, self.rel, self.dst = src, rel, dst
|
||||
self.quote, self.url = quote, url
|
||||
self.corroboration = corroboration
|
||||
|
||||
|
||||
def run_j_rows():
|
||||
"""The run-J KG: three office readings for Pedro Sánchez + noise."""
|
||||
return [
|
||||
R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain",
|
||||
quote="he has been the prime minister of Spain since 2018"),
|
||||
R("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE",
|
||||
quote="Secretary-General of the party since 2017"),
|
||||
R("Pedro Sánchez",
|
||||
"president of Socialist International since 2022",
|
||||
"Socialist International",
|
||||
quote="ninth president of Socialist International since 2022"),
|
||||
R("Pedro Sánchez", "office", "Prime Minister of Spain"),
|
||||
R("Pedro Sánchez", "term start", "2018"),
|
||||
R("Pedro Sánchez", "term start", "2 June 2018"),
|
||||
R("Spain", "population", "48 million"),
|
||||
R("Po", "length", "652 km"),
|
||||
R("European Union", "member count", "27"),
|
||||
]
|
||||
|
||||
|
||||
# --- the gate -----------------------------------------------------------------
|
||||
|
||||
def test_gate_role_in_question():
|
||||
assert role_in_text(Q_PEDRO_SUB) == "president"
|
||||
assert role_in_text(Q_PEDRO) == "president"
|
||||
assert role_in_text(Q_EU) is None
|
||||
assert role_in_text(Q_RIVERS) is None
|
||||
print("ok: gate — role word present only in the office questions")
|
||||
|
||||
|
||||
def test_gate_ref_entity():
|
||||
assert ref_entity(Q_PEDRO_SUB) == "Pedro Sanchez"
|
||||
assert ref_entity(Q_PEDRO) == "Pedro Sanchez"
|
||||
# counterexamples still have entities (Italy, EU) — the gate that
|
||||
# silences them is the role gate, not the entity gate
|
||||
assert ref_entity(Q_RIVERS) == "Italy"
|
||||
assert ref_entity(Q_EU) == "European Union"
|
||||
# role-only run never wins as entity
|
||||
assert ref_entity("Who is the President of France?") == "France"
|
||||
print("ok: ref_entity — 'Pedro Sanchez' (run breaks at 'as'; role runs lose)")
|
||||
|
||||
|
||||
# --- the audit ----------------------------------------------------------------
|
||||
|
||||
def test_pedro_questions_flag():
|
||||
for q in (Q_PEDRO_SUB, Q_PEDRO):
|
||||
a = audit_role_multiplicity(q, run_j_rows(), "Socialist International")
|
||||
assert a is not None, q
|
||||
vals = {alt["value"] for alt in a["alternatives"]}
|
||||
# the picked reading is NOT among the alternatives
|
||||
assert "Socialist International" not in vals
|
||||
# the other two offices are, with quotes (verbatim law)
|
||||
assert any("Prime Minister of Spain" == v for v in vals), vals
|
||||
assert "PSOE" in vals, vals
|
||||
for alt in a["alternatives"]:
|
||||
assert alt["role"] and alt["url"] is not None
|
||||
assert alt["quote"], "alternatives carry verbatim quotes"
|
||||
print("ok: Pedro questions flag — picked reading excluded, quotes carried")
|
||||
|
||||
|
||||
def test_counterexamples_silent():
|
||||
assert audit_role_multiplicity(Q_EU, run_j_rows(), "Germany") is None
|
||||
assert audit_role_multiplicity(Q_RIVERS, run_j_rows(), "Po") is None
|
||||
print("ok: counterexamples silent (no role word — audit never runs)")
|
||||
|
||||
|
||||
def test_single_office_silent():
|
||||
one = [R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain")]
|
||||
assert audit_role_multiplicity(Q_PEDRO, one, "Spain") is None
|
||||
print("ok: single office — no ambiguity to report")
|
||||
|
||||
|
||||
def test_dates_never_alternatives():
|
||||
dates = [R("Pedro Sánchez", "president since", "2018"),
|
||||
R("Pedro Sánchez", "prime minister since", "2 June 2018")]
|
||||
assert audit_role_multiplicity(Q_PEDRO, dates, "2018") is None
|
||||
print("ok: dates as values never become alternatives")
|
||||
|
||||
|
||||
def test_duplicate_office_collapses():
|
||||
dup = [R("Pedro Sánchez", "prime minister of", "Spain"),
|
||||
R("Pedro Sánchez", "office", "Prime Minister of Spain")]
|
||||
assert audit_role_multiplicity(Q_PEDRO, dup, "Spain") is None
|
||||
print("ok: same office in two extraction shapes = one reading")
|
||||
|
||||
|
||||
def test_role_in_object_counts():
|
||||
"""The role may live in the OBJECT, not the relation (extraction shape
|
||||
varies): 'office' | 'Prime Minister of Spain' + 'leader' | 'PSOE'."""
|
||||
obj_rows = [R("Pedro Sánchez", "office", "Prime Minister of Spain"),
|
||||
R("Pedro Sánchez", "leader", "PSOE"),
|
||||
R("Pedro Sánchez", "president", "Socialist International")]
|
||||
a = audit_role_multiplicity(Q_PEDRO, obj_rows, "Socialist International")
|
||||
assert a is not None
|
||||
vals = {alt["value"] for alt in a["alternatives"]}
|
||||
assert "Prime Minister of Spain" in vals and "PSOE" in vals
|
||||
print("ok: role in the object counts (relation shape does not matter)")
|
||||
|
||||
|
||||
# --- the wiring -----------------------------------------------------------------
|
||||
|
||||
def test_expert_wiring_flags_and_passes():
|
||||
"""_maybe_ambig on the real KnowledgeExpert: the Pedro question over a
|
||||
store seeded with the run-J edges flags; the rivers question over the
|
||||
same store does not (and its answer dict is untouched)."""
|
||||
import tempfile
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
tmp = tempfile.mkdtemp()
|
||||
store = KnowledgeStore(f"{tmp}/kg.sqlite")
|
||||
doc = store.add_document("http://x", "Pedro Sánchez", "t", "s1")
|
||||
seeds = [
|
||||
("Pedro Sánchez", "prime minister of Spain since 2018", "Spain"),
|
||||
("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE"),
|
||||
("Pedro Sánchez", "president of Socialist International since 2022",
|
||||
"Socialist International"),
|
||||
]
|
||||
for src, rel, dst in seeds:
|
||||
qid = store.add_quote(doc, f"{src} {rel} {dst}", "http://x", "t")
|
||||
store.add_edge(src, rel, dst, qid)
|
||||
|
||||
e = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
e.cfg = KnowledgeConfig()
|
||||
e.store = store
|
||||
e.streams = None
|
||||
e._checked = e._merged = 0
|
||||
e._seen_pages = {}
|
||||
e._skim_leads = []
|
||||
e._skim_notices = []
|
||||
e._link_queue = []
|
||||
|
||||
# Pedro question: flagged
|
||||
ans = e._maybe_ambig(
|
||||
Q_PEDRO, {"value": "Socialist International", "quote": "q",
|
||||
"url": "u", "confidence": "high"})
|
||||
assert ans.get("ambiguous") is True, ans
|
||||
assert len(ans["alternatives"]) == 2, ans
|
||||
assert "axis" in ans
|
||||
|
||||
# counterexample: untouched, byte-identical dict
|
||||
clean = {"value": "Po", "quote": "q", "url": "u", "confidence": "high"}
|
||||
out = e._maybe_ambig(Q_RIVERS, dict(clean))
|
||||
assert "ambiguous" not in out and "alternatives" not in out
|
||||
assert out == clean, out
|
||||
print("ok: expert wiring — flags Pedro, leaves the rivers answer untouched")
|
||||
|
||||
|
||||
def test_engine_log_and_notes():
|
||||
"""The AMBIGUOUS answer must be visible in three places: the EXPERT
|
||||
log line, the evidence render (context), and the run notes."""
|
||||
from floop.stream import RunStreams
|
||||
from floop.engine import KnowledgeEngine
|
||||
import tempfile
|
||||
|
||||
streams = RunStreams("amb test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||
|
||||
class KE:
|
||||
def answer_question(self, question, parent_question=None, evidence="",
|
||||
charge_llm=None, answer_type=None):
|
||||
return {"value": "Socialist International", "quote": "q",
|
||||
"url": "http://u", "source": "knowledge_graph",
|
||||
"confidence": "high",
|
||||
"ambiguous": True,
|
||||
"axis": "which office does 'president' refer to?",
|
||||
"alternatives": [
|
||||
{"value": "Prime Minister of Spain",
|
||||
"role": "prime minister", "quote": "x",
|
||||
"url": "http://u"},
|
||||
{"value": "PSOE", "role": "secretary-general",
|
||||
"quote": "y", "url": "http://u"}],
|
||||
"stats": {}}
|
||||
ke = KnowledgeEngine(KE())
|
||||
ke.charge = lambda: None
|
||||
|
||||
class Table:
|
||||
def rows(self):
|
||||
return []
|
||||
|
||||
row = ke.run("Q1", Q_PEDRO, "goal?", Table(), None, streams=streams)
|
||||
log = (streams.run_dir / "run.log").read_text()
|
||||
assert "AMBIGUOUS" in log, log
|
||||
assert "Prime Minister of Spain" in log
|
||||
assert row.payload.get("ambiguous") is True
|
||||
assert len(row.payload["alternatives"]) == 2
|
||||
assert "ambiguous" in row.provenance["note"]
|
||||
print("ok: engine — AMBIGUOUS log line + payload + provenance note")
|
||||
|
||||
# machine render: the ambiguous row renders its alternatives
|
||||
from floop.machine import FloopRun
|
||||
from floop.state import Budget
|
||||
from floop.state import OpenQuestion, QuestionStack
|
||||
|
||||
class FM:
|
||||
def init_decompose(self, question):
|
||||
return [], ""
|
||||
|
||||
run = FloopRun("goal?", Budget(max_llm_calls=40, max_depth=2,
|
||||
max_retries=3, missing_extensions=1,
|
||||
min_child_budget=4), modules=FM())
|
||||
run.streams = streams
|
||||
q = OpenQuestion(text=Q_PEDRO, answer_type=None, reason="init")
|
||||
ctx = run._context(q) # empty table -> the row render is exercised below
|
||||
# put the row in the table and render the context of a dependent question
|
||||
run.table.append(row)
|
||||
q2 = OpenQuestion(text="Who held that office before?", answer_type=None,
|
||||
reason="init")
|
||||
q2.deps = [row.qid]
|
||||
ctx2 = run._context(q2)
|
||||
assert "AMBIGUOUS" in ctx2, ctx2
|
||||
assert "Prime Minister of Spain" in ctx2 and "PSOE" in ctx2
|
||||
run._append_checked(row, q2)
|
||||
assert any("AMBIGUOUS" in n for n in run.notes), run.notes
|
||||
print("ok: machine — evidence render + run notes carry the alternatives")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_gate_role_in_question()
|
||||
test_gate_ref_entity()
|
||||
test_pedro_questions_flag()
|
||||
test_counterexamples_silent()
|
||||
test_single_office_silent()
|
||||
test_dates_never_alternatives()
|
||||
test_duplicate_office_collapses()
|
||||
test_role_in_object_counts()
|
||||
test_expert_wiring_flags_and_passes()
|
||||
test_engine_log_and_notes()
|
||||
print("\nambiguity audit tests passed")
|
||||
Reference in New Issue
Block a user