11import sys
22from types import TracebackType
3- from typing import Any , Callable , Dict , List , Optional , Type , Union , cast
3+ from typing import Any , Callable , Dict , List , Optional , Tuple , Type , Union , cast
44
55import wrapt # type: ignore[import-untyped]
66from fi_instrumentation .fi_types import FiSpanKindValues , SpanAttributes
1414)
1515from ._errors import (
1616 ERROR_TYPE ,
17+ ERROR_TYPE_OTHER ,
1718 EXCEPTION_ESCAPED ,
1819 EXCEPTION_EVENT_NAME ,
20+ EXCEPTION_MESSAGE ,
1921 EXCEPTION_TYPE ,
2022 ExceptionSummary ,
2123 clean_error_description ,
@@ -43,8 +45,9 @@ class FiSpan(wrapt.ObjectProxy): # type: ignore[misc]
4345
4446 - ``error.type`` is set when the span ends with status ERROR, from the
4547 exception that failed it (provider error code or fully qualified class
46- name). An exception recorded on a span that still ends OK, such as a
47- recovered retry, does not set it.
48+ name), else ``_OTHER``. An exception recorded on a span that still ends
49+ OK, such as a recovered retry, does not set it, and neither does a
50+ recovered exception set it on a later unrelated ERROR status.
4851 - An ERROR status description is reduced to the exception message; a Python
4952 traceback never ends up in it.
5053 - With ``hide_error_details`` on, the ERROR status has no description and
@@ -58,9 +61,15 @@ def __init__(self, wrapped: Span, config: TraceConfig) -> None:
5861 # Only summaries (class names, message) of recorded exceptions are kept,
5962 # never the exceptions, so their traceback frames and locals are freed.
6063 self ._self_exception_summaries : List [ExceptionSummary ] = []
61- # error.type of the last recorded exception, and of the exception that
62- # was being handled when the status was set to ERROR.
63- self ._self_recorded_error_type : Optional [str ] = None
64+ # error.type of the last exception recorded as escaped, and of the
65+ # exception that was being handled when the status was set to ERROR.
66+ self ._self_escaped_error_type : Optional [str ] = None
67+ # Recently recorded exceptions (error.type, summary) and the description
68+ # of the last ERROR status, to tell which recorded exception a status
69+ # set outside an `except` block is about (LangChain records the error in
70+ # a callback and sets the status later).
71+ self ._self_recorded : List [Tuple [str , ExceptionSummary ]] = []
72+ self ._self_status_description : Optional [str ] = None
6473 self ._self_status_error_type : Optional [str ] = None
6574 self ._self_status_code : Optional [StatusCode ] = None
6675
@@ -88,6 +97,10 @@ def __exit__(
8897 )
8998 self .end ()
9099
100+ def _remember_recorded (self , error_type : str , summary : ExceptionSummary ) -> None :
101+ self ._self_recorded .append ((error_type , summary ))
102+ del self ._self_recorded [:- _MAX_EXCEPTION_SUMMARIES ]
103+
91104 def record_exception (
92105 self ,
93106 exception : BaseException ,
@@ -98,7 +111,10 @@ def record_exception(
98111 span = cast (Span , self .__wrapped__ )
99112 if not span .is_recording ():
100113 return
101- self ._self_recorded_error_type = get_error_type (exception )
114+ error_type = get_error_type (exception )
115+ self ._remember_recorded (error_type , summarize_exception (exception ))
116+ if escaped :
117+ self ._self_escaped_error_type = error_type
102118 if not self ._self_config .hide_error_details :
103119 self ._self_exception_summaries .append (summarize_exception (exception ))
104120 del self ._self_exception_summaries [:- _MAX_EXCEPTION_SUMMARIES ]
@@ -124,8 +140,17 @@ def add_event(
124140 span = cast (Span , self .__wrapped__ )
125141 if name == EXCEPTION_EVENT_NAME and attributes :
126142 exception_type = attributes .get (EXCEPTION_TYPE )
143+ escaped = attributes .get (EXCEPTION_ESCAPED )
127144 if isinstance (exception_type , str ) and exception_type :
128- self ._self_recorded_error_type = exception_type
145+ message = attributes .get (EXCEPTION_MESSAGE )
146+ self ._remember_recorded (
147+ exception_type ,
148+ ExceptionSummary (
149+ (exception_type ,), message if isinstance (message , str ) else None
150+ ),
151+ )
152+ if str (escaped ).lower () == "true" :
153+ self ._self_escaped_error_type = exception_type
129154 if self ._self_config .hide_error_details :
130155 attributes = strip_error_details (attributes )
131156 span .add_event (name , attributes = attributes , timestamp = timestamp )
@@ -151,8 +176,10 @@ def set_status(
151176 # Called from an `except` block (use_span, most instrumentors), the
152177 # handled exception is the one this status is about.
153178 in_flight = sys .exc_info ()[1 ]
154- if in_flight is not None :
155- self ._self_status_error_type = get_error_type (in_flight )
179+ self ._self_status_error_type = (
180+ get_error_type (in_flight ) if in_flight is not None else None
181+ )
182+ self ._self_status_description = status_description
156183 if self ._self_config .hide_error_details :
157184 status_description = None
158185 else :
@@ -169,13 +196,36 @@ def _ended_with_error(self) -> bool:
169196 status_code = self ._self_status_code
170197 return status_code is StatusCode .ERROR
171198
199+ def _recorded_error_type_for_status (self ) -> Optional [str ]:
200+ # The newest recorded exception the ERROR status is about: its message
201+ # or class name is in the status description, or the status has no
202+ # description. A recovered exception the status does not mention (a
203+ # timeout retried successfully, then a guardrail rejection) is skipped.
204+ description = self ._self_status_description
205+ for error_type , summary in reversed (self ._self_recorded ):
206+ if not description :
207+ return error_type
208+ if summary .message and summary .message in description :
209+ return error_type
210+ if any (name in description for name in summary .type_names ):
211+ return error_type
212+ return None
213+
172214 def _set_error_type (self ) -> None :
173215 # Only a span that ends with status ERROR gets error.type: from the
174- # exception handled when the status was set, else the last recorded
175- # one. An instrumentor that set error.type itself is not overwritten.
176- error_type = self ._self_status_error_type or self ._self_recorded_error_type
177- if error_type is None or not self ._ended_with_error ():
216+ # exception handled when the status was set, else the last exception
217+ # recorded as escaped, else "_OTHER" (OpenTelemetry semantic
218+ # conventions). A recovered exception recorded earlier is not used: the
219+ # status may be about something else. An instrumentor that set
220+ # error.type itself is not overwritten.
221+ if not self ._ended_with_error ():
178222 return
223+ error_type = (
224+ self ._self_status_error_type
225+ or self ._self_escaped_error_type
226+ or self ._recorded_error_type_for_status ()
227+ or ERROR_TYPE_OTHER
228+ )
179229 span = cast (Span , self .__wrapped__ )
180230 existing = getattr (span , "attributes" , None ) or {}
181231 if ERROR_TYPE not in existing :
@@ -206,6 +256,7 @@ def end(self, end_time: Optional[int] = None) -> None:
206256 self ._set_error_type ()
207257 span .end (end_time )
208258 self ._self_exception_summaries .clear ()
259+ self ._self_recorded .clear ()
209260
210261 def set_input (
211262 self ,
0 commit comments