Skip to content

Conversation

JWinermaSplunk
Copy link

@JWinermaSplunk JWinermaSplunk commented Oct 8, 2025

Description

Use weak reference in langchain instrumentation span map to avoid memory leaks in long running applications via span storage. Added "cachetools >= 5.2.0" to dependencies.

Fixes #3735

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • Added test_ttl_cache_expires_spans to test_span_manager

Does This PR Require a Core Repo Change?

  • Yes. - Link to PR:
  • No.

Checklist:

See contributing.md for styleguide, changelog guidelines, and more.

  • Followed the style guidelines of this project
  • Changelogs have been updated
  • Unit tests have been added
  • Documentation has been updated

# TODO: Use weak references or a TTL cache to avoid memory leaks in long-running processes. See #3735
self.spans: Dict[UUID, _SpanState] = {}
# Using a TTL cache to avoid memory leaks in long-running processes where end_span might not be called.
self.spans: TTLCache[UUID, _SpanState] = TTLCache(maxsize=1024, ttl=3600)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went ahead and experimented with using a WeakValueDictionary, but it would be a much larger refactor as we
store don't hold a strong ref to _SpanState outside of span_manager, if I am correct. Let me know your thoughts please, thank you.

@JWinermaSplunk JWinermaSplunk requested a review from xrmx October 15, 2025 21:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use weak reference in langchain instrumentation span map

6 participants