Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,7 @@
"isemojisonly",
"islarge",
"ismedium",
"isnan",
"isnonreimbursable",
"issmall",
"jank",
Expand Down Expand Up @@ -813,6 +814,7 @@
"libc's",
"libexec",
"libstuff",
"libsystem",
"licence",
"lightningcss",
"linecap",
Expand Down Expand Up @@ -892,6 +894,7 @@
"oblador",
"octocat",
"Odoo",
"odot",
"officedocument",
"offsite",
"oldarch",
Expand Down
273 changes: 263 additions & 10 deletions ios/SentryNativeSDKManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,237 @@
#import "SentryNativeSDKManager.h"
#import "RNCConfig.h"

#import <UIKit/UIKit.h>
#import <os/lock.h>

@import Sentry;
#import <RNSentry/RNSentryStart.h>

// The helpers below are kept in sync with Mobile-Expensify's SentryNativeSDKManager.m, which starts Sentry in the
// HybridApp (the production iOS app). Standalone NewDot has no `odot.foreground` tag, so every idle hang is
// grouped as NewDot.

// Classification is on `frame.package` (the image path, e.g. ".../UIKitCore"), never on `frame.function`:
// SentryCrashReportConverter fills only instructionAddress, imageAddress, package and inApp, and symbolication
// happens server-side after beforeSend returns, so `function` is always nil.
static NSString *frameImageName(SentryFrame *_Nullable frame) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Give the new native helpers verb-led names

The new helpers such as frameImageName, appHangMinimumDuration, and appHangException have noun-led names that read as values rather than operations. .claude/skills/app-coding-standards/rules/consistency-20-function-names.md, required by AGENTS.md, explicitly requires new function names to start with a verb. These are internal static functions, so no external interface dictates their names. Rename them to forms such as getFrameImageName and getAppHangException, and use verb-led names for the new predicates as well.

AGENTS.md reference: AGENTS.md:L7-L10

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file mirrors SentryNativeSDKManager.m in Mobile-Expensify, where frameImageName and frameIsInImage already exist next to helpers like victimFrame and truncatedTagValue. I kept the new helpers in the same style so both copies stay identical and consistent with that file.

NSString *package = frame.package;
if (![package isKindOfClass:NSString.class] || package.length == 0) {
return @"unknown";
}
return package.lastPathComponent;
}

static BOOL frameIsInImage(SentryFrame *_Nullable frame, NSString *imageName) {
return [frameImageName(frame) isEqualToString:imageName];
}

#pragma mark - App hang context

// Tags and grouping for App Hang events. V2 counts time spent inactive as hang time, but not time in the background.
// Remove this section together with App Hang tracking, which sentry-cocoa 10 drops in favor of MetricKit.

static NSString *const appHangMechanismType = @"AppHang";
static NSString *const fatalAppHangTypePrefix = @"Fatal";
static NSString *const unknownTagValue = @"unknown";

// Written on the main thread by the lifecycle and run loop observers, read in beforeSend on Sentry's queue.
static os_unfair_lock appLifecycleLock = OS_UNFAIR_LOCK_INIT;
static CFTimeInterval lastBecameActiveTime = 0;
static CFTimeInterval lastResignedActiveTime = 0;
static CFTimeInterval lastEnteredBackgroundTime = 0;
static NSUInteger activationCount = 0;

static void recordLifecycleTime(CFTimeInterval *slot) {
os_unfair_lock_lock(&appLifecycleLock);
*slot = CACurrentMediaTime();
os_unfair_lock_unlock(&appLifecycleLock);
}

// Main run loop busy time per second. The gap between two run loop activities is busy unless the
// loop was asleep, which includes the app being suspended.
#define BUSY_HISTORY_SECONDS 600
static double busyTimeInSecond[BUSY_HISTORY_SECONDS];
static long busySecondStamp[BUSY_HISTORY_SECONDS];
static CFTimeInterval lastRunLoopActivityTime = 0;
static BOOL lastRunLoopActivityWasSleep = YES;

static void addBusyTimeLocked(CFTimeInterval from, CFTimeInterval to) {
from = MAX(from, to - BUSY_HISTORY_SECONDS);
for (long second = (long)floor(from); second <= (long)floor(to); second++) {
double overlap = MIN(to, (CFTimeInterval)(second + 1)) - MAX(from, (CFTimeInterval)second);
if (overlap <= 0) {
continue;
}
NSUInteger slot = (NSUInteger)(second % BUSY_HISTORY_SECONDS);
if (busySecondStamp[slot] != second) {
busySecondStamp[slot] = second;
busyTimeInSecond[slot] = 0;
}
busyTimeInSecond[slot] += overlap;
}
}

