Fix an exception when the outermost stack_context is deactivated.

Add more tests for deactivation in various scenarios.