Skip to content

[$175] [Sentry: APP-M0W] HybridApp iOS: App Hang, Live Markdown parser blocks the main thread on the JS runtime lock #104744

Open

Description

@mountiny

Sentry

https://expensify.sentry.io/issues/APP-M0W

Impact (snapshot at filing)

  • Users (total since first seen): 21
  • Events: 21
  • Users (last 14d, all versions): 9
  • Users (last 14d, production 9.5.13 to 9.5.15): 3, all on 9.5.13-6
  • First seen: 2026-09-16
  • Last seen: 2026-10-21 (ongoing)
  • Platform: HybridApp iOS
  • App version(s): 9.5.2 to 9.5.13
  • Mechanism: AppHang (Fatal App Hang Fully Blocked, main thread blocked for at least 2000 ms), level fatal

Stack trace (main thread, top frames)

__psynch_mutexwait
std::__1::recursive_mutex::lock
facebook::jsi::WithRuntimeDecorator<T>::createStringFromUtf8
-[MarkdownParser parseUncached:withParserId:]
-[MarkdownParser parseIfRegistered:withParserId:]
-[MarkdownParser parse:withParserId:]
-[RCTMarkdownUtils applyMarkdownFormatting:withDefaultTextAttributes:]
-[MarkdownTextStorageDelegate textStorage:didProcessEditing:range:changeInLength:]
-[MarkdownTextInputDecoratorComponentView applyNewStyles]
-[MarkdownTextInputDecoratorComponentView updateProps:oldProps:]
RCTPerformMountInstructions (RCTMountingManager.mm:83)
...
reanimated::ReanimatedModuleProxy::executeLayoutAnimationsRequests
worklets::WorkletRuntime::runSyncAndDiscard<T>

Suspected cause

A reanimated layout animation runs a Fabric mount on the main thread. The mount updates the props of a MarkdownTextInput, and Live Markdown parses the text right away on the main thread. The parser calls into a JS runtime and waits for its lock, and another thread holds that lock, so the main thread stays blocked until the watchdog kills the app.

Reproduction

Unknown. See the Sentry events linked from the Sentry issue.

Related

  • Sibling Sentry IDs: none confirmed
  • Prior GH issues: none found
Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @TaduJR

