Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HeadlessTask: Could not enqueue microtask because they are disabled in this runtime #47570

Closed
mbpictures opened this issue Nov 12, 2024 · 57 comments
Labels
Needs: Attention Issues where the author has responded to feedback. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. Type: New Architecture Issues and PRs related to new architecture (Fabric/Turbo Modules)

Comments

@mbpictures
Copy link

mbpictures commented Nov 12, 2024

Description

I'm using react-native-firebase messaging to receive firebase push notifications using this line:

messaging().setBackgroundMessageHandler(onMessageReceived);

However the App Crashes with this error:

Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes

The symbolicated stacktrace looks like this:

node_modules/react-native/Libraries/Core/Timers/immediateShim.js:44:setImmediate
node_modules/react-native/Libraries/ReactNative/AppRegistry.js:307:startHeadlessTask
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:434:__callFunction
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:113:__guard$argument_0
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:368:__guard
react-native/Libraries/BatchedBridge/MessageQueue.js:112:callFunctionReturnFlushedQueue

Steps to reproduce

  1. Setup react native 0.76.1 project
  2. Install and setup react-native-firebase/messaging
  3. Add Background Message Handler
  4. Build for release and test on device

React Native Version

0.76.1

Affected Platforms

Runtime - Android

Areas

Bridgeless - The New Initialization Flow

Output of npx react-native info

System:
  OS: Windows 11 10.0.22631
  CPU: (24) x64 13th Gen Intel(R) Core(TM) i7-13700K
  Memory: 3.65 GB / 31.78 GB
Binaries:
  Node:
    version: 20.10.0
    path: C:\Program Files\nodejs\node.EXE
  Yarn:
    version: 4.4.1
    path: ~\AppData\Roaming\npm\yarn.CMD
  npm:
    version: 8.12.2
    path: C:\Program Files\nodejs\npm.CMD
  Watchman: Not Found
SDKs:
  Android SDK: Not Found
  Windows SDK:
    AllowAllTrustedApps: Enabled
    AllowDevelopmentWithoutDevLicense: Enabled
    Versions:
      - 10.0.19041.0
      - 10.0.22000.0
IDEs:
  Android Studio: Not Found
  Visual Studio:
    - 16.11.35026.282 (Visual Studio Community 2019)
    - 17.10.35122.118 (Visual Studio Community 2022)
Languages:
  Java:
    version: 17.0.9
    path: /cygdrive/c/Program Files/Microsoft/jdk-17.0.9.8-hotspot/bin/javac
  Ruby:
    version: 3.2.3
    path: C:\Ruby32-x64\bin\ruby.EXE
npmPackages:
  "@react-native-community/cli":
    installed: 15.0.0
    wanted: 15.0.0
  react:
    installed: 18.3.1
    wanted: 18.3.1
  react-native:
    installed: 0.76.1
    wanted: 0.76.1
  react-native-windows: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: true
iOS:
  hermesEnabled: Not found
  newArchEnabled: Not found

Stacktrace or Logs

Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermesFATAL EXCEPTION: mqt_native_modules
Process: , PID: 24014
    com.facebook.react.common.JavascriptException: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes, stack:
     setImmediate@1:338517
     startHeadlessTask@1:392921
     __callFunction@1:192422
     anonymous@1:190722
     __guard@1:191681
     callFunctionReturnFlushedQueue@1:190680
                                                                                                    
at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(SourceFile:77)
at com.facebook.jni.NativeRunnable.run(Native Method)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(SourceFile:1)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at  com.facebook.react.bridge.queue.MessageQueueThreadImpl.lambda$startNewBackgroundThread$2(SourceFile:36)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl.b(SourceFile:1)
at com.facebook.react.bridge.queue.b.run(SourceFile:1)	
at java.lang.Thread.run(Thread.java:1012)

Reproducer

mbpictures/react-native-microtask-repro

Screenshots and Videos

No response

@mbpictures mbpictures added Needs: Triage 🔍 Type: New Architecture Issues and PRs related to new architecture (Fabric/Turbo Modules) labels Nov 12, 2024
@react-native-bot react-native-bot added Needs: Author Feedback Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. labels Nov 12, 2024
@react-native-bot
Copy link
Collaborator

Warning

Missing reproducer: We could not detect a reproducible example in your issue report. Please provide either:

@shubhamguptadream11
Copy link
Collaborator

It will be helpful if you provide a repro as well. You can use this template.

@mbpictures
Copy link
Author

Repro added in issue description

@gituser8796
Copy link

@shubhamguptadream11 will it be possible to include a fix for this issue in version 0.76.2? (Android apps using FCM can't use new arch until then)

@mikehardy
Copy link
Contributor

0.76.2 is already out, this would maybe be possible in 0.76.3. Hopefully possible...

@cipolleschi
Copy link
Contributor

0.76.2 is out but with the commit 9f65442

Does this mean that this issue is fixed?

@mikehardy What do we need for 0.76.3?

@mikehardy
Copy link
Contributor

@cipolleschi it might be, we're collaborating over on #47592 so you know I'm looking at this headlessJS stuff. This was next on my list to check out for repro because it seems that it might be working well now. My repro for 47592 wasn't done with this in mind though so I wanted to check it specifically. I'll do so and let you know what I see

@mikehardy
Copy link
Contributor

mikehardy commented Nov 18, 2024

Testing results - I added a branch with Notifee to my reproducer in for #47592 (which is similar to the reproducer here, except no need to send it an FCM, you can trigger things via adb on the command line assuming you use Android 7 emulator to avoid platform background service start limitations)

All testing followed this process:

  • new architecture is enabled - gradle.properties::newArchEnabled=true

  • yarn && yarn android

  • open task switcher and clear all so app activity is destroyed (but app is not force killed!)

  • terminal: adb shell am broadcast -n com.reproducerapp/.ExampleReceiver -a "com.example.intent.TestIntent"

  • watch logcat

  • if a notification posted, try to swipe the notification away

  • if that worked, use adb to send another TestIntent, then click on the notification to open the app

  • If that worked, open task switcher to swipe it away again to reset for next test

  • react-native 0.76.0:

11-18 13:01:46.272  4842  4874 E ReactNativeJS: Error: Failed to call into JavaScript module method AppRegistry.startHeadlessTask(). Module has not been registered as callable. Registered callable JavaScript modules (n = 8): GlobalPerformanceLogger, RCTNativeAppEventEmitter, SamplingProfiler, RCTDeviceEventEmitter, HMRClient, RCTLog, HeapCapture, Systrace. Did you forget to call `registerCallableModule`?

So that's no good. 0.76.0 seems to be ❌

  • react-native 0.76.1

Everything chained through correctly - adb sent intent -> app receiver woke up and got it and forwarded to service -> service started and booted react-native and ran headlessJS ->

11-18 13:08:04.437  5048  5078 I ReactNativeJS: ExampleHeadlessTask JS executing. Received taskData: {"foo":"bar"}

and a Notifee notification posts, everything works? 0.76.1 seems like ✅

  • react-native 0.76.2

same as 0.76.2 - everything seems to work, I get a notification etc, everything works ✅

So:

  1. the reproducer attached here may reproduce it? I don't know? I'm not able to run it because it relies on all that firebase project setup, and cloud messaging to send messages to receivers on device etc, and that is not shareable
  2. my reproducer does not reproduce it
  3. we appear to have a third reproducer in Minimal Expo 52 app crashes when using form sheet modals when using RNTP software-mansion/react-native-screens#2507 and I'm going to see what I can do about making sure it reproduces, making that minimal and posting it up here

@mikehardy
Copy link
Contributor

I am simply not able to reproduce this anymore, I really tried.
0.76.0 is definitely broken for headlessJS
0.76.1 and 0.76.2 using either a full react-native-firebase integration or my stubbed out "test intent" style, they both work for me

Anyone is feel free to take my example from this branch here and extend it as needed, but I/we will need your exact steps to reproduce this in order to find it: https://github.com/mikehardy/old-arch-android-receiver-boot-crash/tree/notifee-integration-issue47570-repro

I'm going to consider this closed though and start recommending that people try notifee and react-native-firebase on 0.76.2+ with new arch on android and iOS, I can't find problems with either of them anymore

@romanakash
Copy link

I had the same issue with 0.76.3, upgrading react-native-firebase/app to ^21.5.0 seems to have fixed the issue

@mikehardy
Copy link
Contributor

@romanakash from version what of react-native-firebase/app to 21.5.0? There have not been any new-architecture-related items released in react-native-firebase/app in a long, long time other than the switch from onCatalystInstanceDestroy to invalidate but it's important to note that only affects the hot reload case as far as I know? But maybe I'm wrong, and it affected more than that somehow

@romanakash
Copy link

From 20.1.0

From my experience there was another error thrown by my code which was a mistake, so I made a change and when fast refresh tried to refresh it got stuck with the micro task error

After upgrading the firebase version I got the same error due to my own code but when fast refresh refreshed I did not get the micro task error

@mikehardy
Copy link
Contributor

@romanakash in fact the one and only time I saw this was similar - I had two apps I was reproducing on and I saw it when one of them accidentally (through a test methodology failure on my part) loaded the bundle from the other app, resulting in all sorts of problems including a microtasks error.

When I kept my methodology clean + fully reproducible I was never able to reproduce the microtasks error on current versions of everything

So this is possibly confirmation bias, but my experience pretty much matches yours

And I still cannot reproduce this problem anymore (a good thing!). I believe headlessJS is working with new architecture on current versions of everything

@mbpictures
Copy link
Author

Well for me it seems like I still have this error. I released an app update yesterday including react native 0.76.2 and today I saw a lot of crashes in firebase crashlytics:

          Fatal Exception: com.facebook.react.common.JavascriptException: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes, stack:
setImmediate@1:338517
startHeadlessTask@1:392921
__callFunction@1:192422
anonymous@1:190722
__guard@1:191681
callFunctionReturnFlushedQueue@1:190680

       at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.kt:52)
       at com.facebook.jni.NativeRunnable.run(NativeRunnable.java)
       at android.os.Handler.handleCallback(Handler.java:938)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
       at android.os.Looper.loop(Looper.java:246)
       at com.facebook.react.bridge.queue.MessageQueueThreadImpl.lambda$startNewBackgroundThread$2(MessageQueueThreadImpl.java:217)
       at java.lang.Thread.run(Thread.java:923)
        

