Skip to content

fix(storage): keep tasks alive when snapshotEvents listeners cancel, and scope Android task registries per engine - #18839

Draft
Lyokone wants to merge 3 commits into
mainfrom
fix/storage-task-lifecycle
Draft

Lyokone wants to merge 3 commits into
mainfrom
fix/storage-task-lifecycle

Conversation

@Lyokone

@Lyokone Lyokone commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Two firebase_storage task lifecycle bugs, both reproduced on main.

1. Cancelling the last snapshotEvents listener cancelled the task, and await task then hung (all native platforms).
MethodChannelTask exposed asBroadcastStream(onCancel: (sub) => sub.cancel()), so when the app's only listener went away (snapshotEvents.first, or a StreamBuilder in a progress dialog that closes), the native event stream was cancelled for good:

  • on Android, TaskStateChannelStreamHandler.onCancel then called androidTask.cancel(), so the upload was silently cancelled;
  • a later await task listened to the already-finished stream: .last threw "No element", the error was swallowed and onComplete never completed (on iOS the upload finishes, but Dart never hears about it).

It only shows when nothing else is listening at that moment, e.g. when the app awaits the task after the dialog closed.

Fix:

  • Dart: one internal subscription, which user cancels can't stop, now drives snapshot and onComplete. Users get a separate broadcast stream. onComplete also fails, instead of hanging, if the native stream closes without a final state or the task fails to start (that error is now a FirebaseException).
  • Android: onCancel only stops sending events. The task keeps running, can still be paused, resumed or cancelled by handle, and its listeners still release it when it ends.

2. Android task and channel registries were static, so engines shared them.
inProgressTasks (in FlutterFirebaseStorageTask) and eventChannels / streamHandlers (in FlutterFirebaseStoragePlugin's companion) were shared by every engine. When a background engine (workmanager and similar) detached, its onDetachedFromEngine cancelled the main engine's uploads and removed its event channels, so the main engine's await task hung. Handles come from a per-isolate Dart counter that starts at 0, so tasks from two engines also overwrote each other. #18255 fixed only the crash.

Fix: each plugin instance owns its registries (FlutterFirebaseStorageTaskRegistry for tasks), so detaching an engine only cancels its own tasks and removes its own channels. Removing a finished task doesn't evict a newer task that reused its handle.

Behaviour change (Android)

Disposing a StreamBuilder, a rebuild, or await for … break no longer cancels the upload or download. The task runs until it ends or task.cancel() is called, as on iOS and web. A paused task the app forgets is kept for the life of the process. This is also in the commit body so it reaches the CHANGELOG.

Known limitations (not changed here)

  • Dev only: firebase_core's static FlutterFirebasePluginRegistry keeps only the last plugin instance. After a background engine attaches, a hot restart of the main engine no longer cancels the main engine's tasks, and may cancel the background engine's instead.
  • TaskState.canceled doesn't complete a pending onComplete, and after a failed start task.snapshot.state stays running. Both predate this PR, and no native platform sends canceled today.
  • Background isolates in the same engine share one plugin instance and number their tasks from 0, so their handles can still collide. This predates the PR.

Coordination

Tests

  • Dart unit tests (firebase_storage_platform_interface/test/method_channel_tests/method_channel_task_test.dart, 9 tests):

    • cancelling the only listener doesn't cancel the native stream;
    • onComplete resolves after that;
    • a new listener still gets events;
    • onComplete and snapshotEvents fail when the native stream closes early;
    • onComplete fails when the task fails to start;
    • plus 3 regression tests: errors reach both the stream and onComplete, an error with no listener only fails onComplete, and a late listener gets done.

    The first 6 fail on main (hang or wrong count), and all 9 pass with this change.

  • Android JUnit (FlutterFirebaseStorageTaskRegistryTest, 3 tests, added to android-unit-tests): the same handle in two engines doesn't collide, removeAll only affects its own engine, and a stale remove keeps a newer task with the same handle. They cover the new class, so they can't run on main; the e2e test below is the before/after check.

  • e2e (example/integration_test/task_e2e.dart):

    • completes the task after its only snapshotEvents listener is cancelled (all platforms): snapshotEvents.first, a short delay, then await task, and the uploaded object must have the full size.
    • detaching firebase_storage from another engine does not affect tasks of this engine (Android): a test-only tests/engines channel in the example's MainActivity attaches the plugin to a second FlutterEngine and destroys it while a 10 MB upload runs.

    Results on the Android emulator against the storage emulator:

    listener-cancel test engine-detach test
    main times out times out
    Dart fix only passes times out
    this PR passes passes

    The whole storage e2e suite passes on Android with this PR, using the CI flags (93 passed, 9 skipped). iOS, macOS, Windows and web were not run locally, so CI covers them.

Review fixes

  • The listener-cancel test's snapshotEvents.first now has the file's 60 s timeout.
  • The engine-detach test uploads 10 MB instead of 20 MB, so it finishes well within its 60 s timeout. On the local Android emulator (storage emulator with STORAGE_EMULATOR_DEBUG), the second engine is destroyed about 230 ms in and the upload ends at about 2.6 s. On the old Android code the test still fails: the emulator log shows the upload cancelled after its first 256 KB chunk, and the test times out. On CI, the 20 MB upload took about 1.8 s.
  • The Android onCancel comment no longer says "as on iOS", which fix(storage, apple): release finished tasks instead of keeping them for the life of the process #18747 would make false.

Related Issues

Follow-up to #18240 / #18255, which fixed only the crash on detach.

Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • My PR includes unit or integration tests for all changed/updated/fixed behaviors (See Contributor Guide).
  • All existing and new tests are passing.
  • I updated/added relevant documentation (doc comments with ///).
  • The analyzer (melos run analyze) does not report any problems on my PR.
  • I read and followed the Flutter Style Guide.
  • I signed the CLA.
  • I am willing to follow-up on review comments in a timely manner.

Breaking Change

  • No, this is not a breaking change.

…and scope Android task registries per engine

- Dart: one internal subscription now drives `snapshot` and `onComplete`, and
  users get a separate broadcast stream. Cancelling the last `snapshotEvents`
  listener no longer cancels the native event stream (which cancelled the
  upload on Android) and `await task` no longer hangs afterwards. `onComplete`
  also fails instead of hanging when the native stream closes without a final
  state or the task fails to start.
- Android: cancelling a task's event stream only stops sending events, as on
  iOS. In-progress tasks and event channels are tracked per plugin instance,
  so detaching a background engine no longer cancels the main engine's tasks
  or tears down its streams, and same-numbered handles from different engines
  no longer collide.
@gemini-code-assist

Copy link
Copy Markdown
Contributor
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

…ix/storage-task-lifecycle

# Conflicts:
#	packages/firebase_storage/firebase_storage_platform_interface/lib/src/method_channel/method_channel_task.dart
#	packages/firebase_storage/firebase_storage_platform_interface/test/method_channel_tests/method_channel_task_test.dart
…the engine-detach upload

- The listener-cancel e2e test now times out its `snapshotEvents.first` wait,
  like the rest of the file.
- The engine-detach e2e test uploads 10 MB instead of 20 MB. On the Android
  emulator it is still uploading about 2 s after the second engine is
  destroyed, and it still fails on the old Android code.
- The Android `onCancel` comment no longer claims parity with iOS.

Android behaviour change (from this PR): disposing a `StreamBuilder`, a
rebuild, or `await for ... break` no longer cancels the upload or download.
The task keeps running until it ends or is cancelled by `task.cancel()`, as on
iOS and web. A paused task the app forgets is kept for the life of the
process.

This branch has not been deployed

No deployments
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.

1 participant