Skip to content

Add event listener memory leak detection tests #162

Closed

Description

@malibio

Problem Statement

Event listeners on document in modals could leak if cleanup fails. No tests verify cleanup happens correctly.

Leak Scenarios:

  • Component unmounted but listener remains
  • Rapid mount/unmount cycles accumulate listeners
  • Errors during unmount prevent cleanup
  • Reference cycles prevent garbage collection

Components With Document Listeners:

  • node-autocomplete.svelte:144 - document.addEventListener('keydown', ...)
  • slash-command-dropdown.svelte:110 - document.addEventListener('keydown', ...)

Why This Matters

Production Impact:

  • Memory usage grows over time
  • Performance degrades
  • Browser tab becomes unresponsive
  • Hard to debug (symptoms appear gradually)

File Locations (Monorepo Structure)

Test File to Create:

packages/desktop-app/src/tests/integration/event-listener-cleanup.test.ts

Components to Test (Full Import Paths):

import NodeAutocomplete from '$lib/components/ui/node-autocomplete/node-autocomplete.svelte';
import SlashCommandDropdown from '$lib/components/ui/slash-command-dropdown/slash-command-dropdown.svelte';

Actual File Paths:

  • packages/desktop-app/src/lib/components/ui/node-autocomplete/node-autocomplete.svelte
  • packages/desktop-app/src/lib/components/ui/slash-command-dropdown/slash-command-dropdown.svelte

EventBus Reference:

  • packages/desktop-app/src/lib/services/eventBus.ts

Acceptance Criteria

Component Lifecycle Tests (6 tests)

  • NodeAutocomplete removes keydown listener on unmount

    • Verify removeEventListener called with exact same handler
    • Normal unmount scenario (happy path)
  • SlashCommandDropdown removes keydown listener on unmount

    • Verify removeEventListener called with exact same handler
    • Normal unmount scenario (happy path)
  • Multiple mount/unmount cycles don't accumulate listeners

    • Mount and unmount 100 times
    • Verify listener count returns to baseline
    • Test both components
  • Listeners removed even if error during unmount

    • Simulate error in onDestroy lifecycle
    • Verify cleanup still happens (or handler is weak)
    • Edge case but important for robustness

Rapid Operations Tests (3 tests)

  • 100 rapid mount/unmount cycles - NodeAutocomplete

    • Verify no listener accumulation
    • Memory usage acceptable
  • 100 rapid mount/unmount cycles - SlashCommandDropdown

    • Verify no listener accumulation
    • Memory usage acceptable
  • Concurrent mount/unmount of both components

    • Verify no interference between components
    • Each cleans up only its own listeners

EventBus Subscription Tests (3 tests)

  • Unsubscribe actually removes handler

    • Subscribe to event
    • Unsubscribe
    • Verify handler count decrements
  • No handlers remain after reset()

    • Subscribe to multiple events
    • Call eventBus.reset()
    • Verify all handlers cleared
  • Wildcard subscriptions cleaned up

    • Subscribe to '*' (all events)
    • Unsubscribe
    • Verify wildcard handler removed

Verification Tools (2 tests)

  • Can detect leaked listeners programmatically

    • Spy on addEventListener/removeEventListener
    • Count additions vs removals
    • Detect imbalance
  • Can measure handler count accurately

    • Use EventBus.getMetrics()
    • Use EventBus.getSubscriberCounts()
    • Verify counts are accurate

Detailed Implementation

Test Structure

// packages/desktop-app/src/tests/integration/event-listener-cleanup.test.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render } from '@testing-library/svelte';
import NodeAutocomplete from '$lib/components/ui/node-autocomplete/node-autocomplete.svelte';
import SlashCommandDropdown from '$lib/components/ui/slash-command-dropdown/slash-command-dropdown.svelte';
import { eventBus } from '$lib/services/eventBus';

