Перейти к основному содержимому

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.

Стратегии:

  1. metadata-only by default;
  2. field-level allow-list/redaction;
  3. hashed/stable IDs;
  4. sampled encrypted payload в отдельном restricted store;
  5. short retention и access audit;
  6. 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:

EventSpan/metric projection
model_decisionmodel span + token/cost
tool_requested/completedtool span + outcome/duration
approval eventswait duration + decision count
retry eventattempt/error metric
final eventterminal 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 traceMulti-tool production
App logsПросто искатьСлабая causality/aggregationLong asynchronous runs
OTel spans + metricsInteroperabilityInstrumentation/cardinalityTiny prototype
Full content tracingDebug depthPrivacy/cost/riskPHI/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?