crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

Fix/memory leak crewbase

Open devenchawla009 opened this issue 1 year ago • 1 comments

Fixes issue #3450 - CrewBase objects cannot be garbage collected

Root Cause Analysis:

The memory leak was caused by multiple circular references:

  1. Memoize decorator holding strong references to 'self' in cache
  2. Callback wrapper functions creating circular references
  3. MCP server method bound to instance preventing GC

Solutions Implemented:

1. Weak Reference Memoization

  • Replaced strong reference caching with WeakKeyDictionary
  • Uses weak references for instance-based caching
  • Allows proper garbage collection while maintaining cache benefits
  • Added cache clearing functionality for debugging

2. Callback System Fix

  • Updated crew decorator to use weak references in callback wrappers
  • Prevents circular references between crew and CrewBase instances
  • Callbacks gracefully handle garbage collected instances

3. MCP Server Method Fix

  • Replaced bound method with functools.partial + weak reference
  • Eliminates circular reference from MCP server cleanup method
  • Maintains functionality while allowing garbage collection

4. Enhanced Cleanup Methods

  • Added del method for automatic cleanup
  • Added explicit cleanup() method for user control
  • Proper resource management for MCP adapters and cached data

Testing:

  • Comprehensive test suite covering all scenarios
  • Memory leak regression tests for issue #3450
  • Tests for multiple instances and explicit cleanup
  • Verified garbage collection works correctly

Performance Impact:

  • Maintains memoization performance benefits
  • No breaking changes to existing API
  • Memory usage now properly bounded
  • Eliminates

devenchawla009 avatar Sep 21 '25 10:09 devenchawla009

This PR is stale because it has been open for 45 days with no activity.

github-actions[bot] avatar Nov 05 '25 12:11 github-actions[bot]