Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
262f40b981 | ||
|
|
9cfc068ad6 | ||
|
|
0f5a3f4ceb | ||
|
|
30d0a48f7a | ||
|
|
522341a1f3 | ||
|
|
872d4b9d42 | ||
|
|
1a4f25bc84 | ||
|
|
86b444391d | ||
|
|
aabacf8c44 | ||
|
|
ca60442570 | ||
|
|
cc1eceb720 | ||
|
|
4766b47127 | ||
|
|
56e3b22bbf | ||
|
|
0ed26d3406 | ||
|
|
4301277ccd | ||
|
|
c257e9fe88 | ||
|
|
12a1ffd77f | ||
|
|
65d42d1942 | ||
|
|
ce028b6973 | ||
|
|
a6453b0cb3 | ||
|
|
66e8bd4daa | ||
|
|
c3d1b5d6d3 | ||
|
|
f953778f0a | ||
|
|
c7bd010f47 | ||
|
|
2a515795e5 |
@@ -0,0 +1,342 @@
|
||||
# RESEARCH: derived answers — conflicts, time, and a prover instead of a judge
|
||||
|
||||
Status: RESEARCH BRANCH (research/semantic-kg). Design doc, not code.
|
||||
Opened: 2026-10-25, from the conflicts inventory + the (K5) session (see
|
||||
RESEARCH-semantic-kg.md, "Findings from the live A/B and the (K5) bug").
|
||||
|
||||
Scope note: this spans more than knowledge/ — the conflict taxonomy and the
|
||||
temporal layer live in the store (knowledge/), the extractor vocabulary in
|
||||
the pipeline (knowledge/), but the derived-answer engine replaces the
|
||||
AnswerFromKG judge inside the loop and talks to the machine, INIT and the
|
||||
evidence table (floop/). Hence the doc lives at code/ level.
|
||||
|
||||
The three findings this design grows from (all measured, live):
|
||||
|
||||
1. 20 conflict pairs in the KG after one Pedro run, ZERO real
|
||||
contradictions — the 4-case classifier conflates conjunction,
|
||||
paraphrase, temporal succession, and genuine polisèmia.
|
||||
2. The (K5) bug: the judge is the last place where an LLM DECIDES inside
|
||||
the loop, and its interface bugs (value contamination) silently kill
|
||||
the ambiguity audit. Multi-binding ambiguity is a SET question; a
|
||||
judge forced to return ONE value is the wrong instrument for it.
|
||||
3. The three-presidency ambiguity is detectable deterministically at
|
||||
ingest (the conflicts table holds it pairwise), yet the system only
|
||||
hears about it through an expensive, fragile judge-time audit.
|
||||
|
||||
## Part 1 — the conflict taxonomy (merge-time, deterministic)
|
||||
|
||||
Four buckets replace the single "contradiction" case. Ordered by signal
|
||||
cost; each pair falls into the FIRST bucket whose signal it matches.
|
||||
|
||||
### A. co-asserted (same quote_id)
|
||||
|
||||
Both values come from the SAME verbatim quote. A trusted source asserting
|
||||
A and B in one sentence means the world holds A and B: conjunction, not
|
||||
conflict. Kills the 10 same-quote "called for" pairs on provenance alone.
|
||||
Zero extra machinery: quote_id is already an edge column.
|
||||
|
||||
### B. temporal succession
|
||||
|
||||
Dates are stated in the text (inside the dst or the quote: "since YYYY",
|
||||
"in YYYY", "from X to Y") but ref_date is empty, so _classify never sees
|
||||
them. With the temporal layer (Part 2), windows are extracted at ingest
|
||||
and the classification is interval arithmetic: disjoint windows →
|
||||
succession (the "became" pair: Leader-of-Opposition in 2014, prime
|
||||
minister in 2018). Overlapping windows → they coexist → bucket C.
|
||||
Backfill: for existing conflicting pairs with empty windows, one
|
||||
targeted re-extraction pass over their quotes (bounded by the conflict
|
||||
count, not the corpus).
|
||||
|
||||
### C. alternatives (the polisèmia)
|
||||
|
||||
Different facts, co-true, from different discriminant entities. The
|
||||
signal chain, all deterministic:
|
||||
|
||||
- discriminant-token analysis: the two values differ not just in
|
||||
order/articles/parenthetical expansions → not a paraphrase;
|
||||
- tail resolution: the institution tails resolve to DIFFERENT nodes
|
||||
("prime minister of Spain" vs "Secretary-General of the PSOE") —
|
||||
same store lookup/stemming the lexical probe already uses;
|
||||
- value type: dst is an entity NAME (not a date/quantity) → the
|
||||
relation is multi-valued by nature (a person holds many positions);
|
||||
dst is a date for a date-like relation → functional → only one value
|
||||
can be true → bucket D;
|
||||
- functionality statistics: per-relation multi-value rate over the
|
||||
growing store (date_of_birth never multi, position held often
|
||||
multi) — an oracle of functionality earned by scale. Cold-store
|
||||
fallback: type logic + co-assertion.
|
||||
|
||||
THE THREE PRESIDENCIES are the type case: pairwise position-held
|
||||
conflicts whose tails resolve to Spain / PSOE / SI. This bucket IS the
|
||||
ambiguity substrate: what the ablation audit re-derives at judge-time
|
||||
(re-asking an LLM per round) is already known here at ingest-time. The
|
||||
flag, not the choice — the alternatives are served to whoever asks.
|
||||
|
||||
### D. real contradiction
|
||||
|
||||
Same src + functional rel + incompatible values, none of the above
|
||||
applies. Two different birth dates. The honest conflict-exposed state of
|
||||
the current design — expected to be RARE (none in the live inventory).
|
||||
|
||||
### Paraphrase → merge (pre-bucket check)
|
||||
|
||||
Before bucketing: same discriminant-free surface (modulo order,
|
||||
articles, "(Spanish: …)" expansions) OR both tails resolve to the same
|
||||
node OR both canonicalize to the same Wikipedia redirect target → SAME
|
||||
FACT. Append-only law: merge is an alias/same_as edge, never a delete;
|
||||
the canonical form guides retrieval, both surfaces remain queryable.
|
||||
|
||||
### What embeddings do and do NOT do here
|
||||
|
||||
Cosine measures TOPIC similarity, not fact identity:
|
||||
"Prime Minister of Spain" vs "Prime Minister of France" ~0.9 — different
|
||||
facts; "…of Spain" vs "president of the Government (Spanish: …)" ~0.65
|
||||
— same fact. A cosine threshold would merge France into Spain and miss
|
||||
the real alias. Embeddings CONFIRM and RANK inside a bucket (best merge
|
||||
candidate first); they never decide the bucket. The curated-semantics
|
||||
channel is Wikipedia's redirect graph (already fetched, redirects=1) —
|
||||
canonicalization grounded in a trusted source, not model weights. Same
|
||||
law as everywhere else in floop: deterministic signals decide; the model
|
||||
never does.
|
||||
|
||||
## Part 2 — time on the KG
|
||||
|
||||
### Representation
|
||||
|
||||
- Edge columns (the Wikidata qualifier model): start, end, point,
|
||||
granularity (year/month/day — "since 2022" is the interval
|
||||
[2022, 2023), not a date). valid time (the fact's window) stays
|
||||
distinct from fetched_at (transaction time), as today.
|
||||
- fact_order(edge_a, edge_b, rel, quote_id) with rel ∈ {before, after,
|
||||
concurrent}: ordering BETWEEN facts. Edges are already addressable
|
||||
(integer ids) — reification comes free in a property graph; no fact
|
||||
nodes to materialize.
|
||||
- Open intervals: "since 2018" → end=open. The overlap of two open
|
||||
intervals is PROVABLE coexistence — the polisèmia signal as interval
|
||||
arithmetic (bucket C), per fact, no statistics needed.
|
||||
|
||||
### The extractor's temporal vocabulary — RESTRICTIONS, not labels
|
||||
|
||||
The extractor transcribes what the text COMMITS, as typed optional
|
||||
fields on Fact (the feature/typed-facts BaseModel is the vehicle):
|
||||
|
||||
- order: before / after / concurrent — asserted ONLY when the text has
|
||||
the connective ("abans de", "alhora", "while", "també") and NO dates
|
||||
would let code compute it; quotable, containment-checkable;
|
||||
- duration: quantity + unit (the skim's quantity regex already knows);
|
||||
- anchor: start/end → date | event-node ("fins que va dimitir de A"
|
||||
anchors F1's end to an EVENT, not a date — events are addressable
|
||||
nodes, dates resolve later by propagation);
|
||||
- immediacy: bool ("l'endemà", "fins que").
|
||||
|
||||
Full Allen algebra is a COMPUTED VIEW, not an extraction target: with
|
||||
endpoints extracted, overlaps/during/starts/finishes/meets are endpoint
|
||||
arithmetic in the store. The text CAN carry the full gamut ("president
|
||||
of A and B at the same time for a month until he resigned from A") but
|
||||
what it carries is three RESTRICTIONS (concurrent F1–F2, duration 1
|
||||
month, F1.end anchored to the resignation event) — asking the model to
|
||||
also CHOOSE an Allen label would (a) replace transcription with
|
||||
classification, (b) produce labels with no quotable connective to check
|
||||
against, (c) create a second channel of truth that silently disagrees
|
||||
with the computed one 1% of the time, (d) invite confident labels at
|
||||
granularity the prose lacks. Restrictions are honest (optional fields
|
||||
stay empty when the text is silent), checkable (containment), and they
|
||||
UPDATE: when a later source dates the resignation, the network
|
||||
propagates and the Allen view recomputes itself — a label extracted on
|
||||
day one never would.
|
||||
|
||||
### Check
|
||||
|
||||
Same law as facts: the temporal field must be contained in the quote
|
||||
("2022" not in quote → reject the date; connective absent → reject the
|
||||
order). LLM proposes, code verifies against the source surface.
|
||||
|
||||
## Part 3 — the derived-answer engine (no judge in the loop)
|
||||
|
||||
The end state he steered to: the component that generates the answer is
|
||||
NOT an LLM. The LLMs translate at the two ends (question → logic on the
|
||||
way in; proven object → prose later, outside the loop) and never in the
|
||||
middle. This is the Logic-LM move of the lineage (lm→solver) applied to
|
||||
floop's own layer, and the real prover the v0.1 map always listed as a
|
||||
stub.
|
||||
|
||||
### The query DSL (small, typed)
|
||||
|
||||
The store's atoms are ground, containment-checked rows; floop's
|
||||
answer_type enum is already the type signature. Six operators:
|
||||
|
||||
- lookup: bind a relation with variables — position_held(sanchez, ?o, I)
|
||||
- temporal filter: contains(I, now), end(I_x) ≤ start(I_s) — Allen as
|
||||
computed views over extracted endpoints;
|
||||
- order & selection: latest, max, nth (ranking questions);
|
||||
- set ops: difference/intersection/count (the setop engine exists);
|
||||
- arithmetic composition: typed templates over intervals (the Run T3
|
||||
composition: n_physical = n_logical × ratio);
|
||||
- path: member_of, succeeded, same_as (multi-hop = chaining; the plan's
|
||||
depends_on already encodes hops).
|
||||
|
||||
Not full FOL — a conjunctive + temporal + algebraic fragment with
|
||||
negation only as inequality. Typed: a term that type-checks against the
|
||||
answer_type is valid before any evaluation; a mistranslation surfaces as
|
||||
an invalid term, deterministically. The translator is one LLM call with
|
||||
structured output (the MASK/EXTRACT class — typed, question-local, no
|
||||
goal leakage), validated before execution.
|
||||
|
||||
### Evaluation = proof = the answer object
|
||||
|
||||
Goal-directed evaluation (SLD-style) over the store:
|
||||
|
||||
q(x) :- position_held(sanchez, O, I_s), % his office, window
|
||||
position_held(x, O, I_x), % any holder of the SAME office
|
||||
x ≠ sanchez,
|
||||
end(I_x) ≤ start(I_s), % term ended before his began
|
||||
latest_by(end(I_x)) % the most recent such holder
|
||||
|
||||
Leaves = edge ids (each carries quote + url); steps = one of the six
|
||||
operators; checks = interval arithmetic. The proof term IS the payload:
|
||||
re-execution over the store is the verification — deterministic, no
|
||||
LLM. verified=True stops being the setop's generous flag and gets a
|
||||
real prover; the stop-check becomes "does the goal have a closed path"
|
||||
— the derivability check the _finish stub owes.
|
||||
|
||||
### What the three findings become under this engine
|
||||
|
||||
- Multi-binding IS the ambiguity: "of what is Sánchez president" as
|
||||
position_held(sanchez, ?x, I), contains(I, now) returns THREE
|
||||
bindings (Spain, PSOE, SI), deterministically, each with its proof.
|
||||
The ablation audit becomes redundant for store-derivable rows; the
|
||||
(K5) bug dies at the root — there is no judge to contaminate a value
|
||||
and no single-value pressure. Branches map 1:1 to bindings.
|
||||
- Silence is the failure mode: no closed path → UNKNOWN → the gather
|
||||
runs. The judge's failure mode was a fluent wrong answer (SI with
|
||||
confidence: high).
|
||||
- The unbound variable IS the missing subquestion: when evaluation
|
||||
stalls, the unligated variable names what to go fetch — MISSING
|
||||
becomes semi-deterministic.
|
||||
- Conflicts/alternatives become disjunction: each alternative pair is
|
||||
an OR-node in the proof tree; evaluation branches per reading,
|
||||
preferred picks the default reading, the question can force the
|
||||
others. The polisèmia stops being an internal anomaly and becomes
|
||||
semantic branching of the proof search.
|
||||
|
||||
### Honest limits
|
||||
|
||||
- Soft questions (why/compare/significance) are synthesis over many
|
||||
rows, not queries: they stay LLM-composed — over proven components
|
||||
(proof terms and leaves), not free prose over the store.
|
||||
- The prover does not remove retrieval; it removes the judge inside
|
||||
the loop. Facts absent from the store still need the gather.
|
||||
- same_as/aliases are load-bearing: without the redirect-canonicalized
|
||||
ontology, evaluation fails on vocabulary, not logic ("President of
|
||||
the Government" vs "Prime Minister of Spain").
|
||||
- Cross-granularity comparison needs the year-as-interval convention
|
||||
decided once, not per query.
|
||||
|
||||
### Engine choice
|
||||
|
||||
Hand-written goal-directed evaluator over SQLite first (six operators,
|
||||
proof terms as objects, re-execution as check) — fixed code that
|
||||
reasons, the house law. clingo earns its place if re-decomposition goes
|
||||
declarative (answer sets = readings); Z3 earns it in FUNCTION
|
||||
composition over intervals (Run T3 with certificates). Neither is a
|
||||
dependency for v1 of this.
|
||||
|
||||
## Verification plan (before any of this is mergeable)
|
||||
|
||||
1. Taxonomy unit tests over the live 20-pair inventory as fixtures:
|
||||
every pair lands in its measured bucket (10 co-asserted, 3+1
|
||||
temporal, 3 alternatives, 5 multi-valued co-true, 0 real).
|
||||
2. Temporal: the "became" pair classified succession from quote-stated
|
||||
dates; the three presidencies classified overlapping-open-intervals
|
||||
→ alternatives; no date invented anywhere (empty windows stay empty
|
||||
until a source closes them).
|
||||
3. Extractor restrictions: the month-duration/resignation sentence
|
||||
yields concurrent + duration + event-anchored end with containment
|
||||
checks passing; a date not in the quote is rejected.
|
||||
4. Query engine: the Pedro question proves Rajoy as a closed path with
|
||||
re-execution verifying; "of what" returns the three bindings as a
|
||||
set; the rivers regression stays green; judge LLM calls per
|
||||
knowledge question go to zero on store-derivable paths.
|
||||
5. The K5 repro pair becomes the regression: raw glm-style judge values
|
||||
never exist anymore on proven paths (nothing to clean — the
|
||||
interface is gone, not patched).
|
||||
|
||||
## What this does NOT touch
|
||||
|
||||
- The gather, the skim, the LIST path, setop guard — unchanged.
|
||||
- The ablation audit stays for the one job left to it: readings that
|
||||
are NOT store-derivable (judge-visible ambiguity in free text).
|
||||
- Branching (floop/branches.py) gains a cleaner trigger (a binding set)
|
||||
but its death/merge semantics are untouched.
|
||||
|
||||
## Implementation plan (proposed — awaiting his approval; no code yet)
|
||||
|
||||
Phases ordered by dependency; each closes with tests + live runs.
|
||||
Phase 0 is main-bound and independent of the research direction.
|
||||
|
||||
### Phase 0 — hygiene (main; small, shippable alone)
|
||||
|
||||
1. (K5) fix: clean the judge's value at the output boundary
|
||||
(_answer_from_rows) — regex anchored to TRAILING row-citation shapes
|
||||
("(K5)", "(cited from rows K16 and K30)") so legitimate parentheticals
|
||||
("(PSOE)") survive. Prompt side: value desc gains "answer only, no
|
||||
row citations". Regression = the K5 repro pair (raw value → audit
|
||||
runs and flags the Spain alternative).
|
||||
2. --no-cache CLI flag (his ruling 25/10: the dspy disk cache is not a
|
||||
bug; it stays the default): when set, configure_lm builds dspy.LM
|
||||
with cache=False — a per-process bypass, the cache dir untouched.
|
||||
For A/B and freshness testing.
|
||||
3. Import assert at startup: the resolved floop/ and knowledge/ module
|
||||
paths must be under the repo being run — the shared venv's editable
|
||||
pth pins imports to MAIN's tree and ran main code inside the branch
|
||||
worktree without any signal (run 085457). Abort loudly on mismatch.
|
||||
|
||||
### Phase 1 — conflict taxonomy at merge (this branch, store)
|
||||
|
||||
_classify 4 → 6 cases, signals in cost order: same quote_id →
|
||||
co-asserted (conjunction, never a conflict); extracted windows →
|
||||
temporal (interval arithmetic: disjoint = succession, overlapping =
|
||||
alternatives); discriminant tokens + tail resolution against nodes →
|
||||
alternatives vs paraphrase-merge (merge = same_as edge, append-only);
|
||||
what survives with a functional relation = real contradiction. The
|
||||
edge gains a class field; the alternatives bucket is exposed to the
|
||||
audit and the render. Fixtures: the live 20-pair inventory (10
|
||||
co-asserted, 3+1 temporal, 3 alternatives, 0 real).
|
||||
|
||||
### Phase 2 — temporal layer (this branch, extractor + store)
|
||||
|
||||
Typed Fact (feature/typed-facts vehicle) gains start/end/point/
|
||||
granularity, orders [{before|after|concurrent, refs}], duration,
|
||||
anchor (date | event node), immediacy — every field containment-
|
||||
checked against the quote. Store: edge start/end columns + fact_order
|
||||
table. _classify consumes interval arithmetic. Bounded backfill:
|
||||
re-extract quotes of existing conflicting pairs with empty windows.
|
||||
NO Allen labels anywhere — the algebra stays a computed view.
|
||||
|
||||
### Phase 3 — the query prover (the new core)
|
||||
|
||||
Hand-written goal-directed evaluator over SQLite: six operators
|
||||
(lookup, temporal filter, order/select, setops, arithmetic
|
||||
composition, path), typed DSL, proof term as the payload, re-execution
|
||||
as the check. Translator question→DSL: one structured-output LLM call
|
||||
(MASK/EXTRACT class), validated before execution. Wiring: the prover
|
||||
becomes the real stop-check at machine._finish (derivability);
|
||||
AnswerFromKG stays only as the fallback for non-translatable
|
||||
questions. Regression: Pedro proves Rajoy as a closed path; "of what"
|
||||
returns the three bindings as a set; rivers stay green; judge LLM
|
||||
calls drop to zero on store-derivable paths.
|
||||
|
||||
### Phase 4 — consumers
|
||||
|
||||
The audit reduces to "is the binding set already multi?" (cheap,
|
||||
deterministic) + ablation only for non-derivable readings. The branch
|
||||
fork (floop/branches.py) starts from binding multiplicity. ANSWER and
|
||||
any surviving judge render over proof terms, not free prose.
|
||||
|
||||
### Open decisions (his call, before Phase 3 coding)
|
||||
|
||||
- DSL vocabulary: the translator and the evaluator share one grammar —
|
||||
its exact terms.
|
||||
- Order primitives: inside Fact (same call) vs a separate pass.
|
||||
- Translator location: inside INIT (the decomposition and the query
|
||||
born together) vs a post-INIT step per question.
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Query anonymization before INIT (his design, 22/10): the model must
|
||||
decompose the question's SHAPE, not lean on its knowledge of the people in
|
||||
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
|
||||
...) before INIT sees the query; the placeholders are restored in the
|
||||
returned subquestions — deterministically, by exact string replacement.
|
||||
|
||||
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
|
||||
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class NamedEntity(BaseModel):
|
||||
"""One named entity found in the question."""
|
||||
name: str = dspy.OutputField(
|
||||
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
||||
kind: str = dspy.OutputField(
|
||||
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
||||
|
||||
|
||||
class EntityMaskSignature(dspy.Signature):
|
||||
"""You are the MASK step of a reasoning machine. Find the named entities
|
||||
in the question — people, organizations, places, titles of works, events.
|
||||
Copy each one's text exactly as it appears; do not add entities that are
|
||||
not explicitly named."""
|
||||
question: str = dspy.InputField()
|
||||
entities: list[NamedEntity] = dspy.OutputField(
|
||||
desc="the named entities found; empty when none")
|
||||
|
||||
|
||||
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
||||
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
||||
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
||||
|
||||
|
||||
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
||||
"""Mask the question deterministically. Longer names first (so
|
||||
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
||||
Returns (masked_question, restore_map placeholder -> original)."""
|
||||
restore: dict[str, str] = {}
|
||||
counters: dict[str, int] = {}
|
||||
masked = question
|
||||
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
|
||||
name = ent.name.strip()
|
||||
if not name or name not in masked:
|
||||
continue
|
||||
kind = ent.kind.strip().upper()
|
||||
prefix = _PREFIX.get(kind, "OTHER")
|
||||
counters[prefix] = counters.get(prefix, 0) + 1
|
||||
ph = f"{prefix}_{counters[prefix]}"
|
||||
if ph in restore: # same surface text twice: keep one mask
|
||||
continue
|
||||
masked = masked.replace(name, ph)
|
||||
restore[ph] = name
|
||||
return masked, restore
|
||||
|
||||
|
||||
def restore_mask(text: str, restore: dict[str, str]) -> str:
|
||||
"""Restore placeholders to the original names, longest first (so
|
||||
PERSON_10 is not eaten by PERSON_1)."""
|
||||
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
|
||||
reverse=True):
|
||||
text = text.replace(ph, name)
|
||||
return text
|
||||
|
||||
|
||||
# an identity question about ONE placeholder — the model asking who/what
|
||||
# the mask refers to. Detection lives in identity_answer: conservative
|
||||
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
|
||||
# text names the mask mechanism ('placeholder', 'refer(s) to').
|
||||
|
||||
|
||||
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
||||
"""If a subquestion only asks who/what one placeholder refers to, the
|
||||
answer is the mask map itself — no expert ever needed. None otherwise.
|
||||
|
||||
Conservative by law (never over-detect): exactly one placeholder in
|
||||
the text, and the question is literally 'who/what is <ph>' (ending
|
||||
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
||||
match) or it names the mask mechanism ('placeholder', 'refer(s) to')."""
|
||||
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
||||
masked_text)]
|
||||
if len(phs) != 1:
|
||||
return None
|
||||
ph = phs[0]
|
||||
t = masked_text.strip()
|
||||
literal = re.match(
|
||||
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"'])",
|
||||
t, flags=re.IGNORECASE)
|
||||
mechanism = any(k in t.casefold() for k in
|
||||
("placeholder", "refer to", "refers to"))
|
||||
if literal or mechanism:
|
||||
return restore[ph]
|
||||
return None
|
||||
+136
-26
@@ -7,24 +7,65 @@ Every module's docstring is the draft prompt — kept minimal on purpose.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .state import AnswerType
|
||||
|
||||
try:
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
except ImportError: # pragma: no cover — dspy <3.x
|
||||
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
||||
|
||||
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer,
|
||||
restore_mask)
|
||||
|
||||
|
||||
class Subquestion(BaseModel):
|
||||
"""One open subquestion in the goal's decomposition."""
|
||||
text: str = dspy.OutputField(desc="the subquestion, phrased as a question")
|
||||
depends_on: list[int] = dspy.OutputField(
|
||||
desc="1-based positions of the subquestions whose answers this one needs first; empty when none")
|
||||
answer_type: AnswerType = dspy.OutputField(
|
||||
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
||||
"CONSTANT for a universal constant, LIST for an enumeration of things, "
|
||||
"DATE for a specific date")
|
||||
|
||||
|
||||
class InitSignature(dspy.Signature):
|
||||
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally
|
||||
present in the question plus a generic planning scaffold (number, method,
|
||||
machine, resources, dependencies), ask: what information or knowledge do I
|
||||
need to answer this? Write 1-4 open subquestions in dependency order.
|
||||
Use answer_type LIST when the subquestion asks for an enumeration of
|
||||
things (which countries, what rivers, list all members...)."""
|
||||
"""You are the INIT step of a reasoning machine. Your job is to make the
|
||||
final answer a direct lookup. Follow this procedure:
|
||||
1. Re-read the question and:
|
||||
1.1. List every word or phrase that could refer to more than one
|
||||
real thing or moment.
|
||||
1.2. Think: what information or knowledge do I need to answer this?
|
||||
2. HIDDEN PRECONDITIONS: for every entity, relation, or value that the
|
||||
question assumes but does not state and that is required to answer
|
||||
it (an implicit owner, role, time window, or intermediate fact),
|
||||
write an explicit subquestion that resolves it. NEVER collapse a
|
||||
hidden precondition into the final subquestion. Always use the most
|
||||
generic term to ask about them.
|
||||
3. Write the subquestion that produces the final answer, with
|
||||
depends_on pointing at the preconditions it needs.
|
||||
Order the subquestions by dependency (1-4 in total).
|
||||
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED named
|
||||
entities from the question — treat each as a known specific entity; do not
|
||||
ask what or who the placeholder is."""
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated fields: "
|
||||
"text | depends_on (line numbers or 'none') | answer_type (OPEN|FUNCTION|INTERVAL|CONSTANT|LIST)"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-4 subquestions in dependency order; never empty")
|
||||
|
||||
|
||||
class Attendant(str, Enum):
|
||||
"""The closed set of attendants the ROUTE step may pick."""
|
||||
KNOWLEDGE = "knowledge"
|
||||
LOGIC = "logic"
|
||||
ANALYTIC = "analytic"
|
||||
NUMERIC = "numeric"
|
||||
FLOOP = "floop"
|
||||
USER = "user"
|
||||
|
||||
|
||||
class RouteSignature(dspy.Signature):
|
||||
@@ -33,10 +74,22 @@ class RouteSignature(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
catalog: str = dspy.InputField(desc="experts | floop | user, one per line with a summary")
|
||||
evidence: str = dspy.InputField(desc="relevant evidence rows, may be empty")
|
||||
attendant: str = dspy.OutputField(desc="one of: knowledge logic analytic numeric floop user")
|
||||
attendant: Attendant = dspy.OutputField(
|
||||
desc="knowledge: factual lookups from trusted sources; logic: deriving conclusions "
|
||||
"from provided premises, counting over evidence; analytic: equations/symbolic "
|
||||
"relations over provided quantities; numeric: closed arithmetic over provided "
|
||||
"numbers; floop: needs a sub-goal; user: nothing else plausibly answers it")
|
||||
reason: str = dspy.OutputField(desc="one sentence, for the log")
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""The expert's honest self-assessment (baseline draft — no engine
|
||||
verifies the expert yet)."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class ExpertSignature(dspy.Signature):
|
||||
"""You are an expert attendant answering a small, focused subquestion.
|
||||
Use the evidence rows when they answer it; otherwise answer from your own
|
||||
@@ -50,7 +103,9 @@ class ExpertSignature(dspy.Signature):
|
||||
value: str = dspy.OutputField(desc="the answer value in its declared type, or 'UNKNOWN'")
|
||||
source_quote: str = dspy.OutputField(
|
||||
desc="VERBATIM text from the given evidence if the answer comes from it; EMPTY when answering from your own knowledge")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: the evidence or your knowledge settles it; medium: plausible "
|
||||
"but not fully settled; low: a guess you would verify first")
|
||||
|
||||
|
||||
class MissingSignature(dspy.Signature):
|
||||
@@ -60,9 +115,8 @@ class MissingSignature(dspy.Signature):
|
||||
the evidence."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField(
|
||||
desc="one subquestion per line, pipe-separated: text | depends_on ('none' or #E refs) | answer_type"
|
||||
)
|
||||
subquestions: list[Subquestion] = dspy.OutputField(
|
||||
desc="1-3 subquestions that would close the gap; empty when nothing helps")
|
||||
|
||||
|
||||
class AnswerSignature(dspy.Signature):
|
||||
@@ -72,7 +126,8 @@ class AnswerSignature(dspy.Signature):
|
||||
marks verification status separately, do not hedge about it."""
|
||||
goal: str = dspy.InputField()
|
||||
evidence: str = dspy.InputField()
|
||||
unverified: str = dspy.InputField(desc="'true' if the prover could not verify derivability")
|
||||
unverified: bool = dspy.InputField(
|
||||
desc="True when the prover could not verify the answer's derivability from the evidence")
|
||||
final_answer: str = dspy.OutputField(desc="answer in natural language; cite only given row ids; no outside facts")
|
||||
|
||||
|
||||
@@ -85,22 +140,76 @@ class FloopModules:
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
self.mask = dspy.Predict(EntityMaskSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||
"""(parsed subquestions, raw model output). The machine decides what
|
||||
an empty parse means: empty raw = the question is atomic; non-empty
|
||||
raw that parses to nothing = model garbage (run I) — degrade."""
|
||||
pred = self.init(question=question)
|
||||
raw = pred.subquestions or ""
|
||||
return parse_subquestions(raw), raw
|
||||
raw that parses to nothing = model garbage (run I) — degrade.
|
||||
|
||||
Typed output: a response that violates the Subquestion schema raises
|
||||
AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
|
||||
the raw garbage — hand it back as the degrade signal.
|
||||
|
||||
ANONYMIZATION (his design): named entities are masked before INIT
|
||||
so the model decomposes shape, not identity — restored in the
|
||||
returned subquestions, deterministically. Identity questions about
|
||||
the placeholders (PR-16 live run: 'who is PERSON_1?') carry a
|
||||
KNOWN answer; the machine seeds them as evidence instead of
|
||||
routing them to an expert."""
|
||||
masked, restore = self.anonymize(question)
|
||||
try:
|
||||
pred = self.init(question=masked)
|
||||
except AdapterParseError as e:
|
||||
return [], (e.lm_response or "unparseable response")
|
||||
subs = []
|
||||
for s in self._subs_from_typed(pred.subquestions):
|
||||
# identity detection on the MASKED text (placeholders still
|
||||
# present); then restore for the machine's question text
|
||||
ans = identity_answer(s["text"], restore)
|
||||
text = restore_mask(s["text"], restore)
|
||||
if ans is not None:
|
||||
s = {**s, "known_answer": ans} # seeded by the machine
|
||||
subs.append({**s, "text": text})
|
||||
return subs, ""
|
||||
|
||||
def anonymize(self, question: str) -> tuple[str, dict]:
|
||||
"""Mask named entities to typed placeholders. No entity found (or the
|
||||
mask call dies) -> the question passes unchanged, mask map empty."""
|
||||
try:
|
||||
pred = self.mask(question=question)
|
||||
entities = pred.entities or []
|
||||
except AdapterParseError:
|
||||
return question, {}
|
||||
masked, restore = apply_mask(question, entities)
|
||||
return masked, restore
|
||||
|
||||
@staticmethod
|
||||
def _subs_from_typed(subs) -> list[dict]:
|
||||
"""Typed Subquestion objects -> machine dicts. A bare number is a
|
||||
line number, never a question (run I law kept)."""
|
||||
out = []
|
||||
for s in (subs or []):
|
||||
text = (s.text or "").strip()
|
||||
if not text or text.isdigit():
|
||||
continue
|
||||
out.append({"text": text, "deps": list(s.depends_on or []),
|
||||
"answer_type": s.answer_type})
|
||||
return out
|
||||
|
||||
def missing_decompose(self, goal: str, evidence: str) -> list[dict]:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
return parse_subquestions(pred.subquestions)
|
||||
try:
|
||||
pred = self.missing(goal=goal, evidence=evidence)
|
||||
except AdapterParseError:
|
||||
return []
|
||||
return self._subs_from_typed(pred.subquestions)
|
||||
|
||||
def route_question(self, question: str, catalog: str, evidence: str) -> tuple[str, str]:
|
||||
"""Typed attendant: the enum is the closed contract. A response
|
||||
outside the set raises AdapterParseError after dspy's re-ask —
|
||||
the machine's invalid-attendant branch stays as a contract guard."""
|
||||
pred = self.route(question=question, catalog=catalog, evidence=evidence)
|
||||
return pred.attendant.strip().lower(), pred.reason.strip()
|
||||
return str(pred.attendant.value), pred.reason.strip()
|
||||
|
||||
def expert_draft(self, question: str, expert_kind: str, evidence: str,
|
||||
parent_question: str = "") -> dict:
|
||||
@@ -109,11 +218,12 @@ class FloopModules:
|
||||
return {
|
||||
"value": pred.value.strip(),
|
||||
"source_quote": pred.source_quote.strip(),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
|
||||
def synthesize(self, goal: str, evidence: str, unverified: bool) -> str:
|
||||
pred = self.answer(goal=goal, evidence=evidence, unverified="true" if unverified else "false")
|
||||
pred = self.answer(goal=goal, evidence=evidence,
|
||||
unverified=unverified)
|
||||
return pred.final_answer.strip()
|
||||
|
||||
|
||||
@@ -159,4 +269,4 @@ def parse_subquestions(raw: str) -> list[dict]:
|
||||
deps.append(int(tok)) # sibling line number, resolved by the machine
|
||||
atype = next((t for t in AnswerType if t.value == atype_raw), AnswerType.OPEN)
|
||||
out.append({"text": text, "deps": deps, "answer_type": atype})
|
||||
return out
|
||||
return out
|
||||
|
||||
@@ -156,6 +156,7 @@ _STAGE_BY_MODULE = {
|
||||
"Expert": "EXPERT",
|
||||
"Missing": "MISSING",
|
||||
"Answer": "ANSWER",
|
||||
"EntityMaskSignature": "MASK",
|
||||
"KnowledgeExpert": "knowledge",
|
||||
"InitSignature": "INIT",
|
||||
"RouteSignature": "ROUTE",
|
||||
@@ -168,6 +169,7 @@ _STAGE_BY_MODULE = {
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
"SkimPromoteSignature": "PROMOTE",
|
||||
"SkimTableSignature": "SKIM_TABLE",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,16 @@ from .stream import RunStreams
|
||||
|
||||
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
|
||||
|
||||
_YEAR_RE = re.compile(r"\b(?:1[5-9]\d{2}|20\d{2}|2[1-9]\d{2})\b") # 1500–2999
|
||||
|
||||
|
||||
def _looks_like_date(v: str) -> bool:
|
||||
"""Deterministic DATE admission: the value must carry a plausible
|
||||
year (1500-2999). '2 June 2018', 'June 2018', '2018' pass; a bare
|
||||
'15' — or a month name alone — is NOT a date and must never
|
||||
satisfy a DATE question (his 22/10 local run)."""
|
||||
return bool(_YEAR_RE.search(v or ""))
|
||||
|
||||
|
||||
def _fmt_num(x: float) -> str:
|
||||
"""Deterministic number formatting for computed rows: integers plain,
|
||||
@@ -192,6 +202,20 @@ class FloopRun:
|
||||
if isinstance(tok, int) and 1 <= tok <= len(created):
|
||||
resolved.append(created[tok - 1].qid)
|
||||
q.deps = resolved
|
||||
# anonymization seeds (his design): identity questions the mask map
|
||||
# already answers land as evidence NOW — zero LLM calls
|
||||
for q, s in zip(created, subs):
|
||||
if s.get("known_answer"):
|
||||
self.table.append(EvidenceRow(
|
||||
qid=q.qid, answer_type=q.answer_type,
|
||||
payload={"value": s["known_answer"],
|
||||
"quote": f"{s['known_answer']} — named in the question itself"},
|
||||
engine="mask:seed", trace=["anonymization: placeholder resolved from the mask map"],
|
||||
provenance={}, verified=True))
|
||||
q.status = "answered"
|
||||
q.reason = "identity seeded from the mask map"
|
||||
self.notes.append(
|
||||
f"{q.qid}: seeded from anonymization — no expert call needed")
|
||||
|
||||
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
||||
|
||||
@@ -465,6 +489,16 @@ class FloopRun:
|
||||
# fan-out bookkeeping: entity rows carry the group so the join finds them
|
||||
if q.fan_group:
|
||||
row.provenance["fan_group"] = q.fan_group
|
||||
# DATE type check (his 22/10 local run: term-start answered '15'):
|
||||
# deterministic — a DATE value must carry a year; bare numbers
|
||||
# are not dates and must never satisfy a DATE question
|
||||
if q.answer_type == AnswerType.DATE:
|
||||
v = str(row.payload.get("value", ""))
|
||||
if not _looks_like_date(v):
|
||||
self.notes.append(
|
||||
f"{q.qid}: DATE answer rejected (no year): {v[:60]!r}")
|
||||
row.payload["value"] = "UNKNOWN"
|
||||
row.payload["note"] = "rejected: DATE without a year"
|
||||
# PR-3: skim notices also land in the run notes — legibility law:
|
||||
# derived answers render CONTENT, not counts alone
|
||||
for n in (row.payload.get("skim") or [])[:2]:
|
||||
|
||||
@@ -20,6 +20,7 @@ class AnswerType(str, Enum):
|
||||
INTERVAL = "INTERVAL"
|
||||
CONSTANT = "CONSTANT"
|
||||
LIST = "LIST"
|
||||
DATE = "DATE"
|
||||
|
||||
|
||||
class BudgetExhausted(Exception):
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Embedding client for semantic KG retrieval (research/semantic-kg).
|
||||
|
||||
Config: local ollama /api/embed (nomic-embed-text, 768d) — the only
|
||||
proven endpoint (ollama.com has NO embeddings API: 404 on /v1/embeddings,
|
||||
401 on /api/embed). Failure is honest: embed() raises EmbedderDown, the
|
||||
expert degrades to the lexical probe (law: offline fallback, never a
|
||||
dead run). No API keys in code.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_MODEL = "nomic-embed-text:latest"
|
||||
DEFAULT_URL = "http://127.0.0.1:11435/api/embed"
|
||||
|
||||
|
||||
class EmbedderDown(Exception):
|
||||
"""The embedding endpoint is unreachable or misbehaving — the caller
|
||||
degrades to the lexical probe (offline fallback law)."""
|
||||
|
||||
|
||||
def embed(texts: list[str], model: str = DEFAULT_MODEL,
|
||||
url: str = DEFAULT_URL, timeout: int = 60) -> list[list[float]]:
|
||||
"""Batch-embed texts via ollama /api/embed. Raises EmbedderDown on any
|
||||
transport/format error — honest failure, never fabricated vectors."""
|
||||
texts = [t or " " for t in texts]
|
||||
if not texts:
|
||||
return []
|
||||
payload = json.dumps({"model": model, "input": texts}).encode()
|
||||
req = urllib.request.Request(
|
||||
url, data=payload, headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
data = json.load(r)
|
||||
except Exception as e: # noqa: BLE001 — one honest exception type
|
||||
raise EmbedderDown(f"{url}: {e}") from e
|
||||
vecs = data.get("embeddings")
|
||||
if not vecs or len(vecs) != len(texts):
|
||||
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
||||
f"{len(vecs) if vecs else 0}")
|
||||
return vecs
|
||||
|
||||
|
||||
def cosine(a: list[float], b: list[float]) -> float:
|
||||
"""Plain cosine — at hundreds of edges numpy brute force is not worth
|
||||
the dependency."""
|
||||
dot = sum(x * y for x, y in zip(a, b))
|
||||
na = sum(x * x for x in a) ** 0.5
|
||||
nb = sum(y * y for y in b) ** 0.5
|
||||
if na == 0 or nb == 0:
|
||||
return 0.0
|
||||
return dot / (na * nb)
|
||||
+201
-105
@@ -1,16 +1,21 @@
|
||||
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
||||
|
||||
Per question (one routed knowledge call):
|
||||
1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap]
|
||||
2. KG PROBE: lexical seed match + BFS depth-1 [engine]
|
||||
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
||||
4. FETCH top articles, CHUNK by sections [engine]
|
||||
5. EXTRACT per chunk (map) with verbatim spans [LLM]
|
||||
6. CHECK: containment in FULL text + well-formedness [engine]
|
||||
7. MERGE into the store: corroboration / conflicts / supersession [engine]
|
||||
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
|
||||
1. TRANSLATE: question -> search queries + resolved entities [LLM, cheap]
|
||||
2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine]
|
||||
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
||||
4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which
|
||||
tables deserve extraction (identity + first rows, BEFORE spend)[LLM, 1/page]
|
||||
5. EXTRACT per chunk (map), QUESTION-BLIND (entities only) [LLM]
|
||||
6. CHECK: containment in FULL text + well-formedness [engine]
|
||||
7. MERGE into the store: corroboration / conflicts / supersession
|
||||
+ vector cache for the semantic probe [engine]
|
||||
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
|
||||
|
||||
Laws: no quote, no edge; no edge, no answer. Every step logged via RunStreams.
|
||||
Laws: no quote, no edge; no edge, no answer. The extractor never sees the
|
||||
question (research/semantic-kg): it transcribes facts about ENTITIES — the
|
||||
question lives in retrieval (skim/ranking/probe) and the judge only.
|
||||
Every step logged via RunStreams.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -25,11 +30,12 @@ from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
|
||||
SkimPromoteSignature, TranslateSignature,
|
||||
VerifyCountSignature)
|
||||
SkimPromoteSignature, SkimTableSignature,
|
||||
TranslateSignature, VerifyCountSignature)
|
||||
from .embeddings import EmbedderDown, embed
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag, parse_stop_table)
|
||||
tables_as_chunks, format_table_frag)
|
||||
|
||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||
|
||||
@@ -116,6 +122,12 @@ class KnowledgeConfig:
|
||||
skim_harvest: bool = True # opportunistic typed ingestion, zero LLM
|
||||
skim_harvest_max_tables: int = 2 # per article, beyond the LIST answer
|
||||
skim_link_queue: bool = True # goal-region links join the fetch order
|
||||
# semantic retrieval (research/semantic-kg)
|
||||
embed_url: str = "http://127.0.0.1:11435/api/embed"
|
||||
embed_model: str = "nomic-embed-text:latest"
|
||||
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
||||
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
||||
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
||||
|
||||
|
||||
class KnowledgeExpert:
|
||||
@@ -134,8 +146,13 @@ class KnowledgeExpert:
|
||||
self.select_table = dspy.Predict(SelectTableSignature)
|
||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
||||
self.skim_tables = dspy.Predict(SkimTableSignature)
|
||||
self._checked = 0
|
||||
self._merged = 0
|
||||
# semantic probe: cached question vector for this call (the probe
|
||||
# runs after every ingest; embedding the question twice is waste)
|
||||
self._qvec_cache: dict[str, list[float]] = {}
|
||||
self._embed_ok = True # flips False on first EmbedderDown; honest
|
||||
# skim notices accumulated this CALL (PR-3): what the fetched
|
||||
# articles contained beyond the current question's answer
|
||||
self._skim_notices: list[str] = []
|
||||
@@ -148,6 +165,49 @@ class KnowledgeExpert:
|
||||
if self.streams:
|
||||
self.streams.state(text, think=think)
|
||||
|
||||
def _qvec(self, question: str) -> list[float] | None:
|
||||
"""Question vector, cached per question text. None = embedder down
|
||||
(the probe degrades to lexical — offline fallback law, never dead)."""
|
||||
if not self._embed_ok:
|
||||
return None
|
||||
if question in self._qvec_cache:
|
||||
return self._qvec_cache[question]
|
||||
try:
|
||||
v = embed([question], model=self.cfg.embed_model,
|
||||
url=self.cfg.embed_url)[0]
|
||||
self._qvec_cache[question] = v
|
||||
return v
|
||||
except EmbedderDown as e:
|
||||
self._embed_ok = False
|
||||
self._log(f"semantic probe disabled (embedder down): {e}")
|
||||
return None
|
||||
|
||||
def _probe(self, question: str, seeds: list[str]) -> list:
|
||||
"""HYBRID probe (research/semantic-kg): lexical seeds UNION semantic
|
||||
rank. The lexical probe keeps exact-vocabulary recall (Po/flow);
|
||||
the semantic layer surfaces vocabulary the lexical one cannot see
|
||||
('President' vs 'Prime Minister', calibration 0.71). Dedup by edge
|
||||
id; semantic order fills the tail after lexical hits."""
|
||||
rows = self.store.probe(seeds)
|
||||
qv = self._qvec(question)
|
||||
if qv is None:
|
||||
return rows
|
||||
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
||||
if not sem:
|
||||
return rows
|
||||
seen = {r.eid for r in rows}
|
||||
added = 0
|
||||
for r in sem:
|
||||
if r.eid in seen:
|
||||
continue
|
||||
seen.add(r.eid)
|
||||
rows.append(r)
|
||||
added += 1
|
||||
if added:
|
||||
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
||||
f"(tau={self.cfg.semantic_tau})", think=True)
|
||||
return rows
|
||||
|
||||
@staticmethod
|
||||
def _keywords(question: str, k: int = 6) -> list[str]:
|
||||
"""Deterministic lexical focus: content words of the question (draft)."""
|
||||
@@ -223,6 +283,9 @@ class KnowledgeExpert:
|
||||
self._skim_notices: list[str] = []
|
||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
||||
# the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves
|
||||
# them; keywords of the question are the fallback when it returns none
|
||||
self._extract_entities: list[str] = []
|
||||
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
|
||||
# before network search so a later question pays zero re-fetch
|
||||
if not hasattr(self, "_seen_pages"):
|
||||
@@ -236,15 +299,14 @@ class KnowledgeExpert:
|
||||
or self._is_enumeration(question))
|
||||
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
|
||||
|
||||
# 2. KG probe first: question keywords + entities from the machine's
|
||||
# context (evidence rows) — 'that state' probes as 'france'
|
||||
# 2. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings)
|
||||
probe_seeds = list(kws)
|
||||
for line in (evidence or "").splitlines():
|
||||
if ":" in line:
|
||||
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
||||
if val and len(val.split()) <= 4:
|
||||
probe_seeds.extend(val.split())
|
||||
rows = self.store.probe(probe_seeds)
|
||||
rows = self._probe(question, probe_seeds)
|
||||
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
|
||||
# SET GATE (lists): mention rows never answer an enumeration — only a
|
||||
# membership set does. With no set held, the probe result is not
|
||||
@@ -269,18 +331,16 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.translate(question=question, context=context)
|
||||
q_raw = (pred.queries or "").strip()
|
||||
queries = [q.strip() for q in
|
||||
next((ln.split(":", 1)[1] for ln in q_raw.splitlines()
|
||||
if ln.strip().upper().startswith("QUERIES")), q_raw).split(",")
|
||||
if q.strip()][:2]
|
||||
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
|
||||
if not queries:
|
||||
queries = [" ".join(kws[:3])]
|
||||
e_raw = (pred.entities or "").strip()
|
||||
entity_terms = [t.strip() for t in
|
||||
next((ln.split(":", 1)[1] for ln in e_raw.splitlines()
|
||||
if ln.strip().upper().startswith("ENTITIES")), e_raw).split(",")
|
||||
if t.strip()][:4]
|
||||
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
|
||||
# the extractor's entities: TRANSLATE's resolved names + evidence
|
||||
# entities + (fallback) the question's proper nouns — the
|
||||
# question-blind extractor transcribes facts about THESE
|
||||
self._extract_entities = list(dict.fromkeys(
|
||||
e for e in (entity_terms + ev_entities
|
||||
+ sorted(_proper_nouns(question))) if e))
|
||||
self._log(f"translate -> queries {queries} entities {entity_terms}", think=True)
|
||||
|
||||
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
|
||||
@@ -391,12 +451,12 @@ class KnowledgeExpert:
|
||||
"skim": self._skim_notices}}
|
||||
else:
|
||||
answer = self._answer_from_rows(
|
||||
question, self.store.probe(probe_seeds), charge_llm)
|
||||
question, self._probe(question, probe_seeds), charge_llm)
|
||||
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
||||
self._log(f"early exit after {page.title}: "
|
||||
f"{answer['value'][:60]}", think=True)
|
||||
return {**self._audit_ambiguity(question, answer,
|
||||
self.store.probe(probe_seeds),
|
||||
self._probe(question, probe_seeds),
|
||||
charge_llm),
|
||||
"source": "knowledge_graph",
|
||||
"stats": {**self._skim_stats(pages),
|
||||
@@ -405,8 +465,8 @@ class KnowledgeExpert:
|
||||
# 5-7. remaining pages already processed inline via _process_page
|
||||
# (early exit); fall through to the final re-probe and answer.
|
||||
|
||||
# 8. re-probe (same seeds) and answer from the merged KG
|
||||
rows = self.store.probe(probe_seeds)
|
||||
# 8. re-probe (same seeds, hybrid) and answer from the merged KG
|
||||
rows = self._probe(question, probe_seeds)
|
||||
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"
|
||||
@@ -647,22 +707,19 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.select_table(question=question, tables=rendered)
|
||||
idx_raw = (pred.table_index or "").strip()
|
||||
if not idx_raw or idx_raw.upper() in ("NONE", "N/A", "0"):
|
||||
return None
|
||||
try:
|
||||
idx = int(re.findall(r"\d+", idx_raw)[0])
|
||||
except (ValueError, IndexError):
|
||||
chosen = pred.chosen
|
||||
if chosen is None:
|
||||
return None
|
||||
idx = chosen.table_index
|
||||
table = next((t for t in page.tables if t.idx == idx), None)
|
||||
if table is None:
|
||||
return None
|
||||
page._list_table_idx = idx # the harvest skips the LIST answer's table
|
||||
column = (pred.column or "").strip()
|
||||
column = chosen.column.strip()
|
||||
col_i = next((i for i, h in enumerate(table.header)
|
||||
if column.casefold() in h.casefold()), 0)
|
||||
set_name = (pred.set_name or "").strip() or question[:60]
|
||||
origin_question = (pred.origin_question or "").strip() or question
|
||||
set_name = chosen.set_name.strip() or question[:60]
|
||||
origin_question = question
|
||||
# INGEST ALL ROWS: one membership edge per row, quote = the full
|
||||
# stored row line, containment against the stored table text
|
||||
doc_id = self.store.add_document(
|
||||
@@ -888,16 +945,12 @@ class KnowledgeExpert:
|
||||
entities=", ".join(expected[:8]),
|
||||
tables="\n".join(rendered))
|
||||
promoted = 0
|
||||
for line in (pred.decision or "").strip().splitlines():
|
||||
m = re.match(r"\s*(\d+)\s*:\s*(YES|NO)\s*(.*)$", line.strip(),
|
||||
flags=re.I)
|
||||
if not m:
|
||||
continue
|
||||
idx, verdict, col = int(m.group(1)), m.group(2).upper(), m.group(3).strip()
|
||||
got = lookup.get(idx)
|
||||
if verdict != "YES" or got is None:
|
||||
for d in (pred.decisions or []):
|
||||
got = lookup.get(d.table_index)
|
||||
if not d.promote or got is None:
|
||||
continue
|
||||
page, t = got
|
||||
col = (d.column or "").strip()
|
||||
ent_i = next((i for i, h in enumerate(t.header)
|
||||
if h.casefold() in _ENTITY_COL), 0)
|
||||
val_i = next((i for i, h in enumerate(t.header)
|
||||
@@ -906,13 +959,13 @@ class KnowledgeExpert:
|
||||
continue
|
||||
overlap, nm = self._entity_overlap_count(t, ent_i, expected)
|
||||
if expected and overlap == 0 and nm >= 2:
|
||||
self._log(f"skim promote: table {idx} ({page.title}): LLM said "
|
||||
self._log(f"skim promote: table {d.table_index} ({page.title}): LLM said "
|
||||
f"YES but {overlap}/{nm} entity overlap — refused",
|
||||
think=True)
|
||||
continue
|
||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||
if merged:
|
||||
self._log(f"skim promote: {merged} rows of table {idx} "
|
||||
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||
promoted += 1
|
||||
self._skim_leads = [] # consumed: bounded, never re-asked
|
||||
@@ -924,14 +977,22 @@ class KnowledgeExpert:
|
||||
page. Returns number of candidates merged this page. Counters
|
||||
ACCUMULATE on self.
|
||||
|
||||
PR-1: chunks are RANKED by skim signals (question terms + goal terms
|
||||
+ quantity-unit patterns) instead of taking the first N in document
|
||||
order — the Italy run burned its extract slots on tangential chunks
|
||||
while the discharge table sat later in the document. A chunk without
|
||||
ANY signal is skipped for free."""
|
||||
research/semantic-kg: the extractor is QUESTION-BLIND — it receives
|
||||
the ENTITIES (from TRANSLATE + evidence + proper nouns) and
|
||||
transcribes their facts; ranking/gating still uses the question
|
||||
(the machine's slots are limited — the best-guess chunks get them).
|
||||
Tables: SkimTableSignature decides BEFORE extraction which tables
|
||||
deserve fragments (identity + first rows, one call per page);
|
||||
fragments of rejected tables are skipped with zero extract spend."""
|
||||
entities = self._extract_entities or sorted(_proper_nouns(question))
|
||||
ent_str = ", ".join(entities[:8]) or "(none named)"
|
||||
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
|
||||
cap=self.cfg.chunk_chars_cap)
|
||||
gated = [c for c in chunks if self._gate(c, kws)]
|
||||
# the gate keeps question terms OR entity mentions — a chunk about
|
||||
# the entity (but in other vocabulary) is exactly what the semantic
|
||||
# layer exists for; a chunk about neither is noise for both
|
||||
gated = [c for c in chunks if self._gate(c, kws)
|
||||
or any(_term_hits(e, c.text) for e in entities)]
|
||||
if goal_terms:
|
||||
from .store import stem
|
||||
|
||||
@@ -943,15 +1004,45 @@ class KnowledgeExpert:
|
||||
gated.sort(key=rank, reverse=True)
|
||||
capped = gated[: self.cfg.max_chunks_extracted]
|
||||
|
||||
# ---- table fragments: the tables seen in this page, as SMALL
|
||||
# structured pieces for the extractor — never a 22k-char dump (run G,
|
||||
# call 8/80). Each fragment repeats the header; the extractor can
|
||||
# STOP_TABLE a hopeless table after reading its identity. The LIST
|
||||
# answer's own table never re-enters the extract path.
|
||||
stopped: set[int] = set()
|
||||
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
||||
# BEFORE paying extraction — identity + first rows, one call per
|
||||
# page. The LIST answer's own table never enters; tables that name
|
||||
# an entity are ALWAYS relevant (never skipped by the LLM's word).
|
||||
list_idx = getattr(page, "_list_table_idx", -1)
|
||||
table_frags = [f for f in tables_as_chunks(page.wikitext)
|
||||
if f["table_idx"] != list_idx]
|
||||
table_frags_all = [f for f in tables_as_chunks(page.wikitext)
|
||||
if f["table_idx"] != list_idx]
|
||||
stopped: set[int] = set()
|
||||
if table_frags_all and page.tables:
|
||||
# deterministic safety net: a table whose caption/headers/first
|
||||
# rows NAME an entity is relevant, no LLM call needed
|
||||
def _names_entity(t) -> bool:
|
||||
surface = " ".join([t.caption or ""] + list(t.header[:6])
|
||||
+ [r and " ".join(r[:2]) or ""
|
||||
for r in t.rows[:3]])
|
||||
toks = _tokens(surface)
|
||||
return any(_prop_hit(e, toks) for e in entities)
|
||||
|
||||
undecided = [t for t in page.tables
|
||||
if t.idx != list_idx and not _names_entity(t)]
|
||||
if undecided:
|
||||
rendered = chr(10).join(
|
||||
f"{t.idx} | {t.caption or '(no caption)'} | "
|
||||
f"header: {', '.join(t.header[:6]) or '(none)'} | "
|
||||
f"rows: {t.total_rows} | first rows: "
|
||||
+ " ;; ".join(" | ".join(r) for r in t.rows[:3] if r)
|
||||
for t in undecided)
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = self.skim_tables(question=question,
|
||||
entities=ent_str, tables=rendered)
|
||||
for d in (pred.decisions or []):
|
||||
if not d.relevant:
|
||||
stopped.add(d.table_index)
|
||||
self._log(f"table skim: table {d.table_index} "
|
||||
f"({(d.reason or '')[:50]}) — skipped before "
|
||||
f"extraction", think=True)
|
||||
table_frags = [f for f in table_frags_all
|
||||
if f["table_idx"] not in stopped]
|
||||
frag_slots = max(0, self.cfg.max_chunks_extracted - len(capped))
|
||||
frag_budget = min(frag_slots, len(table_frags))
|
||||
|
||||
@@ -963,22 +1054,10 @@ class KnowledgeExpert:
|
||||
for chunk in capped:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
|
||||
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]}")
|
||||
continue
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
||||
self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
|
||||
self._merged += 1
|
||||
extracted += 1
|
||||
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
||||
text=chunk.text)
|
||||
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
||||
extracted += self._ingest_candidate(cand, page, containment=page.text)
|
||||
# ---- table fragments (extract path) -----------------------------
|
||||
from .store import stem as _stem
|
||||
# containment target: prose + ALL table rows (the fragment's rows
|
||||
@@ -1002,34 +1081,51 @@ class KnowledgeExpert:
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
||||
raw = self.extract(question=question, heading=heading, text=text)
|
||||
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 (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}): "
|
||||
f"{cand.get('subject', '')[:40]}")
|
||||
continue
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
||||
self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
|
||||
self._merged += 1
|
||||
extracted += 1
|
||||
raw = self.extract(entities=ent_str, heading=heading, text=text)
|
||||
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
||||
extracted += self._ingest_candidate(cand, page, containment=containment)
|
||||
return self._merged
|
||||
|
||||
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int:
|
||||
"""Containment-check one typed Fact, merge it, cache its vector.
|
||||
Returns 1 when merged, 0 otherwise. Shared by the prose and table-
|
||||
fragment extract paths (research/semantic-kg)."""
|
||||
self._checked += 1
|
||||
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"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||
return 0
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
||||
eid = self.store.add_edge(cand["subject"], cand["relation"],
|
||||
cand["object"], qid)
|
||||
self._merged += 1
|
||||
if eid is not None:
|
||||
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
||||
cand["object"])
|
||||
return 1
|
||||
|
||||
def _cache_edge_vector(self, eid: int, subject: str, relation: str,
|
||||
obj: str) -> None:
|
||||
"""Embed 'subject | relation | object' and cache it for the semantic
|
||||
probe. Batched lazily: failures flip _embed_ok off (lexical fallback
|
||||
keeps the run alive); no failure ever blocks an ingest."""
|
||||
if not self._embed_ok:
|
||||
return
|
||||
text = f"{subject} | {relation} | {obj}"
|
||||
try:
|
||||
v = embed([text], model=self.cfg.embed_model,
|
||||
url=self.cfg.embed_url)[0]
|
||||
self.store.set_edge_vector(eid, self.cfg.embed_model,
|
||||
hashlib.sha1(text.encode()).hexdigest(), v)
|
||||
except EmbedderDown:
|
||||
self._embed_ok = False
|
||||
self._log("semantic probe disabled (embedder down at ingest)")
|
||||
|
||||
def _gate(self, chunk, keywords: list[str]) -> bool:
|
||||
"""Lexical gate with stemming: chunk must mention a question stem."""
|
||||
from .store import stem
|
||||
@@ -1053,5 +1149,5 @@ class KnowledgeExpert:
|
||||
"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),
|
||||
"confidence": pred.confidence.strip().lower(),
|
||||
"confidence": str(pred.confidence.value),
|
||||
}
|
||||
+75
-27
@@ -6,10 +6,19 @@ the FULL document text — so chunking can never fake a quote.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Confidence(str, Enum):
|
||||
"""Honest self-assessment of an answer drawn from KG rows."""
|
||||
HIGH = "high"
|
||||
MEDIUM = "medium"
|
||||
LOW = "low"
|
||||
|
||||
|
||||
class Fact(BaseModel):
|
||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||
@@ -23,32 +32,29 @@ class TranslateSignature(dspy.Signature):
|
||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
||||
references ('that state', 'the same river') using the context: the original
|
||||
question and the evidence rows already gathered. Output two lines:
|
||||
QUERIES: 1-2 wikipedia search queries, comma separated.
|
||||
ENTITIES: the resolved entity names the answer is about, comma separated."""
|
||||
question and the evidence rows already gathered."""
|
||||
question: str = dspy.InputField()
|
||||
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
|
||||
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries")
|
||||
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river")
|
||||
queries: list[str] = dspy.OutputField(
|
||||
desc="1-2 Wikipedia search queries, most specific first")
|
||||
entities: list[str] = dspy.OutputField(
|
||||
desc="the resolved entity names the answer is about")
|
||||
|
||||
|
||||
class ExtractSignature(dspy.Signature):
|
||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||
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 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()
|
||||
extract facts about the NAMED ENTITIES: biographical facts, positions
|
||||
and offices held, events, relationships, quantities with their units.
|
||||
Each fact carries its verbatim quote: the FULL sentence or table ROW
|
||||
that states it, copied exactly (at least 10 characters). Only facts
|
||||
the text states; no inference. Extract facts for ALL the named
|
||||
entities that appear in the text; skip entities not mentioned."""
|
||||
entities: str = dspy.InputField(
|
||||
desc="the named entities to extract facts about, comma separated")
|
||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||
text: str = dspy.InputField()
|
||||
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):
|
||||
@@ -59,7 +65,8 @@ class AnswerFromKG(dspy.Signature):
|
||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||
confidence: str = dspy.OutputField(desc="high medium low")
|
||||
confidence: Confidence = dspy.OutputField(
|
||||
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
||||
|
||||
|
||||
class VerifyCountSignature(dspy.Signature):
|
||||
@@ -81,18 +88,31 @@ class VerifyCountSignature(dspy.Signature):
|
||||
quote: str = dspy.OutputField(desc="verbatim sentence stating the count, or NOQUOTE")
|
||||
|
||||
|
||||
class TableChoice(BaseModel):
|
||||
"""The table chosen as the answer's enumeration, if any."""
|
||||
table_index: int = dspy.OutputField(desc="the chosen table's index")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates")
|
||||
|
||||
|
||||
class SelectTableSignature(dspy.Signature):
|
||||
"""You are the SELECT TABLE step of a knowledge machine. Given a question
|
||||
and the tables found in an article (index, caption, header columns, row
|
||||
count — NOT the rows), decide: does one of these tables enumerate the
|
||||
answer? Output the table index and the column holding the answer
|
||||
elements, or NONE."""
|
||||
answer?"""
|
||||
question: str = dspy.InputField()
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N'")
|
||||
table_index: str = dspy.OutputField(desc="the chosen table index (e.g. '2'), or NONE")
|
||||
column: str = dspy.OutputField(desc="header name of the column holding the answer elements; empty if NONE")
|
||||
set_name: str = dspy.OutputField(desc="short name of the set this table enumerates, e.g. 'sovereign states in Europe'; empty if NONE")
|
||||
origin_question: str = dspy.OutputField(desc="the question verbatim, for provenance; empty if NONE")
|
||||
chosen: TableChoice | None = dspy.OutputField(
|
||||
desc="the chosen table and its answer column; null when NO table enumerates the answer")
|
||||
|
||||
|
||||
class PromotionDecision(BaseModel):
|
||||
"""One table's promotion verdict."""
|
||||
table_index: int = dspy.OutputField(desc="the table's index from the list")
|
||||
promote: bool = dspy.OutputField(
|
||||
desc="True when this table holds data about those entities for the goal")
|
||||
column: str = dspy.OutputField(
|
||||
desc="when promoted: the header holding the goal's values; empty otherwise")
|
||||
|
||||
|
||||
class SkimPromoteSignature(dspy.Signature):
|
||||
@@ -102,13 +122,41 @@ class SkimPromoteSignature(dspy.Signature):
|
||||
and the table's words may differ — 'water flow' vs 'Flow at the mouth').
|
||||
Given the run's goal, the entities it is about, and the tables' identity
|
||||
(caption, headers, row count, quantity signals — NOT the rows), decide
|
||||
per table whether it holds data about those entities for the goal.
|
||||
Output one line per table: 'idx: YES <column>' or 'idx: NO' — the column
|
||||
is the header holding the goal's values."""
|
||||
per table whether it holds data about those entities for the goal."""
|
||||
goal: str = dspy.InputField(desc="the run's overall goal question")
|
||||
entities: str = dspy.InputField(desc="the entities the goal is about, comma separated; may be empty")
|
||||
tables: str = dspy.InputField(desc="one line per table: 'idx | caption | header: a, b, c | rows: N | quantities: x, y'")
|
||||
decision: str = dspy.OutputField(desc="one line per table: 'idx: YES <column>' or 'idx: NO'")
|
||||
decisions: list[PromotionDecision] = dspy.OutputField(
|
||||
desc="one verdict per table in the list")
|
||||
|
||||
|
||||
class TableRelevanceDecision(BaseModel):
|
||||
"""One table's extraction-worthiness verdict (skim-level stop)."""
|
||||
table_index: int = dspy.OutputField(desc="the table's index from the list")
|
||||
relevant: bool = dspy.OutputField(
|
||||
desc="True when this table plausibly holds facts about the entities "
|
||||
"or their context; False when its subject is clearly different "
|
||||
"(wrong country, wrong topic, unrelated data)")
|
||||
reason: str = dspy.OutputField(
|
||||
desc="short reason, e.g. 'about world rivers, not Italy'")
|
||||
|
||||
|
||||
class SkimTableSignature(dspy.Signature):
|
||||
"""You are the TABLE SKIM step of a knowledge machine. For each table
|
||||
in an article, given its IDENTITY (caption, header columns, row count
|
||||
— and the FIRST FEW ROWS only), decide whether the table plausibly
|
||||
holds facts about the named entities or the question's subject. The
|
||||
goal is to skip hopeless tables BEFORE paying extraction, and to
|
||||
never skip a table that mentions the entities. Decide per table."""
|
||||
question: str = dspy.InputField(
|
||||
desc="the current question (planning context; the extractor itself "
|
||||
"never sees it)")
|
||||
entities: str = dspy.InputField(
|
||||
desc="the named entities the question is about, comma separated")
|
||||
tables: str = dspy.InputField(
|
||||
desc="one block per table: 'idx | caption | header: a, b, c | rows: N | first rows: <3-5 sample rows>'")
|
||||
decisions: list[TableRelevanceDecision] = dspy.OutputField(
|
||||
desc="one verdict per table in the list")
|
||||
|
||||
|
||||
def parse_facts(raw: str) -> list[dict]:
|
||||
|
||||
+62
-1
@@ -38,6 +38,9 @@ CREATE TABLE IF NOT EXISTS conflicts (
|
||||
id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, value_a TEXT, value_b TEXT,
|
||||
edge_a INTEGER, edge_b INTEGER, note TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS edge_vectors (
|
||||
edge_id INTEGER PRIMARY KEY, model TEXT, text_hash TEXT, vec BLOB
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_node, rel);
|
||||
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(norm_name);
|
||||
"""
|
||||
@@ -68,6 +71,7 @@ def stem(word: str) -> str:
|
||||
|
||||
@dataclass
|
||||
class EdgeView:
|
||||
eid: int
|
||||
src: str
|
||||
rel: str
|
||||
dst: str
|
||||
@@ -257,11 +261,68 @@ class KnowledgeStore:
|
||||
conflict = self.db.execute(
|
||||
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
|
||||
views.append(EdgeView(
|
||||
src=sname, rel=rel, dst=dstv, quote=quote, url=url,
|
||||
eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url,
|
||||
ref_date=rd, corroboration=cor, preferred=bool(pref),
|
||||
conflict=bool(conflict)))
|
||||
|
||||
# ---- membership queries (LIST path) --------------------------------------
|
||||
def set_edge_vector(self, edge_id: int, model: str, text_hash: str,
|
||||
vec: list[float]) -> None:
|
||||
"""Cache one edge's vector, keyed by (edge_id, model, text_hash):
|
||||
switching models (or the edge text changing) invalidates cleanly —
|
||||
the probe re-embeds, the stale row is replaced. Append-only law is
|
||||
kept for QUOTES and EDGES; vectors are a derived cache, upserted."""
|
||||
import struct
|
||||
blob = struct.pack(f"{len(vec)}f", *vec)
|
||||
self.db.execute(
|
||||
"INSERT OR REPLACE INTO edge_vectors(edge_id, model, text_hash, vec) "
|
||||
"VALUES(?,?,?,?)", (edge_id, model, text_hash, blob))
|
||||
self.db.commit()
|
||||
|
||||
def semantic_probe(self, qvec: list[float], tau: float = 0.45,
|
||||
limit: int = 20) -> list[EdgeView]:
|
||||
"""Semantic retrieval: cosine rank ALL edges with a cached vector
|
||||
(for the current model) against the question vector, keep >= tau.
|
||||
|
||||
nomic does not separate 'facts about the same entity' from 'facts
|
||||
that answer the question' (calibration: spouse 0.67) — the semantic
|
||||
layer RANKS and surfaces vocabulary the lexical probe cannot see
|
||||
('Prime Minister' vs 'President'), the JUDGE still decides. At
|
||||
hundreds of edges brute force over cached blobs is instant."""
|
||||
import struct
|
||||
from .embeddings import cosine as _cos
|
||||
out: list[EdgeView] = []
|
||||
rows = self.db.execute(
|
||||
"SELECT v.edge_id, v.vec FROM edge_vectors v").fetchall()
|
||||
scored: list[tuple[float, EdgeView]] = []
|
||||
for eid, blob in rows:
|
||||
n = len(blob) // 4
|
||||
vec = struct.unpack(f"{n}f", blob)
|
||||
d = _cos(qvec, vec)
|
||||
if d < tau:
|
||||
continue
|
||||
ev = self._edge_view_by_id(eid)
|
||||
if ev is not None:
|
||||
scored.append((d, ev))
|
||||
scored.sort(key=lambda t: -t[0])
|
||||
return [ev for _, ev in scored[:limit]]
|
||||
|
||||
def _edge_view_by_id(self, eid: int) -> EdgeView | None:
|
||||
e = self.db.execute(
|
||||
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
|
||||
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
|
||||
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
|
||||
"JOIN nodes n ON n.id=e.src_node WHERE e.id=?", (eid,)).fetchone()
|
||||
if not e:
|
||||
return None
|
||||
conflict = self.db.execute(
|
||||
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
|
||||
(eid_, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e
|
||||
return EdgeView(
|
||||
eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url,
|
||||
ref_date=rd, corroboration=cor, preferred=bool(pref),
|
||||
conflict=bool(conflict))
|
||||
|
||||
def member_sets(self) -> list[str]:
|
||||
"""Distinct set names that have membership edges (rel='member_of')."""
|
||||
rows = self.db.execute(
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
from knowledge.wiki import WikiPage, parse_tables
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.expert import (KnowledgeExpert, KnowledgeConfig,
|
||||
_tokens, _term_hits, _proper_nouns)
|
||||
from knowledge.store import KnowledgeStore
|
||||
@@ -118,10 +119,8 @@ def test_subject_guard_list():
|
||||
e2 = make_expert(KnowledgeStore(f"{tmp2}/kg.sqlite"))
|
||||
|
||||
class Pred:
|
||||
table_index = "1"
|
||||
column = "River"
|
||||
set_name = "longest rivers of Italy"
|
||||
origin_question = q
|
||||
chosen = TableChoice(table_index=1, column="River",
|
||||
set_name="longest rivers of Italy")
|
||||
|
||||
e2.select_table = lambda **kw: Pred()
|
||||
ans2 = e2._list_from_page(italy_page(), q, None)
|
||||
|
||||
@@ -13,6 +13,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||
|
||||
from knowledge.wiki import WikiPage, WikiTable, parse_tables
|
||||
from knowledge.store import KnowledgeStore
|
||||
from knowledge.extract import PromotionDecision
|
||||
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
|
||||
|
||||
|
||||
@@ -32,15 +33,15 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
|
||||
|
||||
class FakePromote:
|
||||
"""Scripted skim_promote (dspy module shape): returns fixed decision."""
|
||||
def __init__(self, decision: str):
|
||||
self.decision_text = decision
|
||||
"""Scripted skim_promote (dspy module shape): returns typed decisions."""
|
||||
def __init__(self, decisions):
|
||||
self.decisions = decisions
|
||||
self.calls = 0
|
||||
|
||||
def __call__(self, **kw):
|
||||
self.calls += 1
|
||||
obj = type("P", (), {})()
|
||||
obj.decision = self.decision_text
|
||||
obj.decisions = self.decisions
|
||||
return obj
|
||||
|
||||
|
||||
@@ -81,7 +82,8 @@ def test_promotion_ingests_goal_table():
|
||||
n = e._harvest_side_tables(lead_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1, "queued as lead, not ingested"
|
||||
# bounded promotion: LLM says YES (column Mean discharge)
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge")
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 1, "promoted table ingested"
|
||||
@@ -100,7 +102,8 @@ def test_promotion_refuses_world_table():
|
||||
e._current_goal_terms = ["total"] # no overlap with caption/header
|
||||
n = e._harvest_side_tables(world_page(), None, "q", EVIDENCE)
|
||||
assert n == 0 and len(e._skim_leads) == 1
|
||||
e.skim_promote = FakePromote("1: YES Mean discharge") # LLM WRONG
|
||||
e.skim_promote = FakePromote([PromotionDecision(
|
||||
table_index=1, promote=True, column="Mean discharge")]) # LLM WRONG
|
||||
p = e._promote_leads(EVIDENCE, lambda: None)
|
||||
assert p == 0, "code disposes: zero entity overlap -> refused"
|
||||
assert all(r.src != "amazon" for r in store.probe(["discharge"])), \
|
||||
@@ -110,7 +113,7 @@ def test_promotion_refuses_world_table():
|
||||
|
||||
def test_no_leads_no_call():
|
||||
e = make_expert(KnowledgeStore(":memory:"))
|
||||
e.skim_promote = FakePromote("1: YES x")
|
||||
e.skim_promote = FakePromote([])
|
||||
charged = []
|
||||
p = e._promote_leads(EVIDENCE, lambda: charged.append(1))
|
||||
assert p == 0 and e.skim_promote.calls == 0 and not charged, \
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Semantic KG retrieval tests (research/semantic-kg).
|
||||
|
||||
Laws under test:
|
||||
1. semantic_probe ranks cached edge vectors by cosine and keeps >= tau:
|
||||
the 'President' question surfaces the 'Prime Minister' edge the LEXICAL
|
||||
probe cannot see (no shared stems) — calibration 0.71 vs cross-ques
|
||||
noise 0.35-0.38, tau=0.45.
|
||||
2. The hybrid _probe: lexical UNION semantic, dedup by edge id — the
|
||||
same edge never enters twice.
|
||||
3. Honest degradation: embedder down -> lexical rows only, never a dead
|
||||
run (_embed_ok flips, the log says it).
|
||||
4. Vectors are a cache keyed (edge_id, model, text_hash): switching the
|
||||
model invalidates — the stale vector is replaced, not mixed.
|
||||
5. EdgeView carries eid (dedup key between the two probes).
|
||||
|
||||
Network: the embed() calls are monkeypatched with scripted vectors —
|
||||
the test runs offline.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||
|
||||
import knowledge.embeddings as emb
|
||||
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
|
||||
def make_store(tmp: str) -> KnowledgeStore:
|
||||
return KnowledgeStore(f"{tmp}/kg.sqlite")
|
||||
|
||||
|
||||
def _add_fact(store: KnowledgeStore, src: str, rel: str, dst: str,
|
||||
quote: str) -> int:
|
||||
doc = store.add_document(url="http://x/" + src, title=src,
|
||||
fetched_at="2026-10-22", sha256="sha" + src)
|
||||
qid = store.add_quote(doc, quote, "http://x/" + src, "2026-10-22")
|
||||
return store.add_edge(src, rel, dst, qid)
|
||||
|
||||
|
||||
def test_semantic_probe_surfaces_lexical_miss():
|
||||
"""The Pedro case: 'President before' shares NO stems with 'prime
|
||||
minister of Spain' — the lexical probe misses it, the semantic one
|
||||
must surface it (this is the long search his run paid)."""
|
||||
import tempfile
|
||||
store = make_store(tempfile.mkdtemp())
|
||||
e1 = _add_fact(store, "Pedro Sanchez", "position",
|
||||
"Prime Minister of Spain", "he has been the prime "
|
||||
"minister of Spain since 2018")
|
||||
e2 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
|
||||
# scripted vectors: PM-edge close to the question, Po-edge far away
|
||||
q_vec = [1.0, 0.0, 0.0]
|
||||
pm_vec = [0.92, 0.39, 0.0]
|
||||
po_vec = [0.0, 0.2, 0.98]
|
||||
store.set_edge_vector(e1, "test-model", "h1", pm_vec)
|
||||
store.set_edge_vector(e2, "test-model", "h2", po_vec)
|
||||
hits = store.semantic_probe(q_vec, tau=0.45)
|
||||
assert any("Prime Minister" in (h.dst or "") for h in hits), hits
|
||||
assert all("652" not in (h.dst or "") for h in hits), hits
|
||||
print("ok: semantic probe surfaces the lexical-missed edge (PM of Spain)")
|
||||
|
||||
|
||||
def test_hybrid_probe_dedups():
|
||||
"""Lexical UNION semantic with dedup by edge id: an edge found by both
|
||||
probes appears once. The lexical hit keeps its position; the semantic
|
||||
fills the tail."""
|
||||
import tempfile
|
||||
store = make_store(tempfile.mkdtemp())
|
||||
e1 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
|
||||
e2 = _add_fact(store, "Pedro Sanchez", "position",
|
||||
"Prime Minister of Spain", "prime minister since 2018")
|
||||
store.set_edge_vector(e1, "m", "h1", [1.0, 0.0])
|
||||
store.set_edge_vector(e2, "m", "h2", [1.0, 0.1])
|
||||
|
||||
expert = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
expert.cfg = KnowledgeConfig()
|
||||
expert.store = store
|
||||
expert.streams = None
|
||||
expert._embed_ok = True
|
||||
expert._qvec_cache = {}
|
||||
expert._log = lambda *a, **k: None
|
||||
|
||||
orig_embed = emb.embed
|
||||
try:
|
||||
def fake_embed(texts, model=None, url=None, timeout=60):
|
||||
vecs = {"Who was the President before Pedro Sanchez?": [0.95, 0.31],
|
||||
"Po | length | 652 km": [1.0, 0.0],
|
||||
"Pedro Sanchez | position | Prime Minister of Spain": [1.0, 0.1]}
|
||||
return [vecs[t] for t in texts]
|
||||
from knowledge import expert as expert_mod
|
||||
expert_mod.embed = fake_embed # the module's imported name
|
||||
rows = expert._probe("Who was the President before Pedro Sanchez?",
|
||||
["pedro", "president"])
|
||||
eids = [r.eid for r in rows]
|
||||
assert len(eids) == len(set(eids)), f"dupes in hybrid probe: {rows}"
|
||||
# lexical hit (Po) present; semantic-only hit (PM) also present
|
||||
assert any(r.src == "po" for r in rows), rows
|
||||
assert any("Prime Minister" in (r.dst or "") for r in rows), rows
|
||||
print("ok: hybrid probe — lexical UNION semantic, dedup by eid")
|
||||
finally:
|
||||
from knowledge import expert as expert_mod
|
||||
expert_mod.embed = orig_embed
|
||||
del expert_mod
|
||||
|
||||
|
||||
def test_embedder_down_degrades():
|
||||
"""Embedder down: _embed_ok flips, the probe returns the lexical rows
|
||||
alone, and nothing raises — the run stays alive (offline fallback)."""
|
||||
import tempfile
|
||||
store = make_store(tempfile.mkdtemp())
|
||||
_add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
|
||||
|
||||
expert = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||
expert.cfg = KnowledgeConfig()
|
||||
expert.store = store
|
||||
expert.streams = None
|
||||
expert._embed_ok = True
|
||||
expert._qvec_cache = {}
|
||||
notes = []
|
||||
expert._log = lambda text, think=False: notes.append(text)
|
||||
|
||||
from knowledge import expert as expert_mod
|
||||
orig = expert_mod.embed
|
||||
def boom(texts, model=None, url=None, timeout=60):
|
||||
raise emb.EmbedderDown("endpoint down")
|
||||
expert_mod.embed = boom
|
||||
try:
|
||||
rows = expert._probe("length of the Po river?", ["river", "length"])
|
||||
assert rows and rows[0].src == "po", rows
|
||||
assert expert._embed_ok is False
|
||||
assert any("disabled" in n for n in notes), notes
|
||||
# second call: no embed attempt at all (cache of the failure)
|
||||
rows2 = expert._probe("length of the Po river?", ["river", "length"])
|
||||
assert rows2
|
||||
print("ok: embedder down -> lexical degradation, run alive")
|
||||
finally:
|
||||
expert_mod.embed = orig
|
||||
|
||||
|
||||
def test_vector_cache_invalidates_by_model():
|
||||
"""Keyed (edge_id, model, text_hash): a new model replaces the stale
|
||||
row — the probe never mixes vectors of two models."""
|
||||
import tempfile
|
||||
store = make_store(tempfile.mkdtemp())
|
||||
eid = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km")
|
||||
store.set_edge_vector(eid, "model-a", "h1", [1.0, 0.0])
|
||||
store.set_edge_vector(eid, "model-b", "h1", [0.0, 1.0])
|
||||
# question along model-b's direction (the LAST upserted vector): the
|
||||
# edge hits; along model-a's old direction it must NOT (replaced)
|
||||
hits_b = store.semantic_probe([0.0, 1.0], tau=0.9)
|
||||
assert hits_b and hits_b[0].eid == eid, hits_b
|
||||
hits_a = store.semantic_probe([1.0, 0.0], tau=0.9)
|
||||
assert not hits_a, f"stale model-a vector still live: {hits_a}"
|
||||
import sqlite3
|
||||
rows = store.db.execute(
|
||||
"SELECT model, vec FROM edge_vectors WHERE edge_id=?", (eid,)).fetchall()
|
||||
assert len(rows) == 1 and rows[0][0] == "model-b", f"upsert failed: {rows}"
|
||||
print("ok: vector cache upserts (one row per edge; last model wins)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_semantic_probe_surfaces_lexical_miss()
|
||||
test_hybrid_probe_dedups()
|
||||
test_embedder_down_degrades()
|
||||
test_vector_cache_invalidates_by_model()
|
||||
print("\nsemantic kg tests passed")
|
||||
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo r
|
||||
|
||||
from knowledge.checks import check_candidate, quote_containment, trusted_source
|
||||
from knowledge.chunker import chunk_page
|
||||
from knowledge.extract import TableChoice
|
||||
from knowledge.store import KnowledgeStore
|
||||
|
||||
|
||||
@@ -225,10 +226,8 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "1"
|
||||
p.column = "Country"
|
||||
p.set_name = "sovereign states in Europe"
|
||||
p.origin_question = kw.get("question", "")
|
||||
p.chosen = TableChoice(table_index=1, column="Country",
|
||||
set_name="sovereign states in Europe")
|
||||
return p
|
||||
|
||||
class FakeStore:
|
||||
@@ -286,10 +285,7 @@ def test_list_ingest_aggregate(tmp="/tmp/floop_kg_list.sqlite"):
|
||||
def __call__(self, **kw):
|
||||
class P: pass
|
||||
p = P()
|
||||
p.table_index = "NONE"
|
||||
p.column = ""
|
||||
p.set_name = ""
|
||||
p.origin_question = ""
|
||||
p.chosen = None
|
||||
return p
|
||||
ke.select_table = FakeNonePicker()
|
||||
assert ke._list_from_page(page, "irrelevant", None) is None
|
||||
|
||||
@@ -71,14 +71,18 @@ def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
e._skim_leads = []
|
||||
e._skim_notices = []
|
||||
e._current_goal_terms = []
|
||||
e._extract_entities = []
|
||||
e._embed_ok = True
|
||||
e._qvec_cache = {}
|
||||
return e
|
||||
|
||||
|
||||
def test_process_page_fragments():
|
||||
"""The extract path over table fragments: no-signal frags skip free,
|
||||
STOP_TABLE kills the REST of that table (never other tables), and
|
||||
surviving fragments ingest their rows with containment-checked quotes.
|
||||
Mirrors run G: goal flow, page holds world-rivers + Italy tables."""
|
||||
the TABLE SKIM (question-aware, pre-extraction) kills hopeless tables
|
||||
BEFORE any extract spend, and surviving fragments ingest their rows
|
||||
with containment-checked quotes. Mirrors run G: goal flow, page holds
|
||||
world-rivers + Italy tables."""
|
||||
import tempfile
|
||||
from knowledge.wiki import parse_tables
|
||||
|
||||
@@ -92,18 +96,31 @@ def test_process_page_fragments():
|
||||
wikitext=WIKITEXT_2TABLES)
|
||||
page.tables = parse_tables(WIKITEXT_2TABLES)
|
||||
|
||||
# scripted extractor: world-table parts -> stop=True; Italy table -> one Fact
|
||||
# scripted TABLE SKIM: world table not relevant; Italy table relevant
|
||||
class Decision:
|
||||
def __init__(self, idx, relevant, reason=""):
|
||||
self.table_index = idx
|
||||
self.relevant = relevant
|
||||
self.reason = reason
|
||||
|
||||
class SkimOut:
|
||||
def __init__(self, decisions):
|
||||
self.decisions = decisions
|
||||
|
||||
e.skim_tables = lambda question, entities, tables: SkimOut([
|
||||
Decision(1, False, "world rivers, not Italy"),
|
||||
Decision(2, True, "rivers of Italy with flow"),
|
||||
])
|
||||
|
||||
# scripted extractor: facts for whichever table the skim lets through
|
||||
calls = []
|
||||
|
||||
class FakeOut:
|
||||
def __init__(self, facts, stop=False):
|
||||
def __init__(self, facts):
|
||||
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=True)
|
||||
def fake_extract(entities, heading, text, _calls=calls):
|
||||
_calls.append((entities, heading, text))
|
||||
if "Rivers of Italy" in text:
|
||||
# quote = the full rendered row context (header + row), verbatim
|
||||
# from the fragment the extractor saw
|
||||
@@ -117,20 +134,21 @@ def test_process_page_fragments():
|
||||
|
||||
q = "What is the total water flow of the three longest rivers of Italy?"
|
||||
kws = e._keywords("What is the water flow of rivers of Italy?")
|
||||
e._extract_entities = ["Italy"]
|
||||
# _process_page signature: (page, question, kws, goal_terms, charge_llm)
|
||||
n = e._process_page(page, question=q, kws=kws,
|
||||
goal_terms=["total", "water", "flow", "italy"],
|
||||
charge_llm=None)
|
||||
goal_terms=["total", "water", "flow", "italy"],
|
||||
charge_llm=None)
|
||||
# the Italy fragment ingested its fact (merged counts edges)
|
||||
rows = store.probe(["italy", "flow"])
|
||||
# probe returns norm_name'd src ('po', not 'Po') — store law
|
||||
assert any(r.dst == "1540 m3/s" and r.src == "po"
|
||||
and r.rel == "Flow at the mouth" for r in rows), rows
|
||||
# STOP_TABLE must have short-circuited table 1 after its FIRST fragment:
|
||||
# at most 1 extract call for table 1 (not 3), plus 1 for the Italy table
|
||||
# the skim must have killed the world table BEFORE extraction: zero
|
||||
# extract calls touch it (parts 1-3 all skipped, zero spend)
|
||||
world_calls = [c for c in calls if "World rivers" in c[2]]
|
||||
assert len(world_calls) == 1, f"STOP_TABLE did not skip parts 2/3: {len(world_calls)} calls"
|
||||
print("ok: extract fragments — STOP_TABLE skips rest of table, facts ingest")
|
||||
assert len(world_calls) == 0, f"skim did not kill table 1 pre-extract: {len(world_calls)} calls"
|
||||
print("ok: table skim kills hopeless tables pre-extract; surviving frags ingest")
|
||||
|
||||
|
||||
def test_prompt_log():
|
||||
|
||||
@@ -191,7 +191,7 @@ def part_of(frag: dict) -> str:
|
||||
|
||||
def parse_stop_table(out_text: str) -> bool:
|
||||
"""LEGACY textual STOP_TABLE detector — kept only for tests. Production
|
||||
code reads the typed `stop: bool` field of ExtractSignature."""
|
||||
code reads the typed `stop_table: bool` field of ExtractSignature."""
|
||||
return "STOP_TABLE" in (out_text or "").upper()[:80]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Query anonymization tests (his design, 22/10): INIT must decompose the
|
||||
question's SHAPE, not lean on its knowledge of the named people in it.
|
||||
|
||||
Laws under test:
|
||||
1. MASK proposes entities; apply_mask/restore_mask are DETERMINISTIC —
|
||||
longer names first, one mask per surface text, typed placeholders.
|
||||
2. init_decompose masks before INIT and restores in the subquestions.
|
||||
3. No entities found -> the question reaches INIT unchanged.
|
||||
4. MASK dying (AdapterParseError) -> passthrough, never a dead run.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/anonymize.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
|
||||
|
||||
|
||||
def _lm(script: list[str]) -> None:
|
||||
"""An engine replaying a script: one raw response per LM call."""
|
||||
class RawEngine:
|
||||
def __init__(self):
|
||||
self.i = 0
|
||||
def complete(self, request):
|
||||
raw = script[min(self.i, len(script) - 1)]
|
||||
self.i += 1
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
Q = "Who was the President before Pedro Sanchez?"
|
||||
_MASKED_ENTS = '''[[ ## entities ## ]]
|
||||
[{"name": "Pedro Sanchez", "kind": "PERSON"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_TWO_SUBS = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which office does PERSON_1 hold as President?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before PERSON_1 took office?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_apply_restore_deterministic():
|
||||
ents = [NamedEntity(name="Pedro Sanchez", kind="PERSON")]
|
||||
masked, restore = apply_mask(Q, ents)
|
||||
assert masked == "Who was the President before PERSON_1?", masked
|
||||
assert restore == {"PERSON_1": "Pedro Sanchez"}
|
||||
# longer first: a full name is never half-masked by a shorter one
|
||||
ents2 = [NamedEntity(name="Pedro Sanchez", kind="PERSON"),
|
||||
NamedEntity(name="Pedro", kind="PERSON")]
|
||||
m2, r2 = apply_mask("Pedro Sanchez and Pedro", ents2)
|
||||
assert m2 == "PERSON_1 and PERSON_2", m2
|
||||
assert restore_mask(m2, r2) == "Pedro Sanchez and Pedro"
|
||||
# restore order: PERSON_10 before PERSON_1
|
||||
r3 = {f"PERSON_{i}": f"name{i}" for i in range(1, 11)}
|
||||
assert "name10" in restore_mask("PERSON_10", r3)
|
||||
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
|
||||
|
||||
|
||||
def test_init_decompose_masks_and_restores():
|
||||
# script: first call = MASK, second = INIT
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS])
|
||||
subs, raw = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2, subs
|
||||
assert "Pedro Sanchez" in subs[0]["text"] and "PERSON_1" not in subs[0]["text"], subs[0]
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: INIT sees the masked query; subquestions come back restored")
|
||||
|
||||
|
||||
def test_no_entities_passthrough():
|
||||
_lm(['''[[ ## entities ## ]]
|
||||
[]
|
||||
|
||||
[[ ## completed ## ]]''', _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: no entities found -> question reaches INIT unchanged")
|
||||
|
||||
|
||||
_TWO_SUBS_ID = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Which office does PERSON_1 hold as President?", "depends_on": [1], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before PERSON_1?", "depends_on": [2], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_identity_subquestion_seeded():
|
||||
# the live PR-16 shape: subquestion 1 asks who PERSON_1 is — the mask
|
||||
# map already knows. It must come back marked known_answer, never routed.
|
||||
_lm([_MASKED_ENTS, _TWO_SUBS_ID])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 3, subs
|
||||
assert subs[0].get("known_answer") == "Pedro Sanchez", subs[0]
|
||||
assert not subs[1].get("known_answer") and not subs[2].get("known_answer")
|
||||
print("ok: identity subquestion carries known_answer (never routed)")
|
||||
|
||||
|
||||
def test_identity_detection_conservative():
|
||||
# 'who is PERSON_1's predecessor' is NOT an identity question
|
||||
r = {"PERSON_1": "Pedro Sanchez"}
|
||||
assert identity_answer("Who is PERSON_1?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
|
||||
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
|
||||
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
|
||||
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
|
||||
assert identity_answer("What office does PERSON_1 hold?", r) is None
|
||||
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
|
||||
print("ok: identity detection conservative (possessives/comparatives not eaten)")
|
||||
|
||||
|
||||
def test_mask_death_passthrough():
|
||||
# MASK response violates the schema -> AdapterParseError -> passthrough
|
||||
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
|
||||
subs, _ = FloopModules().init_decompose(Q)
|
||||
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
|
||||
print("ok: MASK death -> passthrough, never a dead run")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_apply_restore_deterministic()
|
||||
test_init_decompose_masks_and_restores()
|
||||
test_no_entities_passthrough()
|
||||
test_identity_subquestion_seeded()
|
||||
test_identity_detection_conservative()
|
||||
test_mask_death_passthrough()
|
||||
print("\nanonymization tests passed")
|
||||
@@ -0,0 +1,106 @@
|
||||
"""DATE answer type tests (his 22/10 local run: term-start answered '15').
|
||||
|
||||
Laws under test:
|
||||
1. AnswerType.DATE exists; INIT's enum desc mentions it (the schema the
|
||||
model sees carries the date guidance).
|
||||
2. _looks_like_date is deterministic and strict: a plausible YEAR is the
|
||||
admission bar — '15' alone, a month name alone, garbage: NOT dates.
|
||||
3. The machine refuses a DATE answer without a year: the row becomes
|
||||
UNKNOWN and the question fails (re-buttable honestly, never a silent
|
||||
wrong type flowing downstream into dependents).
|
||||
|
||||
No network. Run: .venv/bin/python tests/date_type.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.machine import _looks_like_date
|
||||
from floop.state import AnswerType, Budget, EvidenceRow, OpenQuestion
|
||||
from floop.machine import FloopRun
|
||||
|
||||
|
||||
def test_date_in_enum_and_desc():
|
||||
assert AnswerType.DATE.value == "DATE"
|
||||
from floop.dspy_modules import Subquestion
|
||||
import json
|
||||
schema = json.dumps(Subquestion.model_json_schema(), default=str)
|
||||
assert "DATE for a specific date" in schema, "desc must carry the date guidance"
|
||||
print("ok: AnswerType.DATE exists; the model-visible desc carries it")
|
||||
|
||||
|
||||
def test_looks_like_date():
|
||||
# admission: a plausible year
|
||||
for good in ("2 June 2018", "June 2018", "2018", "17 November 2023",
|
||||
"6–29 December 2023", "sworn in on 1 June 2018"):
|
||||
assert _looks_like_date(good), good
|
||||
# refusal: no year — the exact '15' shape from his run
|
||||
for bad in ("15", "June", "fifteen", "", "the fifteenth",
|
||||
"15 June", "239", "30000"):
|
||||
assert not _looks_like_date(bad), bad
|
||||
print("ok: _looks_like_date deterministic (year required; '15' refused)")
|
||||
|
||||
|
||||
def test_machine_rejects_bare_number_date():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class DateModules:
|
||||
def init_decompose(self, question):
|
||||
return [{"text": "When did the term begin?",
|
||||
"deps": [], "answer_type": "DATE"}], ""
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "date lookup"
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "15", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "synthesized"
|
||||
|
||||
run = FloopRun("Who was the President before X?", b, modules=DateModules())
|
||||
run._init_decompose() # creates Q1 (DATE) from init_decompose
|
||||
q1 = next(q for q in run.stack.items if q.text == "When did the term begin?")
|
||||
run._route_and_execute(q1)
|
||||
# the expert's '15' must NOT satisfy the DATE question
|
||||
assert q1.status == "failed", q1.status
|
||||
assert any("DATE answer rejected" in n for n in run.notes), run.notes
|
||||
print("ok: '15' rejected for a DATE question — row UNKNOWN, question failed")
|
||||
|
||||
|
||||
def test_machine_accepts_real_date():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class DateModules:
|
||||
def init_decompose(self, question):
|
||||
return [{"text": "When did the term begin?",
|
||||
"deps": [], "answer_type": "DATE"}], ""
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "date lookup"
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "2 June 2018", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "synthesized"
|
||||
|
||||
run = FloopRun("Who was the President before X?", b, modules=DateModules())
|
||||
run._init_decompose()
|
||||
q1 = next(q for q in run.stack.items if q.text == "When did the term begin?")
|
||||
run._route_and_execute(q1)
|
||||
assert q1.status == "answered", q1.status
|
||||
print("ok: '2 June 2018' accepted for a DATE question")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_date_in_enum_and_desc()
|
||||
test_looks_like_date()
|
||||
test_machine_rejects_bare_number_date()
|
||||
test_machine_accepts_real_date()
|
||||
print("\nDATE type tests passed")
|
||||
+144
-128
@@ -1,20 +1,24 @@
|
||||
"""PR-6 tests: INIT parsing robustness + the raw-response log (run I).
|
||||
"""PR-10b tests: typed INIT via dspy native structured output.
|
||||
|
||||
Run I: asked 'Who was the President before Pedro Sanchez?' the INIT LM
|
||||
answered with its own line numbers as an extra pipe field
|
||||
('1 | Who was Pedro Sanchez? | none | OPEN'), the naive parse took '1'
|
||||
and '2' as the subquestion texts, ROUTE classified Q1='1' as numeric and
|
||||
the machine burned 4 calls on garbage before luck produced the answer.
|
||||
Run I taught the pipe parser every defensive trick (line-number shifting,
|
||||
bare-number dropping). The typed migration removes the string contract
|
||||
entirely: dspy renders the Subquestion schema (enum answer_type,
|
||||
list[int] depends_on) into the prompt and parses responses back into
|
||||
typed objects — no Python string parsing on the production path.
|
||||
|
||||
Three laws under test:
|
||||
1. parse_subquestions shifts the numbered form and never accepts a bare
|
||||
number as a subquestion text.
|
||||
2. The machine degrades to the ORIGINAL question as one OPEN
|
||||
subquestion when nothing parses (a routable question is text).
|
||||
3. The prompt log appends the RAW LM response to the prompt file — the
|
||||
parsed OUTPUT line can lie by omission.
|
||||
Laws under test:
|
||||
1. The typed path E2E: a model response (raw text, through a REAL
|
||||
dspy.LM engine) parses into typed Subquestions; the machine dicts
|
||||
carry text, depends_on ints, and the AnswerType enum.
|
||||
2. Bare-number texts are still dropped (run-I law, now in
|
||||
_subs_from_typed).
|
||||
3. A schema-violating response (AdapterParseError, even after dspy's
|
||||
own JSON re-ask) becomes the degrade signal: (subs=[], raw) — the
|
||||
machine routes the ORIGINAL question, never garbage.
|
||||
4. The atomic case (empty subquestions list) stays atomic.
|
||||
|
||||
No network, no real LLM. Run: .venv/bin/python tests/robust_init.py
|
||||
No network. The engine returns raw text — DummyLM would bypass the
|
||||
adapter and test nothing. Run: .venv/bin/python tests/robust_init.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,151 +27,163 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.dspy_modules import parse_subquestions
|
||||
import dspy
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from floop.dspy_modules import FloopModules, Subquestion
|
||||
from floop.state import AnswerType, Budget
|
||||
from floop.machine import FloopRun
|
||||
|
||||
import tempfile as tf
|
||||
from floop.stream import RunStreams
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
|
||||
# --- 1) the parser -----------------------------------------------------------
|
||||
|
||||
def test_parse_numbered_lines():
|
||||
# the exact run-I shape: model line numbers as an extra first field
|
||||
raw = ("1 | Who was the President of Spain before Pedro Sanchez? | none | OPEN\n"
|
||||
"2 | When did that president's term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
"""A dspy.LM whose engine returns raw text — the REAL wire shape.
|
||||
cache=False: dspy persists responses to disk keyed by (model, prompt)
|
||||
and would cross-contaminate tests sharing the fake model name."""
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(),
|
||||
cache=False))
|
||||
|
||||
|
||||
# a canonical typed response, markers and all
|
||||
_GOOD = '''[[ ## subquestions ## ]]
|
||||
[{"text": "Which presidency does Pedro Sanchez hold?", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that same office before him?", "depends_on": [1], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
|
||||
|
||||
def test_typed_init_e2e():
|
||||
_lm(_GOOD)
|
||||
subs, raw = FloopModules().init_decompose(
|
||||
"Who was the President before Pedro Sanchez?")
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President of Spain before Pedro Sanchez?"
|
||||
assert subs[0]["deps"] == []
|
||||
assert subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1], subs[1]
|
||||
print("ok: numbered-line form shifted (text, deps, type all intact)")
|
||||
|
||||
|
||||
def test_parse_bare_number_lines_dropped():
|
||||
# even if the number survives as text, it must be dropped — never routable
|
||||
raw = "1 | none | OPEN\n2 | none | OPEN"
|
||||
subs = parse_subquestions(raw)
|
||||
assert subs == [], subs
|
||||
print("ok: bare-number texts dropped (nothing routable = '1' or '2')")
|
||||
|
||||
|
||||
def test_parse_enumerator_prefix():
|
||||
# '1. Who was ...' inside the FIRST field — not a separate field
|
||||
raw = ("1. Who was the President before Pedro Sanchez? | none | OPEN\n"
|
||||
"2. When did his term end? | 1 | OPEN")
|
||||
subs = parse_subquestions(raw)
|
||||
assert len(subs) == 2, subs
|
||||
assert subs[0]["text"] == "Who was the President before Pedro Sanchez?"
|
||||
assert subs[0]["text"] == "Which presidency does Pedro Sanchez hold?"
|
||||
assert subs[0]["deps"] == [] and subs[0]["answer_type"] == AnswerType.OPEN
|
||||
assert subs[1]["deps"] == [1]
|
||||
print("ok: enumerator prefixes stripped from the text field")
|
||||
print("ok: typed INIT parses through the real adapter path (E2E)")
|
||||
|
||||
|
||||
def test_parse_happy_path_unchanged():
|
||||
# the old well-formed cases keep working (regression guard)
|
||||
subs = parse_subquestions(
|
||||
"1. How many qubits are needed? | none | FUNCTION\n"
|
||||
"2. What is the clock speed? | 1 | INTERVAL\n")
|
||||
assert subs[0]["text"].endswith("needed?") and subs[0]["deps"] == []
|
||||
assert subs[1]["deps"] == [1] and subs[1]["answer_type"] == AnswerType.INTERVAL
|
||||
assert parse_subquestions("") == []
|
||||
assert parse_subquestions("|||\n1 | none | OPEN") == []
|
||||
print("ok: well-formed lines parse exactly as before")
|
||||
def test_bare_number_text_dropped():
|
||||
raw = '''[[ ## subquestions ## ]]
|
||||
[{"text": "1", "depends_on": [], "answer_type": "OPEN"},
|
||||
{"text": "Who held that office before?", "depends_on": [], "answer_type": "OPEN"}]
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
subs, _ = FloopModules().init_decompose("Who was the President before?")
|
||||
assert [s["text"] for s in subs] == ["Who held that office before?"], subs
|
||||
print("ok: bare-number texts dropped (run-I law survives typing)")
|
||||
|
||||
|
||||
# --- 2) the INIT degrade -----------------------------------------------------
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
# (subs, raw): nothing parses, but the model DID write — degrade
|
||||
return (parse_subquestions("1 | none | OPEN\n2 | 1 | OPEN"),
|
||||
"1 | none | OPEN\n2 | 1 | OPEN")
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [], "answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
def test_garbage_degrades():
|
||||
# run-I shape: the model wrote its own line numbers, none parse to a
|
||||
# valid schema — after dspy's re-ask the AdapterParseError carries the
|
||||
# garbage; init_decompose must signal (subs=[], raw non-empty)
|
||||
garbage = "1\n2"
|
||||
_lm(garbage)
|
||||
subs, raw = FloopModules().init_decompose("Who was the President before?")
|
||||
assert subs == [] and raw and raw.strip(), (subs, raw)
|
||||
print(f"ok: schema-violating garbage -> degrade signal (raw: {raw[:20]!r})")
|
||||
|
||||
|
||||
def test_init_degrades_to_original_question():
|
||||
def test_garbage_machine_degrades_to_original():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
fm = GarbageInitModules()
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b, modules=fm)
|
||||
|
||||
class GarbageInitModules:
|
||||
"""INIT returns zero parseable subquestions (the run-I transcript)."""
|
||||
|
||||
def init_decompose(self, question):
|
||||
return [], "1\n2" # garbage raw — degrade path
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return [{"text": "fallback question?", "deps": [],
|
||||
"answer_type": "OPEN"}]
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
assert not question.strip().isdigit(), f"garbage routed: {question!r}"
|
||||
return "knowledge", "text question"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "Mariano Rajoy", "source_quote": "",
|
||||
"confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "Mariano Rajoy"
|
||||
|
||||
run = FloopRun("Who was the President before Pedro Sanchez?", b,
|
||||
modules=GarbageInitModules())
|
||||
rep = run.run()
|
||||
# the machine must have routed the ORIGINAL question, not '1'/'2'
|
||||
assert rep is not None
|
||||
q1 = rep.questions[0]
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1 # text, never a bare number
|
||||
assert q1[2] and not q1[2].strip().isdigit(), q1
|
||||
assert "Pedro Sanchez" in q1[2]
|
||||
assert all(not q[2].strip().isdigit() for q in rep.questions), rep.questions
|
||||
print("ok: INIT degrade routes the original question as one OPEN subq")
|
||||
print("ok: INIT degrade routes the ORIGINAL question as one OPEN subq")
|
||||
|
||||
|
||||
# --- 3) the raw-response log --------------------------------------------------
|
||||
def test_empty_stays_atomic():
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
def test_prompt_log_captures_raw_response():
|
||||
import dspy
|
||||
from dspy.utils.dummies import DummyLM
|
||||
import tempfile as tf
|
||||
from floop.llm import PromptLogCallback, install_prompt_log
|
||||
from floop.stream import RunStreams
|
||||
class AtomicModules:
|
||||
def init_decompose(self, question):
|
||||
return [], "" # truly empty — atomic
|
||||
|
||||
def missing_decompose(self, goal, evidence):
|
||||
return []
|
||||
|
||||
def route_question(self, question, catalog, evidence):
|
||||
return "knowledge", "text"
|
||||
|
||||
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||
return {"value": "299792458", "source_quote": "", "confidence": "high"}
|
||||
|
||||
def synthesize(self, goal, evidence, unverified):
|
||||
return "299792458"
|
||||
|
||||
rep = FloopRun("What is the speed of light?", b,
|
||||
modules=AtomicModules()).run()
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0"
|
||||
assert rep.questions[0][2] == "What is the speed of light?"
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
|
||||
def test_prompt_log_still_captures_raw():
|
||||
# PR-4/9 law: the RAW LM response is appended to the prompt file — now
|
||||
# for the typed path too (the engine's raw text is what gets logged)
|
||||
dspy.settings.configure(callbacks=[])
|
||||
streams = RunStreams("raw resp test", verbose=False, runs_dir=tf.mkdtemp())
|
||||
cb = PromptLogCallback(streams)
|
||||
dspy.configure(lm=DummyLM([
|
||||
{"subquestions": "1 | Who was Pedro Sanchez? | none | OPEN"}
|
||||
]), callbacks=[cb])
|
||||
|
||||
class Sig(dspy.Signature):
|
||||
question: str = dspy.InputField()
|
||||
subquestions: str = dspy.OutputField()
|
||||
|
||||
dspy.Predict(Sig)(question="Who was the President before Pedro Sanchez?")
|
||||
_lm(_GOOD)
|
||||
dspy.configure(callbacks=[cb])
|
||||
FloopModules().init_decompose("Who was the President before Pedro Sanchez?")
|
||||
f = next((streams.run_dir / "prompts").glob("01-*.txt"))
|
||||
content = f.read_text()
|
||||
assert "# RAW RESPONSE" in content, content
|
||||
assert "Who was Pedro Sanchez?" in content, content
|
||||
assert "presidency does Pedro Sanchez" in content, content
|
||||
print(f"ok: raw response appended to {f.name}")
|
||||
dspy.settings.configure(callbacks=[])
|
||||
|
||||
|
||||
|
||||
def test_empty_raw_stays_atomic():
|
||||
"""Empty RAW (the model truly returned nothing) keeps the old law: the
|
||||
goal is atomic — stop and synthesize, never fabricate a subquestion."""
|
||||
b = Budget(max_llm_calls=40, max_depth=2, max_retries=3,
|
||||
missing_extensions=1, min_child_budget=4)
|
||||
|
||||
class AtomicModules(GarbageInitModules):
|
||||
def init_decompose(self, question):
|
||||
return [], ""
|
||||
|
||||
fm = AtomicModules()
|
||||
rep = FloopRun("What is the speed of light?", b, modules=fm).run()
|
||||
# atomic: INIT added no subquestions — only the goal's own Q0 remains
|
||||
assert len(rep.questions) == 1, rep.questions
|
||||
assert rep.questions[0][0] == "Q0", rep.questions
|
||||
assert rep.questions[0][2] == "What is the speed of light?", rep.questions
|
||||
print("ok: empty raw stays atomic (no fabricated subquestion)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_parse_numbered_lines()
|
||||
test_parse_bare_number_lines_dropped()
|
||||
test_parse_enumerator_prefix()
|
||||
test_parse_happy_path_unchanged()
|
||||
test_init_degrades_to_original_question()
|
||||
test_empty_raw_stays_atomic()
|
||||
test_prompt_log_captures_raw_response()
|
||||
print("\nrobust_init tests passed")
|
||||
test_typed_init_e2e()
|
||||
test_bare_number_text_dropped()
|
||||
test_garbage_degrades()
|
||||
test_garbage_machine_degrades_to_original()
|
||||
test_empty_stays_atomic()
|
||||
test_prompt_log_still_captures_raw()
|
||||
print("\ntyped-INIT tests passed")
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Typed EXPERT + ANSWER tests (the last floop signatures): confidence is
|
||||
a closed enum; unverified is a real bool InputField.
|
||||
|
||||
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
|
||||
Run: .venv/bin/python tests/typed_expert.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_expert_confidence_enum():
|
||||
raw = '''[[ ## value ## ]]
|
||||
Mariano Rajoy
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
his predecessor Mariano Rajoy
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
high
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
out = FloopModules().expert_draft("Who was the President before Pedro Sanchez?",
|
||||
"knowledge", "E1: his predecessor Mariano Rajoy")
|
||||
assert out["value"] == "Mariano Rajoy" and out["confidence"] == "high", out
|
||||
print("ok: typed EXPERT parses confidence enum through the real path")
|
||||
|
||||
|
||||
def test_expert_bad_confidence_raises():
|
||||
raw = '''[[ ## value ## ]]
|
||||
42
|
||||
|
||||
[[ ## source_quote ## ]]
|
||||
|
||||
[[ ## confidence ## ]]
|
||||
certain
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().expert_draft("q", "knowledge", "")
|
||||
raise AssertionError("bad confidence parsed — enum broken")
|
||||
except AdapterParseError:
|
||||
print("ok: confidence outside the enum raises AdapterParseError")
|
||||
|
||||
|
||||
def test_answer_bool_input():
|
||||
# the bool InputField renders as a plain value in the prompt and the
|
||||
# string answer parses; synthesize passes a real bool now
|
||||
raw = '''[[ ## final_answer ## ]]
|
||||
Mariano Rajoy (E1).
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
ans = FloopModules().synthesize("Who was the President before Pedro Sanchez?",
|
||||
"E1: Mariano Rajoy", unverified=True)
|
||||
assert ans == "Mariano Rajoy (E1).", ans
|
||||
print("ok: ANSWER takes a bool unverified and parses through the real path")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_expert_confidence_enum()
|
||||
test_expert_bad_confidence_raises()
|
||||
test_answer_bool_input()
|
||||
print("\ntyped EXPERT+ANSWER tests passed")
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Typed ROUTE tests: the attendant is a closed enum — invalid picks are
|
||||
impossible by schema (a response outside the set raises AdapterParseError
|
||||
after dspy's own re-ask).
|
||||
|
||||
No network; the engine returns raw text (DummyLM bypasses the adapter —
|
||||
useless here). Run: .venv/bin/python tests/typed_route.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
import warnings
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
import dspy
|
||||
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
||||
from dspy.utils.exceptions import AdapterParseError
|
||||
|
||||
from floop.dspy_modules import FloopModules
|
||||
|
||||
|
||||
def _lm(scripted_raw: str) -> None:
|
||||
class RawEngine:
|
||||
def complete(self, request):
|
||||
return Response(
|
||||
id="x", model="t",
|
||||
message=Message(role="assistant",
|
||||
parts=(TextPart(text=scripted_raw),)),
|
||||
finish_reason="stop",
|
||||
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
|
||||
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
|
||||
|
||||
|
||||
def test_route_valid_enum():
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
knowledge
|
||||
|
||||
[[ ## reason ## ]]
|
||||
A factual lookup of who held the office before.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
attendant, reason = FloopModules().route_question(
|
||||
"Who was the President before Pedro Sanchez?", "catalog", "")
|
||||
assert attendant == "knowledge", attendant
|
||||
assert reason.startswith("A factual")
|
||||
print("ok: typed ROUTE parses through the real adapter path")
|
||||
|
||||
|
||||
def test_route_invalid_attendant_raises():
|
||||
# outside the closed set -> schema violation -> AdapterParseError
|
||||
# (dspy's JSON re-ask gets the same bad value back and gives up)
|
||||
raw = '''[[ ## attendant ## ]]
|
||||
wikipedia
|
||||
|
||||
[[ ## reason ## ]]
|
||||
It's an encyclopedia.
|
||||
|
||||
[[ ## completed ## ]]'''
|
||||
_lm(raw)
|
||||
try:
|
||||
FloopModules().route_question("q", "catalog", "")
|
||||
raise AssertionError("invalid attendant parsed — enum contract broken")
|
||||
except AdapterParseError:
|
||||
print("ok: attendant outside the enum raises AdapterParseError (schema holds)")
|
||||
|
||||
|
||||
def test_route_enum_compatibility():
|
||||
# the machine's comparisons survive typing: Attendant mixes str
|
||||
from floop.machine import EXPERT_ENGINES
|
||||
from floop.dspy_modules import Attendant
|
||||
assert Attendant.FLOOP == "floop"
|
||||
assert Attendant.KNOWLEDGE in EXPERT_ENGINES
|
||||
assert Attendant.USER not in EXPERT_ENGINES
|
||||
print("ok: enum is str-compatible — machine comparisons unchanged")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_route_valid_enum()
|
||||
test_route_invalid_attendant_raises()
|
||||
test_route_enum_compatibility()
|
||||
print("\ntyped-ROUTE tests passed")
|
||||
Reference in New Issue
Block a user