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:
+164
-76
@@ -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")
|
||||
Reference in New Issue
Block a user