The root cause of the crash was that currently the depsgraph does not support
being rebuilt twice without being evaluated in the meantime. While not ideal to
rebuild the depsgraph twice, it's really something I'd expect to work without
crashes/leaks.
The double-rebuild when switching the scene was introduced by b6e1afb6e1
which tagged the depsgraph relations indirectly. Tagging relations at that place
should be valid though. The same bug can easily be reproduced by explicitly
writing code that rebuilds the depsgraph twice as shown in
https://projects.blender.org/blender/blender/issues/139079#issuecomment-1615029.
So far, we've found two places that need to be fixed to properly support
rebuilding the depsgraph before it has been evaluated:
* `update_invalid_cow_pointers`: `previously_visible_components_mask` was used
to check if the id is new and therefore not expanded yet. However, this check
is wrong in the case when the depsgraph was not evaluated yet. Instead, check
whether the ID is expanded directly. IDs which don't use copy-on-eval are
still handled properly due to another existing check.
* `DepsgraphNodeBuilder::begin_build`: This just discarded
allocated-but-not-expanded IDs without freeing them. Now they are freed when
their ownership is not transferred to `IDInfo`.
See
https://projects.blender.org/blender/blender/issues/139079#issuecomment-1615029
for more details.
Pull Request: https://projects.blender.org/blender/blender/pulls/141199