validation BUGFIX keep order of node_when nodes

Fixes sysrepo/sysrepo#2664
diff --git a/src/set.c b/src/set.c
index 8be7ad8..ecf3dae 100644
--- a/src/set.c
+++ b/src/set.c
@@ -226,3 +226,22 @@
 
     return ly_set_rm_index(set, i, destructor);
 }
+
+LY_ERR
+ly_set_rm_index_ordered(struct ly_set *set, uint32_t index, void (*destructor)(void *obj))
+{
+    if (destructor) {
+        destructor(set->objs[index]);
+    }
+    set->count--;
+    if (index == set->count) {
+        /* removing last item in set */
+        set->objs[index] = NULL;
+    } else {
+        /* removing item somewhere in a middle, move following items */
+        memmove(set->objs + index, set->objs + index + 1, (set->count - index) * sizeof *set->objs);
+        set->objs[set->count] = NULL;
+    }
+
+    return LY_SUCCESS;
+}
diff --git a/src/tree_data_internal.h b/src/tree_data_internal.h
index 13c3004..f6d8694 100644
--- a/src/tree_data_internal.h
+++ b/src/tree_data_internal.h
@@ -511,4 +511,14 @@
  */
 LY_ERR lyd_path_list_predicate(const struct lyd_node *node, char **buffer, size_t *buflen, size_t *bufused, ly_bool is_static);
 
+/**
+ * @brief Remove an object on the specific set index keeping the order of the other objects.
+ *
+ * @param[in] set Set from which a node will be removed.
+ * @param[in] index Index of the object to remove in the \p set.
+ * @param[in] destructor Optional function to free the objects being removed.
+ * @return LY_ERR return value.
+ */
+LY_ERR ly_set_rm_index_ordered(struct ly_set *set, uint32_t index, void (*destructor)(void *obj));
+
 #endif /* LY_TREE_DATA_INTERNAL_H_ */
diff --git a/src/validation.c b/src/validation.c
index a6c9fdd..9e365b6 100644
--- a/src/validation.c
+++ b/src/validation.c
@@ -241,8 +241,8 @@
                 node->flags |= LYD_WHEN_TRUE;
             }
 
-            /* remove this node from the set, its when was resolved */
-            ly_set_rm_index(node_when, i, NULL);
+            /* remove this node from the set keeping the order, its when was resolved */
+            ly_set_rm_index_ordered(node_when, i, NULL);
         } else if (ret != LY_EINCOMPLETE) {
             /* error */
             goto error;