fix(observability): address OTel review findings

Adversarial review of the merged OTel instrumentation (#352) surfaced
four issues, all on the enabled path (default-off, so no impact until
tracing is turned on):

- search LLM client was unwrapped, so hybrid/agentic token usage — the
  heaviest LLM spend — never reached Langfuse. Wrap it with
  UsageRecordingClient when observability is enabled, mirroring
  get_llm_client(); graceful keyword-only degradation is preserved.
- set_generation_usage overwrote token counts, undercounting any span
  that wraps more than one chat call (the now-wrapped agentic path).
  Accumulate instead of replacing.
- recall_hit was emitted for uncalibrated methods (unbounded BM25 /
  single-route vector), a near-constant always-hit signal that inflates
  dashboards. Gate hit on calibrated methods (HYBRID/AGENTIC); keyword
  and vector emit only the raw top_score.
- init_tracing / init_score_sink were not idempotent — a re-init without
  an intervening shutdown orphaned the export thread + OTLP socket +
  worker task. Tear down the previous instance first (init_score_sink is
  now async).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
zhanghui
2026-07-24 15:29:54 +08:00
committed by zhanghui
co-authored by Claude Opus 4.8
parent a59d385d23
commit 0cbfb9f854
11 changed files with 291 additions and 34 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ class TracingLifespanProvider(LifespanProvider):
"""
settings = load_settings().observability
enabled = init_tracing(settings)
scores = init_score_sink(settings)
scores = await init_score_sink(settings)
logger.info("tracing_lifespan_startup", enabled=enabled, scores=scores)
return enabled
@@ -181,15 +181,26 @@ def set_generation_usage(
) -> None:
"""Record ``gen_ai.*`` model + token attributes on the current span.
Token counts ACCUMULATE: a span that wraps more than one ``chat`` call
(e.g. the agentic/rank search path issues several LLM calls under one
``everos.search.rank`` span) sums each call's usage rather than letting
the last call overwrite the rest. ``model`` is set as-is (last wins).
No-op when OTel is absent or there is no active recording span, so LLM
client wrappers can call it unconditionally.
"""
if not _OTEL_AVAILABLE:
return
span = _otel_trace.get_current_span()
# `.attributes` exists on a recording SDK span and reflects values set
# earlier in this span's life; a non-recording span has none (getattr
# falls back to {}), and set_attribute on it is itself a no-op.
existing = getattr(span, "attributes", None) or {}
if model is not None:
span.set_attribute(GEN_AI_REQUEST_MODEL, model)
if input_tokens is not None:
span.set_attribute(GEN_AI_USAGE_INPUT_TOKENS, input_tokens)
prior = existing.get(GEN_AI_USAGE_INPUT_TOKENS, 0)
span.set_attribute(GEN_AI_USAGE_INPUT_TOKENS, prior + input_tokens)
if output_tokens is not None:
span.set_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)
prior = existing.get(GEN_AI_USAGE_OUTPUT_TOKENS, 0)
span.set_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, prior + output_tokens)
@@ -117,6 +117,11 @@ def init_tracing(
logger.warning("observability_enabled_but_otel_not_installed")
return False
# Idempotent: a re-init without an intervening shutdown would otherwise
# orphan the previous provider's export thread + OTLP socket.
if _provider is not None:
shutdown_tracing()
from everos import __version__
resource = Resource.create(
@@ -117,11 +117,14 @@ class RecallScoreSink:
_sink: RecallScoreSink | None = None
def init_score_sink(settings: ObservabilitySettings) -> bool:
async def init_score_sink(settings: ObservabilitySettings) -> bool:
"""Build + start the sink when Langfuse creds + emit_recall_scores are set.
Returns True if a sink was installed, False otherwise (disabled, scores
off, or missing creds) — in which case ``emit_recall_scores`` is a no-op.
Idempotent: a re-init without an intervening shutdown tears down the
previous sink first, so its worker task + httpx client are not orphaned.
"""
global _sink
if not settings.enabled or not settings.emit_recall_scores:
@@ -132,6 +135,9 @@ def init_score_sink(settings: ObservabilitySettings) -> bool:
if not (pk and sk and host):
return False
if _sink is not None:
await shutdown_score_sink()
import httpx
endpoint = host.rstrip("/") + "/api/public/scores"
@@ -156,10 +162,15 @@ def emit_recall_scores(
trace_id: str,
observation_id: str | None,
top_score: float,
hit: bool,
hit: bool | None,
method: str,
) -> None:
"""Enqueue recall_top_score + recall_hit; no-op when the sink is off."""
"""Enqueue recall_top_score (always) + recall_hit (only when ``hit`` is
a verdict); no-op when the sink is off.
``hit=None`` means the method's score is uncalibrated (KEYWORD/VECTOR),
so no hit verdict is pushed — only the raw top score.
"""
if _sink is None:
return
comment = f"method={method}"
@@ -168,11 +179,12 @@ def emit_recall_scores(
trace_id, observation_id, "recall_top_score", float(top_score), comment
)
)
_sink.enqueue(
ScoreRecord(
trace_id, observation_id, "recall_hit", 1.0 if hit else 0.0, comment
if hit is not None:
_sink.enqueue(
ScoreRecord(
trace_id, observation_id, "recall_hit", 1.0 if hit else 0.0, comment
)
)
)
async def shutdown_score_sink() -> None:
+16 -3
View File
@@ -139,6 +139,14 @@ def _top_score(data: SearchData) -> float:
return max((item.score for item in items), default=0.0)
# Methods whose top score is calibrated to a comparable [0, 1] scale
# (HYBRID → LR sigmoid, AGENTIC → cross-encoder), so the recall_hit
# threshold is meaningful. KEYWORD (unbounded BM25) and single-route
# VECTOR are excluded — a fixed threshold there yields a misleading
# near-constant "hit" that inflates cross-method dashboards.
_CALIBRATED_METHODS = frozenset({SearchMethod.HYBRID, SearchMethod.AGENTIC})
class SearchManager:
"""Orchestrates per-kind recall, fusion, and shape into the public DTO."""
@@ -224,11 +232,16 @@ class SearchManager:
# Recall-quality signal on the span (always on; the Langfuse
# scores push is separate and gated on creds — see the score sink).
# `hit` is only meaningful for calibrated-score methods; leave it
# unset for KEYWORD/VECTOR so an unbounded score isn't forced
# through a fixed threshold into a misleading always-hit verdict.
top_score = _top_score(data)
threshold = load_settings().observability.recall_hit_threshold
hit = top_score >= threshold
span.set_attribute("everos.search.top_score", top_score)
span.set_attribute("everos.search.hit", hit)
hit: bool | None = None
if req.method in _CALIBRATED_METHODS:
threshold = load_settings().observability.recall_hit_threshold
hit = top_score >= threshold
span.set_attribute("everos.search.hit", hit)
# Push recall-quality scores to Langfuse out-of-band (no-op unless
# a score sink is configured); attach to this retriever span.
+11 -2
View File
@@ -105,7 +105,8 @@ def _get_llm_client() -> LLMClient | None:
from everos.component.llm import build_llm_provider
from everos.config import load_settings
cfg = load_settings().llm
settings = load_settings()
cfg = settings.llm
if not cfg.api_key or not cfg.api_key.get_secret_value() or not cfg.base_url:
logger.warning(
"llm_not_configured",
@@ -113,7 +114,15 @@ def _get_llm_client() -> LLMClient | None:
)
_llm_client = None
else:
_llm_client = build_llm_provider(cfg)
client = build_llm_provider(cfg)
# Record token usage for the hybrid/agentic path, mirroring
# get_llm_client() — otherwise the heaviest LLM spend (query
# decomposition + rerank judge) is invisible in Langfuse.
if settings.observability.enabled:
from everos.component.llm._usage_client import UsageRecordingClient
client = UsageRecordingClient(client)
_llm_client = client
logger.info("search_llm_built", model=cfg.model)
_llm_resolved = True
return _llm_client