NSURLSession delegate methods are sometimes invoked out-of-order, when using concurrent backing NSOperationQueue

Originator:p4checo
Number:rdar://24042545 Date Originated:04/01/2016
Status:Open Resolved:
Product:iOS Product Version:iOS 7, iOS 8, iOS 9
Classification: Reproducible:Sometimes
 
Summary:
When using NSURLSession with a concurrent NSOperationQueue, sometimes the events are processed out-of-order.

This isn't always reproducible, but it seems to happen more often in a heavily concurrent environment, with multiple tasks being handled and other CPU heavy logic in the app.
The issue also seems to happen more frequently when many requests fail in sequence (e.g. by timing out).

Please see attached sample project, which reproduces the issue. The app essentially does a series of dummy file uploads to a Dropbox account (The hardcoded token is from a dummy account too).
It might be necessary to run the app multiple times until the issue reveals itself. Lowering the timeout thresholds can also help.
The app will invoke `fatalError()` when the ordering issue occurs.

My suggestion would be to add dependencies between the multiple task event's operations, so that even if the queue is concurrent, the events are processed in the correct order.

Cheers!

Steps to Reproduce:
1. Create an NSURLSessionTask with a concurrent NSOperationQueue
2. Schedule multiple data tasks (I've observed this more often in this type of task)

Expected Results:
The session tasks' events should be processed in the correct order. 

Namely, `URLSession:task:didCompleteWithError:` should always be the last delegate being called.

Actual Results:
The session tasks' events are (sometimes) fired out-of-order.

Especially on the data tasks, the URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: delegate method is sometimes invoked *after*  URLSession:task:didCompleteWithError:

Version:
iOS 7, iOS 8, iOS 9 (9.0.2 and 9.2), using Xcode 7.2 (7C68) 

Notes:
This issue was initially reported as rdar://21897559, but was closed due to a lack of response from my part.

Configuration:
iPhone 4, iPhone 5S, iPhone 6S, possibly others

Attachments:
'NSURLSession-event-order.zip' was successfully uploaded.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!