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
- Memory Leak: If a message stream completes successfully, the controller is never removed from the Map
- Per-chat leak: Every chat that gets a message keeps its controller in memory indefinitely
- Map growth: Over time with many conversations, the Map grows without bound
- 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
Issue
The
activeGenerationsMap inmessages/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:
Problem
Impact
Suggested Fix
Clean up the controller after the message generation completes (success or failure):
Alternatively, use a cleanup timer:
Affected File
messages/ai/MessageAI.js:22, 57-63, 143+Type
Bug - memory leak from unbounded Map growth