Author SHA1 Message Date
onibot f6e9164e92 feat: two-pass EXTRACT (claims -> typed Facts) for prose chunks
His diagnosis accepted (26/10): the single-pass EXTRACT's giant typed
JSON array (verbatim quotes + temporal restrictions + sibling orders)
is the output budget behind the 40-minute arithmetic on slow local
models. Two-pass shortens EVERY output:

- Pass 1 ExtractClaims: plain claim strings, coreferences resolved
  (entities named, never pronouns) — near-zero format tax.
- Pass 2 TypeClaim: ONE claim -> one typed Fact per call (same Fact
  schema the store eats; temporal fields optional, containment-checked
  downstream as always). Orders NEVER produced here: one claim at a
  time has no siblings — the legacy Fact keeps orders for the
  single-pass path and table frags, untouched.
- extract_mode: two_pass (default) | single (legacy) — config-driven,
  read from config.yaml's knowledge block by run_app.
- Budget: Pass 1 charges once per chunk; Pass 2 charges once per
  claim. Table frags keep the legacy single-pass call.
- Prompt log: CLAIMS/TYPE stage labels added.

TDD: two_pass_extract 5/5 (signatures, coref law, honest empties) +
two_pass_wiring 2/2 (end-to-end on a real store: two_pass ingests
typed facts with windows kept; single-pass control green). Suite: 29
test files green. The router from #26 makes the upcoming
extraction-model swap a pure config edit.
2026-10-26 16:42:22 +01:00
onibot 95dfdf7123 Merge pull request 'feat: per-signature LM router (lm[<SigName>] config blocks + predict factory)' (#26) from feat/lm-signature-router into main 2026-10-26 16:37:14 +01:00
onibot 6ba0bce863 feat: per-signature LM router (lm[<SigName>] config blocks + predict factory)
His ask: one general construction door so a signature's model/settings
change by editing config alone — no call-site ifs, now or ever after.
lm[ExtractSignature]: as a config.yaml sibling of lm: (provider:
inherits base_url + transport ceiling; model: builds a dedicated
cached LM; other keys -> per-call lm_kwargs through Predict config,
honored by dspy 3.4.1 _forward_preprocess). predict() is the door: the
13 construction sites swapped mechanically. First block shipped:
ExtractSignature max_tokens=1800 (the 4096 cap was 3x headroom that
only extended the worst case on slow local models — the 40-min
arithmetic). run.log reports active blocks at startup. TDD:
tests/lm_signature_router.py 5/5 (parse, no-block defaults,
settings-only override, dedicated+cached LM, provenance listing).
2026-10-26 16:37:04 +01:00
onibot 31c7e02e22 Merge pull request 'fix: LM transport ceiling per provider (read_timeout_s + num_retries)' (#25) from fix/lm-transport-ceiling into main 2026-10-26 12:27:57 +01:00
onibot f31b30d811 fix: LM transport ceiling per provider (read_timeout_s + num_retries)
The bug his log pinned: local EXTRACT died at 2407.3s = 4 attempts x
600s + 7s backoff — dspy's retry loop (default num_retries=3) ran
honestly but every attempt hit the SAME wall: lm15's default read
timeout of 600s (and the silent-ollama proxy in front cuts at its own
READ_TIMEOUT=600 too). Retries can't help when each attempt dies at
the same ceiling — the 27b on a single 3090 legitimately needs
minutes for a long EXTRACT output (his nvidia-smi: 21GB resident,
64k context, ~52% util).

The fix: the ceiling is CONFIG, not code.
- config.yaml: local read_timeout_s=1800 (one honest 30-min attempt),
  num_retries=1 (one re-try after a genuine cut, not 3x30min);
  ollama-cloud read_timeout_s=300 (glm answers EXTRACT in ~3s),
  num_retries=2 (cloud retries are cheap).
- configure_lm forwards read_timeout_s as dspy.LM(timeout=...) —
  dspy 3.4.1 routes it to lm15 Timeouts(read/write/pool) — and
  num_retries to the retry loop (LMTransportError is retryable).
- run.log first line now reports the ceiling (no more silent 600s
  walls — you SEE what will kill a slow call).
- Unset keys -> dspy defaults (600s / retries 3), nothing invented.

Verified on the wire (tests/lm_transport_wire.py): a hang server +
timeout=3 kills the call at 3.1s (not 600s); num_retries=1 gives
exactly 2 attempts (3.2s = 2x1s + backoff). Suite: 21 files green.
2026-10-26 12:27:49 +01:00
onibot 27c4bf3812 Merge pull request 'research/semantic-kg: semantic probe + conflict taxonomy + temporal layer + derived-answer prover' (#24) from research/semantic-kg into main 2026-10-25 21:40:17 +01:00
onibot 2cfcb1a59d research: phase 3 shipped live — evaluator + translator + gate, verified on the Pedro run 2026-10-25 21:39:13 +01:00
onibot ee315e0644 knowledge: the prover wired — translate->validate->prove, no judge in the loop (phase 3b)
The LLM at the INPUT boundary only: one structured-output call
(TranslateToDSL — question + the store's relation vocabulary in, typed
DSL out), VALIDATED before execution (validate_query: the shared
grammar — unknown filter/select, empty rel_any, malformed lookup are
rejected deterministically; a mistranslation can never reach
evaluate()). The evaluator (3a) closes the path; re-execution IS the
check. _prover_answer runs BEFORE any judge: a closed path returns the
answer with verified=True and the proof term; a multi-binding returns
the SET with ambiguous=True + alternatives (the three readings as what
they are — deterministic, no ablation rounds, no (K5) surface: the
judge never sees these questions). No translation / no closed path /
re-execution mismatch -> the judge path, unchanged; the prover can
never kill a run.

Wiring is additive: answer_question tries the prover first, falls
back honestly. Tests: translate_dsl.py 4/4 (signature, live-shape
translation, mistranslation rejection, honest decline -> None).
2026-10-25 21:12:56 +01:00
onibot fb612686d6 knowledge: the derived-answer engine, evaluator first (phase 3a)
No LLM in the loop. The query is a small typed DSL (conjunctive +
temporal, hand-writable); 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; a stale proof fails after a retraction —
the check is real, not a flag).

Operators pinned by tests (the fixture = the live three-presidencies
shape): lookup (subject + rel_any -> bindings), value-join
(same_value_as — the SAME office, ANY holder), open_now (window open),
before (window a ended before window b started — both endpoints real,
an open end is never 'before' anything), neq_value (exclude the
queried entity), select all (the binding SET — multi-binding IS the
ambiguity) / latest_end (the predecessor).

Proven end-to-end on the fixture: "of what is Sánchez president?"
returns the three bindings (Spain, PSOE, SI); "who was President
before him?" proves RAJOY as a closed path citing both edges, rejects
the structural distractor (Feijóo holds a different office), returns
empty = UNKNOWN when no path exists, and re-execution fails after
Rajoy's edge is retracted.

The LLM translator (question -> DSL, one structured-output call) and
the machine wiring (prover as the real stop-check) arrive in 3b.
2026-10-25 21:09:19 +01:00
onibot 99f8b6e9db knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2)
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
typed Fact gains start/end/point (optional, ISO-ish) + granularity +
orders [{rel: before|after|concurrent, other: <sibling index>}] — the
text's connectives transcribed, not classified. The Allen algebra stays
a COMPUTED VIEW over endpoints.

- checks.py: every stated date must be CONTAINED IN THE QUOTE — an
  invented date rejects the whole candidate (LLM proposes, code
  verifies against the source surface).
- store.py: edges gain t_start/t_end (valid-time window, None end =
  OPEN, honest to 'since 2018'); fact_order table (order assertions
  between addressable facts — reification is free); _classify consumes
  interval arithmetic: overlapping open windows -> alternatives
  (coexistence provable, no statistics), disjoint windows ->
  succession (never a conflict). Boundary law at year granularity:
  [2014,2018) vs [2018,None) = succession — the mandate changed hands
  in 2018. add_fact_order validates rel in {before, after, concurrent}.
- expert.py: _ingest_candidate returns (merged, eid) and passes the
  windows; the prose path collects positional fact_ids and wires the
  orders' sibling references to real edge ids (malformed refs skip
  honestly).

