Skip to content

[iOS] Platform message handlers queued before destroyContext run after it and crash: "Setting a message handler before the FlutterEngine has been run" #195495

Description

@valentinozegna

Steps to reproduce

On iOS, a platform message handler that Dart queued just before the engine is torn down runs after destroyContext. If that handler registers a channel, as FlutterEventChannel setStreamHandler: does for a Firestore snapshots() call, the app crashes with an NSInternalInconsistencyException.

Minimal native repro (any app; for example in application:didFinishLaunchingWithOptions:):

let engine = FlutterEngine(name: "repro")
engine.run()
engine.perform(NSSelectorFromString("destroyContext"))  // what appOrSceneWillTerminate does
_ = engine.binaryMessenger.setMessageHandlerOnChannel("repro", binaryMessageHandler: { _, _ in })

The app terminates with Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Setting a message handler before the FlutterEngine has been run.'

How it happens in production

  1. FlutterViewController sceneWillDisconnect: (or applicationWillTerminate:) calls appOrSceneWillTerminate, which calls [engine destroyContext], and that calls _shell.reset().
  2. PlatformMessageHandlerIos::HandlePlatformMessage runs each handler with dispatch_async(dispatch_get_main_queue(), run_handler) (or the handler's task queue), so a message Dart sent just before step 1 is already queued.
  3. The queued handler runs after the teardown. The cloud_firestore pigeon querySnapshot handler calls registerEventChannelWithPrefix:, which calls -[FlutterEventChannel setStreamHandler:], which calls -[FlutterEngine setMessageHandlerOnChannel:binaryMessageHandler:taskQueue:], which reaches NSAssert(!handler, @"Setting a message handler before the FlutterEngine has been run.").

sendOnChannel:message:binaryReply: has the same NSAssert(_shell && _shell->IsSetup(), ...). Any native event sink that fires after the teardown reaches it; see #117523 and the termination crashes in #126671, #167650 and #168535.

Production stack (iOS 27.0.1, Flutter 3.47.5, cloud_firestore 6.10.0; app in the background for hours, scene disconnected):

-[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
-[FlutterEngine setMessageHandlerOnChannel:binaryMessageHandler:taskQueue:]
-[FlutterBinaryMessengerRelay setMessageHandlerOnChannel:binaryMessageHandler:]
SetMessageHandler
SetStreamHandlerMessageHandlerOnChannel
-[FlutterEventChannel setStreamHandler:]
-[FLTFirebaseFirestorePlugin registerEventChannelWithPrefix:identifier:streamHandler:]
-[FLTFirebaseFirestorePlugin registerEventChannelWithPrefix:streamHandler:]
-[FLTFirebaseFirestorePlugin querySnapshotApp:path:isCollectionGroup:parameters:options:includeMetadataChanges:source:completion:]
__SetUpFirebaseFirestoreHostApiWithSuffix_block_invoke
__48-[FlutterBasicMessageChannel setMessageHandler:]_block_invoke

Expected results

Once the engine is torn down, setting a handler and sending a message should be no-ops, as setting a nil handler already is (return [FlutterConnectionCollection makeErrorConnectionWithErrorCode:-1L]), or queued handlers should be dropped when the shell is reset. A plugin cannot tell that the engine behind its registrar's messenger is gone, so it cannot guard against this itself.

Actual results

The app crashes with an uncaught NSInternalInconsistencyException (in release builds too), whether iOS disconnects the scene in the background or terminates the app.

Workaround

The app swizzles FlutterEngine. destroyContext flags the engine as torn down. On a flagged engine, setMessageHandlerOnChannel:binaryMessageHandler:taskQueue: returns -1 for a non-nil handler, and sendOnChannel:message:binaryReply: drops the message. This depends on the private destroyContext selector.

Flutter Doctor output

Flutter 3.47.5 stable (revision 6a19cca), iOS 27.0.1. The same code is on master: FlutterEngine.mm setMessageHandlerOnChannel:binaryMessageHandler:taskQueue: and platform_message_handler_ios.mm HandlePlatformMessage.

Activity

  1. added
    platform-ios
    engine
    has reproducible steps
    team-ios
    on Oct 28, 2026
  2. mbcorona commented on Oct 28, 2026

    @mbcorona
    Member

    HI @valentinozegna , thansk for the report.
    Routing to the iOS team for investigation.

  3. added
    P2
    triaged-ios
    on Oct 29, 2026
  4. hellohuanlin commented on Oct 29, 2026

    @hellohuanlin
    Contributor

    From triage: CC @cbracken if you can provide some insights?

  5. removed
    triaged-ios
    P2
    on Oct 29, 2026
  6. added
    P2
    on Nov 5, 2026
  7. self-assigned this
    on Nov 5, 2026
  8. added
    triaged-ios
    a: production
    c: fatal crash
    found in release: 3.47
    on Nov 5, 2026
  9. cbracken commented on Nov 24, 2026

    @cbracken
    Member

    @valentinozegna thanks for reporting. I've got a patch out that fixes this in #197310.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2a: productionc: fatal crashenginefound in release: 3.47has reproducible stepsplatform-iosteam-iostriaged-ios

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions