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