describe('Event Listener Memory Leak Detection', () => {
  let addEventListenerSpy: ReturnType<typeof vi.spyOn>;
  let removeEventListenerSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    // Spy on document event listeners
    addEventListenerSpy = vi.spyOn(document, 'addEventListener');
    removeEventListenerSpy = vi.spyOn(document, 'removeEventListener');
    
    // Reset EventBus
    eventBus.reset();
  });

  afterEach(() => {
    // Clean up spies
    addEventListenerSpy.mockRestore();
    removeEventListenerSpy.mockRestore();
  });

  describe('Component Lifecycle', () => {
    it('should remove keydown listener when NodeAutocomplete unmounts', () => {
      const { unmount } = render(NodeAutocomplete, {
        props: {
          visible: true,
          results: [],
          position: { x: 0, y: 0 }
        }
      });

      // Verify listener was added
      expect(addEventListenerSpy).toHaveBeenCalledWith('keydown', expect.any(Function));
      
      // Get the handler that was added
      const addCalls = addEventListenerSpy.mock.calls;
      const keydownCall = addCalls.find(call => call[0] === 'keydown');
      const addedHandler = keydownCall?.[1];

      unmount();

      // Verify same handler was removed
      expect(removeEventListenerSpy).toHaveBeenCalledWith('keydown', addedHandler);
    });

    it('should remove keydown listener when SlashCommandDropdown unmounts', () => {
      const { unmount } = render(SlashCommandDropdown, {
        props: {
          visible: true,
          commands: [],
          position: { x: 0, y: 0 }
        }
      });

      expect(addEventListenerSpy).toHaveBeenCalledWith('keydown', expect.any(Function));
      
      const addCalls = addEventListenerSpy.mock.calls;
      const keydownCall = addCalls.find(call => call[0] === 'keydown');
      const addedHandler = keydownCall?.[1];

      unmount();

      expect(removeEventListenerSpy).toHaveBeenCalledWith('keydown', addedHandler);
    });

    it('should not accumulate listeners after 100 mount/unmount cycles', () => {
      const initialAddCount = addEventListenerSpy.mock.calls.length;
      const initialRemoveCount = removeEventListenerSpy.mock.calls.length;

      // Mount and unmount 100 times
      for (let i = 0; i < 100; i++) {
        const { unmount } = render(NodeAutocomplete, {
          props: {
            visible: true,
            results: [],
            position: { x: 0, y: 0 }
          }
        });
        unmount();
      }

      const finalAddCount = addEventListenerSpy.mock.calls.length;
      const finalRemoveCount = removeEventListenerSpy.mock.calls.length;

      // Net change should be zero (all adds matched by removes)
      const netAdds = finalAddCount - initialAddCount;
      const netRemoves = finalRemoveCount - initialRemoveCount;

      expect(netAdds).toBe(netRemoves);
      expect(netAdds).toBe(100); // 100 adds
      expect(netRemoves).toBe(100); // 100 removes
    });

    it('should cleanup listeners even if error during unmount', () => {
      // This tests robustness - if onDestroy throws, does cleanup still happen?
      // For Svelte components, onDestroy is called during teardown
      // We'll verify the listener removal happens regardless

      const { unmount } = render(NodeAutocomplete, {
        props: {
          visible: true,
          results: [],
          position: { x: 0, y: 0 }
        }
      });

      const addedHandler = addEventListenerSpy.mock.calls.find(
        call => call[0] === 'keydown'
      )?.[1];

      // Unmount (which calls cleanup)
      unmount();

      // Even if there were errors, cleanup should have happened
      expect(removeEventListenerSpy).toHaveBeenCalledWith('keydown', addedHandler);
    });
  });

  describe('Rapid Operations', () => {
    it('should handle 100 rapid mount/unmount cycles for NodeAutocomplete', () => {
      const baseline = addEventListenerSpy.mock.calls.length;

      for (let i = 0; i < 100; i++) {
        const { unmount } = render(NodeAutocomplete, {
          props: { visible: true, results: [], position: { x: 0, y: 0 } }
        });
        unmount();
      }

      // Verify balanced adds/removes
      const totalAdds = addEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length - baseline;
      
      const totalRemoves = removeEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length;

      expect(totalAdds).toBe(totalRemoves);
    });

    it('should handle 100 rapid mount/unmount cycles for SlashCommandDropdown', () => {
      const baseline = addEventListenerSpy.mock.calls.length;

      for (let i = 0; i < 100; i++) {
        const { unmount } = render(SlashCommandDropdown, {
          props: { visible: true, commands: [], position: { x: 0, y: 0 } }
        });
        unmount();
      }

      const totalAdds = addEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length - baseline;
      
      const totalRemoves = removeEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length;

      expect(totalAdds).toBe(totalRemoves);
    });

    it('should handle concurrent mount/unmount of both components', () => {
      const baseline = addEventListenerSpy.mock.calls.length;

      // Mount both
      const autocomplete = render(NodeAutocomplete, {
        props: { visible: true, results: [], position: { x: 0, y: 0 } }
      });
      const dropdown = render(SlashCommandDropdown, {
        props: { visible: true, commands: [], position: { x: 0, y: 0 } }
      });

      // Should have 2 keydown listeners added
      const afterMount = addEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length;
      expect(afterMount - baseline).toBe(2);

      // Unmount both
      autocomplete.unmount();
      dropdown.unmount();

      // Should have removed both
      const removed = removeEventListenerSpy.mock.calls.filter(
        call => call[0] === 'keydown'
      ).length;
      expect(removed).toBe(2);
    });
  });

  describe('EventBus Subscriptions', () => {
    it('should remove handler when unsubscribe is called', () => {
      const handler = vi.fn();
      const unsubscribe = eventBus.subscribe('node:updated', handler);

      let counts = eventBus.getSubscriberCounts();
      expect(counts['node:updated']).toBe(1);

      unsubscribe();

      counts = eventBus.getSubscriberCounts();
      expect(counts['node:updated']).toBeUndefined();
    });

    it('should clear all handlers after reset()', () => {
      eventBus.subscribe('node:updated', vi.fn());
      eventBus.subscribe('node:created', vi.fn());
      eventBus.subscribe('*', vi.fn());

      let counts = eventBus.getSubscriberCounts();
      expect(Object.keys(counts).length).toBeGreaterThan(0);

      eventBus.reset();

      counts = eventBus.getSubscriberCounts();
      expect(Object.keys(counts).length).toBe(0);
    });

    it('should cleanup wildcard subscriptions', () => {
      const handler = vi.fn();
      const unsubscribe = eventBus.subscribe('*', handler);

      let counts = eventBus.getSubscriberCounts();
      expect(counts['*']).toBe(1);

      unsubscribe();

      counts = eventBus.getSubscriberCounts();
      expect(counts['*']).toBeUndefined();
    });
  });

  describe('Verification Tools', () => {
    it('should detect leaked listeners programmatically', () => {
      const getListenerBalance = () => {
        const adds = addEventListenerSpy.mock.calls.filter(
          call => call[0] === 'keydown'
        ).length;
        const removes = removeEventListenerSpy.mock.calls.filter(
          call => call[0] === 'keydown'
        ).length;
        return adds - removes;
      };

      // Initially balanced
      expect(getListenerBalance()).toBe(0);

      // Mount without unmounting - creates leak
      render(NodeAutocomplete, {
        props: { visible: true, results: [], position: { x: 0, y: 0 } }
      });

      // Now imbalanced (leak detected)
      expect(getListenerBalance()).toBe(1);
    });

    it('should accurately measure EventBus handler count', () => {
      const metrics1 = eventBus.getMetrics();
      const initialCount = metrics1.totalHandlers;

      const unsub1 = eventBus.subscribe('node:updated', vi.fn());
      const unsub2 = eventBus.subscribe('node:created', vi.fn());

      const metrics2 = eventBus.getMetrics();
      expect(metrics2.totalHandlers).toBe(initialCount + 2);

      unsub1();

      const metrics3 = eventBus.getMetrics();
      expect(metrics3.totalHandlers).toBe(initialCount + 1);

      unsub2();

      const metrics4 = eventBus.getMetrics();
      expect(metrics4.totalHandlers).toBe(initialCount);
    });
  });
});