@cipolleschi
Copy link
Contributor

@mbpictures have you updated Firebase to ^21.5.0? Can you try with that version?

@mbpictures
Copy link
Author

@cipolleschi thanks for the hin, but I already updated firebase to version 21.5.0

@mikehardy
Copy link
Contributor

Yeah - unfortunately nothing in RNFB recently is expected to affect this.
I still cannot reproduce this - reproducing is difficult I understand but I have tried pretty hard and I did reproduce some things. It should be possible.

What I'm looking for in order to nail this down is

  • some specific build configuration
  • on an app we can share (read as: ideally not involving firebase cloud messaging...)
  • and the exact series of steps starting from "app is not running at all" to trigger it

Feel free to use this as a start - it's very self-contained and I was able to reproduce things with it:
https://github.com/mikehardy/old-arch-android-receiver-boot-crash

I even have a branch on it that tweaks things a bit specifically to match your handler setup in your reproducer:
https://github.com/mikehardy/old-arch-android-receiver-boot-crash/tree/notifee-integration-issue47570-repro

and I just couldn't see it.

I don't think react-native-firebase is doing anything magical in the chain of receiver -> service -> headlessJS tasks so it should be a valid reproducer, but maybe I'm wrong.

If the app has to be an FCM / react-native-firebase app, then knowing the exact FCM JSON contents I should use, and the exact state the app needs to be in before delivery, would really help me.

Then I could drop it into the a branch I have going here that allows me to check FCM / Android interaction:
https://github.com/mikehardy/rnfbdemo/tree/manual-check-features

But the exact FCM and exact steps to reliably reproduce it are a strict requirement here since I'm failing to reproduce at the moment

@mbpictures
Copy link
Author

mbpictures commented Nov 23, 2024

After a lot of fiddling around, I successfully reproduced it (using the same repo as provided in the issue description). The key point was to create a release build with proguard enabled.

Some detailed reproduction steps:

  • Setup ReproducerApp with correct google-services.json
  • Setup fcmSender with serviceAccount.json
  • Create release build using the build:release:android script inside of the ReproducerApp package
  • Install the release build on a real device (S20+ in my case)
  • Start the release build, request notification permissions and sign up for the topic using the "PERMISSIONS"-button
  • Kill the app
  • Send a notification using the send script inside of the fcmSender package

