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
//! Module: query::plan::semantics::logical
//! Responsibility: logical-plan semantic lowering from planner contracts to access-planned queries.
//! Does not own: access-path index selection internals or runtime execution behavior.
//! Boundary: derives planner-owned execution semantics, shape signatures, and continuation policy.

use crate::{
    db::{
        access::{AccessPlan, ExecutableAccessPlan},
        predicate::IndexCompileTarget,
        predicate::{PredicateExecutionModel, PredicateProgram},
        query::plan::{
            AccessPlannedQuery, ContinuationPolicy, DistinctExecutionStrategy,
            ExecutionShapeSignature, GroupPlan, GroupedAggregateExecutionSpec,
            GroupedDistinctExecutionStrategy, GroupedPlanStrategy, LogicalPlan,
            PlannerRouteProfile, QueryMode, ResolvedOrder, ResolvedOrderField,
            ResolvedOrderValueSource, ScalarPlan, StaticPlanningShape,
            derive_logical_pushdown_eligibility,
            expr::{
                Expr, ProjectionField, ProjectionSpec, ScalarProjectionExpr,
                compile_scalar_projection_expr, compile_scalar_projection_plan,
                parse_supported_computed_order_expr, projection_field_expr,
            },
            grouped_aggregate_execution_specs, grouped_aggregate_specs_from_projection_spec,
            grouped_cursor_policy_violation, grouped_plan_strategy, lower_direct_projection_slots,
            lower_projection_identity, lower_projection_intent,
            residual_query_predicate_after_access_path_bounds,
            residual_query_predicate_after_filtered_access,
            resolved_grouped_distinct_execution_strategy_for_model,
        },
    },
    error::InternalError,
    model::{
        entity::{EntityModel, resolve_field_slot},
        index::IndexKeyItemsRef,
    },
};

impl QueryMode {
    /// True if this mode represents a load intent.
    #[must_use]
    pub const fn is_load(&self) -> bool {
        match self {
            Self::Load(_) => true,
            Self::Delete(_) => false,
        }
    }

    /// True if this mode represents a delete intent.
    #[must_use]
    pub const fn is_delete(&self) -> bool {
        match self {
            Self::Delete(_) => true,
            Self::Load(_) => false,
        }
    }
}

impl LogicalPlan {
    /// Borrow scalar semantic fields shared by scalar/grouped logical variants.
    #[must_use]
    pub(in crate::db) const fn scalar_semantics(&self) -> &ScalarPlan {
        match self {
            Self::Scalar(plan) => plan,
            Self::Grouped(plan) => &plan.scalar,
        }
    }

    /// Borrow scalar semantic fields mutably across logical variants for tests.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar_semantics_mut(&mut self) -> &mut ScalarPlan {
        match self {
            Self::Scalar(plan) => plan,
            Self::Grouped(plan) => &mut plan.scalar,
        }
    }

    /// Test-only shorthand for explicit scalar semantic borrowing.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
        self.scalar_semantics()
    }

    /// Test-only shorthand for explicit mutable scalar semantic borrowing.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
        self.scalar_semantics_mut()
    }
}

impl AccessPlannedQuery {
    /// Borrow scalar semantic fields shared by scalar/grouped logical variants.
    #[must_use]
    pub(in crate::db) const fn scalar_plan(&self) -> &ScalarPlan {
        self.logical.scalar_semantics()
    }

