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>
This commit is contained in:
2026-10-27 14:27:56 +01:00
co-authored by Claude
parent 6ea769b7d1
commit 1af308ae60
10 changed files with 628 additions and 132 deletions
+20
View File
@@ -295,6 +295,26 @@ Conventions the exporter keeps:
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
+45
View File
@@ -467,3 +467,48 @@ depth 6. Three traces pushed live. ARCHITECTURE §9-bis updated: BUILT
**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.
+14
View File
@@ -97,6 +97,20 @@ 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}")
+234 -47
View File
@@ -1,19 +1,27 @@
"""floop-traces — replay a run's events.jsonl as OpenTelemetry spans.
ARCHITECTURE.md §9-bis, now built: one run = one trace; each LLM call,
engine step (probe, search, fetch, check, merge) and evidence append = one
span, carrying the fields the flight recorder already writes. This is the
POST-MORTEM half: it reads runs/<ts>/events.jsonl after the run and pushes
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). The in-process live
export stays future work; the schema is identical either way.
touches the network (observability never kills a run).
Recursive child runs share the parent's events.jsonl (each child recorder
has its own run_ts and restarts seq). Each contiguous run_ts block becomes
its own span — named by that run's question — so the fractal recursion shows
as nested runs in the waterfall; a block parents to whatever component span
is open when it starts (usually the spawning EXPERT), else to the root.
Parentage below that is not recorded today — honest limit, not a guess.
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)
@@ -38,6 +46,7 @@ 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]:
@@ -83,6 +92,45 @@ 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).
@@ -134,8 +182,8 @@ def _block_question(block: list[dict]) -> str:
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 are idempotent-ish
and the UI link is stable."""
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)
@@ -155,6 +203,7 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
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
@@ -170,12 +219,25 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
root_attrs["run.answer"] = answer
spans: list[dict] = []
stack: list[dict] = [] # open spans, outermost first (components + run spans)
stack: list[dict] = [] # open spans, outermost first (comps + sig + runs)
last_nanos = 0
pos = -1 # position in the file — the real identity (seq restarts)
cur_rts: str | None = None
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)."""
@@ -184,9 +246,24 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
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()
cur_rts = rts
mark = len(stack)
parent = stack[-1]["spanId"] if stack else root_id
if multi: # one span per run: the fractal child, visible as nesting
@@ -205,18 +282,28 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
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":
stack.append(span(_hex(f"floop:{run_key}:s{pos}", 16), parent,
str(e.get("comp", "COMP")), now, now,
_attrs(comp=e.get("comp"),
desc=e.get("desc"))))
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-name comp
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]["name"] == str(e.get("comp", "")):
if stack[j].get("_comp") == str(e.get("comp", "")):
s = stack[j]
s["endTimeUnixNano"] = str(now)
s["attributes"].extend(
@@ -231,44 +318,140 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
del stack[j:]
break
else: # unpaired comp.out: honest point span, never dropped
spans.append(span(_hex(f"floop:{run_key}:s{pos}", 16),
parent, f"{e.get('comp', '?')}?",
spans.append(span(sid, parent, f"{_prefix()}{e.get('comp', '?')}?",
now, now, _attrs(**extra)))
continue
# every other event = one span (§9-bis: LLM call / engine step /
# evidence append). llm.done knows its real duration; the rest
# are point spans. kg.snapshot keeps only the counts (size law).
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")}
name = (f"llm.{e['stage']}" if ev == "llm.done" else ev)
dur = int(float(e.get("dur_s", 0)) * 1_000_000_000) \
if ev == "llm.done" else 0
error = bool(e.get("exception"))
spans.append(span(_hex(f"floop:{run_key}:s{pos}", 16), parent,
name, now - dur, now, _attrs(**extra), error))
spans.append(span(sid, parent, f"{_prefix()}{ev}", now, now,
_attrs(**extra)))
spans[-1]["_svc"] = _service()
close_block()
# root: the run itself — the honest envelope of every span inside it
t_start = min(int(s["startTimeUnixNano"]) for s in spans) if spans else 0
t_end = max(int(s["endTimeUnixNano"]) for s in spans) if spans else 0
spans.insert(0, span(root_id, "", (question[:120] or "floop.run"),
t_start, t_end, root_attrs))
# strip the exporter's internal keys; group spans by service
all_spans = []
for s in spans:
all_spans.append(s)
payload = {"resourceSpans": [{
"resource": {"attributes": [
{"key": "service.name", "value": {"stringValue": "floop"}},
# 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": spans}],
}]}
"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=15) as resp:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.status
@@ -321,8 +504,12 @@ def main(argv: list[str]) -> int:
return 2
for d in dirs:
payload, trace_id = build_payload(d, load_events(d))
n = len(payload["resourceSpans"][0]["scopeSpans"][0]["spans"])
print(f"{d.name}: {n} spans, trace {trace_id}")
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())
+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
+164 -76
View File
@@ -1,73 +1,94 @@
"""The traces exporter tests (events.jsonl -> OTLP spans).
"""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 + recorded event files:
unique span ids, no orphan children, the root envelope covering every
span, deterministic trace ids, and the child-run blocks nesting honestly.
No network: payloads are built, never pushed.
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, _Clock
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"
root = spans[0]
assert not root.get("parentSpanId"), f"{label}: root has a parent"
r0, r1 = int(root["startTimeUnixNano"]), int(root["endTimeUnixNano"])
orphans = [s["name"] for s in spans[1:] if s["parentSpanId"] not in 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]}"
outside = [s["name"] for s in spans[1:]
if not (r0 <= int(s["startTimeUnixNano"])
and int(s["endTimeUnixNano"]) <= r1)]
assert not outside, f"{label}: spans outside root window {outside[: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():
import tempfile
tmp = Path(tempfile.mkdtemp(prefix="floop-traces-"))
ev = tmp / "events.jsonl"
ev.write_text(
'{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",'
' "event": "comp.start", "comp": "INIT",'
' "desc": "decompose: What is 2+2?"}\n'
'{"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": null}\n'
'{"seq": 3, "ts": "09:15:23.000", "run_ts": "09:15:21.136",'
' "event": "comp.out", "comp": "INIT", "out": "What is 4?"}\n'
'{"seq": 4, "ts": "09:15:24.000", "run_ts": "09:15:21.136",'
' "event": "run.final", "out": "4"}\n')
payload, tid = build_payload(tmp, load_events(tmp))
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
_check(spans, "single run")
assert len(spans) == 4, spans # root + INIT + llm.INIT + run.final
assert spans[0]["name"] == "What is 2+2?" # root named by the question
tags = {a["key"]: a["value"]["stringValue"]
for a in spans[0]["attributes"]}
assert tags["run.answer"] == "4"
llm = [s for s in spans if s["name"] == "llm.INIT"][0]
lt = {a["key"]: a["value"]["stringValue"] for a in llm["attributes"]}
assert lt["floop.file"] == "prompts/01-INIT.txt" and lt["floop.dur_s"] == "0.7"
# llm duration is real: end-start = 0.7s
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
print("ok: one run -> one trace, question-named root, real llm duration")
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():
import tempfile
tmp = Path(tempfile.mkdtemp(prefix="floop-traces-"))
(tmp / "events.jsonl").write_text(
'{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",'
' "event": "run.final", "out": "x"}\n')
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
@@ -75,58 +96,125 @@ def test_trace_id_is_deterministic():
def test_child_runs_nest_as_blocks():
import json
import tempfile
tmp = Path(tempfile.mkdtemp(prefix="floop-traces-"))
lines = []
events = []
for rts in ("09:15:21.100", "09:15:21.200"): # two child runs, one file
lines += [
json.dumps({"seq": 1, "ts": rts, "run_ts": rts,
"event": "comp.start", "comp": "INIT",
"desc": "decompose: child question?"}),
json.dumps({"seq": 2, "ts": rts, "run_ts": rts,
"event": "comp.out", "comp": "INIT", "out": "done"}),
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 / "events.jsonl").write_text("\n".join(lines) + "\n")
tmp = _run_dir(events)
payload, _ = build_payload(tmp, load_events(tmp))
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
_check(spans, "child runs")
runs = [s for s in spans[1:] if s["name"] == "child question?"]
assert len(runs) == 2, spans # one run-span per block, both shipped
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():
import tempfile
tmp = Path(tempfile.mkdtemp(prefix="20261027-000000-test-"))
lines = (
'{"seq": 1, "ts": "23:59:59.500", "run_ts": "23:59:59.1",'
' "event": "run.final", "out": "a"}\n'
'{"seq": 2, "ts": "00:00:01.500", "run_ts": "23:59:59.1",'
' "event": "run.final", "out": "b"}\n')
(tmp / "events.jsonl").write_text(lines)
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))
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
r0 = int(spans[0]["startTimeUnixNano"])
r1 = int(spans[0]["endTimeUnixNano"])
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)}
out = _cap(big)
assert len(out) <= 20 # width cap
assert len(_cap(big)) <= 20
deep = _cap({"a": {"b": {"c": {"d": {"e": "x"}}}}})
assert deep != {"a": {"b": {"c": {"d": {"e": "x"}}}}} # depth cap
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()
print("\ntraces: 5/5 ok")
test_prompt_parser_splits_raw_response()
print("\ntraces: 7/7 ok")