While following these exact steps, the issue occurs every single time, even on the newest RN version 0.76.3

@mikehardy
Copy link
Contributor

Ah okay - I was definitely testing on debug builds though I can create release builds.
I'll see if I can also reproduce this in the non-google-services / more minimal reproducer but if not I can also work through it on reproducers that use firebase / FCM. Thanks for figuring out a reliable set of steps to work through, that's really critical work
Cheers

@smfunder
Copy link

smfunder commented Nov 26, 2024

Hello! It is happening to me with Firebase and RN 0.75.4 + NewArch enabled.

Here is the output:

 FATAL EXCEPTION: mqt_native_modules
Process: com.wavelengthlabs.airwave.staging, PID: 5584
com.facebook.react.common.JavascriptException: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes, stack:
setImmediate@1:343863
                                                                                                    setDriver@1:1327372
                                                                                                    LocalForage@1:1325942
                                                                                                    anonymous@1:1307483
                                                                                                    s@1:1302294
                                                                                                    e@1:1302037
                                                                                                    anonymous@1:1301939
                                                                                                    anonymous@1:1301787
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:1299563
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:1295908
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:1118959
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:1103398
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:1102505
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:983891
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:833033
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:753366
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138064
                                                                                                    metroRequire@1:137694
                                                                                                    anonymous@1:144771
                                                                                                    loadModuleImplementation@1:138541
                                                                                                    guardedLoadModule@1:138021
                                                                                                    metroRequire@1:137694
                                                                                                    global@1:137222
                                                                                                    
                                                                                                    	at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:65)
                                                                                                    	at com.facebook.jni.NativeRunnable.run(Native Method)
                                                                                                    	at android.os.Handler.handleCallback(Handler.java:942)
                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                                    	at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
                                                                                                    	at android.os.Looper.loopOnce(Looper.java:226)
                                                                                                    	at android.os.Looper.loop(Looper.java:313)
                                                                                                    	at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:235)

Also I put the pro guard rules:

-keep class com.facebook.react.defaults.DefaultNewArchitectureEntryPoint { *; }
-keep class com.facebook.react.ReactApplication { *; }
-keep class com.facebook.react.ReactHost { *; }
-keep class * extends com.facebook.react.ReactHost { *; }
-keepnames class com.facebook.react.ReactActivity

@mikehardy
Copy link
Contributor

@smfunder -->

You need to grab your proguard mappings file for inspection, that's the best way to know if my fix took hold
Similar to the first time around, if I can reproduce it I'll fix it, but if I can't reproduce it I won't - so will need a reproduction for this

@smfunder
Copy link

@mikehardy thanks for your reply, where I can grab my pro guard mapping file? I tried to search in google but it is all pointing to old resources.

@mikehardy
Copy link
Contributor

@smfunder this looks like a good resource https://stackoverflow.com/questions/25724645/where-does-android-studio-save-the-proguard-mapping-file (basically everything in the release - or more accurately ${buildFlavor} - folder there is potentially interesting). So do a release build and look to make sure that the classes I added to Notifee proguard are actually preserved instead of converted to like single-letter names and such


mike@isabela:~/work/react-random/old-arch-android-receiver-boot-crash/ReproducerApp (notifee-integration-issue47570-repro) % ls -lat android/app/build/outputs/mapping/release/
total 25552
-rw-r--r--  1 mike  staff     35185 Nov 25 13:05 configuration.txt
drwxr-xr-x  6 mike  staff       192 Nov 25 13:05 ./
-rw-r--r--  1 mike  staff  10900181 Nov 25 13:05 mapping.txt
-rw-r--r--  1 mike  staff   1437862 Nov 25 13:05 usage.txt
-rw-r--r--  1 mike  staff    697625 Nov 25 13:05 seeds.txt
drwxr-xr-x  3 mike  staff        96 Nov 24 23:43 ../

And I see things like this now (where you can see the rule I added in configurations, and the preserved names):

