Skip to main content

icydb_core/db/query/plan/semantics/
logical.rs

1//! Module: query::plan::semantics::logical
2//! Responsibility: logical-plan semantic lowering from planner contracts to access-planned queries.
3//! Does not own: access-path index selection internals or runtime execution behavior.
4//! Boundary: derives planner-owned execution semantics, shape signatures, and continuation policy.
5
6use crate::{
7    db::{
8        access::{AccessPlan, ExecutableAccessPlan},
9        predicate::IndexCompileTarget,
10        predicate::{Predicate, PredicateProgram},
11        query::plan::{
12            AccessPlannedQuery, ContinuationPolicy, DistinctExecutionStrategy,
13            EffectiveRuntimeFilterProgram, ExecutionShapeSignature, GroupPlan,
14            GroupedAggregateExecutionSpec, GroupedDistinctExecutionStrategy, GroupedPlanStrategy,
15            LogicalPlan, PlannerRouteProfile, QueryMode, ResolvedOrder, ResolvedOrderField,
16            ResolvedOrderValueSource, ScalarPlan, StaticPlanningShape,
17            derive_logical_pushdown_eligibility,
18            expr::{
19                Expr, ProjectionField, ProjectionSpec, ScalarProjectionExpr,
20                compile_scalar_projection_expr, compile_scalar_projection_plan,
21                projection_field_expr,
22            },
23            grouped_aggregate_execution_specs, grouped_aggregate_specs_from_projection_spec,
24            grouped_cursor_policy_violation, grouped_plan_strategy, lower_direct_projection_slots,
25            lower_projection_identity, lower_projection_intent,
26            residual_query_predicate_after_access_path_bounds,
27            residual_query_predicate_after_filtered_access,
28            resolved_grouped_distinct_execution_strategy_for_model,
29        },
30    },
31    error::InternalError,
32    model::{
33        entity::{EntityModel, resolve_field_slot},
34        index::IndexKeyItemsRef,
35    },
36};
37
38impl QueryMode {
39    /// True if this mode represents a load intent.
40    #[must_use]
41    pub const fn is_load(&self) -> bool {
42        match self {
43            Self::Load(_) => true,
44            Self::Delete(_) => false,
45        }
46    }
47
48    /// True if this mode represents a delete intent.
49    #[must_use]
50    pub const fn is_delete(&self) -> bool {
51        match self {
52            Self::Delete(_) => true,
53            Self::Load(_) => false,
54        }
55    }
56}
57
58impl LogicalPlan {
59    /// Borrow scalar semantic fields shared by scalar/grouped logical variants.
60    #[must_use]
61    pub(in crate::db) const fn scalar_semantics(&self) -> &ScalarPlan {
62        match self {
63            Self::Scalar(plan) => plan,
64            Self::Grouped(plan) => &plan.scalar,
65        }
66    }
67
68    /// Borrow scalar semantic fields mutably across logical variants for tests.
69    #[must_use]
70    #[cfg(test)]
71    pub(in crate::db) const fn scalar_semantics_mut(&mut self) -> &mut ScalarPlan {
72        match self {
73            Self::Scalar(plan) => plan,
74            Self::Grouped(plan) => &mut plan.scalar,
75        }
76    }
77
78    /// Test-only shorthand for explicit scalar semantic borrowing.
79    #[must_use]
80    #[cfg(test)]
81    pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
82        self.scalar_semantics()
83    }
84
85    /// Test-only shorthand for explicit mutable scalar semantic borrowing.
86    #[must_use]
87    #[cfg(test)]
88    pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
89        self.scalar_semantics_mut()
90    }
91}
92
93impl AccessPlannedQuery {
94    /// Borrow scalar semantic fields shared by scalar/grouped logical variants.
95    #[must_use]
96    pub(in crate::db) const fn scalar_plan(&self) -> &ScalarPlan {
97        self.logical.scalar_semantics()
98    }
99
100    /// Borrow scalar semantic fields mutably across logical variants for tests.
101    #[must_use]
102    #[cfg(test)]
103    pub(in crate::db) const fn scalar_plan_mut(&mut self) -> &mut ScalarPlan {
104        self.logical.scalar_semantics_mut()
105    }
106
107    /// Test-only shorthand for explicit scalar plan borrowing.
108    #[must_use]
109    #[cfg(test)]
110    pub(in crate::db) const fn scalar(&self) -> &ScalarPlan {
111        self.scalar_plan()
112    }
113
114    /// Test-only shorthand for explicit mutable scalar plan borrowing.
115    #[must_use]
116    #[cfg(test)]
117    pub(in crate::db) const fn scalar_mut(&mut self) -> &mut ScalarPlan {
118        self.scalar_plan_mut()
119    }
120
121    /// Borrow grouped semantic fields when this plan is grouped.
122    #[must_use]
123    pub(in crate::db) const fn grouped_plan(&self) -> Option<&GroupPlan> {
124        match &self.logical {
125            LogicalPlan::Scalar(_) => None,
126            LogicalPlan::Grouped(plan) => Some(plan),
127        }
128    }
129
130    /// Lower this plan into one canonical planner-owned projection semantic spec.
131    #[must_use]
132    pub(in crate::db) fn projection_spec(&self, model: &EntityModel) -> ProjectionSpec {
133        if let Some(static_shape) = &self.static_planning_shape {
134            return static_shape.projection_spec.clone();
135        }
136
137        lower_projection_intent(model, &self.logical, &self.projection_selection)
138    }
139
140    /// Lower this plan into one projection semantic shape for identity hashing.
141    #[must_use]
142    pub(in crate::db::query) fn projection_spec_for_identity(&self) -> ProjectionSpec {
143        lower_projection_identity(&self.logical)
144    }
145
146    /// Return the executor-facing predicate after removing only filtered-index
147    /// guard clauses the chosen access path already proves.
148    ///
149    /// This conservative form is used by preparation/explain surfaces that
150    /// still need to see access-bound equalities as index-predicate input.
151    #[must_use]
152    pub(in crate::db) fn execution_preparation_predicate(&self) -> Option<Predicate> {
153        let query_predicate = self.scalar_plan().predicate.as_ref()?;
154
155        match self.access.selected_index_model() {
156            Some(index) => residual_query_predicate_after_filtered_access(index, query_predicate),
157            None => Some(query_predicate.clone()),
158        }
159    }
160
161    /// Return the executor-facing residual predicate after removing any
162    /// filtered-index guard clauses and fixed access-bound equalities already
163    /// guaranteed by the chosen path.
164    #[must_use]
165    pub(in crate::db) fn effective_execution_predicate(&self) -> Option<Predicate> {
166        // Phase 1: strip only filtered-index guard clauses the chosen access
167        // path already proves.
168        let filtered_residual = self.execution_preparation_predicate();
169        let filtered_residual = filtered_residual.as_ref()?;
170
171        // Phase 2: strip any additional equality clauses already guaranteed by
172        // the concrete access-path bounds, such as `tier = 'gold'` on one
173        // selected `IndexPrefix(tier='gold', ...)` route.
174        residual_query_predicate_after_access_path_bounds(self.access.as_path(), filtered_residual)
175    }
176
177    /// Borrow the planner-compiled execution-preparation predicate program.
178    #[must_use]
179    pub(in crate::db) const fn execution_preparation_compiled_predicate(
180        &self,
181    ) -> Option<&PredicateProgram> {
182        self.static_planning_shape()
183            .execution_preparation_compiled_predicate
184            .as_ref()
185    }
186
187    /// Borrow the planner-compiled effective runtime predicate program.
188    #[must_use]
189    pub(in crate::db) const fn effective_runtime_compiled_predicate(
190        &self,
191    ) -> Option<&PredicateProgram> {
192        match self
193            .static_planning_shape()
194            .effective_runtime_filter_program
195            .as_ref()
196        {
197            Some(EffectiveRuntimeFilterProgram::Predicate(program)) => Some(program),
198            Some(EffectiveRuntimeFilterProgram::Expr(_)) | None => None,
199        }
200    }
201
202    /// Borrow the planner-compiled effective runtime scalar filter expression.
203    #[must_use]
204    pub(in crate::db) const fn effective_runtime_compiled_filter_expr(
205        &self,
206    ) -> Option<&ScalarProjectionExpr> {
207        match self
208            .static_planning_shape()
209            .effective_runtime_filter_program
210            .as_ref()
211        {
212            Some(EffectiveRuntimeFilterProgram::Expr(expr)) => Some(expr),
213            Some(EffectiveRuntimeFilterProgram::Predicate(_)) | None => None,
214        }
215    }
216
217    /// Borrow the planner-frozen effective runtime scalar filter program.
218    #[must_use]
219    pub(in crate::db) const fn effective_runtime_filter_program(
220        &self,
221    ) -> Option<&EffectiveRuntimeFilterProgram> {
222        self.static_planning_shape()
223            .effective_runtime_filter_program
224            .as_ref()
225    }
226
227    /// Lower scalar DISTINCT semantics into one executor-facing execution strategy.
228    #[must_use]
229    pub(in crate::db) fn distinct_execution_strategy(&self) -> DistinctExecutionStrategy {
230        if !self.scalar_plan().distinct {
231            return DistinctExecutionStrategy::None;
232        }
233
234        // DISTINCT on duplicate-safe single-path access shapes is a planner
235        // no-op for runtime dedup mechanics. Composite shapes can surface
236        // duplicate keys and therefore retain explicit dedup execution.
237        match distinct_runtime_dedup_strategy(&self.access) {
238            Some(strategy) => strategy,
239            None => DistinctExecutionStrategy::None,
240        }
241    }
242
243    /// Freeze one planner-owned route profile after model validation completes.
244    pub(in crate::db) fn finalize_planner_route_profile_for_model(&mut self, model: &EntityModel) {
245        self.set_planner_route_profile(project_planner_route_profile_for_model(model, self));
246    }
247
248    /// Freeze planner-owned executor metadata after logical/access planning completes.
249    pub(in crate::db) fn finalize_static_planning_shape_for_model(
250        &mut self,
251        model: &EntityModel,
252    ) -> Result<(), InternalError> {
253        self.static_planning_shape = Some(project_static_planning_shape_for_model(model, self)?);
254
255        Ok(())
256    }
257
258    /// Build one immutable execution-shape signature contract for runtime layers.
259    #[must_use]
260    pub(in crate::db) fn execution_shape_signature(
261        &self,
262        entity_path: &'static str,
263    ) -> ExecutionShapeSignature {
264        ExecutionShapeSignature::new(self.continuation_signature(entity_path))
265    }
266
267    /// Return whether the chosen access contract fully satisfies the current
268    /// scalar query predicate without any additional post-access filtering.
269    #[must_use]
270    pub(in crate::db) fn predicate_fully_satisfied_by_access_contract(&self) -> bool {
271        self.scalar_plan().predicate.is_some() && self.effective_execution_predicate().is_none()
272    }
273
274    /// Return whether scalar filter semantics still require post-access
275    /// filtering after accounting for any derived pushdown predicate and
276    /// access-path equality bounds.
277    #[must_use]
278    pub(in crate::db) fn has_residual_filter(&self) -> bool {
279        match (
280            self.scalar_plan().filter_expr.as_ref(),
281            self.scalar_plan().predicate.as_ref(),
282        ) {
283            (None, None) => false,
284            (Some(_), None) => true,
285            (Some(_) | None, Some(_)) => !self.predicate_fully_satisfied_by_access_contract(),
286        }
287    }
288
289    /// Borrow the planner-frozen compiled scalar projection program.
290    #[must_use]
291    pub(in crate::db) fn scalar_projection_plan(&self) -> Option<&[ScalarProjectionExpr]> {
292        self.static_planning_shape()
293            .scalar_projection_plan
294            .as_deref()
295    }
296
297    /// Borrow the planner-frozen primary-key field name.
298    #[must_use]
299    pub(in crate::db) const fn primary_key_name(&self) -> &'static str {
300        self.static_planning_shape().primary_key_name
301    }
302
303    /// Borrow the planner-frozen projection slot reachability set.
304    #[must_use]
305    pub(in crate::db) const fn projection_referenced_slots(&self) -> &[usize] {
306        self.static_planning_shape()
307            .projection_referenced_slots
308            .as_slice()
309    }
310
311    /// Borrow the planner-frozen mask for direct projected output slots.
312    #[must_use]
313    #[cfg(any(test, feature = "diagnostics"))]
314    pub(in crate::db) const fn projected_slot_mask(&self) -> &[bool] {
315        self.static_planning_shape().projected_slot_mask.as_slice()
316    }
317
318    /// Return whether projection remains the full model-identity field list.
319    #[must_use]
320    pub(in crate::db) const fn projection_is_model_identity(&self) -> bool {
321        self.static_planning_shape().projection_is_model_identity
322    }
323
324    /// Borrow the planner-frozen ORDER BY slot reachability set, if any.
325    #[must_use]
326    pub(in crate::db) fn order_referenced_slots(&self) -> Option<&[usize]> {
327        self.static_planning_shape()
328            .order_referenced_slots
329            .as_deref()
330    }
331
332    /// Borrow the planner-frozen resolved ORDER BY program, if one exists.
333    #[must_use]
334    pub(in crate::db) const fn resolved_order(&self) -> Option<&ResolvedOrder> {
335        self.static_planning_shape().resolved_order.as_ref()
336    }
337
338    /// Borrow the planner-frozen access slot map used by index predicate compilation.
339    #[must_use]
340    pub(in crate::db) fn slot_map(&self) -> Option<&[usize]> {
341        self.static_planning_shape().slot_map.as_deref()
342    }
343
344    /// Borrow grouped aggregate execution specs already resolved during static planning.
345    #[must_use]
346    pub(in crate::db) fn grouped_aggregate_execution_specs(
347        &self,
348    ) -> Option<&[GroupedAggregateExecutionSpec]> {
349        self.static_planning_shape()
350            .grouped_aggregate_execution_specs
351            .as_deref()
352    }
353
354    /// Borrow the planner-resolved grouped DISTINCT execution strategy when present.
355    #[must_use]
356    pub(in crate::db) const fn grouped_distinct_execution_strategy(
357        &self,
358    ) -> Option<&GroupedDistinctExecutionStrategy> {
359        self.static_planning_shape()
360            .grouped_distinct_execution_strategy
361            .as_ref()
362    }
363
364    /// Borrow the frozen projection semantic shape without reopening model ownership.
365    #[must_use]
366    pub(in crate::db) const fn frozen_projection_spec(&self) -> &ProjectionSpec {
367        &self.static_planning_shape().projection_spec
368    }
369
370    /// Borrow the frozen direct projection slots without reopening model ownership.
371    #[must_use]
372    pub(in crate::db) fn frozen_direct_projection_slots(&self) -> Option<&[usize]> {
373        self.static_planning_shape()
374            .projection_direct_slots
375            .as_deref()
376    }
377
378    /// Borrow the planner-frozen key-item-aware compile targets for the chosen access path.
379    #[must_use]
380    pub(in crate::db) fn index_compile_targets(&self) -> Option<&[IndexCompileTarget]> {
381        self.static_planning_shape()
382            .index_compile_targets
383            .as_deref()
384    }
385
386    const fn static_planning_shape(&self) -> &StaticPlanningShape {
387        self.static_planning_shape
388            .as_ref()
389            .expect("access-planned queries must freeze static planning shape before execution")
390    }
391}
392
393fn distinct_runtime_dedup_strategy<K>(access: &AccessPlan<K>) -> Option<DistinctExecutionStrategy> {
394    match access {
395        AccessPlan::Union(_) | AccessPlan::Intersection(_) => {
396            Some(DistinctExecutionStrategy::PreOrdered)
397        }
398        AccessPlan::Path(path) if path.as_ref().is_index_multi_lookup() => {
399            Some(DistinctExecutionStrategy::HashMaterialize)
400        }
401        AccessPlan::Path(_) => None,
402    }
403}
404
405fn derive_continuation_policy_validated(plan: &AccessPlannedQuery) -> ContinuationPolicy {
406    let is_grouped_safe = plan
407        .grouped_plan()
408        .is_none_or(|grouped| grouped_cursor_policy_violation(grouped, true).is_none());
409
410    ContinuationPolicy::new(
411        true, // Continuation resume windows require anchor semantics for pushdown-safe replay.
412        true, // Continuation resumes must advance strictly to prevent replay/regression loops.
413        is_grouped_safe,
414    )
415}
416
417/// Project one planner-owned route profile from the finalized logical+access plan.
418#[must_use]
419pub(in crate::db) fn project_planner_route_profile_for_model(
420    model: &EntityModel,
421    plan: &AccessPlannedQuery,
422) -> PlannerRouteProfile {
423    let secondary_order_contract = plan
424        .scalar_plan()
425        .order
426        .as_ref()
427        .and_then(|order| order.deterministic_secondary_order_contract(model.primary_key.name));
428
429    PlannerRouteProfile::new(
430        derive_continuation_policy_validated(plan),
431        derive_logical_pushdown_eligibility(plan, secondary_order_contract.as_ref()),
432        secondary_order_contract,
433    )
434}
435
436fn project_static_planning_shape_for_model(
437    model: &EntityModel,
438    plan: &AccessPlannedQuery,
439) -> Result<StaticPlanningShape, InternalError> {
440    let projection_spec = lower_projection_intent(model, &plan.logical, &plan.projection_selection);
441    let execution_preparation_compiled_predicate =
442        compile_optional_predicate(model, plan.execution_preparation_predicate().as_ref());
443    let effective_runtime_filter_program = compile_effective_runtime_filter_program(model, plan)?;
444    let scalar_projection_plan =
445        if plan.grouped_plan().is_none() {
446            Some(compile_scalar_projection_plan(model, &projection_spec).ok_or_else(|| {
447            InternalError::query_executor_invariant(
448                "scalar projection program must compile during static planning finalization",
449            )
450        })?)
451        } else {
452            None
453        };
454    let (grouped_aggregate_execution_specs, grouped_distinct_execution_strategy) =
455        resolve_grouped_static_planning_semantics(model, plan, &projection_spec)?;
456    let projection_direct_slots =
457        lower_direct_projection_slots(model, &plan.logical, &plan.projection_selection);
458    let projection_referenced_slots =
459        projection_referenced_slots_for_spec(model, &projection_spec)?;
460    let projected_slot_mask =
461        projected_slot_mask_for_spec(model, projection_direct_slots.as_deref());
462    let projection_is_model_identity =
463        projection_is_model_identity_for_spec(model, &projection_spec);
464    let resolved_order = resolved_order_for_plan(model, plan)?;
465    let order_referenced_slots = order_referenced_slots_for_resolved_order(resolved_order.as_ref());
466    let slot_map = slot_map_for_model_plan(model, plan);
467    let index_compile_targets = index_compile_targets_for_model_plan(model, plan);
468
469    Ok(StaticPlanningShape {
470        primary_key_name: model.primary_key.name,
471        projection_spec,
472        execution_preparation_compiled_predicate,
473        effective_runtime_filter_program,
474        scalar_projection_plan,
475        grouped_aggregate_execution_specs,
476        grouped_distinct_execution_strategy,
477        projection_direct_slots,
478        projection_referenced_slots,
479        projected_slot_mask,
480        projection_is_model_identity,
481        resolved_order,
482        order_referenced_slots,
483        slot_map,
484        index_compile_targets,
485    })
486}
487
488// Compile the executor-owned residual scalar filter contract once so runtime
489// can consume either the predicate fast path or the expression-first filter
490// path without rediscovering which boundary applies.
491fn compile_effective_runtime_filter_program(
492    model: &EntityModel,
493    plan: &AccessPlannedQuery,
494) -> Result<Option<EffectiveRuntimeFilterProgram>, InternalError> {
495    if !plan.has_residual_filter() {
496        return Ok(None);
497    }
498
499    // Keep the existing predicate fast path when the residual semantics still
500    // fit the derived predicate contract. The expression-owned lane is only
501    // needed once pushdown loses semantic coverage and a residual predicate no
502    // longer exists.
503    if let Some(predicate) = plan.effective_execution_predicate().as_ref() {
504        return Ok(Some(EffectiveRuntimeFilterProgram::Predicate(
505            PredicateProgram::compile(model, predicate),
506        )));
507    }
508
509    if let Some(filter_expr) = plan.scalar_plan().filter_expr.as_ref() {
510        let compiled = compile_scalar_projection_expr(model, filter_expr).ok_or_else(|| {
511            InternalError::query_invalid_logical_plan(
512                "effective runtime scalar filter expression must compile during static planning finalization",
513            )
514        })?;
515
516        return Ok(Some(EffectiveRuntimeFilterProgram::Expr(compiled)));
517    }
518
519    Ok(None)
520}
521
522// Compile one optional planner-frozen predicate program while keeping the
523// static planning assembly path free of repeated `Option` mapping boilerplate.
524fn compile_optional_predicate(
525    model: &EntityModel,
526    predicate: Option<&Predicate>,
527) -> Option<PredicateProgram> {
528    predicate.map(|predicate| PredicateProgram::compile(model, predicate))
529}
530
531// Resolve the grouped-only static planning semantics bundle once so grouped
532// aggregate execution specs and grouped DISTINCT strategy stay derived under
533// one shared grouped-plan branch.
534fn resolve_grouped_static_planning_semantics(
535    model: &EntityModel,
536    plan: &AccessPlannedQuery,
537    projection_spec: &ProjectionSpec,
538) -> Result<
539    (
540        Option<Vec<GroupedAggregateExecutionSpec>>,
541        Option<GroupedDistinctExecutionStrategy>,
542    ),
543    InternalError,
544> {
545    let Some(grouped) = plan.grouped_plan() else {
546        return Ok((None, None));
547    };
548
549    let mut aggregate_specs = grouped_aggregate_specs_from_projection_spec(
550        projection_spec,
551        grouped.group.group_fields.as_slice(),
552        grouped.group.aggregates.as_slice(),
553    )?;
554    extend_grouped_having_aggregate_specs(&mut aggregate_specs, grouped)?;
555
556    let grouped_aggregate_execution_specs = Some(grouped_aggregate_execution_specs(
557        model,
558        aggregate_specs.as_slice(),
559    )?);
560    let grouped_distinct_execution_strategy =
561        Some(resolved_grouped_distinct_execution_strategy_for_model(
562            model,
563            grouped.group.group_fields.as_slice(),
564            grouped.group.aggregates.as_slice(),
565            grouped.having_expr.as_ref(),
566        )?);
567
568    Ok((
569        grouped_aggregate_execution_specs,
570        grouped_distinct_execution_strategy,
571    ))
572}
573
574fn extend_grouped_having_aggregate_specs(
575    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
576    grouped: &GroupPlan,
577) -> Result<(), InternalError> {
578    if let Some(having_expr) = grouped.having_expr.as_ref() {
579        collect_grouped_having_expr_aggregate_specs(aggregate_specs, having_expr)?;
580    }
581
582    Ok(())
583}
584
585fn collect_grouped_having_expr_aggregate_specs(
586    aggregate_specs: &mut Vec<GroupedAggregateExecutionSpec>,
587    expr: &Expr,
588) -> Result<(), InternalError> {
589    match expr {
590        Expr::Aggregate(aggregate_expr) => {
591            let aggregate_spec = GroupedAggregateExecutionSpec::from_aggregate_expr(aggregate_expr);
592
593            if aggregate_specs
594                .iter()
595                .all(|current| current != &aggregate_spec)
596            {
597                aggregate_specs.push(aggregate_spec);
598            }
599        }
600        Expr::Field(_) | Expr::Literal(_) => {}
601        Expr::FunctionCall { args, .. } => {
602            for arg in args {
603                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arg)?;
604            }
605        }
606        Expr::Unary { expr, .. } => {
607            collect_grouped_having_expr_aggregate_specs(aggregate_specs, expr)?;
608        }
609        Expr::Case {
610            when_then_arms,
611            else_expr,
612        } => {
613            for arm in when_then_arms {
614                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arm.condition())?;
615                collect_grouped_having_expr_aggregate_specs(aggregate_specs, arm.result())?;
616            }
617
618            collect_grouped_having_expr_aggregate_specs(aggregate_specs, else_expr)?;
619        }
620        Expr::Binary { left, right, .. } => {
621            collect_grouped_having_expr_aggregate_specs(aggregate_specs, left)?;
622            collect_grouped_having_expr_aggregate_specs(aggregate_specs, right)?;
623        }
624        #[cfg(test)]
625        Expr::Alias { expr, .. } => {
626            collect_grouped_having_expr_aggregate_specs(aggregate_specs, expr)?;
627        }
628    }
629
630    Ok(())
631}
632
633fn projection_referenced_slots_for_spec(
634    model: &EntityModel,
635    projection: &ProjectionSpec,
636) -> Result<Vec<usize>, InternalError> {
637    let mut referenced = vec![false; model.fields().len()];
638
639    for field in projection.fields() {
640        mark_projection_expr_slots(
641            model,
642            projection_field_expr(field),
643            referenced.as_mut_slice(),
644        )?;
645    }
646
647    Ok(referenced
648        .into_iter()
649        .enumerate()
650        .filter_map(|(slot, required)| required.then_some(slot))
651        .collect())
652}
653
654fn mark_projection_expr_slots(
655    model: &EntityModel,
656    expr: &Expr,
657    referenced: &mut [bool],
658) -> Result<(), InternalError> {
659    match expr {
660        Expr::Field(field_id) => {
661            let field_name = field_id.as_str();
662            let slot = resolve_required_field_slot(model, field_name, || {
663                InternalError::query_invalid_logical_plan(format!(
664                    "projection expression references unknown field '{field_name}'",
665                ))
666            })?;
667            referenced[slot] = true;
668        }
669        Expr::Literal(_) => {}
670        Expr::FunctionCall { args, .. } => {
671            for arg in args {
672                mark_projection_expr_slots(model, arg, referenced)?;
673            }
674        }
675        Expr::Case {
676            when_then_arms,
677            else_expr,
678        } => {
679            for arm in when_then_arms {
680                mark_projection_expr_slots(model, arm.condition(), referenced)?;
681                mark_projection_expr_slots(model, arm.result(), referenced)?;
682            }
683            mark_projection_expr_slots(model, else_expr.as_ref(), referenced)?;
684        }
685        Expr::Aggregate(_) => {}
686        #[cfg(test)]
687        Expr::Alias { expr, .. } => {
688            mark_projection_expr_slots(model, expr.as_ref(), referenced)?;
689        }
690        Expr::Unary { expr, .. } => {
691            mark_projection_expr_slots(model, expr.as_ref(), referenced)?;
692        }
693        Expr::Binary { left, right, .. } => {
694            mark_projection_expr_slots(model, left.as_ref(), referenced)?;
695            mark_projection_expr_slots(model, right.as_ref(), referenced)?;
696        }
697    }
698
699    Ok(())
700}
701
702fn projected_slot_mask_for_spec(
703    model: &EntityModel,
704    direct_projection_slots: Option<&[usize]>,
705) -> Vec<bool> {
706    let mut projected_slots = vec![false; model.fields().len()];
707
708    let Some(direct_projection_slots) = direct_projection_slots else {
709        return projected_slots;
710    };
711
712    for slot in direct_projection_slots.iter().copied() {
713        if let Some(projected) = projected_slots.get_mut(slot) {
714            *projected = true;
715        }
716    }
717
718    projected_slots
719}
720
721fn projection_is_model_identity_for_spec(model: &EntityModel, projection: &ProjectionSpec) -> bool {
722    if projection.len() != model.fields().len() {
723        return false;
724    }
725
726    for (field_model, projected_field) in model.fields().iter().zip(projection.fields()) {
727        match projected_field {
728            ProjectionField::Scalar {
729                expr: Expr::Field(field_id),
730                alias: None,
731            } if field_id.as_str() == field_model.name() => {}
732            ProjectionField::Scalar { .. } => return false,
733        }
734    }
735
736    true
737}
738
739fn resolved_order_for_plan(
740    model: &EntityModel,
741    plan: &AccessPlannedQuery,
742) -> Result<Option<ResolvedOrder>, InternalError> {
743    if grouped_plan_strategy(plan).is_some_and(GroupedPlanStrategy::is_top_k_group) {
744        return Ok(None);
745    }
746
747    let Some(order) = plan.scalar_plan().order.as_ref() else {
748        return Ok(None);
749    };
750
751    let mut fields = Vec::with_capacity(order.fields.len());
752    for term in &order.fields {
753        fields.push(ResolvedOrderField::new(
754            resolved_order_value_source_for_term(model, term)?,
755            term.direction(),
756        ));
757    }
758
759    Ok(Some(ResolvedOrder::new(fields)))
760}
761
762fn resolved_order_value_source_for_term(
763    model: &EntityModel,
764    term: &crate::db::query::plan::OrderTerm,
765) -> Result<ResolvedOrderValueSource, InternalError> {
766    if term.direct_field().is_none() {
767        let rendered = term.rendered_label();
768        validate_resolved_order_expr_fields(model, term.expr(), rendered.as_str())?;
769        let compiled = compile_scalar_projection_expr(model, term.expr())
770            .ok_or_else(|| order_expression_scalar_seam_error(rendered.as_str()))?;
771
772        return Ok(ResolvedOrderValueSource::expression(compiled));
773    }
774
775    let field = term
776        .direct_field()
777        .expect("direct-field order branch should only execute for field-backed terms");
778    let slot = resolve_required_field_slot(model, field, || {
779        InternalError::query_invalid_logical_plan(format!(
780            "order expression references unknown field '{field}'",
781        ))
782    })?;
783
784    Ok(ResolvedOrderValueSource::direct_field(slot))
785}
786
787fn validate_resolved_order_expr_fields(
788    model: &EntityModel,
789    expr: &Expr,
790    rendered: &str,
791) -> Result<(), InternalError> {
792    match expr {
793        Expr::Field(field_id) => {
794            resolve_required_field_slot(model, field_id.as_str(), || {
795                InternalError::query_invalid_logical_plan(format!(
796                    "order expression references unknown field '{rendered}'",
797                ))
798            })?;
799        }
800        Expr::Literal(_) => {}
801        Expr::FunctionCall { args, .. } => {
802            for arg in args {
803                validate_resolved_order_expr_fields(model, arg, rendered)?;
804            }
805        }
806        Expr::Case {
807            when_then_arms,
808            else_expr,
809        } => {
810            for arm in when_then_arms {
811                validate_resolved_order_expr_fields(model, arm.condition(), rendered)?;
812                validate_resolved_order_expr_fields(model, arm.result(), rendered)?;
813            }
814            validate_resolved_order_expr_fields(model, else_expr.as_ref(), rendered)?;
815        }
816        Expr::Binary { left, right, .. } => {
817            validate_resolved_order_expr_fields(model, left.as_ref(), rendered)?;
818            validate_resolved_order_expr_fields(model, right.as_ref(), rendered)?;
819        }
820        Expr::Aggregate(_) => {
821            return Err(order_expression_scalar_seam_error(rendered));
822        }
823        #[cfg(test)]
824        Expr::Alias { .. } => {
825            return Err(order_expression_scalar_seam_error(rendered));
826        }
827        Expr::Unary { .. } => {
828            return Err(order_expression_scalar_seam_error(rendered));
829        }
830    }
831
832    Ok(())
833}
834
835// Resolve one model field slot while keeping planner invalid-logical-plan
836// error construction at the callsite that owns the diagnostic wording.
837fn resolve_required_field_slot<F>(
838    model: &EntityModel,
839    field: &str,
840    invalid_plan_error: F,
841) -> Result<usize, InternalError>
842where
843    F: FnOnce() -> InternalError,
844{
845    resolve_field_slot(model, field).ok_or_else(invalid_plan_error)
846}
847
848// Keep the scalar-order expression seam violation text under one helper so the
849// parse validation and compile validation paths do not drift.
850fn order_expression_scalar_seam_error(rendered: &str) -> InternalError {
851    InternalError::query_invalid_logical_plan(format!(
852        "order expression '{rendered}' did not stay on the scalar expression seam",
853    ))
854}
855
856// Keep one stable executor-facing slot list for grouped order terms after the
857// planner has frozen the structural `ResolvedOrder`. The grouped Top-K route
858// now consumes this same referenced-slot contract instead of re-deriving order
859// sources from planner strategy at runtime.
860fn order_referenced_slots_for_resolved_order(
861    resolved_order: Option<&ResolvedOrder>,
862) -> Option<Vec<usize>> {
863    let resolved_order = resolved_order?;
864    let mut referenced = Vec::new();
865
866    // Keep one stable slot list without re-parsing order expressions after the
867    // planner has already frozen structural ORDER BY sources.
868    for field in resolved_order.fields() {
869        field.source().extend_referenced_slots(&mut referenced);
870    }
871
872    Some(referenced)
873}
874
875fn slot_map_for_model_plan(model: &EntityModel, plan: &AccessPlannedQuery) -> Option<Vec<usize>> {
876    let access_strategy = plan.access.resolve_strategy();
877    let executable = access_strategy.executable();
878
879    resolved_index_slots_for_access_path(model, executable)
880}
881
882fn resolved_index_slots_for_access_path(
883    model: &EntityModel,
884    access: &ExecutableAccessPlan<'_, crate::value::Value>,
885) -> Option<Vec<usize>> {
886    let path = access.as_path()?;
887    let path_capabilities = path.capabilities();
888    let index_fields = path_capabilities.index_fields_for_slot_map()?;
889    let mut slots = Vec::with_capacity(index_fields.len());
890
891    for field_name in index_fields {
892        let slot = resolve_field_slot(model, field_name)?;
893        slots.push(slot);
894    }
895
896    Some(slots)
897}
898
899fn index_compile_targets_for_model_plan(
900    model: &EntityModel,
901    plan: &AccessPlannedQuery,
902) -> Option<Vec<IndexCompileTarget>> {
903    let index = plan.access.as_path()?.selected_index_model()?;
904    let mut targets = Vec::new();
905
906    match index.key_items() {
907        IndexKeyItemsRef::Fields(fields) => {
908            for (component_index, &field_name) in fields.iter().enumerate() {
909                let field_slot = resolve_field_slot(model, field_name)?;
910                targets.push(IndexCompileTarget {
911                    component_index,
912                    field_slot,
913                    key_item: crate::model::index::IndexKeyItem::Field(field_name),
914                });
915            }
916        }
917        IndexKeyItemsRef::Items(items) => {
918            for (component_index, &key_item) in items.iter().enumerate() {
919                let field_slot = resolve_field_slot(model, key_item.field())?;
920                targets.push(IndexCompileTarget {
921                    component_index,
922                    field_slot,
923                    key_item,
924                });
925            }
926        }
927    }
928
929    Some(targets)
930}