Files
floop/code/knowledge/RESEARCH-semantic-kg.md
T
onibot 262f40b981 research: his ruling on the dspy cache (--no-cache, not a bug) + the implementation plan
- RESEARCH-semantic-kg: measurement note reworded per his call — the
  disk cache is caching doing its job; --no-cache CLI flag for test
  runs, default unchanged.
- RESEARCH-derived-answers: the 5-phase plan appended (hygiene →
  taxonomy → temporal → prover → consumers), open decisions listed
  (DSL vocabulary, order primitives placement, translator location).
  Awaiting his approval; no code.
2026-10-25 15:41:03 +01:00

11 KiB
Raw Blame History

RESEARCH: semantic KG retrieval + question-blind extraction

Status: RESEARCH BRANCH (research/semantic-kg). Parkable by design — if this direction stalls or gets us lost, we shelve it and continue from main with the other experts or the pending backtracking design.

Opened: 2026-10-22, after his local qwen run.

The trigger (his report)

Local run on "Who was the President before Pedro Sanchez?":

  • INIT fine (he LIKES the 3-subquestion shape: presidency-of-what / term-start / predecessor — the date subq may be unnecessary but is not wrong).
  • The auditor flagged NO ambiguity. The KG came back "Spain" after a long search — the PSOE/Socialist International readings never surfaced.
  • The term-start question answered "15" — not a date — making the predecessor question unclear downstream.

Root cause (his diagnosis, agreed)

The EXTRACTOR is question-conditioned: it sees "extract facts that help answer the question". That filter acts BEFORE the ablation audit can see anything: the KG only holds the reading the question preferred. The alternative readings never entered the store — no audit can recover signal that was never ingested. Same class as the run-L interleaved quotes, but one level deeper: not "the mask ate too much", but "the rows were never extracted".

The redesign (his proposal)

  1. QUESTION-BLIND EXTRACTION. The extractor must NOT know the question. It knows only the ENTITIES for which it seeks relations/facts. Per extracted chunk (or per document end), we check whether the extracted relations can contain the answer.

  2. SEMANTIC RETRIEVAL — not string matching of relations, not an LLM. Embedding distance of facts against the question: a semantic search of the question in the KG. (kg probe becomes: nearest edges by embedding, threshold τ.)

  3. STOP_TABLE MOVES TO SKIM. The extractor's side-duty (deciding a table cannot contribute) moves to the skim pass, where it needs an LLM call: for long tables, given header + first rows, decide whether the table plausibly holds useful info. Fires BEFORE any extraction spend, once per table — instead of burning one extract call to discover the same thing.

Agreed refinements (this session, not yet his-blessed)

  • Embedding distance is the CHEAP GATE; the JUDGE (AnswerFromKG) stays LLM, called ONCE per question when retrieval says so — not per chunk as today. Semantic hit ≠ answer: "PM since 2018" sits near "When did his term begin?" but the 2018 must be READ from the fact, not from the distance. (LLMs propose/judge; retrieval is deterministic math.)
  • Keyword probe stays as OFFLINE FALLBACK (gateways do go down).
  • Extraction per (document, entities) is CACHEABLE across questions: the KG fattens with neutral facts and later questions on the same entities get cheap runs. Aligns with his roadmap (article cache + index). The fat KG is the point — active, reusable memory.

