Skip to content

Memory leak: activeGenerations Map never cleaned up on success #47

Description

@cubrift

Issue

The activeGenerations Map in messages/ai/MessageAI.js (lines 22, 57-63) can grow unbounded and never be cleaned up after failed or aborted operations, leading to memory leaks.

Current code:

const activeGenerations = new Map();

// ... later ...
const controller = new AbortController();
activeGenerations.set(jid, controller);  // Added every time

// ... at end of function when aborted:
if (activeGenerations.get(jid) === controller)
  activeGenerations.delete(jid);

Problem

  1. Memory Leak: If a message stream completes successfully, the controller is never removed from the Map
  2. Per-chat leak: Every chat that gets a message keeps its controller in memory indefinitely
  3. Map growth: Over time with many conversations, the Map grows without bound
  4. Old references: Stale controllers accumulate even though they're no longer needed

Impact

  • Memory Usage: Continuous memory growth as more chats receive messages
  • Performance Degradation: Map lookups slow down as size increases
  • Long-running Instability: Bot becomes slow/unresponsive after days/weeks of operation

Suggested Fix

Clean up the controller after the message generation completes (success or failure):

async function messageAI(sock, msg, polls) {
  // ... existing code ...
  
  const controller = new AbortController();
  activeGenerations.set(jid, controller);
  
  try {
    // ... existing message handling code ...
  } catch (error) {
    logger.error(error, "Error in messageAI");
  } finally {
    // Always clean up the controller
    if (activeGenerations.get(jid) === controller) {
      activeGenerations.delete(jid);
    }
  }
}

Alternatively, use a cleanup timer:

const controller = new AbortController();
activeGenerations.set(jid, controller);

// Auto-cleanup after 5 minutes if not manually cleaned
const cleanup = setTimeout(() => {
  if (activeGenerations.get(jid) === controller) {
    activeGenerations.delete(jid);
  }
}, 5 * 60 * 1000);

// ... at successful completion:
clearTimeout(cleanup);
activeGenerations.delete(jid);

Affected File

  • messages/ai/MessageAI.js:22, 57-63, 143+

Type

Bug - memory leak from unbounded Map growth

Metadata

Metadata

Assignees

Labels

codexUse for codex-generated issues only.enhancementPerformance update or requestgood first issueGood for newcomers

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions