I think this is mostly the algorithm in https://secure.phabricator.com/diffusion/P/browse/master/webroot/rsrc/js/core/ToolTip.js;6dc30ecc8ef1006b4b2614ae7e0506414c49722b$140-156, but my browser's thick scrollbars might also be involved:
It looks like the algorithm just looks for a corner that is somewhat on the screen, instead of checking that all corners are.
In https://secure.phabricator.com/uiexample/view/PHUIObjectItemListExample/, the top-most tooltip resolves to South:
{F1194395}
But most of the other ones goes East:
{F1194399}
I've tried hacking 20px off the `getViewport`, to compensate for the scrollbars, and it didn't do anything useful.