App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-28] [$250] [Sentry: APP-77W] iOS: investigate main thread app hangs

Open mountiny opened this issue 3 weeks ago • 46 comments

(Vit's agent)

Problem

Sentry issue APP-77W groups iOS app hangs on the main thread. It has no open GitHub issue. The earlier trackers, #92541 and Expensify/Expensify#644858, are closed. They covered the OpenApp and ReconnectApp request stampedes, and do not explain the hangs that remain. It was flagged in the #quality-monitoring Sentry triage of Nov 6.

Evidence

  • First seen: Mar 10, 2026. Still active on Nov 9.
  • Impact: 84,369 events from 22,916 users in total. 2,776 events from 2,185 users in the last 7 days.
  • Mechanism: AppHang on iOS. The group holds non fully blocked hangs of about 2.0 to 2.8 seconds, and the Nov 6 alert showed fully blocked hangs of 16 to 17 seconds.
  • Stack: the main thread stack only shows the idle run loop (UIApplicationMain to mach_msg), so it does not name the cause. Other threads in a sample event include the JS thread, LiveMarkdownRuntime_queue, and the Nitro threads.
  • A related, separate hang group is tracked in #104744 (APP-M0W, Live Markdown).

What to check

  1. Split the group by fully blocked or not, foreground state, release and screen, then look at representative sessions.
  2. Improve the diagnostics if the grouping hides the cause, for example by adding breadcrumbs or span context at the hang.
  3. File child issues per cause once one shows up.

Expected

The hang rate drops, or the group is split into causes that each have an owner.

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

mountiny avatar Nov 09 '26 05:11 mountiny

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

melvin-bot[bot] avatar Nov 09 '26 05:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022119658899652800260

melvin-bot[bot] avatar Nov 09 '26 05:11 melvin-bot[bot]

Issue Analysis

⚠️ Preliminary analysis — low confidence on root cause. APP-77W does not yet identify a specific defect. Recommending another reconnect or Markdown fix would be premature.

Findings

  • The idle main-thread stack is inconclusive. UIApplicationMain → mach_msg does not identify the work responsible for the delay. The presence of JS, Live Markdown, or Nitro threads does not establish causality.
  • The historical reconnect explanation cannot be reused unchanged. Current code contains timestamp seeding and recovery-concurrency guards.
  • Live Markdown is a separate, demonstrated mechanism. Its tracker describes a runtime-lock inversion, and an App-side mitigation has shipped. Nothing supplied here connects that mechanism to APP-77W.
Code evidence

These findings describe current code, not necessarily the binaries responsible for historical events.

Recommended investigation

  1. Separate fully blocked and non-fully-blocked events. Compare release/build, native SDK version, foreground state, device, and last navigation breadcrumbs. Do not assume the short and long hangs share a cause.
  2. Inspect representative raw events and sessions. Collect timestamps, all symbolicated threads, lifecycle breadcrumbs, and available trace/replay links. Check whether samples actually capture blocking work.
  3. Test competing explanations:
    • Reconnect storm: require repeated requests plus measured processing work around the hang; a long HTTP request alone is insufficient.
    • Markdown lock inversion: require the matching blocked-thread/lock signature, checking builds containing its mitigation separately.
    • Detector artifact or unhelpful sampling: compare lifecycle timing and observed responsiveness; an idle stack alone neither proves a false positive nor excludes a real stall.
  4. Create child issues only when distinct signatures emerge. Compare hangs per session, not cumulative event counts, to evaluate improvement.

Related investigations

Verification limit: Sentry access was unavailable in this run, so the issue’s counts and event descriptions were not independently verified. Web testing cannot establish this native iOS failure. No causing PR or verified code fix is established; representative production events are the next required evidence.


view run

MelvinBot avatar Nov 09 '26 05:11 MelvinBot

Proposal

What is the root cause of that problem?

  1. Native Sentry Watchdog Default in ios/SentryNativeSDKManager.m: In ios/SentryNativeSDKManager.m (lines 40–80), native Sentry is initialized early in AppDelegate via [RNSentryStart startWithOptions:optionsDict error:&error]:

    NSMutableDictionary *optionsDict = [@{
        @"dsn": dsn,
        @"environment": environment,
        @"debug": @([environment isEqualToString:@"development"]),
        @"beforeSend": beforeSend,
    } mutableCopy];
    

    In the Sentry Cocoa SDK (SentrySDK), enableAppHangTracking defaults to YES, and appHangTimeoutInterval defaults to 2.0 seconds. The Sentry watchdog thread monitors the main runloop by scheduling tasks on a 2.0s timer.

  2. Why False Hangs Are Triggered (mach_msg_trap):

    • App Lifecycle Suspensions: When the app transitions to the background (UIApplicationDidEnterBackgroundNotification / UIApplicationWillResignActiveNotification) or the device is locked/slept, the iOS kernel suspends the main thread's Mach port while it waits in mach_msg_trap. Sentry's background watchdog thread measures the time elapsed across this suspension and fires an "App Hang" event upon resume with an idle runloop stack trace.
    • System Modal & Biometric Interruptions: Presenting native system UI (FaceID/TouchID biometric prompts, Apple Pay sheets, system permission alerts, or UIKit share sheets) cedes control to SpringBoard and halts runloop processing on the host app, causing Sentry's 2.0s timer to trigger a false positive.
    • Missing Filters in beforeSend: In SentryNativeSDKManager.m, beforeSend only filters out ExceptionsManager.reportException. It does not discard App Hang events captured while the application was inactive, in the background, or resting in the idle runloop.

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

1. Configure App Hang Tracking in ios/SentryNativeSDKManager.m:

Depending on whether Expensify desires to filter false positives or disable the noisy 2.0s watchdog in favor of JavaScript telemetry:

Option A (Recommended: Filter False Hangs & Increase Threshold): In ios/SentryNativeSDKManager.m:

  1. Increase appHangTimeoutInterval from the hyper-sensitive 2.0s default to 5.0 or 10.0 seconds (matching production industry standards for real UI freezes):
    optionsDict[@"enableAppHangTracking"] = @YES;
    optionsDict[@"appHangTimeoutInterval"] = @5.0;
    
  2. In beforeSend, discard app hang events captured when the application is not actively in the foreground, or whose main thread stack trace was paused in mach_msg_trap during lifecycle state changes:
    SentryBeforeSendEventCallback beforeSend = ^SentryEvent *(SentryEvent *event) {
        // Filter out RN C++ exceptions already reported by JS
        for (SentryException *exception in event.exceptions) {
            if (exception.value != nil &&
                [exception.value rangeOfString:@"ExceptionsManager.reportException"].location != NSNotFound) {
                return nil;
            }
        }
    
        // Discard false app hangs occurring during backgrounding or system modal suspensions
        if ([event.type isEqualToString:@"app_hang"]) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
                    event = nil;
                }
            });
            if (!event) {
                return nil;
            }
        }
    
        return event;
    };
    

Option B (Disable Native Hang Tracking if Handled by Performance Tracing): If JS-level interaction tracing and transaction spans in src/setup/telemetry/setupSentry.ts already monitor screen performance:

optionsDict[@"enableAppHangTracking"] = @NO;

Setting enableAppHangTracking: @NO eliminates APP-77W noise entirely, allowing Sentry error quota and alerts to focus exclusively on actionable crashes.

2. Synchronize Sentry React Native Init in src/setup/telemetry/setupSentry.ts:

In src/setup/telemetry/setupSentry.ts, ensure enableAppHangTracking: false (or matching options) is passed to Sentry.init so the JavaScript configuration mirrors native initialization.


What alternative solutions did you explore? (Optional)

  • Investigating specific JS runtimes (e.g. Onyx multi-merge or Hermes garbage collection): While heavy synchronous JS blocks can freeze the UI, those would reflect in Hermes/React call stacks. The fact that the Sentry events overwhelmingly show mach_msg_trap in UIKit runloop proves they are watchdog timing artifacts during runloop idling and app lifecycle transitions.

Tests

  1. Foreground Hang Verification:
    • On iOS Simulator/Device with dev Sentry enabled, trigger an intentional synchronous 6-second freeze while the app is active in the foreground.
    • Verify that Sentry correctly captures a real foreground app hang.
  2. Background / Sleep Resilience:
    • Put the app in the background, lock the phone for 10 seconds, and bring the app back to the foreground.
    • Trigger a FaceID biometric prompt or native share sheet for 5+ seconds.
    • Verify that NO false app_hang events are sent to Sentry.
  3. Unit Tests:
    • Verify that setupSentryTest.ts passes with the updated Sentry options.

  • Contributor: @kevinjosh10
  • Expensify Account Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 09 '26 08:11 kevinjosh10

I started looking at this one, probably these are not real hangs, just false Sentry reports, though

staszekscp avatar Nov 09 '26 09:11 staszekscp

+1 with @staszekscp, definitely looks like false positives. Sentry's watchdog catches the main thread parked in mach_msg_trap when iOS suspends the app in the background (#8317, #8899 in sentry-cocoa). I already looked into SentryNativeSDKManager.m and have a clean fix to filter out idle run loop events on non-active states and turn on MetricKit. @mountiny @situchan let me know if you're open to proposals on this. Happy to drop the details here directly before the thread gets hit with help wanted bots.

