Author SHA1 Message Date
onibot e365f6d1e8 feat: floop-inspect — the post-mortem HTML debugger (PR B)
One run dir in -> ONE self-contained inspect.html out. The events are
inlined as JSON; the page opens offline from file:// with ZERO network
references. Four views (owner 26/10: IDE-like debugging a posteriori):

- timeline: every component as a bar in time order — LLM calls (with
  real durations) vs code nodes colored differently; click a bar -> its
  in/out in the header detail line. The 'which expert are we inside'
  view.
- kg: the snapshot graph on canvas (spring layout, vanilla JS): nodes
  sized by degree, edges with temporal windows, THIS RUN's touched edges
  highlighted in accent blue, click a node/edge -> detail (subject, rel,
  object, window, last-touch event).
- facts: the two-pass debug table — claims per chunk, each claim ->
  typed fact (or declined), each merge verdict with reason.
- probes: per question what the hybrid probe returned (seeds, rows,
  semantic adds, tau) and the prover's DSL + verdict + bindings.

Fixed on real render (browser-verified): the KG canvas measured 0x0
while its tab was hidden (display:none) — layout now runs lazily on
first visible draw and every tab activation dispatches a resize, so
the canvas paints correctly (verified: painted pixels present, all
four tabs render content).

TDD: inspect_html 3/3 (self-contained offline, honest error without
events, empty run renders). Suite: 32 test files green.
Usage: python -m floop.inspect_html runs/<ts>/
2026-10-27 07:47:21 +01:00
onibot 9f2fbd711c Merge pull request 'feat: flight recorder — events.jsonl for post-mortem debugging' (#30) from feat/flight-recorder into main 2026-10-27 07:42:28 +01:00
onibot d384a10a8d feat: flight recorder — events.jsonl for post-mortem debugging
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
programació, però a posteriori de l'execució' — see WHERE inside which
expert we are at every moment, and the input/output of every component,
LLM or not. This is the recorder half (PR A of the observability plan).

- floop/recorder.py: append-only JSONL, one event per line. LAWS:
  never breaks a run (emitting is swallowed; no run dir = TOTAL no-op,
  no buffer, no counters); every line self-describing (seq, ts, run_ts,
  event, payload); in/out carry structured data, the exact prompt text
  stays in prompts/NN-stage.txt (events stay small).
- Wired via RunStreams (every component already had streams):
  comp.start/comp.out (machine stages INIT/ROUTE/EXPERT/ANSWER/FINAL),
  state, llm.done (stage, dur_s, call_seq, prompt file link — from the
  dspy callback), run.final.
- Knowledge pipeline components (floop-internal nodes, not LLMs):
  probe.done (seeds, rows, tau, semantic adds), claims.done (the claim
  list), type.done (claim -> typed fact, one per claim as ruled),
  fact.merged / fact.rejected (one per fact — _ingest_candidate is
  called per fact; verdict + reason + page), prover.done (dsl, verdict:
  invalid_dsl/no_closed_path/closed/ambiguous, bindings), kg.snapshot
  (once at run end: every edge with temporal window + last_touch from
  this run's merge events).
- kg_snapshot(): rows annotated with their last-touch event (owner:
  'cada fila del kg podria tenir anotat quan s'afegeix o edita').

Live-checked: baseline run writes real events (comp.start, llm.done
dur_s=17.35, comp.out '4'). TDD: recorder 3/3; suite 31 files green.

Next (PR B): floop-inspect — the HTML debugger reading events.jsonl
(timeline Gantt, KG view, facts table, probe view).
2026-10-27 07:42:23 +01:00
onibot 86af2c968d Merge pull request 'fix: completeness beats budget — no claim cap, dedup by code, budget 200' (#29) from fix/no-claim-cap into main 2026-10-26 20:29:31 +01:00
onibot 964189387d fix: completeness beats budget — no claim cap, dedup by code, budget 200
Owner ruling (26/10): 'the budget has never been a priority and must
never harm us here.' The cap=6 from #28 (my call, never agreed) cut the
Socialist International claim — it was #7 of 46 in the lead chunk of
live run 20261026-170521 — so the KG never held the third presidency
reading and the judge could not offer it.

- claims_from: NO cap, NO semantic filter. Code-only honesty: exact
  repeats dropped (live finding: glm listed its 46-claim list with ~26
  exact repeats + thinking leakage as items). Case/whitespace-insensitive
  dedup keeps the FIRST occurrence. Every unique claim gets its TYPE
  call.
- max_claims_per_chunk: deprecated in config (kept only for the
  table-frags legacy path).
- budget.max_llm_calls: 80 -> 200 (bounds runaway runs only).

TDD: two_pass_extract 6/6 (new: dedup keeps unique claims verbatim).
Suite: 30 test files green.
2026-10-26 20:29:27 +01:00
onibot 2ee3b54661 Merge pull request 'fix: two-pass Pass 2 needs the chunk text (invented quotes) + claim cap' (#28) from fix/two-pass-contract into main 2026-10-26 17:05:16 +01:00
onibot a9837981b3 fix: two-pass Pass 2 needs the chunk text (quotes were invented) + claim cap
Live cloud run 20261026-164236 found both on the wire:
1. TypeClaim carried ONLY the claim — the model could not copy the
   verbatim quote from anywhere, so it invented one and the containment
   check rejected 69/70 candidates (the safety net working, the
   CONTRACT wrong). Fix: TypeClaim gains the chunk text; the model finds
   the real quote there ('find the VERBATIM quote here, copied exactly').
2. One charge per claim starved the budget: ~70 claims ate all 80
   llm_calls before Q2 (80/80, baseline fallback, no FINAL). Fix:
   max_claims_per_chunk=6 (each claim costs a TYPE call; without a cap
   one big article starves the run).

The speed win is real and kept: CLAIMS 14-20s/chunk, TYPE 2.8-8s/claim
(the 40-minute output budget is gone). Honest note: the cap bounds per
chunk, not the whole run (3 articles x 6 chunks x 7 calls ~ 126 > 80)
— if the run starves again, next lever is claim selection or a lower
cap, his call.

TDD: two_pass_extract 5/5 on the new contract (TypeClaim fields
{claim,text,fact}). Suite: 29 test files green.
2026-10-26 17:05:10 +01:00
onibot 88769c508c Merge pull request 'feat: two-pass EXTRACT (claims -> typed Facts) for prose chunks' (#27) from feat/two-pass-extract into main 2026-10-26 16:42:27 +01:00
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
14 changed files with 1113 additions and 6 deletions
+3 -1
View File
@@ -35,7 +35,9 @@ lm[ExtractSignature]:
# on slow local models (the 40-min arithmetic) # on slow local models (the 40-min arithmetic)
budget: 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) # entity questions — a 3-river fan needs ~3x a scalar)
min_child_budget: 6 min_child_budget: 6
max_depth: 2 # recursion cap (PIPELINE.md §8.4) max_depth: 2 # recursion cap (PIPELINE.md §8.4)
+317
View File
@@ -0,0 +1,317 @@
"""floop-inspect — the post-mortem HTML debugger (PR B).
One run dir in -> ONE self-contained inspect.html out. The events are
inlined as JSON; the page opens offline from file:// with zero network
references. Four views (owner 26/10):
- timeline: every component as a bar in time order (LLM vs code
colored), the 'where inside which expert are we' view
- kg: the snapshot graph (canvas, force layout, temporal windows +
last-touch highlighted)
- facts: the two-pass debug table (claim -> typed fact -> merge
verdict, rejections with reason)
- probes: per question, what the semantic search returned
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
def generate(run_dir: str | Path) -> Path:
run_dir = Path(run_dir)
ev_path = run_dir / "events.jsonl"
if not ev_path.exists():
print(f"no events.jsonl in {run_dir} — nothing to inspect",
file=sys.stderr)
raise SystemExit(1)
events = []
for line in ev_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line:
try:
events.append(json.loads(line))
except json.JSONDecodeError:
pass # torn line mid-crash: skip, honest
html = _render(events)
out = run_dir / "inspect.html"
out.write_text(html, encoding="utf-8")
return out
def main(argv: list[str]) -> int:
if len(argv) != 2:
print("usage: python -m floop.inspect_html <run_dir>", file=sys.stderr)
return 2
out = generate(argv[1])
print(f"inspect: {out}")
return 0
def _render(events: list[dict]) -> str:
payload = json.dumps(events, default=str)
return _TEMPLATE.replace("__EVENTS__", payload)
# ---- the page (vanilla JS, no deps, no network) ---------------------------
_TEMPLATE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>floop-inspect</title>
<style>
:root { --bg:#111; --fg:#ddd; --dim:#888; --acc:#4cc2ff; --llm:#c678dd;
--ok:#98c379; --bad:#e06c75; --line:#2a2a2a; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--fg);
font:13px/1.45 "JetBrains Mono","Fira Code",monospace; }
header { padding:10px 16px; border-bottom:1px solid var(--line);
position:sticky; top:0; background:var(--bg); z-index:9; }
header b { color:var(--acc); }
nav button { background:none; border:1px solid var(--line); color:var(--dim);
padding:4px 12px; margin-right:6px; cursor:pointer; border-radius:3px;
font:inherit; }
nav button.on { color:var(--fg); border-color:var(--acc); }
.view { display:none; padding:14px 16px; }
.view.on { display:block; }
#timeline { width:100%; height:60vh; }
.bar { position:absolute; height:18px; border-radius:3px; opacity:.9; }
.bar:hover { outline:1px solid #fff; }
.bar.llm { background:var(--llm); } .bar.code { background:var(--acc); }
.bar.bad { background:var(--bad); }
table { border-collapse:collapse; width:100%; margin-top:8px; }
th,td { text-align:left; padding:4px 8px; border-bottom:1px solid var(--line);
vertical-align:top; max-width:480px; overflow-wrap:break-word; }
th { color:var(--dim); font-weight:normal; }
td.ok { color:var(--ok); } td.bad { color:var(--bad); }
.pill { display:inline-block; border-radius:8px; padding:0 8px;
border:1px solid var(--line); color:var(--dim); font-size:11px; }
#kg { width:100%; height:65vh; background:#0b0b0b; border-radius:6px; }
#detail { color:var(--dim); padding:6px 0; min-height:24px; }
h3 { color:var(--acc); margin:14px 0 4px; font-size:13px; }
.final { border:1px solid var(--ok); border-radius:4px; padding:8px 12px;
margin:8px 0; }
</style>
</head>
<body>
<header>
<b>floop-inspect</b> — post-mortem debugger &nbsp;
<span id="stats"></span>
<nav>
<button data-v="timeline" class="on">timeline</button>
<button data-v="kg">kg</button>
<button data-v="facts">facts</button>
<button data-v="probes">probes</button>
</nav>
<div id="detail">hover/click a bar or node</div>
</header>
<div id="timeline" class="view on"></div>
<div id="kg" class="view"><canvas id="kgc"></canvas></div>
<div id="facts" class="view"></div>
<div id="probes" class="view"></div>
<script>
const EV = __EVENTS__;
const $ = (s) => document.querySelector(s);
// ---------- stats ----------
const llms = EV.filter(e => e.event === 'llm.done');
const total = llms.reduce((a,e) => a + (e.dur_s||0), 0);
$('#stats').textContent =
`${EV.length} events · ${llms.length} llm calls · ${total.toFixed(1)}s llm time` +
(EV.some(e=>e.event==='run.final') ? '' : ' · no final answer');
// ---------- tabs ----------
document.querySelectorAll('nav button').forEach(b => b.onclick = () => {
document.querySelectorAll('nav button').forEach(x=>x.classList.remove('on'));
document.querySelectorAll('.view').forEach(x=>x.classList.remove('on'));
b.classList.add('on'); $('#'+b.dataset.v).classList.add('on');
window.dispatchEvent(new Event('resize')); // hidden views measure 0 —
}); // remeasure on every activation
// ---------- timeline ----------
(() => {
const box = $('#timeline');
const t0 = EV.length ? (new Date('2000-01-01T'+EV[0].ts)).getTime() : 0;
const tN = EV.length ? (new Date('2000-01-01T'+EV[EV.length-1].ts)).getTime() : 1;
const span = Math.max(tN - t0, 1);
const W = () => box.clientWidth, H = () => box.clientHeight;
const rows = new Map(); // comp -> row index
const bars = [];
// pair llm.done with the nearest preceding comp.start of the same stage
let open = {};
for (const e of EV) {
if (e.event === 'comp.start') open[e.comp] = e;
else if (e.event === 'llm.done') {
bars.push({...e, kind:'llm', label:e.stage, ev:e});
} else if (e.event === 'comp.out' || e.event === 'state' ||
e.event === 'comp.done') {
const c = e.comp || '?';
bars.push({ts:e.ts, dur:0, kind:'code', label:c, ev:e});
} else if (e.event === 'fact.merged' || e.event === 'fact.rejected' ||
e.event === 'claims.done' || e.event === 'type.done' ||
e.event === 'probe.done' || e.event === 'prover.done') {
bars.push({ts:e.ts, dur:0, kind:'code', label:e.event, ev:e});
}
}
bars.forEach(b => { if (!rows.has(b.label)) rows.set(b.label, rows.size); });
const rowH = 24;
const px = (ts) => ((new Date('2000-01-01T'+ts)).getTime() - t0) / span * (W()-140) + 120;
const durPx = (d) => Math.max(d/span*(W()-140), 4);
bars.forEach(b => {
const x = px(b.ts), w = b.kind==='llm' ? Math.max(durPx((b.dur_s||0)*1000),4) : 8;
const y = 10 + rows.get(b.label)*rowH;
const el = document.createElement('div');
el.className = 'bar ' + (b.kind==='llm'?'llm':'code') +
(b.ev.event==='fact.rejected' ? ' bad':'');
el.style.left = x+'px'; el.style.top = y+'px';
el.style.width = Math.min(w, W()-x-2)+'px';
el.dataset.d = JSON.stringify(b.ev).slice(0,600);
el.title = b.label;
el.onclick = () => { $('#detail').textContent =
b.label + ' — ' + (b.ev.dur_s? b.ev.dur_s+'s · ':'') + el.dataset.d; };
box.appendChild(el);
});
// row labels
for (const [label, i] of rows) {
const s = document.createElement('div');
s.textContent = label;
s.style.cssText = `position:absolute;left:4px;top:${10+i*rowH}px;color:var(--dim);font-size:11px;width:112px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`;
box.appendChild(s);
}
})();
// ---------- facts ----------
(() => {
const box = $('#facts');
const rows = [];
for (const e of EV) {
if (e.event === 'claims.done')
rows.push(`<h3>${e.page} — ${e.heading||''} (${(e.out&&e.out.n_claims)||0} claims)</h3>` +
((e.out&&e.out.claims)||[]).map(c=>`<div>· ${esc(c)}</div>`).join(''));
if (e.event === 'type.done')
rows.push(`<div style="color:var(--dim)">type: ${esc(e.claim||'')} → ` +
(e.out&&e.out.fact ? `<span class="ok">${esc(JSON.stringify(e.out.fact))}</span>` :
'<span class="bad">null (declined)</span>') + `</div>`);
if (e.event === 'fact.merged')
rows.push(`<div class="ok">merged: ${esc(fmt_fact(e.fact))}</div>`);
if (e.event === 'fact.rejected')
rows.push(`<div class="bad">rejected (${esc(e.reason)}): ${esc(fmt_fact(e.fact))}</div>`);
}
const snap = EV.find(e => e.event === 'kg.snapshot');
if (snap) rows.push(`<h3>KG final: ${snap.kg.n_live}/${snap.kg.n_edges} live · ${snap.kg.n_conflicts} conflicts</h3>`);
const fin = EV.find(e => e.event === 'run.final');
if (fin) rows.push(`<div class="final"><b>final:</b> ${esc(fin.out||'')}</div>`);
box.innerHTML = rows.join('') || '<i>no extraction events</i>';
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;');}
function fmt_fact(f){return f ? `${f.subject} | ${f.relation} | ${f.object}` : '';}
})();
// ---------- probes ----------
(() => {
const box = $('#probes');
const rows = [];
for (const e of EV) {
if (e.event === 'probe.done')
rows.push(`<h3>probe — ${esc(e.q||'')}</h3>
<div>seeds: ${(e.seeds||[]).map(esc).join(', ')}</div>
<div>rows: <span class="ok">${e.rows}</span> · semantic adds: <span class="pill">${e.semantic}</span> · tau=${e.tau||'—'}</div>`);
if (e.event === 'prover.done')
rows.push(`<h3>prover — ${esc(e.q||'')}</h3>
<div>verdict: <b class="${e.verdict==='ambiguous'||e.verdict==='closed'?'ok':'bad'}">${e.verdict}</b>${e.reason?' ('+esc(e.reason)+')':''}</div>
<div>bindings (${e.n_bindings||0}): ${(e.bindings||[]).map(esc).join(' · ')}</div>
<div style="color:var(--dim)">dsl: ${esc(JSON.stringify(e.dsl))}</div>`);
}
box.innerHTML = rows.join('') || '<i>no probe/prover events</i>';
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;');}
})();
// ---------- kg canvas (force-ish layout: subjects orbit values) ----------
(() => {
const cv = $('#kgc'), ctx = cv.getContext('2d');
const snap = EV.find(e => e.event === 'kg.snapshot');
if (!snap) { $('#kg').innerHTML = '<i style="padding:20px;display:inline-block">no kg.snapshot in this run</i>'; return; }
const edges = (snap.kg.edges||[]).filter(e => !e.retracted);
const el = $('#kg');
let nodes = null, ns = null;
function layout(){
// node set
nodes = new Map();
const nid = (name) => { if (!nodes.has(name)) nodes.set(name, {
x: Math.random()*cv.width, y: Math.random()*cv.height,
vx:0, vy:0, name, deg:0}); return nodes.get(name); };
edges.forEach(e => { nid(e.subject).deg++; nid(e.object).deg++; });
ns = [...nodes.values()];
const K = 24, REP = 1400;
for (let it=0; it<220; it++) {
for (const n of ns) {
let fx=0, fy=0;
for (const m of ns) if (m!==n) {
let dx=n.x-m.x, dy=n.y-m.y, d2=dx*dx+dy*dy||1;
fx += REP*dx/d2; fy += REP*dy/d2;
}
n.vx=(n.vx+fx)*.85; n.vy=(n.vy+fy)*.85; n.x+=n.vx; n.y+=n.vy;
}
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
let dx=b.x-a.x, dy=b.y-a.y, d=Math.sqrt(dx*dx+dy*dy)||1;
const f=(d-K)/d*.12;
a.vx+=dx*f; a.vy+=dy*f; b.vx-=dx*f; b.vy-=dy*f;
a.x+=a.vx*.02; a.y+=a.vy*.02; b.x-=b.vx*.02; b.y-=b.vy*.02;
});
}
}
function resize0(){ if (cv.width !== el.clientWidth) cv.width = el.clientWidth;
if (cv.height !== el.clientHeight) cv.height = el.clientHeight; }
function draw(){
resize0();
if (cv.width === 0 || cv.height === 0) return; // hidden: retry on activation
if (!nodes) layout();
ctx.fillStyle = '#0b0b0b'; ctx.fillRect(0,0,cv.width,cv.height);
ctx.strokeStyle = '#3a3a3a';
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y);
ctx.strokeStyle = e.last_touch ? '#4cc2ff' : '#3a3a3a';
ctx.lineWidth = e.last_touch ? 1.6 : .8; ctx.stroke();
});
ctx.font = '10px monospace';
ns.forEach(n => {
const r = 4 + Math.min(n.deg,8);
ctx.beginPath(); ctx.arc(n.x,n.y,r,0,7);
ctx.fillStyle = '#c678dd'; ctx.fill();
ctx.fillStyle = '#999';
ctx.fillText(n.name.slice(0,18), n.x+r+2, n.y+3);
});
// edge labels near midpoints (windows)
ctx.fillStyle = '#777';
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
const lab = e.rel + (e.t_start?` [${e.t_start}${e.t_end?('–'+e.t_end):'–'}]`:'');
ctx.fillText(lab.slice(0,24), (a.x+b.x)/2+3, (a.y+b.y)/2-3);
});
}
window.addEventListener('resize', draw);
draw();
cv.onclick = (m) => {
const rect = cv.getBoundingClientRect();
const x = m.clientX-rect.left, y = m.clientY-rect.top;
for (const n of ns) if ((n.x-x)**2+(n.y-y)**2 < 400) {
$('#detail').textContent = n.name + ` (deg ${n.deg})`; return; }
for (const e of edges) {
const a=nodes.get(e.subject), b=nodes.get(e.object);
const mx=(a.x+b.x)/2, my=(a.y+b.y)/2;
if ((mx-x)**2+(my-y)**2 < 500) {
$('#detail').textContent = `${e.subject} — ${e.rel} — ${e.object}` +
(e.t_start?` [${e.t_start}..${e.t_end||'now'}]`:'') +
(e.last_touch?` · touched @${e.last_touch.ts} (${e.last_touch.page})`:' · untouched this run');
return; }
}
};
})();
</script>
</body>
</html>
"""
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+18 -1
View File
@@ -58,6 +58,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
self._starts: dict[str, float] = {} # lm call_id -> monotonic start self._starts: dict[str, float] = {} # lm call_id -> monotonic start
self._stage_of: dict[str, str] = {} # lm call_id -> stage label self._stage_of: dict[str, str] = {} # lm call_id -> stage label
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file 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.reasks = 0 # LM calls the budget did not charge
self.meter = None # callable(str stage) -> None; budget charge self.meter = None # callable(str stage) -> None; budget charge
@@ -117,6 +119,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
encoding="utf-8", encoding="utf-8",
) )
self._file_of[call_id] = f self._file_of[call_id] = f
self._seq_of[call_id] = n
self._fname_of[call_id] = fn
streams.log( streams.log(
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} " f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
f"-> prompts/{fn}" f"-> prompts/{fn}"
@@ -130,7 +134,10 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
label = self._stage_of.pop(call_id, "lm") label = self._stage_of.pop(call_id, "lm")
start = self._starts.pop(call_id, None) start = self._starts.pop(call_id, None)
f = self._file_of.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 — # RAW RESPONSE into the same file: the exact LM text, unmodified —
# the parsed OUTPUT can lie by omission (run I) # the parsed OUTPUT can lie by omission (run I)
if f is not None: if f is not None:
@@ -146,6 +153,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
+ ")\n" + (raw or "(empty)")) + ")\n" + (raw or "(empty)"))
if streams is not None: if streams is not None:
streams.log(f"prompt {label} done in {dur}") 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) # dspy module class -> log stage label (knowledge/ + floop/ share the callback)
@@ -164,6 +179,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",
+124
View File
@@ -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]
+7
View File
@@ -12,6 +12,8 @@ import sys
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from .recorder import Recorder
def _slug(text: str, maxlen: int = 40) -> str: def _slug(text: str, maxlen: int = 40) -> str:
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") 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.log_path = self.run_dir / "run.log"
self.verbose = verbose self.verbose = verbose
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt 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") self._fh = open(self.log_path, "a", encoding="utf-8")
def bump_prompt_seq(self) -> int: def bump_prompt_seq(self) -> int:
@@ -68,18 +71,21 @@ class RunStreams:
def call(self, stage: str, description: str, think: str | None = None) -> None: def call(self, stage: str, description: str, think: str | None = None) -> None:
"""An LLM call or engine step is starting.""" """An LLM call or engine step is starting."""
self._emit_log(f"CALL {stage}: {description}") self._emit_log(f"CALL {stage}: {description}")
self.recorder.emit("comp.start", comp=stage, desc=description[:200])
if think is not None: if think is not None:
self.think_line(f"[{stage}] {think}") self.think_line(f"[{stage}] {think}")
def output(self, stage: str, text: str, think: bool = True) -> None: def output(self, stage: str, text: str, think: bool = True) -> None:
"""Raw LLM (or engine) output as it lands.""" """Raw LLM (or engine) output as it lands."""
self._emit_log(f"OUTPUT {stage}: {text}") self._emit_log(f"OUTPUT {stage}: {text}")
self.recorder.emit("comp.out", comp=stage, out=text[:500])
if think: if think:
self.think(text) self.think(text)
def state(self, text: str, think: bool = False) -> None: def state(self, text: str, think: bool = False) -> None:
"""State change: evidence appended, question status, budget.""" """State change: evidence appended, question status, budget."""
self._emit_log(f"STATE {text}") self._emit_log(f"STATE {text}")
self.recorder.emit("state", text=text[:300])
if think: if think:
self.think_line(text) self.think_line(text)
@@ -94,6 +100,7 @@ class RunStreams:
def final(self, text: str) -> None: def final(self, text: str) -> None:
self._emit_log(f"FINAL {text}") self._emit_log(f"FINAL {text}")
self.recorder.emit("run.final", out=text[:2000])
self.think_line(f"[FINAL] {text}") self.think_line(f"[FINAL] {text}")
# ---- internals --------------------------------------------------------- # ---- internals ---------------------------------------------------------
+103 -3
View File
@@ -30,12 +30,13 @@ 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)
@@ -163,6 +164,13 @@ 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
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: class KnowledgeExpert:
@@ -176,6 +184,8 @@ class KnowledgeExpert:
self.client = client or WikipediaClient() self.client = client or WikipediaClient()
self.streams = streams self.streams = streams
self.extract = predict(ExtractSignature) self.extract = predict(ExtractSignature)
self.claims = predict(ExtractClaims)
self.typeclaim = predict(TypeClaim)
self.answer = predict(AnswerFromKG) self.answer = predict(AnswerFromKG)
self.select_table = predict(SelectTableSignature) self.select_table = predict(SelectTableSignature)
self.verify_count = predict(VerifyCountSignature) self.verify_count = predict(VerifyCountSignature)
@@ -199,6 +209,16 @@ class KnowledgeExpert:
if self.streams: if self.streams:
self.streams.state(text, think=think) 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: def _qvec(self, question: str) -> list[float] | None:
"""Question vector, cached per question text. None = embedder down """Question vector, cached per question text. None = embedder down
(the probe degrades to lexical — offline fallback law, never dead).""" (the probe degrades to lexical — offline fallback law, never dead)."""
@@ -225,9 +245,13 @@ class KnowledgeExpert:
rows = self.store.probe(seeds) rows = self.store.probe(seeds)
qv = self._qvec(question) qv = self._qvec(question)
if qv is None: if qv is None:
self._rec("probe.done", q=question[:80], seeds=list(seeds),
rows=len(rows), semantic=0)
return rows return rows
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau) sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
if not sem: if not sem:
self._rec("probe.done", q=question[:80], seeds=list(seeds),
rows=len(rows), semantic=0)
return rows return rows
seen = {r.eid for r in rows} seen = {r.eid for r in rows}
added = 0 added = 0
@@ -240,6 +264,9 @@ class KnowledgeExpert:
if added: if added:
self._log(f"semantic probe: +{added} edges the lexical probe missed " self._log(f"semantic probe: +{added} edges the lexical probe missed "
f"(tau={self.cfg.semantic_tau})", think=True) 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 return rows
@staticmethod @staticmethod
@@ -325,14 +352,20 @@ class KnowledgeExpert:
ok, reason = validate_query(q) ok, reason = validate_query(q)
if not ok: if not ok:
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True) 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 return None
proof = evaluate(self.store, q) proof = evaluate(self.store, q)
if not proof.bindings: if not proof.bindings:
self._log(f"prover: no closed path; judge path", think=True) 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 return None
if not re_execute(self.store, q, proof): if not re_execute(self.store, q, proof):
self._log("prover: re-execution mismatch (store changed?); judge path", self._log("prover: re-execution mismatch (store changed?); judge path",
think=True) think=True)
self._rec("prover.done", q=question[:80],
verdict="reexecution_mismatch", dsl=q)
return None return None
vals = [] vals = []
quote = "" quote = ""
@@ -368,8 +401,47 @@ class KnowledgeExpert:
self._log(f"prover: closed path ({n} binding(s): " self._log(f"prover: closed path ({n} binding(s): "
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call", f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
think=True) 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 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 = "", 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:
@@ -1166,6 +1238,31 @@ 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)
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: 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,
@@ -1235,6 +1332,8 @@ class KnowledgeExpert:
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]}")
self._rec("fact.rejected", reason=reason, fact=dict(cand),
page=page.title)
return 0, None 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,
@@ -1245,6 +1344,7 @@ class KnowledgeExpert:
t_start=cand["start"] or None, t_start=cand["start"] or None,
t_end=cand["end"] or None) t_end=cand["end"] or None)
self._merged += 1 self._merged += 1
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
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"])
+35
View File
@@ -72,6 +72,41 @@ 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
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): 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
+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
+136
View File
@@ -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")
+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")
+52
View File
@@ -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)
+11
View File
@@ -130,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)
@@ -142,6 +143,16 @@ def main() -> None:
report: RunReport = FloopRun(question, budget, streams=streams, report: RunReport = FloopRun(question, budget, streams=streams,
knowledge_engine=knowledge_engine).run() knowledge_engine=knowledge_engine).run()
finally: 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() streams.close()
print(f"goal: {report.goal}") print(f"goal: {report.goal}")
+108
View File
@@ -0,0 +1,108 @@
"""floop-inspect tests (PR B: the post-mortem HTML debugger).
Law: one run dir in, ONE self-contained inspect.html out — the events
JSON inlined, zero network references (opens offline from file://),
every tab present (timeline, KG, facts, probes), and the run's final
answer visible. A run dir without events.jsonl errors honestly."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from floop.inspect_html import generate
EVENTS = [
{"seq": 1, "ts": "10:00:00.000", "run_ts": "10:00:00.000",
"event": "comp.start", "comp": "INIT", "desc": "decompose: q0"},
{"seq": 2, "ts": "10:00:01.000", "run_ts": "10:00:00.000",
"event": "llm.done", "stage": "INIT", "call_seq": 1, "dur_s": 0.9,
"file": "prompts/01-INIT.txt", "exception": None},
{"seq": 3, "ts": "10:00:01.100", "run_ts": "10:00:00.000",
"event": "comp.out", "comp": "INIT", "out": "Q1 sub"},
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
"event": "claims.done", "page": "Pedro Sanchez",
"heading": "Career", "out": {"n_claims": 1,
"claims": ["PM of Spain since 2018"]}},
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
"event": "type.done", "page": "Pedro Sanchez",
"claim": "PM of Spain since 2018",
"out": {"fact": {"subject": "Pedro Sanchez",
"relation": "prime minister of", "object": "Spain"}}},
{"seq": 6, "ts": "10:00:03.500", "run_ts": "10:00:00.000",
"event": "fact.merged", "eid": 7,
"fact": {"subject": "Pedro Sanchez", "relation": "prime minister of",
"object": "Spain"}, "page": "Pedro Sanchez"},
{"seq": 7, "ts": "10:00:04.000", "run_ts": "10:00:00.000",
"event": "probe.done", "q": "Q1 sub", "seeds": ["pedro"], "rows": 3,
"semantic": 1, "tau": 0.45},
{"seq": 8, "ts": "10:00:05.000", "run_ts": "10:00:00.000",
"event": "prover.done", "q": "Q1 sub", "verdict": "ambiguous",
"dsl": {"lookup": {"subject": "pedro sanchez",
"rel_any": ["prime minister of"], "bind": "x"}},
"n_bindings": 2, "bindings": ["Spain", "PSOE"]},
{"seq": 9, "ts": "10:00:06.000", "run_ts": "10:00:00.000",
"event": "kg.snapshot",
"kg": {"n_edges": 1, "n_live": 1, "n_conflicts": 0,
"edges": [{"eid": 7, "subject": "pedro sanchez",
"rel": "prime minister of", "object": "Spain",
"t_start": "2018", "t_end": None, "retracted": False,
"last_touch": {"seq": 6, "ts": "10:00:03.500",
"page": "Pedro Sanchez"}}]}},
{"seq": 10, "ts": "10:00:07.000", "run_ts": "10:00:00.000",
"event": "run.final", "out": "Spain and PSOE"},
]
def _make_run(tmp: Path, events) -> Path:
run_dir = tmp / "run"
run_dir.mkdir(parents=True)
(run_dir / "events.jsonl").write_text(
"\n".join(json.dumps(e) for e in events), encoding="utf-8")
return run_dir
def test_generate_writes_selfcontained_html():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = _make_run(tmp, EVENTS)
out = generate(run_dir)
assert out == run_dir / "inspect.html", out
html = out.read_text(encoding="utf-8")
# self-contained: zero network refs, JSON inlined
assert "http://" not in html and "https://" not in html, "network ref!"
assert '"PM of Spain since 2018"' in html # events inlined
for tab in ("timeline", "kg", "facts", "probes"):
assert f'id="{tab}"' in html, tab # all tabs present
assert "Spain and PSOE" in html # final answer in
assert "prime minister of" in html # KG data in
print("ok: one self-contained inspect.html (offline, all tabs, inlined)")
def test_missing_events_errors_honestly():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = tmp / "run"
run_dir.mkdir()
try:
generate(run_dir)
raise AssertionError("must fail")
except SystemExit as e:
assert e.code not in (0, None), e
print("ok: no events.jsonl -> honest error (exit != 0)")
def test_empty_events_still_renders():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = _make_run(tmp, [])
out = generate(run_dir)
assert out.exists()
print("ok: empty run renders an honest empty view")
if __name__ == "__main__":
test_generate_writes_selfcontained_html()
test_missing_events_errors_honestly()
test_empty_events_still_renders()
print("\ninspect_run: 3/3 ok")
+65
View File
@@ -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")