-
- Notifications
You must be signed in to change notification settings - Fork 654
fix: memory leaks and server stability issues #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
This commit addresses critical memory management issues that could cause server instability and require reinstallation during heavy usage: 🔧 **Token Cache Management (providers/gemini.py)** - Add bounded cache with 100 entry limit and 10KB text size limit - Implement automatic cache cleanup when limits exceeded - Add cache performance monitoring with hit/miss statistics - Prevent unbounded memory growth from large file processing 🧵 **Background Thread Safety (utils/storage_backend.py)** - Fix cleanup worker thread shutdown race conditions - Add proper exception handling in cleanup worker - Implement incremental sleep for responsive shutdown - Add comprehensive logging for thread lifecycle 🛡️ **Error Handling (server.py)** - Replace silent exception swallowing with proper logging - Add background cache monitoring (30-minute intervals) - Improve visibility into logging system failures ✅ **Testing & Validation** - All simulator tests pass (basic_conversation, content_validation) - Core unit tests pass (38/38 including providers, utils, server) - Conversation memory tests pass (24/24) - No regressions in existing functionality 🎯 **Impact** - Prevents memory leaks in shared MCP server process - Eliminates need for server restarts due to cache bloat - Improves stability for multiple concurrent Claude sessions - Maintains backward compatibility 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @dsaluja, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly enhances the Zen MCP server's stability and reliability by addressing critical memory leaks and improving background thread management. It introduces a controlled token cache to prevent memory exhaustion, refines the graceful shutdown of background processes, and improves diagnostic capabilities through more explicit error logging and new background monitoring.
Highlights
- Memory Leak Mitigation: I've implemented a bounded, LRU-style token cache within the
GeminiModelProvider
to prevent unbounded growth of the_token_counters
dictionary. This includes new methods for cache cleanup, tracking cache hits and misses, and providing performance statistics. - Enhanced Server Stability: I've improved the graceful shutdown mechanism for the storage backend's cleanup worker thread. The worker now sleeps in smaller intervals, allowing for more frequent checks of the shutdown flag, and the
shutdown
method has an increased join timeout with more detailed logging for thread termination status. - Improved Error Visibility: I've replaced instances of silent exception swallowing (
except Exception: pass
) inserver.py
with explicit warning logging. This ensures that failures related to activity logging are now properly recorded, aiding in diagnosis. - Background Monitoring: I've introduced a new asynchronous background task (
_start_cache_monitoring
) inserver.py
to periodically monitor and log the number of active conversation threads in the storage backend, providing ongoing insight into memory usage.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command>
or @gemini-code-assist <command>
. Below is a summary of the supported commands.
Feature | Command | Description |
---|---|---|
Code Review | /gemini review | Performs a code review for the current pull request in its current state. |
Pull Request Summary | /gemini summary | Provides a summary of the current pull request in its current state. |
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
Help | /gemini help | Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/
folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This PR addresses memory leaks and stability issues by implementing a token cache with cleanup in GeminiModelProvider, improving thread shutdown handling in the storage backend, and enhancing error logging in server.py. The changes include cache management settings, thread safety improvements, and better error visibility. The feedback focuses on exception handling and configuration options.
self._cache_max_entries = 100 # Maximum cache entries | ||
self._cache_max_text_length = 10000 # Don't cache very large texts |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This clashes with MCP_PROMPT_SIZE_LIMIT
- 10,000 characters is tiny when it comes to long context Claude at times shares with the other models, needs to match MCP_PROMPT_SIZE_LIMIT for other parts of the server to work
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_cache_max_entries may also not be enough given the conversation 'time' can be configured to up to any number of hours, as some may in fact need this to be long for overnight work (and continuation in the morning) after obtaining continuation uids from the logs
items = list(self._token_counters.items()) | ||
self._token_counters = dict(items[-target_size:]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
except Exception as e: | ||
logger.warning(f"Failed to log tool call activity: {e}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.
except Exception as e: | |
logger.warning(f"Failed to log tool call activity: {e}") | |
except OSError as e: | |
logger.warning(f"Failed to log tool call activity: {e}") |
except Exception as e: | ||
logger.warning(f"Failed to log conversation resume activity: {e}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.
except Exception as e: | |
logger.warning(f"Failed to log conversation resume activity: {e}") | |
except OSError as e: | |
logger.warning(f"Failed to log conversation resume activity: {e}") |
except Exception as e: | ||
logger.warning(f"Failed to log tool completion activity: {e}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.
except Exception as e: | |
logger.warning(f"Failed to log tool completion activity: {e}") | |
except OSError as e: | |
logger.warning(f"Failed to log tool completion activity: {e}") |
except Exception as e: | ||
logger.debug(f"Cache monitoring error: {e}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.
except Exception as e: | |
logger.debug(f"Cache monitoring error: {e}") | |
except OSError as e: | |
logger.debug(f"Cache monitoring error: {e}") |
except Exception as e: | ||
logger.error(f"Error in storage cleanup worker: {e}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.
except Exception as e: | |
logger.error(f"Error in storage cleanup worker: {e}") | |
except OSError as e: | |
logger.error(f"Error in storage cleanup worker: {e}") |
if self._cleanup_thread.is_alive(): | ||
logger.warning("Cleanup thread failed to shutdown gracefully within 5 seconds") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the cleanup thread fails to terminate gracefully, it might be beneficial to log the stack trace to help diagnose the cause of the hang.
if self._cleanup_thread.is_alive(): | |
logger.warning("Cleanup thread failed to shutdown gracefully within 5 seconds") | |
if self._cleanup_thread.is_alive(): | |
logger.warning("Cleanup thread failed to shutdown gracefully within 5 seconds", exc_info=True) | |
else: |
Summary
This PR addresses critical memory leaks and stability issues in the Zen MCP server that were causing server crashes during heavy usage, requiring frequent reinstallation.
Fixed Issues
Technical Details
Testing
These changes ensure the MCP server can handle long-running sessions and heavy usage without memory leaks or stability issues.
🤖 Generated with Claude Code
Co-Authored-By: Claude noreply@anthropic.com