mike@isabela:~/work/react-random/old-arch-android-receiver-boot-crash/ReproducerApp (notifee-integration-issue47570-repro) % grep -r DefaultNewArchitecture android/app/build/outputs/mapping/release/
android/app/build/outputs/mapping/release//configuration.txt:-keep class com.facebook.react.defaults.DefaultNewArchitectureEntryPoint { *; }
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean privateConcurrentReactEnabled
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean privateFabricEnabled
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: com.facebook.react.defaults.DefaultNewArchitectureEntryPoint INSTANCE
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean privateTurboModulesEnabled
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean privateBridgelessEnabled
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void load(boolean)
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean getFabricEnabled()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean getConcurrentReactEnabled()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void load$default(boolean,boolean,boolean,int,java.lang.Object)
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void load(boolean,boolean,boolean)
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean getTurboModulesEnabled()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void getTurboModulesEnabled$annotations()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void getFabricEnabled$annotations()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void getConcurrentReactEnabled$annotations()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void load(boolean,boolean)
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: kotlin.Pair isConfigurationValid(boolean,boolean,boolean)
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: boolean getBridgelessEnabled()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: DefaultNewArchitectureEntryPoint()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void load()
android/app/build/outputs/mapping/release//seeds.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint: void getBridgelessEnabled$annotations()
android/app/build/outputs/mapping/release//mapping.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint -> com.facebook.react.defaults.DefaultNewArchitectureEntryPoint:
android/app/build/outputs/mapping/release//mapping.txt:# {"id":"sourceFile","fileName":"DefaultNewArchitectureEntryPoint.kt"}
android/app/build/outputs/mapping/release//mapping.txt:com.facebook.react.defaults.DefaultNewArchitectureEntryPoint$load$1 -> com.facebook.react.defaults.DefaultNewArchitectureEntryPoint$a:

Before it was a real obvious mishmash of Proguard doing what we normally want - shrinking the names away or removing methods entirely, which was the Notifee crash.

This may very well be a different crash - I don't know - the problem is that react-native eats the source stack trace so we don't know.

@smfunder
Copy link

@mikehardy thank you for your response. Basically I didn't find any mapping so checking my code I have:
def enableProguardInReleaseBuilds = false
So I understand that will make pro guard to not minimize the core right? So my issue is related to any other thing?
I also migrated to RN 0.76.3 and I'm facing the same issue. Not sure where to continue investigating.
When I "grep" all my source code I find the error that it is on the tittle of this issue report, I can find it only in Reanimated library. So I also created an Issue there. I also added more information where that could be coming from.

software-mansion/react-native-reanimated#6764

Any ideas?

@smfunder
Copy link

@mikehardy finally I found that the issue were caused by the react-native-push-notification library with RN 0.76.3 + New Arch + Bridgeless. So I will work on updating it to make sure it can run correctly. The app was crashing right away on the first startup after a fresh install and also when it may receive a push notification, specially in quit state.
It is a 3 years old library so it is not updated for the new Arch.

@mikehardy
Copy link
Contributor

Notifee is working with it and I have active maintenance planned over there

@cipolleschi
Copy link
Contributor

@mikehardy I came back from PTO on Monday and finally found the time to read through this right now.

Do I understand correctly that this is not a bug in React Native? Can we close the issue?

@smfunder
Copy link

smfunder commented Dec 4, 2024

@cipolleschi I found in my case it was not a React Native issue but a 3rd party library issue ( react-native-push-notification) which was causing the issue. Now I updated my code to work with Notifee and everything works as expected without this crash.

@mikehardy
Copy link
Contributor

mikehardy commented Dec 4, 2024

@cipolleschi I believe it is closable yes.

As far as I can tell, react-native 0.76-current + new architecture in bridgeless mode is working. I did not type "working well" because I will admit troubleshooting when it fails is quite difficult. I'm not sure if you have any insight into technical ability to expose the underlying module-specific errors that cause problems, but that would be a really really big help. In the Notifee case, there should have been a clear stack trace with Notifee frames saying NoClassDefFound, but it appears everything helpful is lost and we just get "Could not enqueue microtask..." as an error.

So, headlessJS+new-arch is working, but modules do have problems at the module level and it's hard to fix them at current.

There is still a headlessJS+old-arch issue I believe, it is separate and tracked separately though of course, just noting it.

Hope that is useful feedback? Welcome back! :-)

@mikehardy
Copy link
Contributor

Just confirmed 0.77.0-rc.1 as well, things looking good in headlessJS+new-arch 🫡

@cipolleschi
Copy link
Contributor

@mikehardy Thanks, that was useful.

