Author SHA1 Message Date
onibot 109885773c knowledge: typed Fact extraction via dspy native structured output
His direction: stop explaining string formats to the LLM and parsing
them back with Python — that's exactly what dspy does natively and
better. The pipe format ('subject | relation | object | quote') was
fragile (run-L verbose values, pipe-in-quote ambiguity, STOP_TABLE
string protocol).

THE CHANGE (extractor only, PR-10 scope):
- Fact(BaseModel) with subject/relation/object/quote OutputFields
- ExtractSignature.facts: list[Fact] — the adapter renders the JSON
  schema into the prompt itself (verified in a live run's prompt log)
  and parses responses back into typed Fact objects
- STOP_TABLE string protocol -> stop: bool OutputField
- expert.py consumes typed objects; the cand dict is built at the
  check_candidate boundary only (checks.py unchanged)
- parse_facts/parse_stop_table kept as LEGACY for existing tests only

VERIFIED:
- dspy 3.4.1 pattern E2E'd first with a raw-text engine: list[Fact]
  parses back as Fact objects, schema rendered in prompt (tmp probes)
- full suite 12/12 green (74 tests) — tablefrags.py updated to script
  typed Fact objects
- live E2E run (ollama-cloud glm-5.3-flash, Italy rivers): correct
  Po/Adige/Tiber answer; prompt log shows the native JSON schema;
  table rows ingested cleanly (22 rows, quotes verbatim)

NEXT (his direction, not this PR): apply the same typed-output law to
ALL floop signatures — INIT subquestions, ROUTE engine choice,
AnswerFromKG, SelectTable, SkimPromote, Translate, VerifyCount.
2026-10-22 14:21:13 +02:00
onibot 5c97fbf50a Merge pull request 'knowledge+llm: dst-first ablation mask (run L) + re-ask budget meter' (#9) from feature/ablation-dst-fix into main 2026-10-22 11:21:38 +02:00
onibot efd539c128 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.
2026-10-22 11:21:25 +02:00
onibot 2de9aaa738 Merge pull request 'knowledge: replace curated-vocab ambiguity audit with ablation detector (run J)' (#8) from feature/ablation-ambiguity into main 2026-10-21 23:42:29 +02:00
onibot 8b50e3076e 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.
2026-10-21 23:42:20 +02:00
11 changed files with 711 additions and 525 deletions
+1 -1
View File
@@ -184,7 +184,7 @@ class KnowledgeEngine:
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')}"
alts = "; ".join(a.get("value", "")
for a in (ans.get("alternatives") or [])[:3])
streams.output("EXPERT",
f"{qref} -> ANSWER value={value} "
+31
View File
@@ -42,6 +42,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
(charge happens before the Predict runs), so 08-extract.txt IS the
call 8/80 of run G that hung for minutes. Plus size/duration lines in
run.log; the exact prompt is in the file, log stays line-based.
RE-ASK METER (run L): dspy's chat adapter, on a parse failure, re-fires
the SAME module's LM call through its JSON fallback — an extra wire call
the budget counter never charged (9/80 logged, 10 on the wire, the
second burning 340s of GPU). The meter sees them (same module depth in
the stack twice), charges the budget via an optional meter hook, and
logs the line — dspy's BEHAVIOUR is untouched (his call: the fallback
stays; it is future self-improvement signal, not a bug to fix).
"""
def __init__(self, streams) -> None:
@@ -50,6 +58,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
self.reasks = 0 # LM calls the budget did not charge
self.meter = None # callable(str stage) -> None; budget charge
# -- dspy plumbing -------------------------------------------------------
@@ -57,6 +67,7 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
sig = getattr(getattr(instance, "signature", None), "__name__", None)
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
self._stack.append(label)
self._fresh_forward = True # this forward's first LM call is not a re-ask
def on_module_end(self, call_id, outputs, exception):
if self._stack:
@@ -74,6 +85,26 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
if isinstance(m, dict)
)
chars = len(text)
# RE-ASK METER: a second LM call with NO new module forward between
# them is dspy's adapter fallback re-firing inside the same Predict
# (ChatAdapter catches AdapterParseError and re-calls via JSONAdapter)
# — an extra wire call the budget did not charge. Consecutive SAME-
# stage calls from DIFFERENT forwards (the ablation rounds) are NOT
# re-asks: each round opens its own module.
fresh = getattr(self, "_fresh_forward", False)
self._fresh_forward = False
self._lm_seen = getattr(self, "_lm_seen", 0) + 1
reask = self._lm_seen > 1 and not fresh
if reask:
self.reasks += 1
if streams is not None:
streams.log(f"re-ask detected: stage={label} "
f"(adapter parse-failure fallback, charged to budget)")
if self.meter is not None:
try:
self.meter(label)
except Exception: # noqa: BLE001 — metering must never kill a run
pass
if streams is not None:
n = streams.bump_prompt_seq()
fn = f"{n:02d}-{label}.txt"
+20 -3
View File
@@ -91,6 +91,14 @@ class FloopRun:
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
self.notes: list[str] = []
self.engine_calls = 0
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
# the budget never charged. The prompt-log callback sees them; wire
# its meter to our budget so the count is honest. The BEHAVIOUR of
# dspy stays untouched (his call: the fallback is future
# self-improvement signal, not a bug).
from .llm import _PROMPT_LOG
if _PROMPT_LOG is not None:
_PROMPT_LOG.meter = self._meter_reask
# ---- budget -----------------------------------------------------------
@@ -99,6 +107,16 @@ class FloopRun:
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
f"/{self.budget.max_llm_calls} depth={self.depth}")
def _meter_reask(self, stage: str) -> None:
"""The prompt-log callback detected an adapter re-ask: charge the
budget for the extra wire call (a re-ask may hit the ceiling but
never kills the run mid-step), and note it for the report."""
try:
self.budget.charge_llm()
except BudgetExhausted:
pass # ceiling reached: the call already happened; note only
self.notes.append(f"re-ask charged: stage={stage}")
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
def run(self) -> RunReport:
@@ -458,7 +476,7 @@ class FloopRun:
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]))
a.get("value") for a in alts[:3]))
self.table.append(row)
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
q.status = "failed"
@@ -479,8 +497,7 @@ class FloopRun:
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])
other = "; ".join(a.get("value", "") for a in alts[:3])
return (f"{val} — AMBIGUOUS, other defensible readings: "
f"{other}")
return val
-194
View File
@@ -1,194 +0,0 @@
"""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]}
+117 -33
View File
@@ -24,10 +24,9 @@ import dspy
from .checks import check_candidate, quote_containment
from .chunker import chunk_page
from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, SelectTableSignature,
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
SkimPromoteSignature, TranslateSignature,
VerifyCountSignature, parse_facts)
from .ambiguity import audit_role_multiplicity, ref_entity, role_in_text
VerifyCountSignature)
from .store import KnowledgeStore, norm_name
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag, parse_stop_table)
@@ -110,6 +109,7 @@ class KnowledgeConfig:
max_search_results: int = 4 # candidates considered
max_chunks_extracted: int = 6 # per call (lexical gate decides which)
max_extract_retries: int = 2
ambiguity_rounds: int = 3 # ablation rounds per scalar answer (run J)
chunk_chars_target: int = 32000
chunk_chars_cap: int = 48000
# skim harvest (PR-2): goal-relevant side-tables are ingested in passing
@@ -260,7 +260,7 @@ 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 {**self._maybe_ambig(question, answer),
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
@@ -395,7 +395,9 @@ 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 {**self._maybe_ambig(question, answer),
return {**self._audit_ambiguity(question, answer,
self.store.probe(probe_seeds),
charge_llm),
"source": "knowledge_graph",
"stats": {**self._skim_stats(pages),
"skim": self._skim_notices}}
@@ -408,7 +410,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 {**self._maybe_ambig(question, answer), "source": src,
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
"stats": {**self._skim_stats(pages),
"checked": self._checked, "merged": self._merged,
"skim": self._skim_notices,
@@ -480,31 +482,109 @@ 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"):
def _audit_ambiguity(self, question: str, answer: dict, rows,
charge_llm=None) -> dict:
"""Ablation ambiguity detector (KNOWLEDGE.md §8, run J).
The KG just answered with value V from some support row(s). Ask the
SAME judge (AnswerFromKG) whether the question ALSO answers without
that support: mask the rows whose object/relation produced V, re-ask.
A DIFFERENT surviving value = a second defensible reading -> flag.
Repeat (bounded) until the rows run out of answers. Same-value
survivors are corroboration, not ambiguity — silent.
Zero new prompts: same AnswerFromKG signature, one call per round.
The store is NEVER mutated — the mask is a view, deletion happens
nowhere. Ordinary questions end at round 1 with UNKNOWN (silent).
"""
value = str(answer.get("value", "")).strip()
if (not value or value.upper() == "UNKNOWN" or not rows):
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"]}
# 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:
v = value.casefold()
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:
return answer # the judge invented it: nothing to ablate
alternatives: list[dict] = []
seen = {norm_name(value)}
masked = set(id(r) for r in support)
for _ in range(self.cfg.ambiguity_rounds):
view = [r for r in rows if id(r) not in masked]
if not view:
break
re_ans = self._answer_from_rows(question, view, charge_llm)
re_val = str(re_ans.get("value", "")).strip()
if not re_val or re_val.upper() == "UNKNOWN":
break # the KG has no other reading: clean
key = norm_name(re_val)
if key in seen:
break # same value again: corroboration, not ambiguity
seen.add(key)
# 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", ""),
"url": (src_row.url if src_row is not None
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 _carries_target(r, re_val)]
if not new_support:
break
masked |= set(id(r) for r in new_support)
if not alternatives:
return answer # ordinary question: byte-identical
self._log(f"ambiguity audit: {len(alternatives)} other reading(s) "
f"({'; '.join(a['value'][:40] for a in alternatives[:3])}) "
f"— flagging, not choosing", think=True)
return {**answer, "ambiguous": True,
"axis": f"which {question.strip().rstrip('?')}?",
"alternatives": alternatives}
def _verify_count(self, set_name: str, count: int, prose: str,
charge_llm) -> dict | None:
@@ -884,8 +964,10 @@ class KnowledgeExpert:
if charge_llm:
charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts):
for cand in (raw.facts or []):
self._checked += 1
cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote}
ok, reason = check_candidate(cand, page.text)
if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
@@ -921,17 +1003,19 @@ class KnowledgeExpert:
charge_llm()
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
raw = self.extract(question=question, heading=heading, text=text)
if parse_stop_table(raw.facts):
if raw.stop:
stopped.add(frag["table_idx"])
self._log(f"extractor STOP_TABLE: table {frag['table_idx']} "
f"({frag['caption'][:40]!r}) not relevant — "
f"skipping {frag['of'] - frag['part']} remaining parts",
think=True)
continue
for cand in parse_facts(raw.facts):
for cand in (raw.facts or []):
self._checked += 1
# containment against prose + FULL table text: the fragment is
# rendered from the same rows, so quotes verify honestly
cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote}
ok, reason = check_candidate(cand, containment)
if not ok:
self._log(f"frag candidate rejected ({reason}): "
+23 -14
View File
@@ -7,6 +7,16 @@ the FULL document text — so chunking can never fake a quote.
from __future__ import annotations
import dspy
from pydantic import BaseModel
class Fact(BaseModel):
"""One fact extracted from a text, with its verbatim supporting quote."""
subject: str = dspy.OutputField(desc="the fact's subject entity")
relation: str = dspy.OutputField(desc="the relation between subject and object")
object: str = dspy.OutputField(desc="the fact's object / value")
quote: str = dspy.OutputField(
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
class TranslateSignature(dspy.Signature):
@@ -24,21 +34,21 @@ class TranslateSignature(dspy.Signature):
class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text,
extract facts that help answer the question. Each fact is one line:
subject | relation | object | verbatim quote from the text.
The quote must be the FULL sentence or table ROW that states the fact,
extract the facts that help answer the question. Each fact carries its
verbatim quote: the FULL sentence or table ROW that states the fact,
copied exactly (at least 10 characters). Only facts the text states;
no inference.
If the text is a fragment of a larger TABLE and you can already tell
from its caption/headers that this table cannot contain anything
relevant to the question (wrong subject entirely), reply with the
single word STOP_TABLE and no facts. Do NOT use STOP_TABLE for text
that is merely hard — only when the table's subject is wrong."""
If the text is a fragment of a larger TABLE whose caption/headers show
its subject is wrong for the question, set stop=True with no facts.
Do NOT stop for text that is merely hard — only when the table's
subject is wrong."""
question: str = dspy.InputField()
heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField()
facts: str = dspy.OutputField(
desc="one fact per line: subject | relation | object | verbatim quote; empty if none; or STOP_TABLE if this table fragment's subject is wrong for the question")
facts: list[Fact] = dspy.OutputField(
desc="the extracted facts; empty list if none")
stop: bool = dspy.OutputField(
desc="True when this table fragment's subject is wrong for the question")
class AnswerFromKG(dspy.Signature):
@@ -102,10 +112,9 @@ class SkimPromoteSignature(dspy.Signature):
def parse_facts(raw: str) -> list[dict]:
"""Parse the extractor's piped lines; malformed lines are dropped+counted.
Split into AT MOST 4 fields — the quote is the last field and may itself
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
"""LEGACY pipe parser — kept ONLY for tests that script extractor
responses as text. Production code consumes typed `Fact` objects from
dspy directly (see ExtractSignature.facts). Do not use in new code."""
out: list[dict] = []
for line in (raw or "").strip().splitlines():
line = line.strip()
+365
View File
@@ -0,0 +1,365 @@
"""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()
-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")
+10 -6
View File
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
parse_stop_table)
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
from knowledge.extract import Fact
from knowledge.store import KnowledgeStore
from knowledge.wiki import WikiPage
@@ -91,23 +92,26 @@ def test_process_page_fragments():
wikitext=WIKITEXT_2TABLES)
page.tables = parse_tables(WIKITEXT_2TABLES)
# scripted extractor: world-table parts -> STOP_TABLE; Italy table -> one fact
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
calls = []
class FakeOut:
def __init__(self, facts):
def __init__(self, facts, stop=False):
self.facts = facts
self.stop = stop
def fake_extract(question, heading, text, _calls=calls):
_calls.append((question, heading, text))
if "World rivers" in text:
return FakeOut("STOP_TABLE")
return FakeOut([], stop=True)
if "Rivers of Italy" in text:
# quote = the full rendered row context (header + row), verbatim
# from the fragment the extractor saw
return FakeOut("Po | Flow at the mouth | 1540 m3/s | "
"River | Flow at the mouth Po | 1540")
return FakeOut("")
return FakeOut([Fact(
subject="Po", relation="Flow at the mouth",
object="1540 m3/s",
quote="River | Flow at the mouth Po | 1540")])
return FakeOut([])
e.extract = fake_extract
+2 -4
View File
@@ -190,10 +190,8 @@ def part_of(frag: dict) -> str:
def parse_stop_table(out_text: str) -> bool:
"""True when the extractor's output names this table as not relevant for
the question. The extractor may write STOP_TABLE for a fragment's table
after seeing its identity (caption/header) — fixed code then skips all
remaining fragments of THAT table (never other tables)."""
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
code reads the typed `stop: bool` field of ExtractSignature."""
return "STOP_TABLE" in (out_text or "").upper()[:80]
+142
View File
@@ -0,0 +1,142 @@
"""Re-ask meter tests (run L): dspy's adapter JSON fallback fires a second
LM call inside the SAME module forward — the budget never charged it
(9/80 logged, 10 on the wire, the extra burning 340s of GPU).
Laws under test:
1. The meter DETECTS the fallback (marker-less first response) and charges
the budget once via the hook; dspy's behaviour is untouched (the second
call still runs — his call: the fallback stays, it is future
self-improvement signal).
2. Separate forwards (the ablation rounds) are NOT re-asks.
3. A re-ask at budget ceiling does not kill the run (the call already
happened — note only).
The repro drives dspy's REAL adapter path: a custom engine returning raw
text (exactly what the OpenAI-compatible endpoint returns), first response
WITHOUT the '[[ ## field ## ]]' marker -> ChatAdapter raises
AdapterParseError -> JSONAdapter fallback re-fires the call.
Run: .venv/bin/python tests/reask_meter.py
"""
from __future__ import annotations
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import dspy
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from floop.llm import PromptLogCallback
from floop.stream import RunStreams
from floop.state import Budget, BudgetExhausted
class AnswerSig(dspy.Signature):
goal: str = dspy.InputField()
final_answer: str = dspy.OutputField()
def _resp(text: str) -> Response:
return Response(
id="x", model="fake",
message=Message(role="assistant", parts=(TextPart(text=text),)),
finish_reason="stop",
usage=Usage(input_tokens=1, output_tokens=1))
class FallbackEngine:
"""First response lacks the output-field marker: the ChatAdapter parse
fails and the JSON-adapter fallback re-fires the call (run-L shape)."""
def __init__(self):
self.i = 0
self.responses = [
"L'anterior president del Govern d'Espanya va ser Mariano Rajoy.",
'{"final_answer": "Mariano Rajoy (JSON retry)"}',
]
def complete(self, request, **kw):
i = min(self.i, len(self.responses) - 1)
self.i += 1
return _resp(self.responses[i])
class CleanEngine:
"""Every forward parses cleanly — two separate module forwards, no
fallback (the ablation-rounds shape: same stage, fresh forwards)."""
def __init__(self):
self.i = 0
def complete(self, request, **kw):
self.i += 1
return _resp(f"[[ ## final_answer ## ]]\nreading {self.i}")
def test_fallback_detected_and_charged():
streams = RunStreams("meter test", verbose=False, runs_dir=tempfile.mkdtemp())
cb = PromptLogCallback(streams)
dspy.configure(lm=dspy.LM(model="fake", engine=FallbackEngine()),
callbacks=[cb])
charged = []
cb.meter = lambda stage: charged.append(stage)
out = dspy.Predict(AnswerSig)(goal="who?")
files = list((streams.run_dir / "prompts").glob("*.txt"))
assert len(files) == 2, f"two wire calls expected: {[f.name for f in files]}"
assert cb.reasks == 1, cb.reasks
assert charged == ["AnswerSig"], charged
assert "JSON retry" in out.final_answer, "dspy behaviour untouched"
print("ok: adapter fallback detected — 2 wire calls, 1 re-ask, 1 charge")
def test_separate_forwards_not_flagged():
streams = RunStreams("rounds test", verbose=False, runs_dir=tempfile.mkdtemp())
cb = PromptLogCallback(streams)
charged = []
cb.meter = lambda stage: charged.append(stage)
dspy.configure(lm=dspy.LM(model="fake2", engine=CleanEngine()),
callbacks=[cb])
p = dspy.Predict(AnswerSig)
p(goal="q1")
p(goal="q2") # second forward: fresh module start, NOT a re-ask
assert cb.reasks == 0, f"separate forwards flagged: {cb.reasks}"
assert charged == []
print("ok: two separate forwards (ablation rounds) NOT flagged")
def test_meter_never_kills_run():
"""The meter hook raising (budget ceiling) must not kill the run —
the wire call already happened."""
from floop.machine import FloopRun
b = Budget(max_llm_calls=1, max_depth=1, max_retries=1,
missing_extensions=1, min_child_budget=1)
# simulate: budget at ceiling, meter fires
class FakeModules:
pass
fm = FloopRun.__new__(FloopRun)
fm.budget = b
fm.notes = []
fm.streams = None
fm._meter_reask("ANSWER")
assert fm.budget.llm_calls == 1, "ceiling charge must not overflow the count"
assert any("re-ask charged" in n for n in fm.notes), fm.notes
print("ok: meter at ceiling — charged honestly, run survives")
def main():
test_fallback_detected_and_charged()
test_separate_forwards_not_flagged()
test_meter_never_kills_run()
print("\nre-ask meter tests passed")
if __name__ == "__main__":
main()