    /// Borrow scalar semantic fields mutably across logical variants for tests.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar_plan_mut(&mut self) -> &mut ScalarPlan {
        self.logical.scalar_semantics_mut()
    }

    /// Test-only shorthand for explicit scalar plan borrowing.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
        self.scalar_plan()
    }

    /// Test-only shorthand for explicit mutable scalar plan borrowing.
    #[must_use]
    #[cfg(test)]
    pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
        self.scalar_plan_mut()
    }

    /// Borrow grouped semantic fields when this plan is grouped.
    #[must_use]
    pub(in crate::db) const fn grouped_plan(&self) -> Option<&GroupPlan> {
        match &self.logical {
            LogicalPlan::Scalar(_) => None,
            LogicalPlan::Grouped(plan) => Some(plan),
        }
    }

    /// Lower this plan into one canonical planner-owned projection semantic spec.
    #[must_use]
    pub(in crate::db) fn projection_spec(&self, model: &EntityModel) -> ProjectionSpec {
        if let Some(static_shape) = &self.static_planning_shape {
            return static_shape.projection_spec.clone();
        }

        lower_projection_intent(model, &self.logical, &self.projection_selection)
    }

    /// Lower this plan into one projection semantic shape for identity hashing.
    #[must_use]
    pub(in crate::db::query) fn projection_spec_for_identity(&self) -> ProjectionSpec {
        lower_projection_identity(&self.logical)
    }

    /// Return the executor-facing predicate after removing only filtered-index
    /// guard clauses the chosen access path already proves.
    ///
    /// This conservative form is used by preparation/explain surfaces that
    /// still need to see access-bound equalities as index-predicate input.
    #[must_use]
    pub(in crate::db) fn execution_preparation_predicate(&self) -> Option<PredicateExecutionModel> {
        let query_predicate = self.scalar_plan().predicate.as_ref()?;

        match self.access.selected_index_model() {
            Some(index) => residual_query_predicate_after_filtered_access(index, query_predicate),
            None => Some(query_predicate.clone()),
        }
    }

    /// Return the executor-facing residual predicate after removing any
    /// filtered-index guard clauses and fixed access-bound equalities already
    /// guaranteed by the chosen path.
    #[must_use]
    pub(in crate::db) fn effective_execution_predicate(&self) -> Option<PredicateExecutionModel> {
        // Phase 1: strip only filtered-index guard clauses the chosen access
        // path already proves.
        let filtered_residual = self.execution_preparation_predicate();
        let filtered_residual = filtered_residual.as_ref()?;

        // Phase 2: strip any additional equality clauses already guaranteed by
        // the concrete access-path bounds, such as `tier = 'gold'` on one
        // selected `IndexPrefix(tier='gold', ...)` route.
        residual_query_predicate_after_access_path_bounds(self.access.as_path(), filtered_residual)
    }

    /// Borrow the planner-compiled execution-preparation predicate program.
    #[must_use]
    pub(in crate::db) const fn execution_preparation_compiled_predicate(
        &self,
    ) -> Option<&PredicateProgram> {
        self.static_planning_shape()
            .execution_preparation_compiled_predicate
            .as_ref()
    }

    /// Borrow the planner-compiled effective runtime predicate program.
    #[must_use]
    pub(in crate::db) const fn effective_runtime_compiled_predicate(
        &self,
    ) -> Option<&PredicateProgram> {
        self.static_planning_shape()
            .effective_runtime_compiled_predicate
            .as_ref()
    }

    /// Lower scalar DISTINCT semantics into one executor-facing execution strategy.
    #[must_use]
    pub(in crate::db) fn distinct_execution_strategy(&self) -> DistinctExecutionStrategy {
        if !self.scalar_plan().distinct {
            return DistinctExecutionStrategy::None;
        }

        // DISTINCT on duplicate-safe single-path access shapes is a planner
        // no-op for runtime dedup mechanics. Composite shapes can surface
        // duplicate keys and therefore retain explicit dedup execution.
        match distinct_runtime_dedup_strategy(&self.access) {
            Some(strategy) => strategy,
            None => DistinctExecutionStrategy::None,
        }
    }

    /// Freeze one planner-owned route profile after model validation completes.
    pub(in crate::db) fn finalize_planner_route_profile_for_model(&mut self, model: &EntityModel) {
        self.set_planner_route_profile(project_planner_route_profile_for_model(model, self));
    }

    /// Freeze planner-owned executor metadata after logical/access planning completes.
    pub(in crate::db) fn finalize_static_planning_shape_for_model(
        &mut self,
        model: &EntityModel,
    ) -> Result<(), InternalError> {
        self.static_planning_shape = Some(project_static_planning_shape_for_model(model, self)?);

        Ok(())
    }

    /// Build one immutable execution-shape signature contract for runtime layers.
    #[must_use]
    pub(in crate::db) fn execution_shape_signature(
        &self,
        entity_path: &'static str,
    ) -> ExecutionShapeSignature {
        ExecutionShapeSignature::new(self.continuation_signature(entity_path))
    }

    /// Return whether the chosen access contract fully satisfies the current
    /// scalar query predicate without any additional post-access filtering.
    #[must_use]
    pub(in crate::db) fn predicate_fully_satisfied_by_access_contract(&self) -> bool {
        self.scalar_plan().predicate.is_some() && self.effective_execution_predicate().is_none()
    }

    /// Return whether the scalar logical predicate still requires post-access
    /// filtering after accounting for filtered-index guard predicates and
    /// access-path equality bounds.
    #[must_use]
    pub(in crate::db) fn has_residual_predicate(&self) -> bool {
        self.scalar_plan().predicate.is_some()
            && !self.predicate_fully_satisfied_by_access_contract()
    }

    /// Borrow the planner-frozen compiled scalar projection program.
    #[must_use]
    pub(in crate::db) fn scalar_projection_plan(&self) -> Option<&[ScalarProjectionExpr]> {
        self.static_planning_shape()
            .scalar_projection_plan
            .as_deref()
    }

    /// Borrow the planner-frozen primary-key field name.
    #[must_use]
    pub(in crate::db) const fn primary_key_name(&self) -> &'static str {
        self.static_planning_shape().primary_key_name
    }

    /// Borrow the planner-frozen projection slot reachability set.
    #[must_use]
    pub(in crate::db) const fn projection_referenced_slots(&self) -> &[usize] {
        self.static_planning_shape()
            .projection_referenced_slots
            .as_slice()
    }

    /// Borrow the planner-frozen mask for direct projected output slots.
    #[must_use]
    #[cfg(any(test, feature = "diagnostics"))]
    pub(in crate::db) const fn projected_slot_mask(&self) -> &[bool] {
        self.static_planning_shape().projected_slot_mask.as_slice()
    }

    /// Return whether projection remains the full model-identity field list.
    #[must_use]
    pub(in crate::db) const fn projection_is_model_identity(&self) -> bool {
        self.static_planning_shape().projection_is_model_identity
    }

    /// Borrow the planner-frozen ORDER BY slot reachability set, if any.
    #[must_use]
    pub(in crate::db) fn order_referenced_slots(&self) -> Option<&[usize]> {
        self.static_planning_shape()
            .order_referenced_slots
            .as_deref()
    }

    /// Borrow the planner-frozen resolved ORDER BY program, if one exists.
    #[must_use]
    pub(in crate::db) const fn resolved_order(&self) -> Option<&ResolvedOrder> {
        self.static_planning_shape().resolved_order.as_ref()
    }

    /// Borrow the planner-frozen access slot map used by index predicate compilation.
    #[must_use]
    pub(in crate::db) fn slot_map(&self) -> Option<&[usize]> {
        self.static_planning_shape().slot_map.as_deref()
    }

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

    /// Borrow the planner-resolved grouped DISTINCT execution strategy when present.
    #[must_use]
    pub(in crate::db) const fn grouped_distinct_execution_strategy(
        &self,
    ) -> Option<&GroupedDistinctExecutionStrategy> {
        self.static_planning_shape()
            .grouped_distinct_execution_strategy
            .as_ref()
    }

    /// Borrow the frozen projection semantic shape without reopening model ownership.
    #[must_use]
    pub(in crate::db) const fn frozen_projection_spec(&self) -> &ProjectionSpec {
        &self.static_planning_shape().projection_spec
    }

    /// Borrow the frozen direct projection slots without reopening model ownership.
    #[must_use]
    pub(in crate::db) fn frozen_direct_projection_slots(&self) -> Option<&[usize]> {
        self.static_planning_shape()
            .projection_direct_slots
            .as_deref()
    }

    /// Borrow the planner-frozen key-item-aware compile targets for the chosen access path.
    #[must_use]
    pub(in crate::db) fn index_compile_targets(&self) -> Option<&[IndexCompileTarget]> {
        self.static_planning_shape()
            .index_compile_targets
            .as_deref()
    }

    const fn static_planning_shape(&self) -> &StaticPlanningShape {
        self.static_planning_shape
            .as_ref()
            .expect("access-planned queries must freeze static planning shape before execution")
    }
}

fn distinct_runtime_dedup_strategy<K>(access: &AccessPlan<K>) -> Option<DistinctExecutionStrategy> {
    match access {
        AccessPlan::Union(_) | AccessPlan::Intersection(_) => {
            Some(DistinctExecutionStrategy::PreOrdered)
        }
        AccessPlan::Path(path) if path.as_ref().is_index_multi_lookup() => {
            Some(DistinctExecutionStrategy::HashMaterialize)
        }
        AccessPlan::Path(_) => None,
    }
}

fn derive_continuation_policy_validated(plan: &AccessPlannedQuery) -> ContinuationPolicy {
    let is_grouped_safe = plan
        .grouped_plan()
        .is_none_or(|grouped| grouped_cursor_policy_violation(grouped, true).is_none());

    ContinuationPolicy::new(
        true, // Continuation resume windows require anchor semantics for pushdown-safe replay.
        true, // Continuation resumes must advance strictly to prevent replay/regression loops.
        is_grouped_safe,
    )
}

/// Project one planner-owned route profile from the finalized logical+access plan.
#[must_use]
pub(in crate::db) fn project_planner_route_profile_for_model(
    model: &EntityModel,
    plan: &AccessPlannedQuery,
) -> PlannerRouteProfile {
    let secondary_order_contract = plan
        .scalar_plan()
        .order
        .as_ref()
        .and_then(|order| order.deterministic_secondary_order_contract(model.primary_key.name));

    PlannerRouteProfile::new(
        derive_continuation_policy_validated(plan),
        derive_logical_pushdown_eligibility(plan, secondary_order_contract.as_ref()),
        secondary_order_contract,
    )
}

