icydb-core 0.94.0

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
//! Module: query::plan::group
//! Responsibility: grouped-plan handoff contract between query planning and executor.
//! Does not own: grouped runtime execution logic.
//! Boundary: explicit grouped query-to-executor transfer surface.

use crate::{
    db::query::{
        builder::AggregateExpr,
        plan::{
            AccessPlannedQuery, AggregateKind, FieldSlot, GroupAggregateSpec,
            GroupDistinctAdmissibility, GroupDistinctPolicyReason, GroupedExecutionConfig,
            GroupedPlanStrategy,
            expr::{
                Expr, ProjectionSpec, ScalarProjectionExpr, compile_scalar_projection_expr,
                expr_references_only_fields, projection_field_expr,
            },
            grouped_distinct_admissibility, grouped_plan_strategy,
            resolve_aggregate_target_field_slot, resolve_global_distinct_field_aggregate,
            validate_grouped_projection_layout,
        },
    },
    error::InternalError,
    model::entity::EntityModel,
};

///
/// PlannedProjectionLayout
///
/// Planner-owned grouped projection position layout transferred to executor.
/// Positions are derived only from `ProjectionSpec` semantic shape and preserve
/// projection declaration order for grouped fields and aggregates.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct PlannedProjectionLayout {
    pub(in crate::db) group_field_positions: Vec<usize>,
    pub(in crate::db) aggregate_positions: Vec<usize>,
}

///
/// GroupedAggregateExecutionSpec
///
/// GroupedAggregateExecutionSpec is the canonical grouped aggregate carrier
/// shared across planner projection analysis and grouped runtime handoff.
/// Semantic identity stays present for projection/HAVING matching, while
/// planner-owned slot resolution and compiled input preparation are attached
/// once under model ownership before execution begins.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct GroupedAggregateExecutionSpec {
    kind: AggregateKind,
    target_slot: Option<FieldSlot>,
    input_expr: Option<Expr>,
    filter_expr: Option<Expr>,
    compiled_input_expr: Option<ScalarProjectionExpr>,
    compiled_filter_expr: Option<ScalarProjectionExpr>,
    distinct: bool,
}

///
/// GroupedProjectionAggregateScan
///
/// Planner-local grouped projection aggregate scan result.
/// This keeps aggregate-bearing expression classification and first-seen
/// grouped aggregate slot introduction under one helper so grouped projection
/// handoff does not walk the same expression tree twice.
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct GroupedProjectionAggregateScan {
    contains_aggregate: bool,
    introduced_aggregate_count: usize,
}

impl GroupedProjectionAggregateScan {
    /// Build one empty grouped aggregate scan result.
    #[must_use]
    const fn none() -> Self {
        Self {
            contains_aggregate: false,
            introduced_aggregate_count: 0,
        }
    }

    /// Build one grouped aggregate scan result for a discovered aggregate leaf.
    #[must_use]
    const fn found_aggregate(introduced_aggregate_count: usize) -> Self {
        Self {
            contains_aggregate: true,
            introduced_aggregate_count,
        }
    }

    /// Merge two grouped aggregate scan results while preserving first-seen
    /// introduction counts across one projection expression walk.
    #[must_use]
    const fn combine(self, other: Self) -> Self {
        Self {
            contains_aggregate: self.contains_aggregate || other.contains_aggregate,
            introduced_aggregate_count: self
                .introduced_aggregate_count
                .saturating_add(other.introduced_aggregate_count),
        }
    }

    /// Return whether the scanned expression references at least one grouped aggregate leaf.
    #[must_use]
    const fn contains_aggregate(self) -> bool {
        self.contains_aggregate
    }

    /// Return how many new grouped aggregate slots this expression introduced.
    #[must_use]
    const fn introduced_aggregate_count(self) -> usize {
        self.introduced_aggregate_count
    }
}

impl GroupedAggregateExecutionSpec {
    /// Build one grouped aggregate spec from one semantic aggregate expression.
    #[must_use]
    pub(in crate::db) fn from_aggregate_expr(aggregate_expr: &AggregateExpr) -> Self {
        Self {
            kind: aggregate_expr.kind(),
            target_slot: None,
            input_expr: aggregate_expr.input_expr().cloned(),
            filter_expr: aggregate_expr.filter_expr().cloned(),
            compiled_input_expr: None,
            compiled_filter_expr: None,
            distinct: aggregate_expr.is_distinct(),
        }
    }

