Skip to content

Commit 87d8a50

Browse files
nirgaclaude
andauthored
fix(langchain): spans dictionary memory leak (#3216)
Co-authored-by: Claude <[email protected]>
1 parent cf05cac commit 87d8a50

File tree

4 files changed

+11
-458
lines changed

4 files changed

+11
-458
lines changed

packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -178,14 +178,17 @@ def _get_span(self, run_id: UUID) -> Span:
178178

179179
def _end_span(self, span: Span, run_id: UUID) -> None:
180180
for child_id in self.spans[run_id].children:
181-
child_span = self.spans[child_id].span
182-
if child_span.end_time is None: # avoid warning on ended spans
183-
child_span.end()
181+
if child_id in self.spans:
182+
child_span = self.spans[child_id].span
183+
if child_span.end_time is None: # avoid warning on ended spans
184+
child_span.end()
184185
span.end()
185186
token = self.spans[run_id].token
186187
if token:
187188
context_api.detach(token)
188189

190+
del self.spans[run_id]
191+
189192
def _create_span(
190193
self,
191194
run_id: UUID,
@@ -541,9 +544,8 @@ def on_llm_end(
541544
self._emit_llm_end_events(response)
542545
else:
543546
set_chat_response(span, response)
544-
self._end_span(span, run_id)
545547

546-
# Record duration
548+
# Record duration before ending span
547549
duration = time.time() - self.spans[run_id].start_time
548550
vendor = span.attributes.get(SpanAttributes.LLM_SYSTEM, "Langchain")
549551
self.duration_histogram.record(
@@ -554,6 +556,8 @@ def on_llm_end(
554556
},
555557
)
556558

559+
self._end_span(span, run_id)
560+
557561
@dont_throw
558562
def on_tool_start(
559563
self,

packages/opentelemetry-instrumentation-langchain/tests/cassettes/test_batch_metadata/test_async_batch_metadata_in_span_attributes.yaml

Lines changed: 0 additions & 232 deletions
This file was deleted.

0 commit comments

Comments
 (0)