Skip to content

Conversation

dsaluja
Copy link

@dsaluja dsaluja commented Jun 19, 2025

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

  • Memory leaks in GeminiModelProvider: Added bounded token cache with automatic cleanup (max 100 entries, LRU-style cleanup)
  • Background thread race conditions: Fixed cleanup worker thread shutdown handling in storage backend
  • Silent exception swallowing: Replaced silent exception handling with proper logging in server.py

Technical Details

  • Token Cache Management: Implemented cache size limits, cleanup methods, and performance monitoring
  • Thread Safety: Improved background thread lifecycle management with graceful shutdown
  • Error Visibility: Enhanced error logging to help diagnose future issues

Testing

  • ✅ All 583 unit tests pass (100%)
  • ✅ All simulator tests pass
  • ✅ Code quality checks pass (ruff, black, isort)
  • ✅ Memory usage monitoring and cleanup verified

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

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>
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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) in server.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) in server.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

  1. 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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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.

Comment on lines +57 to +58
self._cache_max_entries = 100 # Maximum cache entries
self._cache_max_text_length = 10000 # Don't cache very large texts
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider making _cache_max_entries and _cache_max_text_length configurable via environment variables. This would allow easier tuning of the cache behavior without requiring code changes.

Copy link
Member

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

Copy link
Member

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

Comment on lines +491 to +492
items = list(self._token_counters.items())
self._token_counters = dict(items[-target_size:])
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

While Python 3.7+ maintains insertion order, it might be more explicit and robust to use collections.OrderedDict if order is critical for the LRU cache implementation. This makes the intent clearer.

Comment on lines +510 to +511
except Exception as e:
logger.warning(f"Failed to log tool call activity: {e}")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.

Suggested change
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}")
Comment on lines +526 to +527
except Exception as e:
logger.warning(f"Failed to log conversation resume activity: {e}")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.

Suggested change
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}")
Comment on lines +623 to +624
except Exception as e:
logger.warning(f"Failed to log tool completion activity: {e}")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.

Suggested change
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}")
Comment on lines +1183 to +1184
except Exception as e:
logger.debug(f"Cache monitoring error: {e}")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.

Suggested change
except Exception as e:
logger.debug(f"Cache monitoring error: {e}")
except OSError as e:
logger.debug(f"Cache monitoring error: {e}")
Comment on lines +95 to +96
except Exception as e:
logger.error(f"Error in storage cleanup worker: {e}")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more specific exception type instead of catching all exceptions. This can help prevent unexpected behavior if an unanticipated exception occurs.

Suggested change
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}")
Comment on lines +123 to +124
if self._cleanup_thread.is_alive():
logger.warning("Cleanup thread failed to shutdown gracefully within 5 seconds")
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants