icydb-core 0.222.4

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Module: executor::order
//! Responsibility: shared structural ordering helpers for executor row paths.
//! Does not own: planner order semantics or cursor wire validation.
//! Boundary: consumes planner-resolved order contracts and applies canonical ordering over slot-readable rows.

use crate::{
    db::{
        cursor::{CursorBoundary, CursorBoundarySlot, apply_order_direction},
        data::{CanonicalSlotReader, DataRow},
        executor::{
            budget::{charge_current_execution_budget, charge_sort_work, runtime_value_work},
            measure_execution_stats_phase,
            projection::eval_compiled_expr_with_value_reader,
            record_ordering,
            terminal::RowLayout,
        },
        numeric::canonical_value_compare,
        query::plan::{OrderDirection, ResolvedOrder, ResolvedOrderValueSource},
    },
    error::InternalError,
    value::Value,
};
use icydb_diagnostic_code::DiagnosticExecutionBudgetResource;
use std::{array, borrow::Cow, cmp::Ordering};

const INLINE_ORDER_VALUE_CAPACITY: usize = 2;
const BOUNDED_ORDER_INITIAL_CAPACITY: usize = 64;

///
/// OrderReadableRow
///
/// Structural executor row contract used by shared ordering logic.
/// Implementors expose slot-indexed values without re-entering typed entity
/// comparators in sort and cursor-boundary hot loops.
///

pub(in crate::db::executor) trait OrderReadableRow {
    /// Borrow one slot value directly when the row owns stable decoded slots.
    ///
    /// This keeps direct-slot ordering from constructing `Cow` wrappers in
    /// comparator hot loops.
    fn read_order_slot_ref(&self, slot: usize) -> Option<&Value>;

    /// Read one slot value for structural ordering and predicate evaluation.
    /// Structural row paths may return borrowed values so shared order/cursor
    /// helpers do not clone already-decoded slots in comparator hot loops.
    fn read_order_slot_cow(&self, slot: usize) -> Option<Cow<'_, Value>>;

    /// Return whether direct field-slot reads are stable borrowed row views.
    ///
    /// Row types that synthesize values on demand must keep the default so
    /// ordering caches their owned values once instead of rebuilding them in
    /// every comparator call.
    fn order_slots_are_borrowed(&self) -> bool {
        false
    }

    /// Estimate the complete owned backing kept alive when this row crosses
    /// the blocking-order boundary. Implementors with indirect allocations
    /// must override the inline-size default.
    fn retained_order_backing_bytes(&self) -> u64 {
        u64::try_from(std::mem::size_of_val(self)).unwrap_or(u64::MAX)
    }

    /// Read one slot value as an owned payload when a caller still needs to
    /// leave the borrowed structural-ordering boundary.
    fn read_order_slot(&self, slot: usize) -> Option<Value> {
        self.read_order_slot_cow(slot).map(Cow::into_owned)
    }
}

// Cache a small ORDER BY tuple inline so common single-field and two-field
// sorts do not heap-allocate one key vector per retained row.
enum CachedOrderValues {
    Inline {
        len: usize,
        values: [Option<Value>; INLINE_ORDER_VALUE_CAPACITY],
    },
    Heap(Vec<Option<Value>>),
}

impl CachedOrderValues {
    fn with_capacity(field_count: usize) -> Self {
        if field_count <= INLINE_ORDER_VALUE_CAPACITY {
            Self::Inline {
                len: 0,
                values: array::from_fn(|_| None),
            }
        } else {
            Self::Heap(Vec::with_capacity(field_count))
        }
    }

    fn push(&mut self, value: Option<Value>) {
        // SQL NULL produced by an expression is represented as `Value::Null`,
        // while a nullable stored slot is absent. Ordering and cursor
        // boundaries must use one canonical missing-slot representation.
        let value = match value {
            Some(Value::Null) | None => None,
            value => value,
        };
        match self {
            Self::Inline { len, values } => {
                debug_assert!(
                    *len < INLINE_ORDER_VALUE_CAPACITY,
                    "inline order-value buffer overflowed declared capacity",
                );
                values[*len] = value;
                *len += 1;
            }
            Self::Heap(values) => values.push(value),
        }
    }

    fn into_values(self) -> impl Iterator<Item = Option<Value>> {
        let values = match self {
            Self::Inline { len, values } => values.into_iter().take(len).collect(),
            Self::Heap(values) => values,
        };

        values.into_iter()
    }

    fn estimated_backing_bytes(&self) -> u64 {
        let values: &[Option<Value>] = match self {
            Self::Inline { len, values } => &values[..*len],
            Self::Heap(values) => values.as_slice(),
        };

        values.iter().flatten().fold(0_u64, |total, value| {
            total.saturating_add(runtime_value_work(value).0)
        })
    }
}

