Two fixes from his 22/10 re-run log, both small and deterministic:
1. THE ABLATION MASK WAS QUOTE-BLINDED (run L: Q1 stayed silent over
the Pedro page that run J flags). The Pedro paragraph interleaves
all three readings in ONE quote ('...Secretary-General ... ninth
president of Socialist International...'), and _carries matched
the picked value by substring over dst OR quote — so masking SI's
support masked the PM/PSOE rows too; round 1 answered UNKNOWN and
the audit died silent. The DST-FIRST LAW: when a row has a
meaningful dst (non-empty, non-numeric) it is the VALUE BEARER and
the mask matches IT; the quote is a fallback only for
empty/numeric dsts. Same law in _carries_target for each round's
surviving value, with one addition: the judge's round value may be
an OFFICE DESCRIPTION ('prime minister of Spain') while the row's
dst is the ENTITY ('Spain') — resolve by reciprocal token
containment, or the loop dies after one alternative.
2. THE ADAPTER RE-ASK WAS INVISIBLE TO THE BUDGET (run L: prompts #9
and #10 were both ANSWER — #10 5 chars shorter, 340s, the
ChatAdapter's JSON-fallback second wire call after a parse
failure; llm_calls said 9/80 while 10 hit the wire). THE METER:
the prompt-log callback already sees every LM call — a second LM
call with NO new module forward between them is the adapter
fallback re-firing inside the same Predict. Count it, log the
line, and charge the budget through a meter hook the machine
wires at construction. A re-ask at the ceiling does not kill the
run (the call already happened). dspy's BEHAVIOUR IS UNTOUCHED —
his call: the fallback stays, it is future self-improvement
signal (which prompts the model formats badly), not a bug.
Tests: knowledge/tests/ablation.py +3 — run-L regression (interleaved
one-paragraph quote flags all three readings), office-description
resolution, numeric-dst quote fallback. tests/reask_meter.py +3 —
fallback detected and charged on the REAL adapter path (custom engine
returning raw text, marker-less first response), separate forwards NOT
flagged (the ablation-rounds shape), ceiling charge survives. Suite
12/12 files green (74 tests). Live smokes: the run-L interleaved-quote
page flags SI+PM+SG through the full pipeline; the run-J
separate-quotes smoke still passes.
365 lines
16 KiB
Python
365 lines
16 KiB
Python
"""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 test_interleaved_quotes_flag_all_three():
|
|
"""RUN-L REGRESSION: one paragraph quote carrying ALL THREE readings
|
|
(the pick's own quote was the PSOE sentence). The dst-first mask must
|
|
keep the other rows alive: all three offices flagged, in order."""
|
|
Q_WHOLE = ("A member of the Spanish Socialist Workers' Party (PSOE), he "
|
|
"is also Secretary-General of the party since 2017, and is "
|
|
"the ninth president of Socialist International since 2022.")
|
|
rows = [
|
|
R("Pedro Sánchez", "prime minister of Spain since 2018", "Spain",
|
|
quote=Q_WHOLE),
|
|
R("Pedro Sánchez", "secretary-general of PSOE since 2017", "PSOE",
|
|
quote=Q_WHOLE),
|
|
R("Pedro Sánchez", "president of Socialist International since 2022",
|
|
"Socialist International", quote=Q_WHOLE),
|
|
]
|
|
order = {"Socialist International": 0, "prime minister of Spain": 1,
|
|
"secretary-general of PSOE": 2}
|
|
state = {"seen": "Socialist International"}
|
|
|
|
def judge(question, rws, charge_llm=None):
|
|
# picks by priority: SI if visible, else PM, else SG
|
|
vals = [str(r.dst) for r in rws]
|
|
if "Socialist International" in vals:
|
|
return {"value": "Socialist International", "quote": Q_WHOLE,
|
|
"url": "u"}
|
|
if "Spain" in vals:
|
|
return {"value": "prime minister of Spain", "quote": Q_WHOLE,
|
|
"url": "u"}
|
|
if "PSOE" in vals:
|
|
return {"value": "secretary-general of PSOE", "quote": Q_WHOLE,
|
|
"url": "u"}
|
|
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
|
|
|
e = make_expert(judge=judge)
|
|
ans = e._audit_ambiguity(Q_PEDRO, {"value": "Socialist International",
|
|
"quote": Q_WHOLE, "url": "u"}, 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
|
|
# run-L failure mode: the OLD quote-matching mask killed round 1
|
|
assert all(a["quote"] == Q_WHOLE for a in ans["alternatives"])
|
|
print("ok: run-L regression — interleaved one-paragraph quote flags all 3")
|
|
|
|
|
|
def test_office_description_value_resolves_row():
|
|
"""The judge's round value may be an OFFICE DESCRIPTION ('prime
|
|
minister of Spain') while the row's dst is the ENTITY ('Spain') —
|
|
reciprocal token containment must resolve and mask the right row,
|
|
without eating the unrelated PSOE row (or the loop dies after one
|
|
alternative). Shape: pick=SI, round 1 returns the PM description."""
|
|
rows = [R("X", "president of", "Socialist International"),
|
|
R("X", "prime minister of", "Spain"),
|
|
R("X", "secretary-general of", "PSOE")]
|
|
|
|
def judge(question, rws, charge_llm=None):
|
|
dsts = {str(r.dst) for r in rws}
|
|
if "Socialist International" in dsts:
|
|
return {"value": "Socialist International", "quote": "", "url": "u"}
|
|
if "Spain" in dsts:
|
|
# OFFICE DESCRIPTION, not the dst entity
|
|
return {"value": "prime minister of Spain", "quote": "", "url": "u"}
|
|
if "PSOE" in dsts:
|
|
return {"value": "secretary-general of PSOE", "quote": "", "url": "u"}
|
|
return {"value": "UNKNOWN", "quote": "", "url": ""}
|
|
|
|
e = make_expert(judge=judge)
|
|
ans = e._audit_ambiguity("What is X?", {"value": "Socialist International",
|
|
"quote": "", "url": "u"}, rows)
|
|
assert ans.get("ambiguous") is True, ans
|
|
alts = [a["value"] for a in ans["alternatives"]]
|
|
# PM's description resolved its Spain row; PSOE survived round 1
|
|
assert alts == ["prime minister of Spain",
|
|
"secretary-general of PSOE"], alts
|
|
print("ok: office-description value resolves its row (token overlap)")
|
|
|
|
|
|
def test_numeric_dst_falls_back_to_quote():
|
|
"""A date dst is NOT meaningful: the quote carries the value there.
|
|
The old numeric dsts (dates) must never mask text-bearing rows."""
|
|
rows = [R("X", "term start", "2 June 2018",
|
|
quote="took office on 2 June 2018"),
|
|
R("Y", "population", "48 million")]
|
|
e = make_expert(judge=lambda *a: {"value": "UNKNOWN"})
|
|
ans = e._audit_ambiguity("When did X start?", {"value": "2 June 2018",
|
|
"quote": "", "url": "u"},
|
|
rows)
|
|
assert "ambiguous" not in ans, ans
|
|
print("ok: numeric dst uses the quote fallback, stays silent")
|
|
|
|
|
|
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()
|
|
test_interleaved_quotes_flag_all_three()
|
|
test_office_description_value_resolves_row()
|
|
test_numeric_dst_falls_back_to_quote()
|
|
print("\nablation ambiguity tests passed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |