apps-android-commons icon indicating copy to clipboard operation
apps-android-commons copied to clipboard

[Bug]: Uncleared CompositeDisposable in @Singleton UploadClient causes memory leak

Open himanchalkaushale opened this issue 4 weeks ago • 0 comments

Summary

UploadClient is an application-level @Singleton managed by Dagger. It maintains a shared CompositeDisposable:

private val compositeDisposable = CompositeDisposable()

Subscriptions for every uploaded file chunk are added to this collection at lines 87 and 173.

Root Cause

1. Disposable Retention

RxJava does not automatically remove completed subscriptions from a CompositeDisposable. Since cleanup only occurs in a narrow branch at line 91, completed observers can remain retained by the singleton, along with references to upload workers, contributions, and media-related objects.

Repeated uploads can therefore increase memory usage over time.

2. Cross-Upload Cancellation

compositeDisposable.clear()

The collection is shared across all uploads. Clearing it for one missing contribution can also cancel subscriptions belonging to other active uploads.

Affected Files

  • app/src/main/java/fr/free/nrw/commons/upload/UploadClient.kt (Lines 51, 87, 91, 173–196)

Steps to Reproduce

  1. Upload multiple photos or a large file split into chunks.
  2. Repeat uploads and allow them to complete.
  3. Inspect UploadClient.compositeDisposable using Android Studio Memory Profiler.
  4. Check for retained completed observers and their captured references.

Expected Behaviour

  • Subscriptions should be scoped to individual uploads.
  • Completed, failed, and cancelled subscriptions should be cleaned up.
  • Cancelling one upload should not affect other active uploads.

Actual Behaviour

  • Completed subscriptions remain referenced by the singleton's CompositeDisposable.
  • Repeated uploads can increase memory retention and memory pressure.
  • Clearing the shared collection can interrupt unrelated uploads.

Proposed Solution

  1. Remove the class-level shared CompositeDisposable from the @Singleton UploadClient.

  2. Scope subscriptions to individual upload operations:

    • Track active disposables separately for each upload operation using an appropriate thread-safe collection.
    • Ensure each upload has independent disposable management.
    • Clean up its disposable set when the upload completes, fails, or is cancelled, using doFinally or equivalent lifecycle handling.
    • Ensure cleanup for one upload does not affect other concurrent uploads.
  3. Add unit tests in UploadClientTest.kt to verify disposable cleanup and ensure cancelling one upload does not affect another.

himanchalkaushale avatar Nov 06 '26 20:11 himanchalkaushale