/// Apply canonical in-memory ordering with an optional bounded top-k window.
pub(in crate::db::executor) fn apply_structural_order_window<R>(
    rows: &mut Vec<R>,
    resolved_order: &ResolvedOrder,
    keep_count: Option<usize>,
) -> Result<(), InternalError>
where
    R: OrderReadableRow,
{
    if let Some(keep_count) = keep_count
        && keep_count == 0
    {
        rows.clear();
        return Ok(());
    }

    if rows.len() <= 1 {
        return Ok(());
    }
    charge_sort_work::<R>(rows.len())?;
    let rows_sorted = rows.len();
    let ((), ordering_micros) = measure_execution_stats_phase(|| {
        apply_structural_order_window_inner(rows, resolved_order, keep_count);
    });
    record_ordering(rows_sorted, ordering_micros);

    Ok(())
}

fn apply_structural_order_window_inner<R>(
    rows: &mut Vec<R>,
    resolved_order: &ResolvedOrder,
    keep_count: Option<usize>,
) where
    R: OrderReadableRow,
{
    // Phase 1: pure direct-slot orders over retained executor rows can compare
    // borrowed values directly. This avoids materializing owned order keys for
    // the common `ORDER BY field[, id]` path while preserving the existing
    // cached fallback for expression orders and rows that synthesize values.
    if can_use_borrowed_direct_order_path(rows.as_slice(), resolved_order) {
        apply_borrowed_direct_order_window(rows, resolved_order, keep_count);
        return;
    }

    // Phase 2: cache resolved order values once per row so bounded selection
    // and final sort do not re-read sparse slots or re-run expression-order
    // derivation inside comparator hot loops.
    let source_rows = std::mem::take(rows);
    let mut cached_rows = Vec::with_capacity(source_rows.len());
    for row in source_rows {
        let cached_values = cache_order_values_from_row(&row, resolved_order);

        cached_rows.push((row, cached_values));
    }

    // Phase 3: retain only the bounded canonical window when pagination
    // exposes one, using the cached order keys instead of live row reads.
    if let Some(keep_count) = keep_count
        && cached_rows.len() > keep_count
    {
        cached_rows.select_nth_unstable_by(keep_count - 1, |left, right| {
            compare_cached_orderable_rows(&left.1, &right.1, resolved_order)
        });
        cached_rows.truncate(keep_count);
    }

    // Phase 4: sort the retained rows into final canonical order using the
    // precomputed key values.
    cached_rows
        .sort_by(|left, right| compare_cached_orderable_rows(&left.1, &right.1, resolved_order));
    rows.extend(cached_rows.into_iter().map(|(row, _)| row));
}

///
/// PendingOrderRows
///
/// Rows retained by a structural scan before canonical post-access ordering.
/// Expression-order rows remain inseparably paired with their evaluated
/// values and originating order contract until that phase consumes them.
///

pub(in crate::db::executor) struct PendingOrderRows<R> {
    storage: PendingOrderRowStorage<R>,
}

impl<R> PendingOrderRows<R> {
    /// Wrap rows that carry no scan-evaluated expression-order values.
    #[must_use]
    pub(in crate::db::executor) const fn plain(rows: Vec<R>) -> Self {
        Self {
            storage: PendingOrderRowStorage::Plain(rows),
        }
    }

    /// Apply canonical ordering, consuming any scan-evaluated order values.
    ///
    /// # Errors
    ///
    /// Returns a query-executor invariant error when cached values were
    /// produced under a different resolved order or bounded keep count.
    pub(in crate::db::executor) fn apply_order(
        self,
        resolved_order: &ResolvedOrder,
        keep_count: Option<usize>,
    ) -> Result<Vec<R>, InternalError>
    where
        R: OrderReadableRow,
    {
        match self.storage {
            PendingOrderRowStorage::Plain(mut rows) => {
                apply_structural_order_window(&mut rows, resolved_order, keep_count)?;
                Ok(rows)
            }
            PendingOrderRowStorage::Cached {
                resolved_order: cached_order,
                mut rows,
                keep_count: cached_keep_count,
            } => {
                if &cached_order != resolved_order
                    || keep_count != Some(cached_keep_count)
                    || rows.len() > cached_keep_count
                {
                    return Err(InternalError::query_executor_invariant());
                }

                let rows_sorted = rows.len();
                if rows_sorted > 1 {
                    charge_sort_work::<R>(rows_sorted)?;
                    let ((), ordering_micros) = measure_execution_stats_phase(|| {
                        rows.sort_by(|left, right| {
                            compare_cached_orderable_rows(&left.1, &right.1, resolved_order)
                        });
                    });
                    record_ordering(rows_sorted, ordering_micros);
                }

                Ok(rows.into_iter().map(|(row, _)| row).collect())
            }
        }
    }

    /// Borrow plain rows when no scan-evaluated order values are attached.
    #[must_use]
    pub(in crate::db::executor) const fn plain_rows(&self) -> Option<&[R]> {
        match &self.storage {
            PendingOrderRowStorage::Plain(rows) => Some(rows.as_slice()),
            PendingOrderRowStorage::Cached { .. } => None,
        }
    }

    /// Return the number of retained rows independent of storage strategy.
    #[must_use]
    pub(in crate::db::executor) const fn retained_count(&self) -> usize {
        match &self.storage {
            PendingOrderRowStorage::Plain(rows) => rows.len(),
            PendingOrderRowStorage::Cached { rows, .. } => rows.len(),
        }
    }

    /// Estimate complete backing bytes retained by the pending row set.
    #[cfg(feature = "diagnostics")]
    #[must_use]
    pub(in crate::db::executor) fn retained_backing_bytes(&self) -> u64
    where
        R: OrderReadableRow,
    {
        match &self.storage {
            PendingOrderRowStorage::Plain(rows) => rows.iter().fold(0_u64, |total, row| {
                total.saturating_add(row.retained_order_backing_bytes())
            }),
            PendingOrderRowStorage::Cached { rows, .. } => {
                rows.iter().fold(0_u64, |total, (row, values)| {
                    total
                        .saturating_add(row.retained_order_backing_bytes())
                        .saturating_add(values.estimated_backing_bytes())
                })
            }
        }
    }

    /// Consume rows that must not carry pending expression-order values.
    ///
    /// # Errors
    ///
    /// Returns a query-executor invariant error when canonical ordering has
    /// not yet consumed cached expression-order values.
    pub(in crate::db::executor) fn into_plain_rows(self) -> Result<Vec<R>, InternalError> {
        match self.storage {
            PendingOrderRowStorage::Plain(rows) => Ok(rows),
            PendingOrderRowStorage::Cached { .. } => Err(InternalError::query_executor_invariant()),
        }
    }
}

/// Internal storage for rows awaiting canonical structural ordering.
enum PendingOrderRowStorage<R> {
    /// Rows without scan-evaluated expression-order values.
    Plain(Vec<R>),
    /// Bounded rows paired with values evaluated under one exact contract.
    Cached {
        resolved_order: ResolvedOrder,
        rows: Vec<(R, CachedOrderValues)>,
        keep_count: usize,
    },
}

///
/// BoundedOrderWindow
///
/// BoundedOrderWindow retains the best `keep_count` rows while a scan is still
/// running. Direct-field orders keep borrowed comparisons; expression-backed
/// orders cache each candidate's complete resolved ordering tuple once.
/// It captures the resolved order used to choose the strategy so later pushes
/// cannot supply a different comparison contract.
/// It deliberately does not final-sort rows; the canonical post-access
/// order/window phase remains the final ordering authority.
///

pub(in crate::db::executor) struct BoundedOrderWindow<'a, R> {
    resolved_order: &'a ResolvedOrder,
    candidates: BoundedOrderCandidates<R>,
}

///
/// DataRowOrderWindow
///
/// DataRowOrderWindow performs incompatible-order selection while raw rows
/// are scanned. Bounded queries retain only the winning output rows plus their
/// compact canonical order tuples; unbounded queries retain the complete set
/// required by full-sort semantics.
///

pub(in crate::db::executor) struct DataRowOrderWindow<'a> {
    row_layout: RowLayout,
    resolved_order: &'a ResolvedOrder,
    candidates: DataRowOrderCandidates,
}

impl<'a> DataRowOrderWindow<'a> {
    /// Build one raw-row ordering window from the semantic page bound.
    #[must_use]
    pub(in crate::db::executor) fn new(
        row_layout: RowLayout,
        resolved_order: &'a ResolvedOrder,
        keep_count: Option<usize>,
    ) -> Self {
        let candidates = keep_count.map_or_else(
            || DataRowOrderCandidates::Complete {
                rows: Vec::new(),
                retained_backing_bytes: 0,
            },
            |keep_count| DataRowOrderCandidates::Bounded(BoundedCachedOrderWindow::new(keep_count)),
        );

        Self {
            row_layout,
            resolved_order,
            candidates,
        }
    }

    /// Evaluate and retain one candidate under the captured order contract.
    pub(in crate::db::executor) fn push(
        &mut self,
        candidate: DataRow,
    ) -> Result<(), InternalError> {
        let cached_values =
            cache_order_values_from_data_row(&candidate, &self.row_layout, self.resolved_order)?;
        let retained_count = self.retained_count();
        let comparisons = match &self.candidates {
            DataRowOrderCandidates::Bounded(window) if retained_count != 0 => {
                if retained_count < window.keep_count {
                    1
                } else {
                    retained_count.saturating_add(1)
                }
            }
            DataRowOrderCandidates::Bounded(_) | DataRowOrderCandidates::Complete { .. } => 0,
        };
        let retained_backing_bytes = data_row_retained_backing_bytes(&candidate)
            .saturating_add(cached_values.estimated_backing_bytes());
        charge_order_candidate_work(comparisons, retained_backing_bytes)?;

        match &mut self.candidates {
            DataRowOrderCandidates::Bounded(window) => {
                window.push_cached(
                    candidate,
                    cached_values,
                    retained_backing_bytes,
                    self.resolved_order,
                );
            }
            DataRowOrderCandidates::Complete {
                rows,
                retained_backing_bytes: total,
            } => {
                rows.push((candidate, cached_values));
                *total = total.saturating_add(retained_backing_bytes);
            }
        }

        Ok(())
    }

