Fix for #3970 cache invalidation bug

Also fixed stable sorting test failure that presents on some platforms