Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat(core): add runtime saturation + dependency timeout metrics (LET-7826) (#9815)
Kian Jones6c83c6032906
diff --git a/letta/data_sources/redis_client.py b/letta/data_sources/redis_client.pyindex c1f7a0987..28b2574d9 100644--- a/letta/data_sources/redis_client.py+++ b/letta/data_sources/redis_client.py@@ -13,6 +13,7 @@ from letta.constants import ()from letta.errors import ConversationBusyError, MemoryRepoBusyErrorfrom letta.log import get_logger+from letta.otel.metric_registry import MetricRegistryfrom letta.settings import settingstry:@@ -131,7 +132,13 @@ class AsyncRedisClient:for attempt in range(max_attempts):try:return await func(self, *args, **kwargs)- except (ConnectionError, TimeoutError) as e:+ except TimeoutError as e:+ MetricRegistry().redis_timeout_counter.add(1, attributes={"operation": func.__name__})+ last_error = e+ if attempt < max_attempts - 1:+ await asyncio.sleep(delay * (2**attempt))+ logger.warning(f"Retry {attempt + 1}/{max_attempts} for {func.__name__}: {e}")+ except ConnectionError as e:last_error = eif attempt < max_attempts - 1:await asyncio.sleep(delay * (2**attempt))diff --git a/letta/monitoring/event_loop_watchdog.py b/letta/monitoring/event_loop_watchdog.pyindex ac8bd015b..3a4e8a315 100644--- a/letta/monitoring/event_loop_watchdog.py+++ b/letta/monitoring/event_loop_watchdog.py@@ -11,6 +11,7 @@ from collections import defaultdictfrom typing import Optionalfrom letta.log import get_logger+from letta.otel.metric_registry import MetricRegistrylogger = get_logger(__name__)@@ -82,6 +83,12 @@ class EventLoopWatchdog:self._last_heartbeat = nowself._heartbeat_scheduled_at = now + 1.0+ try:+ MetricRegistry().event_loop_lag_ms_histogram.record(lag * 1000, attributes={"source": "watchdog_heartbeat"})+ except Exception:+ # Observability must never interfere with watchdog safety.+ pass+# Log if lag is significant (> 2 seconds means event loop is saturated)if lag > 2.0:logger.warning(f"Event loop lag in heartbeat: {lag:.2f}s (expected ~1.0s)")@@ -110,19 +117,28 @@ class EventLoopWatchdog:# Try to estimate event loop load (safe from separate thread)task_count = -1+ executor_backlog = -1try:if self._loop and not self._loop.is_closed():# all_tasks returns only unfinished tasksall_tasks = asyncio.all_tasks(self._loop)task_count = len(all_tasks)+ executor_backlog = self._get_executor_backlog(self._loop)except Exception:# Accessing loop from thread can be fragile, don't failpass+ if executor_backlog >= 0:+ try:+ MetricRegistry().executor_backlog_gauge.set(executor_backlog, attributes={"source": "default_executor"})+ except Exception:+ pass+# ALWAYS log every check to prove watchdog is alivelogger.debug(f"WATCHDOG_CHECK: heartbeat_age={time_since_heartbeat:.1f}s, current_lag={current_lag:.2f}s, "- f"max_lag={max_lag_seen:.2f}s, consecutive_hangs={consecutive_hangs}, tasks={task_count}"+ f"max_lag={max_lag_seen:.2f}s, consecutive_hangs={consecutive_hangs}, "+ f"tasks={task_count}, executor_backlog={executor_backlog}")# Log at INFO if we see significant lag (> 2 seconds indicates saturation)@@ -170,6 +186,22 @@ class EventLoopWatchdog:except Exception as e:logger.error(f"Watchdog error: {e}")+ @staticmethod+ def _get_executor_backlog(loop: asyncio.AbstractEventLoop) -> int:+ """Best-effort backlog size for the loop's default executor work queue."""+ default_executor = getattr(loop, "_default_executor", None)+ if default_executor is None:+ return 0++ work_queue = getattr(default_executor, "_work_queue", None)+ if work_queue is None or not hasattr(work_queue, "qsize"):+ return 0++ try:+ return int(work_queue.qsize())+ except Exception:+ return 0+def _dump_state(self):"""Dump state with stack traces when hang detected."""try:diff --git a/letta/otel/metric_registry.py b/letta/otel/metric_registry.pyindex 40845d51e..ee7aec711 100644--- a/letta/otel/metric_registry.py+++ b/letta/otel/metric_registry.py@@ -269,6 +269,56 @@ class MetricRegistry:),)+ # Runtime saturation and dependency timeout metrics+ @property+ def event_loop_lag_ms_histogram(self) -> Histogram:+ return self._get_or_create_metric(+ "event_loop_lag_ms",+ partial(+ self._meter.create_histogram,+ name="event_loop_lag_ms",+ description="Event loop scheduling lag measured by the watchdog heartbeat.",+ unit="ms",+ ),+ )++ @property+ def executor_backlog_gauge(self) -> Gauge:+ return self._get_or_create_metric(+ "executor_backlog",+ partial(+ self._meter.create_gauge,+ name="executor_backlog",+ description="Best-effort backlog depth of the default event-loop executor queue.",+ unit="1",+ ),+ )++ # (includes operation)+ @property+ def redis_timeout_counter(self) -> Counter:+ return self._get_or_create_metric(+ "redis_timeout_total",+ partial(+ self._meter.create_counter,+ name="redis_timeout_total",+ description="Total number of Redis operation timeout errors.",+ unit="1",+ ),+ )++ # (includes provider)+ @property+ def provider_timeout_counter(self) -> Counter:+ return self._get_or_create_metric(+ "provider_timeout_total",+ partial(+ self._meter.create_counter,+ name="provider_timeout_total",+ description="Total number of model provider timeout errors.",+ unit="1",+ ),+ )# Database connection pool metrics# (includes engine_name, pool_mode)@propertydiff --git a/letta/services/streaming_service.py b/letta/services/streaming_service.pyindex aba80f3da..ce37c815d 100644--- a/letta/services/streaming_service.py+++ b/letta/services/streaming_service.py@@ -185,6 +185,7 @@ class StreamingService:request_start_timestamp_ns=request_start_timestamp_ns,include_return_message_types=request.include_return_message_types,actor=actor,+ provider_name=agent.llm_config.model_endpoint_type,conversation_id=conversation_id,lock_key=lock_key, # For lock release (may differ from conversation_id)client_tools=request.client_tools,@@ -356,6 +357,7 @@ class StreamingService:request_start_timestamp_ns: int,include_return_message_types: Optional[list[MessageType]],actor: User,+ provider_name: str,conversation_id: Optional[str] = None,lock_key: Optional[str] = None,client_tools: Optional[list[ClientToolSchema]] = None,@@ -443,6 +445,7 @@ class StreamingService:except LLMTimeoutError as e:MetricRegistry().request_timeout_counter.add(1, attributes=in_flight_attrs)+ MetricRegistry().provider_timeout_counter.add(1, attributes={"provider": provider_name})run_status = RunStatus.failedstop_reason = LettaStopReason(stop_reason=StopReasonType.llm_api_error)error_message = LettaErrorMessage(