Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d384a10a8d | ||
|
|
86af2c968d | ||
|
|
964189387d | ||
|
|
2ee3b54661 | ||
|
|
a9837981b3 | ||
|
|
88769c508c | ||
|
|
f6e9164e92 | ||
|
|
95dfdf7123 | ||
|
|
6ba0bce863 | ||
|
|
31c7e02e22 | ||
|
|
f31b30d811 |
+22
-1
@@ -8,15 +8,36 @@ lm:
|
||||
model: qwen3.8-27b-uc-64k:latest
|
||||
max_tokens: 4096
|
||||
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:
|
||||
base_url: https://ollama.com/v1
|
||||
model: glm-5.3-flash
|
||||
max_tokens: 4096
|
||||
temperature: 0.0
|
||||
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:
|
||||
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
||||
# owner ruling 26/10: completeness beats budget — the budget must never
|
||||
# silently truncate extraction; it bounds runaway runs only
|
||||
max_llm_calls: 200 # per FLOOP run (children get a slice; fan-outs multiply
|
||||
# entity questions — a 3-river fan needs ~3x a scalar)
|
||||
min_child_budget: 6
|
||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
from enum import Enum
|
||||
|
||||
import dspy
|
||||
from floop.llm import predict
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .state import AnswerType
|
||||
@@ -135,12 +136,12 @@ class FloopModules:
|
||||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.init = dspy.Predict(InitSignature)
|
||||
self.route = dspy.Predict(RouteSignature)
|
||||
self.expert = dspy.Predict(ExpertSignature)
|
||||
self.missing = dspy.Predict(MissingSignature)
|
||||
self.answer = dspy.Predict(AnswerSignature)
|
||||
self.mask = dspy.Predict(EntityMaskSignature)
|
||||
self.init = predict(InitSignature)
|
||||
self.route = predict(RouteSignature)
|
||||
self.expert = predict(ExpertSignature)
|
||||
self.missing = predict(MissingSignature)
|
||||
self.answer = predict(AnswerSignature)
|
||||
self.mask = predict(EntityMaskSignature)
|
||||
|
||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||
"""(parsed subquestions, raw model output). The machine decides what
|
||||
|
||||
+102
-2
@@ -58,6 +58,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||
self._seq_of: dict[str, int] = {} # lm call_id -> prompt seq (budget mirror)
|
||||
self._fname_of: dict[str, str] = {} # lm call_id -> prompt file name
|
||||
self.reasks = 0 # LM calls the budget did not charge
|
||||
self.meter = None # callable(str stage) -> None; budget charge
|
||||
|
||||
@@ -117,6 +119,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
encoding="utf-8",
|
||||
)
|
||||
self._file_of[call_id] = f
|
||||
self._seq_of[call_id] = n
|
||||
self._fname_of[call_id] = fn
|
||||
streams.log(
|
||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||
f"-> prompts/{fn}"
|
||||
@@ -130,7 +134,10 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
label = self._stage_of.pop(call_id, "lm")
|
||||
start = self._starts.pop(call_id, None)
|
||||
f = self._file_of.pop(call_id, None)
|
||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
||||
n = self._seq_of.pop(call_id, None)
|
||||
fn = self._fname_of.pop(call_id, None)
|
||||
dur_s = (time.monotonic() - start) if start is not None else None
|
||||
dur = f"{dur_s:.1f}s" if dur_s is not None else "?"
|
||||
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
||||
# the parsed OUTPUT can lie by omission (run I)
|
||||
if f is not None:
|
||||
@@ -146,6 +153,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
||||
+ ")\n" + (raw or "(empty)"))
|
||||
if streams is not None:
|
||||
streams.log(f"prompt {label} done in {dur}")
|
||||
try:
|
||||
streams.recorder.emit(
|
||||
"llm.done", stage=label, call_seq=n,
|
||||
dur_s=(round(dur_s, 2) if dur_s is not None else None),
|
||||
file=f"prompts/{fn}" if fn is not None else None,
|
||||
exception=repr(exception)[:120] if exception else None)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
||||
@@ -164,6 +179,8 @@ _STAGE_BY_MODULE = {
|
||||
"MissingSignature": "MISSING",
|
||||
"AnswerSignature": "ANSWER",
|
||||
"ExtractSignature": "EXTRACT",
|
||||
"ExtractClaims": "CLAIMS",
|
||||
"TypeClaim": "TYPE",
|
||||
"AnswerFromKG": "answer_kg",
|
||||
"SelectTableSignature": "SELECT_TABLE",
|
||||
"VerifyCountSignature": "VERIFY_COUNT",
|
||||
@@ -196,13 +213,27 @@ def configure_lm(no_cache: bool = False) -> dict:
|
||||
"temperature": p["temperature"],
|
||||
"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:
|
||||
kwargs["cache"] = False
|
||||
lm = dspy.LM(**kwargs)
|
||||
global _ACTIVE
|
||||
_ACTIVE = 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:
|
||||
@@ -219,6 +250,75 @@ def install_prompt_log(streams) -> None:
|
||||
_ACTIVE: "dspy.LM | 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":
|
||||
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""The flight recorder — every component of a run leaves a JSON line.
|
||||
|
||||
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
|
||||
programació, però a posteriori de l'execució.' This is the recorder
|
||||
half: LLM calls and code components (gate, skim, claims, type, merge,
|
||||
probe, prover...) each emit one event to runs/<ts>/events.jsonl with
|
||||
their input, output, and parent — the span tree comes from `parent`.
|
||||
|
||||
Design laws:
|
||||
- The recorder must NEVER break a run: emitting is wrapped so any
|
||||
failure is swallowed; with no run dir it is a silent no-op.
|
||||
- One JSON object per line, appended and flushed: the file is
|
||||
tail-able while the run is live and jq-able afterwards.
|
||||
- `seq` is global per run (order of emission = file order).
|
||||
- `in`/`out` carry only the caller-provided payload; the prompt files
|
||||
keep the exact full text — events stay small and structured.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class Recorder:
|
||||
"""Append-only JSONL event log for one run. No-op without a run dir."""
|
||||
|
||||
def __init__(self, run_dir: str | Path | None = None,
|
||||
memory: bool = False) -> None:
|
||||
self.run_dir = Path(run_dir) if run_dir else None
|
||||
self.run_ts = (datetime.now(timezone.utc).astimezone()
|
||||
.strftime("%H:%M:%S.%f")[:-3])
|
||||
self.seq = 0
|
||||
self.events = 0
|
||||
self._memory = memory # keep events in RAM even without a file
|
||||
self._fh = None
|
||||
self._buffer: list[dict] = []
|
||||
if self.run_dir is not None:
|
||||
try:
|
||||
self._fh = (self.run_dir / "events.jsonl").open(
|
||||
"a", encoding="utf-8")
|
||||
except OSError:
|
||||
self._fh = None
|
||||
|
||||
# -- emission ---------------------------------------------------------
|
||||
|
||||
def emit(self, event: str, **fields: Any) -> None:
|
||||
"""One JSON line. `in_`/`out` are renamed to `in`/`out` (keywords).
|
||||
Never raises: a run must not die for an observability side effect.
|
||||
Without a run dir this is a TOTAL no-op (no file, no buffer, no
|
||||
counters): disabled must mean zero effect.
|
||||
"""
|
||||
if self._fh is None and not self._memory:
|
||||
return
|
||||
try:
|
||||
payload = dict(fields)
|
||||
if "in_" in payload:
|
||||
payload["in"] = payload.pop("in_")
|
||||
self.seq += 1
|
||||
line = {
|
||||
"seq": self.seq,
|
||||
"ts": datetime.now(timezone.utc).astimezone()
|
||||
.strftime("%H:%M:%S.%f")[:-3],
|
||||
"run_ts": self.run_ts,
|
||||
"event": event,
|
||||
**payload,
|
||||
}
|
||||
if self._fh is not None:
|
||||
self._fh.write(json.dumps(line, default=str) + "\n")
|
||||
self._fh.flush()
|
||||
self._buffer.append(line)
|
||||
self.events += 1
|
||||
except Exception: # noqa: BLE001 — observability never kills the run
|
||||
pass
|
||||
|
||||
# -- post-mortem reads --------------------------------------------------
|
||||
|
||||
def events_of(self, event: str) -> list[dict]:
|
||||
"""In-memory events by name (for snapshot annotations)."""
|
||||
return [e for e in self._buffer if e.get("event") == event]
|
||||
|
||||
def close(self) -> None:
|
||||
if self._fh is not None and not self._fh.closed:
|
||||
try:
|
||||
self._fh.flush()
|
||||
self._fh.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def timed(fn, recorder: Recorder, event: str, **parent_fields):
|
||||
"""Wrap a code component: emit comp.done with in/out and duration."""
|
||||
import functools
|
||||
|
||||
@functools.wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
out = fn(*args, **kwargs)
|
||||
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||
ok=True, out=_safe(out), **parent_fields)
|
||||
return out
|
||||
except Exception as e: # noqa: BLE001 — record then re-raise
|
||||
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||
ok=False, error=repr(e)[:200], **parent_fields)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
def _safe(v: Any, _depth: int = 0) -> Any:
|
||||
"""Best-effort JSON-safety: truncate strings, cap depth."""
|
||||
if _depth > 4:
|
||||
return "..."
|
||||
if isinstance(v, str):
|
||||
return v if len(v) <= 500 else v[:500] + "…"
|
||||
if isinstance(v, dict):
|
||||
return {str(k): _safe(x, _depth + 1) for k, x in list(v.items())[:30]}
|
||||
if isinstance(v, (list, tuple)):
|
||||
return [_safe(x, _depth + 1) for x in list(v)[:50]]
|
||||
if v is None or isinstance(v, (bool, int, float)):
|
||||
return v
|
||||
return str(v)[:200]
|
||||
@@ -12,6 +12,8 @@ import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from .recorder import Recorder
|
||||
|
||||
|
||||
def _slug(text: str, maxlen: int = 40) -> str:
|
||||
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
||||
@@ -35,6 +37,7 @@ class RunStreams:
|
||||
self.log_path = self.run_dir / "run.log"
|
||||
self.verbose = verbose
|
||||
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
||||
self.recorder = Recorder(run_dir=self.run_dir, memory=True)
|
||||
self._fh = open(self.log_path, "a", encoding="utf-8")
|
||||
|
||||
def bump_prompt_seq(self) -> int:
|
||||
@@ -68,18 +71,21 @@ class RunStreams:
|
||||
def call(self, stage: str, description: str, think: str | None = None) -> None:
|
||||
"""An LLM call or engine step is starting."""
|
||||
self._emit_log(f"CALL {stage}: {description}")
|
||||
self.recorder.emit("comp.start", comp=stage, desc=description[:200])
|
||||
if think is not None:
|
||||
self.think_line(f"[{stage}] {think}")
|
||||
|
||||
def output(self, stage: str, text: str, think: bool = True) -> None:
|
||||
"""Raw LLM (or engine) output as it lands."""
|
||||
self._emit_log(f"OUTPUT {stage}: {text}")
|
||||
self.recorder.emit("comp.out", comp=stage, out=text[:500])
|
||||
if think:
|
||||
self.think(text)
|
||||
|
||||
def state(self, text: str, think: bool = False) -> None:
|
||||
"""State change: evidence appended, question status, budget."""
|
||||
self._emit_log(f"STATE {text}")
|
||||
self.recorder.emit("state", text=text[:300])
|
||||
if think:
|
||||
self.think_line(text)
|
||||
|
||||
@@ -94,6 +100,7 @@ class RunStreams:
|
||||
|
||||
def final(self, text: str) -> None:
|
||||
self._emit_log(f"FINAL {text}")
|
||||
self.recorder.emit("run.final", out=text[:2000])
|
||||
self.think_line(f"[FINAL] {text}")
|
||||
|
||||
# ---- internals ---------------------------------------------------------
|
||||
|
||||
+111
-10
@@ -25,16 +25,18 @@ import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
import dspy
|
||||
from floop.llm import predict
|
||||
|
||||
from .checks import check_candidate, quote_containment
|
||||
from .chunker import chunk_page
|
||||
from .skim import find_quantities, skim_article
|
||||
from .extract import (AnswerFromKG, ExtractSignature, Fact, SelectTableSignature,
|
||||
SkimPromoteSignature, SkimTableSignature,
|
||||
VerifyCountSignature)
|
||||
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
||||
SelectTableSignature, SkimPromoteSignature,
|
||||
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
||||
from .embeddings import EmbedderDown, embed
|
||||
from .queries import compose_queries, keywords, proper_nouns
|
||||
from .store import KnowledgeStore, norm_name
|
||||
from .two_pass import claims_from, fact_from_claim
|
||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
||||
tables_as_chunks, format_table_frag)
|
||||
|
||||
@@ -162,6 +164,13 @@ class KnowledgeConfig:
|
||||
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
||||
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
||||
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
||||
max_claims_per_chunk: int = 6 # DEPRECATED (owner ruling 26/10:
|
||||
# completeness beats budget) — no longer
|
||||
# read by the two-pass loop; kept only for
|
||||
# the table-frags legacy path
|
||||
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:
|
||||
@@ -174,12 +183,14 @@ class KnowledgeExpert:
|
||||
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
||||
self.client = client or WikipediaClient()
|
||||
self.streams = streams
|
||||
self.extract = dspy.Predict(ExtractSignature)
|
||||
self.answer = dspy.Predict(AnswerFromKG)
|
||||
self.select_table = dspy.Predict(SelectTableSignature)
|
||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
||||
self.skim_tables = dspy.Predict(SkimTableSignature)
|
||||
self.extract = predict(ExtractSignature)
|
||||
self.claims = predict(ExtractClaims)
|
||||
self.typeclaim = predict(TypeClaim)
|
||||
self.answer = predict(AnswerFromKG)
|
||||
self.select_table = predict(SelectTableSignature)
|
||||
self.verify_count = predict(VerifyCountSignature)
|
||||
self.skim_promote = predict(SkimPromoteSignature)
|
||||
self.skim_tables = predict(SkimTableSignature)
|
||||
self._checked = 0
|
||||
self._merged = 0
|
||||
# semantic probe: cached question vector for this call (the probe
|
||||
@@ -198,6 +209,16 @@ class KnowledgeExpert:
|
||||
if self.streams:
|
||||
self.streams.state(text, think=think)
|
||||
|
||||
def _rec(self, event: str, **fields) -> None:
|
||||
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
||||
every component, LLM or not, leaves one JSON line. No streams ->
|
||||
silent no-op (the recorder law: observability never breaks a run)."""
|
||||
if self.streams is not None:
|
||||
try:
|
||||
self.streams.recorder.emit(event, **fields)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def _qvec(self, question: str) -> list[float] | None:
|
||||
"""Question vector, cached per question text. None = embedder down
|
||||
(the probe degrades to lexical — offline fallback law, never dead)."""
|
||||
@@ -224,9 +245,13 @@ class KnowledgeExpert:
|
||||
rows = self.store.probe(seeds)
|
||||
qv = self._qvec(question)
|
||||
if qv is None:
|
||||
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||
rows=len(rows), semantic=0)
|
||||
return rows
|
||||
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
||||
if not sem:
|
||||
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||
rows=len(rows), semantic=0)
|
||||
return rows
|
||||
seen = {r.eid for r in rows}
|
||||
added = 0
|
||||
@@ -239,6 +264,9 @@ class KnowledgeExpert:
|
||||
if added:
|
||||
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
||||
f"(tau={self.cfg.semantic_tau})", think=True)
|
||||
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||
rows=len(rows), semantic=added,
|
||||
tau=self.cfg.semantic_tau)
|
||||
return rows
|
||||
|
||||
@staticmethod
|
||||
@@ -304,7 +332,7 @@ class KnowledgeExpert:
|
||||
from .prover import evaluate, re_execute, validate_query
|
||||
from .translate_dsl import TranslateToDSL
|
||||
if not hasattr(self, "translate_dsl"):
|
||||
self.translate_dsl = dspy.Predict(TranslateToDSL)
|
||||
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()]
|
||||
@@ -324,14 +352,20 @@ class KnowledgeExpert:
|
||||
ok, reason = validate_query(q)
|
||||
if not ok:
|
||||
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
||||
self._rec("prover.done", q=question[:80], verdict="invalid_dsl",
|
||||
reason=reason, dsl=q)
|
||||
return None
|
||||
proof = evaluate(self.store, q)
|
||||
if not proof.bindings:
|
||||
self._log(f"prover: no closed path; judge path", think=True)
|
||||
self._rec("prover.done", q=question[:80], verdict="no_closed_path",
|
||||
dsl=q)
|
||||
return None
|
||||
if not re_execute(self.store, q, proof):
|
||||
self._log("prover: re-execution mismatch (store changed?); judge path",
|
||||
think=True)
|
||||
self._rec("prover.done", q=question[:80],
|
||||
verdict="reexecution_mismatch", dsl=q)
|
||||
return None
|
||||
vals = []
|
||||
quote = ""
|
||||
@@ -367,8 +401,47 @@ class KnowledgeExpert:
|
||||
self._log(f"prover: closed path ({n} binding(s): "
|
||||
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
||||
think=True)
|
||||
self._rec("prover.done", q=question[:80],
|
||||
verdict="closed" if n == 1 else "ambiguous",
|
||||
dsl=q, n_bindings=n, bindings=[v[:80] for v in vals])
|
||||
return answer
|
||||
|
||||
def kg_snapshot(self) -> dict:
|
||||
"""The KG as a JSON-safe object for the flight recorder: every
|
||||
live edge with its temporal window and its LAST-TOUCH event (owner
|
||||
26/10: 'cada fila del kg podria tenir anotat quan s'afegeix o
|
||||
edita'). The last-touch map comes from this run's merge events
|
||||
(in the recorder's memory); rows the run never touched carry the
|
||||
empty marker. One snapshot per run — emitted once at the end."""
|
||||
try:
|
||||
last_touch: dict[int, dict] = {}
|
||||
rec = (self.streams.recorder if self.streams else None)
|
||||
if rec is not None:
|
||||
for e in rec.events_of("fact.merged"):
|
||||
if e.get("eid") is not None:
|
||||
last_touch[e["eid"]] = {"seq": e.get("seq"),
|
||||
"ts": e.get("ts"),
|
||||
"page": e.get("page")}
|
||||
edges = []
|
||||
for (eid, subj, rel, dstv, s, en, red) in self.store.db.execute(
|
||||
"SELECT e.id, n.norm_name, e.rel, e.dst_value, "
|
||||
"e.t_start, e.t_end, e.retracted "
|
||||
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||
"ORDER BY e.id").fetchall():
|
||||
edges.append({
|
||||
"eid": eid, "subject": subj, "rel": rel,
|
||||
"object": dstv, "t_start": s, "t_end": en,
|
||||
"retracted": bool(red),
|
||||
"last_touch": last_touch.get(eid),
|
||||
})
|
||||
conflicts = self.store.db.execute(
|
||||
"SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||
return {"n_edges": len(edges),
|
||||
"n_live": sum(1 for e in edges if not e["retracted"]),
|
||||
"n_conflicts": conflicts, "edges": edges}
|
||||
except Exception: # noqa: BLE001 — a snapshot must never kill a run
|
||||
return {"n_edges": 0, "n_live": 0, "n_conflicts": 0, "edges": []}
|
||||
|
||||
def answer_question(self, question: str, parent_question: str = "",
|
||||
evidence: str = "", charge_llm=None,
|
||||
answer_type: str = "") -> dict:
|
||||
@@ -1165,6 +1238,31 @@ class KnowledgeExpert:
|
||||
think=True)
|
||||
extracted = 0
|
||||
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)
|
||||
self._rec("claims.done", page=page.title,
|
||||
heading=chunk.heading_path,
|
||||
out_={"n_claims": len(claims),
|
||||
"claims": list(claims)})
|
||||
# owner ruling 26/10: completeness beats budget — every
|
||||
# unique claim gets its TYPE call (no cap, dedup only)
|
||||
for claim in claims:
|
||||
fact = fact_from_claim(self, claim, text=chunk.text,
|
||||
charge_llm=charge_llm)
|
||||
self._rec("type.done", page=page.title, claim=claim[:200],
|
||||
out_={"fact": getattr(fact, "__dict__", None)}
|
||||
if fact is not None else {"fact": None})
|
||||
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:
|
||||
charge_llm()
|
||||
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
||||
@@ -1234,6 +1332,8 @@ class KnowledgeExpert:
|
||||
ok, reason = check_candidate(cand, containment)
|
||||
if not ok:
|
||||
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
||||
page=page.title)
|
||||
return 0, None
|
||||
doc_id = self.store.add_document(
|
||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||
@@ -1244,6 +1344,7 @@ class KnowledgeExpert:
|
||||
t_start=cand["start"] or None,
|
||||
t_end=cand["end"] or None)
|
||||
self._merged += 1
|
||||
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
|
||||
if eid is not None:
|
||||
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
||||
cand["object"])
|
||||
|
||||
@@ -72,6 +72,41 @@ class ExtractSignature(dspy.Signature):
|
||||
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
|
||||
and the TEXT it was extracted from, type the claim into the Fact
|
||||
schema: subject entity, relation, object/value, the VERBATIM quote
|
||||
copied EXACTLY from the text (the FULL sentence or table row that
|
||||
states the claim, 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. If the text does not state the claim, return
|
||||
null."""
|
||||
claim: str = dspy.InputField(desc="the claim to type")
|
||||
text: str = dspy.InputField(
|
||||
desc="the text the claim was extracted from — find the VERBATIM "
|
||||
"quote here, copied exactly")
|
||||
fact: Fact | None = dspy.OutputField(
|
||||
desc="the typed Fact with its verbatim quote from the text, or "
|
||||
"null when the claim cannot be typed honestly")
|
||||
|
||||
|
||||
class AnswerFromKG(dspy.Signature):
|
||||
"""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
|
||||
|
||||
@@ -64,7 +64,7 @@ def test_format_and_parse_stop():
|
||||
|
||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||
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.streams = None
|
||||
e._checked = e._merged = 0
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""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", "text", "fact"}, fields # text: the quote must be COPIED from it (live finding: without it, 69/70 invented quotes rejected)
|
||||
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", text="...")
|
||||
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="", text="") is None
|
||||
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||
|
||||
|
||||
def test_claims_from_dedupes_exact_repeats():
|
||||
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||
deterministic — the claim list must not be capped or filtered
|
||||
semantically, only made honest: no exact duplicates survive."""
|
||||
calls = []
|
||||
|
||||
class E: # minimal expert double
|
||||
def claims(self, entities, heading, text):
|
||||
calls.append((entities, heading))
|
||||
class Out:
|
||||
claims = ["Pedro Sanchez is prime minister of Spain.",
|
||||
"pedro sanchez is prime minister of spain. ",
|
||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||
"Pedro Sanchez is prime minister of Spain.",
|
||||
"from the text. I need to list factual claims"]
|
||||
return Out()
|
||||
|
||||
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||
"from the text. I need to list factual claims"], got
|
||||
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_extract_claims_signature()
|
||||
test_type_claim_signature()
|
||||
test_claims_from_dedupes_exact_repeats()
|
||||
test_claims_from_runs_pass1()
|
||||
test_fact_from_claim_types_one_fact()
|
||||
test_honest_empty()
|
||||
print("\ntwo_pass_extract: 6/6 ok")
|
||||
@@ -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")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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.
|
||||
|
||||
The list is made honest by CODE only: exact repeats are dropped
|
||||
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||
thinking leakage leaks in as list items). Dedup is case- and
|
||||
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
||||
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
||||
26/10) — every unique claim gets its TYPE call.
|
||||
"""
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||
seen: dict[str, str] = {}
|
||||
for c in (pred.claims or []):
|
||||
c = (c or "").strip()
|
||||
if c:
|
||||
key = " ".join(c.lower().split())
|
||||
if key not in seen:
|
||||
seen[key] = c
|
||||
return list(seen.values())
|
||||
|
||||
|
||||
def fact_from_claim(expert, claim: str, text: str, charge_llm=None):
|
||||
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
||||
|
||||
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
||||
came from) — without the text the model invents a quote and the
|
||||
containment check rejects it (live finding 26/10: 69/70 rejected).
|
||||
The store's checks validate everything downstream as before. No
|
||||
orders: no siblings by construction.
|
||||
"""
|
||||
if charge_llm:
|
||||
charge_llm()
|
||||
pred = expert.typeclaim(claim=claim, text=text)
|
||||
return getattr(pred, "fact", None)
|
||||
+20
-1
@@ -95,7 +95,15 @@ def main() -> None:
|
||||
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
||||
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} "
|
||||
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:
|
||||
answer = run_baseline(question, streams)
|
||||
@@ -122,6 +130,7 @@ def main() -> None:
|
||||
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
|
||||
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
|
||||
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
|
||||
extract_mode=kcfg.get("extract_mode", "two_pass"),
|
||||
)
|
||||
ke = KnowledgeExpert(config=kconfig, streams=streams)
|
||||
knowledge_engine = KnowledgeEngine(ke)
|
||||
@@ -134,6 +143,16 @@ def main() -> None:
|
||||
report: RunReport = FloopRun(question, budget, streams=streams,
|
||||
knowledge_engine=knowledge_engine).run()
|
||||
finally:
|
||||
# THE FLIGHT RECORDER CLOSE-OUT: the KG snapshot (owner 26/10:
|
||||
# one snapshot at the end, each row annotated with its last-touch
|
||||
# event) and the recorder's file handle. Best-effort: the report
|
||||
# has already been produced; observability never kills a run.
|
||||
try:
|
||||
if knowledge_engine is not None and streams is not None:
|
||||
streams.recorder.emit("kg.snapshot",
|
||||
kg=knowledge_engine.ke.kg_snapshot())
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
streams.close()
|
||||
|
||||
print(f"goal: {report.goal}")
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The flight recorder tests (events.jsonl).
|
||||
|
||||
Law: every component of a run — LLM or not — leaves one JSON line in
|
||||
runs/<ts>/events.jsonl with its input, output, and parent, so the run
|
||||
can be debugged a posteriori like an IDE session (owner 26/10: 'vull
|
||||
fer com un debug amb l'IDE, però a posteriori'). The recorder must
|
||||
never break a run: emitting is side-effect-free and cheap, and with no
|
||||
run dir it is a silent no-op.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from floop.recorder import Recorder
|
||||
|
||||
|
||||
def test_emit_writes_valid_jsonl_lines(tmp=None):
|
||||
import tempfile
|
||||
tmp = Path(tempfile.mkdtemp())
|
||||
r = Recorder(run_dir=tmp)
|
||||
r.emit("comp.done", comp="gate", parent="page:pedro", in_={"heading": "x"},
|
||||
out={"kept": True}, dur_ms=3)
|
||||
r.emit("fact.merged", fact={"s": "a"}, verdict="merged", eid=42)
|
||||
lines = (tmp / "events.jsonl").read_text().strip().splitlines()
|
||||
assert len(lines) == 2, lines
|
||||
e1, e2 = (json.loads(l) for l in lines)
|
||||
assert e1["event"] == "comp.done" and e1["comp"] == "gate", e1
|
||||
assert e1["in"] == {"heading": "x"} and e1["out"] == {"kept": True}, e1
|
||||
assert e1["parent"] == "page:pedro" and e1["seq"] == 1 and e1["dur_ms"] == 3
|
||||
assert "ts" in e1 and e1["run_ts"], e1
|
||||
assert e2["seq"] == 2 and e2["verdict"] == "merged" and e2["eid"] == 42
|
||||
print("ok: emit -> one valid JSON line each, seq/ts/in/out/parent kept")
|
||||
|
||||
|
||||
def test_disabled_recorder_is_a_silent_noop():
|
||||
r = Recorder(run_dir=None)
|
||||
r.emit("comp.done", comp="gate", out={"kept": True}) # must not raise
|
||||
assert r.events == 0
|
||||
print("ok: no run dir -> no-op, never breaks a run")
|
||||
|
||||
|
||||
def test_in_memory_events_readable_for_snapshot():
|
||||
import tempfile
|
||||
tmp = Path(tempfile.mkdtemp())
|
||||
r = Recorder(run_dir=tmp)
|
||||
r.emit("merge.done", eid=7, verdict="merged")
|
||||
r.emit("merge.done", eid=7, verdict="dup") # corroboration bump
|
||||
evs = r.events_of("merge.done")
|
||||
assert [e["eid"] for e in evs] == [7, 7]
|
||||
assert [e["verdict"] for e in evs] == ["merged", "dup"]
|
||||
# last-touch annotation: per-row latest event
|
||||
last = {}
|
||||
for e in evs:
|
||||
last[e["eid"]] = e["verdict"]
|
||||
assert last == {7: "dup"}
|
||||
print("ok: events_of() lets the snapshot annotate each row's last touch")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_emit_writes_valid_jsonl_lines()
|
||||
test_disabled_recorder_is_a_silent_noop()
|
||||
test_in_memory_events_readable_for_snapshot()
|
||||
print("\nrecorder: 3/3 ok")
|
||||
Reference in New Issue
Block a user