fn project_static_planning_shape_for_model(
    model: &EntityModel,
    plan: &AccessPlannedQuery,
) -> Result<StaticPlanningShape, InternalError> {
    let projection_spec = lower_projection_intent(model, &plan.logical, &plan.projection_selection);
    let execution_preparation_compiled_predicate =
        compile_optional_predicate(model, plan.execution_preparation_predicate().as_ref());
    let effective_runtime_compiled_predicate =
        compile_optional_predicate(model, plan.effective_execution_predicate().as_ref());
    let scalar_projection_plan =
        if plan.grouped_plan().is_none() {
            Some(compile_scalar_projection_plan(model, &projection_spec).ok_or_else(|| {
            InternalError::query_executor_invariant(
                "scalar projection program must compile during static planning finalization",
            )
        })?)
        } else {
            None
        };
    let (grouped_aggregate_execution_specs, grouped_distinct_execution_strategy) =
        resolve_grouped_static_planning_semantics(model, plan, &projection_spec)?;
    let projection_direct_slots =
        lower_direct_projection_slots(model, &plan.logical, &plan.projection_selection);
    let projection_referenced_slots =
        projection_referenced_slots_for_spec(model, &projection_spec)?;
    let projected_slot_mask =
        projected_slot_mask_for_spec(model, projection_direct_slots.as_deref());
    let projection_is_model_identity =
        projection_is_model_identity_for_spec(model, &projection_spec);
    let resolved_order = resolved_order_for_plan(model, plan)?;
    let order_referenced_slots = order_referenced_slots_for_resolved_order(resolved_order.as_ref());
    let slot_map = slot_map_for_model_plan(model, plan);
    let index_compile_targets = index_compile_targets_for_model_plan(model, plan);

    Ok(StaticPlanningShape {
        primary_key_name: model.primary_key.name,
        projection_spec,
        execution_preparation_compiled_predicate,
        effective_runtime_compiled_predicate,
        scalar_projection_plan,
        grouped_aggregate_execution_specs,
        grouped_distinct_execution_strategy,
        projection_direct_slots,
        projection_referenced_slots,
        projected_slot_mask,
        projection_is_model_identity,
        resolved_order,
        order_referenced_slots,
        slot_map,
        index_compile_targets,
    })
}

// Compile one optional planner-frozen predicate program while keeping the
// static planning assembly path free of repeated `Option` mapping boilerplate.
fn compile_optional_predicate(
    model: &EntityModel,
    predicate: Option<&PredicateExecutionModel>,
) -> Option<PredicateProgram> {
    predicate.map(|predicate| PredicateProgram::compile(model, predicate))
}

