Phase 0 — judge value cleanup + --no-cache + import assert

The (K5) bug fix (his 24-25/10 session): glm-5.3-flash glues row
citations and glosses onto the judge's value field, killing the ablation
audit silently ("the judge invented it: nothing to ablate") and leaking
LLM prose into typed payloads. Fixed at the judge's output boundary
(_answer_from_rows): trailing-only, marker-anchored cleanup (_clean_value)
that strips the three live citation shapes and survives legitimate
parentheticals ("(PSOE)", "(since 2018)"). The AnswerFromKG value desc
now says what the value must be.

--no-cache CLI flag (his ruling: the dspy disk cache is not a bug, the
default stays; the flag exists for A/B and freshness testing) — builds
dspy.LM with cache=False for the process; verified live: repeated runs
re-run real inference instead of replaying.

Import assert at startup: floop/knowledge SUBMODULE files must resolve
inside this repo's tree. Namespace-package __path__ lies (it recomputes
dynamically and lists every tree), so the check pins the actual module
files (run 085457 was main's pipeline inside the branch worktree, no
signal). Abort loudly, don't log.
This commit is contained in:
2026-10-25 20:00:34 +01:00
parent e594339629
commit 985aec2f60
5 changed files with 200 additions and 6 deletions
+40 -1
View File
@@ -33,6 +33,45 @@ from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
# no citation output field, so the model cites in the only field it has).
# Three live shapes, stripped at the judge's output boundary — BEFORE the
# evidence payload and the ablation audit see the value:
# "... (K5)" — row-id citation suffix
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
# cleans the model's proposal (LLMs propose, code decides — the audit's
# _carries then finds the support rows and the ambiguity audit can run).
_ROW_CITATION_RE = re.compile(
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
re.IGNORECASE)
_ROW_CITED_GLOSS_RE = re.compile(
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
re.IGNORECASE)
_LIST_GLOSS_RE = re.compile(
r"\s*\(\s*list of\b[^()]*\)\s*$",
re.IGNORECASE)
def _clean_value(value: str) -> str:
"""Strip trailing citation/gloss parentheticals from a judge value.
The boundary law: only TRAILING shapes with a citation/list marker are
touched; mid-value text and legitimate parentheticals are the model's
own words and stay. Idempotent by construction (a cleaned value ends
clean). UNKNOWN and empty pass through untouched.
"""
v = (value or "").strip()
if not v or v.upper() == "UNKNOWN":
return v
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
v = rx.sub("", v).rstrip()
return v.strip()
# header/caption terms that name the ENTITY column of a typical scalar table
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
@@ -1019,7 +1058,7 @@ class KnowledgeExpert:
for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered)
return {
"value": pred.value.strip(),
"value": _clean_value(pred.value),
"quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
and r.quote.strip() in pred.quote.strip()), rows[0].url),
+2 -1
View File
@@ -53,7 +53,8 @@ class AnswerFromKG(dspy.Signature):
rows by id. If the rows do not answer it, say UNKNOWN."""
question: str = dspy.InputField()
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
value: str = dspy.OutputField(
desc="the answer, or UNKNOWN — the value ONLY, no row citations, no parenthetical explanations")
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
confidence: Confidence = dspy.OutputField(
desc="high: rows settle it; medium: plausible but partial; low: weak support")
+114
View File
@@ -0,0 +1,114 @@
"""Judge value cleanup tests (the (K5) bug, run 085457 / 24-25/10 session).
glm-5.3-flash glues row citations and glosses onto the value field because
AnswerFromKG says "cite rows by id" but has no citation output field. Three
live shapes, verbatim from the runs:
"Socialist International (K5)" — row id
"2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., ...)" — parenthetical gloss
"15 (list of 15 members: 17 november 2023, ...)" — LIST gloss
Laws under test:
1. Trailing citation shapes are STRIPPED from the value, at the judge's
output boundary (_clean_value), BEFORE the payload and the audit see it.
2. Legitimate parentheticals SURVIVE: "(PSOE)" inside a name,
"(Presidente del Gobierno)" inside an office title.
3. A cleaned value lets the ablation audit RUN where the raw value killed
it silently ("the judge invented it: nothing to ablate").
4. The clean is idempotent and does not touch UNKNOWN/empty.
No network. No LLM: the cleaner is fixed code; the tests call it directly
plus one scripted-judge pass through _answer_from_rows.
Run: .venv/bin/python knowledge/tests/value_clean.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.expert import KnowledgeExpert, _clean_value
def test_row_id_suffix_stripped():
assert _clean_value("Socialist International (K5)") == "Socialist International"
assert _clean_value("Rajoy (K12)") == "Rajoy"
print("ok: row-id citation suffix stripped")
def test_cited_from_rows_gloss_stripped():
v = ("2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., "
"President of the Government — since 2018; cited from rows K16 and K30)")
assert _clean_value(v) == "2018", _clean_value(v)
print("ok: 'cited from rows' parenthetical stripped, year kept")
def test_list_gloss_stripped():
v = "15 (list of 15 members: 17 november 2023, 28 november 2023, 24 september 2024)"
assert _clean_value(v) == "15", _clean_value(v)
print("ok: LIST-members gloss stripped, count kept")
def test_legitimate_parentheticals_survive():
assert _clean_value("Spanish Socialist Workers' Party (PSOE)") == \
"Spanish Socialist Workers' Party (PSOE)"
assert _clean_value("Prime Minister of Spain (Presidente del Gobierno)") == \
"Prime Minister of Spain (Presidente del Gobierno)"
# a parenthetical that merely mentions a number is NOT a citation
assert _clean_value("Prime Minister of Spain (since 2018)") == \
"Prime Minister of Spain (since 2018)"
print("ok: legitimate parentheticals untouched")
def test_unknown_and_empty_untouched():
assert _clean_value("UNKNOWN") == "UNKNOWN"
assert _clean_value("") == ""
assert _clean_value(" Spain ") == "Spain"
print("ok: UNKNOWN/empty/whitespace handled")
def test_idempotent_and_mid_value_citations():
v = _clean_value("Socialist International (K5)")
assert _clean_value(v) == v
# a citation in the MIDDLE is not the live bug shape — leave it (no
# aggressive surgery on the judge's sentence), the boundary law strips
# only the TRAILING gloss
assert _clean_value("Per (K2) the answer is Spain") == \
"Per (K2) the answer is Spain"
print("ok: idempotent; mid-value text untouched (boundary law: trailing only)")
def test_answer_from_rows_boundary():
"""The hook: _answer_from_rows cleans pred.value before the payload is
built. Scripted dspy-style Predict object; no network."""
e = KnowledgeExpert.__new__(KnowledgeExpert)
e.cfg = __import__("knowledge.expert", fromlist=["KnowledgeConfig"]).KnowledgeConfig()
e._log = lambda *a, **k: None
class Pred:
value = "Socialist International (K5)"
quote = "ninth president of Socialist International since 2022"
class confidence:
value = "high"
class Row:
src = rel = dst = quote = url = "u"
conflict = False
e.answer = lambda question, rows: Pred()
out = e._answer_from_rows("which office?", [Row()])
assert out["value"] == "Socialist International", out["value"]
print("ok: _answer_from_rows boundary cleans the value")
if __name__ == "__main__":
test_row_id_suffix_stripped()
test_cited_from_rows_gloss_stripped()
test_list_gloss_stripped()
test_legitimate_parentheticals_survive()
test_unknown_and_empty_untouched()
test_idempotent_and_mid_value_citations()
test_answer_from_rows_boundary()
print("\nvalue_clean: 7/7 ok")