static void recordRunLoopActivity(CFRunLoopActivity activity) {
CFTimeInterval now = CACurrentMediaTime();
os_unfair_lock_lock(&appLifecycleLock);
if (!lastRunLoopActivityWasSleep && lastRunLoopActivityTime > 0) {
addBusyTimeLocked(lastRunLoopActivityTime, now);
}
lastRunLoopActivityTime = now;
lastRunLoopActivityWasSleep = activity == kCFRunLoopBeforeWaiting;
os_unfair_lock_unlock(&appLifecycleLock);
Comment on lines +84 to +92

@situchan situchan Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hang windows mix wall-clock and monotonic time

Sentry measures the hang duration with CLOCK_UPTIME_RAW, but start = now - minimumDuration and the busy history use CFAbsoluteTimeGetCurrent(), which shifts when the system clock is adjusted.
A clock change near a hang moves the window and tags the hang wrongly.

if (!isFatal && !isnan(minimumDuration)) {
// Non-fatal hangs are sent when the hang ends, so the start is roughly now minus the duration.
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime start = now - minimumDuration;

Use clock_gettime_nsec_np(CLOCK_UPTIME_RAW) (or CACurrentMediaTime()) here and in the Mobile-Expensify copy (iOS/Expensify/SentryNativeSDKManager.m at lines 251 and 358).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, switched to CACurrentMediaTime() in both repos and retested the launch and resume cases on a simulator. Since uptime can be shorter than a bogus hang duration right after a reboot, the busy history lookup is now clamped at 0

}

// Blocked: busy for at least half of [start, end]. The caller holds appLifecycleLock.
static BOOL mainThreadWasBlockedLocked(CFTimeInterval start, CFTimeInterval end) {
CFTimeInterval openBusyStart = !lastRunLoopActivityWasSleep && lastRunLoopActivityTime > 0 ? lastRunLoopActivityTime : 0;
// Edge seconds count in proportion to their overlap with the window.
CFTimeInterval busy = 0;
for (long second = (long)floor(MAX(MAX(start, 0), end - BUSY_HISTORY_SECONDS + 1)); second <= (long)floor(end); second++) {
NSUInteger slot = (NSUInteger)(second % BUSY_HISTORY_SECONDS);
double overlap = MIN(end, (CFTimeInterval)(second + 1)) - MAX(start, (CFTimeInterval)second);
if (busySecondStamp[slot] == second && overlap > 0) {
busy += busyTimeInSecond[slot] * overlap;
}
}
if (openBusyStart > 0) {
busy += MAX(0, end - MAX(start, openBusyStart));
}
return busy >= (end - start) / 2;
}

// Idle: above UIApplicationMain only run loop images, ending in a kernel wait entered from CoreFoundation.
// Matches images, not symbols, because `function` is nil before server-side symbolication.
static NSString *mainThreadStateForStacktrace(SentryStacktrace *_Nullable stacktrace) {
static NSSet<NSString *> *runLoopImages = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
runLoopImages = [NSSet setWithArray:@[@"UIKitCore", @"GraphicsServices", @"CoreFoundation", @"libsystem_kernel.dylib"]];
});

NSArray<SentryFrame *> *frames = stacktrace.frames;
if (frames.count == 0) {
return unknownTagValue;
}

// Frames are oldest first. Skip everything before UIApplicationMain.
NSUInteger applicationMainIndex = [frames indexOfObjectPassingTest:^BOOL(SentryFrame *frame, NSUInteger index, BOOL *stop) {
return frameIsInImage(frame, @"UIKitCore");
}];
if (applicationMainIndex == NSNotFound) {
return unknownTagValue;
}

if (!frameIsInImage(frames.lastObject, @"libsystem_kernel.dylib")) {
return @"busy";
}
NSUInteger lastNonKernelIndex = [frames indexOfObjectWithOptions:NSEnumerationReverse passingTest:^BOOL(SentryFrame *frame, NSUInteger index, BOOL *stop) {
return !frameIsInImage(frame, @"libsystem_kernel.dylib");
}];
if (lastNonKernelIndex == NSNotFound || !frameIsInImage(frames[lastNonKernelIndex], @"CoreFoundation")) {
return @"busy";
}
for (NSUInteger index = applicationMainIndex; index < frames.count; index++) {
if (![runLoopImages containsObject:frameImageName(frames[index])]) {
return @"busy";
}
}
return @"idle";
}