    /// Return the current blocking-state row count.
    #[must_use]
    pub(in crate::db::executor) const fn retained_count(&self) -> usize {
        match &self.candidates {
            DataRowOrderCandidates::Bounded(window) => window.rows.len(),
            DataRowOrderCandidates::Complete { rows, .. } => rows.len(),
        }
    }

    /// Return the largest complete backing total retained while selecting.
    #[cfg(feature = "diagnostics")]
    #[must_use]
    pub(in crate::db::executor) const fn peak_retained_backing_bytes(&self) -> u64 {
        match &self.candidates {
            DataRowOrderCandidates::Bounded(window) => window.peak_retained_backing_bytes,
            DataRowOrderCandidates::Complete {
                retained_backing_bytes,
                ..
            } => *retained_backing_bytes,
        }
    }

    /// Consume the selected candidates in final canonical order.
    pub(in crate::db::executor) fn into_sorted_rows(self) -> Result<Vec<DataRow>, InternalError> {
        let mut rows = match self.candidates {
            DataRowOrderCandidates::Bounded(window) => window.into_rows_with_cached_values(),
            DataRowOrderCandidates::Complete { rows, .. } => rows,
        };
        let rows_sorted = rows.len();
        if rows_sorted > 1 {
            charge_sort_work::<DataRow>(rows_sorted)?;
            let ((), ordering_micros) = measure_execution_stats_phase(|| {
                rows.sort_by(|left, right| {
                    compare_cached_orderable_rows(&left.1, &right.1, self.resolved_order)
                });
            });
            record_ordering(rows_sorted, ordering_micros);
        }

        Ok(rows.into_iter().map(|(row, _)| row).collect())
    }
}

enum DataRowOrderCandidates {
    Bounded(BoundedCachedOrderWindow<DataRow>),
    Complete {
        rows: Vec<(DataRow, CachedOrderValues)>,
        retained_backing_bytes: u64,
    },
}

impl<'a, R> BoundedOrderWindow<'a, R>
where
    R: OrderReadableRow,
{
    /// Build one bounded accumulator for the planner-resolved order contract.
    #[must_use]
    pub(in crate::db::executor) fn new(
        keep_count: usize,
        resolved_order: &'a ResolvedOrder,
    ) -> Self {
        let candidates = if resolved_order_uses_only_direct_fields(resolved_order) {
            BoundedOrderCandidates::Direct(BoundedDirectOrderWindow::new(keep_count))
        } else {
            BoundedOrderCandidates::Cached(BoundedCachedOrderWindow::new(keep_count))
        };

        Self {
            resolved_order,
            candidates,
        }
    }

    /// Retain one candidate if it belongs in the bounded resolved-order window.
    pub(in crate::db::executor) fn push(&mut self, candidate: R) -> Result<(), InternalError> {
        let retained_count = match &self.candidates {
            BoundedOrderCandidates::Direct(window) => window.rows.len(),
            BoundedOrderCandidates::Cached(window) => window.rows.len(),
        };
        let comparisons = if retained_count == 0 {
            0
        } else if retained_count < self.candidates.keep_count() {
            1
        } else {
            retained_count.saturating_add(1)
        };
        match &mut self.candidates {
            BoundedOrderCandidates::Direct(window) => {
                charge_order_candidate_work(comparisons, candidate.retained_order_backing_bytes())?;
                window.push(candidate, self.resolved_order);
            }
            BoundedOrderCandidates::Cached(window) => {
                let cached_values = cache_order_values_from_row(&candidate, self.resolved_order);
                let retained_backing_bytes = candidate
                    .retained_order_backing_bytes()
                    .saturating_add(cached_values.estimated_backing_bytes());
                charge_order_candidate_work(comparisons, retained_backing_bytes)?;
                window.push_cached(
                    candidate,
                    cached_values,
                    retained_backing_bytes,
                    self.resolved_order,
                );
            }
        }

        Ok(())
    }

    /// Return the largest complete backing total retained while selecting.
    #[cfg(feature = "diagnostics")]
    #[must_use]
    pub(in crate::db::executor) const fn peak_retained_backing_bytes(&self) -> u64 {
        match &self.candidates {
            BoundedOrderCandidates::Direct(window) => window.peak_retained_backing_bytes,
            BoundedOrderCandidates::Cached(window) => window.peak_retained_backing_bytes,
        }
    }

    /// Consume retained rows while preserving expression-order values for
    /// canonical post-access ordering.
    #[must_use]
    pub(in crate::db::executor) fn into_pending_rows(self) -> PendingOrderRows<R> {
        match self.candidates {
            BoundedOrderCandidates::Direct(window) => PendingOrderRows::plain(window.into_rows()),
            BoundedOrderCandidates::Cached(window) => PendingOrderRows {
                storage: PendingOrderRowStorage::Cached {
                    resolved_order: self.resolved_order.clone(),
                    keep_count: window.keep_count,
                    rows: window.into_rows_with_cached_values(),
                },
            },
        }
    }
}

///
/// BoundedOrderCandidates
///
/// Strategy-owned candidates selected once from the captured resolved order.
///

enum BoundedOrderCandidates<R> {
    Direct(BoundedDirectOrderWindow<R>),
    Cached(BoundedCachedOrderWindow<R>),
}

impl<R> BoundedOrderCandidates<R> {
    const fn keep_count(&self) -> usize {
        match self {
            Self::Direct(window) => window.keep_count,
            Self::Cached(window) => window.keep_count,
        }
    }
}

///
/// BoundedDirectOrderWindow
///
/// BoundedDirectOrderWindow retains the best `keep_count` rows under one
/// direct-slot order while a scan is still running.
/// It deliberately does not final-sort rows; the canonical post-access
/// order/window phase remains the final ordering authority.
///

struct BoundedDirectOrderWindow<R> {
    rows: Vec<R>,
    worst_index: Option<usize>,
    keep_count: usize,
    retained_backing_bytes: u64,
    peak_retained_backing_bytes: u64,
}

impl<R> BoundedDirectOrderWindow<R>
where
    R: OrderReadableRow,
{
    /// Build one bounded direct-order accumulator.
    #[must_use]
    fn new(keep_count: usize) -> Self {
        Self {
            rows: Vec::with_capacity(keep_count.min(BOUNDED_ORDER_INITIAL_CAPACITY)),
            worst_index: None,
            keep_count,
            retained_backing_bytes: 0,
            peak_retained_backing_bytes: 0,
        }
    }

    /// Retain one candidate if it belongs in the bounded order window.
    fn push(&mut self, candidate: R, resolved_order: &ResolvedOrder) {
        if self.keep_count == 0 {
            return;
        }
        let candidate_backing_bytes = candidate.retained_order_backing_bytes();
        if self.rows.len() < self.keep_count {
            self.rows.push(candidate);
            self.retained_backing_bytes = self
                .retained_backing_bytes
                .saturating_add(candidate_backing_bytes);
            self.peak_retained_backing_bytes = self
                .peak_retained_backing_bytes
                .max(self.retained_backing_bytes);
            self.update_worst_after_append(resolved_order);
            return;
        }

        let worst_index = self
            .worst_index
            .unwrap_or_else(|| worst_direct_order_row_index(self.rows.as_slice(), resolved_order));
        if compare_borrowed_direct_orderable_rows(
            &candidate,
            &self.rows[worst_index],
            resolved_order,
        )
        .is_lt()
        {
            self.retained_backing_bytes = self
                .retained_backing_bytes
                .saturating_sub(self.rows[worst_index].retained_order_backing_bytes())
                .saturating_add(candidate_backing_bytes);
            self.peak_retained_backing_bytes = self
                .peak_retained_backing_bytes
                .max(self.retained_backing_bytes);
            self.rows[worst_index] = candidate;
            self.worst_index = Some(worst_direct_order_row_index(
                self.rows.as_slice(),
                resolved_order,
            ));
        }
    }

    /// Consume the retained, not-yet-final-sorted rows.
    #[must_use]
    fn into_rows(self) -> Vec<R> {
        self.rows
    }

    fn update_worst_after_append(&mut self, resolved_order: &ResolvedOrder) {
        let appended_index = self.rows.len().saturating_sub(1);
        let Some(worst_index) = self.worst_index else {
            self.worst_index = Some(appended_index);
            return;
        };
        if compare_borrowed_direct_orderable_rows(
            &self.rows[appended_index],
            &self.rows[worst_index],
            resolved_order,
        )
        .is_gt()
        {
            self.worst_index = Some(appended_index);
        }
    }
}

///
/// BoundedCachedOrderWindow
///
/// Expression-backed candidates paired with their complete resolved order
/// tuples so comparisons never re-evaluate an expression for an already-seen
/// row.
///

struct BoundedCachedOrderWindow<R> {
    rows: Vec<(R, CachedOrderValues)>,
    row_backing_bytes: Vec<u64>,
    worst_index: Option<usize>,
    keep_count: usize,
    retained_backing_bytes: u64,
    peak_retained_backing_bytes: u64,
}

impl<R> BoundedCachedOrderWindow<R> {
    fn new(keep_count: usize) -> Self {
        Self {
            rows: Vec::with_capacity(keep_count.min(BOUNDED_ORDER_INITIAL_CAPACITY)),
            row_backing_bytes: Vec::with_capacity(keep_count.min(BOUNDED_ORDER_INITIAL_CAPACITY)),
            worst_index: None,
            keep_count,
            retained_backing_bytes: 0,
            peak_retained_backing_bytes: 0,
        }
    }