// Resolve the grouped-only static planning semantics bundle once so grouped
// aggregate execution specs and grouped DISTINCT strategy stay derived under
// one shared grouped-plan branch.
fn resolve_grouped_static_planning_semantics(
    model: &EntityModel,
    plan: &AccessPlannedQuery,
    projection_spec: &ProjectionSpec,
) -> Result<
    (
        Option<Vec<GroupedAggregateExecutionSpec>>,
        Option<GroupedDistinctExecutionStrategy>,
    ),
    InternalError,
> {
    let Some(grouped) = plan.grouped_plan() else {
        return Ok((None, None));
    };

    let mut aggregate_specs = grouped_aggregate_specs_from_projection_spec(
        projection_spec,
        grouped.group.group_fields.as_slice(),
        grouped.group.aggregates.as_slice(),
    )?;
    extend_grouped_having_aggregate_specs(&mut aggregate_specs, grouped)?;

    let grouped_aggregate_execution_specs = Some(grouped_aggregate_execution_specs(
        model,
        aggregate_specs.as_slice(),
    )?);
    let grouped_distinct_execution_strategy =
        Some(resolved_grouped_distinct_execution_strategy_for_model(
            model,
            grouped.group.group_fields.as_slice(),
            grouped.group.aggregates.as_slice(),
            grouped.having_expr.as_ref(),
        )?);

    Ok((
        grouped_aggregate_execution_specs,
        grouped_distinct_execution_strategy,
    ))
}

fn extend_grouped_having_aggregate_specs(
    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
    grouped: &GroupPlan,
) -> Result<(), InternalError> {
    if let Some(having_expr) = grouped.having_expr.as_ref() {
        collect_grouped_having_expr_aggregate_specs(aggregate_specs, having_expr)?;
    }

    Ok(())
}

fn collect_grouped_having_expr_aggregate_specs(
    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
    expr: &Expr,
) -> Result<(), InternalError> {
    match expr {
        Expr::Aggregate(aggregate_expr) => {
            let aggregate_spec = GroupedAggregateExecutionSpec::from_aggregate_expr(aggregate_expr);

            if aggregate_specs
                .iter()
                .all(|current| current != &aggregate_spec)
            {
                aggregate_specs.push(aggregate_spec);
            }
        }
        Expr::Field(_) | Expr::Literal(_) => {}
        Expr::FunctionCall { args, .. } => {
            for arg in args {
                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arg)?;
            }
        }
        Expr::Unary { expr, .. } => {
            collect_grouped_having_expr_aggregate_specs(aggregate_specs, expr)?;
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            for arm in when_then_arms {
                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arm.condition())?;
                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arm.result())?;
            }

            collect_grouped_having_expr_aggregate_specs(aggregate_specs, else_expr)?;
        }
        Expr::Binary { left, right, .. } => {
            collect_grouped_having_expr_aggregate_specs(aggregate_specs, left)?;
            collect_grouped_having_expr_aggregate_specs(aggregate_specs, right)?;
        }
        #[cfg(test)]
        Expr::Alias { expr, .. } => {
            collect_grouped_having_expr_aggregate_specs(aggregate_specs, expr)?;
        }
    }

    Ok(())
}

fn projection_referenced_slots_for_spec(
    model: &EntityModel,
    projection: &ProjectionSpec,
) -> Result<Vec<usize>, InternalError> {
    let mut referenced = vec![false; model.fields().len()];

    for field in projection.fields() {
        mark_projection_expr_slots(
            model,
            projection_field_expr(field),
            referenced.as_mut_slice(),
        )?;
    }

    Ok(referenced
        .into_iter()
        .enumerate()
        .filter_map(|(slot, required)| required.then_some(slot))
        .collect())
}