    /// Resolve planner-owned grouped aggregate execution attachments for one model.
    pub(in crate::db) fn resolve_for_model(
        &self,
        model: &EntityModel,
    ) -> Result<Self, InternalError> {
        let compiled_input_expr = self
            .input_expr()
            .map(|expr| {
                compile_scalar_projection_expr(model, expr).ok_or_else(|| {
                    InternalError::planner_executor_invariant(format!(
                        "grouped aggregate execution input expression must stay on the scalar seam: kind={:?} input_expr={expr:?}",
                        self.kind(),
                    ))
                })
            })
            .transpose()?;
        let compiled_filter_expr = self
            .filter_expr()
            .map(|expr| {
                compile_scalar_projection_expr(model, expr).ok_or_else(|| {
                    InternalError::planner_executor_invariant(format!(
                        "grouped aggregate filter expression must stay on the scalar seam: kind={:?} filter_expr={expr:?}",
                        self.kind(),
                    ))
                })
            })
            .transpose()?;
        let target_slot = self
            .target_field()
            .map(|field| {
                resolve_aggregate_target_field_slot(model, field).map_err(|err| {
                    InternalError::planner_executor_invariant(format!(
                        "grouped aggregate execution target slot resolution failed: field='{field}', error={err}",
                    ))
                })
            })
            .transpose()?;

        Ok(Self {
            kind: self.kind(),
            target_slot,
            input_expr: self.input_expr().cloned(),
            filter_expr: self.filter_expr().cloned(),
            compiled_input_expr,
            compiled_filter_expr,
            distinct: self.distinct(),
        })
    }

    /// Return the grouped aggregate kind.
    #[must_use]
    pub(in crate::db) const fn kind(&self) -> AggregateKind {
        self.kind
    }

    /// Borrow the optional grouped aggregate target field label.
    #[must_use]
    pub(in crate::db) const fn target_field(&self) -> Option<&str> {
        match self.input_expr() {
            Some(Expr::Field(field_id)) => Some(field_id.as_str()),
            _ => None,
        }
    }

    /// Borrow the optional planner-resolved grouped aggregate target slot.
    #[must_use]
    pub(in crate::db) const fn target_slot(&self) -> Option<&FieldSlot> {
        self.target_slot.as_ref()
    }

    /// Borrow the canonical grouped aggregate input expression, if any.
    #[must_use]
    pub(in crate::db) const fn input_expr(&self) -> Option<&Expr> {
        self.input_expr.as_ref()
    }

    /// Borrow the canonical grouped aggregate filter expression, if any.
    #[must_use]
    pub(in crate::db) const fn filter_expr(&self) -> Option<&Expr> {
        self.filter_expr.as_ref()
    }

    /// Return whether the grouped aggregate uses DISTINCT semantics.
    #[must_use]
    pub(in crate::db) const fn distinct(&self) -> bool {
        self.distinct
    }

    /// Return whether this grouped aggregate spec matches one planner-owned grouped aggregate.
    #[must_use]
    pub(in crate::db) fn matches_semantic_aggregate(&self, aggregate: &GroupAggregateSpec) -> bool {
        self.kind == aggregate.kind()
            && self.input_expr() == aggregate.semantic_input_expr_owned().as_ref()
            && self.filter_expr() == aggregate.filter_expr()
            && self.distinct == aggregate.distinct()
    }

    /// Borrow the compiled grouped aggregate input expression used by runtime, if any.
    #[must_use]
    pub(in crate::db) const fn compiled_input_expr(&self) -> Option<&ScalarProjectionExpr> {
        self.compiled_input_expr.as_ref()
    }

    /// Borrow the compiled grouped aggregate filter expression used by runtime, if any.
    #[must_use]
    pub(in crate::db) const fn compiled_filter_expr(&self) -> Option<&ScalarProjectionExpr> {
        self.compiled_filter_expr.as_ref()
    }

