#23384·arangodb

ArangoDB AQL `SORTED()` replaces distinct elements that compare equal

Author: the-ShallowCreated Sep 29, 2026Updated Sep 30, 2026

Summary

SORTED() collapses input elements into a std::map keyed by AQL comparison order and keeps only a count per key, so when two structurally different values compare equal under AQL's ordering (e.g. [] and [null], or {} and {a: null}), the second one is discarded and emitted as an extra copy of the first. The result is not a permutation of the input: SORTED([[], [null]]) returns [[], []]. The SORT clause, which is documented to use the same comparison order, returns both values unchanged.

Reproducing the Bug

python
import db_harness as db

print(db.query("RETURN SORTED([[], [null]])").rows)
print(db.query("RETURN SORTED([[null], []])").rows)
print(db.query("RETURN SORTED([{}, {a: null}])").rows)
print(db.query("RETURN SORTED([[], [null], [null, null], 'a'])").rows)
print(db.query("RETURN (FOR x IN [[], [null]] SORT x RETURN x)").rows)

Output:

[[[], []]]                  # expected [[], [null]]
[[[None], [None]]]          # expected [[null], []]
[[{}, {}]]                  # expected [{}, {a: null}]
[['a', [], [], []]]         # expected ['a', [], [null], [null, null]]
[[[], [None]]]              # SORT clause: correct

Fix

Sort the elements themselves instead of deduplicating them into a map. A std::stable_sort over the collected slices preserves every element, preserves input order within an equivalence class, and keeps the same O(n log n) cost.

diff
--- a/arangod/Aql/Function/ArrayFunctions.cpp
+++ b/arangod/Aql/Function/ArrayFunctions.cpp
@@
   AqlValueMaterializer materializer(vopts);
   VPackSlice slice = materializer.slice(value);
 
   basics::VelocyPackHelper::VPackLess<true> less(
       trx->transactionContext()->getVPackOptions(), &slice, &slice);
-  std::map<VPackSlice, size_t, basics::VelocyPackHelper::VPackLess<true>>
-      values(less);
+  std::vector<VPackSlice> values;
+  values.reserve(slice.length());
   for (VPackSlice it : VPackArrayIterator(slice)) {
     if (!it.isNone()) {
-      auto [itr, emplaced] = values.try_emplace(it, 1);
-      if (!emplaced) {
-        ++itr->second;
-      }
+      values.emplace_back(it);
     }
   }
+  std::stable_sort(values.begin(), values.end(), less);
 
   auto builder = ThreadLocalBuilderLeaser::lease();
   builder->openArray();
   for (auto const& it : values) {
-    for (size_t i = 0; i < it.second; ++i) {
-      builder->add(it.first);
-    }
+    builder->add(it);
   }
   builder->close();
   return AqlValue(builder->slice(), builder->size());