Skip to content

Fix subscription cleanup leak in ReactiveNodeService - #645

Merged
malibio merged 2 commits into
mainfrom
feature/issue-640-fix-subscription-leak
Nov 23, 2025
Merged

malibio merged 2 commits into
mainfrom
feature/issue-640-fix-subscription-leak

Conversation

@malibio

@malibio malibio commented Nov 23, 2025

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes memory leak where subscribeAll() subscriptions were never unsubscribed when viewer unmounts
  • Adds destroy() method to ReactiveNodeService for proper cleanup
  • Calls cleanup in NodeServiceContext's onDestroy lifecycle hook

Problem

ReactiveNodeService had a subscription cleanup leak where subscribeAll() subscriptions were never unsubscribed when the viewer unmounts (Issue #640).

Impact:

  • Memory leak: 1 subscription per mounted viewer accumulates
  • Example: Open/close same pane 100 times = 100 active subscriptions
  • All those subscriptions continue receiving callbacks, causing unnecessary processing

Solution

  1. Store the unsubscribe function returned by subscribeAll()
  2. Add destroy() method that calls unsubscribe when service is no longer needed
  3. Call destroy() in NodeServiceContext's onDestroy callback

Test plan

  • Added 7 new tests verifying cleanup behavior
  • Verified destroy() properly cleans up subscription
  • Verified destroy() is safe to call multiple times
  • Verified no memory leak after 100 mount/unmount cycles
  • Verified callbacks stop firing after destroy()
  • All existing tests pass (1431 passed, 3 pre-existing failures unrelated to this change)
  • Quality checks pass

Test Results

Baseline (before changes): Frontend: 1424 passed, 3 failed
After changes: Frontend: 1431 passed, 3 failed (+7 new tests, same failures)

Closes #640

🤖 Generated with Claude Code

## Changes
- Store the unsubscribe function from `subscribeAll()` in a trackable variable
- Add `destroy()` method to ReactiveNodeService that calls the unsubscribe function
- Call `destroy()` in NodeServiceContext's onDestroy lifecycle hook

## Impact
- Prevents 1 subscription per mount from accumulating
- Fixes memory leak when opening/closing panes repeatedly
- No more unnecessary callback processing from orphaned subscriptions

## Testing
- Added 7 new tests verifying cleanup behavior:
  - destroy() properly cleans up subscription
  - destroy() is safe to call multiple times
  - No memory leak after 100 mount/unmount cycles
  - Callbacks stop firing after destroy()
  - Subscription accumulation prevention tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Nov 23, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Report - PR #645

Review Type: Initial Review
Reviewer: Principal Engineer AI (Pragmatic Quality Framework)
Branch: feature/issue-640-fix-subscription-leak


Summary Assessment

This PR fixes a genuine memory leak in ReactiveNodeService where subscribeAll() subscriptions were never cleaned up on component unmount. The implementation is clean, well-tested, and follows established patterns. Recommended for approval.


Requirements Check (Issue #640)

Acceptance Criterion Status Notes
Store the unsubscribe function returned by subscribeAll() ✅ Stored in _subscriptionUnsubscribe variable
Call unsubscribe when ReactiveNodeService is destroyed ✅ destroy() method properly calls unsubscribe
Add test verifying subscription is cleaned up on unmount ✅ 7 comprehensive tests added
Verify no memory leak after repeated mount/unmount cycles ✅ Test verifies 100 mount/unmount cycles

All acceptance criteria satisfied.


Code Review Findings

Critical Issues

None identified.

Suggested Improvements

1. [Improvement] Consider clearing pending debounced operations on destroy()

📁 packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:1114-1118

The destroy() method only cleans up the subscription, but there could be pending debounced operations (fast/expensive timers) that continue to run after the service is destroyed. While not a memory leak per se, these could cause issues if they reference stale state.

destroy() {
  if (_subscriptionUnsubscribe) {
    _subscriptionUnsubscribe();
    _subscriptionUnsubscribe = null;
  }
  // Consider: Clear all debounced operations
  // for (const [nodeId] of debouncedOperations) {
  //   cleanupDebouncedOperations(nodeId);
  // }
  // debouncedOperations.clear();
}

Rationale (YAGNI Consideration): This is a minor concern for this PR's scope. The debounced operations have short timeouts (300ms, 2000ms) and the callbacks check if the node exists before proceeding. Marking as suggestion for future consideration.

2. [Nit] JSDoc could mention idempotency guarantee

📁 packages/desktop-app/src/lib/services/reactive-node-service.svelte.ts:1109-1113

The JSDoc mentions it "MUST be called" but doesn't mention that it's safe to call multiple times. The tests verify this behavior, but documenting it in the JSDoc would be helpful:

/**
 * Cleanup method to prevent subscription memory leaks.
 * MUST be called when the service instance is no longer needed (e.g., on component unmount).
 * Safe to call multiple times (idempotent).
 * Failing to call this will result in subscription accumulation and unnecessary processing.
 */

Nitpicks

Nit: Test file has mock setup that could be shared

📁 packages/desktop-app/src/tests/services/subscription-cleanup.test.ts:14-31

The Svelte 5 rune mocks are repeated from other test files. Consider extracting to a shared test helper for consistency. However, this is a common pattern across the codebase, so not blocking.


Architecture & Design Assessment

Aspect Rating Notes
Single Responsibility ✅ Excellent Change is focused solely on cleanup
Modularity ✅ Good Clean separation between service and context
Backward Compatibility ✅ Good New destroy() method doesn't break existing API
Error Handling ✅ Good Null check prevents double-unsubscribe errors

Testing Assessment

Aspect Rating Notes
Coverage ✅ Excellent 7 new tests covering all scenarios
Edge Cases ✅ Excellent Tests idempotency, ordering, accumulation
Regression Prevention ✅ Excellent "100 mount/unmount cycles" test directly prevents regression

Security Assessment

No security concerns - this is internal state management with no external inputs.

Performance Assessment

✅ Positive Impact - Prevents subscription accumulation which would cause O(n) callback processing where n = mount count.


Test Results Verification

  • Baseline (before changes): 1424 passed, 3 failed
  • After changes: 1431 passed, 3 failed
  • Delta: +7 new tests, 0 regressions
  • Pre-existing failures: Unrelated to this change (confirmed)

Final Recommendation

✅ APPROVE

This PR demonstrates excellent engineering practice:

  1. Atomic fix - Single issue, focused solution
  2. Comprehensive testing - Edge cases covered, regression prevention
  3. Clean implementation - No unnecessary complexity
  4. Good documentation - Issue reference in comments, clear JSDoc

The suggested improvements are minor polish and do not block merge.


🤖 Review generated with Claude Code

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Recommendation: APPROVE - Clean, well-tested fix for subscription memory leak. All acceptance criteria met. See detailed review comment above for minor suggestions.

Added "Safe to call multiple times (idempotent)" to the destroy() method
documentation, as suggested in code review.

Addresses reviewer recommendation from PR #645.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Nov 23, 2025

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

Summary of Changes:

✅ Addressed (1 recommendation)

Recommendation Action
JSDoc could mention idempotency guarantee Added "Safe to call multiple times (idempotent)" to destroy() JSDoc

⏭️ Skipped (2 recommendations)

Recommendation Reason
Consider clearing pending debounced operations on destroy() Reviewer marked as YAGNI - callbacks already check if nodes exist, timeouts are short (300ms-2000ms). Would be scope creep for this bug fix.
Extract shared test mock setup Reviewer noted "not blocking" and it's a common pattern across codebase. Should be its own refactoring issue, not part of this bug fix.

Commits: 1 (3176f65)
Tests: No new tests needed (documentation-only change)
Quality Checks: Passed

🤖 Generated with Claude Code

@malibio
malibio merged commit 3efd1ab into main Nov 23, 2025
@malibio
malibio deleted the feature/issue-640-fix-subscription-leak branch November 23, 2025 23:40
malibio added a commit that referenced this pull request Feb 4, 2026
* Fix subscription cleanup leak in ReactiveNodeService (closes #640)

## Changes
- Store the unsubscribe function from `subscribeAll()` in a trackable variable
- Add `destroy()` method to ReactiveNodeService that calls the unsubscribe function
- Call `destroy()` in NodeServiceContext's onDestroy lifecycle hook

## Impact
- Prevents 1 subscription per mount from accumulating
- Fixes memory leak when opening/closing panes repeatedly
- No more unnecessary callback processing from orphaned subscriptions

## Testing
- Added 7 new tests verifying cleanup behavior:
  - destroy() properly cleans up subscription
  - destroy() is safe to call multiple times
  - No memory leak after 100 mount/unmount cycles
  - Callbacks stop firing after destroy()
  - Subscription accumulation prevention tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Add idempotency documentation to destroy() JSDoc

Added "Safe to call multiple times (idempotent)" to the destroy() method
documentation, as suggested in code review.

Addresses reviewer recommendation from PR #645.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Fix subscription cleanup leak in ReactiveNodeService (closes #640)

## Changes
- Store the unsubscribe function from `subscribeAll()` in a trackable variable
- Add `destroy()` method to ReactiveNodeService that calls the unsubscribe function
- Call `destroy()` in NodeServiceContext's onDestroy lifecycle hook

## Impact
- Prevents 1 subscription per mount from accumulating
- Fixes memory leak when opening/closing panes repeatedly
- No more unnecessary callback processing from orphaned subscriptions

## Testing
- Added 7 new tests verifying cleanup behavior:
  - destroy() properly cleans up subscription
  - destroy() is safe to call multiple times
  - No memory leak after 100 mount/unmount cycles
  - Callbacks stop firing after destroy()
  - Subscription accumulation prevention tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Add idempotency documentation to destroy() JSDoc

Added "Safe to call multiple times (idempotent)" to the destroy() method
documentation, as suggested in code review.

Addresses reviewer recommendation from PR #645.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Fix subscription cleanup leak in ReactiveNodeService (closes #640)

## Changes
- Store the unsubscribe function from `subscribeAll()` in a trackable variable
- Add `destroy()` method to ReactiveNodeService that calls the unsubscribe function
- Call `destroy()` in NodeServiceContext's onDestroy lifecycle hook

## Impact
- Prevents 1 subscription per mount from accumulating
- Fixes memory leak when opening/closing panes repeatedly
- No more unnecessary callback processing from orphaned subscriptions

## Testing
- Added 7 new tests verifying cleanup behavior:
  - destroy() properly cleans up subscription
  - destroy() is safe to call multiple times
  - No memory leak after 100 mount/unmount cycles
  - Callbacks stop firing after destroy()
  - Subscription accumulation prevention tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Add idempotency documentation to destroy() JSDoc

Added "Safe to call multiple times (idempotent)" to the destroy() method
documentation, as suggested in code review.

Addresses reviewer recommendation from PR #645.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix subscription cleanup leak in ReactiveNodeService

1 participant