    /// Return whether one aggregate expression matches this grouped execution spec semantically.
    #[must_use]
    pub(in crate::db) fn matches_aggregate_expr(&self, aggregate_expr: &AggregateExpr) -> bool {
        self.kind == aggregate_expr.kind()
            && self.input_expr() == aggregate_expr.input_expr()
            && self.filter_expr() == aggregate_expr.filter_expr()
            && self.distinct == aggregate_expr.is_distinct()
    }

    /// Build one grouped aggregate execution spec directly for tests that do
    /// not carry a model-owned grouped lowering context.
    #[cfg(test)]
    #[must_use]
    pub(in crate::db) fn from_parts_for_test(
        kind: AggregateKind,
        target_slot: Option<FieldSlot>,
        target_field: Option<&str>,
        distinct: bool,
    ) -> Self {
        Self {
            kind,
            target_slot,
            input_expr: target_field
                .map(|field| Expr::Field(crate::db::query::plan::expr::FieldId::new(field))),
            filter_expr: None,
            compiled_input_expr: None,
            compiled_filter_expr: None,
            distinct,
        }
    }
}

impl PlannedProjectionLayout {
    /// Borrow grouped field positions in projection declaration order.
    #[must_use]
    pub(in crate::db) const fn group_field_positions(&self) -> &[usize] {
        self.group_field_positions.as_slice()
    }

    /// Borrow aggregate positions in projection declaration order.
    #[must_use]
    pub(in crate::db) const fn aggregate_positions(&self) -> &[usize] {
        self.aggregate_positions.as_slice()
    }

    /// Construct one grouped layout invariant for non-monotonic grouped-field positions.
    pub(in crate::db) fn group_field_positions_not_strictly_increasing() -> InternalError {
        InternalError::planner_executor_invariant(
            "grouped projection layout group-field positions must be strictly increasing",
        )
    }

    /// Construct one grouped layout invariant for non-monotonic aggregate positions.
    pub(in crate::db) fn aggregate_positions_not_strictly_increasing() -> InternalError {
        InternalError::planner_executor_invariant(
            "grouped projection layout aggregate positions must be strictly increasing",
        )
    }

    /// Construct one grouped layout invariant for mixed field/aggregate ordering.
    pub(in crate::db) fn group_fields_must_precede_aggregates() -> InternalError {
        InternalError::planner_executor_invariant(
            "grouped projection layout must keep group fields before aggregate terminals",
        )
    }

    /// Construct one grouped layout invariant for runtime projection splits
    /// that reference a layout position outside the projected value buffer.
    pub(in crate::db) fn projected_position_out_of_bounds(
        position_kind: &str,
        position: usize,
        projected_len: usize,
    ) -> InternalError {
        InternalError::query_executor_invariant(format!(
            "grouped projection layout {position_kind} position out of bounds: position={position}, projected_len={projected_len}",
        ))
    }
}

///
/// GroupedExecutorHandoff
///
/// Borrowed grouped planning handoff consumed at the query->executor boundary.
/// This contract keeps grouped execution routing input explicit while grouped
/// runtime entry remains explicit at query->executor boundaries.
///

///
/// GroupedFoldPath
///
/// Planner-carried grouped fold-path contract for executor runtime.
/// This is execution-mechanical only: it tells grouped runtime whether the
/// planner admitted the dedicated grouped `COUNT(*)` fold path or the
/// canonical generic grouped reducer path. Runtime must consume this contract
/// instead of branching on grouped planner strategy directly.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum GroupedFoldPath {
    CountRowsDedicated,
    GenericReducers,
}

impl GroupedFoldPath {
    /// Project one grouped fold path from the planner-owned grouped strategy.
    #[must_use]
    pub(in crate::db) const fn from_plan_strategy(strategy: GroupedPlanStrategy) -> Self {
        if strategy.is_single_count_rows() {
            Self::CountRowsDedicated
        } else {
            Self::GenericReducers
        }
    }

    /// Return whether grouped runtime may use the dedicated grouped `COUNT(*)`
    /// fold/finalize path for this planner-carried fold contract.
    #[must_use]
    pub(in crate::db) const fn uses_count_rows_dedicated_fold(self) -> bool {
        matches!(self, Self::CountRowsDedicated)
    }
}