Scope Clarification

Normal vs Error Scenarios

Primary Focus: Normal Cleanup (12 of 14 tests)

  • Verify cleanup works in standard unmount flow
  • This is what happens 99.99% of the time

Secondary: Error Resilience (2 of 14 tests)

  • Verify cleanup happens even if errors occur
  • Edge case but important for robustness
  • Don't need to simulate complex errors
  • Just verify cleanup is resilient

Implementation:

it('should cleanup listeners even if error during unmount', () => {
  // For Svelte, onDestroy cleanup runs during component teardown
  // Even if user code throws, Svelte's cleanup should still run
  // We verify the listener removal happens regardless
  
  const { unmount } = render(NodeAutocomplete, { /* ... */ });
  const addedHandler = /* capture handler */;
  
  unmount(); // May or may not have errors internally
  
  // Cleanup should have happened either way
  expect(removeEventListenerSpy).toHaveBeenCalledWith('keydown', addedHandler);
});

Dependencies

Requires:

Blocks: None (can be implemented independently)

Definition of Done

  • Test file created at packages/desktop-app/src/tests/integration/event-listener-cleanup.test.ts
  • All 14 test cases implemented and passing
  • Correct import paths using SvelteKit aliases ($lib/...)
  • Both normal and error scenarios tested
  • bun run test -- event-listener-cleanup.test.ts passes
  • No console errors or warnings
  • Code review approved

Estimated Effort

2-3 hours - Focused test suite with clear patterns

Priority

Medium-High - Important for production stability

Reference Materials

Component Locations:

  • packages/desktop-app/src/lib/components/ui/node-autocomplete/node-autocomplete.svelte:144
  • packages/desktop-app/src/lib/components/ui/slash-command-dropdown/slash-command-dropdown.svelte:110

EventBus API:

  • eventBus.subscribe() - Returns unsubscribe function
  • eventBus.reset() - Clears all subscriptions
  • eventBus.getMetrics() - Returns handler count
  • eventBus.getSubscriberCounts() - Returns counts by event type

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions