PromiseKit icon indicating copy to clipboard operation
PromiseKit copied to clipboard

Zalgo is unleashed

Open mxcl opened this issue 10 years ago • 19 comments

A repeated source of sporadic failures prove that our PMKDefaultDispatchQueue tests are in fact not deterministic: https://travis-ci.org/mxcl/PromiseKit/jobs/150471191

Here is an example of a failing test:

func testAlwaysWithDifferentQueue() {
    PMKDefaultDispatchQueue = { () -> dispatch_queue_t in
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
    }

    var fulfilled = false
    let testExpectation = expectationWithDescription("resolving")
    Promise(1).always {
        XCTAssertFalse(NSThread.isMainThread());

        fulfilled = true
        testExpectation.fulfill()
    }
    XCTAssertFalse(fulfilled).  // FAILS

    waitForExpectationsWithTimeout(1) { _ in
        XCTAssertTrue(fulfilled)
    }
}

How can this fail? Well, Travis is a stressed environment and the low priority queue, somehow, executes before the main thread continues.

This is exactly what is not meant to happen, because it means the handler is non-deterministic, sometimes it executes before the following code and sometimes it does not.

It is worrying our A+ tests do not turn this behavior up.

We should re-work how we dispatch, we need to do a single dispatch to the current queue before any handlers execute.

This also gives us an opportunity to apply a general optimization where we "dispatch-zalgo" if we are already on the correct thread after the one-time dispatch to the current queue occurs.

mxcl avatar Aug 07 '16 20:08 mxcl

We should re-work how we dispatch, we need to do a single dispatch to the current queue before any handlers execute.

Just curious, how do you intend to do that? I tried taking a stab at this, but GCD intentionally doesn't allow you to dispatch to the current queue.

By the way, this isn't too hard to repro locally if you just run the body of that test, say, 100 times.

zlangley avatar Oct 24 '16 23:10 zlangley

__dispatch_current_queue_label or something like that. Not great, but I don't see a better way yet.

mxcl avatar Oct 26 '16 16:10 mxcl

I've spent some time to understand the problem better and these are workarounds I considered:

  1. Get the current queue and dispatch to it - fails since it's not possible in iOS. We only have a deprecated and unreliable dispatch_get_current_queue.

  2. Get current queue name - this way we can easily identify main queue, PMKDefaultQueue etc..., but we won't identify user created queues. Without having access to them, we can't dispatch there. However we could focus only on identifying a main queue so it works in majority of cases.

  3. We can try to defer then execution a bit (using asyncAfter) so it works in most cases, but not all cases. (This sounds like a very bad idea though)

  4. There is one workaround that is likely to work. It relies on a fact, that current dispatch queue is tied to a thread which we can access

    @inline(__always) func contain_zalgo(_ q: DispatchQueue, body: @escaping () -> Void) {
        if q === zalgo || q === waldo && !Thread.isMainThread {
            body()
        } else {
            let thread = Thread.current
            let currentRunLoopCycle = thread.getCurrentRunLoopCycle // fictional method
            q.async {
                while thread.currentRunLoopCycle == currentRunLoopCycle {
                    Thread.sleep(forTimeInterval: 0.1)
                }
                body()
            }
        }
    }
    

I think we could get currentRunLoopCycle somehow, however cost of that operation seems to be not worth the result I think.

  • Lastly - we can just document that fact and require user to use then(on q:...) parameter. I get that it's not satisfying though.

It all led me to the thinking that to solve that we need to fill a rdar :-)

Also I'm posting a test case I used for playing with that:

//PMKDefaultDispatchQueueTest.swift
 func testAlwaysWithDifferentQueue() {
        var fulfilled = false
        let testExpectation = expectation(description: "resolving")
        Promise(value: 1).always {
            XCTAssertFalse(Thread.isMainThread)

            fulfilled = true
            testExpectation.fulfill()
        }

        for _ in 1 ... 1_000_000_000 {
            let _ = 0
        }

        XCTAssertFalse(fulfilled)

        waitForExpectations(timeout: 1) { _ in
            XCTAssertTrue(fulfilled)
        }
    }

BTW, in what real-world scenario do you find a PMKDefaultDispatchQueue useful?

FilipZawada avatar Nov 17 '16 22:11 FilipZawada

Lastly - we can just document that fact and require user to use then(on q:...) parameter. I get that it's not satisfying though.

I don't think this helps. We need to know the queue that they are calling then from, not the queue they intend to run the block on.

zlangley avatar Nov 17 '16 23:11 zlangley

