diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py
index 0ddc34330d4147c99f0d6aa1d87ddac8fa166c15_bWVyY3VyaWFsL2JyYW5jaG1hcC5weQ==..1a9bdd0e1c444df10e233b047a120e2b869e4088_bWVyY3VyaWFsL2JyYW5jaG1hcC5weQ== 100644
--- a/mercurial/branchmap.py
+++ b/mercurial/branchmap.py
@@ -166,7 +166,10 @@
 
     def write_delayed(self, repo):
         unfi = repo.unfiltered()
-        for filtername, cache in self._per_filter.items():
+        for filtername in repoviewutil.get_ordered_subset():
+            cache = self._per_filter.get(filtername)
+            if cache is None:
+                continue
             if cache._delayed:
                 if filtername is None:
                     repo = unfi
diff --git a/mercurial/utils/repoviewutil.py b/mercurial/utils/repoviewutil.py
index 0ddc34330d4147c99f0d6aa1d87ddac8fa166c15_bWVyY3VyaWFsL3V0aWxzL3JlcG92aWV3dXRpbC5weQ==..1a9bdd0e1c444df10e233b047a120e2b869e4088_bWVyY3VyaWFsL3V0aWxzL3JlcG92aWV3dXRpbC5weQ== 100644
--- a/mercurial/utils/repoviewutil.py
+++ b/mercurial/utils/repoviewutil.py
@@ -6,6 +6,7 @@
 # This software may be used and distributed according to the terms of the
 # GNU General Public License version 2 or any later version.
 
+from .. import error
 
 ### Nearest subset relation
 # Nearest subset of filter X is a filter Y so that:
@@ -21,3 +22,30 @@
     b'served': b'immutable',
     b'immutable': b'base',
 }
+
+
+def get_ordered_subset():
+    """return a list of subset name from dependencies to dependents"""
+    _unfinalized = set(subsettable.values())
+    ordered = []
+
+    # the subset table is expected to be small so we do the stupid N² version
+    # of the algorithm
+    while _unfinalized:
+        this_level = []
+        for candidate in _unfinalized:
+            dependency = subsettable.get(candidate)
+            if dependency not in _unfinalized:
+                this_level.append(candidate)
+
+        if not this_level:
+            msg = "cyclic dependencies in repoview subset %r"
+            msg %= subsettable
+            raise error.ProgrammingError(msg)
+
+        this_level.sort(key=lambda x: x if x is not None else '')
+
+        ordered.extend(this_level)
+        _unfinalized.difference_update(this_level)
+
+    return ordered