Author SHA1 Message Date
emili a007e8da25 Merge pull request 'feat: OTel trace exporter — events.jsonl to Jaeger (post-mortem)' (#32) from feat/otel-traces into main
Reviewed-on: #32
2026-10-27 15:19:56 +01:00
onibotandClaude 1af308ae60 feat: named inputs/outputs in traces + clickable prompts + expert names
Owner's 27/10 review of the OTel export, four asks, all landed:

1. NAMED IN/OUT PER FUNCTION: fn.done events (fn, in, out) at the
   knowledge pipeline's main functions - search (in.query -> out.titles),
   fetch, skim, compose, chunk_gate, serve_set, list_ingest, harvest,
   promote, check, judge - rendered as spans with in.<arg>/out.<arg>
   attributes. "wiki search ('Pedro date take'): [...]" is now
   knowledge.search with in.query and out.titles as data.
2. SIGNATURE IN/OUT: the dspy prompt-log callback emits sig.start/sig.done
   - the typed fields of every dspy call (in.question, out.entities,
   out.facts...). The LLM span and the sig span are one node.
3. CLICKABLE PROMPT: every LLM span carries a child 'prompt' span with
   the exact prompt + raw response read from prompts/NN-stage.txt at
   export time - retroactive for old runs (the Pedro run re-exports with
   128 prompt children).
4. EXPERT NAMES: EXPERT comp spans carry expert= (EXPERT knowledge);
   nested spans prefix with the expert (knowledge.search,
   knowledge.state, knowledge.TranslateToDSL); each expert exports its
   spans under its own OTel service so Jaeger groups by component.

Live-verified end to end: smoke run (glm-5.3-flash) exported while
running - MASK shows in.question -> out.entities [{France, PLACE}],
EXPERT knowledge nests knowledge.TranslateToDSL under service
knowledge; read back via Jaeger's own API. Suite: traces 7/7, all
floop + knowledge test files green (guards/value_clean caught two bugs
in the new emissions before commit: a wrong-scope variable and a
use-before-define; _rec now reads getattr(streams) so __new__ test
fakes survive).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-27 14:27:56 +01:00
onibot 6ea769b7d1 feat: OTel trace exporter - events.jsonl to Jaeger (post-mortem)
ARCHITECTURE 9-bis BUILT: one run = one OTel trace, deterministic id
(sha of run dir name); root span named by the question with the final
answer as attribute; INIT/ROUTE/EXPERT/ANSWER as nested component spans;
every llm.done/probe.done/fact.merged event one span; recursive child
runs (same events.jsonl, own run_ts, seq restarts) nest as per-run
spans. Post-mortem only - the run never touches the network.

floop/traces.py stdlib only; pushes OTLP/HTTP JSON to Jaeger v2
(docker on agentvps, 10.3.14.59:16686 UI / :4318 ingest, VPN-bound).
python -m floop.traces runs/<dir> | --latest N | --dry.

Verified: Pedro 09:15 run -> 393 spans (root 1193.8s, 128 llm spans),
read back via Jaeger API; fractal goal run nests to depth 6.
tests/traces.py 5/5; recorder 3/3; inspect 3/3.
2026-10-27 12:34:44 +01:00
onibot d6c5bed443 Merge pull request 'feat: floop-inspect — the post-mortem HTML debugger' (#31) from feat/floop-inspect into main 2026-10-27 07:47:27 +01:00
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
18 changed files with 1875 additions and 52 deletions
+50 -12
View File
@@ -260,7 +260,7 @@ branches compete for budget, a learned router earns its place (v2).
becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training
data, and the same data feeds prompt optimization and fine-tuning (META.md). data, and the same data feeds prompt optimization and fine-tuning (META.md).
## 9-bis. Observability roadmap (future plan): OpenTelemetry ## 9-bis. Observability (2026-10-27): OpenTelemetry export, BUILT
Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical
superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the
@@ -268,19 +268,57 @@ WARNING channel (machine judgements worth a human's eye — the mask seed that
auto-answered a question, guards refusing ingests, budget starvation). This is complete auto-answered a question, guards refusing ingests, budget starvation). This is complete
but closed: reading it means tailing files. but closed: reading it means tailing files.
**Planned, not built:** export the run as **OpenTelemetry** traces/spans so floop is **BUILT (post-mortem half):** the run exports as **OpenTelemetry** traces/spans
observable from the standard tooling that already exists — Jaeger, Grafana Tempo, (`floop/traces.py`), so floop is observable from the standard tooling that already
any OTLP consumer — instead of floop growing its own dashboards. The mapping is exists — Jaeger (running on the agentvps as a docker container), Grafana Tempo, any
natural: one run = one trace; each LLM call, engine step (probe, search, fetch, check, OTLP consumer — instead of floop growing its own dashboards. The mapping is the
merge) and evidence append = one span, carrying the fields the logs carry today natural one: one run = one trace; each LLM call, engine step (probe, search, fetch,
check, merge) and evidence append = one span, carrying the fields the logs carry today
(stage, budget tick, duration, prompt-file pointer, verification flags, warnings). (stage, budget tick, duration, prompt-file pointer, verification flags, warnings).
The planned `events.jsonl` (machine-readable event stream) becomes the in-process `events.jsonl` (the flight recorder's machine-readable event stream) is the single
event bus this exporter reads — one schema, two consumers (offline self-analysis in schema with two consumers: offline self-analysis in META.md, and `python -m
META.md, live OTel export). Warnings export as span events first-class, since they are floop.traces <run_dir>` replaying it into Jaeger over OTLP/HTTP after the run — the
the self-improvement signal the lessons bank counts. run itself never touches the network (observability never kills a run). Warnings
export as span attributes/events first-class, since they are the self-improvement
signal the lessons bank counts.
Deferred until the loop hardening is done — building it before v1's shape settles Conventions the exporter keeps:
would instrument a moving target. - Deterministic trace ids (sha of the run dir name) — the same run always maps to
the same trace id, so UI links are stable and a re-push finds the same trace.
- The root span is named by the run's question and carries the final answer as an
attribute; the trace list in Jaeger reads as a list of questions.
- Recursive child runs (recursive floop as an expert attendant) write the SAME
events.jsonl with their own run_ts; each child-run block becomes its own span
nested under the spawning component, so the fractal recursion is visible as
nesting, and `seq` restarting is expected (positions, not seq, identify spans).
- `ts` is local wall time without a date; the date comes from the run dir name,
and a backwards jump means midnight crossed. The clock is only ever fed in
emission order — pre-reading a later event poisons the midnight detector.
Owner's visibility laws (27/10, this PR) — inputs and outputs are data, not
prose:
- Every pipeline function emits `fn.done` (fn, in, out) with NAMED arguments:
in.query / out.titles for the Wikipedia search, in.title / out.{url, chars,
tables} for the fetch, in.question / out.{value, confidence} for the judge,
compose, skim, chunk_gate, serve_set, list_ingest, harvest, promote, check.
- Every dspy call emits `sig.start` (the Signature's input fields, named:
in.question, in.entities...) and `sig.done` (the typed output fields:
out.entities, out.facts, out.value...) — emitted by the prompt-log callback,
which sees the module forward; the LLM span and the sig span are the SAME
node (name = stage, attributes carry in.*/out.* plus dur/call_seq/file).
- The exact prompt + raw response live in a CHILD `prompt` span of every LLM
span, read from the prompts/ file at export time — clickable in Jaeger,
works retroactively for old runs.
- EXPERT component spans carry the attendant's name (EXPERT knowledge);
everything nested inside carries the expert prefix (knowledge.search,
knowledge.state, knowledge.TYPE), and each expert exports its spans under
its own OTel service (floop / knowledge / ...) so Jaeger groups and colors
by component.
**Still deferred:** the in-process LIVE export (an OTLP exporter listening on the
event bus during the run, so Jaeger shows the waterfall while the run is still
going). Same schema, second consumer — build when a live run is actually observed
from outside; the hardening of the loop has priority.
## 10. Risks ## 10. Risks
+94
View File
@@ -418,3 +418,97 @@ PR-1 skim surfaces + unit-pattern signals + chunk ranking + {{cvt}} unit
fix; PR-2 opportunistic harvest + seen-index + link queue; PR-3 skim fix; PR-2 opportunistic harvest + seen-index + link queue; PR-3 skim
notices to the machine. The lucky same-article case is NOT the design notices to the machine. The lucky same-article case is NOT the design
target — the goal-aware harvest is. target — the goal-aware harvest is.
---
# Tooling — OTel traces + Jaeger (2026-10-27, no run)
**Not a run — the observability half of the owner's 26/10 ruling** ('vull
poder fer com un debug amb l'IDE de programació, però a posteriori de
l'execució'): the flight recorder's `events.jsonl` now exports as
OpenTelemetry, and the viewer is Jaeger instead of a hand-grown report.
**What was built:**
- `floop/traces.py` (stdlib only): one run = one trace (deterministic id =
sha of the run dir name — stable UI links); root span named by the
question, final answer as attribute; INIT/ROUTE/EXPERT/ANSWER as nested
component spans; every `llm.done`/`probe.done`/`fact.merged`/... event
one span with its attributes; recursive child runs (same file, own
`run_ts`, `seq` restarts) nest as per-run spans. Post-mortem only: the
run itself never touches the network.
- Jaeger v2.22 all-in-one, docker on agentvps, bound to 10.3.14.59 only
(UI :16686, OTLP :4318) — reachable from the VPN, zero exposure by
itself; Emili's apache at 10.3.14.1 fronts it publicly.
- `python -m floop.traces runs/<dir>` pushes one run; `--latest N` the
newest; `--dry` builds without pushing. `tests/traces.py` 5/5.
**Live-found bugs (the reason this took an afternoon):**
1. Pre-reading the LAST event's timestamp before the loop poisoned the
midnight detector → every span +24h. Law now written down: the clock
is only ever fed in emission order.
2. `comp.out` spans were closed but never appended — the payload shipped
every event as an orphan under the root.
3. Child-run blocks share events.jsonl; run-spans got double-appended
(stack + direct append) → duplicate span ids, Jaeger rejects.
4. OTLP/JSON wants full proto enum names (`SPAN_KIND_INTERNAL`,
`STATUS_CODE_OK`) and rejects empty `parentSpanId` on the root.
5. Jaeger v2 serves the query API at `/api/traces/...` on :16686 (not
`/api/services` — gone in v2; not under `/jaeger/api/` for reads —
that route is the SPA catch-all).
**Verified against real runs:** the 09:15 Pedro run exports 393 spans —
root 1193.8s, INIT→ROUTE→EXPERT→ROUTE→EXPERT→ANSWER children, 128 llm
spans with call_seq/dur_s/prompt-file — read back from Jaeger's own API
(393 stored, service `floop`); the fractal `goal` run nests child runs
depth 6. Three traces pushed live. ARCHITECTURE §9-bis updated: BUILT
(post-mortem), LIVE in-process export still deferred.
**Emili's open item:** the vhost at oniricapps (he configures the apache
reverse proxy + LE cert for e.g. jaeger.oniricapps.com; the container is
already reachable at 10.3.14.59:16686 from his server).
---
# Tooling 2 — named inputs/outputs in the traces (2026-10-27, PM)
**His review of the first export** (the four asks, verbatim in the PR):
inputs and outputs of everything below the floop/expert components; the
prompt accessible from Jaeger itself; the expert's name in the span
names (EXPERT knowledge, knowledge.search inside); Signature inputs and
outputs on LLM calls. All four landed on the same branch (PR #32).
**What was added:**
- `fn.done` events (fn, in, out) at the knowledge pipeline's main
functions: search (in.query/limit -> out.titles), fetch (in.title ->
out.url/chars/tables), skim, compose, chunk_gate, serve_set,
list_ingest, harvest, promote, check, judge (in.question/rows ->
out.value/confidence). Named arguments, structured values as compact
JSON.
- `sig.start`/`sig.done` from the dspy prompt-log callback: every module
forward emits the Signature's input fields (in.question,
in.entities...) and typed outputs (out.entities, out.facts,
out.value...). The LLM span and the sig span are one node.
- The `prompt` child span: the exact prompt + raw response read from
prompts/NN-stage.txt AT EXPORT TIME — retroactive for old runs (the
128-file Pedro run re-exports with 128 clickable prompts).
- Expert names: `streams.call(..., expert=...)` on the EXPERT component;
the exporter renders 'EXPERT knowledge', prefixes children
(knowledge.state, knowledge.TYPE, knowledge.search), and exports each
expert under its own OTel service — Jaeger's service selector and
colors group by component.
**Live-found bugs (mine, fixed before commit):** the harvest fn.done
referenced a local of another function (NameError) and the list_ingest
event read `verify` before it existed (UnboundLocalError) — the
value_clean test's `__new__` fake caught that _rec touched
self.streams; the law now: `_rec` reads getattr(self, "streams", None)
(__new__-built fakes never define it). Smoke run live (glm-5.3-flash):
MASK carries in.question -> out.entities [{France, PLACE}], EXPERT
knowledge nests knowledge.TranslateToDSL — verified in the export
before the run finished (the recorder flushes).
**Still open from his review:** the trace-level 'which input fed which
output' is event-adjacency, not a dataflow edge — the honest limit of
post-mortem spans. And baseline/`--baseline` mode has no recorder yet.
+37
View File
@@ -71,9 +71,46 @@ floop/llm.py dspy LM configuration (OpenAI-compatible endpoints)
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER) floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
floop/engine.py engine interface + draft stub engines floop/engine.py engine interface + draft stub engines
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
floop/recorder.py the flight recorder — events.jsonl (one JSON line per component)
floop/traces.py events.jsonl -> OpenTelemetry spans; push a run to Jaeger (post-mortem)
floop/inspect_html.py events.jsonl -> self-contained inspect.html (offline viewer)
tests/state.py unit tests (no LLM) tests/state.py unit tests (no LLM)
tests/traces.py exporter tests (no network)
``` ```
## Viewing a run as traces (Jaeger, 2026-10-27)
Every run records `events.jsonl`; `floop/traces.py` replays it as one
OpenTelemetry trace and pushes it to the Jaeger container on the agentvps
(`http://10.3.14.59:16686` on the VPN; OTLP ingest on `:4318`):
```bash
uv run python -m floop.traces runs/<ts>-<slug> # one run -> Jaeger
uv run python -m floop.traces --latest 3 # the newest runs
uv run python -m floop.traces <dir> --dry # build the payload, don't push
```
The root span is the run (named by the question, final answer as an
attribute); INIT/ROUTE/EXPERT/ANSWER components nest under it, every LLM
call is a span with its stage/duration/prompt file, and recursive child
runs appear as nested run-spans. Trace ids are deterministic — re-pushing
a run lands on the same trace. Stdlib only; the run itself never touches
the network.
Since 2026-10-27 (visibility laws), inputs and outputs are data:
- Pipeline functions emit `fn.done` — spans carry in.query / out.titles
(search), in.title / out.{url, chars, tables} (fetch), the judge's
question/value, compose/skim/chunk_gate/serve_set/list_ingest/harvest/
promote/check, each with NAMED arguments.
- dspy calls emit `sig.start`/`sig.done` — the Signature's input and
output fields as typed attributes (in.question, out.entities, out.facts).
- Every LLM span carries a CHILD `prompt` span with the exact prompt and
raw response (read from prompts/NN-stage.txt at export time) — click and
read, retroactively for old runs too.
- EXPERT spans carry the attendant name (EXPERT knowledge); nested spans
use the expert prefix (knowledge.search, knowledge.state); each expert
exports under its own OTel service (floop / knowledge / ...).
## Next steps (design order from the docs) ## Next steps (design order from the docs)
1. Real check layer on expert arrival (well-formedness per expert kind) — the 1. Real check layer on expert arrival (well-formedness per expert kind) — the
+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))
+89 -1
View File
@@ -58,20 +58,95 @@ 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._sig_call_id: str | None = None # innermost module call_id (sig events)
self._sig_stage_of: dict[str, str] = {} # module call_id -> stage label
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
# -- dspy plumbing ------------------------------------------------------- # -- dspy plumbing -------------------------------------------------------
@staticmethod
def _jsonable(v) -> object:
"""Signature field values -> JSON-safe primitives (recorder law:
small structured payloads; the exact prompt lives in the file)."""
try:
import pydantic
if isinstance(v, pydantic.BaseModel):
return v.model_dump()
except Exception: # noqa: BLE001 — best effort, never raises
pass
if isinstance(v, (str, int, float, bool)) or v is None:
return v
if isinstance(v, (list, tuple)):
return [PromptLogCallback._jsonable(x) for x in v]
if isinstance(v, dict):
return {str(k): PromptLogCallback._jsonable(x) for k, x in v.items()}
return str(v)
def _emit_sig_start(self, call_id: str, instance, inputs) -> None:
"""Signature inputs (owner 27/10): what the call receives, named.
dspy 3.4 hands the raw *args/**kwargs — the named form is inside
the kwargs repr; unknown shapes degrade to the repr itself
(honest, never a crash)."""
streams = self.streams
if streams is None:
return
try:
import ast
kw = (inputs or {}).get("kwargs", "")
named = ast.literal_eval(kw) if isinstance(kw, str) and kw.strip() \
else dict(kw or {})
if not isinstance(named, dict):
named = {"input": self._jsonable(inputs)}
except Exception: # noqa: BLE001 — observability never breaks a call
named = {"input": str(inputs)[:500]}
sig = getattr(getattr(instance, "signature", None), "__name__", None)
streams.recorder.emit("sig.start", stage=sig or "Predict",
call_id=call_id,
**{f"in.{k}": self._jsonable(v)
for k, v in named.items()})
def _emit_sig_done(self, call_id: str, outputs, exception) -> None:
"""Signature outputs (owner 27/10): the typed fields the call
produced, named — the Prediction's own attributes (only ones the
module's signature declares; dspy appends 'reasoning' internals)."""
streams = self.streams
if streams is None:
return
try:
named: dict[str, object] = {}
if isinstance(outputs, dict):
named = {k: self._jsonable(v) for k, v in outputs.items()
if k not in ("reasoning", "reasoning_model_response")}
elif outputs is not None:
for k in (getattr(outputs, "_store", None) or {}):
if k in ("reasoning", "reasoning_model_response"):
continue
named[k] = self._jsonable(outputs[k])
streams.recorder.emit("sig.done", stage=self._sig_stage_of.pop(call_id, "?"),
call_id=call_id,
exception=repr(exception)[:120] if exception else None,
**{f"out.{k}": v for k, v in named.items()})
except Exception: # noqa: BLE001 — observability never breaks a call
pass
def on_module_start(self, call_id, instance, inputs): def on_module_start(self, call_id, instance, inputs):
sig = getattr(getattr(instance, "signature", None), "__name__", None) sig = getattr(getattr(instance, "signature", None), "__name__", None)
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__) label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
self._stack.append(label) self._stack.append(label)
self._sig_call_id = call_id
self._sig_stage_of[call_id] = label
self._fresh_forward = True # this forward's first LM call is not a re-ask self._fresh_forward = True # this forward's first LM call is not a re-ask
self._emit_sig_start(call_id, instance, inputs)
def on_module_end(self, call_id, outputs, exception): def on_module_end(self, call_id, outputs, exception):
if self._stack: if self._stack:
self._stack.pop() self._stack.pop()
if call_id == self._sig_call_id:
self._emit_sig_done(call_id, outputs, exception)
self._sig_call_id = None
def on_lm_start(self, call_id, instance, inputs): def on_lm_start(self, call_id, instance, inputs):
import time import time
@@ -117,6 +192,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 +207,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 +226,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)
+4 -2
View File
@@ -585,14 +585,16 @@ class FloopRun:
self.knowledge_engine.charge = self._charge self.knowledge_engine.charge = self._charge
self.knowledge_engine.modules = self.modules self.knowledge_engine.modules = self.modules
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}", self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}") think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}",
expert="knowledge")
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table), row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type, self.query, self.table, q.answer_type,
streams=self.streams) streams=self.streams)
else: else:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant) engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}", self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking {attendant}: {q.text[:90]}") think=self.tprefix + f"asking {attendant}: {q.text[:90]}",
expert=attendant)
row = engine.run(q.qid, instantiate(q.text, self.table), row = engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type, streams=self.streams) self.query, self.table, q.answer_type, streams=self.streams)
self.engine_calls += 1 self.engine_calls += 1
+126
View File
@@ -0,0 +1,126 @@
"""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_")
if "out_" in payload:
payload["out"] = payload.pop("out_")
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]
+17 -2
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:
@@ -65,21 +68,32 @@ class RunStreams:
# ---- structural events ------------------------------------------------- # ---- structural events -------------------------------------------------
def call(self, stage: str, description: str, think: str | None = None) -> None: def call(self, stage: str, description: str, think: str | None = None,
"""An LLM call or engine step is starting.""" expert: str | None = None) -> None:
"""An LLM call or engine step is starting. `expert` names the
attendant for EXPERT steps: the trace span reads 'EXPERT
knowledge' and its children carry the 'knowledge.' prefix
(owner 27/10: inside an expert, see the expert's name)."""
self._emit_log(f"CALL {stage}: {description}") self._emit_log(f"CALL {stage}: {description}")
if expert:
self.recorder.emit("comp.start", comp=stage, desc=description[:200],
expert=expert)
else:
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 +108,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 ---------------------------------------------------------
+521
View File
@@ -0,0 +1,521 @@
"""floop-traces — replay a run's events.jsonl as OpenTelemetry spans.
ARCHITECTURE.md §9-bis, built: one run = one trace; each LLM call, engine
step (probe, search, fetch, check, merge) and evidence append = one span.
Post-mortem only: it reads runs/<ts>/events.jsonl after the run and pushes
OTLP/HTTP-JSON to Jaeger (or any OTLP consumer) — the run itself never
touches the network (observability never kills a run).
Owner's visibility laws (27/10), what the exporter renders:
- INPUTS/OUTPUTS NAMED: fn.done events (search, fetch, judge, compose...)
become spans carrying in.<arg> / out.<arg> attributes; LLM calls carry
the Signature's fields in.<field> / out.<field> (sig.start/sig.done,
emitted by the dspy callback), not just the prompt-file pointer.
- THE PROMPT IS CLICKABLE: every LLM span gets a child 'prompt' span whose
attributes carry the prompt-file's full text (prompt + raw response),
read from the run dir at export time — old runs work retroactively.
- EXPERT NAMES: an EXPERT comp.start with expert= reads 'EXPERT
knowledge'; everything nested inside carries the 'knowledge.' prefix
(knowledge.state, knowledge.TYPE, knowledge.search...), and spans of an
expert are exported under their own OTel SERVICE (floop / knowledge /
...) so Jaeger groups and colors them by component.
- Recursive child runs share the parent's events.jsonl (each child has its
own run_ts and restarts seq); each contiguous run_ts block becomes its
own span — the fractal recursion shows as nested runs in the waterfall.
Usage (from code/):
uv run python -m floop.traces runs/<ts>-<slug> # one run (or several)
uv run python -m floop.traces --latest 3 # the 3 newest runs
uv run python -m floop.traces <dir> --dry # build, don't push
Endpoint: --url or FLOOP_OTLP_URL, default http://10.3.14.59:4318/v1/traces
(the Jaeger container on this VPS). Stdlib only — no new dependencies.
"""
from __future__ import annotations
import hashlib
import json
import os
import sys
import urllib.request
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo
DEFAULT_URL = "http://10.3.14.59:4318/v1/traces"
DEFAULT_UI = "http://10.3.14.59:16686"
_TZ = ZoneInfo("Europe/Madrid") # event `ts` is local wall time (recorder law)
_PROMPT_CAP = 60_000 # chars per prompt/response attribute
def load_events(run_dir: str | Path) -> list[dict]:
"""Read events.jsonl; skip empty/torn lines; honest error if absent/empty."""
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 export", file=sys.stderr)
raise SystemExit(1)
events = []
for line in ev_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
try:
events.append(json.loads(line))
except json.JSONDecodeError:
pass # torn line mid-crash: skip, honest
if not events:
print(f"events.jsonl in {run_dir} is empty — nothing to export",
file=sys.stderr)
raise SystemExit(1)
return events
def _cap(v: Any, depth: int = 0) -> Any:
"""Attribute safety: truncate strings, cap depth/width. The kg snapshot
alone can carry 100+ edges — spans must stay small and readable."""
if isinstance(v, str):
return v if len(v) <= 500 else v[:497] + "…"
if v is None or isinstance(v, (bool, int, float)):
return v
if depth >= 3:
return "…"
if isinstance(v, dict):
return {str(k): _cap(x, depth + 1) for k, x in list(v.items())[:20]}
if isinstance(v, (list, tuple)):
return [_cap(x, depth + 1) for x in list(v)[:5]]
return str(v)[:200]
def _attrs(**fields: Any) -> dict[str, str]:
return {f"floop.{k}": str(_cap(v)) for k, v in fields.items() if v is not None}
def _flat_attrs(prefix: str, d: Any) -> dict[str, str]:
"""in./out. attribute blocks: one attribute per named argument
(in.query, out.titles...); structured values compact-JSON (capped)."""
out: dict[str, str] = {}
if not isinstance(d, dict):
return {prefix: str(_cap(d))} if d is not None else out
for k, v in d.items():
if v is None:
continue
if isinstance(v, (str, int, float, bool)):
out[f"{prefix}.{k}"] = str(_cap(v))
else:
out[f"{prefix}.{k}"] = str(_cap(json.dumps(v, default=str,
ensure_ascii=False)))
return out
def _read_prompt(run_dir: Path, rel: str) -> tuple[str, str] | None:
"""(prompt_text, raw_response) from a prompts/NN-stage.txt file — the
exact rendered prompt and the model's raw answer, verbatim."""
p = run_dir / rel
if not p.exists():
return None
try:
text = p.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
head, sep, resp = text.partition("\n\n# RAW RESPONSE")
if not sep:
head, resp = text, ""
if head.startswith("#") and "\n\n" in head: # drop the '# stage=...' line
head = head.split("\n\n", 1)[1]
if sep:
# the header line continues after '# RAW RESPONSE' ('(after 2.3s)');
# the response starts on the NEXT line
_, _, resp = resp.partition("\n")
return head[:_PROMPT_CAP], resp[:_PROMPT_CAP]
class _Clock:
"""Local wall time -> unix nanos. The date comes from the run dir name;
a backwards jump in `ts` means midnight crossed (events are monotonic).
Only ever called in emission order — pre-reading a later event would
poison the midnight detector (found the hard way)."""
def __init__(self, run_dir: Path) -> None:
stamp = run_dir.name.split("-")[0]
try:
self.day = datetime.strptime(stamp, "%Y%m%d").date()
except ValueError: # dir name is not the run contract —
mtime = (run_dir / "events.jsonl").stat().st_mtime # fall back
self.day = datetime.fromtimestamp(mtime).date() # honestly
self._prev_sod = -1
def nanos(self, ts: str) -> int:
t = datetime.strptime(ts, "%H:%M:%S.%f").time()
sod = t.hour * 3600 + t.minute * 60 + t.second
if sod < self._prev_sod: # wrapped past midnight
self.day = self.day + timedelta(days=1)
self._prev_sod = sod
dt = datetime.combine(self.day, t).replace(tzinfo=_TZ)
return int(dt.timestamp() * 1_000_000_000)
def _hex(seed: str, n: int) -> str:
return hashlib.sha256(seed.encode()).hexdigest()[:n]
def _blocks(events: list[dict]) -> list[tuple[str, list[dict]]]:
"""Split into contiguous run_ts blocks (child runs write the same file).
seq restarts are expected across blocks; positions, not seq, identify."""
blocks: list[tuple[str, list[dict]]] = []
for e in events:
rts = str(e.get("run_ts", ""))
if not blocks or blocks[-1][0] != rts:
blocks.append((rts, []))
blocks[-1][1].append(e)
return blocks
def _block_question(block: list[dict]) -> str:
for e in block:
if e["event"] == "comp.start" \
and str(e.get("desc", "")).startswith("decompose: "):
return str(e["desc"][len("decompose: "):])
return ""
def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
"""events.jsonl -> (OTLP/JSON payload, trace_id). Deterministic ids: the
same run always maps to the same trace, so re-pushes land on the same
trace and the UI link is stable."""
run_dir = Path(run_dir)
run_key = run_dir.name # <ts>-<slug>: unique, stable
trace_id = _hex(f"floop:{run_key}", 32)
root_id = _hex(f"floop:{run_key}:root", 16)
clock = _Clock(run_dir)
blocks = _blocks(events)
multi = len(blocks) > 1
def span(span_id: str, parent_id: str, name: str, start: int, end: int,
attrs: dict[str, str], error: bool = False) -> dict:
s = {
"traceId": trace_id, "spanId": span_id,
"name": name, "kind": "SPAN_KIND_INTERNAL",
"startTimeUnixNano": str(start),
"endTimeUnixNano": str(max(end, start + 1_000_000)), # >= 1ms
"attributes": [{"key": k, "value": {"stringValue": v}}
for k, v in attrs.items()],
"status": {"code": "STATUS_CODE_ERROR"} if error else
{"code": "STATUS_CODE_OK"},
"_svc": "floop", # internal keys stripped before the payload
}
if parent_id: # omitted for the root — empty values are rejected
s["parentSpanId"] = parent_id
return s
question = _block_question(blocks[0][1])
answer = next((str(_cap(e["out"])) for e in reversed(events)
if e["event"] == "run.final" and e.get("out")), "")
root_attrs = {"run.id": run_key, "floop.events": str(len(events))}
if question:
root_attrs["run.question"] = _cap(question)
if answer:
root_attrs["run.answer"] = answer
spans: list[dict] = []
stack: list[dict] = [] # open spans, outermost first (comps + sig + runs)
last_nanos = 0
pos = -1 # position in the file — the real identity (seq restarts)
mark = 0 # stack depth the current block may not close below
# -- context helpers (the expert a span lives in) ------------------------
def _expert() -> str | None:
for s in reversed(stack):
if s.get("_expert"):
return s["_expert"]
return None
def _prefix() -> str:
e = _expert()
return f"{e}." if e else ""
def _service() -> str:
return _expert() or "floop"
def close_block() -> None:
"""Block end: everything the block opened closes honestly (a child
run never leaves comps dangling into the next block)."""
while len(stack) > mark:
s = stack.pop()
s["endTimeUnixNano"] = str(last_nanos)
spans.append(s)
def add_prompt_child(parent: dict, rel: str, start: int, end: int) -> None:
"""The clickable prompt (owner 27/10): the file's full text as a
child node under the LLM call it belongs to."""
pr = _read_prompt(run_dir, rel)
if pr is None:
return
attrs = {"prompt.file": rel}
if pr[0]:
attrs["prompt.text"] = pr[0]
if pr[1]:
attrs["prompt.response"] = pr[1]
c = span(_hex(f"floop:{run_key}:p:{parent['spanId']}:{rel}", 16),
parent["spanId"], "prompt", start, end, attrs)
c["_svc"] = parent["_svc"]
spans.append(c)
for rts, block in blocks:
close_block()
mark = len(stack)
parent = stack[-1]["spanId"] if stack else root_id
if multi: # one span per run: the fractal child, visible as nesting
bquestion = _block_question(block)
bstart = clock.nanos(block[0]["ts"]) # its own first event
rs = span(_hex(f"floop:{run_key}:run:{pos + 1}", 16), parent,
(bquestion[:120] or f"floop.run {rts}"),
bstart, bstart,
_attrs(run_ts=rts))
stack.append(rs) # shipped by close_block() — never double-append
for e in block:
pos += 1
ev, ts = e["event"], e["ts"]
now = clock.nanos(ts)
last_nanos = now
parent = stack[-1]["spanId"] if stack else root_id
extra = {k: v for k, v in e.items()
if k not in ("seq", "ts", "run_ts", "event")}
sid = _hex(f"floop:{run_key}:s{pos}", 16)
if ev == "comp.start":
expert = e.get("expert")
name = str(e.get("comp", "COMP"))
if expert:
name = f"{name} {expert}"
s = span(sid, parent, name, now, now,
_attrs(comp=e.get("comp"), desc=e.get("desc")))
s["_comp"] = str(e.get("comp", ""))
if expert:
s["_expert"] = str(expert)
s["_svc"] = str(expert)
stack.append(s)
continue
if ev == "comp.out": # close the innermost same-comp span
# search the WHOLE stack: the parent EXPERT that spawned a
# child stays open across block boundaries (its comp.out
# arrives in a later block); mark only bounds block cleanup.
for j in range(len(stack) - 1, -1, -1):
if stack[j].get("_comp") == str(e.get("comp", "")):
s = stack[j]
s["endTimeUnixNano"] = str(now)
s["attributes"].extend(
{"key": k, "value": {"stringValue": v}}
for k, v in _attrs(out=e.get("out")).items())
spans.append(s) # complete: ship it
# spans opened INSIDE the comp close with it, honest
# (never silently dropped)
for inner in stack[j + 1:]:
inner["endTimeUnixNano"] = str(now)
spans.append(inner)
del stack[j:]
break
else: # unpaired comp.out: honest point span, never dropped
spans.append(span(sid, parent, f"{_prefix()}{e.get('comp', '?')}?",
now, now, _attrs(**extra)))
continue
if ev == "sig.start": # the Signature's inputs, named
s = span(sid, parent, f"{_prefix()}{e.get('stage', 'sig')}",
now, now,
_flat_attrs("in",
{k[3:]: v for k, v in e.items()
if k.startswith("in.")}))
s["_call_id"] = str(e.get("call_id", ""))
s["_svc"] = _service()
stack.append(s)
continue
if ev == "sig.done": # the Signature's outputs, named
out_attrs = _flat_attrs("out",
{k[4:]: v for k, v in e.items()
if k.startswith("out.")})
target = None
for j in range(len(stack) - 1, -1, -1):
if stack[j].get("_call_id") == str(e.get("call_id", "")):
target = stack[j]
break
if target is None: # unpaired: honest point span
spans.append(span(sid, parent,
f"{_prefix()}{e.get('stage', 'sig')}",
now, now, out_attrs,
error=bool(e.get("exception"))))
continue
# close it where it sits; everything above closes with it
j = stack.index(target)
target["endTimeUnixNano"] = str(now)
target["attributes"].extend(
{"key": k, "value": {"stringValue": v}}
for k, v in out_attrs.items())
if e.get("exception"):
target["status"] = {"code": "STATUS_CODE_ERROR"}
spans.append(target)
for inner in stack[j + 1:]:
inner["endTimeUnixNano"] = str(now)
spans.append(inner)
del stack[j:]
continue
if ev == "llm.done":
dur = int(float(e.get("dur_s") or 0) * 1_000_000_000)
stage = str(e.get("stage", "lm"))
# attach to the innermost open sig span (new runs); the
# sig span IS the call. Old runs: a standalone span.
host = None
for j in range(len(stack) - 1, -1, -1):
if "_call_id" in stack[j]:
host = stack[j]
break
err = bool(e.get("exception"))
if host is not None:
host["name"] = f"{_prefix()}{stage}"
host["attributes"].extend(
{"key": k, "value": {"stringValue": v}}
for k, v in _attrs(
dur_s=e.get("dur_s"), call_seq=e.get("call_seq"),
file=e.get("file")).items())
if err:
host["status"] = {"code": "STATUS_CODE_ERROR"}
rel = e.get("file")
if rel:
add_prompt_child(host, str(rel), now - dur, now)
else:
name = f"{'llm.'}{stage}" if not _prefix() \
else f"{_prefix()}{stage}"
s = span(sid, parent, name, now - dur, now,
_attrs(dur_s=e.get("dur_s"), call_seq=e.get("call_seq"),
file=e.get("file"), exception=e.get("exception")),
error=err)
s["_svc"] = _service()
spans.append(s)
rel = e.get("file")
if rel:
add_prompt_child(s, str(rel), now - dur, now)
continue
if ev == "fn.done": # a pipeline function, in/out named
fn = str(e.get("fn", "fn"))
attrs = _flat_attrs("in", e.get("in"))
attrs.update(_flat_attrs("out", e.get("out")))
s = span(sid, parent, f"{_prefix()}{fn}", now, now, attrs,
error=bool(e.get("error")))
s["_svc"] = _service()
spans.append(s)
continue
# every other event = one span (§9-bis: engine step / evidence
# append / state). kg.snapshot keeps only the counts (size law).
if "kg" in extra and isinstance(extra["kg"], dict):
kg = extra.pop("kg")
extra["kg"] = {k: kg.get(k) for k in ("n_edges", "n_live",
"n_conflicts")}
spans.append(span(sid, parent, f"{_prefix()}{ev}", now, now,
_attrs(**extra)))
spans[-1]["_svc"] = _service()
close_block()
# strip the exporter's internal keys; group spans by service
all_spans = []
for s in spans:
all_spans.append(s)
# root: the run itself — the honest envelope of every span inside it
t_start = min(int(s["startTimeUnixNano"]) for s in all_spans) if all_spans else 0
t_end = max(int(s["endTimeUnixNano"]) for s in all_spans) if all_spans else 0
root = span(root_id, "", (question[:120] or "floop.run"),
t_start, t_end, root_attrs)
by_svc: dict[str, list[dict]] = {"floop": [root]}
for s in all_spans:
by_svc.setdefault(s.get("_svc") or "floop", []).append(s)
for s in all_spans: # final strip AFTER grouping by service
for k in ("_svc", "_comp", "_expert", "_call_id"):
s.pop(k, None)
payload = {"resourceSpans": [
{"resource": {"attributes": [
{"key": "service.name", "value": {"stringValue": svc}},
{"key": "service.version", "value": {"stringValue": "0.1"}}]},
"scopeSpans": [{"spans": group}]}
for svc, group in by_svc.items()]}
return payload, trace_id
def _post_json(url: str, body: bytes) -> int:
req = urllib.request.Request(url, data=body, method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.status
def push(run_dir: str | Path, url: str = DEFAULT_URL) -> str:
payload, trace_id = build_payload(run_dir, load_events(run_dir))
status = _post_json(url, json.dumps(payload).encode())
if status != 200:
raise RuntimeError(f"OTLP endpoint answered {status}")
return trace_id
def _latest(n: int) -> list[Path]:
runs = Path("runs")
out = []
for d in sorted(runs.iterdir(), reverse=True):
if (d / "events.jsonl").exists() \
and (d / "events.jsonl").stat().st_size > 0:
out.append(d)
if len(out) >= n:
break
if not out:
print("no run dir with a non-empty events.jsonl under runs/",
file=sys.stderr)
raise SystemExit(1)
return out
def main(argv: list[str]) -> int:
url = os.environ.get("FLOOP_OTLP_URL", DEFAULT_URL)
dry, dirs = False, []
i = 1
while i < len(argv):
a = argv[i]
if a == "--url":
i += 1
url = argv[i]
elif a == "--dry":
dry = True
elif a == "--latest":
n = int(argv[i + 1]) if i + 1 < len(argv) and \
argv[i + 1].isdigit() else 3
i += 1
dirs.extend(_latest(n))
else:
dirs.append(Path(a))
i += 1
if not dirs:
print("usage: python -m floop.traces <run_dir>... | --latest [N]"
" [--url URL] [--dry]", file=sys.stderr)
return 2
for d in dirs:
payload, trace_id = build_payload(d, load_events(d))
n = sum(len(rs["scopeSpans"][0]["spans"])
for rs in payload["resourceSpans"])
svcs = ", ".join(sorted(
rs["resource"]["attributes"][0]["value"]["stringValue"]
for rs in payload["resourceSpans"]))
print(f"{d.name}: {n} spans [{svcs}], trace {trace_id}")
if dry:
continue
status = _post_json(url, json.dumps(payload).encode())
print(f" pushed -> {status} {DEFAULT_UI}/trace/{trace_id}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+139 -3
View File
@@ -164,6 +164,10 @@ 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 extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
# outputs) | "single" (legacy one-call typed # outputs) | "single" (legacy one-call typed
# array — table frags keep using it) # array — table frags keep using it)
@@ -205,6 +209,17 @@ 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;
__new__-built test fakes never define it either)."""
if getattr(self, "streams", None) 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)."""
@@ -231,9 +246,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
@@ -246,6 +265,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
@@ -283,6 +305,10 @@ class KnowledgeExpert:
ordered = self.store.list_is_ordered(set_name) ordered = self.store.list_is_ordered(set_name)
members = self.store.list_members(set_name, ordered=ordered) members = self.store.list_members(set_name, ordered=ordered)
quote, url = self.store.set_provenance(set_name) quote, url = self.store.set_provenance(set_name)
self._rec("fn.done", fn="serve_set",
in_={"set": set_name, "question": question},
out_={"members": members[:50], "count": len(members),
"ranked": ordered})
self._log(f"kg set hit: {set_name} ({len(members)} members" self._log(f"kg set hit: {set_name} ({len(members)} members"
f"{', ranked' if ordered else ', unordered'})", think=True) f"{', ranked' if ordered else ', unordered'})", think=True)
return {"value": str(len(members)), "list_items": members, return {"value": str(len(members)), "list_items": members,
@@ -331,14 +357,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 = ""
@@ -374,8 +406,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:
@@ -458,6 +529,10 @@ class KnowledgeExpert:
# question-blind extractor transcribes facts about THESE. # question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries( queries, entity_terms = compose_queries(
question, evidence_entities=ev_entities, list_mode=list_mode) question, evidence_entities=ev_entities, list_mode=list_mode)
self._rec("fn.done", fn="compose",
in_={"question": question, "evidence_entities": ev_entities,
"list_mode": list_mode},
out_={"queries": queries, "entities": entity_terms})
self._extract_entities = list(dict.fromkeys( self._extract_entities = list(dict.fromkeys(
e for e in (entity_terms + sorted(_proper_nouns(question))) if e)) e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}", self._log(f"compose -> queries {queries} entities {entity_terms}",
@@ -481,6 +556,9 @@ class KnowledgeExpert:
for query in queries: for query in queries:
found = self.client.search(query, limit=self.cfg.max_search_results) found = self.client.search(query, limit=self.cfg.max_search_results)
per_query.append(found) per_query.append(found)
self._rec("fn.done", fn="search",
in_={"query": query, "limit": self.cfg.max_search_results},
out_={"titles": found})
self._log(f"wiki search ({query!r}): {found}", think=True) self._log(f"wiki search ({query!r}): {found}", think=True)
for title in found: for title in found:
if title not in seen_titles: if title not in seen_titles:
@@ -506,6 +584,8 @@ class KnowledgeExpert:
for title in ordered[: self.cfg.max_articles]: for title in ordered[: self.cfg.max_articles]:
if title in self._seen_pages: if title in self._seen_pages:
page = self._seen_pages[title] page = self._seen_pages[title]
self._rec("fn.done", fn="fetch", in_={"title": title},
out_={"cached": True})
self._log(f"seen-index hit: {title} (already fetched this run)", self._log(f"seen-index hit: {title} (already fetched this run)",
think=True) think=True)
else: else:
@@ -515,12 +595,22 @@ class KnowledgeExpert:
self._log(f"fetch failed: {title}: {e}") self._log(f"fetch failed: {title}: {e}")
continue continue
self._seen_pages[title] = page self._seen_pages[title] = page
self._rec("fn.done", fn="fetch", in_={"title": title},
out_={"url": page.url, "chars": len(page.text),
"tables": len(page.tables)})
pages.append(page) pages.append(page)
# SKIM (PR-1): the structural read, in passing — question AND goal # SKIM (PR-1): the structural read, in passing — question AND goal
# oriented; surfaces + signals, zero LLM. The sheet drives chunk # oriented; surfaces + signals, zero LLM. The sheet drives chunk
# ranking in _process_page; PR-2's harvest runs on its signals. # ranking in _process_page; PR-2's harvest runs on its signals.
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms, sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
evidence_entities=ev_entities) evidence_entities=ev_entities)
self._rec("fn.done", fn="skim",
in_={"title": page.title, "question_terms": kws,
"goal_terms": goal_terms},
out_={"tables": len(sheet.tables),
"infobox_quantities": len(sheet.infobox_quantities),
"link_candidates": len(sheet.link_candidates),
"notice": sheet.notice()[:200]})
self._log(f"skim {page.title}: {len(sheet.tables)} tables, " self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
f"{len(sheet.infobox_quantities)} infobox quantities, " f"{len(sheet.infobox_quantities)} infobox quantities, "
f"{len(sheet.link_candidates)} link candidates", think=True) f"{len(sheet.link_candidates)} link candidates", think=True)
@@ -885,6 +975,11 @@ class KnowledgeExpert:
# table (the extract text is the article prose; tables are separate). # table (the extract text is the article prose; tables are separate).
# One bounded call; failure = honest 'no corroboration', never a loop. # One bounded call; failure = honest 'no corroboration', never a loop.
verify = self._verify_count(set_name, len(items), page.text, charge_llm) verify = self._verify_count(set_name, len(items), page.text, charge_llm)
self._rec("fn.done", fn="list_ingest",
in_={"title": page.title, "table": idx, "set": set_name,
"rows": table.total_rows},
out_={"members": items[:50], "count": len(items),
"verified": bool(verify)})
coverage = {"source": page.title, "table": idx, coverage = {"source": page.title, "table": idx,
"rows_total": table.total_rows, "rows_total": table.total_rows,
"rows_ingested": len(members), "rows_ingested": len(members),
@@ -1024,6 +1119,10 @@ class KnowledgeExpert:
merged = self._ingest_scalar_table(page, t, ent_i, val_i) merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged: if merged:
harvested += 1 harvested += 1
self._rec("fn.done", fn="harvest",
in_={"title": page.title, "table": t.idx,
"column": t.header[val_i] if val_i < len(t.header) else "value"},
out_={"merged": merged})
return harvested return harvested
def _promote_leads(self, evidence: str, charge_llm) -> int: def _promote_leads(self, evidence: str, charge_llm) -> int:
@@ -1085,6 +1184,10 @@ class KnowledgeExpert:
continue continue
merged = self._ingest_scalar_table(page, t, ent_i, val_i) merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged: if merged:
self._rec("fn.done", fn="promote",
in_={"title": page.title, "table": d.table_index,
"column": col},
out_={"merged": merged, "refused": False})
self._log(f"skim promote: {merged} rows of table {d.table_index} " self._log(f"skim promote: {merged} rows of table {d.table_index} "
f"({page.title}) ingested (LLM-proposed)", think=True) f"({page.title}) ingested (LLM-proposed)", think=True)
promoted += 1 promoted += 1
@@ -1123,6 +1226,10 @@ class KnowledgeExpert:
return (sig + 2 * len(find_quantities(c.text)), -c.idx) return (sig + 2 * len(find_quantities(c.text)), -c.idx)
gated.sort(key=rank, reverse=True) gated.sort(key=rank, reverse=True)
capped = gated[: self.cfg.max_chunks_extracted] capped = gated[: self.cfg.max_chunks_extracted]
self._rec("fn.done", fn="chunk_gate",
in_={"title": page.title, "chunks": len(chunks),
"question_terms": kws, "entities": entities},
out_={"gated": len(gated), "extracted": len(capped)})
# ---- TABLE SKIM (research/semantic-kg): decide table relevance # ---- TABLE SKIM (research/semantic-kg): decide table relevance
# BEFORE paying extraction — identity + first rows, one call per # BEFORE paying extraction — identity + first rows, one call per
@@ -1179,8 +1286,18 @@ class KnowledgeExpert:
claims = claims_from(self, entities=ent_str, claims = claims_from(self, entities=ent_str,
heading=chunk.heading_path, heading=chunk.heading_path,
text=chunk.text, charge_llm=charge_llm) text=chunk.text, charge_llm=charge_llm)
for claim in claims[: self.cfg.max_facts_per_chunk]: self._rec("claims.done", page=page.title,
fact = fact_from_claim(self, claim, charge_llm=charge_llm) 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: if fact is None:
continue # honestly declined: no invention continue # honestly declined: no invention
merged, _eid = self._ingest_candidate( merged, _eid = self._ingest_candidate(
@@ -1256,6 +1373,13 @@ 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)
self._rec("fn.done", fn="check",
in_={"subject": cand.get("subject", ""),
"relation": cand.get("relation", ""),
"object": cand.get("object", "")},
out_={"ok": False, "reason": reason})
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,
@@ -1266,6 +1390,11 @@ 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)
self._rec("fn.done", fn="check",
in_={"subject": cand["subject"], "relation": cand["relation"],
"object": cand["object"]},
out_={"ok": True, "merged": True, "eid": eid})
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"])
@@ -1306,10 +1435,17 @@ class KnowledgeExpert:
f"{' | CONFLICT' if r.conflict else ''}" f"{' | CONFLICT' if r.conflict else ''}"
for i, r in enumerate(rows)) for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered) pred = self.answer(question=question, rows=rendered)
return { answer = {
"value": _clean_value(pred.value), "value": _clean_value(pred.value),
"quote": pred.quote.strip(), "quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and pred.quote.strip() "url": next((r.url for r in rows if r.quote and pred.quote.strip()
and r.quote.strip() in pred.quote.strip()), rows[0].url), and r.quote.strip() in pred.quote.strip()), rows[0].url),
"confidence": str(pred.confidence.value), "confidence": str(pred.confidence.value),
} }
self._rec("fn.done", fn="judge",
in_={"question": question,
"rows": [f"K{i}: {r.src} | {r.rel} | {r.dst}"
for i, r in enumerate(rows)][:12]},
out_={"value": answer["value"], "confidence": answer["confidence"],
"quote": answer["quote"][:120]})
return answer
+14 -8
View File
@@ -89,16 +89,22 @@ class ExtractClaims(dspy.Signature):
class TypeClaim(dspy.Signature): class TypeClaim(dspy.Signature):
"""You are the TYPE step of a knowledge machine. Given ONE single claim, """You are the TYPE step of a knowledge machine. Given ONE single claim
type it into the Fact schema: subject entity, relation, object/value, and the TEXT it was extracted from, type the claim into the Fact
the VERBATIM quote from the text that states the claim (the FULL schema: subject entity, relation, object/value, the VERBATIM quote
sentence or table row, copied exactly, at least 10 characters), and copied EXACTLY from the text (the FULL sentence or table row that
the temporal restrictions the text states. All temporal fields are states the claim, at least 10 characters), and the temporal
optional and must be contained in the quote. Only what the claim and restrictions the text states. All temporal fields are optional and
its quote state; no inference.""" 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") 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( fact: Fact | None = dspy.OutputField(
desc="the typed Fact, or null when the claim cannot be typed honestly") 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):
+30 -4
View File
@@ -61,7 +61,7 @@ def test_extract_claims_signature():
def test_type_claim_signature(): def test_type_claim_signature():
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here.""" """Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
fields = set(TypeClaim.__fields__) fields = set(TypeClaim.__fields__)
assert fields == {"claim", "fact"}, 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 f = TypeClaim.model_fields["fact"].annotation
assert "Fact" in str(f), f assert "Fact" in str(f), f
# Fact KEEPS orders (the legacy single-pass path and table frags use # Fact KEEPS orders (the legacy single-pass path and table frags use
@@ -88,7 +88,7 @@ def test_fact_from_claim_types_one_fact():
object="Spain", quote="is a Spanish politician who has been the " object="Spain", quote="is a Spanish politician who has been the "
"prime minister of Spain since 2018", "prime minister of Spain since 2018",
start="2018", end=None, point=None, granularity="year"))) start="2018", end=None, point=None, granularity="year")))
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018") 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 assert f.subject == "Pedro Sanchez" and f.start == "2018", f
print("ok: fact_from_claim returns the typed Fact for one claim") print("ok: fact_from_claim returns the typed Fact for one claim")
@@ -97,14 +97,40 @@ def test_honest_empty():
e = Scripted(claims=Scripted(claims=[])) e = Scripted(claims=Scripted(claims=[]))
assert claims_from(e, entities="", heading="", text="") == [] assert claims_from(e, entities="", heading="", text="") == []
e2 = Scripted(typeclaim=Scripted(fact=None)) e2 = Scripted(typeclaim=Scripted(fact=None))
assert fact_from_claim(e2, claim="") is None assert fact_from_claim(e2, claim="", text="") is None
print("ok: no claims -> no facts; untypeable claim -> None, no invention") 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__": if __name__ == "__main__":
test_extract_claims_signature() test_extract_claims_signature()
test_type_claim_signature() test_type_claim_signature()
test_claims_from_dedupes_exact_repeats()
test_claims_from_runs_pass1() test_claims_from_runs_pass1()
test_fact_from_claim_types_one_fact() test_fact_from_claim_types_one_fact()
test_honest_empty() test_honest_empty()
print("\ntwo_pass_extract: 5/5 ok") print("\ntwo_pass_extract: 6/6 ok")
+30 -18
View File
@@ -15,26 +15,38 @@ from __future__ import annotations
def claims_from(expert, entities: str, heading: str, text: str, def claims_from(expert, entities: str, heading: str, text: str,
charge_llm=None) -> list[str]: charge_llm=None) -> list[str]:
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.""" """Pass 1: the chunk's claims as plain strings, coreferences resolved.
if charge_llm:
charge_llm()
pred = expert.claims(entities=entities, heading=heading, text=text)
out = []
for c in (pred.claims or []):
c = (c or "").strip()
if c:
out.append(c)
return out
The list is made honest by CODE only: exact repeats are dropped
def fact_from_claim(expert, claim: str, charge_llm=None): (live finding 26/10: glm sometimes lists its whole list twice, and
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined). thinking leakage leaks in as list items). Dedup is case- and
whitespace-insensitive; the FIRST occurrence's exact text is kept.
The Fact carries the verbatim quote and any temporal restrictions NO cap, NO semantic filter: completeness beats budget (owner ruling
the text states; the store's containment checks validate everything 26/10) — every unique claim gets its TYPE call.
downstream exactly as before. No orders: no siblings by construction.
""" """
if charge_llm: if charge_llm:
charge_llm() charge_llm()
pred = expert.typeclaim(claim=claim) 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) return getattr(pred, "fact", None)
+10
View File
@@ -143,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")
+220
View File
@@ -0,0 +1,220 @@
"""The traces exporter tests (events.jsonl -> OTel spans).
Law (ARCHITECTURE.md §9-bis): one run = one trace; each LLM call, engine
step and evidence append = one span. The exporter is POST-MORTEM only — it
reads the recorded events and never touches the run itself. These tests
check the structural invariants against synthetic event files: unique
span ids, no orphan children, the root envelope, deterministic trace ids,
child-run blocks nesting, and the owner's 27/10 visibility laws — named
in./out. attributes on fn.done and Signature spans, the prompt file as a
clickable child node, expert names on EXPERT spans (EXPERT knowledge) with
the expert prefix inside (knowledge.search), and one OTel service per
expert. No network: payloads are built, never pushed.
"""
import json
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from floop.traces import build_payload, load_events, _cap, _read_prompt
def _run_dir(events: list[dict], prompts: dict[str, str] | None = None,
name: str = "20261027-000000-test") -> Path:
tmp = Path(tempfile.mkdtemp(prefix=name + "-"))
(tmp / "events.jsonl").write_text(
"\n".join(json.dumps(e) for e in events) + "\n")
if prompts:
(tmp / "prompts").mkdir()
for fn, text in prompts.items():
(tmp / "prompts" / fn).write_text(text)
return tmp
def _services(payload: dict) -> dict[str, list[dict]]:
out = {}
for rs in payload["resourceSpans"]:
svc = rs["resource"]["attributes"][0]["value"]["stringValue"]
out[svc] = rs["scopeSpans"][0]["spans"]
return out
def _check(spans: list[dict], label: str) -> None:
ids = {s["spanId"] for s in spans}
assert len(ids) == len(spans), f"{label}: duplicate span ids"
orphans = [s["name"] for s in spans
if s.get("parentSpanId") and s["parentSpanId"] not in ids]
assert not orphans, f"{label}: orphans {orphans[:3]}"
def _attrs(span: dict) -> dict[str, str]:
return {a["key"]: a["value"]["stringValue"] for a in span["attributes"]}
def test_builds_one_trace_per_run():
tmp = _run_dir([
{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
"event": "comp.start", "comp": "INIT",
"desc": "decompose: What is 2+2?"},
{"seq": 2, "ts": "09:15:22.000", "run_ts": "09:15:21.136",
"event": "llm.done", "stage": "INIT", "call_seq": 1,
"dur_s": 0.7, "file": "prompts/01-INIT.txt", "exception": None},
{"seq": 3, "ts": "09:15:23.000", "run_ts": "09:15:21.136",
"event": "comp.out", "comp": "INIT", "out": "What is 4?"},
{"seq": 4, "ts": "09:15:24.000", "run_ts": "09:15:21.136",
"event": "run.final", "out": "4"},
], prompts={"01-INIT.txt":
"# stage=INIT call_seq=1\n\n[user] What is 2+2?\n\n"
"# RAW RESPONSE (after 0.7s)\n{'text': '[[ ## subquestions ## ]]'}\n"})
payload, _ = build_payload(tmp, load_events(tmp))
svcs = _services(payload)
_check(sum(svcs.values(), []), "single run")
root = svcs["floop"][0]
assert root["name"] == "What is 2+2?" and not root.get("parentSpanId")
assert _attrs(root)["run.answer"] == "4"
# the LLM span keeps its real duration and a prompt child
llm = next(s for s in svcs["floop"] if s["name"] == "llm.INIT")
dur = (int(llm["endTimeUnixNano"]) - int(llm["startTimeUnixNano"])) / 1e9
assert abs(dur - 0.7) < 0.01, dur
child = next(s for s in svcs["floop"]
if s.get("parentSpanId") == llm["spanId"] and s["name"] == "prompt")
pa = _attrs(child)
assert "What is 2+2?" in pa["prompt.text"]
assert "subquestions" in pa["prompt.response"]
print("ok: one run -> one trace, question-named root, prompt child")
def test_trace_id_is_deterministic():
tmp = _run_dir([{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
"event": "run.final", "out": "x"}])
_, t1 = build_payload(tmp, load_events(tmp))
_, t2 = build_payload(tmp, load_events(tmp))
assert t1 == t2 and len(t1) == 32
print("ok: same run -> same trace id (stable UI link)")
def test_child_runs_nest_as_blocks():
events = []
for rts in ("09:15:21.100", "09:15:21.200"): # two child runs, one file
events += [
{"seq": 1, "ts": rts, "run_ts": rts, "event": "comp.start",
"comp": "INIT", "desc": "decompose: child question?"},
{"seq": 2, "ts": rts, "run_ts": rts, "event": "comp.out",
"comp": "INIT", "out": "done"},
]
tmp = _run_dir(events)
payload, _ = build_payload(tmp, load_events(tmp))
svcs = _services(payload)
_check(sum(svcs.values(), []), "child runs")
runs = [s for s in svcs["floop"][1:] if s["name"] == "child question?"]
assert len(runs) == 2, [s["name"] for s in svcs["floop"]]
print("ok: child runs in one file nest as per-run spans, no dups")
def test_clock_only_in_event_order():
tmp = _run_dir([
{"seq": 1, "ts": "23:59:59.500", "run_ts": "23:59:59.1",
"event": "run.final", "out": "a"},
{"seq": 2, "ts": "00:00:01.500", "run_ts": "23:59:59.1",
"event": "run.final", "out": "b"},
], name="20261027-235959-test")
payload, _ = build_payload(tmp, load_events(tmp))
root = _services(payload)["floop"][0]
r0 = int(root["startTimeUnixNano"])
r1 = int(root["endTimeUnixNano"])
assert 0 < (r1 - r0) < 10 * 1_000_000_000, (r1 - r0) # 2s, not +24h
print("ok: midnight crossing handled (clock read in event order only)")
def test_expert_names_prefix_and_services():
"""The owner's 27/10 laws: EXPERT knowledge on the component span; inside
it every span carries the knowledge. prefix; the expert's spans export
under their OWN OTel service; fn.done events carry named in./out.
attributes; Signature events carry in./out. field attributes."""
events = [
{"seq": 1, "ts": "12:00:00.100", "run_ts": "12:00:00.050",
"event": "comp.start", "comp": "INIT", "desc": "decompose: What is X?"},
{"seq": 2, "ts": "12:00:00.400", "run_ts": "12:00:00.050",
"event": "comp.out", "comp": "INIT", "out": "What is X?"},
{"seq": 3, "ts": "12:00:00.500", "run_ts": "12:00:00.050",
"event": "comp.start", "comp": "EXPERT", "desc": "knowledge on Q1",
"expert": "knowledge"},
{"seq": 4, "ts": "12:00:00.600", "run_ts": "12:00:00.050",
"event": "fn.done", "fn": "search",
"in": {"query": "X", "limit": 4},
"out": {"titles": ["X", "X (film)"]}},
{"seq": 5, "ts": "12:00:01.000", "run_ts": "12:00:00.050",
"event": "sig.start", "stage": "EXTRACT", "call_id": "m1",
"in.entities": "X", "in.text": "chunk"},
{"seq": 6, "ts": "12:00:03.300", "run_ts": "12:00:00.050",
"event": "llm.done", "stage": "EXTRACT", "call_seq": 3, "dur_s": 2.3,
"file": "prompts/03-EXTRACT.txt", "exception": None},
{"seq": 7, "ts": "12:00:03.300", "run_ts": "12:00:00.050",
"event": "sig.done", "stage": "EXTRACT", "call_id": "m1",
"out.facts": [{"subject": "X", "relation": "is", "object": "Y"}]},
{"seq": 8, "ts": "12:00:03.400", "run_ts": "12:00:00.050",
"event": "state", "text": "merged"},
{"seq": 9, "ts": "12:00:03.500", "run_ts": "12:00:00.050",
"event": "comp.out", "comp": "EXPERT", "out": "Q1 -> ANSWER value=Y"},
]
tmp = _run_dir(events, prompts={
"03-EXTRACT.txt": "# stage=EXTRACT call_seq=3\n\n[user] Extract\n\n"
"# RAW RESPONSE (after 2.3s)\n{'text': 'facts'}\n"})
payload, _ = build_payload(tmp, load_events(tmp))
svcs = _services(payload)
assert "knowledge" in svcs, list(svcs)
_check(sum(svcs.values(), []), "expert run")
fp_names = [s["name"] for s in svcs["floop"]]
kn_names = [s["name"] for s in svcs["knowledge"]]
assert "EXPERT knowledge" in fp_names + kn_names, fp_names + kn_names
assert "knowledge.search" in kn_names, kn_names
assert "knowledge.EXTRACT" in kn_names, kn_names
assert "knowledge.state" in kn_names, kn_names
# fn.done named in/out
srch = next(s for s in svcs["knowledge"] if s["name"] == "knowledge.search")
a = _attrs(srch)
assert a["in.query"] == "X" and "X (film)" in a["out.titles"], a
# sig in/out + duration + prompt child
sig = next(s for s in svcs["knowledge"] if s["name"] == "knowledge.EXTRACT")
a = _attrs(sig)
assert a["in.entities"] == "X" and '"subject"' in a["out.facts"], a
assert a["floop.dur_s"] == "2.3"
child = next(s for s in svcs["knowledge"]
if s.get("parentSpanId") == sig["spanId"] and s["name"] == "prompt")
assert "Extract" in _attrs(child)["prompt.text"]
# the state span inside the expert is prefixed too
assert "knowledge.state" in kn_names
print("ok: expert names, knowledge.* prefix, own service, in/out named")
def test_cap_keeps_spans_small():
big = {"k" + str(i): "x" * 100 for i in range(50)}
assert len(_cap(big)) <= 20
deep = _cap({"a": {"b": {"c": {"d": {"e": "x"}}}}})
assert deep != {"a": {"b": {"c": {"d": {"e": "x"}}}}}
assert _cap("y" * 1000) == ("y" * 497 + "…")
print("ok: _cap truncates depth/width/strings (kg snapshot stays small)")
def test_prompt_parser_splits_raw_response():
tmp = _run_dir([], prompts={
"01-INIT.txt": "# stage=INIT call_seq=1\n\n[user] What is 2+2?\n\n"
"# RAW RESPONSE (after 0.7s)\n{'text': '[[ ## a ## ]]'}\n"})
pr = _read_prompt(tmp, "prompts/01-INIT.txt")
assert pr is not None
assert "What is 2+2?" in pr[0] and "# RAW" not in pr[0]
assert pr[1].startswith("{'text'"), repr(pr[1][:30])
print("ok: prompt parser keeps prompt + raw response verbatim")
if __name__ == "__main__":
test_builds_one_trace_per_run()
test_trace_id_is_deterministic()
test_child_runs_nest_as_blocks()
test_clock_only_in_event_order()
test_expert_names_prefix_and_services()
test_cap_keeps_spans_small()
test_prompt_parser_splits_raw_response()
print("\ntraces: 7/7 ok")