App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-07-06] [$250] [Sentry: APP-4FK] HybridApp Android NullPointerException in expo TaskService.executeTask

Open mountiny opened this issue 5 months ago • 51 comments

Sentry

https://expensify.sentry.io/issues/APP-4FK

Impact (snapshot at filing)

  • Users (total since first seen): 154
  • Events: 5,369
  • Users (last 14d): ongoing on 9.3.89–9.3.91
  • First seen: 2026-01-22
  • Last seen: now (ongoing)
  • Platform: Android, hybrid_app
  • App version(s): seen through 9.3.91
  • Mechanism: chained, fatal

Stack trace (top frames, first-party only)

expo.modules.taskManager.TaskService in executeTask
  -> java.lang.NullPointerException

Suspected cause

Expo background TaskService receives a null context or task payload on Android HybridApp when executing a registered background task.

Reproduction

Unknown deterministically — see linked Sentry events for Android HybridApp sessions.

Related

  • Sibling Sentry IDs (if any): none identified
  • Prior GH issues: none
  • Production scan: releases 9.3.89, 9.3.90, 9.3.91 (2026-06-02)
Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

mountiny avatar Jun 02 '26 18:06 mountiny

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

melvin-bot[bot] avatar Jun 02 '26 18:06 melvin-bot[bot]

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

melvin-bot[bot] avatar Jun 02 '26 18:06 melvin-bot[bot]

Proposal

Android HybridApp users crash with a fatal NullPointerException inside Expo's native expo.modules.taskManager.TaskService.executeTask. The only expo-task-manager task this app registers is the GPS distance-tracking background task, so every event in APP-4FK originates from the GPS distance-request feature.

Root cause

The app defines exactly one Expo task — 'background-location-tracking' — registered at startup in src/setup/backgroundLocationTrackingTask/index.native.ts:13 and started through expo-location's startLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME, BACKGROUND_LOCATION_TASK_OPTIONS) (src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSButtons/index.tsx:74 and src/components/GPSTripStateChecker/index.native.tsx:75). The crash has two compounding causes.

1 - No Android foreground service forces delivery through the crashing headless path. The task options are minimal — no foreground service:

// src/pages/iou/request/step/IOURequestStepDistanceGPS/const.ts:6-9 (current)
const BACKGROUND_LOCATION_TASK_OPTIONS: LocationTaskOptions = {
    accuracy: Accuracy.Highest,
    distanceInterval: GPS_DISTANCE_INTERVAL_METERS,
};

Without a foregroundService, Android does not keep the JS runtime alive while tracking. When a location update fires after the process is backgrounded/killed, Expo's native TaskService.executeTask calls getTaskManager(appScopeKey), finds no running task manager, and falls into the headless branch that must resurrect a React host to run the JS callback. In HybridApp the React Native runtime is hosted inside the OldDot native shell and there is no Expo app record/host registered the way a standalone Expo app expects, so that headless branch dereferences a null context/app record → NullPointerException. Critically, this throws in native code before our defineTask callback runs, so the existing JS-level error handling in the task body cannot catch it.

2 - Orphaned task registration survives process death and re-fires indefinitely. expo-location persists the registration to disk; it outlives the process. The only paths that stop it are:

  • GPSTripStateChecker unmount cleanup — src/components/GPSTripStateChecker/index.native.tsx:47-55 — which never runs when the OS kills a backgrounded process.
  • Sign-out — src/pages/settings/InitialSettingsPage.tsx:237-240.
  • Explicit user stop — stopGpsTrip in src/libs/GPSDraftDetailsUtils.ts:103-108.

So if a trip is interrupted by an OS kill, 'background-location-tracking' stays registered and the OS keeps re-entering the crashing path. This explains the event/user ratio (5,369 events / 154 users ≈ 35× per user) — a stuck registration firing repeatedly per device. The startup effect that should heal this returns early without clearing the orphan:

// src/components/GPSTripStateChecker/index.native.tsx:33-45 (current)
async function handleGpsTripInProgressOnAppRestart() {
    await checkAndCleanGpsNotification();
    const gpsTrip = await OnyxUtils.get(ONYXKEYS.GPS_DRAFT_DETAILS);

    if (!gpsTrip?.isTracking) {
        return; // <-- leaves a possibly-registered task alive
    }
    setShowContinueTripModal(true);
}

Proposed fix

Fix 1 — Run a foreground service so updates reach the live runtime (avoids the headless branch entirely). Convert the static options to a builder so the notification can be localized, and add foregroundService:

// src/pages/iou/request/step/IOURequestStepDistanceGPS/const.ts
import {Accuracy} from 'expo-location';
import type {LocationTaskOptions} from 'expo-location';

const GPS_DISTANCE_INTERVAL_METERS = 100;
const BACKGROUND_LOCATION_TRACKING_TASK_NAME = 'background-location-tracking';

function getBackgroundLocationTaskOptions(notificationTitle: string, notificationBody: string): LocationTaskOptions {
    return {
        accuracy: Accuracy.Highest,
        distanceInterval: GPS_DISTANCE_INTERVAL_METERS,
        pausesUpdatesAutomatically: false,
        // Android: keep the process alive via a foreground service so updates are delivered to the
        // running JS runtime (getTaskManager() != null). Without this the OS resurrects the app
        // headlessly and Expo's TaskService.executeTask dereferences a null React host in HybridApp.
        foregroundService: {
            notificationTitle,
            notificationBody,
            killServiceOnDestroy: true,
        },
    };
}

export {getBackgroundLocationTaskOptions, BACKGROUND_LOCATION_TRACKING_TASK_NAME, GPS_DISTANCE_INTERVAL_METERS};

Update the two call sites to pass localized strings (add gps.backgroundTracking.title/.body to the existing gps namespace at src/languages/en.ts:8589):

// src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSButtons/index.tsx:74
// and src/components/GPSTripStateChecker/index.native.tsx:75
await startLocationUpdatesAsync(
    BACKGROUND_LOCATION_TRACKING_TASK_NAME,
    getBackgroundLocationTaskOptions(translate('gps.backgroundTracking.title'), translate('gps.backgroundTracking.body')),
);

This requires FOREGROUND_SERVICE + FOREGROUND_SERVICE_LOCATION permissions and the expo-location foreground service declared in the Mobile-Expensify AndroidManifest.xml (expo-location's config plugin injects these for standalone builds, but HybridApp's manifest comes from the submodule and must include them).

Fix 2 — Clear an orphaned registration on cold start. In the same startup effect, when no trip is in progress, unregister any lingering task before the OS can fire it:

// src/components/GPSTripStateChecker/index.native.tsx:33-45 (replace early return)
    if (!gpsTrip?.isTracking) {
        // A prior trip may have been killed by the OS, leaving the background task registered.
        // Expo keeps firing it and the headless executeTask path NPEs in HybridApp — clear the orphan.
        const isRunning = await hasStartedLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME);
        if (isRunning) {
            stopLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME).catch((error) =>
                console.error('[GPS distance request] Failed to stop orphaned location tracking', error),
            );
        }
        return;
    }

Why this approach

Fix 1 is the structural cure: a foreground service is Expo's documented requirement for reliable Android background location, and it keeps getTaskManager() non-null so updates dispatch to the live JS task manager instead of the headless branch where the native NPE lives. Fix 2 mirrors patterns already in this component — it reuses the exact hasStartedLocationUpdatesAsync/stopLocationUpdatesAsync guard from the unmount cleanup at index.native.tsx:47-55, and sits alongside the existing checkAndCleanGpsNotification() self-heal in the same effect, extending startup recovery to the task registration. We rejected simply wrapping the task body in try/catch (the team already does this for the sibling task at src/setup/backgroundTask/index.native.ts:10-12) because the NPE is thrown in Expo's native executeTask before any JS runs, so a JS guard cannot intercept it — only avoiding the headless branch (Fix 1) and removing stale registrations (Fix 2) can.

trasnake87 avatar Jun 02 '26 19:06 trasnake87

Proposal

What is the root cause of that problem?

This is a crash inside the third‑party expo-task-manager native code, not in App's own code.

The only background task in App that goes through Expo's TaskService + a location consumer is the GPS distance‑tracking task, registered here: src/setup/backgroundLocationTrackingTask/index.native.ts:13.

When the app process is killed while a GPS trip is in progress, Android later restarts the headless service to deliver a queued location update and calls TaskService.executeTask(...). If the app's JS task manager isn't loaded yet, that method falls into a branch that loads the app headlessly:

// expo-task-manager 55.0.2 — TaskService.java, executeTask()
getAppLoader().loadApp(mContextRef.get(), ...)   // line ~408

getAppLoader() returns null whenever mContextRef.get() is null (the Context is held in a WeakReference and is gone after the process was killed). The call site dereferences it without a null check → NullPointerException.

The smoking gun: the sibling method invalidateAppRecord() in the same file does guard getAppLoader() for null before using it — executeTask() simply forgot to. Android‑only because iOS uses a different (non‑headless) task delivery path, which matches the Sentry data (Android, hybrid_app) and the manual repro in Expensify/App#88700.

Evidence chain
  • Sentry signature: expo.modules.taskManager.TaskService → executeTask → java.lang.NullPointerException, Android / hybrid_app, 154 users, ongoing on 9.3.89–9.3.91.
  • executeTask() unguarded call: node_modules/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java:408 → getAppLoader().loadApp(...).
  • getAppLoader() returns null when context is gone: same file, lines 433–439 (if (mContextRef.get() != null) { ... } else { return null; }).
  • Guarded sibling proving the omission is a bug: same file, lines 599–606 (invalidateAppRecord() null‑checks getAppLoader() before calling invalidateApp).
  • App's GPS task is the only expo-task-manager + expo-location consumer in the codebase ([email protected], [email protected] in package.json).
  • Likely duplicate / same root cause: https://github.com/Expensify/App/issues/88700 — "App crashes reopening while the GPS trip is in progress" (Android only, reproduced by killing the app mid‑trip).

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

Add a patch-package patch to expo-task-manager (lives in App's patches/ directory) that null‑guards getAppLoader() inside executeTask(), mirroring what invalidateAppRecord() already does. When the loader/context is unavailable, drop the queued event instead of dereferencing null:

  • Capture HeadlessAppLoader appLoader = getAppLoader();
  • If it's null, remove the queued event for the app scope key and return (the background update is skipped, which is acceptable — far better than a fatal crash).
  • Otherwise call appLoader.loadApp(...) as before.

This is a minimal, App‑side fix and prevents the crash for all users hitting this path.

What alternative solutions did you explore? (Optional)

Alternatives considered
  • Upstream fix in Expo — file the same null‑guard upstream so the patch can eventually be dropped; doesn't help our users on the current SDK now, so do it in addition to the patch.
  • Stop/unregister the location task more aggressively when a trip ends or is discarded (the #88700 repro mentions "discard tracking twice"). Worth verifying the task is always unregistered via stopLocationUpdatesAsync, but this only narrows the trigger window — the headless‑restart NPE can still occur for a legitimately in‑progress trip, so the null guard is still required.
  • HybridApp headless‑loader registration — the deeper reason the context/loader is unavailable on HybridApp may involve native headless‑app‑loader setup in Mobile-Expensify. That's a separate investigation; the crash guard above is the correct immediate fix and is fully within the App repo.

Possibly related / duplicate

  • https://github.com/Expensify/App/issues/88700 — same crash, reproduced by killing the app while a GPS trip is in progress (Android only). Strong candidate for deduping.

Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/92416) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.

MelvinBot avatar Jun 02 '26 19:06 MelvinBot

Proposal

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

Android HybridApp can fatally crash while Expo TaskManager executes the registered background location task. The Sentry frame is in expo.modules.taskManager.TaskService.executeTask, so the failure happens in Expo's native task dispatch path while the app is trying to deliver a background task event.

What is the root cause of that problem?

The app registers only one Expo TaskManager task: background-location-tracking.

https://github.com/Expensify/App/blob/eaaffe32a99289cabef7d08d61a2e8a538c16695/src/setup/backgroundLocationTrackingTask/index.native.ts#L13-L33

That task is started and restarted through Location.startLocationUpdatesAsync() from the GPS distance request flow.

https://github.com/Expensify/App/blob/eaaffe32a99289cabef7d08d61a2e8a538c16695/src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSButtons/index.tsx#L71-L80

https://github.com/Expensify/App/blob/eaaffe32a99289cabef7d08d61a2e8a538c16695/src/components/GPSTripStateChecker/index.native.tsx#L63-L87

In [email protected], TaskService.executeTask() queues the native task event, then assumes a headless React Native app loader is always available when no foreground task manager is registered:

https://github.com/expo/expo/blob/sdk-55/packages/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java#L368-L428

The same file's getAppLoader() returns null when the weak Context reference has been cleared:

https://github.com/expo/expo/blob/sdk-55/packages/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java#L433-L439

So if Android delivers a location task while the HybridApp process is in a headless/background transition and mContextRef.get() is null, executeTask() reaches getAppLoader().loadApp(...) and throws a native NullPointerException before the JS task can run or fail gracefully. This matches the Sentry top frame and why the issue is Android HybridApp-only and not tied to a deterministic user-visible screen repro.

There is also a secondary app-side assumption in our task executor: after checking error, it immediately reads data.locations.

https://github.com/Expensify/App/blob/eaaffe32a99289cabef7d08d61a2e8a538c16695/src/setup/backgroundLocationTrackingTask/index.native.ts#L13-L27

Expo normally sends an empty Bundle when native data is null, but malformed/empty location events should still be ignored by this task rather than turning into a JS-side crash after the native NPE is fixed.

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

Patch [email protected] via patch-package and add the patch under patches/expo-task-manager/.

In TaskService.executeTask():

  • Resolve Context context = mContextRef.get() and HeadlessAppLoader appLoader = getAppLoader() once before calling loadApp.
  • If context or appLoader is null, remove the queued event/callback for that eventId, log a warning including task.getName() and appScopeKey, and return instead of calling loadApp.
  • Keep the existing behavior for a present foreground task manager, successful headless loading, AppConfigurationError, and unregister-on-load-failure paths.

This fixes the fatal native NPE at the boundary where the nullable loader is introduced, without changing the GPS feature behavior when Android can actually start the headless app.

Also harden src/setup/backgroundLocationTrackingTask/index.native.ts by validating the task payload before mapping it:

  • Treat missing data, missing data.locations, or an empty/non-array locations value as a no-op.
  • Keep the existing error logging, Onyx lookup, offline detection, GPS point merge, and start-address update behavior for valid location arrays.

Add/update patch metadata in patches/expo-task-manager/details.md, and add a focused unit test around the background location task executor if the existing test harness can import the task setup module; otherwise verify by building Android and confirming patch-package applies cleanly.

Scope boundaries:

  • Files touched: patches/expo-task-manager/expo-task-manager+55.0.2+001+guard-null-headless-loader.patch, patches/expo-task-manager/details.md, and src/setup/backgroundLocationTrackingTask/index.native.ts.
  • Native behavior touched: only Expo TaskManager's Android background/headless task dispatch when no foreground task manager exists.
  • Code paths explicitly not touched: the custom @expensify/react-native-background-task module, iOS TaskManager, GPS notification UI, permission flows, trip start/stop actions, Onyx GPS draft writes, and reverse geocoding logic.
  • API/backend changes: none.

What alternative solutions did you explore? (Optional)

I considered only adding a JS guard around data.locations, but that does not address the reported fatal native frame because TaskService.executeTask() can crash before the JS executor is invoked. I also considered stopping/unregistering the GPS task more aggressively on app restart, but that would risk losing legitimate distance tracking. The narrow dependency patch keeps background GPS tracking intact and only guards the nullable native loader path that Expo already exposes through getAppLoader().

At draft time there are no strict human or bot proposals on this issue. The duplicate scan found this target issue and the general monthly Sentry tracking issue only.

KJ21-ENG avatar Jun 02 '26 19:06 KJ21-ENG

Proposal

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

On Android HybridApp, the app fatally crashes with a java.lang.NullPointerException thrown inside Expo's native expo.modules.taskManager.TaskService.executeTask (APP-4FK, 154 users / 5,369 events, ongoing on 9.3.89–9.3.91). The only Expo TaskManager task this app defines is the GPS distance‑tracking background location task, so every event originates from that feature.

What is the root cause of that problem?

1. The exact native line that throws. The app defines exactly one Expo task — background-location-tracking — at module load in src/setup/backgroundLocationTrackingTask/index.native.ts#L13-L33 (imported from src/App.tsx#L47), and starts it via Location.startLocationUpdatesAsync(...).

When Android delivers a location update for that task, expo‑location calls TaskService.executeTask(...). In [email protected] (node_modules/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java), that method is:

public void executeTask(TaskInterface task, Bundle data, Error error, TaskExecutionCallback callback) {
  TaskManagerInterface taskManager = getTaskManager(task.getAppScopeKey()); // L369 – null when the JS runtime/task manager is gone
  ...
  if (taskManager != null) {
    taskManager.executeTaskWithBody(body);                                  // L396 – foreground/alive path (safe)
    return;
  }
  ...
  getAppLoader().loadApp(mContextRef.get(), ...);                           // L408 – HEADLESS path → NPE here

getAppLoader() is nullable — it returns null when it can't resolve/instantiate the headless loader:

private HeadlessAppLoader getAppLoader() {                                  // L433-L439
  if (mContextRef.get() != null) {
    return AppLoaderProvider.getLoader("react-native-headless", mContextRef.get()); // can itself return null
  } else {
    return null;
  }
}

AppLoaderProvider.getLoader(...) returns null whenever the loader can't be created (it swallows the exception and return null — node_modules/expo-modules-core/.../apploader/AppLoaderProvider.kt#L11-L22). So at executeTask L408 the code dereferences a possibly‑null loader with no guard → NullPointerException, exactly matching the Sentry top frame.

The smoking gun that this is an upstream omission: the sibling method invalidateAppRecord() in the same file does null‑guard the loader before using it:

private void invalidateAppRecord(String appScopeKey) {                      // L599-L606
  HeadlessAppLoader appLoader = getAppLoader();
  if (appLoader != null) {                                                  // guarded ✅
    if (getAppLoader().invalidateApp(appScopeKey)) { ... }
  }
}

executeTask() simply forgot the same guard.

2. Why our code reaches that broken branch at all (the actionable App‑side root cause). Reaching L408 requires getTaskManager() at L369 to be null — i.e. the JS task manager / React runtime is no longer alive when the update is delivered. That happens specifically when background location is tracked without an Android foreground service, which is exactly how we start it. The task options have no foregroundService:

// src/pages/iou/request/step/IOURequestStepDistanceGPS/const.ts#L6-L9
const BACKGROUND_LOCATION_TASK_OPTIONS: LocationTaskOptions = {
    accuracy: Accuracy.Highest,
    distanceInterval: GPS_DISTANCE_INTERVAL_METERS,
};

These same options are passed to every startLocationUpdatesAsync call site — GPSButtons/index.tsx#L74 and GPSTripStateChecker/index.native.tsx#L75. Without a foreground service Android does not keep the JS runtime alive while a trip is in progress: when the app is backgrounded and the OS reclaims the process, the foreground task manager (sTaskManagers/sHeadlessTaskManagers, both WeakReference) is gone, so getTaskManager() returns null and the next delivered location update is forced down the headless getAppLoader().loadApp(...) branch — which NPEs in this build. This is a redelivery loop (the OS keeps trying to deliver the queued update), which explains the ~35× events‑per‑user ratio (5,369 / 154).

Why Android‑HybridApp‑only: the GPS distance feature only ships on Android inside the HybridApp build (standalone NewDot is web; iOS uses a different, non‑headless task delivery path), so every Android occurrence is necessarily hybrid_app. The headless React‑host re‑launch path that L408 depends on is the part that isn't viable here — in a managed/standalone Expo app it's the app's own React host, but in HybridApp the host is OldDot's native shell, so the loader path is exactly the fragile spot.

Honesty note: getAppLoader() can return null from two places — a GC'd Context (L437) or AppLoaderProvider.getLoader failing to create the headless loader in this build (the catch → return null at AppLoaderProvider.kt#L18). From frontend code alone I can't fully disambiguate which one fires in production without the Mobile‑Expensify native build, but it doesn't change the fix: both are only reachable on the headless branch, and both are avoided by keeping the JS runtime alive (a foreground service), with the upstream null‑guard as a belt‑and‑suspenders.

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

Primary fix (App‑side, fixes the cause): run a foreground service so updates are delivered to the live JS runtime and never reach the headless NPE branch. A foreground service keeps the process alive → getTaskManager() at L369 stays non‑null → delivery goes through the safe L396 path. It also stops us silently losing GPS points when the process is reclaimed mid‑trip, which is a real correctness win regardless of the crash.

Turn the static options into a small builder so the notification copy can be localized, and add foregroundService:

// src/pages/iou/request/step/IOURequestStepDistanceGPS/const.ts
import {Accuracy} from 'expo-location';
import type {LocationTaskOptions} from 'expo-location';

const GPS_DISTANCE_INTERVAL_METERS = 100;
const BACKGROUND_LOCATION_TRACKING_TASK_NAME = 'background-location-tracking';

function getBackgroundLocationTaskOptions(notificationTitle: string, notificationBody: string): LocationTaskOptions {
    return {
        accuracy: Accuracy.Highest,
        distanceInterval: GPS_DISTANCE_INTERVAL_METERS,
        // Android: a foreground service keeps the process/JS runtime alive while a trip is in
        // progress, so location updates are dispatched to the running task manager
        // (TaskService.getTaskManager() != null) instead of the headless getAppLoader().loadApp()
        // path that NPEs in HybridApp.
        foregroundService: {
            notificationTitle,
            notificationBody,
            killServiceOnDestroy: true,
        },
    };
}

export {getBackgroundLocationTaskOptions, BACKGROUND_LOCATION_TRACKING_TASK_NAME, GPS_DISTANCE_INTERVAL_METERS};

Update both start sites to pass localized strings (add gps.backgroundTracking.title / .body to the existing gps namespace at src/languages/en.ts#L8589, and es.ts):

// GPSButtons/index.tsx#L74 and GPSTripStateChecker/index.native.tsx#L75
await startLocationUpdatesAsync(
    BACKGROUND_LOCATION_TRACKING_TASK_NAME,
    getBackgroundLocationTaskOptions(translate('gps.backgroundTracking.title'), translate('gps.backgroundTracking.body')),
);

This requires the foreground‑service plumbing to exist in the Android manifest: FOREGROUND_SERVICE + FOREGROUND_SERVICE_LOCATION permissions and expo‑location's foreground <service android:foregroundServiceType="location">. In a managed Expo app expo‑location's config plugin injects these automatically; in HybridApp the manifest is hand‑managed in the Mobile-Expensify submodule, so these entries must be added there (this is the one cross‑repo piece and should be verified against the existing BackgroundLocationPermissionsFlow permission set).

Defense‑in‑depth (dependency patch): null‑guard executeTask() so a missing loader can never crash again. Even with a foreground service, the OS can still kill the service under extreme memory pressure and later attempt a headless redelivery, so the native NPE should be made impossible. Add a patch-package patch under patches/ to expo-task-manager+55.0.2 that mirrors the guard invalidateAppRecord() already uses:

// TaskService.executeTask(), replacing the unguarded getAppLoader().loadApp(...) at L408
HeadlessAppLoader appLoader = getAppLoader();
if (appLoader == null) {
    // No headless loader/context available (e.g. HybridApp background redelivery).
    // Drop the queued event for this app scope instead of dereferencing null.
    appEvents.remove(eventId);
    mTasksAndEventsRepository.removeEvents(appScopeKey);
    return;
}
appLoader.loadApp(mContextRef.get(), new HeadlessAppLoader.Params(appScopeKey, task.getAppUrl()), () -> {}, success -> {
    if (!success) {
        sEvents.remove(appScopeKey);
        mTasksAndEventsRepository.removeEvents(appScopeKey);
        unregisterAllTasksForAppScopeKey(appScopeKey);
    }
});

(Worth filing the same guard upstream in expo/expo so the patch can eventually be dropped.)

Offline / platform notes: the change is Android‑only behavior (the foregroundService option is ignored on iOS, which already uses a non‑headless path). It is independent of network state — the background task already uses NetInfo.fetch() for offline detection (index.native.ts#L19-L24) and the foreground service only affects whether the runtime stays alive, not what the task does.

What alternative solutions did you explore? (Optional)

  • Patch‑only (null‑guard executeTask) without the foreground service. This is the minimal crash‑stopper and is correct as far as it goes, but it treats the symptom: it makes the native NPE disappear by silently dropping the location update, so the GPS trip quietly stops accumulating points whenever the process is reclaimed. Keeping the runtime alive via the foreground service both prevents the crash and preserves tracking — hence patch as defense‑in‑depth, not as the sole fix.
  • Wrapping the JS task body in try/catch. Doesn't help — the NPE is thrown in Expo's native executeTask before our defineTask callback runs, so no JS guard can intercept it.
  • Aggressively unregistering the task on cold start when no trip is in progress. Narrows the trigger window but doesn't fix a legitimately in‑progress trip (the exact case the feature exists for), and risks tearing down tracking the "continue trip" flow in GPSTripStateChecker is designed to resume. The foreground service addresses the in‑progress case directly.

yusufdeveloper2903 avatar Jun 02 '26 19:06 yusufdeveloper2903

⚠️ @yusufdeveloper2903 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar Jun 02 '26 19:06 github-actions[bot]

Proposal

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

Android HybridApp can fatally crash while Expo TaskManager is executing a background task. The Sentry frame is expo.modules.taskManager.TaskService.executeTask, so the failure happens in Expo's Android native task dispatch path before the app can handle the event safely in JS.

What is the root cause of that problem?

The public App repo registers one Expo TaskManager task, background-location-tracking, during app startup.

https://github.com/Expensify/App/blob/21afc571018cd2c5ace7c3821420d04da74c226b/src/App.tsx#L46-L48 https://github.com/Expensify/App/blob/21afc571018cd2c5ace7c3821420d04da74c226b/src/setup/backgroundLocationTrackingTask/index.native.ts#L13-L33

That task is started from the GPS distance request flow through Location.startLocationUpdatesAsync(...), so Android location updates are handed to Expo Location and then into Expo TaskManager.

https://github.com/Expensify/App/blob/21afc571018cd2c5ace7c3821420d04da74c226b/src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSButtons/index.tsx#L71-L80 https://github.com/Expensify/App/blob/21afc571018cd2c5ace7c3821420d04da74c226b/src/components/GPSTripStateChecker/index.native.tsx#L62-L79

The App is pinned to [email protected] but still uses [email protected].

https://github.com/Expensify/App/blob/21afc571018cd2c5ace7c3821420d04da74c226b/package.json#L145-L148

In [email protected], TaskService.executeTask() builds and queues the task event, but when no foreground task manager is available it immediately calls getAppLoader().loadApp(...). getAppLoader() is nullable because it depends on the weak Android context/app-loader state, but executeTask() does not check that return value before dereferencing it.

https://github.com/expo/expo/blob/7d7f6762fc6907c27a329953c682134a84410dea/packages/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java#L368-L428 https://github.com/expo/expo/blob/7d7f6762fc6907c27a329953c682134a84410dea/packages/expo-task-manager/android/src/main/java/expo/modules/taskManager/TaskService.java#L433-L439

So when Android delivers a persisted GPS task while HybridApp is backgrounded or between React task-manager instances, the native dispatcher can reach getAppLoader().loadApp(...) with no loader/context available and throw a Java NullPointerException from executeTask. The JS executor's own data.locations assumption is a secondary hardening target, but it cannot be the primary root cause because the reported fatal frame is native TaskService.executeTask.

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

Add a focused patch-package patch for [email protected] under patches/expo-task-manager/.

Because Android Expo modules can use prebuilt AARs, also add expo-task-manager to package.json's expo.autolinking.android.buildFromSource list so Gradle builds the patched module source instead of resolving the unpatched prebuilt artifact.

In TaskService.executeTask():

  • Keep the existing fast path when getTaskManager(appScopeKey) returns a foreground or headless task manager.
  • Before the fallback loadApp call, resolve Context context = mContextRef.get() and HeadlessAppLoader appLoader = getAppLoader() into locals.
  • If context or appLoader is null, log a warning with task.getName() and appScopeKey, remove the queued event/callback for that eventId, invoke the task callback so JobService.jobFinished(...) is not left waiting for the timeout, and return without calling loadApp.
  • Keep the existing unregister-on-load-failure path for a real headless load that returns success=false.

Also harden src/setup/backgroundLocationTrackingTask/index.native.ts so the JS task treats missing data, missing data.locations, non-array locations, or an empty locations array as a no-op before mapping. That does not fix the native Sentry crash by itself, but it prevents the same malformed event from becoming a JS crash after the native boundary is safe.

Scope boundaries:

  • Files touched: patches/expo-task-manager/expo-task-manager+55.0.2+001+guard-null-task-loader.patch, patches/expo-task-manager/details.md, package.json expo.autolinking.android.buildFromSource, and src/setup/backgroundLocationTrackingTask/index.native.ts.
  • Platforms: Android native/HybridApp background GPS task execution only.
  • Code paths explicitly not touched: @expensify/react-native-background-task, iOS TaskManager, GPS notification UI, permission prompts, trip start/stop Onyx actions, reverse geocoding, and backend/API contracts.
  • API/backend changes: none.

What alternative solutions did you explore? (Optional)

Only guarding data.locations in the JS task is not enough because the fatal Sentry frame is native and can happen before the JS executor runs. I also considered upgrading all Expo task packages to the latest 55.0.x, but that brings unrelated headless-timer changes and still does not make the nullable loader boundary explicit. A narrow patch-package change matches the repo's existing dependency-patch pattern and addresses the exact native NPE boundary.

KJ21-ENG avatar Jun 02 '26 19:06 KJ21-ENG

⚠️ @KJ21-ENG Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar Jun 02 '26 19:06 github-actions[bot]

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

wildan-m avatar Jun 02 '26 19:06 wildan-m

⚠️ @wildan-m Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar Jun 02 '26 19:06 github-actions[bot]

Proposal

What is the root cause of that problem?

APP-4FK is a fatal java.lang.NullPointerException thrown from expo.modules.taskManager.TaskService.executeTask, Android + hybrid_app only. The app defines exactly one expo-task-manager task — 'background-location-tracking' — registered at module load and started for every GPS distance trip via expo-location.startLocationUpdatesAsync(...):

  • task body: https://github.com/Expensify/App/blob/main/src/setup/backgroundLocationTrackingTask/index.native.ts#L13-L33
  • start sites (both pass BACKGROUND_LOCATION_TASK_OPTIONS with no foregroundService): https://github.com/Expensify/App/blob/main/src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSButtons/index.tsx#L71-L80 https://github.com/Expensify/App/blob/main/src/components/GPSTripStateChecker/index.native.tsx#L62-L88
  • options: https://github.com/Expensify/App/blob/main/src/pages/iou/request/step/IOURequestStepDistanceGPS/const.ts#L1-L13

When Android delivers a location event to [email protected], TaskService.executeTask resolves the foreground manager via getTaskManager(appScopeKey) (a WeakReference<TaskManagerInterface> populated when the app's React host registers itself with Expo). If that ref is null — which on HybridApp it almost always is after the React activity is torn down — executeTask falls into the headless branch: getAppLoader().loadApp(mContextRef.get(), ...). getAppLoader() is AppLoaderProvider.getLoader("react-native-headless", context), which only returns non-null when a managed Expo app has registered a react-native-headless loader at startup. The HybridApp React host is created by @expensify/react-native-hybrid-app + Mobile-Expensify's native shell; nothing registers react-native-headless for it, so the call returns null and executeTask immediately dereferences it → NPE. This is structurally unreachable to fix from the JS task body — the NPE is thrown before defineTask's callback ever runs.

The smoking gun for the framing I want to propose is hiding in this same Android tree:

  • https://github.com/Expensify/App/blob/main/android/app/src/main/java/com/expensify/chat/GpsTripService.kt#L1-L100
  • https://github.com/Expensify/App/blob/main/android/app/src/main/java/com/expensify/chat/GpsTripServiceModule.kt#L1-L44
  • https://github.com/Expensify/App/blob/main/android/app/src/main/AndroidManifest.xml#L11-L37
  • https://github.com/Expensify/App/blob/main/src/pages/iou/request/step/IOURequestStepDistanceGPS/GPSNotifications/index.android.ts#L1-L23

The app already runs its own native foreground service — GpsTripService — for the entire lifetime of every GPS trip. It is declared with android:foregroundServiceType="location", the manifest already holds FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION, ACCESS_FINE_LOCATION, and ACCESS_BACKGROUND_LOCATION, and JS already starts/stops it on trip boundaries via GpsTripServiceModule.startService(...)/stopService(). But that service is used purely to host the persistent notification — it does no location work. So we are paying the cost of running a FOREGROUND_SERVICE_LOCATION service for the whole trip while still delegating the actual location stream to Expo's TaskManager dispatch path that NPEs on HybridApp.

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

Move Android GPS collection off expo-task-manager and onto the existing GpsTripService, so the TaskService.executeTask codepath is never reached on Android. iOS keeps expo-location (it uses a non-headless delivery path and does not crash).

  1. In GpsTripService.kt, after startForeground(...), acquire a FusedLocationProviderClient and requestLocationUpdates with a LocationRequest mirroring today's options (PRIORITY_HIGH_ACCURACY, setMinUpdateDistanceMeters(100f) to match GPS_DISTANCE_INTERVAL_METERS). In onDestroy, removeLocationUpdates. Pseudocode for the added piece:
// GpsTripService.kt
private lateinit var fusedClient: FusedLocationProviderClient
private val locationCallback = object : LocationCallback() {
    override fun onLocationResult(result: LocationResult) {
        val batch = result.locations.map {
            Arguments.createMap().apply {
                putDouble("latitude", it.latitude)
                putDouble("longitude", it.longitude)
                putDouble("timestamp", it.time.toDouble())
            }
        }
        GpsTripLocationBridge.emitOrBuffer(applicationContext, batch)
    }
}
// in onStartCommand, after startForeground(...):
fusedClient = LocationServices.getFusedLocationProviderClient(this)
val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, /* intervalMs */ 1000L)
    .setMinUpdateDistanceMeters(100f)
    .build()
fusedClient.requestLocationUpdates(request, locationCallback, Looper.getMainLooper())
  1. Add a tiny GpsTripLocationBridge helper that:

    • emits GpsTripLocationUpdate via DeviceEventManagerModule.RCTDeviceEventEmitter when a ReactContext is alive,
    • otherwise serializes the batch to a SharedPreferences-backed JSON list (small, append-only, capped at e.g. 5,000 points),
    • exposes @ReactMethod fun drainBufferedLocations(promise: Promise) on GpsTripServiceModule so JS can replay the queue on next startup.
  2. In GpsTripServiceModule, on startService(...) clear any leftover buffer if no trip is in progress (mirrors today's checkAndCleanGpsNotification cleanup in GPSNotifications/index.android.ts:21).

  3. JS side, add src/setup/backgroundLocationTracking/index.android.ts that subscribes once to new NativeEventEmitter(NativeModules.GpsTripServiceModule).addListener('GpsTripLocationUpdate', handleBatch) and also calls drainBufferedLocations() on app boot. handleBatch is the same body that lives in src/setup/backgroundLocationTrackingTask/index.native.ts:13-33 today (NetInfo offline check, addGpsPoints, shouldUpdateStartAddress → updateStartAddress) — pulled into a pure function and reused so the trip semantics don't change.

  4. Make the existing files Android-no-ops: convert backgroundLocationTrackingTask/index.native.ts to platform-split so Android exports nothing and only iOS keeps defineTask. Change the two startLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME, ...) call sites (GPSButtons/index.tsx:74, GPSTripStateChecker/index.native.tsx:75) to no-op on Android — GpsTripServiceModule.startService is already called for the notification right after, so the service starting is sufficient to begin tracking. Likewise the three stopLocationUpdatesAsync sites (GPSTripStateChecker/index.native.tsx:53, InitialSettingsPage.tsx:239, GPSDraftDetailsUtils.ts:107) become Android no-ops; stopService() already runs in those paths.

  5. Drop the unused BACKGROUND_LOCATION_TASK_OPTIONS constant on Android. Leave expo-location/expo-task-manager installed (iOS still uses them).

Why this — not "add foregroundService to options" or "patch expo-task-manager": both of those keep the broken executeTask → getAppLoader codepath in our execution graph and only try to make it harder to reach or safer when reached. The path is structurally wrong for HybridApp regardless of how alive we keep the runtime. Routing collection through the foreground service we already own eliminates the crash class by construction and gives us a single owner (GpsTripService) for the trip's lifecycle, notification, and data stream.

What alternative solutions did you explore? (Optional)

  1. Add foregroundService to BACKGROUND_LOCATION_TASK_OPTIONS so expo-location runs its own FG service. Standard expo-location guidance and a strong fit for managed Expo apps. I'm not picking it here because the app already runs GpsTripService with foregroundServiceType="location" for the same trip — adding expo-location's option starts a second FG service alongside ours (Android requires one notification per FG service, so two persistent notifications), and we still depend on TaskService.executeTask. Once Android tears down the React activity (Doze, multitasking, low-memory backgrounding), the WeakReference<TaskManagerInterface> clears and the same headless NPE branch is reachable even with a foreground service alive. Solid mitigation, but does not remove the broken path.
  2. patch-package null-guard inside TaskService.executeTask mirroring the guard invalidateAppRecord already has. Stops the native crash, but it makes the queued event a silent no-op whenever the loader is null, which is exactly the headless dispatch we'd be relying on if we keep expo-location. The result is a trip that quietly stops accumulating points after a process kill — worse UX than crashing, and exactly when motion is most likely. Worth keeping as belt-and-suspenders if we stayed on expo-location; with the consolidation above we don't need it.
  3. Aggressively stopLocationUpdatesAsync / unregisterTaskAsync on every cold start when no trip is in progress. Shrinks the trigger window but cannot help a legitimately in-progress trip whose process was reclaimed mid-drive, which is the precise case this feature exists for.
  4. Register a react-native-headless AppLoaderProvider from Mobile-Expensify so getAppLoader() returns non-null. This is the "real" upstream fix and would unblock expo-task-manager for HybridApp generally, but it lives in the submodule, requires bootstrapping a second React host for headless dispatch, and is well out of scope for an App-side change. The proposal above is fully resolvable inside this repo.

David-2002065 avatar Jun 02 '26 19:06 David-2002065

⚠️ @dilshodmackbook-sketch Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar Jun 02 '26 19:06 github-actions[bot]

This PR was merged yesterday; maybe it will fix the problem. Let's wait a few days to see if it helps.

Eskalifer1 avatar Jun 03 '26 09:06 Eskalifer1

@Eskalifer1 can you please check out the proposals? Thank you!

mountiny avatar Jun 03 '26 14:06 mountiny

Hi @mountiny Starting Friday, I'll be OOO until the 14th. I wasn't able to reproduce this bug, and it seems the PR mentioned above didn't help, since Sentry shows there have already been 10 crashes on the latest release in just a few hours.

I think it's best to reassign this task.

I’m sorry that I won’t be able to help here…

Eskalifer1 avatar Jun 03 '26 15:06 Eskalifer1

📣 @Eskalifer1 You have been assigned to this job! Please apply to the Upwork job and leave a comment on the Github issue letting us know when we can expect a PR to be ready for review 🧑‍💻 Once you apply to this job, your Upwork ID will be stored and you will be automatically hired for future jobs! Keep in mind: Code of Conduct | Contributing 📖

melvin-bot[bot] avatar Jun 03 '26 15:06 melvin-bot[bot]

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

melvin-bot[bot] avatar Jun 03 '26 18:06 melvin-bot[bot]

@truph01 Huh... This is 4 days overdue. Who can take care of this?

melvin-bot[bot] avatar Jun 08 '26 22:06 melvin-bot[bot]

📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

melvin-bot[bot] avatar Jun 09 '26 16:06 melvin-bot[bot]