diff BUGFIX diff merge userord node order

Fixes #3316
diff --git a/src/diff.c b/src/diff.c
index 744f039..76f9c6a 100644
--- a/src/diff.c
+++ b/src/diff.c
@@ -1651,14 +1651,18 @@
             orig_meta = lyd_find_meta((*diff_match)->meta, NULL, orig_meta_name);
             LY_CHECK_ERR_RET(!orig_meta, LOGERR_META(ctx, orig_meta_name, *diff_match), LY_EINVAL);
 
-            /* the (incorrect) assumption made here is that there are no previous diff nodes that would affect
-             * the anchors stored in the metadata */
             if (strcmp(lyd_get_meta_value(meta), lyd_get_meta_value(orig_meta))) {
                 /* deleted + created at another position -> operation REPLACE */
                 LY_CHECK_RET(lyd_diff_change_op(*diff_match, LYD_DIFF_OP_REPLACE));
 
                 /* add anchor metadata */
                 LY_CHECK_RET(lyd_dup_meta_single(meta, *diff_match, NULL));
+
+                /* previous created nodes affect the metadata so move it at the end */
+                child = lyd_first_sibling(*diff_match);
+                if (child->next) {
+                    LY_CHECK_RET(lyd_insert_after(child->prev, *diff_match));
+                }
             } else {
                 /* deleted + created at the same position -> operation NONE */
                 LY_CHECK_RET(lyd_diff_change_op(*diff_match, LYD_DIFF_OP_NONE));
diff --git a/tests/utests/data/test_diff.c b/tests/utests/data/test_diff.c
index c121bc1..d85027b 100644
--- a/tests/utests/data/test_diff.c
+++ b/tests/utests/data/test_diff.c
@@ -976,13 +976,13 @@
             "    <l1>a</l1>\n"
             "    <l2 yang:operation=\"delete\">1</l2>\n"
             "  </ul>\n"
-            "  <ul yang:orig-key=\"[l1='a']\" yang:operation=\"replace\" yang:key=\"[l1='c']\">\n"
-            "    <l1>b</l1>\n"
-            "  </ul>\n"
             "  <ul yang:operation=\"none\">\n"
             "    <l1>c</l1>\n"
             "    <l2 yang:operation=\"replace\" yang:orig-default=\"false\" yang:orig-value=\"3\">33</l2>\n"
             "  </ul>\n"
+            "  <ul yang:orig-key=\"[l1='a']\" yang:operation=\"replace\" yang:key=\"[l1='c']\">\n"
+            "    <l1>b</l1>\n"
+            "  </ul>\n"
             "</df>\n";
 
     TEST_DIFF_3(xml1, xml2, xml3, out_diff_1, out_diff_2, out_merge);