This dossier reverse-engineers Langfuse v3.177.1 from the actual source at /Users/julien/Documents/Repos/langfuse — backend, frontend, Postgres + ClickHouse schemas, queue/worker, OpenTelemetry, ingestion, reconstruction, infra. Every Part 1 claim cites a file:line.
flowchart TB
subgraph PROD["🔁 生产环 (online,每个 run 都跑)"]
A["📥 生产 trace<br/>OTLP / OpenInference"] --> B["🗄️ events span table<br/>ClickHouse + agent 一等列"]
B --> C["🎯 失败检测<br/>结构检查 + LLM judge"]
C --> D["🔢 失败聚类<br/>结构签名 + 语义 embedding"]
D --> E["📋 Candidate EvaluationCase<br/>自动起草,人工确认"]
end
subgraph COLD["🧊 冷存储(定义与字节)"]
F[("📦 Postgres<br/>EvaluationCase 定义<br/>AgentVersion 绑定")]
G[("🗃️ S3 / MinIO<br/>fixtures + reference<br/>immutable blobs")]
end
subgraph CI["🚦 CI 环 (per PR)"]
H["🔀 PR 改动 prompt/model/tool/graph<br/>→ 新 AgentVersion (config_hash)"]
H --> I["⚙️ tracely gate<br/>hermetic record-replay"]
J["📚 EvaluationSuite"] --> I
K[("🗄️ recorded fixtures")] --> I
I --> L{"PASS / FAIL /<br/>INCOMPLETE / SKIP"}
L --> M["💬 PR comment<br/>逐 case delta + firstFailingStepId"]
end
E --> F
E --> G
F --> J
G --> K
L -->|green| N["🚀 AgentVersion 可部署"]
N -.新 trace.-> A
L -->|red| O["🔔 告警流<br/>Slack / email / webhook / LLM step"]
style A fill:#C7CEEA,stroke:#8A93C4,color:#333
style B fill:#E8D5F5,stroke:#A98BC4,color:#333
style C fill:#FFDAB9,stroke:#C49A6C,color:#333
style D fill:#FFDAB9,stroke:#C49A6C,color:#333
style E fill:#FFF9C4,stroke:#C4B95A,color:#333
style F fill:#F5F5F5,stroke:#A0A0A0,color:#333
style G fill:#F5F5F5,stroke:#A0A0A0,color:#333
style H fill:#C7CEEA,stroke:#8A93C4,color:#333
style I fill:#FFB3C6,stroke:#C4889B,color:#333
style J fill:#B5EAD7,stroke:#7FBFA3,color:#333
style K fill:#F5F5F5,stroke:#A0A0A0,color:#333
style L fill:#FFF9C4,stroke:#C4B95A,color:#333
style M fill:#B5EAD7,stroke:#7FBFA3,color:#333
style N fill:#B5EAD7,stroke:#7FBFA3,color:#333
style O fill:#FFB3C6,stroke:#C4889B,color:#333
defsplit_errors(traj): """(tool_errors, run_errors): erroring TOOL steps(被回放的环境) vs agent 自己的 erroring steps。""" tool_errs = [st.name for st in traj.steps if st.level == "ERROR"and st.kind == "tool"] run_errs = [st.name for st in traj.steps if st.level == "ERROR"and st.kind != "tool"] return tool_errs, run_errs
def_lookup(obj, key): """`a.b.c` path lookup into a parsed tool input; `@observe` tools record `{kwargs: {...}}` or the bound args directly, so both shapes are tried.""" for root in (obj, (obj or {}).get("kwargs") ifisinstance(obj, dict) elseNone): cur = root for part in key.split("."): ifnotisinstance(cur, dict) or part notin cur: cur = _MISSING break cur = cur[part] if cur isnot _MISSING: return cur return _MISSING
@classmethod defdecode(cls, raw: bytes) -> dict: """An empty or unparsable blob raises `ValueError`: a recording that cannot be read must surface as an execution problem, never as "no calls recorded" (which strict replay would treat as an explicitly empty recording) or as live execution.""" ifnot raw: raise ValueError("fixture bundle is empty") ...
如果 miss 的时候悄悄走真实网络,你的 CI 会在一个 PR 上花真实的钱、调真实的外部服务,然后返回一个不可复现的测试结果——比没有测试更糟。
// design 文档 §3.1 原文 // The shim emits its *own* OTel spans so the replay produces a real Trace // in `events_full` — the run is observable exactly like production.
五、核心机制三:INCOMPLETE —— 第四种判定状态
这是我在整个项目里认为最有工程价值的设计,也是 Tracely 和绝大多数 CI gate 的分水岭。
5.1 绝大多数工具的隐含假设
几乎所有 LLM CI gate 的判定逻辑都长这样:
1
passed = all(check.passed for check in checks) # 没人检查过 check 是否真的跑了
这个写法有一个致命漏洞:当某个检查因为环境问题没能跑起来时,它被算成了”通过”。
具体场景:你的 case 要求两个 judge——一个 tool_routing(结构判定,不需要 LLM),一个 honest_report(LLM judge,需要 API key)。某天 workspace 的人把 key 删了,或者 judge 被 disable 了:
PASS, FAIL, INCOMPLETE, SKIP, UNAVAILABLE = "PASS", "FAIL", "INCOMPLETE", "SKIP", "UNAVAILABLE" # Bumped when the aggregation rules below change, so a stored result says which policy made it. POLICY = "required-checks/v1"
# The gate statuses, worst last. NO_COVERAGE (suite exercised nothing) and # INCOMPLETE (a case could not be fully checked) both block; FAIL names an actual regression. GATE_SEVERITY = {"PASS": 0, "NO_COVERAGE": 1, "INCOMPLETE": 2, "FAIL": 3}
defaggregate(checks: list[Check], execution: Execution) -> str: """Order matters: a behavioural FAIL outranks an execution problem so the two stay distinguishable even when both block; an unavailable REQUIRED check can never be read as a pass; advisory checks never decide.""" required = [c for c in checks if c.required] ifany(c.status == FAIL for c in required): return FAIL ifnot execution.complete orany(c.status == UNAVAILABLE for c in required): return INCOMPLETE return PASS
还有一层:Tracely 把 judge 身份和配置也存下来(judges 参数),注释写着 “stored beside the result so a historical verdict stays explainable after the evaluator changes”。半年后你想复盘一条三个月前的判定,能知道当时用的是哪个 judge、什么 prompt、什么模型——否则”为什么这条 case 当时判 FAIL”永远查不清。
六、Flakiness:为什么它其实不是问题
一个合理的质疑:LLM 输出有随机性,轨迹比对肯定会 flaky。
Tracely 的回答分两层:
第一层:Fully hermetic 的 case 按构造就无 flaky。 因为 LLM 输出也被录下来了。你重放的不是”模型会怎么回答”,而是”模型当时回答了什么”。
第二层:只有 Tool-hermetic 和 LIVE 模式才会引入 flaky。 对应的三个缓解手段:
defcall(self, kind: str, name: str, args: Any) -> Any: q = self._queues.get(canonical_hash(kind, name, args)) ifnot q: self.misses.append(f"{kind}:{name}") raise KeyError(f"no fixture for {kind}:{name} — fixture missing is an " "execution problem, never a silent live call") entry = q.pop(0) # per-key 队列:同 args 的第 N 次调用拿第 N 个 fixture self.served.append(name) if entry.error: raise RuntimeError(f"replay error: recorded {name} failed: {entry.error}") return entry.output
deftool_sequence(traj): return [s.name for s in traj.steps if s.kind == "tool"] deffailed_tool_sequence(traj): """执行过但报错的工具名。真实 trace 的 bug 几乎都在这里,而不是「少调了一个工具」。""" return [s.name for s in traj.steps if s.kind == "tool"and s.level == "ERROR"]
defsplit_errors(traj): """工具错误(被回放的环境)vs agent 自身 run 错误 —— 让「修好了错误处理」也能 PASS。""" tool_errs = failed_tool_sequence(traj) run_errs = [s.name for s in traj.steps if s.level == "ERROR"and s.kind != "tool"] return tool_errs, run_errs
deftools_satisfied(mode, produced, reference): missing = [t for t in reference if t notin produced] extra = [t for t in produced if t notin reference] if mode == "strict": ok = produced == reference elif mode == "unordered": ok = sorted(produced) == sorted(reference) elif mode == "subset": ok = len(extra) == 0 else: ok = len(missing) == 0# superset return ok, missing, extra
_MISSING = object()
def_lookup(obj, key): """`a.b.c` 路径查找,兼容 {kwargs: {...}} 与直接绑参两种录制形状。""" for root in (obj, (obj or {}).get("kwargs") ifisinstance(obj, dict) elseNone): cur, ok = root, True for part in key.split("."): ifnotisinstance(cur, dict) or part notin cur: ok = False break cur = cur[part] if ok: return cur return _MISSING
defcheck_tool_args(predicates, traj): violations = [] for p in predicates or []: tool, key = str(p.get("tool") or""), str(p.get("key") or"") ifnot tool ornot key: continue for s in traj.steps: if s.kind != "tool"or s.name != tool: continue raw = s.input ifisinstance(raw, str): try: raw = json.loads(raw) except (ValueError, TypeError): pass got = _lookup(raw, key) if got is _MISSING: violations.append(f"{tool}: argument '{key}' missing") elif got != p.get("equals"): violations.append(f"{tool}: '{key}' was {got!r}, expected {p.get('equals')!r}") return violations
forbidden = [t for t in assertions.get("forbidden_tools") or [] if t in produced] over = [f"{t}: called {produced.count(t)}x, max {n}" for t, n in (assertions.get("max_tool_calls") or {}).items() ifisinstance(n, int) and produced.count(t) > n] arg_violations = check_tool_args(assertions.get("tool_args") or [], traj)
defaggregate(checks, execution): """顺序很重要:行为 FAIL 压过执行问题,两者保持可区分; required 检查的 UNAVAILABLE 绝不能被读成 PASS。""" required = [c for c in checks if c.required] ifany(c.status == FAIL for c in required): return FAIL ifnot execution.complete orany(c.status == UNAVAILABLE for c in required): return INCOMPLETE return PASS
defevaluate_contract(assertions, match_mode, traj, *, quality=None, quality_blocks=True, execution=None): execution = execution or Execution() _s, detail = evaluate_assertions(assertions, match_mode, traj) checks = [] ifnot execution.complete: why = f"not evaluated: {execution.problem}" checks.append(Check("tools", True, UNAVAILABLE, why)) if assertions.get("no_error", True): checks.append(Check("no_error", True, UNAVAILABLE, why)) else: reason = "" if detail["missing_tools"]: reason = "missing tools: " + ", ".join(detail["missing_tools"]) elifnot detail["tools_ok"]: reason = f"tool sequence mismatch (mode={detail['match_mode']})" checks.append(Check("tools", True, PASS if detail["tools_ok"] else FAIL, reason)) if assertions.get("no_error", True): er = ("run failed: " + ", ".join(detail["run_errors"])) if detail["run_errors"] \ else (""if detail["error_ok"] else"tool errors: " + ", ".join(detail["tool_errors"])) checks.append(Check("no_error", True, PASS if detail["error_ok"] else FAIL, er)) if assertions.get("forbidden_tools"): hit = detail.get("forbidden_hit") or [] checks.append(Check("forbidden_tools", True, FAIL if hit else PASS, ("called: " + ", ".join(hit)) if hit else"")) if assertions.get("max_tool_calls"): over = detail.get("count_violations") or [] checks.append(Check("call_counts", True, FAIL if over else PASS, "; ".join(over))) if assertions.get("tool_args"): bad = detail.get("arg_violations") or [] checks.append(Check("tool_args", True, FAIL if bad else PASS, "; ".join(bad)))
expected = list(((assertions.get("quality") or {}).get("score_names")) or []) got = {q.get("score_name"): q for q in quality or []} for name in expected: q = got.get(name) ifnot execution.complete: checks.append(Check(f"quality:{name}", quality_blocks, UNAVAILABLE, f"not evaluated: {execution.problem}")) elif q isNone: checks.append(Check(f"quality:{name}", quality_blocks, UNAVAILABLE, "judge returned no result (no LLM key, judge disabled or errored)")) elif q.get("verdict") == FAIL: checks.append(Check(f"quality:{name}", quality_blocks, FAIL, str(q.get("comment") or""))) elif q.get("verdict") == PASS: checks.append(Check(f"quality:{name}", quality_blocks, PASS, str(q.get("comment") or""))) else: checks.append(Check(f"quality:{name}", quality_blocks, UNAVAILABLE, "judge gave no verdict"))
Every eval tool asks you to hand-author a dataset: sit down, invent questions, write ideal answers, keep them current as the product changes. That dataset is a guess about what might break. Production already handed you the real thing.