Skip to main content

promql/
go_sort.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A port of Go's `sort.Sort` / `slices.SortFunc` (pattern-defeating quicksort, Go 1.19+).
16//!
17//! Prometheus orders results with these, and with comparators that are not total orders
18//! (NaN ranks first in `Less` against everything, `natsort.Compare` holds both ways for "1"
19//! and "01"). The order of such elements is part of the result, and Rust's sorts may panic on
20//! such comparators, so the exact algorithm is reproduced.
21
22/// Sorts `v` the way Go's `sort.Sort` does with `less` as `Less`.
23pub(crate) fn sort_by<T>(v: &mut [T], mut less: impl FnMut(&T, &T) -> bool) {
24    let n = v.len();
25    if n <= 1 {
26        return;
27    }
28    let limit = bit_len(n);
29    let mut sorter = Sorter { v, less: &mut less };
30    sorter.pdqsort(0, n, limit);
31}
32
33fn bit_len(n: usize) -> usize {
34    (usize::BITS - n.leading_zeros()) as usize
35}
36
37#[derive(PartialEq, Eq)]
38enum Hint {
39    Unknown,
40    Increasing,
41    Decreasing,
42}
43
44struct Sorter<'a, T, F> {
45    v: &'a mut [T],
46    less: &'a mut F,
47}
48
49impl<T, F: FnMut(&T, &T) -> bool> Sorter<'_, T, F> {
50    fn less(&mut self, i: usize, j: usize) -> bool {
51        (self.less)(&self.v[i], &self.v[j])
52    }
53
54    fn swap(&mut self, i: usize, j: usize) {
55        self.v.swap(i, j);
56    }
57
58    fn insertion_sort(&mut self, a: usize, b: usize) {
59        for i in a + 1..b {
60            let mut j = i;
61            while j > a && self.less(j, j - 1) {
62                self.swap(j, j - 1);
63                j -= 1;
64            }
65        }
66    }
67
68    fn sift_down(&mut self, lo: usize, hi: usize, first: usize) {
69        let mut root = lo;
70        loop {
71            let mut child = 2 * root + 1;
72            if child >= hi {
73                break;
74            }
75            if child + 1 < hi && self.less(first + child, first + child + 1) {
76                child += 1;
77            }
78            if !self.less(first + root, first + child) {
79                return;
80            }
81            self.swap(first + root, first + child);
82            root = child;
83        }
84    }
85
86    fn heap_sort(&mut self, a: usize, b: usize) {
87        let first = a;
88        let hi = b - a;
89        for i in (0..=(hi - 1) / 2).rev() {
90            self.sift_down(i, hi, first);
91        }
92        for i in (0..hi).rev() {
93            self.swap(first, first + i);
94            self.sift_down(0, i, first);
95        }
96    }
97
98    fn pdqsort(&mut self, mut a: usize, mut b: usize, mut limit: usize) {
99        const MAX_INSERTION: usize = 12;
100        let mut was_balanced = true;
101        let mut was_partitioned = true;
102        loop {
103            let length = b - a;
104            if length <= MAX_INSERTION {
105                self.insertion_sort(a, b);
106                return;
107            }
108            if limit == 0 {
109                self.heap_sort(a, b);
110                return;
111            }
112            if !was_balanced {
113                self.break_patterns(a, b);
114                limit -= 1;
115            }
116
117            let (mut pivot, mut hint) = self.choose_pivot(a, b);
118            if hint == Hint::Decreasing {
119                self.reverse_range(a, b);
120                pivot = (b - 1) - (pivot - a);
121                hint = Hint::Increasing;
122            }
123            if was_balanced
124                && was_partitioned
125                && hint == Hint::Increasing
126                && self.partial_insertion_sort(a, b)
127            {
128                return;
129            }
130            if a > 0 && !self.less(a - 1, pivot) {
131                a = self.partition_equal(a, b, pivot);
132                continue;
133            }
134
135            let (mid, already_partitioned) = self.partition(a, b, pivot);
136            was_partitioned = already_partitioned;
137            let (left_len, right_len) = (mid - a, b - mid);
138            let balance_threshold = length / 8;
139            if left_len < right_len {
140                was_balanced = left_len >= balance_threshold;
141                self.pdqsort(a, mid, limit);
142                a = mid + 1;
143            } else {
144                was_balanced = right_len >= balance_threshold;
145                self.pdqsort(mid + 1, b, limit);
146                b = mid;
147            }
148        }
149    }
150
151    // Indices stay signed here: `j` can step to `a` - 1 when nothing is below the pivot.
152    fn partition(&mut self, a: usize, b: usize, pivot: usize) -> (usize, bool) {
153        self.swap(a, pivot);
154        let (mut i, mut j) = (a as isize + 1, b as isize - 1);
155        let at = |k: isize| k as usize;
156        while i <= j && self.less(at(i), a) {
157            i += 1;
158        }
159        while i <= j && !self.less(at(j), a) {
160            j -= 1;
161        }
162        if i > j {
163            self.swap(at(j), a);
164            return (at(j), true);
165        }
166        self.swap(at(i), at(j));
167        i += 1;
168        j -= 1;
169        loop {
170            while i <= j && self.less(at(i), a) {
171                i += 1;
172            }
173            while i <= j && !self.less(at(j), a) {
174                j -= 1;
175            }
176            if i > j {
177                break;
178            }
179            self.swap(at(i), at(j));
180            i += 1;
181            j -= 1;
182        }
183        self.swap(at(j), a);
184        (at(j), false)
185    }
186
187    fn partition_equal(&mut self, a: usize, b: usize, pivot: usize) -> usize {
188        self.swap(a, pivot);
189        let (mut i, mut j) = (a as isize + 1, b as isize - 1);
190        let at = |k: isize| k as usize;
191        loop {
192            while i <= j && !self.less(a, at(i)) {
193                i += 1;
194            }
195            while i <= j && self.less(a, at(j)) {
196                j -= 1;
197            }
198            if i > j {
199                break;
200            }
201            self.swap(at(i), at(j));
202            i += 1;
203            j -= 1;
204        }
205        at(i)
206    }
207
208    fn partial_insertion_sort(&mut self, a: usize, b: usize) -> bool {
209        const MAX_STEPS: usize = 5;
210        const SHORTEST_SHIFTING: usize = 50;
211        let mut i = a + 1;
212        for _ in 0..MAX_STEPS {
213            while i < b && !self.less(i, i - 1) {
214                i += 1;
215            }
216            if i == b {
217                return true;
218            }
219            if b - a < SHORTEST_SHIFTING {
220                return false;
221            }
222            self.swap(i, i - 1);
223            if i - a >= 2 {
224                let mut j = i - 1;
225                while j >= 1 {
226                    if !self.less(j, j - 1) {
227                        break;
228                    }
229                    self.swap(j, j - 1);
230                    j -= 1;
231                }
232            }
233            if b - i >= 2 {
234                for j in i + 1..b {
235                    if !self.less(j, j - 1) {
236                        break;
237                    }
238                    self.swap(j, j - 1);
239                }
240            }
241        }
242        false
243    }
244
245    fn break_patterns(&mut self, a: usize, b: usize) {
246        let length = b - a;
247        if length >= 8 {
248            let mut random = length as u64;
249            let modulus = 1usize << bit_len(length);
250            for idx in a + (length / 4) * 2 - 1..=a + (length / 4) * 2 + 1 {
251                random ^= random << 13;
252                random ^= random >> 7;
253                random ^= random << 17;
254                let mut other = (random as usize) & (modulus - 1);
255                if other >= length {
256                    other -= length;
257                }
258                self.swap(idx, a + other);
259            }
260        }
261    }
262
263    fn choose_pivot(&mut self, a: usize, b: usize) -> (usize, Hint) {
264        const SHORTEST_NINTHER: usize = 50;
265        const MAX_SWAPS: usize = 4 * 3;
266        let l = b - a;
267        let mut swaps = 0;
268        let mut i = a + l / 4;
269        let mut j = a + l / 4 * 2;
270        let mut k = a + l / 4 * 3;
271        if l >= 8 {
272            if l >= SHORTEST_NINTHER {
273                i = self.median(i - 1, i, i + 1, &mut swaps);
274                j = self.median(j - 1, j, j + 1, &mut swaps);
275                k = self.median(k - 1, k, k + 1, &mut swaps);
276            }
277            j = self.median(i, j, k, &mut swaps);
278        }
279        match swaps {
280            0 => (j, Hint::Increasing),
281            MAX_SWAPS => (j, Hint::Decreasing),
282            _ => (j, Hint::Unknown),
283        }
284    }
285
286    fn order2(&mut self, a: usize, b: usize, swaps: &mut usize) -> (usize, usize) {
287        if self.less(b, a) {
288            *swaps += 1;
289            return (b, a);
290        }
291        (a, b)
292    }
293
294    fn median(&mut self, a: usize, b: usize, c: usize, swaps: &mut usize) -> usize {
295        let (a, b) = self.order2(a, b, swaps);
296        let (b, _) = self.order2(b, c, swaps);
297        let (_, b) = self.order2(a, b, swaps);
298        b
299    }
300
301    fn reverse_range(&mut self, a: usize, b: usize) {
302        let (mut i, mut j) = (a, b - 1);
303        while i < j {
304            self.swap(i, j);
305            i += 1;
306            j -= 1;
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    /// Orders produced by Go's `sort.Sort` (and identically `slices.SortFunc`), generated by
314    /// promql-compat `cmd/narthex-golden-gosort`; line format: `kind keys | ids`.
315    #[test]
316    fn matches_go_sort_on_comparators_that_are_not_total_orders() {
317        let text = include_str!("go_sort_cases.txt");
318        let mut cases = 0;
319        for line in text.lines() {
320            let (head, expected) = line.split_once(" | ").unwrap();
321            let (kind, keys) = head.split_once(' ').unwrap();
322            let kind: u8 = kind.parse().unwrap();
323            let parse = |list: &str| -> Vec<usize> {
324                list.split(',')
325                    .filter(|item| !item.is_empty())
326                    .map(|item| item.trim().parse().unwrap())
327                    .collect()
328            };
329            let mut items: Vec<(usize, usize)> = parse(keys).into_iter().zip(0..).collect();
330            super::sort_by(&mut items, |&(a, a_id), &(b, b_id)| match kind {
331                0 => a < b,
332                1 => a == 0 || a < b,
333                2 => a % 3 < b % 3,
334                _ => (a_id * 31 + b_id * 17) % 5 < 2,
335            });
336            let actual: Vec<usize> = items.iter().map(|&(_, id)| id).collect();
337            assert_eq!(actual, parse(expected), "{line}");
338            cases += 1;
339        }
340        assert!(cases >= 200);
341    }
342}