In 0.77 we reimplemented the early JS reporting pipeline, reimplementing it in C++. Errors should bubble up better and with a better stack trace in that version. Hopefully, it will help in these cases too.

I'll close this, then. Thank you so much for spending all that time on this!

@mikehardy
Copy link
Contributor

mikehardy commented Dec 4, 2024

Hey @cipolleschi - I like the idea of better error reporting, it was so difficult to test this because of the swallowed root cause information so I thought I'd test it on 0.77 to see if it was improved as you mentioned

When I moved my reproducer to 0.77.0-rc.1 (hot off the presses!) I do not see any improvement in error reporting in the headlessJS "startup failed because native module had a crash" exception case


12-04 14:43:24.262  3491  3491 D getReactContext: Determining ReactContext using fallback method
12-04 14:43:24.264  3491  3519 E ReactNativeJS: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes
--------- beginning of crash
12-04 14:43:24.265  3491  3520 E AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
12-04 14:43:24.265  3491  3520 E AndroidRuntime: Process: com.reproducerapp, PID: 3491
12-04 14:43:24.265  3491  3520 E AndroidRuntime: com.facebook.react.common.JavascriptException: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes, stack:
12-04 14:43:24.265  3491  3520 E AndroidRuntime: setImmediate@1:176837
12-04 14:43:24.265  3491  3520 E AndroidRuntime: startHeadlessTask@1:232094
12-04 14:43:24.265  3491  3520 E AndroidRuntime: __callFunction@1:31368
12-04 14:43:24.265  3491  3520 E AndroidRuntime: anonymous@1:29673
12-04 14:43:24.265  3491  3520 E AndroidRuntime: __guard@1:30629
12-04 14:43:24.265  3491  3520 E AndroidRuntime: callFunctionReturnFlushedQueue@1:29631
12-04 14:43:24.265  3491  3520 E AndroidRuntime: 
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(SourceFile:77)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.jni.NativeRunnable.run(Native Method)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at android.os.Handler.handleCallback(Handler.java:751)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:95)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(SourceFile:1)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadImpl.lambda$startNewBackgroundThread$2(SourceFile:36)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.react.bridge.queue.MessageQueueThreadImpl.b(SourceFile:1)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at com.facebook.react.bridge.queue.b.run(SourceFile:1)
12-04 14:43:24.265  3491  3520 E AndroidRuntime:        at java.lang.Thread.run(Thread.java:761)
12-04 14:43:24.271   926  1272 E SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
12-04 14:43:24.300  1182  3523 D         : HostConnection::get() New Host Connection established 0x7c2c97c5e0, tid 3523

The root cause is reflectively loading a class name that was altered during minification, so should be a NoClassDefFound or ClassNotFound Exception, but it is buried was a branch of logic was taken incorrectly because of minification altering Java names, and the unexpected branch doing something un-safe, and other things relying on that etc - ending in an Exception in the module

Just wanted to report that 0.77 is not an improvement for this case at least

If the module works, headlessJS works though - I'm just talking about how react-native reports module errors in headlessJS at this point.

@HemangiVekaria
Copy link

HemangiVekaria commented Dec 9, 2024

I am using React Native 0.75.4 and "@aws-amplify/rtn-push-notification" version "^1.2.31" for notifications. In AWS, Firebase is configured as the notification provider for Android.

When I run the app in debug mode, I receive multiple notifications without any issues. However, after creating the release APK, the app crashes upon receiving a notification after 3-4 notifications have been received. Here is the crash log:

Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes
FATAL EXCEPTION: mqt_native_modules (Ask Gemini)
Process: com.test PID: 13898
com.facebook.react.common.JavascriptException: Error: Exception in HostFunction: Could not enqueue microtask because they are disabled in this runtime, js engine: hermes, stack:
                                      setImmediate@1:274584
                                      startHeadlessTask@1:329670
                                      __callFunction@1:131854
                                      anonymous@1:130154
                                      __guard@1:131113
                                      callFunctionReturnFlushedQueue@1:130112
                                      
                                      	at com.facebook.react.modules.core.ExceptionsManagerModule.reportException(ExceptionsManagerModule.java:65)
                                      	at com.facebook.jni.NativeRunnable.run(Native Method)
                                      	at android.os.Handler.handleCallback(Handler.java:958)
                                      	at android.os.Handler.dispatchMessage(Handler.java:99)
                                      	at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
                                      	at android.os.Looper.loopOnce(Looper.java:230)
                                      	at android.os.Looper.loop(Looper.java:319)
                                      	at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:235)

