Skip to content

fix(langchain): langchain end span#3007

Closed
DRXD1000 wants to merge 10 commits intotraceloop:mainfrom
DRXD1000:fix_langchain_end_span
Closed

fix(langchain): langchain end span#3007
DRXD1000 wants to merge 10 commits intotraceloop:mainfrom
DRXD1000:fix_langchain_end_span

Conversation

@DRXD1000
Copy link
Copy Markdown

@DRXD1000 DRXD1000 commented Jun 11, 2025

  • I have added tests that cover my changes.
  • If adding a new instrumentation or changing an existing one, I've added screenshots from some observability platform showing the change.
  • PR name follows conventional commits format: feat(instrumentation): ... or fix(instrumentation): ....
  • (If applicable) I have updated the documentation accordingly.

Regarding #2790 i have experimented with this change. As far as i have seen it in my applications, this reduces the memory leak significantly, but does not fix it completely.

I would really much appreciate if someone could look at this change and check its usability.


Important

Fixes memory leak in TraceloopCallbackHandler by ensuring spans are deleted from self.spans after ending.

This description was created by Ellipsis for 0993186. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

  • Bug Fixes
    • Improved internal cleanup to ensure completed spans are properly removed from tracking, enhancing reliability and resource management.

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Jun 11, 2025

CLA assistant check
All committers have signed the CLA.

Copy link
Copy Markdown
Contributor

@ellipsis-dev ellipsis-dev Bot left a comment

Choose a reason for hiding this comment

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

Caution

Changes requested ❌

Reviewed everything up to 0993186 in 1 minute and 32 seconds. Click for details.
  • Reviewed 18 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 1 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py:397
  • Draft comment:
    Consider using self.spans.pop(run_id, None) for removing the span associated with run_id. This approach is more concise and reduces the chance of errors.
  • Reason this comment was not posted:
    Marked as duplicate.

Workflow ID: wflow_RwfZg1GoT5gbkyj1

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@dinmukhamedm
Copy link
Copy Markdown
Collaborator

Hey @DRXD1000 thanks for opening this! I'm happy to jump into the investigation on

but does not fix it completely.

Do you have any minimal repro application and setup for tracking memory consumption?

@DRXD1000
Copy link
Copy Markdown
Author

DRXD1000 commented Jun 11, 2025

@dinmukhamedm sadly not. I tested with a running application using the memray package locally and grafana kubernetes Dashboards. The application i tested with is a langgraph stategraph inside a fastapi application. Maybe someone from the mentioned issue can provide a minimal example.

What i can provide right now are screenshots of the memray graphs. The only thing i changed is the openllmetry package. Both runs have gone trough 120 requests to the fastapi service.

Openllmetry main branch without modification 512MB -> 543.3 MB

Main-Branch-Start
Main-Branch-End

Branch of this pull request 455.9MB -> 458.3MB

Fix-Branch-Start
Fix-Branch-End

@nirga nirga changed the title fix(instrumentation-langchain): Fix langchain end span fix(langchain): langchain end span Jun 28, 2025
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

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

Bug: Child Span Cleanup Fails

The memory leak fix for child spans is incomplete. The self.spans.pop(child_id, None) call is incorrectly placed inside the if child_span.end_time is None: condition. This prevents child spans that were already ended from being removed from self.spans, causing a persistent memory leak for those spans. To fully address the leak, self.spans.pop(child_id, None) should be moved outside this condition to ensure all child spans are cleaned up regardless of their end status.

packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py#L397-L401

for child_id in self.spans[run_id].children:
child_span = self.spans[child_id].span
if child_span.end_time is None: # avoid warning on ended spans
child_span.end()
self.spans.pop(child_id, None)

Fix in Cursor


BugBot free trial expires on July 22, 2025
You have used $0.00 of your $50.00 spend limit so far. Manage your spend limit in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

nirga
nirga previously approved these changes Jun 28, 2025
Copy link
Copy Markdown
Member

@nirga nirga left a comment

Choose a reason for hiding this comment

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

Thanks so much @DRXD1000 and sorry for taking so long in addressing this. This is a completely needed fix - not sure why / when these got disappeared from the instrumentation.

@nirga nirga dismissed their stale review June 28, 2025 09:59

Interesting - this seems to cause some of the tests to fail, and it seems some spans are not being generated no because of this change. Can it be that the order of _end_span is not what we expect and so we may need to access a certain span or their children after _end_span has been called? 🤔

@DRXD1000
Copy link
Copy Markdown
Author

Thanks @nirga for checking in. I would really appreciate if you could investigate this :)

@nirga
Copy link
Copy Markdown
Member

nirga commented Jun 28, 2025

Yes will do too! @DRXD1000

@joschne
Copy link
Copy Markdown

joschne commented Jul 9, 2025

We would greatly appreciate this fix and would be very happy if this PR could be merged soon! Thank you so much 😃

@DRXD1000
Copy link
Copy Markdown
Author

@nirga Any updates on this ?

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 31, 2025

Walkthrough

The _end_span method in the TraceloopCallbackHandler class was updated to remove span entries from the internal self.spans dictionary after ending them. This cleanup now applies to both child spans and the main span within the method.

Changes

Cohort / File(s) Change Summary
Span Cleanup Logic
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py
Updated _end_span to remove ended spans from self.spans after completion for both child and main spans.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

A rabbit hops through callback code,
Tidying up the spans it owed.
With every end, it sweeps the den,
No lingering spans to track again.
Clean and neat, the traces run—
Another code review, swiftly done! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8176494 and 61a0d81.

📒 Files selected for processing (1)
  • packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Test Packages (3.9)
  • GitHub Check: Test Packages (3.11)
  • GitHub Check: Test Packages (3.12)
  • GitHub Check: Test Packages (3.10)
  • GitHub Check: Build Packages (3.11)
  • GitHub Check: Lint
🔇 Additional comments (1)
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py (1)

184-184: LGTM! Effective memory leak fix.

The addition of self.spans.pop(child_id, None) and self.spans.pop(run_id, None) properly addresses the memory leak by removing span references from the tracking dictionary immediately after they are ended. The use of pop() with a default value is safe and efficient, preventing KeyError exceptions if spans are somehow processed multiple times.

This change aligns with the PR objectives to reduce memory accumulation in long-running applications and follows the previous feedback to use pop() instead of membership checks.

Also applies to: 190-190

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nirga
Copy link
Copy Markdown
Member

nirga commented Aug 2, 2025

I think #3216 should fix this - closing this in favor of my PR.

@nirga nirga closed this Aug 2, 2025
@DRXD1000 DRXD1000 deleted the fix_langchain_end_span branch August 5, 2025 13:34
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.

5 participants