Files
onibot 096326e3a3 merge main (phase 0: K5 fix, --no-cache, import assert) into research/semantic-kg
Conflict resolutions, the honest way:
- extract/expert gap-step: main's deterministic COMPOSE wins over the
  branch's TRANSLATE LLM (main removed it 23/10 with measurement: the
  model was putting the ANSWER into retrieval queries). The branch's
  _extract_entities contract (question-blind extractor) is fed from
  compose's entities.
- tablefrags/semantic tests: restored the branch's adapted versions +
  fixed their single-insert sys.path bug (parent.parent resolved to
  knowledge/, not code/ — the tests were silently importing MAIN's
  expert.py through the venv pth; same class as the run-085457 trap).
2026-10-25 20:04:47 +01:00

169 lines
7.2 KiB
Python

"""Semantic KG retrieval tests (research/semantic-kg).
Laws under test:
1. semantic_probe ranks cached edge vectors by cosine and keeps >= tau:
the 'President' question surfaces the 'Prime Minister' edge the LEXICAL
probe cannot see (no shared stems) — calibration 0.71 vs cross-ques
noise 0.35-0.38, tau=0.45.
2. The hybrid _probe: lexical UNION semantic, dedup by edge id — the
same edge never enters twice.
3. Honest degradation: embedder down -> lexical rows only, never a dead
run (_embed_ok flips, the log says it).
4. Vectors are a cache keyed (edge_id, model, text_hash): switching the
model invalidates — the stale vector is replaced, not mixed.
5. EdgeView carries eid (dedup key between the two probes).
Network: the embed() calls are monkeypatched with scripted vectors —
the test runs offline.
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
import knowledge.embeddings as emb
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
from knowledge.store import KnowledgeStore
def make_store(tmp: str) -> KnowledgeStore:
return KnowledgeStore(f"{tmp}/kg.sqlite")
def _add_fact(store: KnowledgeStore, src: str, rel: str, dst: str,
quote: str) -> int:
doc = store.add_document(url="http://x/" + src, title=src,
fetched_at="2026-10-22", sha256="sha" + src)
qid = store.add_quote(doc, quote, "http://x/" + src, "2026-10-22")
return store.add_edge(src, rel, dst, qid)
def test_semantic_probe_surfaces_lexical_miss():
"""The Pedro case: 'President before' shares NO stems with 'prime
minister of Spain' — the lexical probe misses it, the semantic one
must surface it (this is the long search his run paid)."""
import tempfile
store = make_store(tempfile.mkdtemp())
e1 = _add_fact(store, "Pedro Sanchez", "position",
"Prime Minister of Spain", "he has been the prime "
"minister of Spain since 2018")
e2 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
# scripted vectors: PM-edge close to the question, Po-edge far away
q_vec = [1.0, 0.0, 0.0]
pm_vec = [0.92, 0.39, 0.0]
po_vec = [0.0, 0.2, 0.98]
store.set_edge_vector(e1, "test-model", "h1", pm_vec)
store.set_edge_vector(e2, "test-model", "h2", po_vec)
hits = store.semantic_probe(q_vec, tau=0.45)
assert any("Prime Minister" in (h.dst or "") for h in hits), hits
assert all("652" not in (h.dst or "") for h in hits), hits
print("ok: semantic probe surfaces the lexical-missed edge (PM of Spain)")
def test_hybrid_probe_dedups():
"""Lexical UNION semantic with dedup by edge id: an edge found by both
probes appears once. The lexical hit keeps its position; the semantic
fills the tail."""
import tempfile
store = make_store(tempfile.mkdtemp())
e1 = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
e2 = _add_fact(store, "Pedro Sanchez", "position",
"Prime Minister of Spain", "prime minister since 2018")
store.set_edge_vector(e1, "m", "h1", [1.0, 0.0])
store.set_edge_vector(e2, "m", "h2", [1.0, 0.1])
expert = KnowledgeExpert.__new__(KnowledgeExpert)
expert.cfg = KnowledgeConfig()
expert.store = store
expert.streams = None
expert._embed_ok = True
expert._qvec_cache = {}
expert._log = lambda *a, **k: None
orig_embed = emb.embed
try:
def fake_embed(texts, model=None, url=None, timeout=60):
vecs = {"Who was the President before Pedro Sanchez?": [0.95, 0.31],
"Po | length | 652 km": [1.0, 0.0],
"Pedro Sanchez | position | Prime Minister of Spain": [1.0, 0.1]}
return [vecs[t] for t in texts]
from knowledge import expert as expert_mod
expert_mod.embed = fake_embed # the module's imported name
rows = expert._probe("Who was the President before Pedro Sanchez?",
["pedro", "president"])
eids = [r.eid for r in rows]
assert len(eids) == len(set(eids)), f"dupes in hybrid probe: {rows}"
# lexical hit (Po) present; semantic-only hit (PM) also present
assert any(r.src == "po" for r in rows), rows
assert any("Prime Minister" in (r.dst or "") for r in rows), rows
print("ok: hybrid probe — lexical UNION semantic, dedup by eid")
finally:
from knowledge import expert as expert_mod
expert_mod.embed = orig_embed
del expert_mod
def test_embedder_down_degrades():
"""Embedder down: _embed_ok flips, the probe returns the lexical rows
alone, and nothing raises — the run stays alive (offline fallback)."""
import tempfile
store = make_store(tempfile.mkdtemp())
_add_fact(store, "Po", "length", "652 km", "the Po is 652 km long")
expert = KnowledgeExpert.__new__(KnowledgeExpert)
expert.cfg = KnowledgeConfig()
expert.store = store
expert.streams = None
expert._embed_ok = True
expert._qvec_cache = {}
notes = []
expert._log = lambda text, think=False: notes.append(text)
from knowledge import expert as expert_mod
orig = expert_mod.embed
def boom(texts, model=None, url=None, timeout=60):
raise emb.EmbedderDown("endpoint down")
expert_mod.embed = boom
try:
rows = expert._probe("length of the Po river?", ["river", "length"])
assert rows and rows[0].src == "po", rows
assert expert._embed_ok is False
assert any("disabled" in n for n in notes), notes
# second call: no embed attempt at all (cache of the failure)
rows2 = expert._probe("length of the Po river?", ["river", "length"])
assert rows2
print("ok: embedder down -> lexical degradation, run alive")
finally:
expert_mod.embed = orig
def test_vector_cache_invalidates_by_model():
"""Keyed (edge_id, model, text_hash): a new model replaces the stale
row — the probe never mixes vectors of two models."""
import tempfile
store = make_store(tempfile.mkdtemp())
eid = _add_fact(store, "Po", "length", "652 km", "the Po is 652 km")
store.set_edge_vector(eid, "model-a", "h1", [1.0, 0.0])
store.set_edge_vector(eid, "model-b", "h1", [0.0, 1.0])
# question along model-b's direction (the LAST upserted vector): the
# edge hits; along model-a's old direction it must NOT (replaced)
hits_b = store.semantic_probe([0.0, 1.0], tau=0.9)
assert hits_b and hits_b[0].eid == eid, hits_b
hits_a = store.semantic_probe([1.0, 0.0], tau=0.9)
assert not hits_a, f"stale model-a vector still live: {hits_a}"
import sqlite3
rows = store.db.execute(
"SELECT model, vec FROM edge_vectors WHERE edge_id=?", (eid,)).fetchall()
assert len(rows) == 1 and rows[0][0] == "model-b", f"upsert failed: {rows}"
print("ok: vector cache upserts (one row per edge; last model wins)")
if __name__ == "__main__":
test_semantic_probe_surfaces_lexical_miss()
test_hybrid_probe_dedups()
test_embedder_down_degrades()
test_vector_cache_invalidates_by_model()
print("\nsemantic kg tests passed")