crewAI
crewAI copied to clipboard
Fix/memory leak crewbase
Fixes issue #3450 - CrewBase objects cannot be garbage collected
Root Cause Analysis:
The memory leak was caused by multiple circular references:
- Memoize decorator holding strong references to 'self' in cache
- Callback wrapper functions creating circular references
- 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
This PR is stale because it has been open for 45 days with no activity.