Found by Opus 5: before starting these steps, it's important that the template is rewritten following the serialization rules (integers using their shortest unsigned decimal representation, hex lowercase, syntactic sugars used, etc), otherwise there might be discrepancies in the sorting. This is implemented in the reference, and specified above ("The following ''serialization rules'' apply to the template and to every key expression, leaf, and subtree in it..."), but could be repeated here to make it even more clear.
Also, a test vector that catches this should be added:
diff --git a/bip-0395/gen_vectors.py b/bip-0395/gen_vectors.py
index 54ba2ae..ff46aef 100644
--- a/bip-0395/gen_vectors.py
+++ b/bip-0395/gen_vectors.py
@@ -88,6 +88,8 @@ def generate():
add("tree-reshaped", "tr(_/**,{{pk(@0/**),pk(@1/**)},pk(@2/**)})", [A, B, C])
add("tree-repeated", "tr(_/**,{pk(@0/**),pk(@0/**)})", [A])
add("tree-duplicate-record", "tr(_/**,{pk(@0/**),pk(@1/**)})", [A, A])
+ add("tree-sugar", "tr(_/**,{pk(@0/**),pk(@1/**)})", [B, A])
+ add("tree-sugar-expanded", "tr(_/**,{c:pk_k(@0/**),pk(@1/**)})", [B, A])
add("timelock", "tr(_/**,and_v(v:pk(@0/**),older(144)))", [A])
add("timelock-changed", "tr(_/**,and_v(v:pk(@0/**),older(145)))", [A])
add("sugar", "tr(_/**,and_n(pk(@0/**),tv:pkh(@1/**)))", [A, B])
@@ -117,6 +119,7 @@ def generate():
["sorted", "sorted-permuted"], ["musig", "musig-permuted"],
["musig-repeated", "musig-duplicate-record"], ["musig-same-point", "musig-same-point-reversed"],
["tree", "tree-swapped"], ["tree-repeated", "tree-duplicate-record"],
+ ["tree-sugar", "tree-sugar-expanded"],
["sugar", "sugar-expanded"], ["l-zero", "u-zero", "or-zero"],
["numeric-spelling", "numeric-canonical"], ["hashlock", "hashlock-lower"],
]