knowledge: replace curated-vocab ambiguity audit with ablation detector (run J)

PR-7's audit (merged hours earlier) detected office ambiguity with a
curated role vocabulary (president, prime minister, ...) plus entity
and shape heuristics. His run-K log killed it: all three alternatives
came out '[prime minister]', Mariano Rajoy (a person, not an office)
was one, PSOE never appeared — the vocabulary could not see the
difference. His design replaces it, and it is better: instead of
listing what counts as a role, ask the judge whether the question
STILL answers once the support for the picked value is masked out.

_audit_ambiguity (knowledge/expert.py), zero new prompts:
- After a scalar KG answer V, find V's support rows (dst/quote carry
  the value) and MASK them from the view — the store is never
  mutated, the mask is a Python-level view.
- Re-ask the SAME judge (AnswerFromKG) on the surviving rows.
  A DIFFERENT value = a second defensible reading -> record, mask
  its support too, repeat (ambiguity_rounds=3, budget law).
- Same surviving value = corroboration -> silent stop.
- UNKNOWN -> clean answer, byte-identical to pre-audit behaviour.
- Run J: pick 'Socialist International' -> ablation surfaces
  'prime minister of Spain' then 'secretary-general of PSOE' — the
  third paragraph reading, no role vocabulary anywhere.

Removed: knowledge/ambiguity.py + knowledge/tests/ambiguity.py
(PR-7), the .ambiguity import, and _maybe_ambig at the three scalar
return paths — replaced by _audit_ambiguity(question, answer, rows,
charge_llm) at the same three sites.

Consumers (engine/machine) now render the simpler alternative shape
{value, quote, url} — no 'role' field exists to render.

