Severe memory leak causing system crashes in extended sessions (4+ hours)
What happened?
Gemini CLI gradually consumes exponentially increasing amounts of RAM during long sessions, eventually causing system instability and crashes. Memory usage grows from ~200MB to 7GB+ over 4-6 hours of normal usage, making the tool unusable for professional development work that requires extended focus sessions.
Timeline observed:
- Hour 1: 200MB RAM (normal baseline)
- Hour 2: 800MB RAM (4x increase)
- Hour 3: 2.1GB RAM (exponential growth)
- Hour 4: 4.8GB RAM (system becoming unstable)
Correlation with activities:
- Heavy file operations (
/filecommands on large files >1MB) - Frequent chat save operations (
/chat saveevery 30 minutes) - Long conversation histories (100+ exchanges)
- Web search operations with large result sets
- Codebase analysis tasks
What did you expect to happen?
Memory usage should remain relatively stable regardless of session length, probably staying under 500-1000MB for normal development operations. The CLI should not consume system resources exponentially or cause system instability.
Expected behavior:
- Stable memory usage throughout long sessions
- Automatic garbage collection of unused data
- Memory usage warnings if approaching system limits
- Graceful degradation instead of system crashes
Client information
Platform: Ubuntu 22.04 LTS, Windows 11
CLI Version: 0.1.18 Model: gemini-2.5-pro Sandbox: No sandbox Node.js: 20.x
(Note: Unable to get /about output due to crashes, but issue reproduced across multiple systems and versions)
Login information
Google Account (OAuth) - issue occurs regardless of authentication method (also reproduced with API key authentication)
Anything else we need to know?
technical causes might be:
- Conversation history not being garbage collected
- File content caching without size limits
- Event listeners accumulating without cleanup
- Web search results stored indefinitely in memory
Hi, thanks for the detailed report. The exponential RAM growth (≈200MB → 800MB → 2.1GB → 4.8GB → 7GB+ over 4–6 hours) strongly suggests a memory leak or at least unbounded retention of conversation and artifact data in the Gemini CLI (v0.1.18, model gemini-2.5-pro, Node.js 20.x, Ubuntu 22.04 LTS & Windows 11).
Below are (1) additional data requests, (2) recommended measurement / profiling steps, (3) root cause hypotheses, (4) interim mitigations, and (5) a minimal repro skeleton.
Restated Context
- Triggers: large /file operations (>1MB), frequent /chat save (~every 30 min), very long histories (100+ exchanges), web searches with large result sets, codebase analysis.
- Growth appears exponential rather than linear, indicating either cumulative copying (O(N^2) growth) or an accumulating cache without eviction.
Additional Data Requests
- Per-hour (or per 30m) RSS + heapUsed samples for both Linux and Windows (ps / top / Task Manager + Node heap snapshots).
- Confirmation whether growth occurs within a single long-lived process or also across fresh restarts.
- Approximate total number and aggregate size of distinct files processed in a session.
- Whether repeating
/fileon the same file re-reads & re-caches without deduplication. - Whether clearing or truncating visible conversation history (if possible) lowers memory.
- Node flags used (e.g. --max-old-space-size).
- GC pressure observations: does CPU spike with frequent GC cycles before crash?
- On Windows, which metric explodes first: Working Set vs Private Bytes?
Measurement / Profiling Steps A. Start a fresh session (clean process). B. After every N actions (e.g. 20–30), record:
- ps -o pid,rss,vsz,etime -p
(Linux) - cat /proc/
/status | grep -E 'VmRSS|VmSize' - process.memoryUsage() (if a diagnostic flag can expose it)
- Heap snapshot (Chrome DevTools via node --inspect) C. Isolate each activity type for 30–60 min: only /file operations, only chatting + /chat save, only web searches, only codebase analysis. D. Compare heap snapshots (early vs mid vs late) focusing on Dominator nodes: large Arrays, Maps, Buffers, retained Strings. E. Enable: NODE_OPTIONS="--trace-gc --trace-gc-verbose" (for one run) to see GC cycles and if old generation keeps expanding. F. (Optional) Use Clinic.js (clinic heapprof / clinic flame) or node --inspect heap allocation timeline.
Root Cause Hypotheses
- Conversation history accumulating without truncation or summarization (no sliding window).
- File content caching (global Map) lacking LRU / size cap → each /file adds permanent large strings.
- Web search result objects (JSON) stored indefinitely.
- /chat save performing a deep copy of entire history each time (quadratic growth).
- EventEmitter listener leak (re-adding per command; check for MaxListenersExceededWarning).
- Streaming token buffers not released after finalization.
- Duplicate storage: raw + processed versions of file contents (e.g., original + tokenized + analyzed).
- Platform-specific newline / encoding transformations leaving interim buffers uncollected.
- Large intermediate diff / analysis results persisted for “undo” or “context reuse” but never pruned.
Interim Mitigations (User-Side)
- Proactive process cycling: auto-restart CLI when RSS > 1500MB (export history before restart).
- Manual history compaction: periodically remove or externally archive older exchanges (if a command isn’t available, manual file backup).
- Reduce /file usage on very large files; instead supply smaller excerpts or references.
- Limit web searches; prefer targeted queries; clear search context if a command exists.
- ENV tuning: NODE_OPTIONS="--max-old-space-size=4096" (delays OOM but not a fix) plus deterministic GC triggers for diagnostics only.
- Adopt segmented sessions: separate file ingestion from long Q&A streams.
- Force summarization manually (ask model to produce a session summary and then start a new chat seeded with that summary).
Developer-Facing Improvement Suggestions
- Add sliding window / token budget enforcement with summarization (e.g. when total history > X chars).
- LRU + upper byte cap (e.g. 256MB) for file and search caches; evict least recently used.
- Periodic memory poll (process.memoryUsage()) → trigger automatic trimming / warning thresholds (2GB warning, 3.5GB critical).
- De-duplicate identical file contents via content hash; store only one instance.
- Avoid full deep copies on /chat save; move to structural sharing or incremental snapshot deltas.
- Provide --diagnostics flag logging: timestamp, rssMB, heapUsedMB, historyChars, cachedFilesCount, cachedFilesBytes, activeListeners.
- Ensure streaming buffers (token arrays / partial lines) are nulled after finalize.
- Provide user commands: gemini cache purge, gemini chat compact, flags like --max-history-bytes, --max-cache-bytes.
- Optional memory watermark warnings printed to stderr with actionable hints.
Minimal Repro Skeleton (Conceptual)
- Prepare a 1MB synthetic file (repeated pattern).
- Loop 400–500 cycles: a) /file add bigfile.txt b) Short prompt → model reply c) /chat save d) (Optional) web search (same query) e) 1–2s delay
- Every 50 cycles, record RSS + heap snapshot.
- Plot iteration vs RSS: verify exponential or super-linear curve.
Diagnostic Logging Wish List
- After each command: {timestamp, rssMB, heapUsedMB, retainedHistoryChars, fileCacheCount, fileCacheBytes, webResultCount, eventListenerCount}
- Expose request IDs for memory-heavy commands to correlate with internal metrics.
Feature Requests (Could Be Separate Issues)
- Memory usage warnings with color-coded thresholds.
- Manual & automatic cache purge.
- Conversation compaction / summarization command.
- Configurable caps: --max-history-bytes / --max-cache-bytes / --max-search-results.
- Optional “stateless mode” for long-running scripting tasks.
Next Steps If you can attach:
- 2–3 heap snapshots (early/mid/late) with top Dominators
- A time-series (CSV) of timestamp,RSS(MB),heapUsed(MB)
- Result of isolated tests (only /file vs only /chat save)
…I can help refine this into a narrowly scoped reproducible case and (if maintainers are open) draft a design proposal for memory governance.
Happy to iterate further—thanks again for surfacing this with structured observations.