///
/// GroupedExecutorHandoff
///
/// Borrowed grouped planning handoff consumed at the query->executor boundary.
/// This contract keeps grouped execution routing input explicit while grouped
/// runtime entry remains explicit at query->executor boundaries.
///

#[derive(Clone)]
pub(in crate::db) struct GroupedExecutorHandoff<'a> {
    base: &'a AccessPlannedQuery,
    group_fields: &'a [FieldSlot],
    #[cfg(test)]
    aggregate_specs: Vec<GroupedAggregateExecutionSpec>,
    grouped_aggregate_execution_specs: Vec<GroupedAggregateExecutionSpec>,
    projection_layout: PlannedProjectionLayout,
    projection_is_identity: bool,
    grouped_plan_strategy: GroupedPlanStrategy,
    grouped_fold_path: GroupedFoldPath,
    grouped_distinct_policy_contract: GroupedDistinctPolicyContract,
    having_expr: Option<&'a crate::db::query::plan::expr::Expr>,
    execution: GroupedExecutionConfig,
}

impl<'a> GroupedExecutorHandoff<'a> {
    /// Borrow the grouped query base plan.
    #[must_use]
    pub(in crate::db) const fn base(&self) -> &'a AccessPlannedQuery {
        self.base
    }

    /// Borrow declared grouped key fields.
    #[must_use]
    pub(in crate::db) const fn group_fields(&self) -> &'a [FieldSlot] {
        self.group_fields
    }

    /// Borrow grouped aggregate specs derived from planner projection semantics.
    #[cfg(test)]
    #[must_use]
    pub(in crate::db) const fn aggregate_specs(&self) -> &[GroupedAggregateExecutionSpec] {
        self.aggregate_specs.as_slice()
    }

    /// Borrow grouped aggregate execution specs resolved during static planning.
    #[must_use]
    pub(in crate::db) const fn grouped_aggregate_execution_specs(
        &self,
    ) -> &[GroupedAggregateExecutionSpec] {
        self.grouped_aggregate_execution_specs.as_slice()
    }

    /// Borrow grouped projection position layout derived by planner.
    #[must_use]
    pub(in crate::db) const fn projection_layout(&self) -> &PlannedProjectionLayout {
        &self.projection_layout
    }

    /// Return whether planner already proved the grouped projection is row-identical.
    #[must_use]
    pub(in crate::db) const fn projection_is_identity(&self) -> bool {
        self.projection_is_identity
    }

    /// Borrow grouped execution strategy projected by planner semantics.
    #[must_use]
    pub(in crate::db) const fn grouped_plan_strategy(&self) -> GroupedPlanStrategy {
        self.grouped_plan_strategy
    }

    /// Borrow planner-carried grouped fold-path selection.
    #[must_use]
    pub(in crate::db) const fn grouped_fold_path(&self) -> GroupedFoldPath {
        self.grouped_fold_path
    }

    /// Borrow grouped DISTINCT execution strategy lowered by planner.
    #[must_use]
    pub(in crate::db) const fn distinct_execution_strategy(
        &self,
    ) -> &GroupedDistinctExecutionStrategy {
        self.grouped_distinct_policy_contract.execution_strategy()
    }

    /// Borrow grouped DISTINCT policy violation reason for executor boundaries.
    #[must_use]
    pub(in crate::db) const fn distinct_policy_violation_for_executor(
        &self,
    ) -> Option<GroupDistinctPolicyReason> {
        self.grouped_distinct_policy_contract
            .violation_for_executor()
    }

    /// Borrow grouped HAVING expression when present.
    #[must_use]
    pub(in crate::db) const fn having_expr(
        &self,
    ) -> Option<&'a crate::db::query::plan::expr::Expr> {
        self.having_expr
    }

    /// Borrow grouped execution hard-limit policy selected by planning.
    #[must_use]
    pub(in crate::db) const fn execution(&self) -> GroupedExecutionConfig {
        self.execution
    }
}

/// Build one grouped executor handoff from one grouped logical plan.
pub(in crate::db) fn grouped_executor_handoff(
    plan: &AccessPlannedQuery,
) -> Result<GroupedExecutorHandoff<'_>, InternalError> {
    // Grouped handoff is valid only for plans with grouped execution payload.
    let Some(grouped) = plan.grouped_plan() else {
        return Err(InternalError::planner_executor_invariant(
            "grouped executor handoff requires grouped logical plans",
        ));
    };
    let projection_spec = plan.frozen_projection_spec();
    let (projection_layout, aggregate_specs, projection_is_identity) =
        planned_projection_layout_and_aggregate_specs_from_spec(
            projection_spec,
            grouped.group.group_fields.as_slice(),
            grouped.group.aggregates.as_slice(),
        )?;
    #[cfg(not(test))]
    let _ = &aggregate_specs;
    validate_grouped_projection_layout(&projection_layout)?;
    let grouped_plan_strategy = grouped_plan_strategy(plan).ok_or_else(|| {
        InternalError::planner_executor_invariant(
            "grouped executor handoff must carry grouped strategy for grouped plans",
        )
    })?;
    let grouped_aggregate_execution_specs = plan
        .grouped_aggregate_execution_specs()
        .ok_or_else(|| {
            InternalError::planner_executor_invariant(
                "grouped executor handoff requires frozen grouped aggregate execution specs",
            )
        })?
        .to_vec();
    let grouped_fold_path = GroupedFoldPath::from_plan_strategy(grouped_plan_strategy);
    let grouped_distinct_policy_contract = GroupedDistinctPolicyContract::new(
        match grouped_distinct_admissibility(grouped.scalar.distinct, grouped.having_expr.is_some())
        {
            GroupDistinctAdmissibility::Allowed => None,
            GroupDistinctAdmissibility::Disallowed(reason) => Some(reason),
        },
        plan.grouped_distinct_execution_strategy()
            .ok_or_else(|| {
                InternalError::planner_executor_invariant(
                    "grouped executor handoff requires frozen grouped DISTINCT strategy",
                )
            })?
            .clone(),
    );

    Ok(GroupedExecutorHandoff {
        base: plan,
        group_fields: grouped.group.group_fields.as_slice(),
        #[cfg(test)]
        aggregate_specs,
        grouped_aggregate_execution_specs,
        projection_layout,
        projection_is_identity,
        grouped_plan_strategy,
        grouped_fold_path,
        grouped_distinct_policy_contract,
        having_expr: grouped.having_expr.as_ref(),
        execution: grouped.group.execution,
    })
}

/// Build grouped aggregate execution specs from planner-owned aggregate
/// projection specs and one structural model context.
pub(in crate::db) fn grouped_aggregate_execution_specs(
    model: &EntityModel,
    aggregate_specs: &[GroupedAggregateExecutionSpec],
) -> Result<Vec<GroupedAggregateExecutionSpec>, InternalError> {
    aggregate_specs
        .iter()
        .map(|aggregate_spec| aggregate_spec.resolve_for_model(model))
        .collect()
}

/// Lower grouped aggregate specs directly from canonical grouped
/// projection semantics without requiring a frozen grouped executor handoff.
pub(in crate::db) fn grouped_aggregate_specs_from_projection_spec(
    projection_spec: &ProjectionSpec,
    group_fields: &[FieldSlot],
    aggregates: &[GroupAggregateSpec],
) -> Result<Vec<GroupedAggregateExecutionSpec>, InternalError> {
    let (_, aggregate_specs, _) = planned_projection_layout_and_aggregate_specs_from_spec(
        projection_spec,
        group_fields,
        aggregates,
    )?;

    Ok(aggregate_specs)
}

///
/// GroupedDistinctPolicyContract
///
/// Planner-projected grouped DISTINCT policy contract for executor boundaries.
/// Route/load layers consume this contract directly instead of re-deriving
/// grouped DISTINCT policy from logical plan internals.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct GroupedDistinctPolicyContract {
    violation_for_executor: Option<GroupDistinctPolicyReason>,
    execution_strategy: GroupedDistinctExecutionStrategy,
}

impl GroupedDistinctPolicyContract {
    /// Construct one grouped DISTINCT policy contract.
    #[must_use]
    const fn new(
        violation_for_executor: Option<GroupDistinctPolicyReason>,
        execution_strategy: GroupedDistinctExecutionStrategy,
    ) -> Self {
        Self {
            violation_for_executor,
            execution_strategy,
        }
    }

    /// Borrow grouped DISTINCT execution strategy lowered by planner.
    #[must_use]
    pub(in crate::db) const fn execution_strategy(&self) -> &GroupedDistinctExecutionStrategy {
        &self.execution_strategy
    }

    /// Borrow grouped DISTINCT policy violation reason for executor boundaries.
    #[must_use]
    pub(in crate::db) const fn violation_for_executor(&self) -> Option<GroupDistinctPolicyReason> {
        self.violation_for_executor
    }
}

///
/// GroupedDistinctExecutionStrategy
///
/// Planner-owned grouped DISTINCT execution strategy lowered for executor consumption.
/// This strategy is mechanical-only and must not be re-derived by executor policy checks.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) enum GroupedDistinctExecutionStrategy {
    None,
    GlobalDistinctFieldCount {
        target_field: String,
        target_slot: FieldSlot,
    },
    GlobalDistinctFieldSum {
        target_field: String,
        target_slot: FieldSlot,
    },
    GlobalDistinctFieldAvg {
        target_field: String,
        target_slot: FieldSlot,
    },
}

impl GroupedDistinctExecutionStrategy {
    /// Borrow the planner-resolved target field slot used by grouped DISTINCT runtime.
    #[must_use]
    pub(in crate::db) const fn global_distinct_target_slot(&self) -> Option<&FieldSlot> {
        match self {
            Self::None => None,
            Self::GlobalDistinctFieldCount { target_slot, .. }
            | Self::GlobalDistinctFieldSum { target_slot, .. }
            | Self::GlobalDistinctFieldAvg { target_slot, .. } => Some(target_slot),
        }
    }

    /// Return the canonical aggregate kind used by the dedicated global
    /// DISTINCT field-target runtime path.
    #[must_use]
    pub(in crate::db) const fn global_distinct_aggregate_kind(&self) -> Option<AggregateKind> {
        match self {
            Self::None => None,
            Self::GlobalDistinctFieldCount { .. } => Some(AggregateKind::Count),
            Self::GlobalDistinctFieldSum { .. } => Some(AggregateKind::Sum),
            Self::GlobalDistinctFieldAvg { .. } => Some(AggregateKind::Avg),
        }
    }
}

// Lower grouped DISTINCT execution strategy from validated grouped planner semantics
// while freezing the field-target slot under planner ownership.
pub(in crate::db) fn resolved_grouped_distinct_execution_strategy_for_model(
    model: &EntityModel,
    group_fields: &[FieldSlot],
    aggregates: &[GroupAggregateSpec],
    having_expr: Option<&crate::db::query::plan::expr::Expr>,
) -> Result<GroupedDistinctExecutionStrategy, InternalError> {
    match resolve_global_distinct_field_aggregate(group_fields, aggregates, having_expr) {
        Ok(Some(aggregate)) => {
            let target_field = aggregate.target_field().to_string();
            let target_slot =
                resolve_aggregate_target_field_slot(model, aggregate.target_field()).map_err(
                    |err| {
                        InternalError::planner_executor_invariant(format!(
                            "grouped DISTINCT strategy target slot resolution failed: field='{}', error={err}",
                            aggregate.target_field(),
                        ))
                    },
                )?;

            match aggregate.kind() {
                AggregateKind::Count => {
                    Ok(GroupedDistinctExecutionStrategy::GlobalDistinctFieldCount {
                        target_field,
                        target_slot,
                    })
                }
                AggregateKind::Sum => {
                    Ok(GroupedDistinctExecutionStrategy::GlobalDistinctFieldSum {
                        target_field,
                        target_slot,
                    })
                }
                AggregateKind::Avg => {
                    Ok(GroupedDistinctExecutionStrategy::GlobalDistinctFieldAvg {
                        target_field,
                        target_slot,
                    })
                }
                AggregateKind::Exists
                | AggregateKind::Min
                | AggregateKind::Max
                | AggregateKind::First
                | AggregateKind::Last => Err(InternalError::planner_executor_invariant(
                    "planner grouped DISTINCT strategy handoff must lower only COUNT/SUM/AVG field-target aggregates",
                )),
            }
        }
        Ok(None) => Ok(GroupedDistinctExecutionStrategy::None),
        Err(reason) => Err(reason.into_planner_handoff_internal_error()),
    }
}

