knowledge+llm: dst-first ablation mask (run L) + re-ask budget meter

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.
This commit is contained in:
2026-10-22 11:21:25 +02:00
parent 2de9aaa738
commit efd539c128
5 changed files with 327 additions and 13 deletions
+42 -13
View File
@@ -501,14 +501,46 @@ class KnowledgeExpert:
if (not value or value.upper() == "UNKNOWN" or not rows):
return answer
# The supporting rows for the PICKED value: those whose dst or quote
# carries it. Masked cumulatively each round; the store never
# changes — the view handed to the judge shrinks, nothing else.
# The supporting rows for the PICKED value. DST-FIRST LAW (run L):
# when a row has a meaningful dst it is the VALUE BEARER — quotes
# interleave readings in one paragraph ('... Secretary-General ...
# president of Socialist International ...' is ONE quote), so
# quote-matching over-masks and the audit dies silent at round 1.
# The quote is a fallback ONLY for rows whose dst is empty/numeric.
_NUMERIC_RE = re.compile(r"^[\d\s.,:+\-/–—%]+$")
def _dst(r) -> str:
return (getattr(r, "dst", "") or "").strip()
def _dst_meaningful(r) -> bool:
d = _dst(r)
return bool(d) and not _NUMERIC_RE.match(d)
def _carries(r) -> bool:
dst = (getattr(r, "dst", "") or "").strip().casefold()
quote = (getattr(r, "quote", "") or "").strip().casefold()
v = value.casefold()
return v in dst or v in quote
if _dst_meaningful(r):
return v in _dst(r).casefold()
quote = (getattr(r, "quote", "") or "").strip().casefold()
return v in quote
def _carries_target(r, val: str) -> bool:
"""DST-FIRST law, parameterized for a round's surviving value.
The judge's value may be an OFFICE DESCRIPTION, not the dst
entity itself ('prime minister of Spain' vs dst='Spain') —
resolve the row by reciprocal token containment: the dst
names the entity, the value describes the reading; overlap
means this row carried it."""
v = val.casefold()
if _dst_meaningful(r):
d = _dst(r).casefold()
if v == d or v in d or d in v:
return True
vt = set(WORD_RE.findall(v))
dt = set(WORD_RE.findall(d))
return bool(vt & dt) if vt and dt else False
quote = (getattr(r, "quote", "") or "").strip().casefold()
return v in quote
support = [r for r in rows if _carries(r)]
if not support:
@@ -530,11 +562,9 @@ class KnowledgeExpert:
if key in seen:
break # same value again: corroboration, not ambiguity
seen.add(key)
# which surviving row produced this reading? the one whose
# dst/quote carries it — for the report and the next mask
src_row = next((r for r in view
if re_val.casefold() in (r.dst or "").casefold()
or re_val.casefold() in (r.quote or "").casefold()), None)
# which surviving row produced this reading? DST-FIRST here too
# — same law as the pick's mask, for the report and the next mask
src_row = next((r for r in view if _carries_target(r, re_val)), None)
alternatives.append({
"value": re_val,
"quote": re_ans.get("quote", ""),
@@ -542,8 +572,7 @@ class KnowledgeExpert:
else re_ans.get("url", "")),
})
# mask this reading's own support too — next round hunts a third
new_support = [r for r in view if re_val.casefold() in (
(r.dst or "").casefold() + " " + (r.quote or "").casefold())]
new_support = [r for r in view if _carries_target(r, re_val)]
if not new_support:
break
masked |= set(id(r) for r in new_support)
+94
View File
@@ -256,6 +256,97 @@ def test_engine_and_machine_wiring():
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()
@@ -264,6 +355,9 @@ def main():
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")