fix: initialize() spawns new headless bridge without closing old one — process leak
Pre-submission checklist | 提交前检查
- [x] I have searched existing issues and this hasn't been mentioned before | 我已搜索现有问题,确认此问题尚未被提及
- [x] I have read the project documentation and confirmed this issue doesn't already exist | 我已阅读项目文档并确认此问题尚未存在
- [x] This issue is specific to MemOS and not a general software issue | 该问题是针对 MemOS 的,而不是一般软件问题
Bug Description | 问题描述
Plugin Version
@memtensor/memos-local-pluginv2.0.7- Platform: Hermes Agent (Linux, 2-core 4GB)
Description
When the Hermes memory provider's initialize() is called (e.g. on each session start or reconnect), a new MemosBridgeClient (and thus a new --no-viewer Node.js bridge process) is spawned without closing the previous one. The old bridge process becomes an orphan, consuming ~93 MB of RAM each. Over time, these accumulate indefinitely.
The headless bridge reaper (_reap_stale_headless_bridges_locked) does NOT clean these up because their parent process is still alive — it only reaps bridges whose parent has died or are legacy entries older than HEADLESS_STALE_SECONDS.
Root Cause
File: plugins/memory/memtensor/__init__.py, initialize() (line ~296)
def initialize(self, session_id, **kwargs):
# ...
ensure_bridge_running()
new_bridge = MemosBridgeClient() # ← spawns new Node process
self._bridge = new_bridge # ← overwrites old reference, old bridge leaked
Compare with _reconnect_bridge() (line ~1727) which does it correctly:
def _reconnect_bridge(self, ...):
old_bridge = self._bridge
if old_bridge:
old_bridge.close() # ← correctly closes old bridge first
new_bridge = MemosBridgeClient()
Additionally: In bridge_client.py _reap_stale_headless_bridges_locked() (line ~206), the reaper only kills bridges when parent_dead or legacy_stale. Since the parent (Hermes dashboard or gateway) remains alive, none of the leaked bridges are ever reaped.
And: bridge.cjs (line ~57) intentionally skips the PID-file singleton guard for --no-viewer bridges, so there's no Node-side protection either.
How to Reproduce | 如何重现
- Run Hermes with
memory.provider: memtensorconfigured - Start a
hermes dashboardorhermes gatewaysession - Each session start / reconnect calls
initialize()and spawns a new bridge - Check
ps aux | grep bridge.cjs— orphaned--no-viewerprocesses accumulate
Observed timeline from a live instance (dashboard PID 333413):
23:40:53 PID 335421 --no-viewer (initialize call #1)
23:40:57 PID 335577 --no-viewer (initialize call #2, 4s later)
23:42:15 PID 337303 --no-viewer (initialize call #3)
23:42:17 PID 337443 --no-viewer (initialize call #4, 2s later)
23:47:42 PID 342591 --no-viewer (initialize call #5)
23:47:45 PID 342675 --no-viewer (initialize call #6, 3s later)
6 orphaned bridges = ~558 MB wasted RAM on a 3.6 GB machine.
Suggested Fix
In initialize(), close the existing bridge before creating a new one:
def initialize(self, session_id, **kwargs):
# Close previous bridge if any
if self._bridge:
old_pid = getattr(self._bridge, "pid", "?")
logger.info("MemOS: closing previous bridge (pid=%s) before re-init", old_pid)
with contextlib.suppress(Exception):
self._bridge.close()
self._bridge = None
# ... rest of existing initialize() code ...
Optionally, also strengthen the reaper in bridge_client.py to deduplicate bridges under the same living parent (keep only the most recent one per parent).
Environment | 环境信息
- OS: Ubuntu 24.04.4 LTS (2-core, 4GB RAM)
- Node.js: v22.x
- Hermes Agent: latest (Telegram gateway + CLI dashboard)
- memos-local-plugin: v2.0.7 (installed via npm)
Additional Context | 其他信息
{ "bridges": [ {"pid": 335421, "parentPid": 333413, "startedAt": 1781538054.3, "agent": "hermes"}, {"pid": 335577, "parentPid": 333413, "startedAt": 1781538058.4, "agent": "hermes"}, {"pid": 337303, "parentPid": 333413, "startedAt": 1781538136.1, "agent": "hermes"}, {"pid": 337443, "parentPid": 333413, "startedAt": 1781538138.2, "agent": "hermes"}, {"pid": 342591, "parentPid": 333413, "startedAt": 1781538463.7, "agent": "hermes"}, {"pid": 342675, "parentPid": 333413, "startedAt": 1781538466.0, "agent": "hermes"}, {"pid": 359586, "parentPid": 355477, "startedAt": 1781539434.6, "agent": "hermes"} ] }
Willingness to Implement | 实现意愿
- [ ] I'm willing to implement this myself | 我愿意自己解决
- [x] I would like someone else to implement this | 我希望其他人来解决
🤖 AutoDev has picked up this issue and started working on it.
Task ID: 00ed0a7e14bf0dd3
Working branch: bugfix/autodev-1927
Target branch: latest dev* branch
Workflow: opsp (analysis → coding → testing → PR)
I will post the PR link here once done. If I need more information, I will ask in the comments.
✅ AutoDev task 00ed0a7e14bf0dd3 completed.
Summary: Fixes #1927: MemTensorProvider.initialize() was spawning a fresh MemosBridgeClient (and therefore a new --no-viewer Node bridge subprocess) on every call without closing the previously-referenced self._bridge, leaking ~93 MB per re-initialization. Hermes re-calls initialize() on each reconnect / new session, so orphaned bridges accumulated indefinitely — the headless-bridge reaper never collected them because their parent (Hermes dashboard / gateway) stays alive.
The fix mirrors the safe pattern already used by _reconnect_bridge() (line ~1727 of the same file): at the very top of initialize(), capture the current self._bridge, log its PID, call .close() inside contextlib.suppress(Exception) so a stuck Node subprocess never blocks re-init, and clear self._bridge before the existing creation flow runs. The fix is +19 lines in apps/memos-local-plugin/adapters/hermes/memos_provider/__init__.py, scoped entirely to the plugin sub-project; main src/memos/ is untouched and make openapi is not required.
Verification (TDD): added 3 regression tests in tests/python/test_hermes_provider_pipeline.py — test_initialize_closes_previous_bridge_before_spawning_new_one (the actual leak scenario, two queued FakeBridge instances), test_initialize_when_no_previous_bridge_does_not_call_close (first-init happy path), and test_initialize_swallows_exception_from_old_bridge_close (isolation when the previous bridge's close() raises). Tests #1 and #3 fail before the fix and pass after; full plugin Python suite is 45/45 passing. ruff check and ruff format --check both clean on the touched files.
Branch bugfix/autodev-1927 pushed to origin at commit 5a0a3fc3. Spec archive synced to memos-autodev-specs.
Base branch: main
Branch: bugfix/autodev-1927
Commit: 5a0a3fc
PR: https://github.com/MemTensor/MemOS/pull/1928
Assigned to: @MatthewZhuang, @CarltonXiang, @syzsunshine219, @World-controller
Reviewers: @MatthewZhuang, @CarltonXiang, @syzsunshine219, @World-controller
Additional analysis on the root cause:
The issue description says initialize() spawns a new headless bridge without closing the old one. Looking at the code pattern typical for bridge.cjs processes:
-
What happens: Each
initialize()call creates a new bridge.cjs subprocess. When called repeatedly (e.g., Hermes Agent reconnection, session recovery), old bridge processes remain running because there's no cleanup of the previous PID/file descriptor. -
Process table impact: On the 2-core 4GB Hermes Agent Linux environment described, 4+ bridge processes each consuming ~50-100MB RSS means 200-400MB of memory is wasted on zombie bridge processes. This directly impacts the memory budget available for LLM inference and embedding operations.
-
Suggested fix approach: Before spawning a new bridge.cjs process, the
initialize()method should:- Track the previous bridge PID (stored as
self._bridge_pid) - On re-initialization, send SIGTERM to the old PID and wait with a timeout
- If the process doesn't exit within the timeout, escalate to SIGKILL
- Only then spawn the new bridge process
- Track the previous bridge PID (stored as
-
Edge case to consider: If the bridge process is in the middle of writing state to disk (memory traces, cube data), a SIGKILL could corrupt the on-disk state. The retry logic should handle this gracefully by:
- First sending SIGTERM and waiting for graceful shutdown (2-3s)
- Checking if the data files are intact before completing initialization
- Falling back to a cold start (deleting and re-creating) only as last resort
This pattern is similar to PID file management used by httpd/nginx hot-reload and would be the right architecture for the bridge lifecycle.