NSFetchedResultsController index out of bounds during context merging changes

I've noticed several crashes that look like they're caused by an index out of bound in internal methods of NSFetchedResultsController. This happens while changes are merged from the persistent store container into the view context. Here's an example of the last exception backtrace.

Exactly which internal methods that are called in - [NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] vary between crash reports but they all end up crashing from _NSArrayRaiseBoundException.

The Core Data stack consists of one persistent store, one persistent store coordinator that the view context is set up to automatically merge changes from, and data is saved to disk from background context.

persistentContainer.loadPersistentStores(...)

viewContext = persistentContainer.viewContext
viewContext.automaticallyMergesChangesFromParent = true
        
backgroundContext = persistentContainer.newBackgroundContext()
backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        
backgroundClientContext = persistentContainer.newBackgroundContext()
backgroundClientContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

Does anyone have any ideas what could be causing this? Thankful for any ideas or advice on how to investigate further.

The Core Data stack looks fine. Did you implement any NSFetchedResultsControllerDelegate method? For debugging purpose, you can try the following and see if the crashes are still there:

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Thank you for your reply, @DTS Engineer!

Yes, the app uses NSFetchedResultsControllerDelegate to refresh the UI, and controllerDidChangeContent(_:) is the only method that is implemented throughout the app.

Unfortunately, I have not yet been able to reproduce this crash myself. I noticed in the Xcode organizer that it affected 20 devices during the past two weeks and around 230 devices past year. It seems pretty rare but would of course be very nice to understand and eliminate these crashes.

To my understanding it looks like Core Data is stepping out of bounds when accessing some internal data representation in NSFetchedResultsController. However, I struggle to understand how that can happen during a single merge that is all taking place on the same (main) thread. Is it be possible that the input notification to -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] could have become invalid in some edge cases at the time of actually performing the merge?

Or do you have any other advice on how to reach a stage where I can reproduce / work towards a fix for this issue? :)

All the best, Oscar

NSFetchedResultsController index out of bounds during context merging changes
 
 
Q