In my React Native code, I have added a notification receive handler. When the app crashes, that method gets called, and the log "receive notification when app in background:::::::::::::::::::::::::::::::::::::::::::" inside that method is printed in Android Studio Logcat.

const myAsyncNotificationReceivedHandler = async notification => {
  console.log(
    'receive notification when app in background:::::::::::::::::::::::::::::::::::::::::::',
  );
};
onNotificationReceivedInBackground(myAsyncNotificationReceivedHandler);

Can anyone help me with this?

@cipolleschi
Copy link
Contributor

@mikehardy thanks for checking with the new version. I'll let the person working on the error pipeline know that there are cases where we are not covered yet.

@HemangiVekaria if you are on 0.75, you are still on the Old Arch. Please move the conversation to the Old Arch issue: #47592. As far as I can see that has been resolved as well by this commit: 3c747eb

We have to make a patch release which includes the commit.

@HemangiVekaria
Copy link

@HemangiVekaria if you are on 0.75, you are still on the Old Arch. Please move the conversation to the Old Arch issue: #47592. As far as I can see that has been resolved as well by this commit: 3c747eb

We have to make a patch release which includes the commit.

Can i get patch file please?

@gituser8796
Copy link

hi @cipolleschi @mikehardy we are experiencing the crash in our latest Android rollout using the new architecture. This issue was not detected during internal testing but has now started affecting a growing number of users. Any insights or guidance on resolving this would be greatly appreciated.

Some more context:

  1. relevant dependencies in our project:
    react-native: "0.76.2"
    @notifee/react-native: "9.1.3"
    @react-native-firebase/messaging: "21.6.1"

  2. We had some piece of code which used HeadlessJsTaskService, and have just removed it (we might be able to move forward without it).

  3. This crash is also reported:
    Fatal Exception: java.lang.AssertionError: Tried to start a task on a react context that has already been destroyed
    at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:19)
    at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:102)
    at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:91)
    at io.invertase.notifee.NotifeeReactUtils.lambda$startHeadlessTask$1(NotifeeReactUtils.java:194)
    at android.os.Handler.handleCallback(Handler.java:958)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:230)
    at android.os.Looper.loop(Looper.java:319)
    at android.app.ActivityThread.main(ActivityThread.java:9063)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:588)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)

@gituser8796
Copy link

hi @cipolleschi @mikehardy we are experiencing the crash in our latest Android rollout using the new architecture. This issue was not detected during internal testing but has now started affecting a growing number of users. Any insights or guidance on resolving this would be greatly appreciated.

Some more context:

  1. relevant dependencies in our project:
    react-native: "0.76.2"
    @notifee/react-native: "9.1.3"
    @react-native-firebase/messaging: "21.6.1"
  2. We had some piece of code which used HeadlessJsTaskService, and have just removed it (we might be able to move forward without it).
  3. This crash is also reported:
    Fatal Exception: java.lang.AssertionError: Tried to start a task on a react context that has already been destroyed
    at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:19)
    at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:102)
    at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:91)
    at io.invertase.notifee.NotifeeReactUtils.lambda$startHeadlessTask$1(NotifeeReactUtils.java:194)
    at android.os.Handler.handleCallback(Handler.java:958)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:230)
    at android.os.Looper.loop(Looper.java:319)
    at android.app.ActivityThread.main(ActivityThread.java:9063)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:588)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)

@cipolleschi @mikehardy The crash persists even after removing all code related to HeadlessTask. The only references to HeadlessTask in the project (including dependencies) are found in:

react-native: "0.76.2"
@notifee/react-native: "9.1.3"
@react-native-firebase/messaging: "21.6.1"

Would greatly appreciate your input

@HamoBoker
Copy link

@gituser8796 you should update to [email protected]

@gituser8796
Copy link

@HamoBoker will give it a try although we're using the new architecture, thx!

@gituser8796
Copy link

@mikehardy @cipolleschi it still happens even on 0.76.5 - also added changes make by notifee to our proguard-rules.pro

@mikehardy
Copy link
Contributor

