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:
@@ -295,6 +295,26 @@ Conventions the exporter keeps:
|
|||||||
and a backwards jump means midnight crossed. The clock is only ever fed in
|
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.
|
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
|
**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
|
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
|
going). Same schema, second consumer — build when a live run is actually observed
|
||||||
|
|||||||
@@ -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
|
**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
|
reverse proxy + LE cert for e.g. jaeger.oniricapps.com; the container is
|
||||||
already reachable at 10.3.14.59:16686 from his server).
|
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.
|
||||||
|
|||||||
@@ -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
|
a run lands on the same trace. Stdlib only; the run itself never touches
|
||||||
the network.
|
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)
|
## Next steps (design order from the docs)
|
||||||
|
|
||||||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||||||
|
|||||||
@@ -60,20 +60,93 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
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._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._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.reasks = 0 # LM calls the budget did not charge
|
||||||
self.meter = None # callable(str stage) -> None; budget charge
|
self.meter = None # callable(str stage) -> None; budget charge
|
||||||
|
|
||||||
# -- dspy plumbing -------------------------------------------------------
|
# -- 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):
|
def on_module_start(self, call_id, instance, inputs):
|
||||||
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||||
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
||||||
self._stack.append(label)
|
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._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):
|
def on_module_end(self, call_id, outputs, exception):
|
||||||
if self._stack:
|
if self._stack:
|
||||||
self._stack.pop()
|
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):
|
def on_lm_start(self, call_id, instance, inputs):
|
||||||
import time
|
import time
|
||||||
|
|||||||
@@ -585,14 +585,16 @@ class FloopRun:
|
|||||||
self.knowledge_engine.charge = self._charge
|
self.knowledge_engine.charge = self._charge
|
||||||
self.knowledge_engine.modules = self.modules
|
self.knowledge_engine.modules = self.modules
|
||||||
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
|
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),
|
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
|
||||||
self.query, self.table, q.answer_type,
|
self.query, self.table, q.answer_type,
|
||||||
streams=self.streams)
|
streams=self.streams)
|
||||||
else:
|
else:
|
||||||
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
||||||
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
|
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),
|
row = engine.run(q.qid, instantiate(q.text, self.table),
|
||||||
self.query, self.table, q.answer_type, streams=self.streams)
|
self.query, self.table, q.answer_type, streams=self.streams)
|
||||||
self.engine_calls += 1
|
self.engine_calls += 1
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ class Recorder:
|
|||||||
payload = dict(fields)
|
payload = dict(fields)
|
||||||
if "in_" in payload:
|
if "in_" in payload:
|
||||||
payload["in"] = payload.pop("in_")
|
payload["in"] = payload.pop("in_")
|
||||||
|
if "out_" in payload:
|
||||||
|
payload["out"] = payload.pop("out_")
|
||||||
self.seq += 1
|
self.seq += 1
|
||||||
line = {
|
line = {
|
||||||
"seq": self.seq,
|
"seq": self.seq,
|
||||||
|
|||||||
+11
-3
@@ -68,10 +68,18 @@ class RunStreams:
|
|||||||
|
|
||||||
# ---- structural events -------------------------------------------------
|
# ---- structural events -------------------------------------------------
|
||||||
|
|
||||||
def call(self, stage: str, description: str, think: str | None = None) -> None:
|
def call(self, stage: str, description: str, think: str | None = None,
|
||||||
"""An LLM call or engine step is starting."""
|
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._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:
|
if think is not None:
|
||||||
self.think_line(f"[{stage}] {think}")
|
self.think_line(f"[{stage}] {think}")
|
||||||
|
|
||||||
|
|||||||
+234
-47
@@ -1,19 +1,27 @@
|
|||||||
"""floop-traces — replay a run's events.jsonl as OpenTelemetry spans.
|
"""floop-traces — replay a run's events.jsonl as OpenTelemetry spans.
|
||||||
|
|
||||||
ARCHITECTURE.md §9-bis, now built: one run = one trace; each LLM call,
|
ARCHITECTURE.md §9-bis, built: one run = one trace; each LLM call, engine
|
||||||
engine step (probe, search, fetch, check, merge) and evidence append = one
|
step (probe, search, fetch, check, merge) and evidence append = one span.
|
||||||
span, carrying the fields the flight recorder already writes. This is the
|
Post-mortem only: it reads runs/<ts>/events.jsonl after the run and pushes
|
||||||
POST-MORTEM half: it reads runs/<ts>/events.jsonl after the run and pushes
|
|
||||||
OTLP/HTTP-JSON to Jaeger (or any OTLP consumer) — the run itself never
|
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
|
touches the network (observability never kills a run).
|
||||||
export stays future work; the schema is identical either way.
|
|
||||||
|
|
||||||
Recursive child runs share the parent's events.jsonl (each child recorder
|
Owner's visibility laws (27/10), what the exporter renders:
|
||||||
has its own run_ts and restarts seq). Each contiguous run_ts block becomes
|
- INPUTS/OUTPUTS NAMED: fn.done events (search, fetch, judge, compose...)
|
||||||
its own span — named by that run's question — so the fractal recursion shows
|
become spans carrying in.<arg> / out.<arg> attributes; LLM calls carry
|
||||||
as nested runs in the waterfall; a block parents to whatever component span
|
the Signature's fields in.<field> / out.<field> (sig.start/sig.done,
|
||||||
is open when it starts (usually the spawning EXPERT), else to the root.
|
emitted by the dspy callback), not just the prompt-file pointer.
|
||||||
Parentage below that is not recorded today — honest limit, not a guess.
|
- 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/):
|
Usage (from code/):
|
||||||
uv run python -m floop.traces runs/<ts>-<slug> # one run (or several)
|
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_URL = "http://10.3.14.59:4318/v1/traces"
|
||||||
DEFAULT_UI = "http://10.3.14.59:16686"
|
DEFAULT_UI = "http://10.3.14.59:16686"
|
||||||
_TZ = ZoneInfo("Europe/Madrid") # event `ts` is local wall time (recorder law)
|
_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]:
|
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}
|
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:
|
class _Clock:
|
||||||
"""Local wall time -> unix nanos. The date comes from the run dir name;
|
"""Local wall time -> unix nanos. The date comes from the run dir name;
|
||||||
a backwards jump in `ts` means midnight crossed (events are monotonic).
|
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]:
|
def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
|
||||||
"""events.jsonl -> (OTLP/JSON payload, trace_id). Deterministic ids: the
|
"""events.jsonl -> (OTLP/JSON payload, trace_id). Deterministic ids: the
|
||||||
same run always maps to the same trace, so re-pushes are idempotent-ish
|
same run always maps to the same trace, so re-pushes land on the same
|
||||||
and the UI link is stable."""
|
trace and the UI link is stable."""
|
||||||
run_dir = Path(run_dir)
|
run_dir = Path(run_dir)
|
||||||
run_key = run_dir.name # <ts>-<slug>: unique, stable
|
run_key = run_dir.name # <ts>-<slug>: unique, stable
|
||||||
trace_id = _hex(f"floop:{run_key}", 32)
|
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()],
|
for k, v in attrs.items()],
|
||||||
"status": {"code": "STATUS_CODE_ERROR"} if error else
|
"status": {"code": "STATUS_CODE_ERROR"} if error else
|
||||||
{"code": "STATUS_CODE_OK"},
|
{"code": "STATUS_CODE_OK"},
|
||||||
|
"_svc": "floop", # internal keys stripped before the payload
|
||||||
}
|
}
|
||||||
if parent_id: # omitted for the root — empty values are rejected
|
if parent_id: # omitted for the root — empty values are rejected
|
||||||
s["parentSpanId"] = parent_id
|
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
|
root_attrs["run.answer"] = answer
|
||||||
|
|
||||||
spans: list[dict] = []
|
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
|
last_nanos = 0
|
||||||
pos = -1 # position in the file — the real identity (seq restarts)
|
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
|
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:
|
def close_block() -> None:
|
||||||
"""Block end: everything the block opened closes honestly (a child
|
"""Block end: everything the block opened closes honestly (a child
|
||||||
run never leaves comps dangling into the next block)."""
|
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)
|
s["endTimeUnixNano"] = str(last_nanos)
|
||||||
spans.append(s)
|
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:
|
for rts, block in blocks:
|
||||||
close_block()
|
close_block()
|
||||||
cur_rts = rts
|
|
||||||
mark = len(stack)
|
mark = len(stack)
|
||||||
parent = stack[-1]["spanId"] if stack else root_id
|
parent = stack[-1]["spanId"] if stack else root_id
|
||||||
if multi: # one span per run: the fractal child, visible as nesting
|
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
|
parent = stack[-1]["spanId"] if stack else root_id
|
||||||
extra = {k: v for k, v in e.items()
|
extra = {k: v for k, v in e.items()
|
||||||
if k not in ("seq", "ts", "run_ts", "event")}
|
if k not in ("seq", "ts", "run_ts", "event")}
|
||||||
|
sid = _hex(f"floop:{run_key}:s{pos}", 16)
|
||||||
|
|
||||||
if ev == "comp.start":
|
if ev == "comp.start":
|
||||||
stack.append(span(_hex(f"floop:{run_key}:s{pos}", 16), parent,
|
expert = e.get("expert")
|
||||||
str(e.get("comp", "COMP")), now, now,
|
name = str(e.get("comp", "COMP"))
|
||||||
_attrs(comp=e.get("comp"),
|
if expert:
|
||||||
desc=e.get("desc"))))
|
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
|
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
|
# search the WHOLE stack: the parent EXPERT that spawned a
|
||||||
# child stays open across block boundaries (its comp.out
|
# child stays open across block boundaries (its comp.out
|
||||||
# arrives in a later block); mark only bounds block cleanup.
|
# arrives in a later block); mark only bounds block cleanup.
|
||||||
for j in range(len(stack) - 1, -1, -1):
|
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 = stack[j]
|
||||||
s["endTimeUnixNano"] = str(now)
|
s["endTimeUnixNano"] = str(now)
|
||||||
s["attributes"].extend(
|
s["attributes"].extend(
|
||||||
@@ -231,44 +318,140 @@ def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
|
|||||||
del stack[j:]
|
del stack[j:]
|
||||||
break
|
break
|
||||||
else: # unpaired comp.out: honest point span, never dropped
|
else: # unpaired comp.out: honest point span, never dropped
|
||||||
spans.append(span(_hex(f"floop:{run_key}:s{pos}", 16),
|
spans.append(span(sid, parent, f"{_prefix()}{e.get('comp', '?')}?",
|
||||||
parent, f"{e.get('comp', '?')}?",
|
|
||||||
now, now, _attrs(**extra)))
|
now, now, _attrs(**extra)))
|
||||||
continue
|
continue
|
||||||
# every other event = one span (§9-bis: LLM call / engine step /
|
|
||||||
# evidence append). llm.done knows its real duration; the rest
|
if ev == "sig.start": # the Signature's inputs, named
|
||||||
# are point spans. kg.snapshot keeps only the counts (size law).
|
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):
|
if "kg" in extra and isinstance(extra["kg"], dict):
|
||||||
kg = extra.pop("kg")
|
kg = extra.pop("kg")
|
||||||
extra["kg"] = {k: kg.get(k) for k in ("n_edges", "n_live",
|
extra["kg"] = {k: kg.get(k) for k in ("n_edges", "n_live",
|
||||||
"n_conflicts")}
|
"n_conflicts")}
|
||||||
name = (f"llm.{e['stage']}" if ev == "llm.done" else ev)
|
spans.append(span(sid, parent, f"{_prefix()}{ev}", now, now,
|
||||||
dur = int(float(e.get("dur_s", 0)) * 1_000_000_000) \
|
_attrs(**extra)))
|
||||||
if ev == "llm.done" else 0
|
spans[-1]["_svc"] = _service()
|
||||||
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()
|
close_block()
|
||||||
|
|
||||||
# root: the run itself — the honest envelope of every span inside it
|
# strip the exporter's internal keys; group spans by service
|
||||||
t_start = min(int(s["startTimeUnixNano"]) for s in spans) if spans else 0
|
all_spans = []
|
||||||
t_end = max(int(s["endTimeUnixNano"]) for s in spans) if spans else 0
|
for s in spans:
|
||||||
spans.insert(0, span(root_id, "", (question[:120] or "floop.run"),
|
all_spans.append(s)
|
||||||
t_start, t_end, root_attrs))
|
|
||||||
|
|
||||||
payload = {"resourceSpans": [{
|
# root: the run itself — the honest envelope of every span inside it
|
||||||
"resource": {"attributes": [
|
t_start = min(int(s["startTimeUnixNano"]) for s in all_spans) if all_spans else 0
|
||||||
{"key": "service.name", "value": {"stringValue": "floop"}},
|
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"}}]},
|
{"key": "service.version", "value": {"stringValue": "0.1"}}]},
|
||||||
"scopeSpans": [{"spans": spans}],
|
"scopeSpans": [{"spans": group}]}
|
||||||
}]}
|
for svc, group in by_svc.items()]}
|
||||||
return payload, trace_id
|
return payload, trace_id
|
||||||
|
|
||||||
|
|
||||||
def _post_json(url: str, body: bytes) -> int:
|
def _post_json(url: str, body: bytes) -> int:
|
||||||
req = urllib.request.Request(url, data=body, method="POST",
|
req = urllib.request.Request(url, data=body, method="POST",
|
||||||
headers={"Content-Type": "application/json"})
|
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
|
return resp.status
|
||||||
|
|
||||||
|
|
||||||
@@ -321,8 +504,12 @@ def main(argv: list[str]) -> int:
|
|||||||
return 2
|
return 2
|
||||||
for d in dirs:
|
for d in dirs:
|
||||||
payload, trace_id = build_payload(d, load_events(d))
|
payload, trace_id = build_payload(d, load_events(d))
|
||||||
n = len(payload["resourceSpans"][0]["scopeSpans"][0]["spans"])
|
n = sum(len(rs["scopeSpans"][0]["spans"])
|
||||||
print(f"{d.name}: {n} spans, trace {trace_id}")
|
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:
|
if dry:
|
||||||
continue
|
continue
|
||||||
status = _post_json(url, json.dumps(payload).encode())
|
status = _post_json(url, json.dumps(payload).encode())
|
||||||
|
|||||||
@@ -212,8 +212,9 @@ class KnowledgeExpert:
|
|||||||
def _rec(self, event: str, **fields) -> None:
|
def _rec(self, event: str, **fields) -> None:
|
||||||
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
||||||
every component, LLM or not, leaves one JSON line. No streams ->
|
every component, LLM or not, leaves one JSON line. No streams ->
|
||||||
silent no-op (the recorder law: observability never breaks a run)."""
|
silent no-op (the recorder law: observability never breaks a run;
|
||||||
if self.streams is not None:
|
__new__-built test fakes never define it either)."""
|
||||||
|
if getattr(self, "streams", None) is not None:
|
||||||
try:
|
try:
|
||||||
self.streams.recorder.emit(event, **fields)
|
self.streams.recorder.emit(event, **fields)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
@@ -304,6 +305,10 @@ class KnowledgeExpert:
|
|||||||
ordered = self.store.list_is_ordered(set_name)
|
ordered = self.store.list_is_ordered(set_name)
|
||||||
members = self.store.list_members(set_name, ordered=ordered)
|
members = self.store.list_members(set_name, ordered=ordered)
|
||||||
quote, url = self.store.set_provenance(set_name)
|
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"
|
self._log(f"kg set hit: {set_name} ({len(members)} members"
|
||||||
f"{', ranked' if ordered else ', unordered'})", think=True)
|
f"{', ranked' if ordered else ', unordered'})", think=True)
|
||||||
return {"value": str(len(members)), "list_items": members,
|
return {"value": str(len(members)), "list_items": members,
|
||||||
@@ -524,6 +529,10 @@ class KnowledgeExpert:
|
|||||||
# question-blind extractor transcribes facts about THESE.
|
# question-blind extractor transcribes facts about THESE.
|
||||||
queries, entity_terms = compose_queries(
|
queries, entity_terms = compose_queries(
|
||||||
question, evidence_entities=ev_entities, list_mode=list_mode)
|
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(
|
self._extract_entities = list(dict.fromkeys(
|
||||||
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
||||||
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
||||||
@@ -547,6 +556,9 @@ class KnowledgeExpert:
|
|||||||
for query in queries:
|
for query in queries:
|
||||||
found = self.client.search(query, limit=self.cfg.max_search_results)
|
found = self.client.search(query, limit=self.cfg.max_search_results)
|
||||||
per_query.append(found)
|
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)
|
self._log(f"wiki search ({query!r}): {found}", think=True)
|
||||||
for title in found:
|
for title in found:
|
||||||
if title not in seen_titles:
|
if title not in seen_titles:
|
||||||
@@ -572,6 +584,8 @@ class KnowledgeExpert:
|
|||||||
for title in ordered[: self.cfg.max_articles]:
|
for title in ordered[: self.cfg.max_articles]:
|
||||||
if title in self._seen_pages:
|
if title in self._seen_pages:
|
||||||
page = self._seen_pages[title]
|
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)",
|
self._log(f"seen-index hit: {title} (already fetched this run)",
|
||||||
think=True)
|
think=True)
|
||||||
else:
|
else:
|
||||||
@@ -581,12 +595,22 @@ class KnowledgeExpert:
|
|||||||
self._log(f"fetch failed: {title}: {e}")
|
self._log(f"fetch failed: {title}: {e}")
|
||||||
continue
|
continue
|
||||||
self._seen_pages[title] = page
|
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)
|
pages.append(page)
|
||||||
# SKIM (PR-1): the structural read, in passing — question AND goal
|
# SKIM (PR-1): the structural read, in passing — question AND goal
|
||||||
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
||||||
# ranking in _process_page; PR-2's harvest runs on its signals.
|
# ranking in _process_page; PR-2's harvest runs on its signals.
|
||||||
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
||||||
evidence_entities=ev_entities)
|
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, "
|
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
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).
|
# table (the extract text is the article prose; tables are separate).
|
||||||
# One bounded call; failure = honest 'no corroboration', never a loop.
|
# One bounded call; failure = honest 'no corroboration', never a loop.
|
||||||
verify = self._verify_count(set_name, len(items), page.text, charge_llm)
|
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,
|
coverage = {"source": page.title, "table": idx,
|
||||||
"rows_total": table.total_rows,
|
"rows_total": table.total_rows,
|
||||||
"rows_ingested": len(members),
|
"rows_ingested": len(members),
|
||||||
@@ -1090,6 +1119,10 @@ class KnowledgeExpert:
|
|||||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||||
if merged:
|
if merged:
|
||||||
harvested += 1
|
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
|
return harvested
|
||||||
|
|
||||||
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
||||||
@@ -1151,6 +1184,10 @@ class KnowledgeExpert:
|
|||||||
continue
|
continue
|
||||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||||
if merged:
|
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} "
|
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
||||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||||
promoted += 1
|
promoted += 1
|
||||||
@@ -1189,6 +1226,10 @@ class KnowledgeExpert:
|
|||||||
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
||||||
gated.sort(key=rank, reverse=True)
|
gated.sort(key=rank, reverse=True)
|
||||||
capped = gated[: self.cfg.max_chunks_extracted]
|
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
|
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
||||||
# BEFORE paying extraction — identity + first rows, one call per
|
# 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._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||||
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
||||||
page=page.title)
|
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
|
return 0, None
|
||||||
doc_id = self.store.add_document(
|
doc_id = self.store.add_document(
|
||||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||||
@@ -1345,6 +1391,10 @@ class KnowledgeExpert:
|
|||||||
t_end=cand["end"] or None)
|
t_end=cand["end"] or None)
|
||||||
self._merged += 1
|
self._merged += 1
|
||||||
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
|
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:
|
if eid is not None:
|
||||||
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
||||||
cand["object"])
|
cand["object"])
|
||||||
@@ -1385,10 +1435,17 @@ class KnowledgeExpert:
|
|||||||
f"{' | CONFLICT' if r.conflict else ''}"
|
f"{' | CONFLICT' if r.conflict else ''}"
|
||||||
for i, r in enumerate(rows))
|
for i, r in enumerate(rows))
|
||||||
pred = self.answer(question=question, rows=rendered)
|
pred = self.answer(question=question, rows=rendered)
|
||||||
return {
|
answer = {
|
||||||
"value": _clean_value(pred.value),
|
"value": _clean_value(pred.value),
|
||||||
"quote": pred.quote.strip(),
|
"quote": pred.quote.strip(),
|
||||||
"url": next((r.url for r in rows if r.quote and 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),
|
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
||||||
"confidence": str(pred.confidence.value),
|
"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
@@ -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
|
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
|
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
|
reads the recorded events and never touches the run itself. These tests
|
||||||
check the structural invariants against synthetic + recorded event files:
|
check the structural invariants against synthetic event files: unique
|
||||||
unique span ids, no orphan children, the root envelope covering every
|
span ids, no orphan children, the root envelope, deterministic trace ids,
|
||||||
span, deterministic trace ids, and the child-run blocks nesting honestly.
|
child-run blocks nesting, and the owner's 27/10 visibility laws — named
|
||||||
No network: payloads are built, never pushed.
|
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 sys
|
||||||
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
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:
|
def _check(spans: list[dict], label: str) -> None:
|
||||||
ids = {s["spanId"] for s in spans}
|
ids = {s["spanId"] for s in spans}
|
||||||
assert len(ids) == len(spans), f"{label}: duplicate span ids"
|
assert len(ids) == len(spans), f"{label}: duplicate span ids"
|
||||||
root = spans[0]
|
orphans = [s["name"] for s in spans
|
||||||
assert not root.get("parentSpanId"), f"{label}: root has a parent"
|
if s.get("parentSpanId") and s["parentSpanId"] not in ids]
|
||||||
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]}"
|
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)]
|
def _attrs(span: dict) -> dict[str, str]:
|
||||||
assert not outside, f"{label}: spans outside root window {outside[:3]}"
|
return {a["key"]: a["value"]["stringValue"] for a in span["attributes"]}
|
||||||
|
|
||||||
|
|
||||||
def test_builds_one_trace_per_run():
|
def test_builds_one_trace_per_run():
|
||||||
import tempfile
|
tmp = _run_dir([
|
||||||
tmp = Path(tempfile.mkdtemp(prefix="floop-traces-"))
|
{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
|
||||||
ev = tmp / "events.jsonl"
|
"event": "comp.start", "comp": "INIT",
|
||||||
ev.write_text(
|
"desc": "decompose: What is 2+2?"},
|
||||||
'{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",'
|
{"seq": 2, "ts": "09:15:22.000", "run_ts": "09:15:21.136",
|
||||||
' "event": "comp.start", "comp": "INIT",'
|
"event": "llm.done", "stage": "INIT", "call_seq": 1,
|
||||||
' "desc": "decompose: What is 2+2?"}\n'
|
"dur_s": 0.7, "file": "prompts/01-INIT.txt", "exception": None},
|
||||||
'{"seq": 2, "ts": "09:15:22.000", "run_ts": "09:15:21.136",'
|
{"seq": 3, "ts": "09:15:23.000", "run_ts": "09:15:21.136",
|
||||||
' "event": "llm.done", "stage": "INIT", "call_seq": 1,'
|
"event": "comp.out", "comp": "INIT", "out": "What is 4?"},
|
||||||
' "dur_s": 0.7, "file": "prompts/01-INIT.txt", "exception": null}\n'
|
{"seq": 4, "ts": "09:15:24.000", "run_ts": "09:15:21.136",
|
||||||
'{"seq": 3, "ts": "09:15:23.000", "run_ts": "09:15:21.136",'
|
"event": "run.final", "out": "4"},
|
||||||
' "event": "comp.out", "comp": "INIT", "out": "What is 4?"}\n'
|
], prompts={"01-INIT.txt":
|
||||||
'{"seq": 4, "ts": "09:15:24.000", "run_ts": "09:15:21.136",'
|
"# stage=INIT call_seq=1\n\n[user] What is 2+2?\n\n"
|
||||||
' "event": "run.final", "out": "4"}\n')
|
"# RAW RESPONSE (after 0.7s)\n{'text': '[[ ## subquestions ## ]]'}\n"})
|
||||||
payload, tid = build_payload(tmp, load_events(tmp))
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
|
svcs = _services(payload)
|
||||||
_check(spans, "single run")
|
_check(sum(svcs.values(), []), "single run")
|
||||||
assert len(spans) == 4, spans # root + INIT + llm.INIT + run.final
|
root = svcs["floop"][0]
|
||||||
assert spans[0]["name"] == "What is 2+2?" # root named by the question
|
assert root["name"] == "What is 2+2?" and not root.get("parentSpanId")
|
||||||
tags = {a["key"]: a["value"]["stringValue"]
|
assert _attrs(root)["run.answer"] == "4"
|
||||||
for a in spans[0]["attributes"]}
|
# the LLM span keeps its real duration and a prompt child
|
||||||
assert tags["run.answer"] == "4"
|
llm = next(s for s in svcs["floop"] if s["name"] == "llm.INIT")
|
||||||
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
|
dur = (int(llm["endTimeUnixNano"]) - int(llm["startTimeUnixNano"])) / 1e9
|
||||||
assert abs(dur - 0.7) < 0.01, dur
|
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():
|
def test_trace_id_is_deterministic():
|
||||||
import tempfile
|
tmp = _run_dir([{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
|
||||||
tmp = Path(tempfile.mkdtemp(prefix="floop-traces-"))
|
"event": "run.final", "out": "x"}])
|
||||||
(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))
|
_, t1 = build_payload(tmp, load_events(tmp))
|
||||||
_, t2 = build_payload(tmp, load_events(tmp))
|
_, t2 = build_payload(tmp, load_events(tmp))
|
||||||
assert t1 == t2 and len(t1) == 32
|
assert t1 == t2 and len(t1) == 32
|
||||||
@@ -75,58 +96,125 @@ def test_trace_id_is_deterministic():
|
|||||||
|
|
||||||
|
|
||||||
def test_child_runs_nest_as_blocks():
|
def test_child_runs_nest_as_blocks():
|
||||||
import json
|
events = []
|
||||||
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
|
for rts in ("09:15:21.100", "09:15:21.200"): # two child runs, one file
|
||||||
lines += [
|
events += [
|
||||||
json.dumps({"seq": 1, "ts": rts, "run_ts": rts,
|
{"seq": 1, "ts": rts, "run_ts": rts, "event": "comp.start",
|
||||||
"event": "comp.start", "comp": "INIT",
|
"comp": "INIT", "desc": "decompose: child question?"},
|
||||||
"desc": "decompose: child question?"}),
|
{"seq": 2, "ts": rts, "run_ts": rts, "event": "comp.out",
|
||||||
json.dumps({"seq": 2, "ts": rts, "run_ts": rts,
|
"comp": "INIT", "out": "done"},
|
||||||
"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))
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
|
svcs = _services(payload)
|
||||||
_check(spans, "child runs")
|
_check(sum(svcs.values(), []), "child runs")
|
||||||
runs = [s for s in spans[1:] if s["name"] == "child question?"]
|
runs = [s for s in svcs["floop"][1:] if s["name"] == "child question?"]
|
||||||
assert len(runs) == 2, spans # one run-span per block, both shipped
|
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")
|
print("ok: child runs in one file nest as per-run spans, no dups")
|
||||||
|
|
||||||
|
|
||||||
def test_clock_only_in_event_order():
|
def test_clock_only_in_event_order():
|
||||||
import tempfile
|
tmp = _run_dir([
|
||||||
tmp = Path(tempfile.mkdtemp(prefix="20261027-000000-test-"))
|
{"seq": 1, "ts": "23:59:59.500", "run_ts": "23:59:59.1",
|
||||||
lines = (
|
"event": "run.final", "out": "a"},
|
||||||
'{"seq": 1, "ts": "23:59:59.500", "run_ts": "23:59:59.1",'
|
{"seq": 2, "ts": "00:00:01.500", "run_ts": "23:59:59.1",
|
||||||
' "event": "run.final", "out": "a"}\n'
|
"event": "run.final", "out": "b"},
|
||||||
'{"seq": 2, "ts": "00:00:01.500", "run_ts": "23:59:59.1",'
|
], name="20261027-235959-test")
|
||||||
' "event": "run.final", "out": "b"}\n')
|
|
||||||
(tmp / "events.jsonl").write_text(lines)
|
|
||||||
payload, _ = build_payload(tmp, load_events(tmp))
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
spans = payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
|
root = _services(payload)["floop"][0]
|
||||||
r0 = int(spans[0]["startTimeUnixNano"])
|
r0 = int(root["startTimeUnixNano"])
|
||||||
r1 = int(spans[0]["endTimeUnixNano"])
|
r1 = int(root["endTimeUnixNano"])
|
||||||
assert 0 < (r1 - r0) < 10 * 1_000_000_000, (r1 - r0) # 2s, not +24h
|
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)")
|
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():
|
def test_cap_keeps_spans_small():
|
||||||
big = {"k" + str(i): "x" * 100 for i in range(50)}
|
big = {"k" + str(i): "x" * 100 for i in range(50)}
|
||||||
out = _cap(big)
|
assert len(_cap(big)) <= 20
|
||||||
assert len(out) <= 20 # width cap
|
|
||||||
deep = _cap({"a": {"b": {"c": {"d": {"e": "x"}}}}})
|
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 + "…")
|
assert _cap("y" * 1000) == ("y" * 497 + "…")
|
||||||
print("ok: _cap truncates depth/width/strings (kg snapshot stays small)")
|
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__":
|
if __name__ == "__main__":
|
||||||
test_builds_one_trace_per_run()
|
test_builds_one_trace_per_run()
|
||||||
test_trace_id_is_deterministic()
|
test_trace_id_is_deterministic()
|
||||||
test_child_runs_nest_as_blocks()
|
test_child_runs_nest_as_blocks()
|
||||||
test_clock_only_in_event_order()
|
test_clock_only_in_event_order()
|
||||||
|
test_expert_names_prefix_and_services()
|
||||||
test_cap_keeps_spans_small()
|
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