---
name: memory-leak-guard
description: "Scans XINGZIER AI codebase for memory leaks and fixes them. Invoke when backend OOM crashes, memory usage grows, or user says 'memory leak' / '内存泄漏'. | 扫描XINGZIER AI代码库的内存泄漏并修复。当后端OOM崩溃、内存使用增长，或用户说'内存泄漏'时触发。"
metadata:
  {
    "builtin_skill_version": "1.0",
    "xingzierai":
      {
        "emoji": "🛡️",
        "requires": {}
      }
  }
---
# Memory Leak Guard

Systematically scan the XINGZIER AI codebase for memory leaks, diagnose root causes, and apply fixes.

## When to Invoke

- Backend crashes with OOM (Out of Memory)
- Memory usage grows continuously without stabilizing
- User reports "内存泄漏" or "memory leak"
- Periodic health check (every few days)
- After adding new features that involve caching or stateful objects

## Known Leak Patterns (27 found in audit)

### HIGH Priority - Infinite Growth Data Structures

| # | Module | Variable | Fix |
|---|--------|----------|-----|
| 1 | cross_session_memory.py | `_entries` | MAX_ENTRIES=5000 + expired cleanup |
| 2 | outcomes_evaluator.py | `_records` | Truncate to 500 after persist |
| 3 | orchestrator.py | `_running_tasks` | Clean completed tasks (max 100) |
| 4 | blackboard.py | `_entries` | Add max entries + default TTL |
| 5 | priority_queue.py | `_completed_tasks` | Periodic cleanup |
| 6 | orchestrator_workers.py | `_orchestrations` | Limit to 100 recent |
| 7 | orchestrator_workers.py | `_tasks/_results` | Clean after orchestration |
| 8 | online_metrics.py | `_pending` | 5min timeout cleanup |

### MEDIUM Priority

| # | Module | Variable | Fix |
|---|--------|----------|-----|
| 9 | mdrm.py | `_graphs` | Add graph size limit |
| 10 | adaptive_learner.py | `feedback_list` | Truncate after save |
| 11 | managed_agent.py | `_harnesses` | Idle timeout cleanup |
| 12 | evolution_bridges.py | `_st_model` | ~400MB, add idle release |

### LOW Priority

| # | Module | Variable | Fix |
|---|--------|----------|-----|
| 13 | routing_history.py | `records` | Has 10000 limit |
| 14 | agent_monitor.py | `_agent_status` | Clean offline agents |
| 15 | process_manager.py | `_log_file_handle` | Close after process ends |

## Diagnostic Procedure

### Phase 1: Quick Memory Check

```bash
ps aux | grep uvicorn | grep -v grep | awk '{print "MEM:", $6/1024, "MB"}'
vm_stat | head -5
```

### Phase 2: Identify Growing Data Structures

Search for these patterns:

```bash
grep -rn "self\._[a-z]*: Dict\|self\._[a-z]*: List" src/xingzierai/ | grep -v "maxsize\|maxlen\|MAX_"
grep -rn "asyncio.create_task" src/xingzierai/ | grep -v "add_done_callback\|_background_tasks"
grep -rn "@lru_cache\b" src/xingzierai/ | grep -v "maxsize"
```

### Phase 3: Apply Fix Template

For infinite-growth dicts/lists:

```python
MAX_ENTRIES = 5000

def _cleanup_oversized(self):
    if len(self._entries) > self.MAX_ENTRIES:
        sorted_entries = sorted(
            self._entries.items(),
            key=lambda x: getattr(x[1], 'importance', 0),
        )
        remove_count = len(self._entries) - self.MAX_ENTRIES
        for key, _ in sorted_entries[:remove_count]:
            del self._entries[key]
```

For untracked asyncio tasks:

```python
self._background_tasks: set = set()
task = asyncio.create_task(some_coroutine())
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
```

### Phase 4: Verify Fix

Monitor memory over 20 rounds of chat requests to confirm stabilization.

## Prevention Rules

1. **Every Dict/List that grows must have a MAX constant and cleanup logic**
2. **Every asyncio.create_task must be tracked with add_done_callback**
3. **Every open() must be in a with statement or have explicit close()**
4. **Every cache must have maxsize or TTL**
5. **Every session/conversation data must have expiry or max count**
6. **Run this skill after adding any new caching or stateful feature**

## File Paths Reference

| Component | Path |
|-----------|------|
| CrossSessionMemory | `src/xingzierai/agents/cross_session_memory.py` |
| OutcomeTracker | `src/xingzierai/agents/outcomes_evaluator.py` |
| OrgOrchestrator | `src/xingzierai/org/orchestrator.py` |
| OrgBlackboard | `src/xingzierai/org/blackboard.py` |
| PriorityQueue | `src/xingzierai/agents/priority_queue.py` |
| OrchestratorWorkers | `src/xingzierai/agents/orchestrator_workers.py` |
| MDRMStore | `src/xingzierai/memory/mdrm.py` |
| TTFTTracker | `src/xingzierai/telemetry/online_metrics.py` |
| AdaptiveLearner | `src/xingzierai/agents/adaptive_learner.py` |
| ManagedAgent | `src/xingzierai/agents/managed_agent.py` |
| ProcessManager | `src/xingzierai/agentscope_runtime/engine/deployers/utils/service_utils/process_manager.py` |