Open questions (park if we can't resolve them)

  • Early exit vs completeness: neutral extraction processes more per chunk; ambiguity usually declares in the intro paragraph, but a late-chunk reading can still be cut by an early exit. Options: keep early exit (start here), exit only after the first full document, or audit-directed fetching.
  • Volume: per-entity extraction ingests much more (birth, marriage, career...). Needs a per-chunk fact cap. Ingest growth is accepted (the fat KG is the point) but must stay bounded per run.
  • Embedding model: configurable endpoint (local ollama, e.g. bge-m3); vectors stored in the KG keyed by (model, text hash) so switching models invalidates cleanly. At hundreds of edges, numpy brute force suffices — no vector DB.
  • DATE answer type: "term-start" answered "15" and the dependent question became unclear. Proposal: AnswerType.DATE + judge desc + a deterministic looks-like-a-date check that rebuts bare numbers. SMALL and orthogonal — could ship to main independently of this research branch (asked; awaiting his call).

Verification plan (before this branch is mergeable)

  1. Unit: embedding client + cosine ranking over a fixture KG; τ chosen so the Pedro fixtures rank the three office readings above the career noise.
  2. Integration (scripted extractor, no network): the run-L paragraph yields ALL THREE readings under question-blind extraction; the audit flags 2 alternatives (the fix the dst-first mask never fully got).
  3. Live E2E (glm + his qwen): the Pedro question flags the ambiguity; the rivers question stays green (regression guard); judge calls per question drop to 1 (the "searched a lot" cost).
  4. His log (pending): confirm which rung died in the local run — extractor filtered the rows / probe never surfaced them / judge saw them and was strict. The redesign fixes the first two BY DESIGN; the third (strictness with "as President") lives in the judge by agreement.

Findings from the live E2E (23/10, glm-5.3-flash, this branch)

  • MACHINERY LIVE AND WORKING: semantic probe fires ("+1 edges the lexical probe missed"), blind extractor ingests fat entity facts (12-fact chunks), vectors cache, hybrid dedup clean, table skim runs.
  • PEDRO RUN — a reading trap, NOT a retrieval failure: the KG held the right facts, but the top search hit was 'Third government of Pedro Sánchez' and the judge answered the LITERAL question: the 3rd government succeeded the 2nd Sánchez government, so "immediately before this term" = Sánchez himself. The Pedro Sánchez article (with the Rajoy motion-of-no-confidence sentence) was in the fetch order but the early exit at the first article starved it. ALSO: INIT returned garbage this run ("no parseable subquestions from 3 chars") and the honest degrade routed the ORIGINAL question — worked, but the INIT raw should be watched (model flakiness, not code).
  • RIVERS RUN — BUDGET DEATH BY FAN-OUT, not by this PR: the Q1 LIST path worked perfectly (22 members ingested from the right table). But the planner expanded 'length of each' into 22 entity questions and EVERY child paid ROUTE + answer_kg (44 calls) for data the parent's table already held; the join (top-3) never ran. Fix candidates (machine-level, next on this branch): (a) fan-out children inherit the parent's engine (zero ROUTE), (b) the fan-out attribute question checks the KG first (the LIST ingest usually wrote the members as edges), (c) cap entity questions per fan-out.
  • COST NOTE: question-blind extraction is slower per chunk (more facts ingested, each vector-cached: one HTTP call per edge at ingest — batching pending). No 22k-char hangs, no STOP confusion, logs clean.

What stays untouched

  • The mask/ablation audit (dst-first law, run-L fix) — it gains signal.
  • Anonymization before INIT (PR-16/17) — orthogonal.
  • The branching design — still pending discussion; this branch may feed it better questions, but does not implement it.

Findings from the live A/B and the (K5) bug (24–25/10, glm-5.3-flash)

The A/B he asked for (his question, cold KG both sides, dspy disk cache deleted per run):

  • glm-5.3-flash (cloud, cold KG): Rajoy, correct, 28 calls, 148 s.
  • qwen3.8-27b (his PC via the house router, cold KG): honest UNKNOWN, 33 calls, 3,025 s. The KG HELD Rajoy (K12 "Rajoy recommended Sánchez as his successor") — the judge lost it to a noise row ("ninth president of Socialist International" made it read "that specific presidency" as the SI).
  • Warm-KG glm answered "Sánchez himself" (the third-succeeded-second reading trap). Substrate state weighs as much as the model.
  • Cloud is non-deterministic at temperature 0: identical INIT prompt, two different decompositions (2 vs 3 subquestions) across runs.
  • MEASUREMENT NOTE (both A/B sides): dspy.LM defaults cache=True and persists to ~/.dspy_cache ACROSS processes and days, keyed on the request (model+prompt+params, not base_url). A repeated question is a byte-identical REPLAY wearing inference's clothes (0.4 s "runs"). Proven by curl (server does not cache) and by running the whole app in an isolated netns (unshare -rn) — it completed with no network. HIS RULING (25/10): NOT a bug — caching doing its job; the CLI gains a --no-cache flag for test runs, the default stays. Until that flag exists: rm -rf ~/.dspy_cache before any run that must be fresh.

The (K5) bug — the audit's silent death (run 085457):

  • glm answered Q1 ("which country or organization was he President of?") with value="Socialist International (K5)" — the row-id glued to the value, because AnswerFromKG says "cite rows by id" but has NO citation output field. The judge sees K{i} ids (positional enumerate indices over the probe's view — NOT store keys), so it cites in the only field it has.
  • _audit_ambiguity's _carries looks for the value inside row dsts: "socialist international (k5)" is in no dst → support = [] → "the judge invented it: nothing to ablate" → silent return. The audit never runs. Repro on the warm KG: raw value → no audit; cleaned value ("Socialist International") → ambiguous=True with Spain alternatives (two rounds). The detector works; the interface kills it. Value contamination is systematic with glm-5.3-flash, three observed shapes: "(K5)" suffix, parenthetical reasoning ("2018 (Pedro Sánchez has been Prime Minister … cited from rows K16 and K30)"), and a DATE question answered "15 (list of 15 members: …)" via the LIST path.
  • SECOND violation: pred.value.strip() enters the evidence payload untyped — "typed payloads, never LLM prose" broken at the same spot.
  • FIX DIRECTION (agreed, not yet coded): clean at the judge's output boundary (_answer_from_rows), regex-anchored to trailing row-citation shapes only ( "(PSOE)" inside a name is legitimate and must survive).

Run 090402 — the branch's own machinery, live and green:

  • Semantic probe live via VPS-local nomic-embed-text (his PC was down; the house router had cloud-failovered and ollama.com has NO embeddings API — same model pulled locally, identical vectors, tau=0.45 calibration holds). "+9/+11 edges the lexical probe missed" on both subquestions; final Rajoy correct.
  • 0 AMBIGUOUS is CORRECT for this run: INIT decomposed to 2 subqs (term-start → predecessor) and never asked "of what", so no scalar answer ever faced the three readings. The ambiguity needs either the "of what" subquestion or the conflicts-table signal (below).
  • INFRA PITFAL: the code venv carries an editable-install pth that pins imports to MAIN's tree — a PYTHONPATH shim that imported knowledge.expert silently resolved to main and ran main's pipeline inside the branch worktree (run 085457 was main code with the branch's config; its "compose -> queries" line is main's deterministic composer). Always assert the resolved module path when running branch code with the shared venv.

The conflicts inventory (20 pairs in the live KG, ZERO real contradictions): 10 same-quote "called for" (co-asserted conjunction, one platform sentence split into 5 triples), 5 cross-quote "called for" (a multi-valued relation), 3 "position held" (THE THREE PRESIDENCIES, pairwise — the polisèmia sitting in the store since ingest), 1 "became" (temporal: 2014 vs 2018 live in the quotes, ref_date empty), 1 "re-elected as" (entity-diff PSOE/PM). The taxonomy, the temporal representation, and the answer engine that consumes all of this are designed in RESEARCH-derived-answers.md (this branch, same session).