Fix sorting for complex dependency chains (but regress sort performance)