    fn push_cached(
        &mut self,
        candidate: R,
        cached_values: CachedOrderValues,
        retained_backing_bytes: u64,
        resolved_order: &ResolvedOrder,
    ) {
        if self.rows.len() < self.keep_count {
            self.rows.push((candidate, cached_values));
            self.row_backing_bytes.push(retained_backing_bytes);
            self.retained_backing_bytes = self
                .retained_backing_bytes
                .saturating_add(retained_backing_bytes);
            self.peak_retained_backing_bytes = self
                .peak_retained_backing_bytes
                .max(self.retained_backing_bytes);
            self.update_worst_after_append(resolved_order);
            return;
        }

        let worst_index = self
            .worst_index
            .unwrap_or_else(|| worst_cached_order_row_index(self.rows.as_slice(), resolved_order));
        if compare_cached_orderable_rows(&cached_values, &self.rows[worst_index].1, resolved_order)
            .is_lt()
        {
            self.rows[worst_index] = (candidate, cached_values);
            self.retained_backing_bytes = self
                .retained_backing_bytes
                .saturating_sub(self.row_backing_bytes[worst_index])
                .saturating_add(retained_backing_bytes);
            self.peak_retained_backing_bytes = self
                .peak_retained_backing_bytes
                .max(self.retained_backing_bytes);
            self.row_backing_bytes[worst_index] = retained_backing_bytes;
            self.worst_index = Some(worst_cached_order_row_index(
                self.rows.as_slice(),
                resolved_order,
            ));
        }
    }

    fn into_rows_with_cached_values(self) -> Vec<(R, CachedOrderValues)> {
        self.rows
    }

    fn update_worst_after_append(&mut self, resolved_order: &ResolvedOrder) {
        let appended_index = self.rows.len().saturating_sub(1);
        let Some(worst_index) = self.worst_index else {
            self.worst_index = Some(appended_index);
            return;
        };
        if compare_cached_orderable_rows(
            &self.rows[appended_index].1,
            &self.rows[worst_index].1,
            resolved_order,
        )
        .is_gt()
        {
            self.worst_index = Some(appended_index);
        }
    }
}

fn charge_order_candidate_work(
    comparisons: usize,
    retained_backing_bytes: u64,
) -> Result<(), InternalError> {
    charge_current_execution_budget(DiagnosticExecutionBudgetResource::SortEntries, 1)?;
    charge_current_execution_budget(
        DiagnosticExecutionBudgetResource::SortComparisons,
        u64::try_from(comparisons).unwrap_or(u64::MAX),
    )?;
    charge_current_execution_budget(
        DiagnosticExecutionBudgetResource::SortTemporaryBytes,
        retained_backing_bytes,
    )
}

fn data_row_retained_backing_bytes(row: &DataRow) -> u64 {
    u64::try_from(std::mem::size_of::<DataRow>())
        .unwrap_or(u64::MAX)
        .saturating_add(u64::try_from(row.1.len()).unwrap_or(u64::MAX))
}

/// Compare one structural row against one cursor boundary under the canonical order contract.
pub(in crate::db::executor) fn compare_orderable_row_with_boundary<R>(
    row: &R,
    resolved_order: &ResolvedOrder,
    boundary: &CursorBoundary,
) -> Result<Ordering, InternalError>
where
    R: OrderReadableRow,
{
    compare_structural_order_slots_fallible(resolved_order, |slot_index, source, direction| {
        let row_slot = order_value_from_row(row, source);
        let boundary_slot = boundary
            .slots
            .get(slot_index)
            .ok_or_else(InternalError::query_executor_invariant)?;

        Ok(apply_order_direction(
            compare_order_value_with_boundary(row_slot, boundary_slot),
            direction,
        ))
    })
}

fn compare_structural_order_slots_fallible(
    resolved_order: &ResolvedOrder,
    mut compare_slot: impl FnMut(
        usize,
        &ResolvedOrderValueSource,
        OrderDirection,
    ) -> Result<Ordering, InternalError>,
) -> Result<Ordering, InternalError> {
    for (slot_index, field) in resolved_order.fields().iter().enumerate() {
        let ordering = compare_slot(slot_index, field.source(), field.direction())?;
        if ordering != Ordering::Equal {
            return Ok(ordering);
        }
    }

    Ok(Ordering::Equal)
}

// Compare two cached structural ordering tuples according to the resolved
// canonical order without re-reading row slots inside the comparator.
fn compare_cached_orderable_rows(
    left: &CachedOrderValues,
    right: &CachedOrderValues,
    resolved_order: &ResolvedOrder,
) -> Ordering {
    match (left, right) {
        (
            CachedOrderValues::Inline {
                len: left_len,
                values: left_values,
            },
            CachedOrderValues::Inline {
                len: right_len,
                values: right_values,
            },
        ) => compare_cached_order_value_lists(
            &left_values[..*left_len],
            &right_values[..*right_len],
            resolved_order,
        ),
        (CachedOrderValues::Heap(left_values), CachedOrderValues::Heap(right_values)) => {
            compare_cached_order_value_lists(left_values, right_values, resolved_order)
        }
        (
            CachedOrderValues::Inline {
                len: left_len,
                values: left_values,
            },
            CachedOrderValues::Heap(right_values),
        ) => compare_cached_order_value_lists(
            &left_values[..*left_len],
            right_values,
            resolved_order,
        ),
        (
            CachedOrderValues::Heap(left_values),
            CachedOrderValues::Inline {
                len: right_len,
                values: right_values,
            },
        ) => compare_cached_order_value_lists(
            left_values,
            &right_values[..*right_len],
            resolved_order,
        ),
    }
}