fn mark_projection_expr_slots(
    model: &EntityModel,
    expr: &Expr,
    referenced: &mut [bool],
) -> Result<(), InternalError> {
    match expr {
        Expr::Field(field_id) => {
            let field_name = field_id.as_str();
            let slot = resolve_required_field_slot(model, field_name, || {
                InternalError::query_invalid_logical_plan(format!(
                    "projection expression references unknown field '{field_name}'",
                ))
            })?;
            referenced[slot] = true;
        }
        Expr::Literal(_) => {}
        Expr::FunctionCall { args, .. } => {
            for arg in args {
                mark_projection_expr_slots(model, arg, referenced)?;
            }
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            for arm in when_then_arms {
                mark_projection_expr_slots(model, arm.condition(), referenced)?;
                mark_projection_expr_slots(model, arm.result(), referenced)?;
            }
            mark_projection_expr_slots(model, else_expr.as_ref(), referenced)?;
        }
        Expr::Aggregate(_) => {}
        #[cfg(test)]
        Expr::Alias { expr, .. } => {
            mark_projection_expr_slots(model, expr.as_ref(), referenced)?;
        }
        Expr::Unary { expr, .. } => {
            mark_projection_expr_slots(model, expr.as_ref(), referenced)?;
        }
        Expr::Binary { left, right, .. } => {
            mark_projection_expr_slots(model, left.as_ref(), referenced)?;
            mark_projection_expr_slots(model, right.as_ref(), referenced)?;
        }
    }

    Ok(())
}

fn projected_slot_mask_for_spec(
    model: &EntityModel,
    direct_projection_slots: Option<&[usize]>,
) -> Vec<bool> {
    let mut projected_slots = vec![false; model.fields().len()];

    let Some(direct_projection_slots) = direct_projection_slots else {
        return projected_slots;
    };

    for slot in direct_projection_slots.iter().copied() {
        if let Some(projected) = projected_slots.get_mut(slot) {
            *projected = true;
        }
    }

    projected_slots
}

fn projection_is_model_identity_for_spec(model: &EntityModel, projection: &ProjectionSpec) -> bool {
    if projection.len() != model.fields().len() {
        return false;
    }

    for (field_model, projected_field) in model.fields().iter().zip(projection.fields()) {
        match projected_field {
            ProjectionField::Scalar {
                expr: Expr::Field(field_id),
                alias: None,
            } if field_id.as_str() == field_model.name() => {}
            ProjectionField::Scalar { .. } => return false,
        }
    }

    true
}

fn resolved_order_for_plan(
    model: &EntityModel,
    plan: &AccessPlannedQuery,
) -> Result<Option<ResolvedOrder>, InternalError> {
    if grouped_plan_strategy(plan).is_some_and(GroupedPlanStrategy::is_top_k_group) {
        return Ok(None);
    }

    let Some(order) = plan.scalar_plan().order.as_ref() else {
        return Ok(None);
    };

    let mut fields = Vec::with_capacity(order.fields.len());
    for (field, direction) in &order.fields {
        fields.push(ResolvedOrderField::new(
            resolved_order_value_source_for_field(model, field)?,
            *direction,
        ));
    }

    Ok(Some(ResolvedOrder::new(fields)))
}

fn resolved_order_value_source_for_field(
    model: &EntityModel,
    field: &str,
) -> Result<ResolvedOrderValueSource, InternalError> {
    if let Some(expr) = parse_supported_computed_order_expr(field) {
        validate_resolved_order_expr_fields(model, &expr, field)?;
        let compiled = compile_scalar_projection_expr(model, &expr)
            .ok_or_else(|| order_expression_scalar_seam_error(field))?;

        return Ok(ResolvedOrderValueSource::expression(compiled));
    }

    let slot = resolve_required_field_slot(model, field, || {
        InternalError::query_invalid_logical_plan(format!(
            "order expression references unknown field '{field}'",
        ))
    })?;

    Ok(ResolvedOrderValueSource::direct_field(slot))
}

