research/semantic-kg: semantic probe + conflict taxonomy + temporal layer + derived-answer prover #24

Merged
onibot merged 14 commits from research/semantic-kg into main 2026-10-25 21:40:18 +01:00
17 changed files with 2422 additions and 127 deletions
+381
View File
@@ -0,0 +1,381 @@
# 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).
**LIVE RESULT (run 20261025-201413, cold KG, glm-5.3-flash, f32a6db):**
204 edges, **0 conflicts** (was 20), 30 alternatives, 0 same_as. The
three presidencies land pairwise in alternatives and
alternatives_of('pedro sanchez','position held') returns the co-true
set — the ambiguity substrate is queryable at ingest time. Rajoy
answered correctly, judge values clean (phase 0 alive in the pipeline).
Honest noise, accepted by design (do NOT "fix" with word lists — the
run-J lesson): cross-quote conjunctions (the ministers he appointed)
land in alternatives too. Same-quote pairs are caught by provenance;
cross-quote conjunction is indistinguishable from co-true readings
WITHOUT the temporal layer (phase 2 windows + per-relation
functionality statistics). The bucket is neutral; the consumer
(audit / fork) decides which alternatives are defensible readings FOR
A QUESTION. Known follow-ups: same_as recorded but not yet consumed
by probe/render (phase 4); paraphrase via tail resolution needs the
extractor to RESOLVE dst_node more often (most live edges carry
dst_node=None — the paraphrase signal rarely fires).
### 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.
**SHIPPED (3a `fb61268` + 3b `ee315e0`) — live-verified (run
20261025-211302, cold KG, glm-5.3-flash):** 3a pinned the evaluator
first (prover.py 5/5: the three-presidency fixture returns the three
bindings as a set; the predecessor proves RAJOY as a closed path
citing both edges; empty = UNKNOWN; re-execution FAILS a stale proof
after a retraction — the check is real). 3b wired it: TranslateToDSL
(one structured call, the store's relation vocabulary in),
validate_query as the shared grammar gate (a mistranslation is an
invalid term, NEVER executed), _prover_answer BEFORE any judge with
honest fallback on decline/no-path/re-execution-mismatch.
LIVE: the gate caught a live invalid term ("no lookup" — the model
proposed a filterless shape for the date question; rejected
deterministically, judge answered 2018 clean); Q2's predecessor
needed the judge (this run's KG lacked Rajoy's closed window — the
blind extractor did not transcribe t_end), final Rajoy correct.
Honest gap to close in phase 4: the prover closes only when the KG
holds the needed windows; either the EXTRACT prompt asks for
start/end more explicitly, or `before` degrades to start-vs-start
comparison when the old holder's end is open.
### 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.
+1
View File
@@ -168,6 +168,7 @@ _STAGE_BY_MODULE = {
"SelectTableSignature": "SELECT_TABLE",
"VerifyCountSignature": "VERIFY_COUNT",
"SkimPromoteSignature": "PROMOTE",
"SkimTableSignature": "SKIM_TABLE",
}
+214
View File
@@ -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).
+7
View File
@@ -42,4 +42,11 @@ def check_candidate(cand: dict, full_text: str) -> tuple[bool, str]:
subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
if not (subj and rel and obj):
return False, "incomplete triple"
# phase 2: temporal restrictions are quotable — every stated date must
# be CONTAINED IN THE QUOTE (an invented date rejects the candidate;
# the model proposes, code verifies against the source surface)
for field in ("start", "end", "point"):
val = (cand.get(field) or "").strip()
if val and val not in quote:
return False, f"temporal {field} not in quote"
return True, "ok"
+54
View File
@@ -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)
+304 -77
View File
@@ -1,16 +1,21 @@
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
Per question (one routed knowledge call):
1. COMPOSE: question + evidence -> queries/entities [engine]
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. COMPOSE: question + evidence -> queries/entities (deterministic) [engine]
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,13 @@ 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, VerifyCountSignature)
SkimPromoteSignature, SkimTableSignature,
VerifyCountSignature)
from .embeddings import EmbedderDown, embed
from .queries import compose_queries, keywords, proper_nouns
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']+")
@@ -149,6 +156,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:
@@ -166,8 +179,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] = []
@@ -180,6 +198,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 — delegates to knowledge/queries.py
@@ -227,6 +288,87 @@ class KnowledgeExpert:
"ranked": ordered}}
# ---- the pipeline --------------------------------------------------------
def _prover_answer(self, question: str, charge_llm=None) -> dict | None:
"""The derived-answer path (phase 3b): translate -> validate ->
evaluate -> re-execute. Returns the answer dict with the proof
term, or None to fall back to the judge.
The laws, end to end: the LLM only TRANSLATES (one structured
call, the store's relation vocabulary in); the term is validated
BEFORE evaluation (a mistranslation is an invalid term, never a
wrong answer); the proof's steps name every edge; re-execution
IS the check (verified=True with a real prover, not a flag);
multi-binding returns the SET with ambiguous=True — the three
readings surface as what they are, deterministically.
"""
from .prover import evaluate, re_execute, validate_query
from .translate_dsl import TranslateToDSL
if not hasattr(self, "translate_dsl"):
self.translate_dsl = dspy.Predict(TranslateToDSL)
rels = [r[0] for r in self.store.db.execute(
"SELECT DISTINCT rel FROM edges WHERE retracted=0 "
"ORDER BY rel LIMIT 200").fetchall()]
if not rels:
return None
if charge_llm:
charge_llm()
try:
pred = self.translate_dsl(question=question,
relations=", ".join(rels))
except Exception as e: # noqa: BLE001 — translation failure = fallback
self._log(f"translate-to-DSL failed ({e!r}); judge path", think=True)
return None
q = getattr(pred, "query", None)
if not q:
return None # the model honestly declined
ok, reason = validate_query(q)
if not ok:
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
return None
proof = evaluate(self.store, q)
if not proof.bindings:
self._log(f"prover: no closed path; judge path", think=True)
return None
if not re_execute(self.store, q, proof):
self._log("prover: re-execution mismatch (store changed?); judge path",
think=True)
return None
vals = []
quote = ""
url = ""
for b in proof.bindings:
v = next((bv["value"] for k, bv in b.items()
if isinstance(bv, dict) and bv.get("value")), None)
if v:
vals.append(v)
if not quote:
eid = next((bv["eid"] for k, bv in b.items()
if isinstance(bv, dict) and bv.get("eid")), None)
if eid:
row = self.store.db.execute(
"SELECT q.verbatim, q.url FROM quotes q "
"JOIN edges e ON e.quote_id=q.id WHERE e.id=?",
(eid,)).fetchone()
if row:
quote, url = row
n = len(vals)
if n == 1:
answer = {"value": vals[0], "quote": quote, "url": url,
"source": "derived_proof", "confidence": "high",
"verified": True, "proof": proof}
else:
answer = {"value": "; ".join(vals), "quote": quote, "url": url,
"source": "derived_proof", "confidence": "high",
"verified": True, "proof": proof,
"ambiguous": True,
"axis": f"which reading of '{question[:60]}'?",
"alternatives": [{"value": v, "quote": quote, "url": url}
for v in vals]}
self._log(f"prover: closed path ({n} binding(s): "
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
think=True)
return answer
def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None,
answer_type: str = "") -> dict:
@@ -244,11 +386,26 @@ class KnowledgeExpert:
goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these
self._current_goal_question = parent_question or question
# ---- phase 3b: the derived-answer engine, BEFORE any judge ----
# If the question translates to the DSL and the store closes the
# path, the proof term IS the answer (re-execution = the check,
# verified=True) — the judge never runs on this question. No
# translation or no closed path -> the judge path, unchanged.
try:
proven = self._prover_answer(question, charge_llm)
except Exception as e: # noqa: BLE001 — the prover must never kill a run
self._log(f"prover path failed ({e!r}); judge path", think=True)
proven = None
if proven is not None:
return proven
# per-CALL skim state (PR-3): notices for the machine + ambiguous
# leads pending the bounded promotion decision
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"):
@@ -262,15 +419,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
@@ -289,13 +445,14 @@ class KnowledgeExpert:
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
"source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. COMPOSE (deterministic — the old
# TRANSLATE LLM, 23/10): queries from question ∪ evidence only;
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
# the model's own knowledge of the entities can no longer steer
# retrieval (it was putting the ANSWER into queries: 'Pedro
# Sánchez 2018 investiture…' for a term-start question).
# retrieval) + the branch's extract-entities contract: the
# question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode)
self._extract_entities = list(dict.fromkeys(
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}",
think=True)
@@ -407,12 +564,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),
@@ -421,8 +578,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"
@@ -933,14 +1090,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
@@ -952,15 +1117,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))
@@ -972,22 +1167,28 @@ 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]}")
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
text=chunk.text)
# phase 2: ingest with order assertions — fact_ids collects the
# edge id per 0-based position in THIS extraction's facts list,
# so 'orders' sibling references resolve to real edges
fact_ids: list[int | None] = []
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
merged, eid = self._ingest_candidate(cand, page, containment=page.text)
extracted += merged
fact_ids.append(eid)
# second pass: the order assertions of all facts of this chunk
for cand, fid in zip((raw.facts or [])[: self.cfg.max_facts_per_chunk], fact_ids):
if fid is None:
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
for o in (getattr(cand, "orders", None) or []):
other = o.get("other")
rel = o.get("rel")
if (other is None or rel not in ("before", "after", "concurrent")
or not 0 <= other < len(fact_ids)
or fact_ids[other] is None):
continue # malformed reference: skip honestly
self.store.add_fact_order(fid, fact_ids[other], rel)
# ---- table fragments (extract path) -----------------------------
from .store import stem as _stem
# containment target: prose + ALL table rows (the fragment's rows
@@ -1011,34 +1212,60 @@ 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_table:
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]:
merged, _eid = self._ingest_candidate(cand, page, containment=containment)
extracted += merged
return self._merged
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> tuple[int, int | None]:
"""Containment-check one typed Fact, merge it, cache its vector.
Returns (merged, eid): merged=1 when the candidate was accepted
(a duplicate counts — corroboration was recorded), eid=None when
no NEW edge was created (duplicate or reject). Phase 2: the CALLER
wires order assertions through the returned eid."""
self._checked += 1
cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote,
"start": getattr(cand, "start", None),
"end": getattr(cand, "end", None),
"point": getattr(cand, "point", None)}
ok, reason = check_candidate(cand, containment)
if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
return 0, None
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,
t_start=cand["start"] or None,
t_end=cand["end"] or None)
self._merged += 1
if eid is not None:
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
cand["object"])
return 1, eid
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
+66 -12
View File
@@ -20,31 +20,56 @@ class Confidence(str, Enum):
class Fact(BaseModel):
"""One fact extracted from a text, with its verbatim supporting quote."""
"""One fact extracted from a text, with its verbatim supporting quote
and its TEMPORAL RESTRICTIONS (phase 2 — restrictions, never Allen
labels; the algebra is a computed view over these endpoints).
All temporal fields are optional and must be CONTAINED IN THE QUOTE
(an invented date fails the containment check and the whole fact is
rejected — the honest law). 'since YYYY' means start=YYYY, end OPEN.
Granularity is honest precision: 'year' | 'month' | 'day'.
orders: temporal-order assertions BETWEEN SIBLING FACTS of the same
extraction, by their 0-based position in the same facts list —
{rel: before|after|concurrent, other: <index>}."""
subject: str = dspy.OutputField(desc="the fact's subject entity")
relation: str = dspy.OutputField(desc="the relation between subject and object")
object: str = dspy.OutputField(desc="the fact's object / value")
quote: str = dspy.OutputField(
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
start: str | None = dspy.OutputField(
default=None,
desc="when the fact begins, as stated in the text (a year like 2018, or a full date); empty when the text states no start")
end: str | None = dspy.OutputField(
default=None,
desc="when the fact ends, as stated in the text; empty when ongoing/unknown")
point: str | None = dspy.OutputField(
default=None,
desc="for point-in-time facts (events): the stated date; empty otherwise")
granularity: str | None = dspy.OutputField(
default=None,
desc="precision of the stated dates: year, month, or day; empty when no dates")
orders: list[dict] = dspy.OutputField(
default_factory=list,
desc="temporal order between THIS fact and SIBLING facts of the same list, "
"ONLY when the text asserts it with a connective (before/after/at the same "
"time as); each entry {rel: before|after|concurrent, other: <0-based index "
"of the sibling fact>}; empty when the text asserts no order")
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_table=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_table: bool = dspy.OutputField(
desc="True when this table fragment's subject is wrong for the question")
class AnswerFromKG(dspy.Signature):
@@ -121,6 +146,35 @@ class SkimPromoteSignature(dspy.Signature):
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]:
"""LEGACY pipe parser — kept ONLY for tests that script extractor
responses as text. Production code consumes typed `Fact` objects from
+224
View File
@@ -0,0 +1,224 @@
"""The derived-answer engine (phase 3a, RESEARCH-derived-answers Part 3).
No LLM in the loop. The query is a small TYPED DSL (conjunctive +
temporal, hand-writable — the LLM translator arrives in 3b); the
evaluation is goal-directed over the store; THE ANSWER IS THE PROOF
TERM: every step names its operator and the edge ids it consumed, and
re-execution over the store IS the verification (deterministic, no
model). This is the Logic-LM move of the lineage applied to floop's
own layer: LLMs translate at the two ends, fixed code decides inside.
DSL (the subset pinned by tests/prover.py):
{"lookup": {subject, rel_any, bind} | [lookups...]
"filter": [{open_now: [var]}, {before: [a, b]}, {neq_value: [var, lit]}]
"select": "all" | "latest_end"}
lookup binds `var` to every matching edge (subject exact-normalized,
rel in rel_any). A second lookup may carry same_value_as: var — a join
on the bound value (the SAME office, a different holder). Filters:
open_now (the edge's window is open now — end None or >= today's
year), before (window a ends before window b starts — the interval
succession law), neq_value (a bound subject differs from a literal —
exclusion of the queried entity itself). select: all (the binding SET
— multi-binding IS the ambiguity) or latest_end (the most recent
closed window among the surviving bindings — the predecessor).
Evaluation semantics, honestly narrow:
- values compare through norm_name (the store's normalization);
- `before` requires BOTH windows to have real endpoints on the
compared sides — an open end is NOT "before" anything (the world
moved on, we cannot prove when);
- select=latest_end sorts by t_end descending, requiring a real t_end;
- nothing is ever invented: no closed path -> empty bindings (UNKNOWN).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from .store import KnowledgeStore, norm_name
_THIS_YEAR = "2026" # open_now: an open end or an end >= today coexists
_KNOWN_FILTERS = {"open_now", "before", "neq_value"}
_KNOWN_SELECTS = {"all", "latest_end"}
def validate_query(q: Any) -> tuple[bool, str]:
"""The shared grammar: a DSL term type-checks BEFORE evaluation.
The translator (LLM) proposes; this deterministic gate decides. A
mistranslation surfaces as an invalid term — unknown filter, unknown
select, empty rel_any, malformed lookup — and NEVER reaches
evaluate(): no wrong answer can hide inside an unexecutable query.
Returns (ok, reason).
"""
if not isinstance(q, dict) or not q:
return False, "empty or non-dict query"
lookups = q.get("lookup")
if isinstance(lookups, dict):
lookups = [lookups]
if not lookups or not isinstance(lookups, list):
return False, "no lookup"
for lk in lookups:
if not isinstance(lk, dict) or not lk.get("subject"):
return False, "lookup without subject"
if not lk.get("rel_any"):
return False, "lookup without rel_any"
if not isinstance(lk["rel_any"], list):
return False, "rel_any not a list"
if not lk.get("bind"):
return False, "lookup without bind var"
for f in q.get("filter", []):
if not isinstance(f, dict) or len(f) != 1:
return False, f"malformed filter {f!r}"
key = next(iter(f))
if key not in _KNOWN_FILTERS:
return False, f"unknown filter {key!r}"
if not isinstance(f[key], list):
return False, f"filter args not a list: {key}"
sel = q.get("select", "all")
if sel not in _KNOWN_SELECTS:
return False, f"unknown select {sel!r}"
return True, "ok"
@dataclass
class Step:
op: str # lookup | filter | select
note: str = ""
edges: list[int] = field(default_factory=list)
@dataclass
class Proof:
bindings: list[dict] = field(default_factory=list)
steps: list[Step] = field(default_factory=list)
def _edges_of(store: KnowledgeStore, subject: str, rel_any: list[str]) -> list:
"""All live edges of one subject under any of the rels (order: id)."""
rows = store.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name "
"FROM edges e JOIN nodes n ON n.id=e.src_node "
"WHERE n.norm_name=? AND e.retracted=0 ORDER BY e.id",
(norm_name(subject),)).fetchall()
return [r for r in rows if r[1] in rel_any]
def _row_to_binding(var: str, r) -> dict:
return {var: {"eid": r[0], "rel": r[1], "value": r[2],
"start": r[3], "end": r[4], "subject": r[5]}}
def _window_open_now(b: dict) -> bool:
end = b["end"]
return end is None or end >= _THIS_YEAR
def _before(a: dict, b: dict) -> bool:
"""Window a ENDED before window b STARTED. Both sides must be real —
an open end is not 'before' anything (honesty: no invented dates)."""
if a["end"] is None or b["start"] is None:
return False
return a["end"] <= b["start"] # year granularity, closed-open
def evaluate(store: KnowledgeStore, query: dict) -> Proof:
"""Goal-directed evaluation. Returns the proof term (bindings + steps)."""
proof = Proof()
lookups = query.get("lookup")
if isinstance(lookups, dict):
lookups = [lookups]
# ---- first lookup: bind every matching edge -------------------------
first = lookups[0]
var = first["bind"]
rows = _edges_of(store, first["subject"], first.get("rel_any", []))
proof.steps.append(Step("lookup", f"bind {var}: subject={first['subject']} "
f"rels={first.get('rel_any')}",
[r[0] for r in rows]))
bindings = [_row_to_binding(var, r) for r in rows]
# ---- further lookups: JOIN on the bound value -----------------------
for lk in lookups[1:]:
jvar = lk["bind"]
joined = []
for b in bindings:
same = b[lk.get("same_value_as", var)]["value"]
# the joining side's subject may be a VARIABLE (?x): iterate
# every live edge under the rels and keep value matches
rows = store.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name "
"FROM edges e JOIN nodes n ON n.id=e.src_node "
"WHERE e.rel IN (%s) AND e.retracted=0 ORDER BY e.id"
% ",".join("?" * len(lk.get("rel_any", []))),
tuple(lk.get("rel_any", []))).fetchall()
for r in rows:
if norm_name(r[2]) == norm_name(same):
nb = dict(b)
nb[jvar] = {"eid": r[0], "rel": r[1], "value": r[2],
"start": r[3], "end": r[4], "subject": r[5]}
nb["?x"] = r[5] # the OTHER holder
joined.append(nb)
proof.steps.append(Step("lookup", f"join {jvar} on value={same}",
[r[0]]))
bindings = joined
# ---- filters ----------------------------------------------------------
for f in query.get("filter", []):
for key, args in f.items():
kept = []
for b in bindings:
if key == "open_now":
ok = _window_open_now(b[args[0]])
elif key == "before":
ok = _before(b[args[0]], b[args[1]])
elif key == "neq_value":
# the arg may be a bound edge var (dict) or a plain
# string var ('?x') holding the joined subject's name
ref = b.get(args[0])
subj = (ref["subject"] if isinstance(ref, dict)
else ref) or ""
ok = norm_name(subj) != norm_name(args[1])
else:
raise ValueError(f"unknown filter {key!r}")
if ok:
kept.append(b)
proof.steps.append(Step("filter", f"{key} {args}",
[b[var]["eid"] for b in kept if var in b]))
bindings = kept
# ---- select -----------------------------------------------------------
sel = query.get("select", "all")
if sel == "latest_end":
def _end_key(b):
e = next((v["end"] for k, v in b.items()
if isinstance(v, dict) and v.get("end")), None)
return e or ""
bindings = sorted(bindings, key=_end_key, reverse=True)
bindings = bindings[:1]
proof.steps.append(Step("select", "latest_end",
[b[var]["eid"] for b in bindings if var in b]))
elif sel != "all":
raise ValueError(f"unknown select {sel!r}")
proof.bindings = bindings
return proof
def re_execute(store: KnowledgeStore, query: dict, proof: Proof) -> bool:
"""The check: the same store must reproduce the SAME closed path.
Deterministic, no model — evaluation is pure, so this is equality of
the re-run proof term against the claimed one. A store that changed
under the proof (retractions, new edges winning latest_end) makes
the re-run differ and the claimed proof FAILS: the check is real.
"""
fresh = evaluate(store, query)
if len(fresh.bindings) != len(proof.bindings):
return False
for a, b in zip(fresh.bindings, proof.bindings):
ka = {k: (v["eid"] if isinstance(v, dict) else v)
for k, v in a.items()}
kb = {k: (v["eid"] if isinstance(v, dict) else v)
for k, v in b.items()}
if ka != kb:
return False
return True
+285 -17
View File
@@ -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);
"""
@@ -51,6 +54,72 @@ def norm_name(name: str) -> str:
return re.sub(r"\s+", " ", s).strip().casefold()
# a value is FUNCTIONAL (only one can be true) when it is date-like or a
# bare number/quantity: '29 February 1972', '2018', '15', '1,006 km',
# '17 november 2023'. Two entity-ish values ('prime minister of Spain' vs
# 'Secretary-General of the PSOE') are co-true readings of a multi-valued
# relation instead. The signal: no entity WORDS survive after dropping
# numbers, month names, and units.
_MONTHS = {"january", "february", "march", "april", "may", "june", "july",
"august", "september", "october", "november", "december",
"gener", "febrer", "marc", "abril", "maig", "juny", "juliol",
"agost", "setembre", "octubre", "novembre", "desembre",
"de", "d", "of", "the", "in", "on", "at", "since", "until"}
_UNITS = {"km", "km2", "mi", "m", "kg", "s", "cu", "ft", "ms", "mm", "cm",
"people", "inhabitants", "days", "years", "months", "hours",
"percent", "m3", "m3/s", "bps", "kb", "mb", "gb", "%", "eur",
"usd", "millions", "billions"}
def _looks_functional(value: str) -> bool:
"""True when the value is date-like or a bare quantity (phase 1 signal:
functional relations keep the contradiction case; entity-ish pairs go
to alternatives). A value with two or more entity words is NOT
functional ('prime minister of Spain'); a date or quantity is.
A lone entity word ('Spain') is an entity reading, not a datum —
functional needs NUMBERS with at most one unit/month word."""
words = re.findall(r"[A-Za-zÀ-ÿ]{1,}", value or "")
entity_words = [w for w in words
if w.lower() not in _MONTHS and w.lower() not in _UNITS]
has_number = bool(re.search(r"\d", value or ""))
if not has_number:
return False # pure words: an entity reading (Spain / PSOE)
return len(entity_words) < 2
# ---- phase 2: valid-time windows (RESEARCH-derived-answers Part 2) -----------
# A window is (start, end) with None = OPEN. Granularity is compared as
# text (ISO-like, left-padded by the extractor: '2018' < '2018-06' <
# '2018-06-02' all compare correctly as strings when normalized to the
# finest stated granularity — a year window is the interval
# [2018, 2019), honest to its precision).
def _window(start: str | None, end: str | None) -> tuple[str | None, str | None] | None:
"""The window, or None when the fact states NO time at all (empty
windows stay empty — no invention, no pretending)."""
if not start and not end:
return None
return (start or None, end or None)
def _overlaps(a: tuple[str | None, str | None],
b: tuple[str | None, str | None]) -> bool:
"""Two valid-time windows overlap? None endpoints are OPEN (±inf).
The boundary law (year granularity, honest to its precision): an end
year CLOSES the window and the next start year OPENS there —
[2014,2018) vs [2018,None) is SUCCESSION (the mandate changed hands
in 2018), not coexistence. Overlap is max(starts) < min(ends); the
open sides degenerate correctly: both starts None (share the
indefinite past) or both ends None (both ongoing) always overlap.
"""
lo = max(a[0] or "-inf", b[0] or "-inf")
hi = min(a[1] or "9999", b[1] or "9999")
if lo == "-inf" or hi == "9999":
return True
return lo < hi # strict: touching at one year = succession
def stem(word: str) -> str:
"""Tiny suffix stemmer so question words match text words (draft):
'populated'/'population' -> 'populat', 'states' -> 'state'."""
@@ -68,6 +137,7 @@ def stem(word: str) -> str:
@dataclass
class EdgeView:
eid: int
src: str
rel: str
dst: str
@@ -105,6 +175,38 @@ class KnowledgeStore:
if "list_ord" not in cols:
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
self.db.commit()
# ---- phase 2: temporal windows (RESEARCH-derived-answers Part 2) ----
for col in ("t_start", "t_end"):
if col not in cols:
self.db.execute(f"ALTER TABLE edges ADD COLUMN {col} TEXT")
self.db.commit()
# fact_order: order assertions BETWEEN facts (edges are addressable;
# reification is free). rel in {before, after, concurrent}.
self.db.execute(
"CREATE TABLE IF NOT EXISTS fact_order ("
" id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, "
" rel TEXT, quote_id INTEGER, "
" UNIQUE(edge_a, edge_b, rel))")
self.db.commit()
# ---- phase 1: the conflict taxonomy (RESEARCH-derived-answers.md) ----
# alternatives: co-true readings of one (src, rel) — the polisèmia
# (the three presidencies). Same shape as conflicts (pairwise), but
# the world holds BOTH: it is the ambiguity substrate, never an
# error state.
self.db.execute(
"CREATE TABLE IF NOT EXISTS alternatives ("
" id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, "
" value_a TEXT, value_b TEXT, edge_a INTEGER, edge_b INTEGER, "
" UNIQUE(node, rel, edge_a, edge_b))")
self.db.commit()
# same_as: paraphrase merges. Append-only law — the merge never
# deletes; the alias pair is recorded and the canonical edge's
# corroboration goes up.
self.db.execute(
"CREATE TABLE IF NOT EXISTS same_as ("
" id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, "
" UNIQUE(edge_a, edge_b))")
self.db.commit()
# ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
@@ -139,8 +241,14 @@ class KnowledgeStore:
dst_sort: str = "CONCEPT", confidence: float = 0.8,
ref_date: str | None = None,
origin_question: str | None = None,
list_ord: int | None = None) -> int | None:
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
list_ord: int | None = None,
t_start: str | None = None, t_end: str | None = None) -> int | None:
"""Add an edge, applying the taxonomy (KNOWLEDGE.md §2 + the
RESEARCH-derived-answers parts 1-2).
t_start/t_end: the fact's VALID-TIME window as stated in the source
('since 2018' -> t_start='2018', t_end=None = OPEN). None/None when
the text states no time — empty windows stay empty, no invention.
Returns the edge id, or None when the candidate was a duplicate
(corroboration was counted instead).
@@ -158,26 +266,45 @@ class KnowledgeStore:
return None
# contradiction classification: same src+rel, different value, not retracted
others = self.db.execute(
"SELECT id, dst_value, ref_date FROM edges WHERE src_node=? AND rel=? "
"SELECT id, dst_value, ref_date, dst_node, quote_id, t_start, t_end "
"FROM edges WHERE src_node=? AND rel=? "
"AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
(src, rel)).fetchall()
cur = self.db.execute(
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
"extraction_confidence, origin_question, ref_date, preferred, list_ord) "
"VALUES(?,?,?,?,?,?,?,?,0,?)",
"extraction_confidence, origin_question, ref_date, preferred, list_ord, t_start, t_end) "
"VALUES(?,?,?,?,?,?,?,?,0,?,?,?)",
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question,
ref_date, list_ord))
ref_date, list_ord, t_start, t_end))
edge_id = cur.lastrowid
for other_id, other_val, other_date in others:
for other_id, other_val, other_date, other_dn, other_q, o_ts, o_te in others:
case = self._classify(new_val=dst_value, new_date=ref_date,
old_val=other_val, old_date=other_date)
if case == "duplicate":
old_val=other_val, old_date=other_date,
new_node=dst_node, old_node=other_dn,
new_quote=quote_id, old_quote=other_q,
new_start=t_start, new_end=t_end,
old_start=o_ts, old_end=o_te)
if case in ("duplicate", "paraphrase"):
if case == "paraphrase":
self.db.execute(
"INSERT OR IGNORE INTO same_as(edge_a, edge_b) VALUES(?,?)",
(other_id, edge_id))
self.db.execute(
"UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
(other_id,))
continue
elif case == "supersedes":
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id))
self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
elif case == "temporal":
pass # both coexist; queries pick by date
elif case in ("temporal", "coasserted", "succession"):
# both dated (series) / one sentence asserts both / disjoint
# windows: the world holds or moves on — never a conflict
pass
elif case == "alternatives":
self.db.execute(
"INSERT OR IGNORE INTO alternatives(node, rel, value_a, value_b, edge_a, edge_b) "
"VALUES(?,?,?,?,?,?)",
(src, rel, other_val, dst_value, other_id, edge_id))
else: # contradiction
self.db.execute(
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
@@ -185,19 +312,103 @@ class KnowledgeStore:
self.db.commit()
return edge_id
def add_fact_order(self, edge_a: int, edge_b: int, rel: str,
quote_id: int | None = None) -> None:
"""Record a temporal-order assertion BETWEEN two facts (phase 2).
The text asserts the order with a connective ('before becoming',
'at the same time as'); the extractor transcribes it as an order
restriction, code verifies the connective's quote and stores it
here. Edges are addressable — reification is free. rel is one of
{before, after, concurrent} (the extractor's vocabulary; Allen's
finer relations are computed views over the windows, never labels).
"""
if rel not in ("before", "after", "concurrent"):
raise ValueError(f"unknown order relation {rel!r}")
self.db.execute(
"INSERT OR IGNORE INTO fact_order(edge_a, edge_b, rel, quote_id) "
"VALUES(?,?,?,?)", (edge_a, edge_b, rel, quote_id))
self.db.commit()
@staticmethod
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str:
"""Deterministic four-case classification (KNOWLEDGE.md §2)."""
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None,
new_node: int | None = None, old_node: int | None = None,
new_quote: int | None = None, old_quote: int | None = None,
new_start: str | None = None, new_end: str | None = None,
old_start: str | None = None, old_end: str | None = None) -> str:
"""Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers
parts 1-2). Cost-ordered: the cheapest signal decides.
duplicate same normalized value
coasserted same quote — one trusted sentence asserts both
(conjunction: the platform sentence split into facts)
supersedes subsumption with dates
temporal both dated (ref_date), different dates — time series
paraphrase tails resolve to the SAME node — the same fact
alternatives co-true readings: overlapping VALID-TIME windows
(two open ends overlap), or entity-ish values with
different tails
contradiction the residue: functional values, disjoint windows on
a functional relation
Interval arithmetic (phase 2): windows come from the text via the
extractor (t_start/t_end, end=None = OPEN). Two windows OVERLAP ->
coexistence -> alternatives. DISJOINT -> succession (never a
conflict; the world just moved on). The comparison is honest: a
window with no endpoints does not pretend to overlap.
"""
nv, ov = norm_name(new_val), norm_name(old_val)
if nv == ov:
return "duplicate"
# subsumption: the new value equals the old plus extra qualifiers
if new_quote is not None and new_quote == old_quote:
return "coasserted"
if ov and ov in nv and (new_date or old_date):
return "supersedes"
# both dated -> time series, not contradiction
if new_date and old_date and new_date != old_date:
return "temporal"
return "contradiction"
# ---- phase 2: interval arithmetic over valid-time windows -------
new_w = _window(new_start, new_end)
old_w = _window(old_start, old_end)
if new_w and old_w:
if _overlaps(new_w, old_w):
return "alternatives" # coexistence is provable
# disjoint: succession — not a conflict, not co-true either
return "succession"
if new_node and old_node and new_node == old_node:
return "paraphrase"
if _looks_functional(new_val) or _looks_functional(old_val):
return "contradiction"
return "alternatives"
# ---- phase 1: alternatives query (the ambiguity substrate) -------------
def alternatives_of(self, src_name: str, rel: str) -> list[tuple[str, str]]:
"""The co-true readings of one (src, rel): the alternatives bucket.
Returns [(value, tail_node_name), ...] — the set the audit and the
render consume (the ambiguity was detected at INGEST, deterministi-
cally; nobody needs to re-derive it at judge time). Values appear
once, first-seen order; None tail when the edge carries no node.
"""
src = self.db.execute("SELECT id FROM nodes WHERE norm_name=?",
(norm_name(src_name),)).fetchone()
if not src:
return []
rows = self.db.execute(
"SELECT a.value_a, a.value_b, na.norm_name, nb.norm_name "
"FROM alternatives a "
"LEFT JOIN edges ea ON ea.id = a.edge_a "
"LEFT JOIN edges eb ON eb.id = a.edge_b "
"LEFT JOIN nodes na ON na.id = ea.dst_node "
"LEFT JOIN nodes nb ON nb.id = eb.dst_node "
"WHERE a.node=? AND a.rel=? ORDER BY a.id",
(src[0], rel)).fetchall()
seen: list[tuple[str, str]] = []
for va, vb, ta, tb in rows:
for val, tail in ((va, ta), (vb, tb)):
key = (val, tail or "")
if key not in [(s, t or "") for s, t in seen]:
seen.append((val, tail or ""))
return [(v, t or None) for v, t in seen]
# ---- queries --------------------------------------------------------------
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
@@ -257,11 +468,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(
+160
View File
@@ -0,0 +1,160 @@
"""The derived-answer engine tests (phase 3a, RESEARCH-derived-answers Part 3).
No LLM in the loop: the ANSWER IS THE PROOF TERM — every step names its
operator and the edge ids it consumed; re-execution over the store IS the
verification. The DSL is conjunctive + temporal, typed, hand-writable
(the LLM translator arrives in 3b; the evaluator it must satisfy is
pinned here first).
Laws under test (the fixture = the live three-presidencies shape):
1. "Of what is Sánchez president?" — one lookup over office rels with
an open-now window filter returns the THREE bindings as a set
(Spain, PSOE, SI), each citing its edge.
2. The predecessor: conjunctive join (his office O + anyone holding O +
window-before + not-him) proves RAJOY as a CLOSED PATH — proof steps
name the edges and the interval check; re-execution verifies it.
3. select=latest_end distinguishes the predecessor (Rajoy ended 2018)
from a later holder of the same office (Feijóo, open — not before).
4. Empty bindings = UNKNOWN — silence, no invention.
5. Re-execution: same store → same proof (deterministic); a changed
store → the re-execution FAILS the stale proof (the check is real).
Run: .venv/bin/python knowledge/tests/prover.py
"""
from __future__ import annotations
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.prover import evaluate, re_execute
from knowledge.store import KnowledgeStore
def fixture_kg() -> KnowledgeStore:
"""The live shape (phase-2 run): the three presidencies with open
windows, plus Rajoy's premiership (closed 2018) and Feijóo's later,
unrelated-office row — the distractor select=latest must reject."""
store = KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite")
docs = {}
for i, text in enumerate([
"He has been the prime minister of Spain since 2018.",
"He is Secretary-General of the PSOE since 2017.",
"He is the ninth president of Socialist International since 2022.",
"Mariano Rajoy was the prime minister of Spain from 2011 to 2018.",
"Alberto Núñez Feijóo has been the leader of the People's Party since 2018.",
"Mariano Rajoy lost the motion of no confidence in 2018.",
]):
url = f"u{i}"
doc = store.add_document(url=url, title="t", fetched_at="2026-10-25",
sha256=f"{i:064d}")
docs[i] = store.add_quote(doc_id=doc, verbatim=text, url=url,
access_date="2026-10-25")
store.add_edge("pedro sanchez", "prime minister of", "Spain",
quote_id=docs[0], t_start="2018")
store.add_edge("pedro sanchez", "secretary general of",
"Spanish Socialist Workers' Party (PSOE)",
quote_id=docs[1], t_start="2017")
store.add_edge("pedro sanchez", "president of",
"Socialist International", quote_id=docs[2], t_start="2022")
store.add_edge("mariano rajoy", "prime minister of", "Spain",
quote_id=docs[3], t_start="2011", t_end="2018")
store.add_edge("alberto nunez feijoo", "leader of",
"People's Party", quote_id=docs[4], t_start="2018")
return store
OF_WHAT_QUERY = {
"lookup": {"subject": "pedro sanchez",
"rel_any": ["prime minister of", "secretary general of",
"president of"],
"bind": "office"},
"filter": [{"open_now": ["office"]}],
"select": "all",
}
PREDECESSOR_QUERY = {
"lookup": [{"subject": "pedro sanchez",
"rel_any": ["prime minister of"],
"bind": "his_office"},
{"subject": "?x",
"rel_any": ["prime minister of"],
"bind": "other",
"same_value_as": "his_office"}],
"filter": [{"neq_value": ["?x", "pedro sanchez"]},
{"before": ["other", "his_office"]}],
"select": "latest_end",
}
def test_three_bindings():
store = fixture_kg()
proof = evaluate(store, OF_WHAT_QUERY)
vals = sorted(b["other_or_office_value"] if "other_or_office_value" in b
else b["office"]["value"] for b in proof.bindings)
assert "Spain" in vals and "Socialist International" in vals, vals
assert any("PSOE" in v for v in vals), vals
assert len(proof.bindings) == 3, f"three readings, got {proof.bindings}"
assert all(b["office"]["eid"] for b in proof.bindings), "every binding cites its edge"
print(f"ok: 'of what' returns the three bindings: {vals}")
def test_predecessor_closed_path():
store = fixture_kg()
proof = evaluate(store, PREDECESSOR_QUERY)
assert len(proof.bindings) == 1, f"one predecessor, got {proof.bindings}"
assert proof.bindings[0]["?x"] == "mariano rajoy", proof.bindings
edges = {e for step in proof.steps for e in step.edges}
assert len(edges) >= 2, "the closed path cites both the Rajoy and Sánchez edges"
assert any("before" in (step.note or "") or step.op == "filter"
for step in proof.steps), "the interval check is a named step"
assert re_execute(store, PREDECESSOR_QUERY, proof), "re-execution verifies"
print("ok: predecessor proved as a closed path (Rajoy), re-execution green")
def test_select_latest_rejects_open_distractor():
"""Feijóo holds a DIFFERENT office (leader of PP) — the join on
same_value_as (office=Spain) must keep him out entirely; the only
other Spain-PM is Rajoy. The distractor is structural, not temporal."""
store = fixture_kg()
proof = evaluate(store, PREDECESSOR_QUERY)
names = [b["?x"] for b in proof.bindings]
assert "alberto nunez feijoo" not in names, names
print(f"ok: distractor rejected (bindings: {names})")
def test_empty_is_unknown():
store = fixture_kg()
q = {"lookup": {"subject": "pedro sanchez",
"rel_any": ["chancellor of"], "bind": "office"},
"filter": [{"open_now": ["office"]}],
"select": "all"}
proof = evaluate(store, q)
assert proof.bindings == [], "no closed path: silence, never invention"
print("ok: no path -> empty bindings (UNKNOWN), no invention")
def test_reexecution_detects_stale_proof():
store = fixture_kg()
proof = evaluate(store, PREDECESSOR_QUERY)
assert re_execute(store, PREDECESSOR_QUERY, proof)
# retract Rajoy's edge -> the stale proof must FAIL re-execution
store.db.execute(
"UPDATE edges SET retracted=1, retraction_reason='test' "
"WHERE src_node IN (SELECT id FROM nodes WHERE norm_name='mariano rajoy')")
store.db.commit()
assert not re_execute(store, PREDECESSOR_QUERY, proof), \
"a changed store must fail the stale proof (the check is real)"
print("ok: re-execution fails a stale proof after retraction — the check is real")
if __name__ == "__main__":
test_three_bindings()
test_predecessor_closed_path()
test_select_latest_rejects_open_distractor()
test_empty_is_unknown()
test_reexecution_detects_stale_proof()
print("\nprover: 5/5 ok")
+169
View File
@@ -0,0 +1,169 @@
"""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))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
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")
+9 -4
View File
@@ -73,11 +73,16 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
assert a and b
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 0, "dated different values are a time series, not a conflict"
# contradiction: same rel, undated different values -> exposed conflict
c1 = ks.add_edge("Seine", "length_km", "777", q1)
c2 = ks.add_edge("Seine", "length_km", "776", q1)
# contradiction: same rel, undated different FUNCTIONAL values -> exposed conflict
# (phase 1 taxonomy: entity-ish pairs are alternatives; numeric/date
# values on a functional relation keep the contradiction. Different
# quotes — same-quote pairs are co-asserted conjunction, by law.)
qc1 = ks.add_quote(doc, "The Seine is 777 kilometres long.", "url", "d")
qc2 = ks.add_quote(doc, "One source lists the Seine at 776 kilometres.", "url", "d")
c1 = ks.add_edge("Seine", "length_km", "777", qc1)
c2 = ks.add_edge("Seine", "length_km", "776", qc2)
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 1, "undated different values must be exposed as conflict"
assert conflicts == 1, "undated different functional values must be exposed as conflict"
# probe: seeds find edges with quotes
rows = ks.probe(["Loire", "loire"])
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
+36 -17
View File
@@ -6,7 +6,8 @@ from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
parse_stop_table)
@@ -71,14 +72,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 +97,31 @@ def test_process_page_fragments():
wikitext=WIKITEXT_2TABLES)
page.tables = parse_tables(WIKITEXT_2TABLES)
# scripted extractor: world-table parts -> stop_table=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_table=False):
def __init__(self, facts):
self.facts = facts
self.stop_table = stop_table
def fake_extract(question, heading, text, _calls=calls):
_calls.append((question, heading, text))
if "World rivers" in text:
return FakeOut([], stop_table=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 +135,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():
+188
View File
@@ -0,0 +1,188 @@
"""Conflict taxonomy tests (phase 1, RESEARCH-derived-answers.md Part 1).
The four-case classifier conflated conjunction, paraphrase and polisèmia
into "contradiction" — 20 conflict pairs in the live KG after one Pedro
run, ZERO real contradictions. The taxonomy (deterministic, cost-ordered):
co-asserted same quote_id — one trusted sentence asserts both values
(conjunction, never a conflict)
paraphrase discriminant-free surface OR tails resolving to the same
node — the same fact said differently: MERGE (same_as,
append-only; corroboration up, no conflict row)
alternatives different discriminant entity, tails resolve to different
nodes, multi-valued relation — co-true readings (the
polisèmia: Spain / PSOE / SI). Recorded as alternatives,
not contradictions.
temporal both dated (time series) — unchanged law
contradiction what survives: functional relation, incompatible values
Laws under test (fixtures = the live 20-pair inventory):
1. The platform sentence split into 5 "called for" facts with the SAME
quote never yields conflicts (co-asserted).
2. "Prime Minister of Spain" vs "president of the Government (Spanish:
Presidente del Gobierno)" merges (paraphrase — tails resolve to the
same office; no conflict row).
3. The three presidencies (PM-of-Spain / SG-of-PSOE / president-of-SI)
land in the alternatives bucket, pairwise — never "contradiction".
4. Two different birth dates stay a real contradiction (functional rel).
5. Both-dated pairs stay temporal.
6. The alternatives bucket is queryable: the store exposes, per
(src, rel), the co-true value set with their tails — the ambiguity
substrate for the audit and the render.
Run: .venv/bin/python knowledge/tests/taxonomy.py
"""
from __future__ import annotations
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.store import KnowledgeStore, norm_name
def make_store() -> tuple[KnowledgeStore, str]:
d = tempfile.mkdtemp()
return KnowledgeStore(f"{d}/kg.sqlite"), d
def add_doc(store: KnowledgeStore, text: str) -> int:
"""One document + one quote carrying the given verbatim text."""
url = f"u{abs(hash(text)) % 10**8}"
doc_id = store.add_document(url=url, title="t", fetched_at="2026-10-25",
sha256=f"{abs(hash(text)) % 10**16:016x}")
return store.add_quote(doc_id=doc_id, verbatim=text, url=url,
access_date="2026-10-25")
def test_coasserted_never_conflicts():
"""The platform sentence: 5 facts, one quote — conjunction, not conflict."""
store, _ = make_store()
q = add_doc(store, "Presenting a platform based on political regeneration, "
"Sánchez called for constitutional reforms establishing "
"federalism; a new progressive fiscal policy; extending "
"the welfare state to all citizens; increasing the "
"membership of labour unions; and regaining the "
"confidence of Socialist voters.")
for dst in ("constitutional reforms establishing federalism",
"a new progressive fiscal policy",
"extending the welfare state to all citizens",
"increasing the membership of labour unions",
"regaining the confidence of Socialist voters"):
store.add_edge("pedro sanchez", "called for", dst, quote_id=q)
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"co-asserted facts must not conflict (got {n})"
print("ok: 5 same-quote facts -> 0 conflicts (co-asserted conjunction)")
def test_paraphrase_merges():
"""Same office, two surfaces, tails resolve to the same node -> merge."""
store, _ = make_store()
q1 = add_doc(store, "The prime minister of Spain, officially the president "
"of the Government, is the head of government of Spain.")
q2 = add_doc(store, "The head of government of Spain is the Prime Minister "
"of Spain, often called president of the Government.")
a = store.add_edge("pedro sanchez", "position held",
"prime minister of Spain",
dst_node_name="Prime Minister of Spain", quote_id=q1)
b = store.add_edge("pedro sanchez", "position held",
"president of the Government (Spanish: Presidente del Gobierno)",
dst_node_name="Prime Minister of Spain", quote_id=q2)
assert a and b, "both edges ingested"
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"a paraphrase must merge, not conflict (got {n})"
# corroboration counted on the canonical edge, same_as alias recorded
canon = store.db.execute(
"SELECT corroboration FROM edges WHERE id=?", (min(a, b),)).fetchone()
assert canon and canon[0] >= 2, "paraphrase merge must corroborate the canonical edge"
aliases = store.db.execute(
"SELECT COUNT(*) FROM same_as WHERE edge_a IN (?,?) OR edge_b IN (?,?)",
(a, b, a, b)).fetchone()[0]
assert aliases >= 1, "the merge must record a same_as alias (append-only law)"
print("ok: paraphrase merges (canonical corroborated, same_as recorded)")
def test_three_presidencies_are_alternatives():
"""THE polisèmia: three offices, three institutions, co-true.
Live shape (run 090402 inventory): the three readings came from
DIFFERENT sentences — the intro sentence carries the party/SI offices,
the lead paragraph the premiership. Same-quote co-assertion would be
the conjunction case; the presidencies are separate assertions and
land in alternatives."""
store, _ = make_store()
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
q2 = add_doc(store, "A member of the Spanish Socialist Workers' Party "
"(PSOE), he is also Secretary-General of the party "
"since 2017.")
q3 = add_doc(store, "He is the ninth president of Socialist "
"International since 2022.")
store.add_edge("pedro sanchez", "position held",
"prime minister of Spain since 2018",
dst_node_name="Spain", quote_id=q1)
store.add_edge("pedro sanchez", "position held",
"Secretary-General of the PSOE since 2017",
dst_node_name="PSOE", quote_id=q2)
store.add_edge("pedro sanchez", "position held",
"ninth president of Socialist International since 2022",
dst_node_name="Socialist International", quote_id=q3)
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
assert real == 0, f"co-true readings are not contradictions (got {real})"
assert alts == 3, f"three pairwise alternatives expected (got {alts})"
print("ok: three presidencies -> 3 alternatives, 0 contradictions")
def test_alternatives_queryable():
"""The ambiguity substrate: per (src, rel) the co-true value set."""
store, _ = make_store()
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
q2 = add_doc(store, "He is also Secretary-General of the party since 2017.")
store.add_edge("pedro sanchez", "position held",
"prime minister of Spain since 2018", dst_node_name="Spain", quote_id=q1)
store.add_edge("pedro sanchez", "position held",
"Secretary-General of the PSOE since 2017",
dst_node_name="PSOE", quote_id=q2)
got = store.alternatives_of("pedro sanchez", "position held")
vals = {norm_name(v)[:30] for v, _t in got}
assert len(got) == 2 and len(vals) == 2, f"expected 2 alternative readings, got {got}"
print(f"ok: alternatives_of returns the co-true set: {[v[:40] for v, _ in got]}")
def test_functional_contradiction_survives():
"""Two different birth dates: a REAL contradiction, kept."""
store, _ = make_store()
q1 = add_doc(store, "Pedro Sánchez was born on 29 February 1972.")
q2 = add_doc(store, "Pedro Sánchez was born on 28 February 1972.")
store.add_edge("pedro sanchez", "date of birth", "29 February 1972", quote_id=q1)
store.add_edge("pedro sanchez", "date of birth", "28 February 1972", quote_id=q2)
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert real == 1, f"a functional contradiction must stay (got {real})"
print("ok: two birth dates -> 1 real contradiction (functional rel)")
def test_temporal_unchanged():
"""Both dated pairs: temporal, coexist — the old law, untouched."""
store, _ = make_store()
q1 = add_doc(store, "In 2014 he was elected Secretary-General.")
q2 = add_doc(store, "In 2017 he was re-elected Secretary-General.")
store.add_edge("pedro sanchez", "elected secretary-general",
"in 2014", ref_date="2014", quote_id=q1)
store.add_edge("pedro sanchez", "elected secretary-general",
"in 2017", ref_date="2017", quote_id=q2)
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert n == 0, f"dated pairs are temporal, not conflicts (got {n})"
print("ok: both-dated pair stays temporal, no conflict")
if __name__ == "__main__":
test_coasserted_never_conflicts()
test_paraphrase_merges()
test_three_presidencies_are_alternatives()
test_alternatives_queryable()
test_functional_contradiction_survives()
test_temporal_unchanged()
print("\ntaxonomy: 6/6 ok")
+161
View File
@@ -0,0 +1,161 @@
"""Temporal restriction tests (phase 2, RESEARCH-derived-answers Part 2).
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
start/end/point (dates, optional, containment-checked against the quote),
granularity, and fact-order assertions {before, after, concurrent} that
reference sibling facts by local index. The Allen algebra stays a
COMPUTED VIEW over endpoints (the store's job); asking the model to
choose labels would replace transcription with classification and
produce uncheckable, granularity-blind, silently-disagreeing labels.
Laws under test:
1. A date field not contained in the quote is REJECTED (the honest law:
the model proposes, code verifies against the source surface).
2. Windows feed the taxonomy: overlapping open windows on one (src,rel)
are alternatives (coexistence is interval arithmetic, not statistics);
disjoint windows are succession — never a conflict.
3. 'since 2018' means END OPEN; two open ends overlap.
4. Order assertions between sibling facts survive ingest as fact_order
rows (edges are addressable; reification is free).
5. Empty temporal fields stay empty — no invented dates.
The extractor call itself is scripted (structured-output Fact objects,
like the live dspy adapter returns); no network.
Run: .venv/bin/python knowledge/tests/temporal.py
"""
from __future__ import annotations
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.extract import Fact
from knowledge.store import KnowledgeStore
def make_store() -> KnowledgeStore:
return KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite")
def add_doc(store: KnowledgeStore, text: str) -> int:
url = f"u{abs(hash(text)) % 10**8}"
doc_id = store.add_document(url=url, title="t", fetched_at="2026-10-25",
sha256=f"{abs(hash(text)) % 10**16:016x}")
return store.add_quote(doc_id=doc_id, verbatim=text, url=url,
access_date="2026-10-25")
# --- the Fact contract ---------------------------------------------------------
def test_fact_temporal_fields():
"""Fact carries optional start/end/point/granularity + orders."""
f = Fact(subject="X", relation="position held", object="President of A",
quote="X was president of A and B at the same time for one month.",
start="2020", end=None, point=None, granularity="year",
orders=[])
assert f.start == "2020" and f.granularity == "year"
f2 = Fact(subject="X", relation="position held", object="President of B",
quote="X was also president of B.",
start=None, end=None, point=None, granularity=None,
orders=[{"rel": "concurrent", "other": 0}])
assert f2.orders[0]["rel"] == "concurrent"
print("ok: Fact typed temporal fields + order assertions")
def test_date_not_in_quote_rejected():
"""The honest law: a temporal field must be contained in the quote."""
from knowledge.checks import check_candidate
good = {"subject": "X", "relation": "term start",
"object": "2018", "quote": "X took office in 2018.",
"start": "2018"}
bad = {"subject": "X", "relation": "term start",
"object": "2018", "quote": "X took office some years ago.",
"start": "2018"}
ok, reason = check_candidate(good, "X took office in 2018.")
assert ok, f"contained date must pass: {reason}"
ok, reason = check_candidate(bad, "X took office some years ago.")
assert not ok, f"invented date must be rejected, got pass ({reason})"
print("ok: temporal containment check (invented dates rejected)")
# --- windows feed the taxonomy ---------------------------------------------------
def test_overlapping_open_windows_are_alternatives():
"""'since 2018' and 'since 2022' on one (src, rel): two open intervals
overlap -> coexistence -> alternatives, not contradiction."""
store = make_store()
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
q2 = add_doc(store, "He is the ninth president of Socialist International since 2022.")
store.add_edge("pedro sanchez", "position held",
"prime minister of Spain", quote_id=q1, t_start="2018")
store.add_edge("pedro sanchez", "position held",
"ninth president of Socialist International", quote_id=q2,
t_start="2022")
conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
assert conf == 0, f"overlapping open windows must not conflict (got {conf})"
assert alts >= 1, "overlapping open windows are co-true alternatives"
print("ok: overlapping open windows -> alternatives (interval arithmetic)")
def test_disjoint_windows_are_succession_not_conflict():
"""Leader of the Opposition (2014-2018) vs prime minister (2018-): the
'became' pair — disjoint windows mean succession, never a conflict."""
store = make_store()
q1 = add_doc(store, "In 2014, he was elected, becoming Leader of the Opposition.")
q2 = add_doc(store, "In 2018 he became prime minister.")
store.add_edge("pedro sanchez", "became", "Leader of the Opposition",
quote_id=q1, t_start="2014", t_end="2018")
store.add_edge("pedro sanchez", "became", "prime minister",
quote_id=q2, t_start="2018")
conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
assert conf == 0, f"succession is not a conflict (got {conf})"
assert alts == 0, f"disjoint windows are not co-true (got {alts} alts)"
print("ok: disjoint windows -> succession, no conflict, no alternatives")
def test_empty_windows_stay_empty():
"""No dates in the text -> no dates in the edge. No invention."""
store = make_store()
q1 = add_doc(store, "He was a city councillor in Madrid.")
q2 = add_doc(store, "He later was a member of parliament.")
e1 = store.add_edge("pedro sanchez", "became", "city councillor", quote_id=q1)
e2 = store.add_edge("pedro sanchez", "became", "member of parliament", quote_id=q2)
row = store.db.execute("SELECT t_start, t_end FROM edges WHERE id=?", (e1,)).fetchone()
assert row == (None, None), f"undated facts keep empty windows ({row})"
print("ok: no dates in text -> empty windows stay empty")
# --- fact_order -------------------------------------------------------------------
def test_order_assertions_ingest():
"""'X was leader of the opposition BEFORE being president' -> two facts,
one fact_order row (before), reification-free (edges carry ids)."""
store = make_store()
q = add_doc(store, "X was leader of the opposition before becoming president.")
a = store.add_edge("X", "position held", "leader of the opposition", quote_id=q)
b = store.add_edge("X", "position held", "president", quote_id=q)
store.add_fact_order(a, b, "before", quote_id=q)
rows = store.db.execute(
"SELECT rel FROM fact_order WHERE edge_a=? AND edge_b=?", (a, b)).fetchall()
assert rows and rows[0][0] == "before", f"fact_order row missing: {rows}"
# concurrent order also representable
c = store.add_edge("X", "position held", "president of B", quote_id=q)
store.add_fact_order(b, c, "concurrent", quote_id=q)
n = store.db.execute("SELECT COUNT(*) FROM fact_order").fetchone()[0]
assert n == 2, f"expected 2 fact_order rows, got {n}"
print("ok: fact_order rows ingest (before/concurrent between addressable edges)")
if __name__ == "__main__":
test_fact_temporal_fields()
test_date_not_in_quote_rejected()
test_overlapping_open_windows_are_alternatives()
test_disjoint_windows_are_succession_not_conflict()
test_empty_windows_stay_empty()
test_order_assertions_ingest()
print("\ntemporal: 6/6 ok")
+101
View File
@@ -0,0 +1,101 @@
"""The question->DSL translator tests (phase 3b, RESEARCH-derived-answers
Part 3) — the LLM at the INPUT boundary, validated before execution.
Laws under test:
1. The translator is ONE structured-output call (the MASK/EXTRACT
class): question + the store's relation vocabulary in, typed DSL out.
2. Validation before execution: an unknown filter/select/rel in the
proposal is REJECTED deterministically (mistranslation surfaces as an
invalid term, never as a wrong answer). The model proposes, code
decides — a bad translation can never reach evaluate().
3. The two live questions translate to terms the pinned evaluator
executes: "of what is X president" -> lookup + open_now + all;
"who was president before X" -> the two-lookup join + before +
latest_end. (Scripted LM responses; no network.)
4. Untranslatable questions return None — the caller falls back to the
judge path, honestly.
Run: .venv/bin/python knowledge/tests/translate_dsl.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
from knowledge.prover import validate_query
from knowledge.translate_dsl import TranslateToDSL, translate
class ScriptedLM:
"""Returns one scripted DSL proposal per call (the dspy adapter's
structured output shape: attribute-dict with 'query')."""
def __init__(self, query):
self.query = query
def __call__(self, **kwargs):
class Out:
pass
out = Out()
out.query = self.query
return out
def test_translator_signature():
"""One structured-output call; the DSL schema is the signature."""
fields = set(TranslateToDSL.__fields__)
assert "question" in fields and "relations" in fields and "query" in fields, fields
print("ok: TranslateToDSL signature (question+relations in, typed query out)")
def test_of_what_translation():
e = type("E", (), {})()
e.translate_dspy = ScriptedLM({
"lookup": {"subject": "pedro sanchez",
"rel_any": ["prime minister of", "secretary general of",
"president of"],
"bind": "office"},
"filter": [{"open_now": ["office"]}],
"select": "all"})
q = translate(e, "Of what is Pedro Sanchez the president?",
["prime minister of", "secretary general of", "president of"])
assert q and q["select"] == "all" and len(q["filter"]) == 1
ok, reason = validate_query(q)
assert ok, f"valid term rejected: {reason}"
print(f"ok: 'of what' -> lookup+open_now+all (validated: {reason})")
def test_mistranslation_rejected():
"""An unknown filter or select never reaches evaluate()."""
bad_filters = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"},
"filter": [{"contains_now": ["v"]}], # not in the DSL
"select": "all"}
ok, reason = validate_query(bad_filters)
assert not ok and "contains_now" in reason, f"unknown filter slipped: {reason}"
bad_select = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"},
"filter": [], "select": "second_best"}
ok, reason = validate_query(bad_select)
assert not ok and "select" in reason, f"unknown select slipped: {reason}"
bad_rel = {"lookup": {"subject": "x", "rel_any": [], "bind": "v"},
"filter": [], "select": "all"}
ok, reason = validate_query(bad_rel)
assert not ok, "empty rel_any is an invalid term"
print("ok: mistranslations rejected deterministically (never executed)")
def test_untranslatable_returns_none():
e = type("E", (), {})()
e.translate_dspy = ScriptedLM(None) # the model honestly declines
q = translate(e, "Why is the sky blue?", ["length"])
assert q is None
print("ok: untranslatable question -> None (caller falls back to the judge)")
if __name__ == "__main__":
test_translator_signature()
test_of_what_translation()
test_mistranslation_rejected()
test_untranslatable_returns_none()
print("\ntranslate_dsl: 4/4 ok")
+62
View File
@@ -0,0 +1,62 @@
"""The question->DSL translator (phase 3b) — the LLM at the INPUT boundary.
One structured-output call (the MASK/EXTRACT class): the question + the
store's relation vocabulary in; a typed DSL term out; VALIDATED BEFORE
EXECUTION — a mistranslation is an invalid term caught deterministically,
never a wrong answer. The model never sees the goal, the evidence, or the
answer; it sees the question and which relations exist. If the question is
not translatable, the call returns None and the caller falls back to the
judge path, honestly.
"""
from __future__ import annotations
from typing import Any
import dspy
from .prover import validate_query
class TranslateToDSL(dspy.Signature):
"""You are the TRANSLATE-TO-QUERY step of a reasoning machine. Turn the
question into ONE typed query over the knowledge graph, choosing from
the given relations ONLY. The machine executes the query deterministically.
Shapes you may build:
- lookup: {"subject": "<entity>", "rel_any": ["<one or more relations>"], "bind": "<var>"}
- a second lookup with {"subject": "?x", "rel_any": [...], "bind": "<var>",
"same_value_as": "<bound var>"} — anyone holding the SAME value (e.g. the
same office) as the first lookup bound
- filters: {"open_now": ["<var>"]} (the fact holds now), {"before": ["<a>", "<b>"]}
(a's window ended before b's started), {"neq_value": ["<var-or-?x>", "<literal>"]}
(a bound name differs from the literal — e.g. exclude the queried entity)
- select: "all" (every binding — the question asks for the SET) or
"latest_end" (the most recent one that ended)
If the question cannot be expressed with these shapes, return an empty
query ({} or null) — never force a wrong translation."""
question: str = dspy.InputField()
relations: str = dspy.InputField(
desc="the relations that exist in the graph, comma separated")
query: dict | None = dspy.OutputField(
desc="the typed query as JSON, or null when not expressible")
_KNOWN_FILTERS = {"open_now", "before", "neq_value"}
_KNOWN_SELECTS = {"all", "latest_end"}
def translate(expert, question: str, relations: list[str]) -> dict | None:
"""One call: question + relation vocabulary -> a validated DSL term.
None when the model declines or the proposal is invalid — the caller
falls back to the judge path (the prover never executes an invalid
term; code decides, the model proposes).
"""
pred = expert.translate_dspy(question=question,
relations=", ".join(sorted(set(relations))))
q = getattr(pred, "query", None)
if not q:
return None
ok, _reason = validate_query(q)
return q if ok else None