From 985aec2f60b45e3e13900aaaebd3418c35b23d3b Mon Sep 17 00:00:00 2001 From: Onibot Date: Sun, 25 Oct 2026 20:00:34 +0100 Subject: [PATCH] =?UTF-8?q?Phase=200=20=E2=80=94=20judge=20value=20cleanup?= =?UTF-8?q?=20+=20--no-cache=20+=20import=20assert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- code/floop/llm.py | 9 ++- code/knowledge/expert.py | 41 +++++++++- code/knowledge/extract.py | 3 +- code/knowledge/tests/value_clean.py | 114 ++++++++++++++++++++++++++++ code/run_app.py | 39 +++++++++- 5 files changed, 200 insertions(+), 6 deletions(-) create mode 100644 code/knowledge/tests/value_clean.py diff --git a/code/floop/llm.py b/code/floop/llm.py index 6226bb1..4cd733f 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -171,9 +171,14 @@ _STAGE_BY_MODULE = { } -def configure_lm() -> dict: +def configure_lm(no_cache: bool = False) -> dict: """Configure dspy's default LM from config.yaml + FLOOP_LM env override. + no_cache=True builds the LM with dspy's response cache DISABLED for this + process (his ruling 25/10: the cache is caching doing its job — the + default stays cache=True; the flag exists for A/B and freshness testing + so a repeated question is a real run, not a byte-identical replay). + Returns the active provider settings (for provenance logs). """ cfg = _load_yaml()["lm"] @@ -190,6 +195,8 @@ def configure_lm() -> dict: "temperature": p["temperature"], "api_key": os.environ.get(p.get("api_key_env", ""), "empty"), } + if no_cache: + kwargs["cache"] = False lm = dspy.LM(**kwargs) global _ACTIVE _ACTIVE = lm diff --git a/code/knowledge/expert.py b/code/knowledge/expert.py index f471183..c1f048d 100644 --- a/code/knowledge/expert.py +++ b/code/knowledge/expert.py @@ -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), diff --git a/code/knowledge/extract.py b/code/knowledge/extract.py index 63da75f..fa685ef 100644 --- a/code/knowledge/extract.py +++ b/code/knowledge/extract.py @@ -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") diff --git a/code/knowledge/tests/value_clean.py b/code/knowledge/tests/value_clean.py new file mode 100644 index 0000000..94a2511 --- /dev/null +++ b/code/knowledge/tests/value_clean.py @@ -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") \ No newline at end of file diff --git a/code/run_app.py b/code/run_app.py index cb27486..7d18254 100644 --- a/code/run_app.py +++ b/code/run_app.py @@ -4,6 +4,7 @@ uv run run_app.py "Per què el cel és blau?" # log only uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison) + uv run run_app.py --no-cache "..." # dspy response cache OFF for this run FLOOP_LM=ollama-cloud uv run run_app.py "..." Always: runs/-/run.log written with flush -> `tail -f` it from another @@ -42,27 +43,59 @@ def run_baseline(question: str, streams: RunStreams) -> str: return answer +def _assert_local_imports(code_dir: Path) -> None: + """Abort loudly if floop/knowledge resolve OUTSIDE this repo's tree. + + The shared venv carries an editable-install .pth pointing at another + checkout, and a poisoned PYTHONPATH (shim importing knowledge.* first) + pins SUBMODULES to another tree even when the package __path__ lists + this one — a namespace package recomputes __path__ dynamically, so + checking the package proves nothing (run 085457, 25/10: main's pipeline + ran inside the branch worktree with zero signal). Check the FILES the + run actually executes. A wrong import tree invalidates the run; refuse + it, don't log it. + """ + root = str(code_dir.resolve()) + for name, relpath in (("floop", "machine.py"), ("floop", "llm.py"), + ("knowledge", "expert.py"), ("knowledge", "store.py")): + try: + mod = __import__(f"{name}.{relpath[:-3]}", fromlist=[""]) + except ImportError as e: # pragma: no cover — broken install, abort anyway + raise SystemExit(f"ABORT: cannot import {name}.{relpath[:-3]}: {e}") + loaded = str(Path(mod.__file__).resolve()) + if not loaded.startswith(root): + raise SystemExit( + f"ABORT: module '{name}.{relpath[:-3]}' resolved outside this repo\n" + f" repo: {root}\n" + f" loaded: {loaded}\n" + "The venv's editable .pth or PYTHONPATH shadows this tree — " + "the run would test the WRONG code. Fix sys.path and retry.") + + def main() -> None: args = sys.argv[1:] verbose = "--verbose" in args baseline = "--baseline" in args - args = [a for a in args if a not in ("--verbose", "--baseline")] + no_cache = "--no-cache" in args + args = [a for a in args if a not in ("--verbose", "--baseline", "--no-cache")] if not args: print(__doc__) sys.exit(1) question = " ".join(args) code_dir = Path(__file__).resolve().parent + _assert_local_imports(code_dir) # the editable-pth trap: wrong tree = invalid run cfg = yaml.safe_load((code_dir / "config.yaml").read_text()) b = cfg["budget"] budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"], max_retries=b["max_retries"], missing_extensions=b["missing_extensions"], min_child_budget=b["min_child_budget"]) - lm_info = configure_lm() + lm_info = configure_lm(no_cache=no_cache) streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs") install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt - streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}") + streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} " + f"baseline={baseline} no_cache={no_cache}") if baseline: answer = run_baseline(question, streams) -- 2.55.0