fn validate_resolved_order_expr_fields(
    model: &EntityModel,
    expr: &Expr,
    rendered: &str,
) -> Result<(), InternalError> {
    match expr {
        Expr::Field(field_id) => {
            resolve_required_field_slot(model, field_id.as_str(), || {
                InternalError::query_invalid_logical_plan(format!(
                    "order expression references unknown field '{rendered}'",
                ))
            })?;
        }
        Expr::Literal(_) => {}
        Expr::FunctionCall { args, .. } => {
            for arg in args {
                validate_resolved_order_expr_fields(model, arg, rendered)?;
            }
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            for arm in when_then_arms {
                validate_resolved_order_expr_fields(model, arm.condition(), rendered)?;
                validate_resolved_order_expr_fields(model, arm.result(), rendered)?;
            }
            validate_resolved_order_expr_fields(model, else_expr.as_ref(), rendered)?;
        }
        Expr::Binary { left, right, .. } => {
            validate_resolved_order_expr_fields(model, left.as_ref(), rendered)?;
            validate_resolved_order_expr_fields(model, right.as_ref(), rendered)?;
        }
        Expr::Aggregate(_) => {
            return Err(order_expression_scalar_seam_error(rendered));
        }
        #[cfg(test)]
        Expr::Alias { .. } => {
            return Err(order_expression_scalar_seam_error(rendered));
        }
        Expr::Unary { .. } => {
            return Err(order_expression_scalar_seam_error(rendered));
        }
    }

    Ok(())
}

// Resolve one model field slot while keeping planner invalid-logical-plan
// error construction at the callsite that owns the diagnostic wording.
fn resolve_required_field_slot<F>(
    model: &EntityModel,
    field: &str,
    invalid_plan_error: F,
) -> Result<usize, InternalError>
where
    F: FnOnce() -> InternalError,
{
    resolve_field_slot(model, field).ok_or_else(invalid_plan_error)
}

// Keep the scalar-order expression seam violation text under one helper so the
// parse validation and compile validation paths do not drift.
fn order_expression_scalar_seam_error(rendered: &str) -> InternalError {
    InternalError::query_invalid_logical_plan(format!(
        "order expression '{rendered}' did not stay on the scalar expression seam",
    ))
}

// Keep one stable executor-facing slot list for grouped order terms after the
// planner has frozen the structural `ResolvedOrder`. The grouped Top-K route
// now consumes this same referenced-slot contract instead of re-deriving order
// sources from planner strategy at runtime.
fn order_referenced_slots_for_resolved_order(
    resolved_order: Option<&ResolvedOrder>,
) -> Option<Vec<usize>> {
    let resolved_order = resolved_order?;
    let mut referenced = Vec::new();

    // Keep one stable slot list without re-parsing order expressions after the
    // planner has already frozen structural ORDER BY sources.
    for field in resolved_order.fields() {
        field.source().extend_referenced_slots(&mut referenced);
    }

    Some(referenced)
}

fn slot_map_for_model_plan(model: &EntityModel, plan: &AccessPlannedQuery) -> Option<Vec<usize>> {
    let access_strategy = plan.access.resolve_strategy();
    let executable = access_strategy.executable();

    resolved_index_slots_for_access_path(model, executable)
}

fn resolved_index_slots_for_access_path(
    model: &EntityModel,
    access: &ExecutableAccessPlan<'_, crate::value::Value>,
) -> Option<Vec<usize>> {
    let path = access.as_path()?;
    let path_capabilities = path.capabilities();
    let index_fields = path_capabilities.index_fields_for_slot_map()?;
    let mut slots = Vec::with_capacity(index_fields.len());

    for field_name in index_fields {
        let slot = resolve_field_slot(model, field_name)?;
        slots.push(slot);
    }

    Some(slots)
}

fn index_compile_targets_for_model_plan(
    model: &EntityModel,
    plan: &AccessPlannedQuery,
) -> Option<Vec<IndexCompileTarget>> {
    let index = plan.access.as_path()?.selected_index_model()?;
    let mut targets = Vec::new();

    match index.key_items() {
        IndexKeyItemsRef::Fields(fields) => {
            for (component_index, &field_name) in fields.iter().enumerate() {
                let field_slot = resolve_field_slot(model, field_name)?;
                targets.push(IndexCompileTarget {
                    component_index,
                    field_slot,
                    key_item: crate::model::index::IndexKeyItem::Field(field_name),
                });
            }
        }
        IndexKeyItemsRef::Items(items) => {
            for (component_index, &key_item) in items.iter().enumerate() {
                let field_slot = resolve_field_slot(model, key_item.field())?;
                targets.push(IndexCompileTarget {
                    component_index,
                    field_slot,
                    key_item,
                });
            }
        }
    }

    Some(targets)
}