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
10 changed files with 1073 additions and 21 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
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
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
but closed: reading it means tailing files.
**Planned, not built:** export the run as **OpenTelemetry** traces/spans so floop is
observable from the standard tooling that already exists — Jaeger, Grafana Tempo,
any OTLP consumer — instead of floop growing its own dashboards. The mapping is
natural: 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
**BUILT (post-mortem half):** the run exports as **OpenTelemetry** traces/spans
(`floop/traces.py`), so floop is observable from the standard tooling that already
exists — Jaeger (running on the agentvps as a docker container), Grafana Tempo, any
OTLP consumer — instead of floop growing its own dashboards. The mapping is the
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).
The planned `events.jsonl` (machine-readable event stream) becomes the in-process
event bus this exporter reads — one schema, two consumers (offline self-analysis in
META.md, live OTel export). Warnings export as span events first-class, since they are
the self-improvement signal the lessons bank counts.
`events.jsonl` (the flight recorder's machine-readable event stream) is the single
schema with two consumers: offline self-analysis in META.md, and `python -m
floop.traces <run_dir>` replaying it into Jaeger over OTLP/HTTP after the run — the
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
would instrument a moving target.
Conventions the exporter keeps:
- 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
+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
notices to the machine. The lucky same-article case is NOT the design
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/engine.py engine interface + draft stub engines
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/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)
1. Real check layer on expert arrival (well-formedness per expert kind) — the
+73
View File
@@ -60,20 +60,93 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
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.meter = None # callable(str stage) -> None; budget charge
# -- 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):
sig = getattr(getattr(instance, "signature", None), "__name__", None)
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
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._emit_sig_start(call_id, instance, inputs)
def on_module_end(self, call_id, outputs, exception):
if self._stack:
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):
import time
+4 -2
View File
@@ -585,14 +585,16 @@ class FloopRun:
self.knowledge_engine.charge = self._charge
self.knowledge_engine.modules = self.modules
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),
self.query, self.table, q.answer_type,
streams=self.streams)
else:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
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),
self.query, self.table, q.answer_type, streams=self.streams)
self.engine_calls += 1
+2
View File
@@ -58,6 +58,8 @@ class Recorder:
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,
+11 -3
View File
@@ -68,10 +68,18 @@ class RunStreams:
# ---- structural events -------------------------------------------------
def call(self, stage: str, description: str, think: str | None = None) -> None:
"""An LLM call or engine step is starting."""
def call(self, stage: str, description: str, think: str | None = None,
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.recorder.emit("comp.start", comp=stage, desc=description[:200])
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:
self.think_line(f"[{stage}] {think}")
+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))
+61 -4
View File
@@ -212,8 +212,9 @@ class KnowledgeExpert:
def _rec(self, event: str, **fields) -> None:
"""Flight-recorder event (post-mortem debugging, owner 26/10):
every component, LLM or not, leaves one JSON line. No streams ->
silent no-op (the recorder law: observability never breaks a run)."""
if self.streams is not None:
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
@@ -304,6 +305,10 @@ class KnowledgeExpert:
ordered = self.store.list_is_ordered(set_name)
members = self.store.list_members(set_name, ordered=ordered)
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"
f"{', ranked' if ordered else ', unordered'})", think=True)
return {"value": str(len(members)), "list_items": members,
@@ -524,6 +529,10 @@ class KnowledgeExpert:
# question-blind extractor transcribes facts about THESE.
queries, entity_terms = compose_queries(
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(
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
self._log(f"compose -> queries {queries} entities {entity_terms}",
@@ -547,6 +556,9 @@ class KnowledgeExpert:
for query in queries:
found = self.client.search(query, limit=self.cfg.max_search_results)
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)
for title in found:
if title not in seen_titles:
@@ -572,6 +584,8 @@ class KnowledgeExpert:
for title in ordered[: self.cfg.max_articles]:
if title in self._seen_pages:
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)",
think=True)
else:
@@ -581,12 +595,22 @@ class KnowledgeExpert:
self._log(f"fetch failed: {title}: {e}")
continue
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)
# SKIM (PR-1): the structural read, in passing — question AND goal
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
# ranking in _process_page; PR-2's harvest runs on its signals.
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
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, "
f"{len(sheet.infobox_quantities)} infobox quantities, "
f"{len(sheet.link_candidates)} link candidates", think=True)
@@ -951,6 +975,11 @@ class KnowledgeExpert:
# table (the extract text is the article prose; tables are separate).
# One bounded call; failure = honest 'no corroboration', never a loop.
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,
"rows_total": table.total_rows,
"rows_ingested": len(members),
@@ -1090,6 +1119,10 @@ class KnowledgeExpert:
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
if merged:
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
def _promote_leads(self, evidence: str, charge_llm) -> int:
@@ -1151,6 +1184,10 @@ class KnowledgeExpert:
continue
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
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} "
f"({page.title}) ingested (LLM-proposed)", think=True)
promoted += 1
@@ -1189,6 +1226,10 @@ class KnowledgeExpert:
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
gated.sort(key=rank, reverse=True)
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
# BEFORE paying extraction — identity + first rows, one call per
@@ -1334,6 +1375,11 @@ class KnowledgeExpert:
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
doc_id = self.store.add_document(
url=page.url, title=page.title, fetched_at=page.fetched_at,
@@ -1345,6 +1391,10 @@ class KnowledgeExpert:
t_end=cand["end"] or None)
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:
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
cand["object"])
@@ -1385,10 +1435,17 @@ class KnowledgeExpert:
f"{' | CONFLICT' if r.conflict else ''}"
for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered)
return {
answer = {
"value": _clean_value(pred.value),
"quote": 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),
"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
+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")