Observability
После главы вы сможете построить telemetry, которая отвечает «что медленно/дорого/сломалось», не превращая tracing backend в recovery database и склад sensitive prompts.
Четыре разных объекта
| Объект | Вопрос | Пример |
|---|---|---|
| Domain/run event | Что произошло и как восстановиться? | tool_completed(op-1) |
| Log | Что разработчику нужно прочитать? | timeout class + endpoint |
| Metric | Как система ведёт себя в агрегате? | p95 latency, tool error rate |
| Trace/span | Где прошли время и причинные вызовы? | run → model → tool → policy |
Удаление trace не должно ломать resume. Удаление authoritative event без backup — должно считаться потерей state/audit.
Span tree
Учебный tracer использует общий traceId = runId, отдельные span IDs, kind/name/outcome, duration, nullable cost и attributes.
Correlation vocabulary
Минимум:
trace_id— одна causal execution;run_id— durable run;thread_id/turn_id— conversation scope;step— model decision index;operation_id— idempotent effect;tool_call_id— связь request/result;tenant_id— только в безопасной нормализованной форме;- model/prompt/tool/policy versions.
Не используйте email или PHI как ID. Stable pseudonymous identifier лучше raw identity.
Что измерять
Latency
- queue wait;
- context/retrieval;
- time to first token и full model response;
- policy/approval wait отдельно от compute;
- tool connect/server time;
- total run wall time.
Cost/usage
- input/output/reasoning tokens, если provider сообщает;
- model/tool cost;
- cache hit;
- retry amplification;
- cost per successful domain outcome, не только per call.
Reliability
- terminal reasons;
- typed tool failures;
- approval/rejection rate;
- retry exhausted;
- stale observation rate;
- resume/crash count;
- outcome/eval pass rate.
Content privacy
Prompts, tool args/results и retrieved documents могут содержать secrets/PII/PHI. Полный content не должен автоматически попадать в spans.
Стратегии:
- metadata-only by default;
- field-level allow-list/redaction;
- hashed/stable IDs;
- sampled encrypted payload в отдельном restricted store;
- short retention и access audit;
- synthetic eval fixtures для CI.
Redaction после export может быть поздней: collector и network уже увидели content.
High cardinality
run_id полезен для trace lookup, но плох как metric label. Metrics используют bounded dimensions: model version, tool name, terminal reason, error class, environment. Raw user/tool arguments не подходят label’ам.
Events и traces не должны расходиться
Используйте одну vocabulary:
| Event | Span/metric projection |
|---|---|
model_decision | model span + token/cost |
tool_requested/completed | tool span + outcome/duration |
| approval events | wait duration + decision count |
| retry event | attempt/error metric |
| final event | terminal reason + end-to-end duration |
Trace добавляет timing и causal parentage. Event добавляет recovery semantics. Если telemetry говорит tool success, а event outcome failure, это instrumentation defect.
Replay
Есть два разных replay:
- State replay: pure reducer восстанавливает projection из events; модель/tools не вызываются.
- Eval replay: historical input/fixture запускается через новую версию runtime/model; внешние writes заменяются sandbox/stubs.
Никогда не replay production side effects ради диагностики.
OpenTelemetry status
По состоянию на 2026-08-30 OpenTelemetry GenAI agent/framework semantic conventions находятся в статусе Development и вынесены в отдельный semantic-conventions-genai repository. Они описывают операции вроде invoke_agent, plan, execute_tool, model/retrieval/memory spans. Не замораживайте internal schema на unstable naming без adapter/version.
Primary source: OpenTelemetry GenAI agent spans.
Варианты
| Решение | Выигрыш | Цена | Когда плохо |
|---|---|---|---|
| Provider dashboard only | Быстро | Нет domain events/cross-system trace | Multi-tool production |
| App logs | Просто искать | Слабая causality/aggregation | Long asynchronous runs |
| OTel spans + metrics | Interoperability | Instrumentation/cardinality | Tiny prototype |
| Full content tracing | Debug depth | Privacy/cost/risk | PHI/regulated data |
| Metadata + sampled secure payload | Баланс | Две storage policies | Нет доступа к secure ops |
Helios и реальный аналог
Helios видит, что p95 вырос не из-за модели, а из-за approval wait; cost per successful refund отличается от cost per model call. В telehealth voice agent отдельно измеряются turn latency, ASR/model/tool time и escalation outcome, без записи raw transcript в каждый span.
Лаборатория
npm run test:course:pattern -- "projects model, tool, and policy spans"
Тест очищает TraceSink и затем восстанавливает completed run из StateStore. Добавьте failure и проверьте outcome=error, не сохраняя sensitive arguments.
Self-check
- Какой store authoritative для resume?
- Какие IDs связывают model, policy и tool?
- Где content redacted до export?
- Какие labels имеют bounded cardinality?
- Как измеряется approval wait отдельно от compute?
- Версионируется ли unstable OTel mapping через adapter?