Fix infinite loop when saving root container

Also wrote a unit test to verify it.