// Returns 2.4 for "App hanging between 2.4 and 3.2 seconds.", the lower bound, and NAN for any other wording.
static double appHangMinimumDuration(NSString *_Nullable value) {
static NSRegularExpression *durationExpression = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
durationExpression = [NSRegularExpression regularExpressionWithPattern:@"between ([0-9]+(?:\\.[0-9]+)?) and" options:0 error:nil];
});

if (![value isKindOfClass:NSString.class]) {
return NAN;
}
NSTextCheckingResult *match = [durationExpression firstMatchInString:value options:0 range:NSMakeRange(0, value.length)];
if (match == nil) {
return NAN;
}
return [[value substringWithRange:[match rangeAtIndex:1]] doubleValue];
}

static SentryException *_Nullable appHangException(SentryEvent *event) {
for (SentryException *exception in event.exceptions) {
if ([exception.mechanism.type isEqualToString:appHangMechanismType]) {
return exception;
}
}
return nil;
}

// Idle snapshots get one issue per hang type and app. Busy hangs keep stack grouping.
static void addAppHangContext(SentryEvent *event, SentryException *hang) {
NSMutableDictionary<NSString *, NSString *> *tags = [(event.tags ?: @{}) mutableCopy];

NSString *mainThreadState = mainThreadStateForStacktrace(hang.stacktrace);
tags[@"app_hang.main_thread"] = mainThreadState;

double minimumDuration = appHangMinimumDuration(hang.value);

// A fatal hang is sent on the next launch, so this process's lifecycle times say nothing about it.
BOOL isFatal = [hang.type hasPrefix:fatalAppHangTypePrefix];
if (!isFatal && !isnan(minimumDuration)) {
// Non-fatal hangs are sent when the hang ends, so the start is roughly now minus the duration.
CFTimeInterval now = CACurrentMediaTime();
CFTimeInterval start = now - minimumDuration;

os_unfair_lock_lock(&appLifecycleLock);
CFTimeInterval becameActive = lastBecameActiveTime;
CFTimeInterval resignedActive = lastResignedActiveTime;
CFTimeInterval enteredBackground = lastEnteredBackgroundTime;
NSUInteger activations = activationCount;
// beforeSend runs about a second after the hang ends.
BOOL blocked = mainThreadWasBlockedLocked(start - 1, now);
os_unfair_lock_unlock(&appLifecycleLock);

// "launch" until the first return from the background before the hang.
NSUInteger activationsBeforeHang = activations > 0 && becameActive > start ? activations - 1 : activations;
tags[@"app_hang.since"] = activationsBeforeHang <= 1 ? @"launch" : @"resume";
// Includes returning from the background mid-hang.
if (enteredBackground > start || (activations > 1 && becameActive > start)) {
tags[@"app_hang.interrupted"] = @"background";
} else if (resignedActive > start) {
tags[@"app_hang.interrupted"] = @"inactive";
} else {
tags[@"app_hang.interrupted"] = @"no";
}
tags[@"app_hang.blocked"] = blocked ? @"yes" : @"no";
}

event.tags = tags;

if ([mainThreadState isEqualToString:@"idle"]) {
NSString *app = [event.tags[@"odot.foreground"] isEqualToString:@"true"] ? @"olddot" : @"newdot";
event.fingerprint = @[@"app-hang-idle-main-thread", hang.type ?: unknownTagValue, app];
}
}

static SentryEvent *_Nullable processEventBeforeSend(SentryEvent *event) {
// On New Architecture, React Native wraps JS errors in C++ exceptions caught by the native crash
// handler. Filter these out since the JS error handler already reports them. Matches prepareOptions:
// in RNSentry.mm which is not called when we initialize natively.
for (SentryException *exception in event.exceptions) {
if (exception.value != nil &&
[exception.value rangeOfString:@"ExceptionsManager.reportException"].location != NSNotFound) {
return nil;
}
}

SentryException *hang = appHangException(event);
if (hang != nil) {
addAppHangContext(event, hang);
}
return event;
}

