This seems like it can get expensive. I wonder why `topologically_sort_terms()` is needed in the first place.