Skip to content

mergeMap with concurrency and synchronous inner observables leads to a memory leak and outer observable never completes. #7334

Open
@jonapgar-groupby

Description

@jonapgar-groupby

Describe the bug

A memory leak occurs when using mergeMap with a concurrency and a synchronous inner observable, apparently due to the nested try-catch in the doInner function.

Somewhat relates to #3609 but isn't the exact same bug.

In this case, you don't actually get the RangeError, and instead receive no feedback at all, it appears the observable just hangs (despite the source and the inner observables all completing).

You can prevent this error by editing the mergeInternals doInnerSub function to not reference the subscriber in the catch.

https://github.com/ReactiveX/rxjs/blob/7.8.1/src/internal/operators/mergeInternals.ts#L100-L128

You can actually leave the try-catch in place, simply commenting out that subscriber reference is enough to prevent the memory leak.

This suggests that the issue is a memory leak due to the way nodejs is holding on to the reference to subscriber in case there is an error (forgive me for not being to articulate that more clearly :p )

Expected behavior

No memory leak should occur

Reproduction code

import { EMPTY, from, timer } from 'rxjs';
import { finalize, last, mergeMap } from 'rxjs/operators';

let i = 0;
from(Array(600).keys())
  .pipe(
    mergeMap(
      (n) =>
        (n < 100 ? timer(0) : EMPTY).pipe(
          finalize(() => console.log(++i, 'inner complete')),
        ),
      10,
    ),
    last(),
    finalize(() => console.log('outer complete')),
  )
  .subscribe({
    next: (v) => console.log(),
    error: (err) => console.error(err),
  });

You may have to tweak the size of the initial Array to reproduce the error.



### Reproduction URL

https://rxjs-playground-test-1kzutu.stackblitz.io

### Version

7.8.1

### Environment

node v18.15.0

### Additional context

_No response_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions