Fix for #3970 cache invalidation bug

Also fixed stable sorting bug that presents on some platforms