Tests: temporal.py 6/6 (typed fields, containment rejection, open-
window overlap -> alternatives, touch-at-year -> succession, empty
stays empty, fact_order ingest) + 7/7 interval cases incl. the
open-past degenerate. Suite: all green.

LIVE (run 20261025-205018, cold KG, glm-5.3-flash): 29 edges carry
windows (Spain 2018 / PSOE 2017 / SI 2022 all open-ended), 25
fact_order rows (Madrid before Congress of Deputies...), 8 invented
end-dates REJECTED by the containment check (the footballer Pedro
articles — the check catching exactly what it should), 0 conflicts.
The run itself answered UNKNOWN on its Q1 ("what DATE did he take
office") — honest: the blind extractor did not transcribe the exact
date this run and the noisy re-probe view (four Pedros) is the known
branch weakness, not a phase-2 regression. Design note for phase 4:
the three presidencies live under DIFFERENT rels, so the alternatives
substrate must be queried trans-rel by the consumer (alternatives_of
is per-rel by construction).
2026-10-25 21:07:34 +01:00
onibot b4b26c5ee6 research: phase 1 live result — 0 conflicts, the three presidencies queryable as alternatives 2026-10-25 20:24:18 +01:00
onibot f32a6db531 knowledge: conflict taxonomy at merge (phase 1, RESEARCH-derived-answers Part 1)
The four-case classifier conflated conjunction, paraphrase and polisèmia
into "contradiction" — the live KG after one Pedro run held 20 conflict
pairs, ZERO real ones. The taxonomy (deterministic, cost-ordered):

  co-asserted   same quote_id — one trusted sentence asserts both values
                (the platform sentence split into 5 "called for" facts)
  paraphrase    tails resolve to the same node — the same fact in two
                surfaces: MERGE (same_as alias, append-only; the canonical
                edge's corroboration goes up, no conflict row)
  alternatives  entity-ish values, different tails — co-true readings of a
                multi-valued relation (THE three presidencies). New table
                + alternatives_of(src, rel): the ambiguity substrate,
                detected at INGEST, deterministically — the audit no
                longer needs to re-derive it at judge time
  temporal      both dated — unchanged
  contradiction the residue: functional values (dates/quantities —
                _looks_functional: numbers with at most unit/month words;
                pure entity words are readings, not data)

Files: store.py (_classify 4->7 cases, migrations for alternatives +
same_as, alternatives_of), tests taxonomy.py (6/6: the 20-pair inventory
as fixtures), store.py test updated to the new law (different quotes for
the contradiction pair — same-quote is co-asserted by law).

Known scope notes: same_as is recorded but not yet consumed by the
probe/render (phase 4); the three-presidencies-in-one-sentence shape
stays conjunction (the live readings came from different quotes).
2026-10-25 20:14:06 +01:00
23 changed files with 2118 additions and 48 deletions
+39
View File
@@ -303,6 +303,25 @@ edge gains a class field; the alternatives bucket is exposed to the
audit and the render. Fixtures: the live 20-pair inventory (10 audit and the render. Fixtures: the live 20-pair inventory (10
co-asserted, 3+1 temporal, 3 alternatives, 0 real). 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) ### Phase 2 — temporal layer (this branch, extractor + store)
Typed Fact (feature/typed-facts vehicle) gains start/end/point/ Typed Fact (feature/typed-facts vehicle) gains start/end/point/
@@ -326,6 +345,26 @@ questions. Regression: Pedro proves Rajoy as a closed path; "of what"
returns the three bindings as a set; rivers stay green; judge LLM returns the three bindings as a set; rivers stay green; judge LLM
calls drop to zero on store-derivable paths. 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 ### Phase 4 — consumers
The audit reduces to "is the binding set already multi?" (cheap, The audit reduces to "is the binding set already multi?" (cheap,
+19
View File
@@ -8,12 +8,31 @@ lm:
model: qwen3.8-27b-uc-64k:latest model: qwen3.8-27b-uc-64k:latest
max_tokens: 4096 max_tokens: 4096
temperature: 0.0 temperature: 0.0
# transport ceiling (fix: EXTRACT hangs >600s on a busy 3090; the
# silent-ollama proxy in front cuts at its own READ_TIMEOUT=600s).
# read_timeout_s -> lm15 Timeouts(read=) — one attempt may run this long.
# num_retries -> dspy's retry loop (LMTransportError is retryable);
# each retry costs up to read_timeout_s, so keep retries LOW locally.
read_timeout_s: 1800 # 30 min: one honest attempt for a long EXTRACT
num_retries: 1 # one re-try after a cut, not 3x30min
ollama-cloud: ollama-cloud:
base_url: https://ollama.com/v1 base_url: https://ollama.com/v1
model: glm-5.3-flash model: glm-5.3-flash
max_tokens: 4096 max_tokens: 4096
temperature: 0.0 temperature: 0.0
api_key_env: OLLAMA_API_KEY api_key_env: OLLAMA_API_KEY
read_timeout_s: 300 # glm answers EXTRACT in ~3s; 300s bounds a wedged call
num_retries: 2 # cloud retries are cheap
# per-signature settings: lm[<SignatureName>] overrides the active provider's
# settings for that stage ONLY (model/max_tokens/temperature/...). provider:
# selects which provider block inherits base_url + transport ceiling; model:
# builds a dedicated cached LM for that stage. No block -> run defaults.
lm[ExtractSignature]:
provider: local
max_tokens: 1800 # EXTRACT output is facts+quotes: ~120 tok/fact;
# 4096 was 3x headroom that only extended hangs
# on slow local models (the 40-min arithmetic)
budget: budget:
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
+7 -6
View File
@@ -10,6 +10,7 @@ import re
from enum import Enum from enum import Enum
import dspy import dspy
from floop.llm import predict
from pydantic import BaseModel from pydantic import BaseModel
from .state import AnswerType from .state import AnswerType
@@ -135,12 +136,12 @@ class FloopModules:
"""All LLM entry points of the draft. Each returns a dspy.Prediction.""" """All LLM entry points of the draft. Each returns a dspy.Prediction."""
def __init__(self) -> None: def __init__(self) -> None:
self.init = dspy.Predict(InitSignature) self.init = predict(InitSignature)
self.route = dspy.Predict(RouteSignature) self.route = predict(RouteSignature)
self.expert = dspy.Predict(ExpertSignature) self.expert = predict(ExpertSignature)
self.missing = dspy.Predict(MissingSignature) self.missing = predict(MissingSignature)
self.answer = dspy.Predict(AnswerSignature) self.answer = predict(AnswerSignature)
self.mask = dspy.Predict(EntityMaskSignature) self.mask = predict(EntityMaskSignature)
def init_decompose(self, question: str) -> tuple[list[dict], str]: def init_decompose(self, question: str) -> tuple[list[dict], str]:
"""(parsed subquestions, raw model output). The machine decides what """(parsed subquestions, raw model output). The machine decides what
+86 -1
View File
@@ -164,6 +164,8 @@ _STAGE_BY_MODULE = {
"MissingSignature": "MISSING", "MissingSignature": "MISSING",
"AnswerSignature": "ANSWER", "AnswerSignature": "ANSWER",
"ExtractSignature": "EXTRACT", "ExtractSignature": "EXTRACT",
"ExtractClaims": "CLAIMS",
"TypeClaim": "TYPE",
"AnswerFromKG": "answer_kg", "AnswerFromKG": "answer_kg",
"SelectTableSignature": "SELECT_TABLE", "SelectTableSignature": "SELECT_TABLE",
"VerifyCountSignature": "VERIFY_COUNT", "VerifyCountSignature": "VERIFY_COUNT",
@@ -196,13 +198,27 @@ def configure_lm(no_cache: bool = False) -> dict:
"temperature": p["temperature"], "temperature": p["temperature"],
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"), "api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
} }
# transport ceiling (fix: EXTRACT hangs on slow local models): the
# config's read_timeout_s becomes the lm15 Timeouts(read=) via the
# `timeout=` kwarg (a plain number of seconds bounds read/write/
# pool — dspy 3.4.1 execution.py routes it as RouterConfig timeouts;
# the default is 600s, the wall your 2407.3s EXTRACT call died on,
# 4 attempts x 600s + backoff). num_retries feeds dspy's retry loop
# (LMTransportError IS retryable — execution.py is_retryable_lm_error).
# Unset -> dspy defaults (600s / retries 3), nothing invented.
if p.get("read_timeout_s"):
kwargs["timeout"] = float(p["read_timeout_s"])
if p.get("num_retries") is not None:
kwargs["num_retries"] = int(p["num_retries"])
if no_cache: if no_cache:
kwargs["cache"] = False kwargs["cache"] = False
lm = dspy.LM(**kwargs) lm = dspy.LM(**kwargs)
global _ACTIVE global _ACTIVE
_ACTIVE = lm _ACTIVE = lm
dspy.configure(lm=lm) dspy.configure(lm=lm)
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]} return {"provider": provider, "model": p["model"], "base_url": p["base_url"],
"read_timeout_s": p.get("read_timeout_s"),
"num_retries": p.get("num_retries")}
def install_prompt_log(streams) -> None: def install_prompt_log(streams) -> None:
@@ -219,6 +235,75 @@ def install_prompt_log(streams) -> None:
_ACTIVE: "dspy.LM | None" = None _ACTIVE: "dspy.LM | None" = None
_PROMPT_LOG: "PromptLogCallback | None" = None _PROMPT_LOG: "PromptLogCallback | None" = None
# per-signature dedicated LMs (lm[<SigName>] blocks with a model override),
# keyed f"{provider}:{model}" — ONE LM per provider+model, built once
_SIGNATURE_LMS: dict[str, "dspy.LM"] = {}
def _signature_settings(sig) -> dict:
"""The lm[<SignatureName>] block for a signature, or {} when absent."""
name = getattr(sig, "__name__", None) or str(sig)
return _load_yaml().get(f"lm[{name}]") or {}
def signature_overrides() -> dict[str, dict]:
"""Every lm[<SigName>] block in config.yaml, by signature name.
For the run.log provenance line: which stages run with dedicated
settings today, visible at startup.
"""
return {k[3:-1]: v for k, v in _load_yaml().items()
if k.startswith("lm[") and k.endswith("]")}
def predict(signature, **extra_config):
"""dspy.Predict construction honoring per-signature config blocks.
A `lm[<SignatureName>]:` block in config.yaml (sibling of `lm:`) may
carry: provider (which provider block to inherit base_url + transport
ceiling from — defaults to the active provider), model, max_tokens,
temperature, and any other dspy.LM kwarg. Settings WITHOUT a model
travel as per-call lm_kwargs through Predict's own config (dspy 3.4.1
merges self.config into the request — verified on the wire); a model:
override builds ONE dedicated cached dspy.LM (same provider ceiling,
its own model id) bound to the Predict instance. No block -> a plain
dspy.Predict with the run defaults, untouched.
This is the ONE construction door: swapping dspy.Predict(...) for
predict(...) here means a signature's model/settings change by
editing config alone — no call-site ifs, now or ever after.
"""
import dspy
block = _signature_settings(signature)
if not block:
return dspy.Predict(signature, **extra_config)
cfg = _load_yaml()["lm"]
provider = block.get("provider") or cfg.get("default")
base = cfg[provider]
settings = {k: v for k, v in block.items() if k != "provider"}
model = settings.pop("model", None)
if model is None:
return dspy.Predict(signature, **settings, **extra_config)
key = f"{provider}:{model}"
if key not in _SIGNATURE_LMS:
kwargs: dict = {
"model": f"openai/{model}",
"base_url": base["base_url"],
"api_base": base["base_url"],
"max_tokens": settings.pop("max_tokens", base["max_tokens"]),
"temperature": settings.pop("temperature", base["temperature"]),
"api_key": os.environ.get(base.get("api_key_env", ""), "empty"),
}
if base.get("read_timeout_s"):
kwargs["timeout"] = float(base["read_timeout_s"])
if base.get("num_retries") is not None:
kwargs["num_retries"] = int(base["num_retries"])
kwargs.update(settings) # any other block keys pass through
_SIGNATURE_LMS[key] = dspy.LM(**kwargs)
inst = dspy.Predict(signature, **extra_config)
inst.lm = _SIGNATURE_LMS[key]
return inst
def active_lm() -> "dspy.LM": def active_lm() -> "dspy.LM":
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw).""" """The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
+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", "") subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
if not (subj and rel and obj): if not (subj and rel and obj):
return False, "incomplete triple" 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" return True, "ok"
+160 -18
View File
@@ -25,16 +25,18 @@ import time
from dataclasses import dataclass from dataclasses import dataclass
import dspy import dspy
from floop.llm import predict
from .checks import check_candidate, quote_containment from .checks import check_candidate, quote_containment
from .chunker import chunk_page from .chunker import chunk_page
from .skim import find_quantities, skim_article from .skim import find_quantities, skim_article
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature, from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
SkimPromoteSignature, SkimTableSignature, SelectTableSignature, SkimPromoteSignature,
VerifyCountSignature) SkimTableSignature, TypeClaim, VerifyCountSignature)
from .embeddings import EmbedderDown, embed from .embeddings import EmbedderDown, embed
from .queries import compose_queries, keywords, proper_nouns from .queries import compose_queries, keywords, proper_nouns
from .store import KnowledgeStore, norm_name from .store import KnowledgeStore, norm_name
from .two_pass import claims_from, fact_from_claim
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert, from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
tables_as_chunks, format_table_frag) tables_as_chunks, format_table_frag)
@@ -162,6 +164,9 @@ class KnowledgeConfig:
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
# cross-question 0.35-0.38 out, spouse-noise ~0.67 # cross-question 0.35-0.38 out, spouse-noise ~0.67
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
# outputs) | "single" (legacy one-call typed
# array — table frags keep using it)
class KnowledgeExpert: class KnowledgeExpert:
@@ -174,12 +179,14 @@ class KnowledgeExpert:
self.store = store or KnowledgeStore(self.cfg.kb_path) self.store = store or KnowledgeStore(self.cfg.kb_path)
self.client = client or WikipediaClient() self.client = client or WikipediaClient()
self.streams = streams self.streams = streams
self.extract = dspy.Predict(ExtractSignature) self.extract = predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG) self.claims = predict(ExtractClaims)
self.select_table = dspy.Predict(SelectTableSignature) self.typeclaim = predict(TypeClaim)
self.verify_count = dspy.Predict(VerifyCountSignature) self.answer = predict(AnswerFromKG)
self.skim_promote = dspy.Predict(SkimPromoteSignature) self.select_table = predict(SelectTableSignature)
self.skim_tables = dspy.Predict(SkimTableSignature) self.verify_count = predict(VerifyCountSignature)
self.skim_promote = predict(SkimPromoteSignature)
self.skim_tables = predict(SkimTableSignature)
self._checked = 0 self._checked = 0
self._merged = 0 self._merged = 0
# semantic probe: cached question vector for this call (the probe # semantic probe: cached question vector for this call (the probe
@@ -288,6 +295,87 @@ class KnowledgeExpert:
"ranked": ordered}} "ranked": ordered}}
# ---- the pipeline -------------------------------------------------------- # ---- 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 = 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 = "", def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None, evidence: str = "", charge_llm=None,
answer_type: str = "") -> dict: answer_type: str = "") -> dict:
@@ -305,6 +393,18 @@ class KnowledgeExpert:
goal_terms = self._keywords(parent_question) if parent_question else [] goal_terms = self._keywords(parent_question) if parent_question else []
self._current_goal_terms = goal_terms # the harvest reads these self._current_goal_terms = goal_terms # the harvest reads these
self._current_goal_question = parent_question or question 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 # per-CALL skim state (PR-3): notices for the machine + ambiguous
# leads pending the bounded promotion decision # leads pending the bounded promotion decision
self._skim_notices: list[str] = [] self._skim_notices: list[str] = []
@@ -1072,12 +1172,45 @@ class KnowledgeExpert:
think=True) think=True)
extracted = 0 extracted = 0
for chunk in capped: for chunk in capped:
if self.cfg.extract_mode == "two_pass":
# two-pass (26/10): Pass 1 claims (short strings, coref
# resolved), Pass 2 one typed Fact per claim — every
# output short; the giant typed array is gone from prose.
claims = claims_from(self, entities=ent_str,
heading=chunk.heading_path,
text=chunk.text, charge_llm=charge_llm)
for claim in claims[: self.cfg.max_facts_per_chunk]:
fact = fact_from_claim(self, claim, charge_llm=charge_llm)
if fact is None:
continue # honestly declined: no invention
merged, _eid = self._ingest_candidate(
fact, page, containment=page.text)
extracted += merged
continue
if charge_llm: if charge_llm:
charge_llm() charge_llm()
raw = self.extract(entities=ent_str, heading=chunk.heading_path, raw = self.extract(entities=ent_str, heading=chunk.heading_path,
text=chunk.text) 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]: for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
extracted += self._ingest_candidate(cand, page, containment=page.text) 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
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) ----------------------------- # ---- table fragments (extract path) -----------------------------
from .store import stem as _stem from .store import stem as _stem
# containment target: prose + ALL table rows (the fragment's rows # containment target: prose + ALL table rows (the fragment's rows
@@ -1103,31 +1236,40 @@ class KnowledgeExpert:
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})" heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
raw = self.extract(entities=ent_str, heading=heading, text=text) raw = self.extract(entities=ent_str, heading=heading, text=text)
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]: for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
extracted += self._ingest_candidate(cand, page, containment=containment) merged, _eid = self._ingest_candidate(cand, page, containment=containment)
extracted += merged
return self._merged return self._merged
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int: def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> tuple[int, int | None]:
"""Containment-check one typed Fact, merge it, cache its vector. """Containment-check one typed Fact, merge it, cache its vector.
Returns 1 when merged, 0 otherwise. Shared by the prose and table-
fragment extract paths (research/semantic-kg).""" 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 self._checked += 1
cand = {"subject": cand.subject, "relation": cand.relation, cand = {"subject": cand.subject, "relation": cand.relation,
"object": cand.object, "quote": cand.quote} "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) ok, reason = check_candidate(cand, containment)
if not ok: if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}") self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
return 0 return 0, None
doc_id = self.store.add_document( doc_id = self.store.add_document(
url=page.url, title=page.title, fetched_at=page.fetched_at, url=page.url, title=page.title, fetched_at=page.fetched_at,
sha256=hashlib.sha256(page.text.encode()).hexdigest()) sha256=hashlib.sha256(page.text.encode()).hexdigest())
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at) qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
eid = self.store.add_edge(cand["subject"], cand["relation"], eid = self.store.add_edge(cand["subject"], cand["relation"],
cand["object"], qid) cand["object"], qid,
t_start=cand["start"] or None,
t_end=cand["end"] or None)
self._merged += 1 self._merged += 1
if eid is not None: if eid is not None:
self._cache_edge_vector(eid, cand["subject"], cand["relation"], self._cache_edge_vector(eid, cand["subject"], cand["relation"],
cand["object"]) cand["object"])
return 1 return 1, eid
def _cache_edge_vector(self, eid: int, subject: str, relation: str, def _cache_edge_vector(self, eid: int, subject: str, relation: str,
obj: str) -> None: obj: str) -> None:
+58 -1
View File
@@ -20,12 +20,40 @@ class Confidence(str, Enum):
class Fact(BaseModel): 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") subject: str = dspy.OutputField(desc="the fact's subject entity")
relation: str = dspy.OutputField(desc="the relation between subject and object") relation: str = dspy.OutputField(desc="the relation between subject and object")
object: str = dspy.OutputField(desc="the fact's object / value") object: str = dspy.OutputField(desc="the fact's object / value")
quote: str = dspy.OutputField( 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)") 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): class ExtractSignature(dspy.Signature):
@@ -44,6 +72,35 @@ class ExtractSignature(dspy.Signature):
desc="the extracted facts; empty list if none") desc="the extracted facts; empty list if none")
class ExtractClaims(dspy.Signature):
"""You are the CLAIMS step of a knowledge machine. From the given text,
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
and offices held, biographical facts, events, relationships,
quantities with units. One claim per line, plain text, no numbering.
Resolve coreferences: name the entity in the claim, never a pronoun
or a shorthand. Only what the text states; no inference."""
entities: str = dspy.InputField(
desc="the named entities to extract claims about, comma separated")
heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField()
claims: list[str] = dspy.OutputField(
desc="the factual claims, one string each, coreferences resolved "
"(entities named, never pronouns); empty list if none")
class TypeClaim(dspy.Signature):
"""You are the TYPE step of a knowledge machine. Given ONE single claim,
type it into the Fact schema: subject entity, relation, object/value,
the VERBATIM quote from the text that states the claim (the FULL
sentence or table row, copied exactly, at least 10 characters), and
the temporal restrictions the text states. All temporal fields are
optional and must be contained in the quote. Only what the claim and
its quote state; no inference."""
claim: str = dspy.InputField(desc="the claim to type")
fact: Fact | None = dspy.OutputField(
desc="the typed Fact, or null when the claim cannot be typed honestly")
class AnswerFromKG(dspy.Signature): class AnswerFromKG(dspy.Signature):
"""You are the ANSWER step of a knowledge machine. Answer the question using """You are the ANSWER step of a knowledge machine. Answer the question using
ONLY the given knowledge-graph rows, each with its quote and source. Cite ONLY the given knowledge-graph rows, each with its quote and source. Cite
+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
+222 -15
View File
@@ -54,6 +54,72 @@ def norm_name(name: str) -> str:
return re.sub(r"\s+", " ", s).strip().casefold() 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: def stem(word: str) -> str:
"""Tiny suffix stemmer so question words match text words (draft): """Tiny suffix stemmer so question words match text words (draft):
'populated'/'population' -> 'populat', 'states' -> 'state'.""" 'populated'/'population' -> 'populat', 'states' -> 'state'."""
@@ -109,6 +175,38 @@ class KnowledgeStore:
if "list_ord" not in cols: if "list_ord" not in cols:
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER") self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
self.db.commit() 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 ------------------------------------------------ # ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str, def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
@@ -143,8 +241,14 @@ class KnowledgeStore:
dst_sort: str = "CONCEPT", confidence: float = 0.8, dst_sort: str = "CONCEPT", confidence: float = 0.8,
ref_date: str | None = None, ref_date: str | None = None,
origin_question: str | None = None, origin_question: str | None = None,
list_ord: int | None = None) -> int | None: list_ord: int | None = None,
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2). 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 Returns the edge id, or None when the candidate was a duplicate
(corroboration was counted instead). (corroboration was counted instead).
@@ -162,26 +266,45 @@ class KnowledgeStore:
return None return None
# contradiction classification: same src+rel, different value, not retracted # contradiction classification: same src+rel, different value, not retracted
others = self.db.execute( 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)", "AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
(src, rel)).fetchall() (src, rel)).fetchall()
cur = self.db.execute( cur = self.db.execute(
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, " "INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
"extraction_confidence, origin_question, ref_date, preferred, list_ord) " "extraction_confidence, origin_question, ref_date, preferred, list_ord, t_start, t_end) "
"VALUES(?,?,?,?,?,?,?,?,0,?)", "VALUES(?,?,?,?,?,?,?,?,0,?,?,?)",
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question, (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 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, case = self._classify(new_val=dst_value, new_date=ref_date,
old_val=other_val, old_date=other_date) old_val=other_val, old_date=other_date,
if case == "duplicate": 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 continue
elif case == "supersedes": elif case == "supersedes":
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id)) 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,)) self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
elif case == "temporal": elif case in ("temporal", "coasserted", "succession"):
pass # both coexist; queries pick by date # 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 else: # contradiction
self.db.execute( self.db.execute(
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) " "INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
@@ -189,19 +312,103 @@ class KnowledgeStore:
self.db.commit() self.db.commit()
return edge_id 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 @staticmethod
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str: def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None,
"""Deterministic four-case classification (KNOWLEDGE.md §2).""" 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) nv, ov = norm_name(new_val), norm_name(old_val)
if nv == ov: if nv == ov:
return "duplicate" 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): if ov and ov in nv and (new_date or old_date):
return "supersedes" return "supersedes"
# both dated -> time series, not contradiction
if new_date and old_date and new_date != old_date: if new_date and old_date and new_date != old_date:
return "temporal" return "temporal"
# ---- 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 "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 -------------------------------------------------------------- # ---- queries --------------------------------------------------------------
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]: def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
+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")
+9 -4
View File
@@ -73,11 +73,16 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
assert a and b assert a and b
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0] conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 0, "dated different values are a time series, not a conflict" assert conflicts == 0, "dated different values are a time series, not a conflict"
# contradiction: same rel, undated different values -> exposed conflict # contradiction: same rel, undated different FUNCTIONAL values -> exposed conflict
c1 = ks.add_edge("Seine", "length_km", "777", q1) # (phase 1 taxonomy: entity-ish pairs are alternatives; numeric/date
c2 = ks.add_edge("Seine", "length_km", "776", q1) # 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] 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 # probe: seeds find edges with quotes
rows = ks.probe(["Loire", "loire"]) rows = ks.probe(["Loire", "loire"])
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows) assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
+1 -1
View File
@@ -64,7 +64,7 @@ def test_format_and_parse_stop():
def make_expert(store: KnowledgeStore) -> KnowledgeExpert: def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
e.cfg = KnowledgeConfig() e.cfg = KnowledgeConfig(extract_mode="single") # this test pins the LEGACY path
e.store = store e.store = store
e.streams = None e.streams = None
e._checked = e._merged = 0 e._checked = e._merged = 0
+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")
+110
View File
@@ -0,0 +1,110 @@
"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts).
Law: the old single call asked a slow model for verbatim quotes + typed
temporal fields + sibling order assertions in ONE giant JSON array — the
output budget that produced the 40-minute arithmetic. The two-pass split
shortens EVERY output: Pass 1 extracts plain claims (free-form strings
with coreference resolved to the entity names — near-zero format tax);
Pass 2 types ONE claim into the existing Fact schema per call.
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
assertions become IMPOSSIBLE by construction, so orders are dropped from
the two-pass path (the store's fact_order keeps working for whatever
arrives as a typed Fact with orders; the two-pass facts carry none).
The store, the containment checks and the merge are UNTOUCHED — Pass 2
emits the same typed Fact as before, minus orders.
Pinned:
1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the
claim must name its entities, not 'he/it/the party').
2. TypeClaim: one claim in -> one typed Fact out (same fields as the
legacy ExtractSignature.facts minus orders; temporal fields optional).
3. The pipeline wiring: _extract_two_pass returns typed Fact objects;
candidates flow into _ingest_candidate exactly as before.
4. Honest empty: no claims -> no facts, no invention.
5. The legacy single-pass signature STAYS (table frags use it; flipping
the whole pipeline over is a later decision, config-driven).
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
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 ExtractClaims, TypeClaim, Fact, ExtractSignature
from knowledge.two_pass import claims_from, fact_from_claim
class Scripted:
def __init__(self, **attrs):
self.__dict__.update(attrs)
def __call__(self, **kw):
return self
def test_extract_claims_signature():
"""Pass 1: claims are free-form strings; coreferences resolved."""
fields = set(ExtractClaims.__fields__)
assert fields == {"entities", "heading", "text", "claims"}, fields
# what the model actually sees: dspy keeps desc in json_schema_extra
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
assert "coreference" in d.lower() or "resolved" in d.lower(), d
print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft")
def test_type_claim_signature():
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
fields = set(TypeClaim.__fields__)
assert fields == {"claim", "fact"}, fields
f = TypeClaim.model_fields["fact"].annotation
assert "Fact" in str(f), f
# Fact KEEPS orders (the legacy single-pass path and table frags use
# them — untouched); the two-pass law is that TypeClaim never fills
# them: one claim per call means no siblings to reference.
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
d = TypeClaim.__doc__ or ""
assert "one claim" in d.lower() or "single" in d.lower(), d
print("ok: TypeClaim = one claim -> one Fact; orders never produced (no siblings)")
def test_claims_from_runs_pass1():
e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018",
"Sanchez became Secretary-General of the PSOE in 2017"]))
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
assert out == ["Pedro Sanchez is the prime minister of Spain since 2018",
"Sanchez became Secretary-General of the PSOE in 2017"], out
print("ok: claims_from extracts the plain claim strings")
def test_fact_from_claim_types_one_fact():
e = Scripted(typeclaim=Scripted(fact=Fact(
subject="Pedro Sanchez", relation="prime minister of",
object="Spain", quote="is a Spanish politician who has been the "
"prime minister of Spain since 2018",
start="2018", end=None, point=None, granularity="year")))
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018")
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
print("ok: fact_from_claim returns the typed Fact for one claim")
def test_honest_empty():
e = Scripted(claims=Scripted(claims=[]))
assert claims_from(e, entities="", heading="", text="") == []
e2 = Scripted(typeclaim=Scripted(fact=None))
assert fact_from_claim(e2, claim="") is None
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
if __name__ == "__main__":
test_extract_claims_signature()
test_type_claim_signature()
test_claims_from_runs_pass1()
test_fact_from_claim_types_one_fact()
test_honest_empty()
print("\ntwo_pass_extract: 5/5 ok")
+133
View File
@@ -0,0 +1,133 @@
"""The two-pass pipeline wiring test: prose chunks flow claims->facts->store.
End-to-end on a REAL store (tmp kg.sqlite): _process_page in two_pass
mode ingests the typed facts from Pass 2 exactly as the legacy path
did — same _ingest_candidate, same containment checks, same merge; the
single-pass path keeps working (control). No network: the expert's
claims/typeclaim/extract modules are scripted.
"""
from __future__ import annotations
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
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.expert import KnowledgeConfig, KnowledgeExpert
from knowledge.store import KnowledgeStore
from knowledge.wiki import WikiPage
PAGE_TEXT = (
"Pedro Sanchez is a Spanish politician who has been the prime "
"minister of Spain since 2018. He is also Secretary-General of the "
"Spanish Socialist Workers' Party (PSOE) since 2017."
)
def make_page() -> WikiPage:
return WikiPage(title="Pedro Sanchez", pageid=1,
url="https://en.wikipedia.org/wiki/P",
fetched_at="2026-10-26", text=PAGE_TEXT, tables=[])
class ScriptedClaims:
def __call__(self, **kw):
class Out:
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
return Out()
class ScriptedTypeClaim:
def __init__(self, facts):
self.facts = facts
self.i = 0
def __call__(self, **kw):
f = self.facts[self.i]
self.i += 1
class Out:
fact = f
return Out()
def test_two_pass_ingests_typed_facts():
tmp = tempfile.mkdtemp()
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
e = KnowledgeExpert(config=KnowledgeConfig(
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="two_pass"),
store=store)
e.claims = ScriptedClaims()
e.typeclaim = ScriptedTypeClaim([
Fact(subject="Pedro Sanchez", relation="prime minister of",
object="Spain",
quote="has been the prime minister of Spain since 2018",
start="2018", end=None, point=None, granularity="year"),
Fact(subject="Pedro Sanchez", relation="secretary-general of",
object="PSOE",
quote="Secretary-General of the Spanish Socialist Workers' "
"Party (PSOE) since 2017",
start="2017", end=None, point=None, granularity="year"),
])
# per-call state that answer_question initializes (the wiring test
# drives _process_page directly)
e._extract_entities = []
e._current_goal_terms = []
e._current_goal_question = "the question"
n = e._process_page(make_page(), "the question", kws=["pedro", "prime"],
charge_llm=None, goal_terms=[])
assert n >= 2, f"two_pass should merge both facts (merged={n})"
rows = store.db.execute(
"SELECT n.norm_name, e.rel, e.dst_value, e.t_start FROM edges e "
"JOIN nodes n ON n.id=e.src_node "
"WHERE n.norm_name='pedro sanchez' ORDER BY e.id").fetchall()
assert len(rows) == 2, rows
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
def test_single_pass_still_works():
"""Control: extract_mode='single' -> the legacy one-call path."""
tmp = tempfile.mkdtemp()
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
e = KnowledgeExpert(config=KnowledgeConfig(
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="single"),
store=store)
from knowledge.extract import Fact
class ScriptedExtract:
def __call__(self, **kw):
class Out:
facts = [Fact(subject="Pedro Sanchez",
relation="prime minister of", object="Spain",
quote="has been the prime minister of Spain "
"since 2018",
start="2018", end=None, point=None,
granularity="year")]
return Out()
e.extract = ScriptedExtract()
e._extract_entities = []
e._current_goal_terms = []
e._current_goal_question = "the question"
n = e._process_page(make_page(), "the question", kws=["pedro"],
charge_llm=None, goal_terms=[])
assert n >= 1, n
rows = store.db.execute(
"SELECT COUNT(*) FROM edges e JOIN nodes n ON n.id=e.src_node "
"WHERE n.norm_name='pedro sanchez'"
).fetchone()[0]
assert rows == 1, rows
print("ok: single-pass legacy path untouched (control)")
if __name__ == "__main__":
test_two_pass_ingests_typed_facts()
test_single_pass_still_works()
print("\ntwo_pass_wiring: 2/2 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
+40
View File
@@ -0,0 +1,40 @@
"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts).
The single-pass EXTRACT asked slow local models for a giant JSON array
of typed Facts with verbatim quotes + temporal restrictions + sibling
order assertions — the output budget behind the 40-minute arithmetic.
Two-pass shortens every output: Pass 1 lists plain claims (free-form
strings, coreferences resolved — near-zero format tax); Pass 2 types
ONE claim at a time into the same Fact schema the store already eats.
Orders: NEVER produced here — one claim per call has no siblings to
reference. The legacy single-pass path (and table frags) keeps them.
"""
from __future__ import annotations
def claims_from(expert, entities: str, heading: str, text: str,
charge_llm=None) -> list[str]:
"""Pass 1: the chunk's claims as plain strings, coreferences resolved."""
if charge_llm:
charge_llm()
pred = expert.claims(entities=entities, heading=heading, text=text)
out = []
for c in (pred.claims or []):
c = (c or "").strip()
if c:
out.append(c)
return out
def fact_from_claim(expert, claim: str, charge_llm=None):
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
The Fact carries the verbatim quote and any temporal restrictions
the text states; the store's containment checks validate everything
downstream exactly as before. No orders: no siblings by construction.
"""
if charge_llm:
charge_llm()
pred = expert.typeclaim(claim=claim)
return getattr(pred, "fact", None)
+10 -1
View File
@@ -95,7 +95,15 @@ def main() -> None:
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs") streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} " streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} "
f"baseline={baseline} no_cache={no_cache}") f"baseline={baseline} no_cache={no_cache} "
f"read_timeout_s={lm_info.get('read_timeout_s')} "
f"num_retries={lm_info.get('num_retries')}")
from floop.llm import signature_overrides
ov = signature_overrides()
if ov:
streams.log(f"signature_overrides: "
+ ", ".join(f"{name}[{', '.join(f'{k}={v}' for k, v in blk.items())}]"
for name, blk in sorted(ov.items())))
if baseline: if baseline:
answer = run_baseline(question, streams) answer = run_baseline(question, streams)
@@ -122,6 +130,7 @@ def main() -> None:
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6), max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
chunk_chars_target=kcfg.get("chunk_chars_target", 32000), chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000), chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
extract_mode=kcfg.get("extract_mode", "two_pass"),
) )
ke = KnowledgeExpert(config=kconfig, streams=streams) ke = KnowledgeExpert(config=kconfig, streams=streams)
knowledge_engine = KnowledgeEngine(ke) knowledge_engine = KnowledgeEngine(ke)
+113
View File
@@ -0,0 +1,113 @@
"""The per-signature LM router tests (lm[<SignatureName>] config blocks).
Law: any dspy.Signature may carry its own settings block in config.yaml —
`lm[ExtractSignature]:` — inheriting its provider's transport ceiling and
overriding model/max_tokens/temperature. The factory `floop.llm.predict()`
applies the block at CONSTRUCTION: no call-site if's; a signature can
change model by editing config alone, forever after (his ask, 26/10: one
general function so no more config edits mid-code as the pipeline grows).
Pinned:
1. The config block parses and carries only the intended overrides.
2. predict() with no block -> plain dspy.Predict (defaults, untouched).
3. predict() with a settings-only block -> Predict whose config carries
the overrides (dspy merges self.config as lm_kwargs per call —
verified against dspy 3.4.1 _forward_preprocess).
4. predict() with a model: override -> Predict bound to a DEDICATED
cached dspy.LM (same provider base_url/ceiling, its own model); a
second predict() returns the SAME LM object (no rebuild per call).
5. A block for a signature that is never constructed breaks nothing.
6. signature_overrides() lists the active blocks for the run.log line.
Run: .venv/bin/python tests/lm_signature_router.py
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import floop.llm as llm
from floop.llm import predict, signature_overrides
from knowledge.extract import ExtractSignature
from floop.dspy_modules import InitSignature
def test_config_block_parses():
"""config.yaml carries lm[ExtractSignature] with the intended override."""
import yaml
cfg = yaml.safe_load((Path(__file__).resolve().parent.parent
/ "config.yaml").read_text())
assert "lm[ExtractSignature]" in cfg, (
"the per-signature block must be a top-level key `lm[<SigName>]`")
block = cfg["lm[ExtractSignature]"]
assert block.get("max_tokens") == 1800, block
assert "model" not in block, "no model override yet (his call: default)"
assert "lm[NoSuchSignature]" not in cfg
print("ok: config.yaml carries the lm[ExtractSignature] block, model-free")
def test_no_block_means_plain_predict():
"""A signature without a block gets the defaults, untouched."""
p = predict(InitSignature)
assert type(p).__name__ == "Predict"
assert not p.config, f"no overrides expected, got {p.config}"
assert p.lm is None, "no dedicated LM without a model override"
print("ok: no block -> plain dspy.Predict, defaults untouched")
def test_settings_block_becomes_predict_config():
"""Settings-only block -> per-call lm_kwargs (dspy honors self.config)."""
p = predict(ExtractSignature)
assert p.config.get("max_tokens") == 1800, p.config
assert p.lm is None, "settings-only block must not build a new LM"
print("ok: lm[ExtractSignature].max_tokens -> Predict config (lm_kwargs)")
def test_model_override_builds_dedicated_cached_lm():
"""A model: override binds a dedicated LM; the factory caches it."""
orig_load = llm._load_yaml
llm._load_yaml = lambda: { # noqa: E731 — monkeypatch, test-only
"lm": {"default": "local",
"local": {"base_url": "http://127.0.0.1:11435/v1",
"model": "qwen3.8-27b-uc-64k:latest",
"max_tokens": 4096, "temperature": 0.0,
"read_timeout_s": 1800, "num_retries": 1}},
"lm[InitSignature]": {"provider": "local", "model": "qwen3.8:27b",
"max_tokens": 1024},
}
llm._SIGNATURE_LMS.clear()
try:
p = predict(InitSignature)
assert p.lm is not None, "model override must bind a dedicated LM"
assert p.lm.model == "openai/qwen3.8:27b", p.lm.model
assert p.lm.kwargs["timeout"] == 1800, "inherits provider ceiling"
assert p.lm.kwargs["max_tokens"] == 1024, "block max_tokens on the LM"
assert not p.config, "dedicated LM carries the settings, not config"
# cached: a second construction reuses the SAME LM object
p2 = predict(InitSignature)
assert p2.lm is p.lm, "the factory must cache LMs per provider+model"
finally:
llm._load_yaml = orig_load
llm._SIGNATURE_LMS.clear()
print("ok: model override -> dedicated cached LM (provider ceiling inherited)")
def test_signature_overrides_lists_active_blocks():
ov = signature_overrides()
block = ov.get("ExtractSignature")
assert block and block.get("max_tokens") == 1800 and block.get("provider") == "local", ov
assert "NoSuchSignature" not in ov
print(f"ok: signature_overrides lists active blocks: {list(ov)}")
if __name__ == "__main__":
test_config_block_parses()
test_no_block_means_plain_predict()
test_settings_block_becomes_predict_config()
test_model_override_builds_dedicated_cached_lm()
test_signature_overrides_lists_active_blocks()
print("\nlm_signature_router: 5/5 ok")
+120
View File
@@ -0,0 +1,120 @@
"""The LM transport ceiling tests (fix: EXTRACT hangs on slow local models).
Law: a provider's transport ceiling (read timeout + retries) is
CONFIG, not code — a 27b model on a busy home GPU can legitimately
take >600s for a long structured output, and the silent-ollama proxy
in front of it cuts at its own READ_TIMEOUT. dspy 3.4.1 routes
openai/... through lm15 whose default read timeout is 600s — the
wall every attempt of your 2407.3s EXTRACT call died on.
Pinned here:
1. config.yaml may set per-provider `read_timeout_s` and `num_retries`;
configure_lm forwards them (timeout= -> lm15 Timeouts(read=),
num_retries -> the dspy retry loop, LMTransportError IS retryable).
2. Defaults stay honest: nothing configured -> dspy defaults
(read 600s, retries 3), unchanged behavior for cloud.
3. The first run.log line reports the ceiling (no more silent 600s
walls — you SEE the read timeout that will kill a slow call).
4. The run dies at startup on an impossible ceiling (retries<0,
timeout<=0) rather than mid-run.
Run: .venv/bin/python tests/lm_transport.py
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import floop.llm as llm
from floop.llm import configure_lm
CFG = Path(__file__).resolve().parent.parent / "config.yaml"
def test_config_carries_ceiling():
"""config.yaml supports read_timeout_s + num_retries per provider."""
import yaml
cfg = yaml.safe_load(CFG.read_text())["lm"]
local = cfg["local"]
assert local.get("read_timeout_s") == 1800, (
"local provider should declare read_timeout_s=1800 (30min — the "
"silent-ollama cut is 600s and the 27b EXTRACT runs longer)")
assert local.get("num_retries") == 1, (
"local provider should declare num_retries=1 (a hung call retries "
"once more, not 3 — each attempt costs up to read_timeout_s)")
cloud = cfg["ollama-cloud"]
assert cloud.get("read_timeout_s") == 300, (
"cloud provider should declare read_timeout_s=300 (glm-5.3-flash "
"answers EXTRACT in ~3s; 300s bounds a wedged call)")
print("ok: config.yaml declares per-provider read_timeout_s + num_retries")
def test_configure_lm_forwards_ceiling():
"""configure_lm builds the LM with timeout=/num_retries from config."""
import dspy
os.environ["FLOOP_LM"] = "local"
info = configure_lm()
assert info["provider"] == "local"
lm = llm._ACTIVE
assert lm.kwargs.get("timeout") == 1800, lm.kwargs.get("timeout")
assert getattr(lm, "num_retries", None) == 1, getattr(lm, "num_retries", None)
# the cloud provider, in the same config, carries its own ceiling
os.environ["FLOOP_LM"] = "ollama-cloud"
info2 = configure_lm()
assert info2["provider"] == "ollama-cloud"
lm2 = llm._ACTIVE
assert lm2.kwargs.get("timeout") == 300
assert getattr(lm2, "num_retries", None) == 2
del os.environ["FLOOP_LM"]
print("ok: configure_lm forwards timeout= + num_retries per provider")
def test_defaults_unchanged_when_unset():
"""No ceiling declared -> dspy defaults (600s read, retries 3)."""
import yaml
src = CFG.read_text()
assert "read_timeout_s" in src, "config.yaml must carry the new keys"
# simulate: build an LM from a config WITHOUT the keys — the loader
# must not invent values (None -> dspy default)
cfg = yaml.safe_load(src)["lm"]
stripped = {k: ({kk: vv for kk, vv in v.items()
if kk not in ("read_timeout_s", "num_retries")}
if isinstance(v, dict) else v)
for k, v in cfg.items()}
orig_load = llm._load_yaml
llm._load_yaml = lambda: {"lm": stripped} # noqa: E731 — monkeypatch, test-only
try:
os.environ["FLOOP_LM"] = "local"
configure_lm()
lm = llm._ACTIVE
assert "timeout" not in lm.kwargs, (
f"unset ceiling must not reach the LM (got {lm.kwargs.get('timeout')})")
assert getattr(lm, "num_retries", None) is None or lm.num_retries == 3, (
"dspy default num_retries=3 must survive untouched")
finally:
llm._load_yaml = orig_load
del os.environ["FLOOP_LM"]
print("ok: no ceiling declared -> dspy defaults, nothing invented")
def test_run_log_first_line_reports_ceiling():
"""The provider dict carries the ceiling for the run.log provenance."""
os.environ["FLOOP_LM"] = "local"
info = configure_lm()
assert info.get("read_timeout_s") == 1800, info
assert info.get("num_retries") == 1, info
del os.environ["FLOOP_LM"]
print("ok: configure_lm returns read_timeout_s/num_retries for the log line")
if __name__ == "__main__":
test_config_carries_ceiling()
test_configure_lm_forwards_ceiling()
test_defaults_unchanged_when_unset()
test_run_log_first_line_reports_ceiling()
print("\nlm_transport: 4/4 ok")
+87
View File
@@ -0,0 +1,87 @@
"""Live wire check: does config timeout= actually bound the HTTP read?
Starts a local server that NEVER answers (a socket that accepts and
hangs), points the LM at it with a tiny timeout, and asserts the call
dies in ~timeout (not dspy's default 600s, not forever). This is the
one-hop proof that the ceiling travels configure_lm -> dspy.LM ->
lm15 engine -> the wire. Offline (127.0.0.1), one call, seconds.
"""
import os
import socket
import sys
import threading
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
HOST, PORT = "127.0.0.1", 0 # ephemeral
def hang_server(stop: threading.Event, port_box: list):
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((HOST, PORT))
srv.listen(4)
port_box.append(srv.getsockname()[1])
srv.settimeout(1.0)
while not stop.is_set():
try:
conn, _ = srv.accept()
# read nothing more; just hold the connection open forever
conn.settimeout(5.0)
try:
conn.recv(65536)
except OSError:
pass
except socket.timeout:
continue
srv.close()
def main():
port_box: list = []
stop = threading.Event()
t = threading.Thread(target=hang_server, args=(stop, port_box), daemon=True)
t.start()
while not port_box:
time.sleep(0.05)
port = port_box[0]
import dspy
import floop.llm as llm
orig_load = llm._load_yaml
llm._load_yaml = lambda: {"lm": {
"default": "hang",
"hang": {"base_url": f"http://127.0.0.1:{port}/v1",
"model": "test-model", "max_tokens": 8,
"temperature": 0.0,
"read_timeout_s": 3, "num_retries": 0},
}}
try:
os.environ["FLOOP_LM"] = "hang"
llm.configure_lm()
lm = llm._ACTIVE
assert lm.kwargs["timeout"] == 3.0, lm.kwargs
t0 = time.monotonic()
try:
lm(messages=[{"role": "user", "content": "hi"}])
print("FAIL: the hang server answered?!")
return 1
except Exception as e:
dt = time.monotonic() - t0
# the call must die at ~3s (+ handshake slack), NOT 600s
assert dt < 10, f"timeout did not bound the read: {dt:.1f}s"
print(f"ok: read died at {dt:.1f}s (timeout=3 honored on the wire; "
f"exception={type(e).__name__})")
return 0
finally:
stop.set()
llm._load_yaml = orig_load
os.environ.pop("FLOOP_LM", None)
if __name__ == "__main__":
rc = main()
print("WIRE CHECK:", "PASS" if rc == 0 else "FAIL")
sys.exit(rc)