I am trully unable to reproduce any kind of misbehaviours regarding p=, no matter what I set and at what kind of timing I start the miner. Everything is working just fine. I tested with sgminer 4.0.0.
So, until I have a way to reproduce this bug I really have no idea what else to do or look. Believe me, I have been sitting in front of code for hours trying to figure out what could have gone wrong, and I couldn't find it. I can paste you the part regarding it and you will see on your own.
I wish I could spend the time to help you find it -- because it just happened twice on one miner and once on another while I had them up on my screen, within twenty minutes of your last post. I was unable to capture any usable logs, but it went something like this. I was mining at nicehash with p=7.9 and there were one or two 7.9 orders available (and none higher) that were active and mining properly. Then they expired or were canceled (they fell off the order list anyway), leaving only lower priced orders, and my miners did not disconnect from the stratum server, instead the GPUs spun down (as seen by decreasing GPU temperatures), and neither accepted nor rejected shares increased. At this point, my monitoring process will notice stuck accepted shares and restart the miner, but I disabled it temporarily to see if I could gather any more data while it was stuck doing nothing. Unfortunately before I could, a new 8.1 order popped up and hashing started again. So I've reenabled my monitor process and will just hope that you find the cause soon.
There are indeed times that nicehash will properly fail over to my backup pool as expected without my monitor process having to intervene, so this problem is almost certainly intermittent in nature. What you have coded does work at least some of the time, so the source of this problem will probably not be obvious.
Also worth noting is that from what I have observed before, the appearance of a higher priced order will not necessarily pull my miner out of its nap, as that order might already be full. Perhaps you can think of another non-standard way to get a miner to disconnect before sending authorization error and closing the socket? I am running sgminer 4.1.271.