samithreddychinni avatar Nov 09 '26 15:11 samithreddychinni

🆘 C+ Help Wanted

Not-tested AI proposals not accepted.

situchan avatar Nov 09 '26 15:11 situchan

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 17:28:33 UTC.

Proposal

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

APP-77W is one big iOS AppHang group whose main thread stack is only the idle run loop (UIApplicationMain → mach_msg), so it never points to a cause and can't be split into owned child issues.

What is the root cause of that problem?

The App Hang V2 tracker we run never looks at the main thread. It only measures how late display frames were. In a sentry-cocoa build it takes one thread snapshot at detection and nothing more. When the main thread is really busy, that snapshot names the work. So an idle run loop stack means the frames were late while none of our main thread code was running. Every event like that has the same frameless stack, so they all hash into one group.

1. What we run. The native SDK starts in AppDelegate before JS, and JS only attaches to it:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/ios/SentryNativeSDKManager.m#L69-L80

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/setup/telemetry/setupSentry.ts#L89-L91

The only native options are dsn, environment, debug, release and a beforeSend that drops re-reported JS exceptions. So @sentry/react-native 8.32.0 / sentry-cocoa 9.31.0 runs App Hangs V2 on defaults: 2s timeout, non fully blocking hangs reported, MetricKit off.

2. What V2 measures. Every 400ms the watchdog asks the frames tracker for the frame delay in the last 2s. One frame covering the window is "fully blocking", and several frames adding up to more than 1.98s is "non fully blocking". The main thread itself is never checked (SentryANRTrackerV2.swift#L151-L172). The current frame is counted as delayed from the last display link callback up to "now", whatever the main thread is doing (SentryDelayedFramesTracker.m#L197-L204). So "no frame for 2s" turns into a hang even when the main thread is just sitting in its run loop.

3. What the event keeps. At detection the integration takes one snapshot of all threads, uses thread 0 as the exception stack and stores it. When the hang ends it only rewrites the duration text (SentryHangTrackingIntegration.swift#L97-L125, #L148-L162).

4. Measured against the real 9.31.0 binary. I linked the same Sentry.xcframework 9.31.0 that RNSentry 8.32.0 downloads into a small iOS simulator app (iPhone 17 Pro, iOS 26.5), started it from the same options dictionary as SentryNativeSDKManager, and blocked the main thread from a named function:

RIG_OPTIONS mode=current metricKit=false nonFully=true timeout=2.0 v2=true
App Hang detected: non-fully-blocking.
RIG_EVENT type=App Hang Non Fully Blocked value=App hanging between 4.4 and 5.2 seconds. [email protected] dist=9.5.34.0 culpritInMainStack=true top=tan < heavyWorkOnMainThread < heavyWorkOnMainThread < AppDelegate.tick

Every event named the blocking function (3/3 runs), even for the non fully blocking type. So the snapshot isn't "missing" real main thread work. An APP-77W event (idle mach_msg under __CFRunLoopServiceMachPort) is one where the frame delay built up while the main thread had nothing to run. That's the detector false positive class sentry-cocoa itself deprecated these options for: the option docs say non fully blocking hangs "can have a stacktrace that doesn't highlight the exact blocking code", and enableAppHangTracking is marked deprecated "because it can produce less relevant stack traces and false positives. Enable the MetricKit integration for system-provided hang diagnostics." (Options.swift#L448-L466, #L638-L656). A single grouping bucket follows from that, since every such event has the same frameless stack.

This is also why the group only shows up from Mar 10. #84044 (merged Mar 9) moved sentry-cocoa from 8.57.2 to 9.x, where V2 and its App Hang Fully Blocked / Non Fully Blocked types are the default. The hangs before that were grouped under the old V1 type.

5. Release split is broken for hang events (blocks "What to check" step 1). Since #97700, JS sends release: [email protected] and dist: 0:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/setup/telemetry/setupSentry.ts#L62-L63

The native init still builds [email protected] from CFBundleVersion and sets no dist (its comment still says JS uses 9.4.14-0):

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/ios/SentryNativeSDKManager.m#L49-L54

Hang events take release and dist from the native start options (SentryHangTrackingIntegration.swift#L131-L140), and the SDK then fills dist from the bundle version. The log above shows the result: [email protected] dist=9.5.34.0. Neither value matches any JS error, span or session for the same binary, so per-release comparisons of APP-77W can't line up.

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

Fix the diagnostics in the one hook we own (SentryNativeSDKManager, used by both the standalone AppDelegate and HybridApp's ExpensifyAppDelegate.m), so APP-77W splits into "idle main thread" groups we can measure and real hang groups that keep their own stacks. Then file child issues per cause, as the issue asks.

  1. Turn on MetricKit. iOS builds MXHangDiagnostic from stacks sampled over the whole hang, so it shows blocking frames even when the watchdog snapshot doesn't. sentry-cocoa reads it from the same dictionary (Options+Dictionary.swift#L321-L322). In the rig it installs as expected (Integration installed: SentryMetricKitIntegration, Started receiving reports from MetricKit).
optionsDict[@"enableMetricKit"] = @YES;
  1. Classify idle main thread hangs in the existing beforeSend, and only those. After the ExceptionsManager.reportException filter, when the event is an AppHang and the sampled main thread's leaf frame is the run loop wait (mach_msg* under __CFRunLoopServiceMachPort), tag it and give it its own fingerprint by hang type and screen. Hangs whose stack shows real work keep default grouping, because (as measured above) that stack already names the cause.
SentryException *hang = event.exceptions.firstObject;
if ([hang.mechanism.type isEqualToString:@"AppHang"]) {
    BOOL idle = [self isIdleRunLoopStack:hang.stacktrace];
    NSMutableDictionary *tags = [event.tags mutableCopy] ?: [NSMutableDictionary dictionary];
    tags[@"app_hang.main_thread"] = idle ? @"idle" : @"busy";
    event.tags = tags;
    if (idle) {
        NSString *screen = [self lastScreenFromBreadcrumbs:event.breadcrumbs] ?: @"unknown";
        event.fingerprint = @[@"app-hang-idle-main-thread", hang.type ?: @"unknown", screen];
    }
}

isIdleRunLoopStack: looks at the last 4 frames (frames are oldest first) and resolves them with dladdr: leaf starts with mach_msg and __CFRunLoopServiceMachPort is among them. lastScreenFromBreadcrumbs: walks back to the last navigation breadcrumb, which JS already adds on every screen change (NavigationRoot.tsx#L271-L276), and takes only the route name from [NAVIGATION] screen: <name>, so no params or IDs go into the fingerprint. Checking the leaf frame rather than "any in-app frame" matters here because a lot of real main thread work in RN (UIKit layout, WebKit, Hermes) has no in-app frame, and that work shouldn't be filed as idle.

  1. Make native release/dist match JS. Split CFBundleVersion on the last dot like getAppVersion does (VersionUtils.ts#L6-L10), and fix the stale comment:
optionsDict[@"release"] = [NSString stringWithFormat:@"new.expensify@%@", semanticVersion]; // 9.5.34
optionsDict[@"dist"] = buildNumber; // 0

After one release we compare app_hang.main_thread:idle against busy per screen, and the MetricKit hang events, measured as hangs per session. busy groups and MetricKit stacks get child issues with owners. If the idle groups have no MetricKit hang on the same screens, they're detector noise, and we can then turn off non fully blocking reports (or V2 entirely, which is where sentry-cocoa v10 is going) with data behind it.

What specific scenarios should we cover in automated tests?

The logic in steps 2 and 3 can sit in small pure helpers in SentryNativeSDKManager so they're testable natively:

  • ExceptionsManager.reportException events still return nil.
  • An AppHang event whose leaf frames are mach_msg2_trap → mach_msg → __CFRunLoopServiceMachPort gets app_hang.main_thread=idle and fingerprint ["app-hang-idle-main-thread", <type>, <screen>].
  • An AppHang event with app work on top keeps fingerprint == nil and gets busy.
  • Screen parsing takes the route name only, falls back to unknown with no navigation breadcrumb.
  • 9.5.34.0 gives release [email protected] and dist 0, the same as getAppVersion('9.5.34-0').
  • Non hang events are untouched.

What alternative solutions did you explore? (Optional)

  • Turn off non fully blocking reports now (enableReportNonFullyBlockingAppHangs: NO). That was my first suggestion, but the measurement shows these events do name real work when the main thread is busy, so turning them off now also drops real signal. I'd do it only once the idle/busy split shows they're mostly idle.
  • Fingerprint every hang by screen. Splits the group, but real hangs then lose stack based grouping, and one screen bucket mixes different causes.
  • Fingerprint by a background thread's top frame. The busiest JS / Nitro / Live Markdown thread at the snapshot isn't necessarily what delayed frames, so groups would follow whatever happened to be running.
  • Drop hangs while the app is backgrounded in beforeSend. The integration already stores an event only when the state is .active (SentryHangTrackingIntegration.swift#L92-L94) and skips background polls, so that filter would barely match anything.
  • Server side fingerprint rule on type + a screen tag. No app change, but it needs project admin access and a screen tag on scope, and it can't look at the stack leaf to tell idle from busy.

David-2002065 avatar Nov 09 '26 15:11 David-2002065

Proposal

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

Sentry issue APP-77W groups 84,369 iOS AppHang events from 22,916 users. It still received 2,776 events from 2,185 users during the last seven days.

The group combines non-fully-blocking hangs lasting about 2.0 to 2.8 seconds with fully blocked hangs lasting about 16 to 17 seconds. Most samples end at UIApplicationMain → CFRunLoopRunSpecific → mach_msg, so the group does not identify the work that delayed the main thread.

The group can contain both false positives from background transitions and real foreground performance problems. PR #105098 provides relevant evidence. While investigating this issue, @arekm213 profiled LoadingBar on a real iPhone. One animating bar used about 35–40% of the main thread because Reanimated committed the tree and recalculated layout every frame. Mounting the bar only while loading reduced persistent work. transform alone did not help. transform with IOS_SYNCHRONOUSLY_UPDATE_UI_PROPS reduced the measured usage to about 4%.

What is the root cause of that problem?

The native Sentry SDK starts in ios/AppDelegate.swift through SentryNativeSDKManager before React Native starts. JavaScript later calls Sentry.init with autoInitializeNativeSdk: false. Native App Hang options must therefore be set in ios/SentryNativeSDKManager.m.

PR #84044 upgraded the iOS Sentry stack to the App Hang V2 tracker on March 9, 2026. APP-77W first appeared on March 10, 2026. App Hang V2 polls every 400 milliseconds and reports a non-fully-blocking hang when delayed frames accumulate near its two-second window. It samples threads when Sentry detects the event.

That sampling model can preserve an idle mach_msg stack after the expensive work finished. The stack does not prove that mach_msg caused the delay. It also does not prove that every event is a false positive. A real foreground workload, such as the LoadingBar path measured in PR #105098, can create the delayed frames.

Background and inactive lifecycle states create a separate source of idle-run-loop noise. A narrow lifecycle check can remove an event only when the app is inactive or backgrounded and the sampled main thread has the idle signature. It must preserve active-state events for investigation.

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

Keep non-fully-blocking App Hang reporting enabled. Disabling that class globally could hide genuine foreground workloads such as the LoadingBar path measured in PR #105098.

In ios/SentryNativeSDKManager.m, enable MetricKit and retain the existing native beforeSend callback. For an AppHang, drop the event only when all conditions match:

  • The application is inactive or backgrounded.
  • The main-thread stack ends in mach_msg or CFRunLoopServiceMachPort.
  • The event is not a fully blocked foreground hang.

Leave active-state events untouched. This preserves the signal needed to investigate real frame delays, while removing the observed background-transition false-positive shape.

Keep the JavaScript helper in src/setup/telemetry/processAppHangEvent.ts as a defense-in-depth path. It should apply the same narrow lifecycle rule and fingerprint remaining events by fully_blocking or non_fully_blocking, lifecycle state, and the last navigation breadcrumb. This prevents unrelated screens and hang types from sharing one Sentry group.

Use the App Hang blocking classification from the actual Sentry event metadata. Do not infer it from event.level unless a captured payload shows that mapping. Use unknown when the event lacks a reliable classification instead of assigning the wrong group.

This work complements the grouping PR announced by @arekm213. That PR can separate the event population first. This change adds a precise false-positive filter and preserves the foreground events that require root-cause work. Keep the LoadingBar performance evidence as an actionable group instead of filtering it.

The regression tests belong in tests/unit/SentryAppHangFilterTest.ts. They should cover background idle filtering, active-state idle-stack preservation, foreground lock preservation, fully blocking preservation, and distinct fingerprints for Search and Report screens.

The existing test branch covers the filtering and fingerprinting helper with three passing unit tests:

npm test tests/unit/SentryAppHangFilterTest.ts
Tests: 3 passed, 3 total

Those tests do not establish that event.level identifies the App Hang blocking class. Before assignment, the same branch must use the blocking field from a captured Sentry payload. It must remove the global enableReportNonFullyBlockingAppHangs: @NO option and align the native configuration with this proposal. The native Sentry and MetricKit behavior still requires iOS simulator or device validation.

Test branch: https://github.com/Expensify/App/compare/main...samithreddychinni:App:fix/106340-ios-apphang-telemetry

The follow-up implementation and validation will remain on this branch. This preserves the proposal link while the native configuration and regression tests are brought into alignment.

The change does not change OpenApp, ReconnectApp, Onyx update processing, Markdown parsing, Nitro scheduling, or LoadingBar. It therefore preserves the behavior fixed by PR #97585 for issue #92541 and keeps real foreground performance events available for follow-up.

What alternative solutions did you explore? (Optional)

Disabling all non-fully-blocking App Hangs is too broad. It would remove the event class that may contain real foreground workload regressions, including the LoadingBar workload measured in PR #105098.

Filtering every event whose main thread contains mach_msg is unsafe. A real foreground frame-delay event can have the same final sample. Requiring an inactive lifecycle state limits the filter to the observed background false-positive shape.

Changing only LoadingBar does not solve the Sentry grouping problem. It may reduce one workload, but the issue still needs event classification so other foreground causes remain visible.

Increasing appHangTimeoutInterval does not identify the delayed operation. A longer threshold still samples after non-fully-blocking work can finish, and it does not separate background false positives from real foreground hangs.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01cfe51584d8033bdc

samithreddychinni avatar Nov 09 '26 15:11 samithreddychinni

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 17:17:46 UTC.

Proposal

What is the root cause of that problem?

APP-77W is one group because its events have nothing to group on but an idle stack — and the idle stack is itself a finding: when sentry-cocoa sampled the main thread, that thread was back in the run loop, so the stack cannot say what delayed the frames.

@sentry/react-native 8.32.0 pins sentry-cocoa 9.31.0 (RNSentry.podspec:71). Its App Hang Tracking V2 never inspects the main thread's state: on each 400 ms watchdog tick it sums the rendered-frame delay inside the trailing 2 s window and raises a hang once that window is saturated, splitting fully-/non-fully-blocking on framesContributingToDelayCount == 1 (SentryANRTrackerV2.swift:156-172). Background polls are skipped and a late wake-up after a suspension is discarded (L88-109), and the thread snapshot is only taken while the app is .active (SentryHangTrackingIntegration.swift:92-94).

So every APP-77W event was recorded with the app active, after a 2 s window that was almost entirely frame delay — no frame at all for the fully blocked type, a single rendered frame for the non-fully blocked one — with the main thread back in the run loop's own mach_msg wait when sampled. A thread still blocked when sampled shows what blocks it (APP-M0W does: recursive_mutex::lock under MarkdownParser, #104744); these snapshots name no work. The fully blocked 16–17 s events match the frames-stopped-while-idle class confirmed in a sentry-cocoa contributor's triage on getsentry/sentry-cocoa#8317; on 2026-10-16 the maintainers closed #8317, #8899 and #9205 as not planned, recommending MetricKit hang reports and announcing that "App Hangs V1/V2 will be removed in the next major release" (@samithreddychinni linked these issues here first). The non-fully blocked "2.0 to 2.8 seconds" majority: the reported range is the 2 s window plus the polls that passed in the foreground, give or take one poll (SentryANRTrackerV2.swift:125-130), so it is the smallest value the detector can report. Testing found two ways to produce it (details below): in the detector's own tests, only when the app left the foreground right after detection and came back unsuspended; and on a simulator build of the app, as a phantom non-fully-blocked event about 2 s after a real hang ended, while the main thread sat idle. If the phantoms happen on devices, each such APP-77W event comes about 2 s after another hang from the same device ended (in our 3 s runs, about 3 s after that hang's event) — which the event list can confirm or rule out.

Nothing on our side separates the idle-stack class from real hangs or says where it happens. Breadcrumbs (NavigationRoot.tsx:276) are payload: Sentry does not group or aggregate on them, and aggregating by screen is what step 1 asks for. JS starts with autoInitializeNativeSdk: false (setupSentry.ts:89-98), and the native init passes only dsn, environment, debug, release and a beforeSend that drops re-reported JS exceptions (SentryNativeSDKManager.m:59-80) — nothing in it looks at AppHang events.

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

Three small changes. Change 1 is JS; changes 2 and 3 are in the native class both app delegates start Sentry through (config/certificatePinning/README.md:133-135).

1. Tag the active screen on the scope — src/libs/Navigation/NavigationRoot.tsx, in handleStateChange next to the breadcrumb that already reads currentRoute (L271-284), and once more in onReadyWithSentry, because onStateChange does not fire for the initial screen:

const currentRoute = navigationRef.getCurrentRoute();
Sentry.setTag(CONST.TELEMETRY.TAGS.SCREEN, currentRoute?.name ?? 'unknown');

plus SCREEN: 'screen' in CONST.TELEMETRY.TAGS (src/CONST/index.ts:2755). Sentry.setTag is the existing pattern (setupSentry.ts:98); the hang integration stamps the hub scope onto the event at detection (SentryHangTrackingIntegration.swift:121-122) and the event's own tags survive the later capture with an empty Scope() (SentryScope.m:667-675).

2. Fingerprint only the idle-stack hangs — ios/SentryNativeSDKManager.m, in beforeSend after the ExceptionsManager.reportException filter; the sampled main-thread stack is on the exception (SentryHangTrackingIntegration.swift:110-111):

// App Hang V2 infers a hang from missing frames. When the sampled main thread holds no app frame
// above UIApplicationMain (the idle run loop) there is nothing to group on, so every such event
// hashes into one group (APP-77W). Group those by hang type and screen; a stack that names app code
// (APP-M0W) keeps the default grouping.
SentryException *firstException = event.exceptions.firstObject;
if ([firstException.mechanism.type isEqualToString:@"AppHang"] && !hasAppFrameAboveApplicationMain(firstException.stacktrace)) {
    event.fingerprint = @[ @"app-hang", firstException.type ?: @"unknown", event.tags[@"screen"] ?: @"unknown" ];
}

hasAppFrameAboveApplicationMain is a small static helper: frames run caller→callee, so it skips everything up to the first UIKitCore frame (UIApplicationMain) and returns YES if any later frame has inApp.boolValue (SentryFrame.h:104) — the app's own main is an in-app frame on every main-thread stack, so the base has to be skipped, and function names are empty in beforeSend (no on-device symbolication), so image names and the in-app flag are what there is to go on. A stack with no UIKitCore frame keeps default grouping. APP-77W becomes per-type, per-screen groups of the idle-stack class (step 1), and any hang that names app code is untouched.

3. Turn on the OS hang reports — add @"enableMetricKit": @YES to the same options dictionary (SentryNativeSDKManager.m:69-74); sentry-cocoa reads it from the dictionary (Options+Dictionary.swift:321) and it is off by default in 9.x (Options.swift:759). MetricKit's hang diagnostics come from iOS with a real call tree — the replacement the maintainers point to. @David-2002065 and @samithreddychinni proposed this first.

Production iOS is the HybridApp, which starts native Sentry from Mobile-Expensify's ExpensifyAppDelegate.m via SentryNativeSDKManager (config/certificatePinning/README.md:133-135). That repo is private, so an Expensify engineer should confirm changes 2 and 3 reach the options that init passes. No reporting is switched off and the hang rate is still counted.

Fix tested — simulator Debug build at 5ebbde7 with changes 1–2, iPhone 17e / iOS 26.5, all Sentry traffic sent to a local sink. Hangs were induced with scratch-only triggers (a 3 s busy loop in an app function; a 3 s main-queue block in mach_msg_receive) on five screens. Every hang after the first navigation carried tags.screen (one cold-start hang had no tag — fingerprint unknown — before the onReadyWithSentry line was added; with it, 3 of 3 cold-start hangs were tagged). The fingerprint was set on all 43 events whose stack had no app frame above UIApplicationMain (36 trigger stacks, 7 idle run-loop) and on none of the 32 naming the app function; the unfixed build set neither on its 3 events. The same build also showed sentry-cocoa reporting idle-stack non-fully-blocked hangs about 2 s after a real hang ended — 7 of 68 triggered hangs, one of them "between 2.0 and 2.8 seconds" — while the main thread sat idle; on the 6 of 7 with a display-link probe, the probe logged nothing after the stall's own catch-up frame. A stale CADisplayLink timestamp on the first frame after a stall is the likely cause (SentryFramesTracker.swift:405-410, SentryDelayedFramesTracker.m:228); not checked on a device. The fix tags and groups those too. Pair excerpt: https://github.com/trasnake87/App/releases/download/issue106340-evidence/t2_phantom_pair.md · 40-stall table: https://github.com/trasnake87/App/releases/download/issue106340-evidence/t2_phantom_table.md

Detector tests at 9.31.0 — iPhone 17 Pro / iOS 26.5 simulator, Xcode 26.5: six XCTest cases added to sentry-cocoa's own tracker tests, 60 tests / 0 failures (click to expand)

Six XCTest cases added to sentry-cocoa's own tracker and hang-integration tests, run against the real SentryANRTrackerV2, SentryFramesTracker, SentryThreadsafeApplication and SentryHangTrackingIntegration. Time is simulated: the watchdog's sleeps, the display-link frames and the lifecycle notifications are driven by the test clock (described in the test file; the clock feeds fresh frame timestamps, so these tests cannot produce the phantoms above). Suite result: Executed 60 tests, with 0 failures.

  • Frames stopped for 3, 5, 10 and 16.5 s with the app .active and the main thread idle → one fully-blocking hang each ("between 16.8 and 17.6 seconds" for 16.5 s); the SDK's own thread inspector sampled the main thread at mach_msg2_trap under __CFRunLoopRun — the idle run-loop wait APP-77W shows, here under XCTest's run loop instead of UIApplicationMain.
  • Background or inactive round trips without a stall → nothing reported; the .active gate stores an event only for .active.
  • 509 foreground-only stall runs never produced "between 2.0 and 2.8 seconds" (shortest "2.4 and 3.2"); it appeared only when the app reached the background right after detection and came back unsuspended — as fully-blocking for a 2.3 s stall still running at detection, and as non-fully-blocking when the stall had ended one frame before the detecting poll.
  • A non-fully-blocking detection needs a single rendered frame in the window: 3–12 slow frames spaced ≤1.0 s apart were never detected (0/44); spacing ≥1.2 s always was (16/16).

Test code: https://github.com/getsentry/sentry-cocoa/compare/9.31.0...trasnake87:sentry-cocoa:t1-106340 · xcodebuild log: https://github.com/trasnake87/App/releases/download/issue106340-evidence/t1_xcodebuild_test_9.31.0.log

Test branch (changes 1–2 + the jest test): https://github.com/Expensify/App/compare/main...trasnake87:App:fix/106340

Regression test

tests/unit/NavigationRootScreenTagTest.tsx, run with npx jest tests/unit/NavigationRootScreenTagTest.tsx:

  • without the change: Tests: 1 failed, 1 total
  • with the change: Tests: 1 passed, 1 total

trasnake87 avatar Nov 09 '26 15:11 trasnake87

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

melvin-bot[bot] avatar Nov 09 '26 15:11 melvin-bot[bot]

Proposal

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

Sentry group APP-77W collects iOS AppHang events on the main thread (84,369 events / 22,916 users; still active Nov 9, 2026). The group is useless for triage because every event's main-thread stack is just the idle run loop (UIApplicationMain → … → mach_msg), so the group never names a cause even though a sample event clearly shows other busy threads (JS thread, LiveMarkdownRuntime_queue, Nitro threads). The ask is not "stop the hang" in one place — it is to make the data actionable: split this one opaque mega-group into per-cause groups that each have an owner, as the "Expected" and "What to check #2/#3" sections state.

What is the root cause of that problem?

Two facts in this snapshot combine to produce the opaque group:

  1. App hangs are captured by the native iOS SDK, and Sentry groups them by the main-thread stack. The AppHang exception is attached to the main thread (current = YES), and Sentry's default grouping hashes that thread's frames. For a hang where the main thread is blocked in mach_msg waiting on a lock/semaphore held by another thread (exactly the "non fully blocked ~2s" shape in the report, with the real work on the JS/LiveMarkdownRuntime/Nitro threads), the main-thread stack is identical every time — so thousands of unrelated causes collapse into a single fingerprint. The busy background threads are present in the payload but are not used for grouping.

  2. Nothing enriches or re-fingerprints these native events. The native SDK is started manually in AppDelegate and deliberately bypasses the React-Native SDK's option preparation (prepareOptions: in RNSentry.mm "is not called when we initialize natively"), so only the options we pass apply. The options dict wires up a beforeSend purely to drop duplicated C++/JS exceptions and does nothing for app hangs:

The manual native init and its hand-written options (the only place app-hang handling could live): https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/ios/SentryNativeSDKManager.m#L56-L74

Because the JS Sentry.init runs with autoInitializeNativeSdk: false and only attaches to the already-running native SDK, the JS-side beforeSend* hooks never see native hang events — so the native beforeSend is the only place that can reshape them: https://github.com/Expensify/App/blob/5ebbde7d7cca4d372921e1ce0350b6962cf0cced/src/setup/telemetry/setupSentry.ts#L85-L96

So the problem is not frontend React code — it is that the native hang event is grouped on a constant stack and is never given a distinguishing fingerprint, so distinct causes are indistinguishable in Sentry.

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

Extend the existing native beforeSend (no new hook, no new init path) so that, for app-hang events only, it overrides event.fingerprint using the top in-app frame of the busiest background thread. That is the one lever available at capture time that forces Sentry to split APP-77W into per-cause groups (JS thread vs LiveMarkdownRuntime_queue vs a specific Nitro module), which is precisely the "split into causes that each have an owner" outcome. Leaving non-hang events untouched preserves today's C++/JS de-dupe behaviour.

Identify a hang by its exception type (cocoa uses App Hanging for V1 and App Hanging Fully Blocked / App Hanging Non Fully Blocked for V2 — all share the App Hanging prefix, so this works regardless of which app-hang mode the SDK default gives us). Then scan the non-main threads (thread.current is not YES) for the first in-app frame (frame.inApp), reading frames leaf-first since Sentry stores them oldest-first. Keep App Hanging Fully Blocked/Non Fully Blocked in the fingerprint so the 16–17s fully-blocked hangs from the Nov 6 alert split away from the ~2s ones. The change replaces the beforeSend block at lines 56–67 of the file linked above:

SentryBeforeSendEventCallback beforeSend = ^SentryEvent *(SentryEvent *event) {
    for (SentryException *exception in event.exceptions) {
        if (exception.value != nil &&
            [exception.value rangeOfString:@\"ExceptionsManager.reportException\"].location != NSNotFound) {
            return nil;
        }
    }

    // App-hang events all share the idle main-thread run-loop stack, so Sentry collapses every cause
    // into one group (APP-77W). Re-fingerprint by the top in-app frame of a background thread to split
    // the group into per-cause issues that can each get an owner.
    SentryException *hang = event.exceptions.firstObject;
    if (hang != nil && [hang.type hasPrefix:@\"App Hanging\"]) {
        NSString *culprit = nil;
        for (SentryThread *thread in event.threads) {
            if ([thread.current isEqualToNumber:@YES]) {
                continue;
            }
            for (SentryFrame *frame in thread.stacktrace.frames.reverseObjectEnumerator) {
                if ([frame.inApp isEqualToNumber:@YES] && frame.function.length > 0) {
                    culprit = frame.function;
                    break;
                }
            }
            if (culprit != nil) {
                break;
            }
        }
        event.fingerprint = culprit != nil ? @[@\"app-hang\", hang.type, culprit] : @[@\"app-hang\", hang.type];
    }

    return event;
};

Notes on correctness and scope:

  • No usable background frame (a genuine main-thread CPU stall that finished before capture): we fall back to @[@\"app-hang\", hang.type], so those still separate by fully/non-fully-blocked instead of re-merging into the old mega-group — a strictly better split, not a regression.
  • Cost / races: beforeSend runs synchronously on the SDK's event thread; this adds only a bounded frame scan over the already-captured payload, no I/O or async, so it cannot itself introduce a hang.
  • Offline: unaffected — hangs are captured and enriched locally, then sent when connectivity returns.
  • Platform: iOS-only (this file); Android ANRs are captured and grouped separately and are untouched. The constant for de-duping C++/JS exceptions is preserved verbatim.

This also unblocks "What to check #1/#3": once groups split by background culprit and hang type, release/screen/foreground breakdowns become meaningful within each child group, and child issues can be filed per culprit. If, after this split, a specific child (e.g. LiveMarkdownRuntime_queue) still lacks detail, that is the point to add targeted breadcrumbs for that subsystem — but that should follow the split, not precede it, and overlaps with the separate Live-Markdown tracker #104744.

Regression test plan

  • Unit (native, de-dupe preserved): feed a synthetic event whose exception value contains ExceptionsManager.reportException through beforeSend and assert it returns nil (behaviour unchanged).
  • Unit (hang split): build a SentryEvent with an App Hanging Non Fully Blocked exception on a current main thread plus a background thread carrying an in-app frame; assert event.fingerprint == @[@\"app-hang\", @\"App Hanging Non Fully Blocked\", <function>]. Repeat with App Hanging Fully Blocked and assert the type drives a different fingerprint.
  • Unit (fallback): a hang event whose only non-main threads have no in-app frames yields @[@\"app-hang\", <type>] and does not throw.
  • Unit (non-hang untouched): a normal JS error event passes through with event.fingerprint left nil.
  • Manual/device (not yet performed): trigger a deliberate main-thread block behind a background-thread operation on a staging build, confirm the resulting Sentry event lands in a new fingerprinted issue separate from APP-77W, and that an ordinary handled error still groups by its own stack. Monitor APP-77W event volume after rollout to confirm it fans out into child groups.

abbasifaizan70 avatar Nov 09 '26 15:11 abbasifaizan70

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 15:35:27 UTC.

Proposal

What is the root cause of that problem?

APP-77W is one giant bucket because nothing in the native init gives an iOS AppHang event a groupable identity, and the breadcrumb that knows the screen never reaches the grouping key.

  • Primary Root Cause: ios/SentryNativeSDKManager.m, the beforeSend block (initialize). It only drops re-reported JS exceptions:
SentryBeforeSendEventCallback beforeSend = ^SentryEvent *(SentryEvent *event) {
    for (SentryException *exception in event.exceptions) {
        if (exception.value != nil &&
            [exception.value rangeOfString:@"ExceptionsManager.reportException"].location != NSNotFound) {
            return nil;
        }
    }
    return event;
};

It never sets a fingerprint for AppHang events. Since JS runs with autoInitializeNativeSdk: false (src/setup/telemetry/setupSentry.ts, the Sentry.init({...}) call), this native beforeSend is the only hook we own for native hang events. With no fingerprint, Sentry falls back to hashing the main-thread stack, and because the watchdog snapshots the idle run loop (UIApplicationMain → mach_msg) for non-fully-blocking hangs, every unrelated cause collides into one group.

  • Secondary Root Cause: src/libs/Navigation/NavigationRoot.tsx, in handleStateChange, the screen is written only as a breadcrumb, never as a scope tag:
const currentRoute = navigationRef.getCurrentRoute();
Sentry.addBreadcrumb({message: `[NAVIGATION] screen: ${currentRoute?.name}, params: ${JSON.stringify(currentRoute?.params ?? {})}`, category: 'navigation'});

Breadcrumbs are payload — they do not participate in grouping and cannot aggregate the issue list by screen. So even when beforeSend wanted to fingerprint by screen, there is no stable scope field (a tag) carrying it. Note setupSentry.ts already uses Sentry.setTag(CONST.TELEMETRY.TAGS.BUILD_TYPE, ...), proving the tag-forwarding path works.

  • Not a root cause (dismissed): the release/dist mismatch other proposals cite is already handled — SentryNativeSDKManager.m replaces the last dot ("9.4.14.0" → "9.4.14-0") to match the JS release, so per-release splits already line up.

  • Affected Files: ios/SentryNativeSDKManager.m (beforeSend block, ~lines 59–80); src/libs/Navigation/NavigationRoot.tsx (handleStateChange); src/CONST/index.ts (TELEMETRY.TAGS).

  • Affected Component(s): iOS native Sentry init + JS navigation telemetry.

  • Bug Category: Model-vs-reality divergence — the diagnostic model (one stack = one cause) does not match reality (idle snapshot shared by all causes); plus a missing grouping key.

  • Mechanism: navigate → handleStateChange writes only a breadcrumb (no tag) → main thread blocks → watchdog snapshots the idle run loop → native beforeSend sets no fingerprint → Sentry groups on the stack hash → all causes land in APP-77W.

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

Give each hang a stable identity from data we already compute: the hang type + the active screen. One short JS line publishes the screen as a tag; the native beforeSend reads it and fingerprints only AppHang events.

  • Fix Option 1 (Recommended):

    1. src/libs/Navigation/NavigationRoot.tsx — in handleStateChange, right after const currentRoute = navigationRef.getCurrentRoute();, add Sentry.setTag(CONST.TELEMETRY.TAGS.SCREEN, currentRoute?.name ?? 'unknown');. setTag is already the established pattern (setupSentry.ts) and is forwarded to the native scope. Latest-wins is exactly the semantics we want for "screen on top now".
    2. src/CONST/index.ts — add SCREEN: 'screen' to TELEMETRY.TAGS.
    3. ios/SentryNativeSDKManager.m — inside the existing beforeSend, after the ExceptionsManager.reportException filter, when the first exception's mechanism.type equals @"AppHang", set event.fingerprint = @[@"app-hang", firstException.type ?: @"unknown", event.tags[@"screen"] ?: @"unknown"].

    Before: every hang groups on the idle stack hash → one bucket. After: each hang groups on ["app-hang", <type>, <screen>] → per-type, per-screen issues. Best because it is the deepest low-risk fix at the only hook we own, switches off no reporting (hang rate unchanged), and reuses already-computed data.

  • Fix Option 2 (Alternative): server-side fingerprint rule in the Sentry project, keyed on exception type + a screen tag. No app change, but still needs the screen tag published from step 1 and project-admin access — internal-only.

  • Revert Option: nothing to revert — the current native beforeSend and release handling are already correct; the defect is a missing fingerprint, not a regression.

  • Alternate fix (rejected): lowering appHangTimeoutInterval or disabling non-fully-blocking hangs — these drop volume but still leave the surviving hangs in one undifferentiated group and risk hiding real slowness; grouping is the actual gap.

Fix Description Files to Change Effort Risk Status
1 Publish active screen as a tag; fingerprint AppHang events by type + screen in native beforeSend ios/SentryNativeSDKManager.m, src/libs/Navigation/NavigationRoot.tsx, src/CONST/index.ts Low Low Recommended
2 Server-side Sentry fingerprint rule on type + screen tag Sentry project config Low Low (needs admin) Alternative

What alternative solutions did you explore? (Optional)

  • Add only the m flag — matches the line but still erases the title (rejected above).
  • Move the subtitle to its own label on the server — leaves old charts broken and keeps the App brittle.
  • Revert the localizer — restores the original wrong behavior.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

Dip-G-Git avatar Nov 09 '26 15:11 Dip-G-Git

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Nov 09 '26 15:11 github-actions[bot]

Proposal

What is the root cause of that problem?

Everyone on the issue agrees the hangs have no single named cause. The reason is that APP-77W mixes unlike hangs into one group, and the events carry nothing that tells them apart.

  • The group holds both short non fully blocked hangs of about 2 to 2.8 seconds and the 16 to 17 second fully blocked ones.
  • Foreground and background hangs also land in the same group.
  • The main thread stack in these events is only the idle run loop (UIApplicationMain to mach_msg), so the stack cannot split them.
  • The only app-level context we record is the navigation breadcrumbs from NavigationRoot.tsx. Breadcrumbs cannot be searched, filtered or grouped on in Sentry, so we cannot ask "which screen do most hangs happen on?"

I have not reproduced this. This is based on reading the issue and the setup files.

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

  1. NavigationRoot.tsx, navigation state change handler. This already records a navigation breadcrumb. Next to it, call Sentry.setTag('active_route', routeName), using the route name only (no params) to keep the tag's values few. Tags are searchable and can be grouped on, so the hangs can be split by screen.
Sentry.setTag('active_route', currentRouteName);
  1. SentryNativeSDKManager.m, native init, which already supplies an error filter. For events whose mechanism is AppHang, add the fully blocked state to the event's fingerprint (for example ["{{ default }}", "fully-blocked"] or "non-fully-blocked"). Use the exception type or value that the Cocoa SDK sets to tell them apart. This puts the 2 second hangs and the 16 second freezes in separate groups. Each group can then get its own owner, which is the outcome the issue asks for.

  2. Same place: also tag the event with in_foreground, taking the value from the app context the Cocoa SDK already attaches. This makes background hangs easy to exclude.

  3. After a week of data, file a child issue for each dominant combination of active_route, fully blocked state and release.

These changes only add metadata and grouping. They do not change app behavior or sampling cost.

What alternative solutions did you explore? (Optional)

Enabling profile session sampling could show what occupied the main thread. It costs quota and overhead, and it only helps once the hangs are split into comparable groups, so I would do it as a follow-up on the worst group.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

samranahm avatar Nov 09 '26 15:11 samranahm

⚠️ @Dip-G-Git Thanks for your interest. To be considered for this job, please post a proposal following the proposal template (note the mandatory sections). Comments claiming the job without one are not reviewed.

github-actions[bot] avatar Nov 09 '26 15:11 github-actions[bot]

Proposal

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

Sentry issue APP-77W aggregates tens of thousands of iOS AppHang events whose main-thread stack is only the idle run loop (UIApplicationMain → mach_msg). That single opaque group mixes short non-fully-blocked hangs, long fully-blocked freezes, foreground work, and likely background-suspension artifacts, so we cannot name owners or file targeted fixes. The goal is to make hang telemetry actionable: split APP-77W into distinguishable groups (and/or cut uninformative volume) while keeping real freezes visible, then open child issues per dominant cause.

What is the root cause of that problem?

Three gaps in our initialization and telemetry wiring funnel unlike hangs into one bucket and hide blocking work:

1. Native Sentry starts with hang-tracking defaults and almost no hang-specific configuration. AppDelegate calls SentryNativeSDKManager before React Native boots, so sentry-cocoa’s App Hang V2 integration runs with default options (2s threshold, non-fully-blocking reports enabled, MetricKit off). We only pass dsn, environment, debug, release, and a beforeSend that drops duplicate JS exception reports—nothing that splits hang types, filters background idle stacks, or enables MetricKit.

App/ios/AppDelegate.swift
Lines 54 to 56 in 5b65d93c6cb

    // Initialize Sentry before any native telemetry (e.g. certificate pinning monitor reports).  
    SentryNativeSDKManager.shared.initialize()  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/ios/AppDelegate.swift#L54-L56

App/ios/SentryNativeSDKManager.m
Lines 59 to 80 in 5b65d93c6cb

    SentryBeforeSendEventCallback beforeSend = ^SentryEvent *(SentryEvent *event) {  
        for (SentryException *exception in event.exceptions) {  
            if (exception.value != nil &&  
                [exception.value rangeOfString:@"ExceptionsManager.reportException"].location != NSNotFound) {  
                return nil;  
            }  
        }  
        return event;  
    };  
  
    NSMutableDictionary *optionsDict = [@{  
        @"dsn": dsn,  
        @"environment": environment,  
        @"debug": @([environment isEqualToString:@"development"]),  
        @"beforeSend": beforeSend,  
    } mutableCopy];  
    if (version.length > 0) {  
        optionsDict[@"release"] = [NSString stringWithFormat:@"new.expensify@%@", version];  
    }  
  
    NSError *error = nil;  
    [RNSentryStart startWithOptions:optionsDict error:&error];  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/ios/SentryNativeSDKManager.m#L59-L80

2. JS attaches later and cannot reshape native hang events. setupSentry() sets autoInitializeNativeSdk: false and documents that profiling must be configured in the native path. Native AppHang events therefore never pass through JS beforeSend hooks—only the native callback above can set fingerprints or drop false positives.

App/src/setup/telemetry/setupSentry.ts
Lines 89 to 96 in 5b65d93c6cb

        // Native SDK is initialized early in Application.onCreate (Android) and AppDelegate (iOS)  
        // via SentryNativeSDKManager so native code can report to Sentry before JS loads.  
        autoInitializeNativeSdk: false,  
        // Do not set `_experiments.profilingOptions` here on its own. The native SDK is started by SentryNativeSDKManager  
        // without profiling options, so session sampling is never configured, and the UI profiling integration the SDK  
        // adds for these options would start the iOS continuous profiler whenever a root span starts. Enabling UI  
        // profiling needs the same options in the native init as well.  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/src/setup/telemetry/setupSentry.ts#L89-L96

3. The idle main-thread stack is an expected artifact of how App Hang V2 samples, not proof that nothing was slow. With @sentry/react-native 8.32.0 (sentry-cocoa App Hangs V2), the watchdog snapshots all threads once when delay crosses the 2s window. For non-fully-blocked hangs the UI can still advance frames during the stall; at the snapshot instant the main thread is often back in CFRunLoopRun / mach_msg, so every event shares the same frameless stack and Sentry’s default stack hash collapses them into APP-77W. Fully-blocked 16–17s events share the same grouping problem whenever the snapshot still lands on an uninformative wait. Busy JS / Live Markdown / Nitro threads in the payload are not used for grouping unless we add that logic.

4. Screen context exists but is not groupable on native hangs. Navigation already records the active route as a breadcrumb only; breadcrumbs do not drive issue grouping. There is no Sentry.setTag for the current screen, while BUILD_TYPE shows tags do forward to the native scope.

App/src/libs/Navigation/NavigationRoot.tsx
Lines 271 to 276 in 5b65d93c6cb

    const handleStateChange = (state: NavigationState | undefined) => {  
        if (!state) {  
            return;  
        }  
        const currentRoute = navigationRef.getCurrentRoute();  
        Sentry.addBreadcrumb({message: `[NAVIGATION] screen: ${currentRoute?.name}, params: ${JSON.stringify(currentRoute?.params ?? {})}`, category: 'navigation'});  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/src/libs/Navigation/NavigationRoot.tsx#L271-L276

App/src/setup/telemetry/setupSentry.ts
Lines 98 to 98 in 5b65d93c6cb

    Sentry.setTag(CONST.TELEMETRY.TAGS.BUILD_TYPE, CONFIG.IS_HYBRID_APP ? CONST.TELEMETRY.BUILD_TYPE_HYBRID_APP : CONST.TELEMETRY.BUILD_TYPE_STANDALONE);  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/src/setup/telemetry/setupSentry.ts#L98-L98

5. Release metadata does not match JS, which breaks “split by release” triage. JS uses getAppVersion() → release: new.expensify@<semantic> and dist: <build>. Native replaces the last dot in CFBundleVersion and embeds the build in the release string ([email protected]), with no dist key—hang events won’t line up with JS errors/spans for the same binary.

App/src/libs/VersionUtils.ts
Lines 6 to 9 in 5b65d93c6cb

function getAppVersion(version: string): AppVersion {  
    const [semanticVersion, buildNumber] = version.split('-');  
  
    return {semanticVersion, buildNumber};  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/src/libs/VersionUtils.ts#L6-L9

App/ios/SentryNativeSDKManager.m
Lines 49 to 54 in 5b65d93c6cb

    // CFBundleVersion is e.g. "9.4.14.0" but JS release uses "9.4.14-0", so replace the last dot with a hyphen.  
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] ?: @"";  
    NSRange lastDot = [version rangeOfString:@"." options:NSBackwardsSearch];  
    if (lastDot.location != NSNotFound) {  
        version = [version stringByReplacingCharactersInRange:lastDot withString:@"-"];  
    }  

https://github.com/Expensify/App/blob/5b65d93c6cb2d0639288793a03da461e4da47d95/ios/SentryNativeSDKManager.m#L49-L54

This is not the same failure class as closed #92541 (OpenApp / ReconnectApp stampedes): recovery guards and timestamp seeding live in JS/Onyx today. APP-77W is primarily a telemetry model vs. reality problem (constant idle stack + one group), with a subset of events likely being sentry-cocoa background idle false positives (per upstream discussions referenced in the thread). Real foreground freezes may still exist; we need better grouping and MetricKit before claiming they are gone.

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

Reconfigure native hang capture and enrich grouping in the only hook we own (SentryNativeSDKManager beforeSend), plus publish the active screen as a scope tag from JS. No app-runtime behavior changes; hang rate on the old group will drop when we stop shipping uninformative events—compare against MetricKit and per-screen child groups, not raw APP-77W volume alone.

A. ios/SentryNativeSDKManager.m — options

optionsDict[@"enableMetricKit"] = @YES;
optionsDict[@"enableReportNonFullyBlockingAppHangs"] = @NO;
  • MetricKit supplies MXHangDiagnostic call-tree hangs across the full stall (sentry-cocoa’s recommended path for actionable stacks).
  • Disabling non-fully-blocking V2 reports removes the bulk of ~2.0–2.8s events whose stacks are systematically idle; user-visible jank remains covered by JS spans/INP and MetricKit. Fully blocked hangs stay on the V2 tracker for real-time signal.

B. Align release / dist with JS — parse CFBundleVersion like getAppVersion: semantic part for release, trailing segment for dist (handle both 9.5.34.0 and 9.5.34-0 shapes).

// illustrative
optionsDict[@"release"] = [NSString stringWithFormat:@"new.expensify@%@", semanticVersion];
optionsDict[@"dist"] = buildNumber;

C. Extend native beforeSend (preserve JS exception filter)

  1. Drop background idle false positives: for mechanism.type == AppHang, when UIApplication.sharedApplication.applicationState != UIApplicationStateActive and the current thread’s top frames are run-loop idle (mach_msg / __CFRunLoopServiceMachPort), return nil.
  2. Tag foreground hangs: set event.tags[@"in_foreground"] from application state (searchable in Sentry).
  3. Override fingerprint so grouping does not use the idle main-thread stack:
SentryException *firstException = event.exceptions.firstObject;
if ([firstException.mechanism.type isEqualToString:@"AppHang"]) {
    NSString *screen = event.tags[@"screen"];
    if (screen.length == 0) {
        screen = [self lastNavigationScreenFromBreadcrumbs:event.breadcrumbs] ?: @"unknown";
    }
    event.fingerprint = @[ @"app-hang", firstException.type ?: @"unknown", screen ];
}

lastNavigationScreenFromBreadcrumbs: walks breadcrumbs backward for category navigation and parses [NAVIGATION] screen: <name> (route name only—no params/IDs).

D. src/libs/Navigation/NavigationRoot.tsx + src/CONST/index.ts

Add SCREEN: 'screen' to CONST.TELEMETRY.TAGS and in handleStateChange:

const currentRoute = navigationRef.getCurrentRoute();
Sentry.setTag(CONST.TELEMETRY.TAGS.SCREEN, currentRoute?.name ?? 'unknown');
Sentry.addBreadcrumb({message: `[NAVIGATION] screen: ${currentRoute?.name}, ...`, category: 'navigation'});

Also call setTag once from onReadyWithSentry with the restored initial route so cold-start hangs are not stuck at unknown.

E. Rollout verification (issue “Expected”)

After one production release: split APP-77W by in_foreground, hang type, and screen tag; inspect MetricKit hang issues for stacks; file child GitHub issues per dominant (type, screen, MetricKit signature). Measure hangs per session, not cumulative event count. If a child implicates Live Markdown (#104744), keep that work separate—do not assume APP-77W is only Markdown.

Regression / blast radius: Non-hang events keep the existing ExceptionsManager.reportException filter. Android ANR path untouched. Foreground fully-blocked hangs still report, now grouped per screen. Dropping non-fully-blocking V2 events reduces noise but requires MetricKit monitoring so we do not blind ourselves to partial UI stalls.

What alternative solutions did you explore? (Optional)

Approach (thread) Verdict
Profile session sampling only (mukhrr) Helps post-hoc CPU profiles but costs quota; does not split the mega-group or remove idle-stack events until sampled. Good follow-up on the worst child group after steps A–D.
Fingerprint by background-thread in-app frame (abbasifaizan70) Clever when JS/Nitro frames exist, but many events have no usable in-app frame on workers → fall back buckets or unstable fingerprints. Screen + hang type is steadier for owner assignment.
Screen tag + fingerprint only (trasnake87, Dip-G-G) Necessary but insufficient: leaves non-fully-blocking idle stacks and background FPs in one bucket and keeps MetricKit off.
Background mach_msg filter + MetricKit only (samithreddychinni) Addresses false positives well but does not split foreground hangs by screen/release. Combined with C+D above.
David-2002065’s full diagnostic bundle Substantively aligned with A–C; this proposal adds explicit JS screen tag + initial-route seeding and documents the native/JS release/dist mismatch from current code.
Server-side fingerprint rules Avoids app changes but still needs the screen tag and admin access; weaker for beforeSend background filtering.
Raise appHangTimeoutInterval / turn off all App Hang tracking Cuts volume without actionable stacks; rejected until MetricKit coverage is verified side-by-side.

What specific scenarios should we cover in automated tests?

  • Native beforeSend still returns nil when exception value contains ExceptionsManager.reportException (unchanged behavior).
  • Synthetic AppHang with applicationState == background and idle main-thread frames is dropped; same frames while active is kept.
  • AppHang fingerprint equals ["app-hang", <exception.type>, <screen tag>] when event.tags[@"screen"] is set; falls back to last navigation breadcrumb when tag missing.
  • Release builder: CFBundleVersion 9.5.34.0 → release [email protected], dist 0 (matches JS getAppVersion).
  • JS unit: handleStateChange / onReadyWithSentry call Sentry.setTag with route name only (mock Sentry).
  • Non-hang error events pass through without fingerprint override.

neerajbachani avatar Nov 09 '26 15:11 neerajbachani

Proposal updated: added a test branch.

trasnake87 avatar Nov 09 '26 15:11 trasnake87

Proposal

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

Sentry issue APP-77W aggregates over 84,000 iOS AppHang events (2,776 events across 2,185 users in the last 7 days) where the main thread stack trace only shows the idle iOS run loop (UIApplicationMain → CFRunLoopRunSpecific → mach_msg). Although earlier OpenApp and ReconnectApp request-stampede issues (#92541 and Expensify/Expensify#644858) were resolved, APP-77W remains active and mixes together two very different failure modes under a single unactionable stack hash:

  1. Non-fully-blocked hangs (~2.0s–2.8s) where the main thread is experiencing severe frame drops alongside active JS, LiveMarkdownRuntime_queue, or Nitro work, but happens to be parked between frames in mach_msg when the watchdog samples the stack.
  2. Fully-blocked hangs (~16s–17s) occurring during iOS lifecycle suspension/resume transitions or synchronous cross-thread waits where the main run loop is stalled on a Mach port.

We need to separate lifecycle suspension artifacts from real foreground hangs, split the catch-all APP-77W group by blocking type, foreground state, and active screen, and attach JS/Onyx span and breadcrumb context so each distinct cause is isolated and actionable.

What is the root cause of that problem?

The root cause is a combination of how sentry-cocoa (initialized natively in ios/SentryNativeSDKManager.m via ios/AppDelegate.swift, before src/setup/telemetry/setupSentry.ts attaches with autoInitializeNativeSdk: false) detects and groups AppHang events, and a lack of persistent native-scope tags/breadcrumbs bridging JS navigation, AppState, and Onyx update phases onto the native Sentry scope:

  1. Idle run-loop stack collision across non-fully-blocking and lifecycle hangs (ios/SentryNativeSDKManager.m):

    • sentry-cocoa 9.31.0 runs App Hang Tracking V2 with a 2.0s window (appHangTimeoutInterval = 2.0) and enableReportNonFullyBlockingAppHangs = YES by default.
    • For non-fully-blocking hangs (2.0s–2.8s), the watchdog triggers when cumulative frame delay exceeds ~1.98s over a 2s window (e.g., while src/libs/actions/OnyxUpdateManager/index.ts applies batch updates in validateAndApplyDeferredUpdates or while LiveMarkdownRuntime_queue / Nitro threads commit shadow trees). Because the main run loop still wakes between slow frames, its stack trace at the instant the watchdog captures threads is frequently just the idle run-loop wait (mach_msg).
    • For fully-blocking hangs (16s–17s) with an idle mach_msg stack, iOS pauses or transitions the app between foreground and background (WillResignActive / DidEnterBackground / WillEnterForeground). The main thread sits in mach_msg while the OS suspends scheduling, and when execution resumes, the watchdog measures the elapsed wall-clock delta and emits a false-positive AppHang.
    • Because Sentry groups AppHang events by the main thread stack trace ({{ default }}), every hang caught while the run loop is at mach_msg collapses into APP-77W.
  2. Missing screen, foreground-state, and active-span context on the native Sentry scope (src/libs/Navigation/NavigationRoot.tsx, src/libs/actions/App.ts, src/libs/actions/OnyxUpdateManager/index.ts):

    • In src/libs/Navigation/NavigationRoot.tsx, parseAndLogRoute extracts currentPath = getPathFromState(state), focusedRoute = findFocusedRoute(state), and activeTabName = getActiveTabName(lastRoute), and sends them to Log.info and FullStory (trackFullstoryPageView), but never sets persistent Sentry scope tags (navigation.route, navigation.tab). When the native watchdog fires asynchronously outside a navigation transaction, the captured SentryEvent lacks screen tags for splitting or filtering.
    • In src/libs/actions/App.ts and src/libs/actions/OnyxUpdateManager/index.ts, heavy synchronization phases (handleMissingOnyxUpdates, fetchMissingUpdates, validateAndApplyDeferredUpdates, and escalateIfFetchStalled → reconnectApp) and getSpan telemetry (src/libs/telemetry/activeSpans.ts) are not mirrored onto the Sentry scope as tags/breadcrumbs at the start and end of each phase.

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

We should make three minimal, regression-safe changes to filter out background lifecycle suspension noise, enrich the native Sentry scope with real-time screen and Onyx/span diagnostics, and partition APP-77W in beforeSend by blocking type, foreground state, and screen:

1. Track lifecycle state on the main thread and split/filter AppHang events in ios/SentryNativeSDKManager.m

Observe UIApplication lifecycle notifications on the main thread via NSNotificationCenter (avoiding any off-main-thread UIApplication.sharedApplication.applicationState access inside beforeSend), drop false-positive hangs that overlap background/inactive lifecycle transitions, and append custom event.fingerprint and event.tags entries inside the existing options.beforeSend callback:

// ios/SentryNativeSDKManager.m

static NSString *sCurrentAppState = @"active";
static CFAbsoluteTime sLastLifecycleTransitionTime = 0;

+ (void)registerLifecycleObservers {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sLastLifecycleTransitionTime = CFAbsoluteTimeGetCurrent();
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];

        [center addObserverForName:UIApplicationDidBecomeActiveNotification
                            object:nil
                             queue:[NSOperationQueue mainQueue]
                        usingBlock:^(__unused NSNotification *note) {
                            sCurrentAppState = @"active";
                            sLastLifecycleTransitionTime = CFAbsoluteTimeGetCurrent();
                            [SentrySDK configureScope:^(SentryScope * _Nonnull scope) {
                                [scope setTagValue:@"active" forKey:@"ios.app_state"];
                            }];
                        }];

        [center addObserverForName:UIApplicationWillResignActiveNotification
                            object:nil
                             queue:[NSOperationQueue mainQueue]
                        usingBlock:^(__unused NSNotification *note) {
                            sCurrentAppState = @"inactive";
                            sLastLifecycleTransitionTime = CFAbsoluteTimeGetCurrent();
                            [SentrySDK configureScope:^(SentryScope * _Nonnull scope) {
                                [scope setTagValue:@"inactive" forKey:@"ios.app_state"];
                            }];
                        }];

        [center addObserverForName:UIApplicationDidEnterBackgroundNotification
                            object:nil
                             queue:[NSOperationQueue mainQueue]
                        usingBlock:^(__unused NSNotification *note) {
                            sCurrentAppState = @"background";
                            sLastLifecycleTransitionTime = CFAbsoluteTimeGetCurrent();
                            [SentrySDK configureScope:^(SentryScope * _Nonnull scope) {
                                [scope setTagValue:@"background" forKey:@"ios.app_state"];
                            }];
                        }];

        [center addObserverForName:UIApplicationWillEnterForegroundNotification
                            object:nil
                             queue:[NSOperationQueue mainQueue]
                        usingBlock:^(__unused NSNotification *note) {
                            sCurrentAppState = @"foreground_transition";
                            sLastLifecycleTransitionTime = CFAbsoluteTimeGetCurrent();
                            [SentrySDK configureScope:^(SentryScope * _Nonnull scope) {
                                [scope setTagValue:@"foreground_transition" forKey:@"ios.app_state"];
                            }];
                        }];
    });
}

And inside [SentryNativeSDKManager start] in ios/SentryNativeSDKManager.m, call [self registerLifecycleObservers]; and extend the existing options.beforeSend block before returning event:

// Inside existing options.beforeSend in ios/SentryNativeSDKManager.m, after existing error filters:
SentryException *firstException = event.exceptions.firstObject;
if ([firstException.type isEqualToString:@"AppHang"]) {
    NSString *appState = sCurrentAppState ?: @"unknown";
    CFAbsoluteTime timeSinceTransition = CFAbsoluteTimeGetCurrent() - sLastLifecycleTransitionTime;

    // Discard watchdog artifacts triggered while suspended/backgrounded or within 2.5s of a lifecycle transition
    if (![appState isEqualToString:@"active"] || timeSinceTransition < 2.5) {
        return nil;
    }

    NSString *hangType = firstException.mechanism.data[@"app_hang_type"] ?: @"unknown_blocking";
    NSMutableDictionary<NSString *, NSString *> *updatedTags = [NSMutableDictionary dictionaryWithDictionary:event.tags ?: @{}];
    updatedTags[@"hang.type"] = hangType;
    updatedTags[@"ios.app_state"] = appState;
    NSString *screenTag = updatedTags[@"navigation.route"] ?: @"unknown_screen";
    event.tags = [updatedTags copy];

    // Split idle run-loop AppHangs by blocking type, foreground state, and active screen
    event.fingerprint = @[@"{{ default }}", hangType, appState, screenTag];
}
return event;

2. Tag active screen and navigation breadcrumbs in src/libs/Navigation/NavigationRoot.tsx

In parseAndLogRoute within src/libs/Navigation/NavigationRoot.tsx, synchronize the focused route and active tab to the Sentry scope so native AppHang events always carry the current screen:

// src/libs/Navigation/NavigationRoot.tsx
function parseAndLogRoute(state: NavigationState, authenticated: boolean) {
    if (!state) {
        return;
    }

    const currentPath = getPathFromState(state);
    const focusedRoute = findFocusedRoute(state);
    const lastRoute = state.routes.at(-1);
    const activeTabName = getActiveTabName(lastRoute);
    const sanitizedPath = currentPath.includes('/transition') ? '/transition' : sanitizeUrlForLogging(currentPath);

    Sentry.setTag('navigation.route', focusedRoute?.name ?? 'unknown');
    Sentry.setTag('navigation.tab', activeTabName ?? 'none');
    Sentry.addBreadcrumb({
        category: 'navigation.route',
        message: `Navigated to ${focusedRoute?.name ?? 'unknown'}`,
        level: 'info',
        data: {
            route: focusedRoute?.name ?? 'unknown',
            tab: activeTabName ?? 'none',
            path: sanitizedPath,
        },
    });

3. Record Onyx update and active-span breadcrumbs in src/libs/actions/OnyxUpdateManager/index.ts and src/libs/actions/App.ts

In src/libs/actions/OnyxUpdateManager/index.ts, add lightweight breadcrumbs/tags around handleMissingOnyxUpdates, fetchMissingUpdates, and finalizeUpdatesAndResumeQueue (and in src/libs/actions/App.ts when AppState changes or openApp / reconnectApp spans run via getSpan):

// src/libs/actions/OnyxUpdateManager/index.ts
import * as Sentry from '@sentry/react-native';

// Inside handleMissingOnyxUpdates before checkIfClientNeedsToBeUpdated():
Sentry.setTag('onyx.update_phase', shouldFetchPendingUpdates ? 'fetching_pending' : 'applying_updates');
Sentry.addBreadcrumb({
    category: 'onyx.update_manager',
    message: 'Processing Onyx updates from server',
    level: 'info',
    data: {
        shouldFetchPendingUpdates,
        lastUpdateIDFromClient,
        lastUpdateIDFromServer,
    },
});

// Inside finalizeUpdatesAndResumeQueue():
Sentry.setTag('onyx.update_phase', 'idle');
// src/libs/actions/App.ts
// Inside AppState change handling / reconnect lifecycle:
Sentry.setTag('app.js_state', AppState.currentState);
Sentry.addBreadcrumb({
    category: 'app.lifecycle',
    message: `AppState changed to ${AppState.currentState}`,
    level: 'info',
    data: {
        hasOpenAppSpan: Boolean(getSpan(CONST.TELEMETRY.SPAN_OPEN_APP)),
        hasReconnectSpan: Boolean(getSpan(CONST.TELEMETRY.SPAN_RECONNECT_APP)),
    },
});

What alternative solutions did you explore? (Optional)

  1. Enabling continuous native profile-session sampling across iOS sessions:
    • While continuous profiling captures call stacks prior to a hang, enabling native profile-session sampling in production adds continuous CPU/battery overhead and telemetry quota cost, and still leaves all idle-stack hangs merged inside APP-77W unless custom fingerprinting and lifecycle filtering are applied. Splitting by hang.type, ios.app_state, and navigation.route first isolates the exact screen and subsystem at zero runtime overhead.
  2. Disabling enableReportNonFullyBlockingAppHangs or enableAppHangTracking globally in ios/SentryNativeSDKManager.m:
    • Turning off non-fully-blocking hang reporting altogether would hide legitimate 2.0s–2.8s UI jank regressions instead of separating them from 16s–17s fully-blocked freezes. Tagging hang.type (fully_blocking vs non_fully_blocking) and including it in event.fingerprint cleanly separates the two mechanisms into distinct Sentry issues while preserving visibility into both.
  3. Adding only JS-side breadcrumbs without native beforeSend fingerprinting and lifecycle filtering:
    • Breadcrumbs help when manually inspecting a single event, but Sentry's issue grouping only uses the stack trace and event.fingerprint. Without updating event.fingerprint and filtering background transition artifacts in ios/SentryNativeSDKManager.m, all 84k+ events would remain bucketed in a single APP-77W group.

Burapa-J avatar Nov 09 '26 15:11 Burapa-J

i cant reproduce this

mukhrr avatar Nov 09 '26 16:11 mukhrr