// Return whether one row set can use the borrowed direct-slot comparator path.
fn can_use_borrowed_direct_order_path<R>(rows: &[R], resolved_order: &ResolvedOrder) -> bool
where
    R: OrderReadableRow,
{
    resolved_order_uses_only_direct_fields(resolved_order)
        && rows
            .first()
            .is_some_and(OrderReadableRow::order_slots_are_borrowed)
}

fn resolved_order_uses_only_direct_fields(resolved_order: &ResolvedOrder) -> bool {
    resolved_order
        .fields()
        .iter()
        .all(|field| matches!(field.source(), ResolvedOrderValueSource::DirectField(_)))
}

// Apply direct-slot ordering by borrowing row values during comparisons instead
// of building owned cached order tuples.
fn apply_borrowed_direct_order_window<R>(
    rows: &mut Vec<R>,
    resolved_order: &ResolvedOrder,
    keep_count: Option<usize>,
) where
    R: OrderReadableRow,
{
    if let Some(keep_count) = keep_count
        && rows.len() > keep_count
    {
        rows.select_nth_unstable_by(keep_count - 1, |left, right| {
            compare_borrowed_direct_orderable_rows(left, right, resolved_order)
        });
        rows.truncate(keep_count);
    }

    rows.sort_by(|left, right| compare_borrowed_direct_orderable_rows(left, right, resolved_order));
}

// Compare direct field-slot order rows through borrowed slot values only.
fn compare_borrowed_direct_orderable_rows<R>(
    left: &R,
    right: &R,
    resolved_order: &ResolvedOrder,
) -> Ordering
where
    R: OrderReadableRow,
{
    for field in resolved_order.fields() {
        let ResolvedOrderValueSource::DirectField(slot) = field.source() else {
            return Ordering::Equal;
        };

        let ordering = apply_order_direction(
            compare_cached_order_values(
                left.read_order_slot_ref(*slot),
                right.read_order_slot_ref(*slot),
            ),
            field.direction(),
        );
        if ordering != Ordering::Equal {
            return ordering;
        }
    }

    Ordering::Equal
}

// Find the currently worst retained row under canonical direct-slot ordering.
fn worst_direct_order_row_index<R>(rows: &[R], resolved_order: &ResolvedOrder) -> usize
where
    R: OrderReadableRow,
{
    debug_assert!(
        !rows.is_empty(),
        "bounded order window must have retained rows before resolving worst row",
    );
    let mut worst_index = 0usize;
    for index in 1..rows.len() {
        if compare_borrowed_direct_orderable_rows(&rows[index], &rows[worst_index], resolved_order)
            .is_gt()
        {
            worst_index = index;
        }
    }

    worst_index
}

// Find the currently worst retained cached tuple under the complete resolved
// order, including direction and the planner-appended primary-key tie-breaker.
fn worst_cached_order_row_index<R>(
    rows: &[(R, CachedOrderValues)],
    resolved_order: &ResolvedOrder,
) -> usize {
    debug_assert!(
        !rows.is_empty(),
        "bounded cached order window must have retained rows before resolving worst row",
    );
    let mut worst_index = 0usize;
    for index in 1..rows.len() {
        if compare_cached_orderable_rows(&rows[index].1, &rows[worst_index].1, resolved_order)
            .is_gt()
        {
            worst_index = index;
        }
    }

    worst_index
}

// Cache one row's order values once so sort/select hot loops can compare
// cheap owned key tuples instead of re-deriving them repeatedly.
fn cache_order_values_from_row<R>(row: &R, resolved_order: &ResolvedOrder) -> CachedOrderValues
where
    R: OrderReadableRow,
{
    let fields = resolved_order.fields();
    let mut cached_values = CachedOrderValues::with_capacity(fields.len());

    for field in fields {
        cached_values.push(order_value_from_row(row, field.source()).map(Cow::into_owned));
    }

    cached_values
}

// Cache one raw row's order values once so materialized raw-row sort/select
// can avoid building retained-slot kernel rows only to feed the order cache.
fn cache_order_values_from_data_row(
    row: &DataRow,
    row_layout: &RowLayout,
    resolved_order: &ResolvedOrder,
) -> Result<CachedOrderValues, InternalError> {
    // Phase 1: pure direct-field ORDER BY terms can stay on the sparse
    // contract path and decode only the ordered slots in field order.
    if let Some(required_slots) = resolved_order.direct_field_slots() {
        let values = row_layout.decode_indexed_values_from_data_key(
            &row.1,
            &row.0,
            required_slots.as_slice(),
        )?;
        let mut cached_values = CachedOrderValues::with_capacity(values.len());

        for value in values {
            cached_values.push(value);
        }

        return Ok(cached_values);
    }

    // Phase 2: expression-backed ordering still needs the general structural
    // slot reader so expression evaluation can borrow slots repeatedly.
    let slots = row_layout.open_raw_row_with_contract(&row.1)?;
    let mut cached_values = CachedOrderValues::with_capacity(resolved_order.fields().len());

    for field in resolved_order.fields() {
        let value = match field.source() {
            ResolvedOrderValueSource::DirectField(slot) => {
                Some(slots.required_value_by_contract(*slot)?)
            }
            ResolvedOrderValueSource::Expression(expr) => {
                eval_compiled_expr_with_value_reader(expr, &mut |slot| {
                    slots.required_value_by_contract(slot).ok()
                })
                .ok()
            }
        };

        cached_values.push(value);
    }

    Ok(cached_values)
}

/// Build one canonical continuation boundary from a decoded structural row.
pub(in crate::db::executor) fn cursor_boundary_from_orderable_row<R>(
    row: &R,
    resolved_order: &ResolvedOrder,
) -> CursorBoundary
where
    R: OrderReadableRow,
{
    let slots = resolved_order
        .fields()
        .iter()
        .map(|field| match order_value_from_row(row, field.source()) {
            Some(value) => CursorBoundarySlot::Present(value.into_owned()),
            None => CursorBoundarySlot::Missing,
        })
        .collect();

    CursorBoundary { slots }
}

/// Build one canonical continuation boundary from a persisted data row.
pub(in crate::db::executor) fn cursor_boundary_from_data_row(
    row: &DataRow,
    row_layout: &RowLayout,
    resolved_order: &ResolvedOrder,
) -> Result<CursorBoundary, InternalError> {
    let values = cache_order_values_from_data_row(row, row_layout, resolved_order)?;
    let slots = values
        .into_values()
        .map(|value| match value {
            Some(value) => CursorBoundarySlot::Present(value),
            None => CursorBoundarySlot::Missing,
        })
        .collect();

    Ok(CursorBoundary { slots })
}

// Compare two already-materialized ordering tuples by walking their cached
// value lists directly instead of re-entering indexed slot lookups.
fn compare_cached_order_value_lists(
    left: &[Option<Value>],
    right: &[Option<Value>],
    resolved_order: &ResolvedOrder,
) -> Ordering {
    debug_assert_eq!(
        left.len(),
        resolved_order.fields().len(),
        "cached left order values must align with resolved order fields",
    );
    debug_assert_eq!(
        right.len(),
        resolved_order.fields().len(),
        "cached right order values must align with resolved order fields",
    );

    for ((left_slot, right_slot), field) in left
        .iter()
        .zip(right.iter())
        .zip(resolved_order.fields().iter())
    {
        let ordering = apply_order_direction(
            compare_cached_order_values(left_slot.as_ref(), right_slot.as_ref()),
            field.direction(),
        );
        if ordering != Ordering::Equal {
            return ordering;
        }
    }

    Ordering::Equal
}

// Borrow one slot-reader value through the shared ordering seam.
fn order_value_from_row<'a, R>(
    row: &'a R,
    source: &'a ResolvedOrderValueSource,
) -> Option<Cow<'a, Value>>
where
    R: OrderReadableRow + ?Sized,
{
    let value = match source {
        ResolvedOrderValueSource::DirectField(slot) => row.read_order_slot_cow(*slot),
        ResolvedOrderValueSource::Expression(expr) => {
            eval_compiled_expr_with_value_reader(expr, &mut |slot| row.read_order_slot(slot))
                .ok()
                .map(Cow::Owned)
        }
    };

    value.filter(|value| !matches!(value.as_ref(), Value::Null))
}

// Compare two cached owned ordering values after key precomputation.
fn compare_cached_order_values(left: Option<&Value>, right: Option<&Value>) -> Ordering {
    match (left, right) {
        (None, None) => Ordering::Equal,
        (None, Some(_)) => Ordering::Less,
        (Some(_), None) => Ordering::Greater,
        (Some(left), Some(right)) => canonical_value_compare(left, right),
    }
}

// Compare one row-provided ordering value against one persisted cursor
// boundary slot without rebuilding the row side into an owned boundary slot.
fn compare_order_value_with_boundary(
    value: Option<Cow<'_, Value>>,
    boundary: &CursorBoundarySlot,
) -> Ordering {
    match (value, boundary) {
        (None, CursorBoundarySlot::Missing) => Ordering::Equal,
        (None, CursorBoundarySlot::Present(_)) => Ordering::Less,
        (Some(_), CursorBoundarySlot::Missing) => Ordering::Greater,
        (Some(value), CursorBoundarySlot::Present(boundary_value)) => {
            canonical_value_compare(value.as_ref(), boundary_value)
        }
    }
}