@gituser8796 you'll need to provide a reproducible example. I can say that the error "Could not enqueue microtask because they are disabled in this runtime" is what all native module errors get mapped to in headlessJS.

It could be anything. Any module.

For a while it was in react-native new arch and old arch. New arch was fixed first and has worked since I believe 0.76.0 or .1. old-arch was just fixed in react-native with 0.76.5.

But modules, they may still have problems. Notifee definitely did until notifee v9.1.3. react-native-firebase has worked fine for a while, well before v21. But there could be some other problem.

No way to know without an example that reproduces it. My reproducer for the modules I maintain no longer shows any problems though and I haven't heard any specific scenarios I could try even, so I can't advance this.

@gituser8796
Copy link

@mikehardy We managed to trace the offending code to a dependency that was attempting to call Reanimated too early (during file imports) and have removed it.

However, we are still receiving reports of the Notifee crash from Firebase, though, unfortunately, no clear scenario has been identified yet. Do you have any suggestions on how to move forward?

 Fatal Exception: java.lang.AssertionError: Tried to start a task on a react context that has already been destroyed
       at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:19)
       at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:102)
       at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:91)
       at io.invertase.notifee.NotifeeReactUtils.lambda$startHeadlessTask$1(NotifeeReactUtils.java:194)
       at android.os.Handler.handleCallback(Handler.java:958)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:230)
       at android.os.Looper.loop(Looper.java:319)
       at android.app.ActivityThread.main(ActivityThread.java:9063)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:588)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)

@Immacio
Copy link

Immacio commented Dec 11, 2024

+1

Facing the same issue as @gituser8796 - we are also using new arch on "react-native: "0.76.5"" with the latest notifee and firebase libraries installed.

I am also able to reproduce this in debug mode and I get this warning in my console. The stacktrace leads back to HeadlessJsTaskContext
No task registered for key ReactNativeFirebaseMessagingHeadlessTask

 Fatal Exception: java.lang.AssertionError: Tried to start a task on a react context that has already been destroyed
       at com.facebook.infer.annotation.Assertions.assertNotNull(Assertions.java:19)
       at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:102)
       at com.facebook.react.jstasks.HeadlessJsTaskContext.startTask(HeadlessJsTaskContext.java:91)
       at io.invertase.notifee.NotifeeReactUtils.lambda$startHeadlessTask$1(NotifeeReactUtils.java:194)
       at android.os.Handler.handleCallback(Handler.java:958)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:230)
       at android.os.Looper.loop(Looper.java:319)
       at android.app.ActivityThread.main(ActivityThread.java:9063)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:588)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)

@Immacio
Copy link

Immacio commented Dec 12, 2024

Solved the issue on our end.

We were initializing our firebase remote config prior to calling the background message handler. The initialization was a promise and we were awaiting it, removing the await and letting it run synchronously solved the issue for us. I guess if you have any promises running prior to the handler either remove it or defer it to after initializing the background message handler. It seems to mess with the creation of a headless task on Android.

@mikehardy
Copy link
Contributor

For anyone following along at home - there was one more new architecture + headlessJS issue (a startup race where module beat react-native to startup so ReactContext was null in module...) in Notifee resulting in a crash. I just released a fix for that yesterday.

It is possible as mentioned above that playing around with how you used module APIs during startup could workaround it and let you startup headlessJS correctly but really it was a module problem that needed a fix.

I remain unaware of "upstream" (that is, here: react-native internal code) issues with headlessJS at the moment but it's clearly difficult for modules to get correct in the new arch environment

@gituser8796
Copy link

@mikehardy in the meanwhile we reverted back to old architecture. Is it safe to use 9.1.4 with old architecture?

@mikehardy
Copy link
Contributor

For anyone seeing this:

No task registered for key ReactNativeFirebaseMessagingHeadlessTask

You can just supply an empty background message handler (firebase().messaging.setBackgroundMessagingHandler(async () => {}) to quiet the warning, it is a harmless warning though

@gituser8796 I do believe 9.1.4 is safe with the old architecture. However 9.1.4+ of notifee should be safe with new architecture as well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Attention Issues where the author has responded to feedback. Needs: Repro This issue could be improved with a clear list of steps to reproduce the issue. Type: New Architecture Issues and PRs related to new architecture (Fabric/Turbo Modules)
Projects
None yet
Development

No branches or pull requests