Skip to content

Commit 635606f

Browse files
committed
fix: missing workflow span closing
1 parent b09e718 commit 635606f

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

sentry_sdk/integrations/openai_agents/patches/agent_run.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,19 @@ def _get_current_agent(
4646
"""Get the current agent from context wrapper"""
4747
return getattr(context_wrapper, "_sentry_current_agent", None)
4848

49+
def _close_workflow_span_on_error(agent: "Optional[agents.Agent]") -> None:
50+
"""
51+
Close the workflow span on error for streaming executions.
52+
53+
This ensures the workflow span is properly closed when an exception
54+
occurs in _run_single_turn_streamed or execute_handoffs, preventing
55+
resource leaks and ensuring accurate telemetry.
56+
"""
57+
if agent and hasattr(agent, "_sentry_workflow_span"):
58+
workflow_span = agent._sentry_workflow_span
59+
workflow_span.__exit__(*sys.exc_info())
60+
delattr(agent, "_sentry_workflow_span")
61+
4962
def _maybe_start_agent_span(
5063
context_wrapper: "agents.RunContextWrapper",
5164
agent: "agents.Agent",
@@ -129,7 +142,9 @@ async def patched_execute_handoffs(
129142
# Call original method with all parameters
130143
try:
131144
result = await original_execute_handoffs(*args, **kwargs)
132-
145+
except Exception:
146+
_close_workflow_span_on_error(agent)
147+
raise
133148
finally:
134149
# End span for current agent after handoff processing is complete
135150
if agent and context_wrapper and _has_active_agent_span(context_wrapper):
@@ -161,10 +176,7 @@ async def patched_execute_final_output(
161176

162177
# For streaming: close the workflow span if it exists
163178
# (For non-streaming, the workflow span is closed by the context manager in _create_run_wrapper)
164-
if agent and hasattr(agent, "_sentry_workflow_span"):
165-
workflow_span = agent._sentry_workflow_span
166-
workflow_span.__exit__(*sys.exc_info())
167-
delattr(agent, "_sentry_workflow_span")
179+
_close_workflow_span_on_error(agent)
168180

169181
return result
170182

@@ -221,6 +233,7 @@ async def patched_run_single_turn_streamed(
221233
if span is not None and span.timestamp is None:
222234
_record_exception_on_span(span, exc)
223235
end_invoke_agent_span(context_wrapper, agent)
236+
_close_workflow_span_on_error(agent)
224237
reraise(*sys.exc_info())
225238

226239
return result

0 commit comments

Comments
 (0)