Activity

  1. self-assigned this
    on Oct 22, 2026
  2. added
    ExternalAdded to denote the issue can be worked on by a contributor
    BugSomething is broken. Auto assigns a BugZero manager.
    on Oct 22, 2026
  3. melvin-bot commented on Oct 22, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @TaduJR (External)

  4. changed the title [-][Sentry: APP-M0W] HybridApp iOS: App Hang, Live Markdown parser blocks the main thread on the JS runtime lock[/-] [+][$175] [Sentry: APP-M0W] HybridApp iOS: App Hang, Live Markdown parser blocks the main thread on the JS runtime lock[/+] on Oct 22, 2026
  5. melvin-bot commented on Oct 22, 2026

    @melvin-bot
  6. Abdallah-1551 commented on Oct 22, 2026

    @Abdallah-1551

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    On HybridApp iOS, the app sometimes freezes for 2 seconds or more, and the iOS watchdog reports a fatal App Hang. The main thread is blocked inside -[MarkdownParser parseUncached:withParserId:]. It is waiting on a std::recursive_mutex that guards a JS (worklet) runtime, and another thread holds that lock. The call chain is:

    1. A Reanimated layout animation runs a Fabric mount on the main thread.
    2. The mount calls MarkdownTextInputDecoratorComponentView updateProps → applyNewStyles.
    3. applyNewStyles triggers textStorage:didProcessEditing, which synchronously calls the markdown parser.

    The goal is that the main thread never blocks on a JS runtime lock because of Live Markdown. At minimum, a props or style update on a MarkdownTextInput must not trigger a synchronous JS call.

    What is the root cause of that problem?

    This analysis is from the stack trace only. There is no reproduction, so the details below are strong hypotheses.

    1. The native parser calls into a JS runtime synchronously on the main thread. MarkdownParser.mm has to create JSI values (createStringFromUtf8) and run the parser worklet on a worklet runtime. That runtime is wrapped in a decorator that takes a recursive_mutex for every access. If any other thread is using the runtime, the main thread waits for it.
    2. The re-parse is triggered by a props update, not only by a text edit.
      • updateProps → applyNewStyles rewrites the attributes of the whole text storage, which fires didProcessEditing and re-runs the parser.
      • The parse result only contains ranges (type, location, length, depth). It does not depend on markdownStyle.
      • Re-parsing on a style-only or layout-driven prop update is therefore unnecessary. When the parse cache misses, as with a new or long text, the call goes to the JS runtime and can block.
    3. The runtime lock is held for a long time by another thread. A likely holder is the JS thread or the UI runtime running a long markdown parse worklet (long text, or parseExpensiMark invoked elsewhere via runOnRuntime/runOnJS). The Reanimated layout-animation path (executeLayoutAnimationsRequests → runSyncAndDiscard) makes this worse, because the mount runs inside a synchronous worklet-runtime section on the main thread. That creates a lock-ordering and contention window.

    What changes do you think we should make in order to solve the problem?

    1. Main fix, in react-native-live-markdown (native iOS). Do not call into JS when only styles or props change.

    • In MarkdownTextInputDecoratorComponentView, store the last parsed ranges together with the text and parserId they were computed from.
    • In applyNewStyles, if the text and parser are unchanged, re-apply attributes from the cached ranges and skip MarkdownParser parse:.
    // RCTMarkdownUtils.mm (sketch)
    - (NSAttributedString *)applyMarkdownFormatting:(NSAttributedString *)input
                          withDefaultTextAttributes:(NSDictionary *)defaults {
      NSString *text = input.string;
      NSArray *ranges;
      if ([text isEqualToString:_lastText] && _lastParserId == _parserId) {
        ranges = _lastRanges;                    // no JS call, no runtime lock
      } else {
        ranges = [_parser parse:text withParserId:_parserId]; // may hit JS
        _lastText = [text copy]; _lastParserId = _parserId; _lastRanges = ranges;
      }
      return [self applyRanges:ranges toText:input defaults:defaults];
    }

    This removes the hang path from the stack trace, where a layout-animation mount only changes props or styles. It is also a performance win.

    2. Defense in depth in react-native-live-markdown. For the unavoidable parse on the main thread (a real text change or the initial mount), avoid an unbounded wait on the runtime lock.

    • Use a dedicated worklet runtime for the markdown parser. It must be used only by Live Markdown and never shared with the UI runtime or user code.
    • Keep the existing parse cache and make sure it is populated before mount where possible. For example, pre-parse the defaultValue or value on the JS side.
    • If a non-blocking try-lock is available, fall back to plain unformatted text and schedule an async re-format on the next run loop tick instead of blocking.

    3. In Expensify/App.

    • Verify that the markdown parser (parseExpensiMark) is only executed on the dedicated markdown runtime. Remove any usage on the JS thread or UI runtime (runOnRuntime, runOnUI and similar).
    • Audit the screens in the stack trace (Composer, MarkdownTextInput inside Animated.View or LayoutAnimation). Do not apply Reanimated layout/entering/exiting to an ancestor that remounts or relayouts a MarkdownTextInput. Animate a wrapper or use plain transforms instead.
    • After the live-markdown fix is released, bump the @expensify/react-native-live-markdown version in App's package.json and update the patch if one exists.

    What alternative solutions did you explore? (Optional)

    • Increase the watchdog timeout or ignore the Sentry event: rejected, because the app is still frozen and gets killed.
    • Run parsing fully asynchronously in all cases: rejected for the main fix. Text would flash unstyled while the user types, and edits would need reconciling with stale results. It is kept only as a fallback for the contended case.
    • Replace the JS parser with a native (C++) parser: the most robust option, because it removes the runtime lock entirely. It is too large for this issue and is a possible follow-up.
    • Disable layout animations globally in App: rejected as overly broad and a UX regression. The targeted audit in step 3 is preferred.

    Testing

    1. Unit/native test (live-markdown): mount a MarkdownTextInput with text and spy on MarkdownParser parse:. Update only markdownStyle, layout props or the font. Assert that the parser is not called again and that the attributes are updated correctly. Change the text and assert that it is called once.
    2. Contention test: in the live-markdown example app, hold the markdown runtime lock on a background thread, for example with a long-running worklet via runOnRuntime. Trigger a layout animation that changes the props of a MarkdownTextInput. Before the fix the main thread blocks. After the fix there is no hang, and the UI stays responsive.
    3. Manual in HybridApp iOS: open a report with a long draft in the composer, then trigger navigation and layout animations such as opening and closing the emoji picker, attachments, and the keyboard. Confirm there are no freezes, and that markdown formatting (bold, links, mentions, code) is still highlighted correctly after style changes.
    4. Monitoring: after release, watch Sentry issue APP-M0W for new events on the fixed version. It should stop recurring.
  7. MelvinBot commented on Oct 22, 2026

    @MelvinBot
    Contributor

    Updated 2026-10-25: Corrected based on feedback from TaduJR.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    The app freezes with a fatal App Hang (APP-M0W) while a Live Markdown input parses text on the main thread. The same hang appears on Android.

    What is the root cause of that problem?

    A lock-order deadlock between two worklet runtimes. TaduJR confirmed it with lldb on the iOS simulator.

    1. The main thread holds the UI runtime lock and waits for the markdown runtime lock. A Reanimated layout animation flush mounts a MarkdownTextInput, and Live Markdown parses its text on the main thread through the LiveMarkdownRuntime.
    2. The JS thread holds the markdown runtime lock and waits for the UI runtime lock. Our parser worklets read Reanimated SharedValues. On a runtime other than the UI runtime, a SharedValue read is a synchronous call into the UI runtime. Two parsers do this:

    What changed to cause this?

    • Start: the Reanimated 4.3.1 upgrade on 2026-06-01 made SharedValue reads on other runtimes synchronous calls into the UI runtime.
    • APP-EF1 was the same deadlock. live-markdown 0.1.336 (from Bump react-native-live-markdown) only changed where it shows up in the stack.
    • APP-M0W was first seen on 9.4.74-2. The JS thread holds the markdown lock in all 25 events.
    • Android: the same hang appears as APP-KA6, APP-KY2, APP-KH2, APP-NC2 and APP-M9K. This change fixes those too.

    What changes do you think we should make in order to solve the problem?

    Never read a SharedValue inside a parser worklet. Capture the data in the parser closure instead, and keep the parsers stable while typing.

    1. RNMarkdownTextInput: the default parser captures availableLoginsList in its closure. Pass a custom parser prop straight through instead of wrapping it.
    2. SearchAutocompleteInput: pass one KnownFilterValues object of Sets (userLogins, currencies, categories, tags, exportedTo) to parseForLiveMarkdown, and use Set.has in filterOutRangesWithCorrectValue.
    3. Use the closure, not a global on the markdown runtime. Live Markdown caches ranges by text and parser id. A global keeps stale highlights after a list changes, and the first parse can run before the effect sets it. With the closure, a list change gives the input a new parser id and it re-parses.
    4. Keep the parsers stable. A list with a new identity means a new parser id, a new registration, and an uncached parse on the main thread. So:
      • Select categories and tags with useOnyx selectors.
      • Build each Set where its list is created. Building it later in the component hits a React Compiler memoization issue.
      • In useExportedToFilterOptions, read the policy IDs again after useCombinedExportTemplates. React Compiler drops memoization for a value made before a hook call and used after it, so the hook returned a new array on every render and the Search parser changed on every keystroke.
    5. Remove the scheduleOnLiveMarkdownRuntime effects, the helper, and its mock in jest/setup.ts.

    The library hardening in react-native-live-markdown (main-thread parse reads only the cache) is out of scope and will be a separate follow-up.

    Tests
    • Update SearchAutocompleteUtilsTest to pass KnownFilterValues.
    • Add a test that useExportedToFilterOptions returns the same array across re-renders with unchanged data.
    • Add a test that SearchAutocompleteInput passes the same parser when only the query changes.

    What alternative solutions did you explore? (Optional)

    • A global on the markdown runtime set by an effect: rejected, because it keeps stale cached highlights and can miss the first parse.
    • Library change only: stops the main thread from blocking, but a background parse can still block on the UI runtime.
    • Turn off locking on LiveMarkdownRuntime: unsafe, because the parser runs on several threads.

    Confidence: high. TaduJR confirmed the lock owners with lldb.

    Implemented in Stop reading SharedValues in Live Markdown parsers to prevent an App Hang deadlock.

  8. camesenin commented on Oct 22, 2026

    @camesenin
  9. melvin-bot commented on Oct 22, 2026

    @melvin-bot

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  10. shilo1979jk commented on Oct 24, 2026

    @shilo1979jk

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    On HybridApp iOS, the app can freeze for >2 seconds (Sentry APP-M0W App Hang) when mounting or updating RNMarkdownTextInput while a layout animation is flushing on the main thread. The main thread blocks inside -[MarkdownParser parseUncached:withParserId:] waiting for the LiveMarkdownRuntime mutex while holding the Reanimated UI runtime lock.

    What is the root cause of that problem?

    The hang is a classic AB-BA lock-order inversion between the Reanimated UI runtime mutex and the LiveMarkdownRuntime worker mutex:

    1. Main thread (holds UI runtime lock -> waits for LiveMarkdownRuntime lock):
      During a Reanimated layout animation flush on the main thread (-[REANodesManager performOperations] -> executeLayoutAnimationsRequests), the main thread holds the UI runtime lock and flushes Fabric mount mutations (RCTMountingManager.mm:83 -> -[MarkdownTextInputDecoratorComponentView updateProps:oldProps:] -> applyNewStyles -> -[RCTMarkdownUtils applyMarkdownFormatting:inputView:] -> -[MarkdownParser parseUncached:withParserId:]). Because the component view's RCTMarkdownUtils instance has its own parser cache (separate from the shadow node's cache), the cache misses on initial mount and synchronously enters LiveMarkdownRuntime, waiting on its std::recursive_mutex.

    2. LiveMarkdownRuntime worker thread (holds LiveMarkdownRuntime lock -> waits for UI runtime lock):
      In src/components/RNMarkdownTextInput.tsx:38 and 62-81, mentionsSharedVal is a Reanimated SharedValue (useSharedValue<string[]>(availableLoginsList)):

      const parserWorklet = useCallback(
          (text: string) => {
              'worklet';
      
              if (parser) {
                  return parser(text);
              }
      
              return parseExpensiMarkWithShortMentions(text, mentionsSharedVal.get(), currentUserMentions);
          },
          [currentUserMentions, mentionsSharedVal, parser],
      );

      In react-native-reanimated, reading mentionsSharedVal.get() from a non-UI worker runtime (LiveMarkdownRuntime) calls getSync() (mutables.native.ts), which synchronously dispatches into the UI runtime and waits to acquire the UI runtime lock.

    3. Why a simple useEffect-only runtime global is not enough on initial mount:
      If mentionsSharedVal is removed and replaced only by a globalThis assignment inside useEffect(() => { scheduleOnLiveMarkdownRuntime(...); }, [availableLoginsList]), the very first synchronous parse during Fabric mount (RCTMountingManager Insert mutation) executes before React's useEffect and before the asynchronous scheduleOnRuntime task runs on LiveMarkdownRuntime. At that moment, the runtime global would still be undefined, causing existing draft @shortMentions to fail to highlight on initial mount.

    What changes do you think we should make in order to solve the problem?

    In src/components/RNMarkdownTextInput.tsx:

    1. Remove useSharedValue (mentionsSharedVal) completely so parserWorklet never makes a synchronous cross-runtime getSync() call into the UI runtime while holding the LiveMarkdownRuntime lock.
    2. Store availableLoginsList in a LiveMarkdownRuntime-local global (globalThis.__liveMarkdownAvailableLogins) WITH an initial closure fallback for synchronous mount parses:
      • Keep a ref (const initialAvailableLoginsRef = useRef(availableLoginsList);) captured once when parserWorklet is created so that if parserWorklet runs synchronously during the initial Fabric mount (before useEffect / scheduleOnLiveMarkdownRuntime has executed), globalThis.__liveMarkdownAvailableLogins ?? initialAvailableLogins already has the initial list without re-creating parserWorklet on every availableLoginsList update.
      • In useEffect, use scheduleOnLiveMarkdownRuntime to update globalThis.__liveMarkdownAvailableLogins = availableLoginsList directly on the markdown runtime whenever availableLoginsList changes:
      const initialAvailableLoginsRef = useRef(availableLoginsList);
      
      const parserWorklet = useCallback(
          (text: string) => {
              'worklet';
      
              if (parser) {
                  return parser(text);
              }
      
              const initialLogins = initialAvailableLoginsRef.current;
              const logins = (globalThis as {__liveMarkdownAvailableLogins?: string[]}).__liveMarkdownAvailableLogins ?? initialLogins;
              return parseExpensiMarkWithShortMentions(text, logins, currentUserMentions);
          },
          [currentUserMentions, parser],
      );
      
      useEffect(() => {
          scheduleOnLiveMarkdownRuntime((nextLogins: string[]) => {
              'worklet';
      
              (globalThis as {__liveMarkdownAvailableLogins?: string[]}).__liveMarkdownAvailableLogins = nextLogins;
          }, availableLoginsList);
      }, [availableLoginsList]);
      (Note: scheduleOnLiveMarkdownRuntime in src/libs/scheduleOnLiveMarkdownRuntime/index.native.tsx accepts (worklet, ...args) and forwards ...args to scheduleOnRuntime, avoiding recreating the worklet closure on every render.)

    What alternative solutions did you explore? (Optional)

    • Capturing availableLoginsList directly in parserWorklet's useCallback dependency array ([availableLoginsList, currentUserMentions, parser]): Rejected because availableLoginsList can contain up to 20,000 logins on large accounts; re-registering a new parserId and re-serializing the full array on every personal-details update would add unnecessary overhead.
    • Setting globalThis.__liveMarkdownAvailableLogins in useEffect without an initial fallback: Rejected because Fabric mount (updateProps -> applyNewStyles) invokes parserWorklet synchronously before useEffect runs, which would leave logins empty on initial mount.
  11. 21 remaining items

  12. mountiny commented on Nov 6, 2026

    @mountiny
    ContributorAuthor

    Getting there.

  13. jeffrey-graham commented on Nov 7, 2026

    @jeffrey-graham
  14. melvin-bot commented on Nov 7, 2026

    @melvin-bot
  15. TaduJR commented on Nov 9, 2026

    @TaduJR
    Contributor

    @MelvinBot

    Please remove the Payment Label from the issue title.

  16. changed the title [-][Due for payment 2026-11-13] [$175] [Sentry: APP-M0W] HybridApp iOS: App Hang, Live Markdown parser blocks the main thread on the JS runtime lock[/-] [+][$175] [Sentry: APP-M0W] HybridApp iOS: App Hang, Live Markdown parser blocks the main thread on the JS runtime lock[/+] on Nov 9, 2026
  17. MelvinBot commented on Nov 9, 2026

    @MelvinBot
    Contributor

    Removed “[Due for payment 2026-11-13]” from the issue title.


    view run

  18. melvin-bot commented on Nov 12, 2026

    @melvin-bot

    @TaduJR Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

  19. expensify-chore-bot commented on Nov 18, 2026

    @expensify-chore-bot

    @TaduJR Now this issue is 8 days overdue. Are you sure this should be a Daily? Feel free to change it!

  20. added and removed on Nov 19, 2026
  21. expensify-chore-bot commented on Nov 19, 2026

    @expensify-chore-bot

    @mountiny @TaduJR this issue is now 4 weeks old, please consider:

    • Finding a contributor to fix the bug
    • Closing the issue if BZ has been unable to add the issue to a VIP or Wave project
    • If you have any questions, don't hesitate to start a discussion in #expensify-open-source

    Thanks!

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

Metadata

Metadata

Labels

BugSomething is broken. Auto assigns a BugZero manager.ExternalAdded to denote the issue can be worked on by a contributorSkip PaymentSkips all the payment process steps for an issue. Use it for fixed-price projects.WeeklyKSv2

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions