Skip to content

fix(ios): warm up RCTImageLoader before parallel image loads - #4373

Merged
mfazekas merged 3 commits into
rnmapbox:mainfrom
doguyilmaz:fix/ios-image-queue-serial-queue
Oct 20, 2026
Merged

mfazekas merged 3 commits into
rnmapbox:mainfrom
doguyilmaz:fix/ios-image-queue-serial-queue

Conversation

@doguyilmaz

@doguyilmaz doguyilmaz commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Related to #3725.

RNMBXImageQueue starts its loads on DispatchQueue.global, so an <Images> with many entries calls a new RCTImageLoader from many threads at once. Two lazy initializations in RCTImageLoader are not safe for that first concurrent use:

The imageCache one crashes like this:

EXC_BAD_ACCESS  objc_retain
-[RCTImageLoader _loadImageOrDataWithURLRequest:size:scale:resizeMode:priority:attribution:progressBlock:partialLoadBlock:completionBlock:]
closure #1 in RNMBXImageQueueOperation.start() at RNMBXImageQueue.swift:80

This PR warms each new RCTImageLoader up once before the parallel loads: the first load is a 1×1 data: PNG with a partialLoadBlock, made under a lock. Its synchronous part sets up _loaders and imageCache. _decoders is set up when that image is decoded, on the loader's serial request queue, which is also where network and data: images get decoded. After that the loads run in parallel as before. The warm-up is keyed per loader because a JS reload creates a new one.

Tested with the reproducer below in /example (RN 0.84.1, iPhone 17 Pro simulator, iOS 26.5). On the simulator the race does not fire on its own, so I widened its window with a temporary swizzle of -[RCTImageLoader imageCache] (not part of this PR):

main this PR
widened window 51 of 51 launches crashed no crash in 191 runs
no instrumentation no crash in ~170 runs

Checklist

  • I've read CONTRIBUTING.md
  • I updated the doc/other generated code with running yarn generate in the root folder (no changes)
  • I have tested the new feature on /example app.
    • In V11 mode/ios
    • In New Architecture mode/ios
    • In V11 mode/android
    • In New Architecture mode/android
  • I added/updated a sample - if a new feature was implemented (/example)

iOS only.

Component to reproduce the issue you're fixing

Register it as the root component in example/index.js (it reloads JS after every run so each run gets a new RCTImageLoader), then press Start.

import React, { useEffect, useState } from 'react';
import { Button, DevSettings, Settings, StyleSheet, Text, View } from 'react-native';
import { Images, MapView } from '@rnmapbox/maps';

// Every run mounts a map whose <Images> loads IMAGE_COUNT images at once, so
// RNMBXImageQueue calls RCTImageLoader from that many GCD threads in parallel.
// The run then reloads JS, which creates a new RCTImageLoader whose lazily
// created imageCache is hit concurrently again on the next run.
// A run that never finished means the app crashed during it.

const RUNNING = 'imageQueueRepro.running';
const RUNS = 'imageQueueRepro.runs';
const CRASHES = 'imageQueueRepro.crashes';
const PENDING = 'imageQueueRepro.pending';

const IMAGE_COUNT = 64;
const PIXEL =
  'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';

const images = Object.fromEntries(
  Array.from({ length: IMAGE_COUNT }, (_, i) => [
    `repro-${i}`,
    { uri: `${PIXEL}#${i}` },
  ]),
);

const emptyStyle = JSON.stringify({ version: 8, sources: {}, layers: [] });

const read = (key) => Settings.get(key) ?? 0;

const BugReportExample = () => {
  const [running, setRunning] = useState(() => read(RUNNING) === 1);
  const [counts] = useState(() => {
    const crashed = read(PENDING) === 1;
    const crashes = read(CRASHES) + (crashed ? 1 : 0);
    Settings.set({ [CRASHES]: crashes, [PENDING]: 0 });
    return { runs: read(RUNS), crashes };
  });

  useEffect(() => {
    if (!running) {
      return undefined;
    }
    Settings.set({ [RUNS]: counts.runs + 1, [PENDING]: 1 });
    const timer = setTimeout(() => {
      Settings.set({ [PENDING]: 0 });
      DevSettings.reload();
    }, 1500);
    return () => clearTimeout(timer);
  }, [running, counts.runs]);

  const start = () => {
    Settings.set({ [RUNNING]: 1, [RUNS]: 0, [CRASHES]: 0, [PENDING]: 0 });
    setRunning(true);
  };

  const stop = () => {
    Settings.set({ [RUNNING]: 0, [PENDING]: 0 });
    setRunning(false);
  };

  return (
    <View style={styles.container}>
      <MapView style={styles.map} styleJSON={emptyStyle}>
        {running && <Images images={images} />}
      </MapView>
      <View style={styles.panel}>
        <Text>
          runs: {counts.runs} crashes: {counts.crashes}
        </Text>
        <Button title={running ? 'Stop' : 'Start'} onPress={running ? stop : start} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1 },
  map: { flex: 1 },
  panel: { padding: 16, gap: 8 },
});

export default BugReportExample;
Temporary swizzle that widens the race window (AppDelegate.mm)

Call it at the top of application:didFinishLaunchingWithOptions: and launch with SIMCTL_CHILD_REPRO_WIDEN_RACE=1 xcrun simctl launch <udid> org.reactjs.native.example.RNMapboxExample.

#import <objc/runtime.h>

// Repro instrumentation, not part of the fix: widens the window of the unlocked
// lazy `-[RCTImageLoader imageCache]` getter. Same logic as RN's getter, with sleeps
// between the nil check and the store, and between the ivar load and the retain.
static void ReproWidenImageCacheRace(void)
{
  Class loaderClass = NSClassFromString(@"RCTImageLoader");
  Class cacheClass = NSClassFromString(@"RCTImageCache");
  Ivar ivar = class_getInstanceVariable(loaderClass, "_imageCache");
  Method method = class_getInstanceMethod(loaderClass, NSSelectorFromString(@"imageCache"));
  if (!loaderClass || !cacheClass || !ivar || !method) {
    NSLog(@"[repro] instrumentation unavailable");
    return;
  }
  method_setImplementation(method, imp_implementationWithBlock(^id(id loader) {
    if (object_getIvar(loader, ivar) == nil) {
      usleep(2000);
      object_setIvar(loader, ivar, [cacheClass new]);
    }
    __unsafe_unretained id cache = object_getIvar(loader, ivar);
    usleep(500);
    return cache;
  }));
  NSLog(@"[repro] imageCache race window widened");
}
  if ([NSProcessInfo.processInfo.environment[@"REPRO_WIDEN_RACE"] isEqualToString:@"1"]) {
    ReproWidenImageCacheRace();
  }

@mfazekas mfazekas left a comment

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.

Thanks for digging into this and for the reproducer.

It's unfortunate that we have to work around this at all, since these are bugs in React Native's RCTImageLoader, whose protocol says it can be called from any thread. There are two first-call races there:

Both only bite on the first concurrent use of a fresh loader, so rather than serializing every load, could we warm the loader up once instead? For example, on first use in RNMBXImageQueue, do a single loadImage of a 1×1 data: PNG (with a partialLoadBlock, so the cache path runs too) before starting the parallel loads. That initializes _loaders, _decoders and imageCache through public API, keeps loads parallel, and is easy to delete once our minimum RN includes both fixes. A one-line comment pointing at the two RN PRs is enough.

Could you also mention #57297 in the description, and if possible check the warm-up against your swizzle reproducer?

@doguyilmaz doguyilmaz changed the title fix(ios): start RNMBXImageQueue loads from a serial queue fix(ios): warm up RCTImageLoader before parallel image loads Oct 19, 2026
@doguyilmaz

Copy link
Copy Markdown
Contributor Author

Thanks, that is a better approach. Switched to a one-time warm-up per RCTImageLoader: a 1×1 data: PNG with a partialLoadBlock, made under a lock before the parallel loads, so loads are parallel again. With the swizzle reproducer: no crash in 191 runs, while main crashes on every launch. Added #57297 to the description. Anything else you would like changed?

@mfazekas mfazekas left a comment

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.

Thanks, this is what I had in mind. The warm-up is small, runs once per loader, and loads are parallel again. I checked it against RCTImageLoader: the synchronous part of the data: PNG load sets up _loaders and, with the partialLoadBlock, imageCache. _decoders is then set up on the serial request queue, where our decodes happen anyway. The completion isn't awaited and the lock is only taken off the main thread, so I don't see a deadlock or hang risk.

Two small things for a follow-up. Could the comment say it can be removed once our minimum RN includes both #57297 and #57971, so whoever cleans it up later knows when? And warmUp could be fileprivate, since only the operation in this file calls it.

Again, it's unfortunate we need this at all for what is an RN bug, but this keeps the workaround cheap and easy to delete.

@mfazekas
mfazekas merged commit 5776f8f into rnmapbox:main Oct 20, 2026
9 checks passed
@doguyilmaz

Copy link
Copy Markdown
Contributor Author

Thanks for the review and the merge. Both follow-ups are in #4377.

This branch was previously deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants