From 6ea769b7d19993fbec618bbcb06b2bf3c9598efa Mon Sep 17 00:00:00 2001 From: Onibot Date: Tue, 27 Oct 2026 12:34:44 +0100 Subject: [PATCH] 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/ | --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. --- ARCHITECTURE.md | 42 ++++-- RUNLOG.md | 49 +++++++ code/README.md | 23 +++ code/floop/traces.py | 334 +++++++++++++++++++++++++++++++++++++++++++ code/tests/traces.py | 132 +++++++++++++++++ 5 files changed, 568 insertions(+), 12 deletions(-) create mode 100644 code/floop/traces.py create mode 100644 code/tests/traces.py diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 982bbf0..0a472ce 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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//run.log` (the line-based technical superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the @@ -268,19 +268,37 @@ 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 ` 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. + +**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 diff --git a/RUNLOG.md b/RUNLOG.md index b07d2d2..5cad093 100644 --- a/RUNLOG.md +++ b/RUNLOG.md @@ -418,3 +418,52 @@ 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/` 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). diff --git a/code/README.md b/code/README.md index 4ec4808..779b4d1 100644 --- a/code/README.md +++ b/code/README.md @@ -71,9 +71,32 @@ 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/- # one run -> Jaeger +uv run python -m floop.traces --latest 3 # the newest runs +uv run python -m floop.traces --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. + ## Next steps (design order from the docs) 1. Real check layer on expert arrival (well-formedness per expert kind) — the diff --git a/code/floop/traces.py b/code/floop/traces.py new file mode 100644 index 0000000..c0695d3 --- /dev/null +++ b/code/floop/traces.py @@ -0,0 +1,334 @@ +"""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//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. + +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. + +Usage (from code/): + uv run python -m floop.traces runs/- # one run (or several) + uv run python -m floop.traces --latest 3 # the 3 newest runs + uv run python -m floop.traces --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) + + +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} + + +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 are idempotent-ish + and the UI link is stable.""" + run_dir = Path(run_dir) + run_key = run_dir.name # -: 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"}, + } + 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 (components + run spans) + 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 + + 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) + + 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 + 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")} + 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")))) + continue + if ev == "comp.out": # close the innermost same-name comp + # 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", "")): + 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(_hex(f"floop:{run_key}:s{pos}", 16), + parent, f"{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 "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)) + 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)) + + payload = {"resourceSpans": [{ + "resource": {"attributes": [ + {"key": "service.name", "value": {"stringValue": "floop"}}, + {"key": "service.version", "value": {"stringValue": "0.1"}}]}, + "scopeSpans": [{"spans": spans}], + }]} + 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: + 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 ... | --latest [N]" + " [--url URL] [--dry]", file=sys.stderr) + 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}") + 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)) \ No newline at end of file diff --git a/code/tests/traces.py b/code/tests/traces.py new file mode 100644 index 0000000..1a32115 --- /dev/null +++ b/code/tests/traces.py @@ -0,0 +1,132 @@ +"""The traces exporter tests (events.jsonl -> OTLP 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. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from floop.traces import build_payload, load_events, _cap, _Clock + + +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] + 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 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 + 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") + + +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') + _, 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(): + import json + import tempfile + tmp = Path(tempfile.mkdtemp(prefix="floop-traces-")) + lines = [] + 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"}), + ] + (tmp / "events.jsonl").write_text("\n".join(lines) + "\n") + 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 + 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) + payload, _ = build_payload(tmp, load_events(tmp)) + spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"] + r0 = int(spans[0]["startTimeUnixNano"]) + r1 = int(spans[0]["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_cap_keeps_spans_small(): + big = {"k" + str(i): "x" * 100 for i in range(50)} + out = _cap(big) + assert len(out) <= 20 # width cap + deep = _cap({"a": {"b": {"c": {"d": {"e": "x"}}}}}) + assert deep != {"a": {"b": {"c": {"d": {"e": "x"}}}}} # depth cap + assert _cap("y" * 1000) == ("y" * 497 + "…") + print("ok: _cap truncates depth/width/strings (kg snapshot stays small)") + + +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_cap_keeps_spans_small() + print("\ntraces: 5/5 ok") \ No newline at end of file