"""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")