Add a check and error for conditions that shouldn't happen.

This fixes the current locking problems (but does not actually fix
the condition that caused the infinite loop). This does add a failing
test that exercises these new conditions.
Cleanup based on review comments