Correct, it should be additional returnOn: parameter or sth like that

FilipZawada avatar Nov 17 '16 23:11 FilipZawada

We cannot assume the caller knows what queue it is running on, just like we cannot determine what queue we are running on. (Not to mention this would be a very easy API to misuse; simply pass the wrong queue and you may be deadlocked.)

zlangley avatar Nov 17 '16 23:11 zlangley

We cannot assume the caller knows what queue it is running on, just like we cannot determine what queue we are running on.

True, that's why I said "it's not satisfying too".

FilipZawada avatar Nov 17 '16 23:11 FilipZawada

(I don't know how could we cause a deadlock by passing a wrong queue though - we're not using dispatch.sync after all)

FilipZawada avatar Nov 17 '16 23:11 FilipZawada

You're right, I typed that comment too quickly.

zlangley avatar Nov 18 '16 22:11 zlangley

I spent some time trying to solve this well in the experimental PMK5 branch, the only real option is to create an object and wait for it to be deallocated. This is not good IMO as the docs for GCD say that autoreleasepools in threads without NSRunLoops only run every 50ms or so. Thus we are slowing down promises quite substantially (for queues without runloops, which is almost all queues that aren't the main queue).

So in the end I have decided that we do not guarantee Promises/A+ off the main queue, I don't see how else to avoid this.

In practice however it mostly behaves as desired. Especially if the chain starts on the main thread. Which is almost always. This really is edge-case, potentially “zalgo” behavior.

However in PMK5 I did implement the optimization where subsequent thens execute in the same “context” for the main queue. This avoids a dispatch to the next main run loop cycle in many cases so is a win, though in practice nobody is going to notice IMO.

mxcl avatar Feb 24 '17 23:02 mxcl

the only real option is to create an object and wait for it to be deallocated.

How do you want to achieve that?

{
  code...
  Promise()
  code...
}
// Promise() gets deallocated

but

{
  code...
  promise = Promise()
  code...
}
// promise is still in the memory

FilipZawada avatar Feb 25 '17 17:02 FilipZawada

It wasn't the promise itself that this logic was inside, it was in a helper object that the Promise itself manages (or didn't manage specifically).

mxcl avatar Feb 25 '17 17:02 mxcl

I have no idea how did you achieve that even within NSRunLoops 🤔. For me since it's happening within promise, it's deallocated before returning to function that created promise.

FilipZawada avatar Feb 25 '17 17:02 FilipZawada

This creates a new DispatchQueue, surely that means the thread it executes onto is undefined? And we have to wait for the thread a then handler is added to have a new “execution context”, so forgive me, but I'm not quite seeing how your example works.

I did something like:

class Helper {
    var done = {}
    deinit {
        done() // deallocate occurs in the thread that you instantiate your object, provided no other thread gets a handle anyway
    }
}

extension Promise {
   func then(body: () -> Void) -> Promise {
       let helper = Helper()
       helper.done = body
       // ^^ simplified obv.
   }
}

Where I did it in such a way that Swift wouldn't smartly optimize away the autorelease.

mxcl avatar Feb 25 '17 17:02 mxcl

so forgive me, but I'm not quite seeing how your example works.

Sorry, the example was broken, so I removed it before you posted an answer.

Regarding your example, I can't make it to work too, but congrats on the idea anyway :) Will play with that again when I have more time.

FilipZawada avatar Feb 25 '17 17:02 FilipZawada

Well, my idea didn't work well enough, so I didn't consider it good enough. With up to 50ms latency, it didn't seem acceptable.

Also I didn't use it for threads with runloops as your suggestion worked better.

If we could figure out a general solution for threads without runloops then I'd be all for it.

mxcl avatar Feb 25 '17 17:02 mxcl

Really the only solution is something like this (pseudocode):

let p = somePromise()
defer { p.continue() }
p.then {
    //…
}

defer does what is needed, but we can't automate its usage.

mxcl avatar Jul 02 '17 16:07 mxcl

If we assume there's no solution without changing syntax, then maybe worth using your solution (~50ms penalty in some cases) with slightly changed syntax? E.g. somePromise.deferred.then { ... }? (deferred would unlock your hack)

Still way more convenient then asking user to write proper defer {...} statement. In docs we could describe potential perf penalty and show proper defer { ... } alternative for people interested in that.

FilipZawada avatar Aug 23 '17 21:08 FilipZawada

I don't believe we can really fix this.

mxcl avatar Feb 12 '18 21:02 mxcl