Crash fix equal_computations() again and scan opt speed up.

The crash was partly fixed in gh-1928. I add test for both fixes. Reported by John Jaques.

Also cherry-pick some related changes/speed up in scan PR gh-1872. That PR have some crash in user code. I pick what should be same(don't change opt order). When I get a case that reproduce the user error, I will be able to finish that PR.
idx is unused.