// Derive grouped field/aggregate projection slots and grouped aggregate
// projection specs from canonical projection semantics.
fn planned_projection_layout_and_aggregate_specs_core(
    projection_spec: &ProjectionSpec,
    group_fields: &[FieldSlot],
    aggregates: &[GroupAggregateSpec],
) -> (
    PlannedProjectionLayout,
    Vec<GroupedAggregateExecutionSpec>,
    bool,
) {
    let grouped_field_names = group_fields
        .iter()
        .map(FieldSlot::field)
        .collect::<Vec<_>>();
    let mut group_field_positions = Vec::new();
    let mut aggregate_positions = Vec::new();
    let mut aggregate_specs = Vec::new();
    let mut projection_is_identity =
        projection_spec.len() == group_fields.len().saturating_add(aggregates.len());
    let mut next_group_field_index = 0usize;
    let mut next_aggregate_index = 0usize;

    for (index, field) in projection_spec.fields().enumerate() {
        let root_expr = expression_without_alias(projection_field_expr(field));
        let aggregate_scan =
            collect_grouped_projection_aggregate_scan(root_expr, &mut aggregate_specs);

        match root_expr {
            Expr::Field(field_id) => {
                group_field_positions.push(index);
                projection_is_identity &= next_aggregate_index == 0
                    && group_fields
                        .get(next_group_field_index)
                        .is_some_and(|group_field| field_id.as_str() == group_field.field.as_str());
                next_group_field_index = next_group_field_index.saturating_add(1);
            }
            Expr::Aggregate(aggregate_expr) => {
                aggregate_positions.push(index);
                let aggregate_spec =
                    GroupedAggregateExecutionSpec::from_aggregate_expr(aggregate_expr);
                projection_is_identity &= next_group_field_index == group_fields.len()
                    && aggregates
                        .get(next_aggregate_index)
                        .is_some_and(|aggregate| {
                            aggregate_spec.matches_semantic_aggregate(aggregate)
                        });
                next_aggregate_index = next_aggregate_index
                    .saturating_add(aggregate_scan.introduced_aggregate_count());
            }
            _ if aggregate_scan.contains_aggregate() => {
                aggregate_positions.push(index);
                projection_is_identity = false;
                next_aggregate_index = next_aggregate_index
                    .saturating_add(aggregate_scan.introduced_aggregate_count());
            }
            _ if expr_references_only_fields(root_expr, grouped_field_names.as_slice()) => {
                group_field_positions.push(index);
                projection_is_identity &= grouped_projection_expression_preserves_identity(
                    root_expr,
                    group_fields,
                    next_group_field_index,
                    next_aggregate_index,
                );
                next_group_field_index = next_group_field_index.saturating_add(1);
            }
            _ => {
                group_field_positions.push(index);
                projection_is_identity = false;
                next_group_field_index = next_group_field_index.saturating_add(1);
            }
        }
    }
    projection_is_identity &=
        next_group_field_index == group_fields.len() && next_aggregate_index == aggregates.len();

    (
        PlannedProjectionLayout {
            group_field_positions,
            aggregate_positions,
        },
        aggregate_specs,
        projection_is_identity,
    )
}

#[allow(
    clippy::unnecessary_wraps,
    reason = "test builds keep one extra grouped projection strictness pass while non-test builds stay on the planner core path"
)]
fn planned_projection_layout_and_aggregate_specs_from_spec(
    projection_spec: &ProjectionSpec,
    group_fields: &[FieldSlot],
    aggregates: &[GroupAggregateSpec],
) -> Result<
    (
        PlannedProjectionLayout,
        Vec<GroupedAggregateExecutionSpec>,
        bool,
    ),
    InternalError,