Tests: knowledge/tests/ablation.py — the 4 agreed cases (2 Pedro
positives flag with 2 alternatives each, EU and rivers
counterexamples silent), corroboration-not-ambiguity, store
unchanged after audit (mask is a view), single-source silent, rounds
cap. Suite 70/70. Live smoke: full pipeline over the run-J page
picks SI and flags PM+SG via two ablation rounds; the rivers
question over the same KG stays silent.
This commit is contained in:
2026-10-21 23:42:20 +02:00
parent 599188181c
commit 8b50e3076e
6 changed files with 353 additions and 496 deletions
+271
View File
@@ -0,0 +1,271 @@
"""Ablation ambiguity detector tests (run J) — same 4 agreed cases, now for
the ablation loop.
Laws under test:
1. Pedro office question: the judge picks Socialist International; ablation
rounds surface prime minister (of Spain) and secretary-general (PSOE) as
OTHER defensible readings — flagged, never chosen.
2. Ordinary questions: the first ablation round returns UNKNOWN (the KG has
no second reading) — byte-identical answer, no flag.
3. Corroboration is not ambiguity: a second row supporting the SAME value
keeps the audit silent.
4. The KG store is never mutated (the mask is a view).
5. The wiring: EXPERT log line carries AMBIGUOUS; payload {ambiguous, axis,
alternatives}; run notes + evidence render carry them.
No network. The judge is a scripted AnswerFromKG: a queue of responses.
Run: .venv/bin/python knowledge/tests/ablation.py
"""
from __future__ import annotations
import sys
import tempfile
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, KnowledgeConfig
from knowledge.store import KnowledgeStore
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 from the FIRST PARAGRAPH (one
chunk) + noise rows (dates, unrelated entities)."""
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", "term start", "2 June 2018"),
R("Spain", "population", "48 million"),
R("Po", "length", "652 km"),
]
def make_expert(store=None, judge=None):
"""KnowledgeExpert with a scripted judge: judge is a callable
(question, rows) -> answer dict, replacing AnswerFromKG."""
store = store or KnowledgeStore(
f"{tempfile.mkdtemp()}/kg.sqlite")
e = KnowledgeExpert.__new__(KnowledgeExpert)
e.cfg = KnowledgeConfig()
e.store = store
e.client = None # no network in these tests
e._log = lambda *a, **k: None
if judge is not None:
e._answer_from_rows = judge
return e
# --- the ablation loop --------------------------------------------------------
def test_pedro_flags():
"""The judge: round 0 pick SI; round 1 PM; round 2 SG; then UNKNOWN."""
rows = run_j_rows()
calls = []
def judge(question, rws, charge_llm=None):
calls.append(len(rws))
# rows visible shrink as supports are masked
vals = [str(r.dst) for r in rws]
if any("Socialist" in v for v in vals):
return {"value": "Socialist International",
"quote": "ninth president of Socialist International",
"url": "u"}
if any("Spain" in v for v in vals):
return {"value": "prime minister of Spain",
"quote": "he has been the prime minister of Spain",
"url": "u"}
if any("PSOE" in v for v in vals):
return {"value": "secretary-general of PSOE",
"quote": "Secretary-General of the party",
"url": "u"}
return {"value": "UNKNOWN", "quote": "", "url": ""}
e = make_expert(judge=judge)
base = {"value": "Socialist International", "quote": "q", "url": "u"}
ans = e._audit_ambiguity(Q_PEDRO, base, rows)
assert ans.get("ambiguous") is True, ans
alts = [a["value"] for a in ans["alternatives"]]
assert alts == ["prime minister of Spain", "secretary-general of PSOE"], alts
assert "Socialist International" not in alts
assert all(a["quote"] for a in ans["alternatives"]), "verbatim law"
print("ok: Pedro question flags — 2 alternatives by ablation, picked excluded")
def test_counterexamples_silent():
"""Ordinary questions: judge answers with one value; ablation round 1
sees no other reading (UNKNOWN) — byte-identical answer, no flag."""
rows = [R("Germany", "population rank", "second in European Union",
quote="Germany is the second most populated country"),
R("Spain", "population", "48 million"),
R("Po", "length", "652 km")]
def judge(question, rws, charge_llm=None):
vals = [str(r.dst) for r in rws]
if any("second" in v for v in vals):
return {"value": "Germany",
"quote": "Germany is the second most populated country",
"url": "u"}
return {"value": "UNKNOWN", "quote": "", "url": ""}
e = make_expert(judge=judge)
base = {"value": "Germany", "quote": "q", "url": "u"}
ans = e._audit_ambiguity(Q_EU, base, rows)
assert ans == base, ans # byte-identical, no flag
print("ok: counterexample (EU) silent — single reading, no extra flag")
# rivers: list answers skip the audit entirely (scalar-only)
rivers_rows = [R("Po", "length rank", "longest river in Italy")]
e2 = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
ans2 = e2._audit_ambiguity(Q_RIVERS,
{"value": "Po, Adige, Tiber", "quote": "q",
"url": "u"}, rivers_rows)
assert ans2.get("ambiguous") is not True, ans2
print("ok: counterexample (rivers) silent")
def test_corroboration_not_ambiguity():
"""A second row supporting the SAME value: the judge (honest) answers
Germany again; same-value survivors are corroboration — silent."""
rows = [R("Germany", "population rank", "second most populated",
quote="Germany is the second most populated"),
R("Germany", "member of", "European Union")]
def judge(question, rws, charge_llm=None):
vals = [str(r.dst) for r in rws]
if any("second" in v for v in vals):
return {"value": "Germany", "quote": "q", "url": "u"}
return {"value": "UNKNOWN", "quote": "", "url": ""}
e = make_expert(judge=judge)
ans = e._audit_ambiguity(Q_EU, {"value": "Germany", "quote": "q",
"url": "u"}, rows)
assert "ambiguous" not in ans, ans
print("ok: same-value survivor (corroboration) stays silent")
def seed_store(ks, rows):
"""Seed a real store with the R rows (doc + quote + edge each)."""
for i, r in enumerate(rows):
doc = ks.add_document(url=f"http://u{i}", source="wikipedia",
fetched_at="2026-10-21", sha256=f"h{i}",
trusted=True, title=r.src)
qid = ks.add_quote(doc, r.quote or f"about {r.dst}", f"http://u{i}",
"2026-10-21")
ks.add_edge(r.src, r.rel, r.dst, qid)
def test_store_never_mutated():
"""The mask is a view: after the audit, probe() still returns all rows."""
tmp = tempfile.mkdtemp()
ks = KnowledgeStore(f"{tmp}/kg.sqlite")
seed_store(ks, run_j_rows())
before = len(ks.probe(["pedro", "sánchez", "office", "spain"]))
e = make_expert(store=ks)
def judge(question, rws, charge_llm=None):
vals = [str(r.dst) for r in rws]
if any("Socialist" in v for v in vals):
return {"value": "Socialist International", "quote": "q", "url": "u"}
if any("Spain" in v for v in vals):
return {"value": "prime minister of Spain", "quote": "q", "url": "u"}
return {"value": "UNKNOWN", "quote": "", "url": ""}
e._answer_from_rows = judge
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
"quote": "q", "url": "u"},
ks.probe(["pedro", "sánchez", "office", "spain"]))
after = len(ks.probe(["pedro", "sánchez", "office", "spain"]))
assert after == before, f"store mutated: {before} -> {after}"
assert ans.get("ambiguous") is True
print("ok: the mask is a view — probe() unchanged after the audit")
def test_single_source_silent():
"""Support rows but no survivors: nothing to ablate — silent."""
rows = [R("Pedro Sánchez", "president of", "Socialist International",
quote="president of Socialist International")]
e = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
"quote": "q", "url": "u"}, rows)
assert "ambiguous" not in ans, ans
print("ok: single-source KG — nothing to ablate, silent")
def test_rounds_cap():
"""The loop honors ambiguity_rounds: more readings than rounds -> the
flag carries at most ambiguity_rounds alternatives, the loop ends."""
rows = [R("X", "r1", "v1"), R("X", "r2", "v2"), R("X", "r3", "v3"),
R("X", "r4", "v4"), R("X", "r5", "v5")]
def judge(question, rws, charge_llm=None):
# always the first visible row's dst
return {"value": str(rws[0].dst), "quote": "", "url": "u"}
e = make_expert(judge=judge)
ans = e._audit_ambiguity("What is X?", {"value": "v1", "quote": "", "url": "u"},
rows)
assert ans.get("ambiguous") is True, ans
assert len(ans["alternatives"]) <= 3, ans
print("ok: rounds cap honored (<= ambiguity_rounds alternatives)")
# --- the wiring ----------------------------------------------------------------
def test_engine_and_machine_wiring():
"""The flag surface: EXPERT log line, payload, provenance, run notes and
the evidence render — with the new value/quote/url alternative shape."""
import inspect
src = inspect.getsource(KnowledgeExpert)
assert "_audit_ambiguity" in src
assert "_maybe_ambig" not in src, "the PR-7 audit must be fully removed"
# engine log line: AMBIGUOUS without [role] prefixes
import floop.engine as fe
esrc = inspect.getsource(fe)
assert "AMBIGUOUS" in esrc
assert "[{a.get('role')}]" not in esrc, "role prefixes are gone"
# machine notes + render: same shape
import floop.machine as fm
msrc = inspect.getsource(fm)
assert "AMBIGUOUS" in msrc
assert "({a.get('role')})" not in msrc
print("ok: wiring — audit renamed, role prefixes gone, log/notes/render keep AMBIGUOUS")
def main():
test_pedro_flags()
test_counterexamples_silent()
test_corroboration_not_ambiguity()
test_store_never_mutated()
test_single_source_silent()
test_rounds_cap()
test_engine_and_machine_wiring()
print("\nablation ambiguity tests passed")
if __name__ == "__main__":
main()
-270
View File
@@ -1,270 +0,0 @@
"""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")