@implementation SentryNativeSDKManager

static BOOL initialized = NO;
Expand Down Expand Up @@ -53,17 +281,8 @@ - (void)initialize {
version = [version stringByReplacingCharactersInRange:lastDot withString:@"-"];
}

// On New Architecture, React Native wraps JS errors in C++ exceptions caught by the native crash
// handler. Filter these out since the JS error handler already reports them. Matches prepareOptions:
// in RNSentry.mm which is not called when we initialize natively.
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;
return processEventBeforeSend(event);
};

NSMutableDictionary *optionsDict = [@{
Expand All @@ -80,7 +299,41 @@ - (void)initialize {
[RNSentryStart startWithOptions:optionsDict error:&error];
if (error != nil) {
NSLog(@"[SentryNativeSDKManager] Failed to initialize Sentry: %@", error.localizedDescription);
return;
}

[self startObservingAppLifecycle];
}

// Lifecycle and run loop observers, installed natively so they run before any JS.
- (void)startObservingAppLifecycle {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
// Launch code is running, so the main thread counts as busy until the first run loop activity.
os_unfair_lock_lock(&appLifecycleLock);
lastRunLoopActivityTime = CACurrentMediaTime();
lastRunLoopActivityWasSleep = NO;
os_unfair_lock_unlock(&appLifecycleLock);
CFRunLoopObserverRef runLoopObserver = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, true, LONG_MAX, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recordRunLoopActivity(activity);
});
CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
CFRelease(runLoopObserver);
[center addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:mainQueue usingBlock:^(NSNotification *notification) {
// Counts launch and returns from the background, not a brief inactive state (system alert, Control Center).
os_unfair_lock_lock(&appLifecycleLock);
if (activationCount == 0 || lastEnteredBackgroundTime > lastBecameActiveTime) {
lastBecameActiveTime = CACurrentMediaTime();
activationCount++;
}
os_unfair_lock_unlock(&appLifecycleLock);
}];
[center addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:mainQueue usingBlock:^(NSNotification *notification) {
recordLifecycleTime(&lastResignedActiveTime);
}];
[center addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:mainQueue usingBlock:^(NSNotification *notification) {
recordLifecycleTime(&lastEnteredBackgroundTime);
}];
}

@end
1 change: 1 addition & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2860,6 +2860,7 @@ const CONST = {
CONTEXT_FULLSTORY: 'Fullstory',
CONTEXT_MEMORY: 'Memory',
CONTEXT_POLICIES: 'Policies',
CONTEXT_NEWDOT_SCREEN: 'NewDot Screen',
// Breadcrumb names
BREADCRUMB_CATEGORY_MEMORY: 'system.memory',
BREADCRUMB_CATEGORY_MFA: 'mfa',
Expand Down
15 changes: 15 additions & 0 deletions src/libs/Navigation/NavigationRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,17 @@ function parseAndLogRoute(state: NavigationState, authenticated: boolean) {
trackFullstoryPageView(state);
}

let lastNewDotScreenName: string | undefined;

function setNewDotScreenContext() {
const name = navigationRef.getCurrentRoute()?.name;
if (name === lastNewDotScreenName) {
return;
}
lastNewDotScreenName = name;
Sentry.setContext(CONST.TELEMETRY.CONTEXT_NEWDOT_SCREEN, {name, timestamp: Date.now() / 1000});
}
Comment thread
arekm213 marked this conversation as resolved.
Resolved

function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: NavigationRootProps) {
useStartSpansOnRender([
{
Expand Down Expand Up @@ -274,6 +285,7 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
}
const currentRoute = navigationRef.getCurrentRoute();
Sentry.addBreadcrumb({message: `[NAVIGATION] screen: ${currentRoute?.name}, params: ${JSON.stringify(currentRoute?.params ?? {})}`, category: 'navigation'});
setNewDotScreenContext();

updateCurrentReportID(state);
parseAndLogRoute(state, authenticated);
Expand All @@ -296,6 +308,9 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
// from the restored root state so isTopMostReportId is correct on the first report screen
// (e.g. the composer's keyboard avoiding view is enabled right away).
updateCurrentReportID(navigationRef.getRootState());

// Records the first screen, for the same reason.
setNewDotScreenContext();
};

// Re-establish on (re)mount — StrictMode's cleanup-then-remount otherwise leaves us listener-less; setup is idempotent.
Expand Down
Loading