> {
    // Test builds keep one extra strictness pass so grouped layout regressions
    // fail at the planner boundary instead of only in downstream assertions.
    #[cfg(test)]
    {
        let grouped_field_names = group_fields
            .iter()
            .map(FieldSlot::field)
            .collect::<Vec<_>>();

        for (index, field) in projection_spec.fields().enumerate() {
            let root_expr = expression_without_alias(projection_field_expr(field));
            if !expr_references_only_fields(root_expr, grouped_field_names.as_slice()) {
                return Err(InternalError::planner_executor_invariant(format!(
                    "grouped projection layout expects only field/aggregate expressions; found non-grouped projection expression at index={index}",
                )));
            }
        }
    }

    Ok(planned_projection_layout_and_aggregate_specs_core(
        projection_spec,
        group_fields,
        aggregates,
    ))
}

// Keep grouped layout identity checks local to the planner-owned layout core
// so computed grouped-key expressions do not pretend to preserve field-order
// identity.
fn grouped_projection_expression_preserves_identity(
    root_expr: &Expr,
    group_fields: &[FieldSlot],
    next_group_field_index: usize,
    next_aggregate_index: usize,
) -> bool {
    next_aggregate_index == 0
        && matches!(
            root_expr,
            Expr::Field(field_id)
                if group_fields.get(next_group_field_index).is_some_and(
                    |group_field| field_id.as_str() == group_field.field.as_str(),
                )
        )
}

fn collect_grouped_projection_aggregate_scan(
    expr: &Expr,
    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
) -> GroupedProjectionAggregateScan {
    match expr {
        Expr::Aggregate(aggregate_expr) => {
            GroupedProjectionAggregateScan::found_aggregate(push_unique_grouped_aggregate_spec(
                aggregate_specs,
                GroupedAggregateExecutionSpec::from_aggregate_expr(aggregate_expr),
            ))
        }
        Expr::Field(_) | Expr::Literal(_) => GroupedProjectionAggregateScan::none(),
        Expr::FunctionCall { args, .. } => {
            args.iter()
                .fold(GroupedProjectionAggregateScan::none(), |scan, arg| {
                    scan.combine(collect_grouped_projection_aggregate_scan(
                        arg,
                        aggregate_specs,
                    ))
                })
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => when_then_arms.iter().fold(
            collect_grouped_projection_aggregate_scan(else_expr.as_ref(), aggregate_specs),
            |scan, arm| {
                scan.combine(collect_grouped_projection_aggregate_scan(
                    arm.condition(),
                    aggregate_specs,
                ))
                .combine(collect_grouped_projection_aggregate_scan(
                    arm.result(),
                    aggregate_specs,
                ))
            },
        ),
        Expr::Binary { left, right, .. } => {
            collect_grouped_projection_aggregate_scan(left.as_ref(), aggregate_specs).combine(
                collect_grouped_projection_aggregate_scan(right.as_ref(), aggregate_specs),
            )
        }
        #[cfg(test)]
        Expr::Alias { expr, .. } => {
            collect_grouped_projection_aggregate_scan(expr.as_ref(), aggregate_specs)
        }
        Expr::Unary { expr, .. } => {
            collect_grouped_projection_aggregate_scan(expr.as_ref(), aggregate_specs)
        }
    }
}

// Keep grouped aggregate specs on one stable first-seen unique
// order so repeated aggregate leaves reuse the same grouped execution slot.
fn push_unique_grouped_aggregate_spec(
    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
    aggregate_spec: GroupedAggregateExecutionSpec,
) -> usize {
    if aggregate_specs
        .iter()
        .all(|current| current != &aggregate_spec)
    {
        aggregate_specs.push(aggregate_spec);
        return 1;
    }

    0
}

// Strip alias wrappers so layout classification uses semantic expression roots.
#[allow(
    clippy::missing_const_for_fn,
    reason = "alias stripping traverses boxed expression refs that are not const-callable on stable"
)]
fn expression_without_alias(expr: &Expr) -> &Expr {
    #[cfg(test)]
    {
        let mut current = expr;
        while let Expr::Alias { expr: inner, .. } = current {
            current = inner.as_ref();
        }

        current
    }

    #[cfg(not(test))]
    expr
}