Skip to content

fix(observable_subscription): destroy native ROS subscription on destroy() - #1704

Merged
minggangw merged 2 commits into
RobotWebTools:developfrom
PierreSachot:fix/observable-subscription-destroy-leak
Nov 27, 2026
Merged

minggangw merged 2 commits into
RobotWebTools:developfrom
PierreSachot:fix/observable-subscription-destroy-leak

Conversation

@PierreSachot

@PierreSachot PierreSachot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ObservableSubscription.destroy() / .complete() only calls Subject.complete(). It never destroys the underlying native ROS 2 subscription created in Node.createObservableSubscription().

Any consumer that creates a new ObservableSubscription per reconnect and disposes of the previous one — for example a switchMap + share() wrapper whose finalize() calls obsSub.destroy(), driven by an RxJS timeout() + catchError() + repeat() pattern that detects a stalled topic — leaks one native subscription per reconnect cycle. Each leaked subscription keeps receiving and deserializing every message on the topic forever, with nothing listening to it. CPU usage climbs a little more on every reconnect and never comes back down.

Note: merely unsubscribing from RxJS (e.g. repeat() resubscribing to the same wrapper's .observable) never touches the native subscription either way — only an explicit destroy()/complete() call does. The leak only shows up once app code creates a fresh ObservableSubscription per cycle and relies on destroy() to free the old one, which is the pattern below.

Fix

Pass the owning Node into ObservableSubscription and call node.destroySubscription(subscription) from complete()/destroy(), in addition to completing the Subject. destroySubscription is already idempotent (guarded by the entity's isDestroyed()), so this is safe to call even if the node itself destroys the subscription later (e.g. via node.destroy()).

Reproduction

Minimal repro extracted from a real app that hit this (unrelated app internals mocked out). The switchMap/share/finalize wrapper is the part that actually creates a new ObservableSubscription on every reconnect and disposes of the previous one — this is what was missing from an earlier version of this repro:

import rclnodejs from 'rclnodejs';
import { defer, of, switchMap, share, finalize, timeout, catchError, repeat } from 'rxjs';

await rclnodejs.init();
const node = new rclnodejs.Node('repro_node');
node.spin();

const publisher = node.createPublisher('std_msgs/msg/String', 'state');

// Same shape apps build around createObservableSubscription(): a fresh native
// subscription is created on (re)subscribe and destroyed via finalize() once
// every downstream subscriber disconnects (share()'s refCounting).
const state$ = defer(() => of(node)).pipe(
  switchMap((n) => {
    const obsSub = n.createObservableSubscription('std_msgs/msg/String', 'state');
    return obsSub.observable.pipe(finalize(() => obsSub.destroy()));
  }),
  share()
);

// Mimic a client resetting state after a connection gap, e.g. at 20Hz with a
// 2s timeout. When the publisher stalls, timeout() errors, the sole
// subscriber to state$ drops to zero, share() tears down the current wrapper
// (finalize -> destroy), and repeat() resubscribes, making switchMap create a
// brand new native subscription.
state$
  .pipe(
    timeout(2000),
    catchError(() => of(undefined)),
    repeat({ delay: 2000 })
  )
  .subscribe((msg) => console.log('received:', msg?.data));

// Simulate the publisher going quiet for >2s and resuming, several times in a
// row (e.g. a dropped connection reconnecting). Before this fix, every gap
// leaves one more native subscription alive, still deserializing every
// message published below, with CPU usage increasing on every cycle.
let count = 0;
setInterval(() => publisher.publish({ data: `msg_${count++}` }), 50);

Before this fix, process CPU usage (e.g. via top/htop on the node process) increases by a roughly constant amount after every publish-gap/resume cycle, with no corresponding increase in subscriber count or log output — the extra work is happening in orphaned native subscriptions nobody is listening to.

Tests

Added two tests to test/test-observable-subscription.js:

  • destroy() also destroys the underlying native ROS subscription.
  • Repeated subscribe/destroy cycles on the same topic do not leak native subscriptions.

Both explicitly create a new ObservableSubscription and call .destroy() each cycle, matching the finalize()-driven disposal shown in the reproduction above (plain RxJS unsubscription alone wouldn't exercise this code path).

I don't have a ROS 2 environment set up in the sandbox I used to write this patch, so I wasn't able to run npm test locally — please let me know if CI surfaces anything and I'll fix it up.

…roy()

ObservableSubscription.destroy()/complete() only completed the RxJS
Subject wrapper; the underlying native ROS 2 subscription created by
createObservableSubscription() was never destroyed. Any code that
reconnects an observable subscription (e.g. an rxjs timeout()+repeat()
pattern resubscribing after a publisher gap) leaks one native
subscription per cycle, each still receiving and deserializing every
message forever, causing CPU usage to climb on every reconnect.

Pass the owning node into ObservableSubscription and call
node.destroySubscription() when the wrapper is destroyed.
Copilot AI balanced review requested due to automatic review settings November 26, 2026 10:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The reproduction only resubscribes to the same Subject rather than exercising cleanup, so it needs repeated wrapper creation, explicit disposal, and clarification that RxJS unsubscription alone does not release the native subscription.

1 open issue
What changed in this PR

This PR makes explicit disposal of an ObservableSubscription release its underlying native ROS 2 subscription, rather than only completing the RxJS Subject.

Changes:

  • Pass the owning node into each observable subscription wrapper.
  • Destroy the native subscription when complete() or destroy() is called.
  • Add regression tests for native cleanup and repeated creation/disposal cycles.
File Description
test/​test-observable-subscription.js Adds native cleanup and repeated-disposal regression tests.
lib/​observable_subscription.js Stores the owning node and releases the native subscription on completion.
lib/​node.js Passes the owning node to the observable subscription constructor.

Review effort: Balanced

if (!this.#destroyed) {
this.#destroyed = true;
this.#subject.complete();
this.#node.destroySubscription(this.#subscription);

@PierreSachot PierreSachot Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right — the original repro only resubscribed to the same wrapper's .observable via repeat(), so it never called destroy()/complete() and never actually created a second native subscription. Updated both:

  • PR description: the reproduction now wraps createObservableSubscription in a switchMap + share() + finalize(() => obsSub.destroy()) (the same shape the affected app code uses), so each timeout()/repeat() cycle creates a fresh wrapper and disposes of the previous one.
  • Test comment (now around test-observable-subscription.js:224): clarified that plain RxJS unsubscription never releases the native subscription either way, and that the leak only happens when app code creates a new ObservableSubscription per reconnect and relies on destroy() to free the old one — which is exactly what the two tests below exercise explicitly.

@coveralls

coveralls commented Nov 26, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 91.357% (+0.002%) from 91.355% — PierreSachot:fix/observable-subscription-destroy-leak into RobotWebTools:develop

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the change addressing native ROS 2 subscription leaks during disposal.

1 open issue

Review effort: Balanced

@minggangw minggangw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@PierreSachot Thanks for submitting the PR, LGTM!

@minggangw
minggangw merged commit 5fbe5d1 into RobotWebTools:develop Nov 27, 2026
13 checks passed
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.

4 participants