Skip to main content

hawdb_plan_cache/
template.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4use hawdb_core::{HawDBError, Result, Value};
5use hawdb_cypher as cypher;
6use hawdb_plan_cypher::{
7    self as planner, AggregateTarget, Aggregation, GraphMatchStep, LogicalPlan, PathFunction,
8    PhysicalPlan, Predicate, Projection, ProjectionExpression, RelationshipCountFilter, SortItem,
9    SortKey,
10};
11use std::collections::{BTreeMap, BTreeSet};
12use std::hash::{Hash, Hasher};
13use std::sync::Arc;
14
15const PARAMETER_SLOT_NAME_KEY: &str = "\0skein_parameter_slot";
16const PARAMETER_SLOT_PATH_KEY: &str = "\0skein_parameter_path";
17
18mod retained;
19
20#[derive(Debug, Clone)]
21enum ParameterCacheValue {
22    Slot(ParameterValueShape),
23    CaseSlot(ParameterValueShape),
24    Exact(Value),
25}
26
27// Numeric equality intentionally ignores Decimal scale. A folded cached result
28// must also preserve its representation, including decimals inside containers.
29fn exact_value_cmp(left: &Value, right: &Value) -> std::cmp::Ordering {
30    left.cmp(right).then_with(|| match (left, right) {
31        (Value::Decimal(left), Value::Decimal(right)) => left.scale().cmp(&right.scale()),
32        (Value::List(left), Value::List(right)) => left
33            .iter()
34            .zip(right)
35            .map(|(left, right)| exact_value_cmp(left, right))
36            .find(|order| !order.is_eq())
37            .unwrap_or(std::cmp::Ordering::Equal),
38        (Value::Map(left), Value::Map(right)) => left
39            .values()
40            .zip(right.values())
41            .map(|(left, right)| exact_value_cmp(left, right))
42            .find(|order| !order.is_eq())
43            .unwrap_or(std::cmp::Ordering::Equal),
44        _ => std::cmp::Ordering::Equal,
45    })
46}
47
48fn exact_scale_hash(value: &Value, state: &mut impl Hasher) {
49    match value {
50        Value::Decimal(value) => value.scale().hash(state),
51        Value::List(values) => values
52            .iter()
53            .for_each(|value| exact_scale_hash(value, state)),
54        Value::Map(values) => values
55            .values()
56            .for_each(|value| exact_scale_hash(value, state)),
57        _ => {}
58    }
59}
60
61impl PartialEq for ParameterCacheValue {
62    fn eq(&self, other: &Self) -> bool {
63        self.cmp(other).is_eq()
64    }
65}
66impl Eq for ParameterCacheValue {}
67impl PartialOrd for ParameterCacheValue {
68    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
69        Some(self.cmp(other))
70    }
71}
72impl Ord for ParameterCacheValue {
73    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
74        use std::cmp::Ordering;
75        match (self, other) {
76            (Self::Slot(left), Self::Slot(right))
77            | (Self::CaseSlot(left), Self::CaseSlot(right)) => left.cmp(right),
78            (Self::Exact(left), Self::Exact(right)) => exact_value_cmp(left, right),
79            (Self::Slot(_), _) | (Self::CaseSlot(_), Self::Exact(_)) => Ordering::Less,
80            _ => Ordering::Greater,
81        }
82    }
83}
84impl Hash for ParameterCacheValue {
85    fn hash<H: Hasher>(&self, state: &mut H) {
86        match self {
87            Self::Slot(value) => {
88                0u8.hash(state);
89                value.hash(state);
90            }
91            Self::CaseSlot(value) => {
92                1u8.hash(state);
93                value.hash(state);
94            }
95            Self::Exact(value) => {
96                2u8.hash(state);
97                value.hash(state);
98                exact_scale_hash(value, state);
99            }
100        }
101    }
102}
103
104impl ParameterCacheValue {
105    fn validate_slot_use(&mut self, marker_use: MarkerUse) -> bool {
106        if matches!(self, Self::Exact(_)) {
107            return true;
108        }
109        if !marker_use.is_safe() {
110            return false;
111        }
112        // Reclassify after all exact guards have been restored. A planner
113        // rewrite may move a slot into or out of CASE without changing its
114        // validity domain; its physical retention policy must follow that move.
115        *self = match std::mem::replace(self, Self::Exact(Value::Null)) {
116            Self::Slot(shape) | Self::CaseSlot(shape) => {
117                if marker_use == MarkerUse::SafeCase {
118                    Self::CaseSlot(shape)
119                } else {
120                    Self::Slot(shape)
121                }
122            }
123            exact @ Self::Exact(_) => exact,
124        };
125        true
126    }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
130enum ParameterValueShape {
131    Null,
132    Bool,
133    Int,
134    Float,
135    Decimal(hawdb_core::DecimalType),
136    String,
137    Binary,
138    Vector(hawdb_core::VectorDimension),
139    Uuid,
140    Date,
141    LocalTime,
142    LocalDateTime,
143    DateTime,
144    Duration,
145    List(Vec<ParameterValueShape>),
146    Map(BTreeMap<String, ParameterValueShape>),
147}
148
149#[derive(Debug, Clone, PartialEq)]
150pub struct ParameterizedLogicalPlan {
151    // Immutable proven state is shared by cache admission and readers.
152    // Cloning a handle must not deep-copy the marker tree or exact guards.
153    logical: Arc<LogicalPlan>,
154    cache_key: Arc<PlanParameterCacheKey>,
155    slot_count: usize,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
159pub struct PlanParameterCacheKey {
160    values: BTreeMap<String, ParameterCacheValue>,
161}
162
163/// A proven logical template and its complete parameter validity boundary.
164/// Schema, statistics, access control and scoring remain physical-cache keys.
165#[derive(Debug, Clone, PartialEq)]
166#[doc(hidden)]
167pub struct ParameterBindingTemplate {
168    plan: ParameterizedLogicalPlan,
169}
170
171impl ParameterBindingTemplate {
172    /// Conservative requested heap retained by this template, including Arc
173    /// allocations even when shared with another owner. Unknown plan shapes or
174    /// arithmetic overflow decline admission instead of undercharging.
175    pub fn retained_heap_bytes(&self) -> Option<usize> {
176        retained::template_bytes(self)
177    }
178
179    pub fn new(
180        plan: &ParameterizedLogicalPlan,
181        parameters: &BTreeMap<String, Value>,
182    ) -> Option<Self> {
183        // An omitted binding may influence planning without leaving a marker.
184        // Do not infer its validity domain or retain unused request payloads.
185        (plan.cache_key.values.len() == parameters.len()).then(|| Self { plan: plan.clone() })
186    }
187
188    pub fn reuse(&self, parameters: &BTreeMap<String, Value>) -> Option<ParameterizedLogicalPlan> {
189        if self.plan.cache_key.values.len() != parameters.len()
190            || parameters.values().any(value_contains_any_marker)
191            || self.plan.cache_key.values.iter().any(|(name, cached)| {
192                parameters.get(name).is_none_or(|value| match cached {
193                    ParameterCacheValue::Slot(shape) | ParameterCacheValue::CaseSlot(shape) => {
194                        !shape.matches(value)
195                    }
196                    ParameterCacheValue::Exact(expected) => {
197                        !exact_value_cmp(value, expected).is_eq()
198                    }
199                })
200            })
201        {
202            return None;
203        }
204        Some(self.plan.clone())
205    }
206}
207
208impl ParameterValueShape {
209    fn matches(&self, value: &Value) -> bool {
210        match (self, value) {
211            (Self::Null, Value::Null)
212            | (Self::Bool, Value::Bool(_))
213            | (Self::Int, Value::Int(_))
214            | (Self::Float, Value::Float(_))
215            | (Self::String, Value::String(_))
216            | (Self::Binary, Value::Binary(_))
217            | (Self::Uuid, Value::Uuid(_))
218            | (Self::Date, Value::Date(_))
219            | (Self::LocalTime, Value::LocalTime(_))
220            | (Self::LocalDateTime, Value::LocalDateTime(_))
221            | (Self::DateTime, Value::DateTime(_))
222            | (Self::Duration, Value::Duration(_)) => true,
223            (Self::Vector(dimension), Value::Vector(value)) => *dimension == value.dimension(),
224            (Self::Decimal(kind), Value::Decimal(value)) => *kind == value.decimal_type(),
225            (Self::List(shapes), Value::List(values)) => {
226                shapes.len() == values.len()
227                    && shapes
228                        .iter()
229                        .zip(values)
230                        .all(|(shape, value)| shape.matches(value))
231            }
232            (Self::Map(shapes), Value::Map(values)) => {
233                shapes.len() == values.len()
234                    && shapes
235                        .iter()
236                        .zip(values)
237                        .all(|((key, shape), (name, value))| key == name && shape.matches(value))
238            }
239            _ => false,
240        }
241    }
242}
243
244/// Allocation-free cache bucket selector. A collision can only cause a miss:
245/// the template must still validate every shape and exact folded dependency.
246#[doc(hidden)]
247pub fn parameter_binding_shape_fingerprint(parameters: &BTreeMap<String, Value>) -> u64 {
248    fn visit(value: &Value, state: &mut impl Hasher) {
249        std::mem::discriminant(value).hash(state);
250        match value {
251            Value::List(values) => {
252                values.len().hash(state);
253                for value in values {
254                    visit(value, state);
255                }
256            }
257            Value::Map(values) => {
258                values.len().hash(state);
259                for (key, value) in values {
260                    key.hash(state);
261                    visit(value, state);
262                }
263            }
264            Value::Vector(value) => value.dimension().hash(state),
265            Value::Decimal(value) => value.decimal_type().hash(state),
266            _ => {}
267        }
268    }
269    let mut state = std::collections::hash_map::DefaultHasher::new();
270    parameters.len().hash(&mut state);
271    for (name, value) in parameters {
272        name.hash(&mut state);
273        visit(value, &mut state);
274    }
275    state.finish()
276}
277
278impl ParameterizedLogicalPlan {
279    /// CASE marker trees stay in the byte-budgeted logical cache. Physical
280    /// copies remain request-owned until the physical cache has a byte budget.
281    pub fn has_case_parameter_slots(&self) -> bool {
282        self.cache_key
283            .values
284            .values()
285            .any(|value| matches!(value, ParameterCacheValue::CaseSlot(_)))
286    }
287
288    pub fn logical(&self) -> &LogicalPlan {
289        &self.logical
290    }
291
292    pub fn cache_key(&self) -> &PlanParameterCacheKey {
293        &self.cache_key
294    }
295
296    pub fn slot_count(&self) -> usize {
297        self.slot_count
298    }
299
300    pub fn exact_variant_count(&self) -> usize {
301        self.cache_key.values.len() - self.slot_count
302    }
303}
304
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306enum MarkerUse {
307    None,
308    Safe,
309    SafeCase,
310    Unsafe,
311}
312
313#[cfg(test)]
314thread_local! {
315    static PARAMETER_PLANNING_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
316}
317
318fn plan_parameter_bindings(
319    statement: &cypher::Statement,
320    parameters: &BTreeMap<String, Value>,
321) -> Result<LogicalPlan> {
322    #[cfg(test)]
323    PARAMETER_PLANNING_CALLS.with(|calls| calls.set(calls.get() + 1));
324    planner::plan_with_params(statement, parameters)
325}
326
327impl MarkerUse {
328    fn is_safe(self) -> bool {
329        matches!(self, Self::Safe | Self::SafeCase)
330    }
331
332    fn cache_value(self, value: &Value) -> ParameterCacheValue {
333        match self {
334            Self::SafeCase => ParameterCacheValue::CaseSlot(parameter_value_shape(value)),
335            Self::Safe => ParameterCacheValue::Slot(parameter_value_shape(value)),
336            Self::None | Self::Unsafe => ParameterCacheValue::Exact(value.clone()),
337        }
338    }
339
340    fn combine(self, other: Self) -> Self {
341        match (self, other) {
342            (Self::Unsafe, _) | (_, Self::Unsafe) => Self::Unsafe,
343            (Self::SafeCase, _) | (_, Self::SafeCase) => Self::SafeCase,
344            (Self::Safe, _) | (_, Self::Safe) => Self::Safe,
345            (Self::None, Self::None) => Self::None,
346        }
347    }
348}
349
350pub fn parameterize_logical_plan(
351    statement: &cypher::Statement,
352    parameters: &BTreeMap<String, Value>,
353) -> Result<ParameterizedLogicalPlan> {
354    let actual = plan_parameter_bindings(statement, parameters)?;
355    if parameters.values().any(value_contains_any_marker) {
356        return Ok(ParameterizedLogicalPlan {
357            logical: Arc::new(actual),
358            cache_key: Arc::new(PlanParameterCacheKey {
359                values: parameters
360                    .iter()
361                    .map(|(name, value)| (name.clone(), ParameterCacheValue::Exact(value.clone())))
362                    .collect(),
363            }),
364            slot_count: 0,
365        });
366    }
367    if parameters.is_empty() {
368        return Ok(ParameterizedLogicalPlan {
369            logical: Arc::new(actual),
370            cache_key: Arc::new(PlanParameterCacheKey {
371                values: BTreeMap::new(),
372            }),
373            slot_count: 0,
374        });
375    }
376    let folded_parameters = folded_predicate_parameters(statement);
377    if let Some(parameterized) =
378        parameterize_together(statement, parameters, &actual, &folded_parameters)
379    {
380        return Ok(parameterized);
381    }
382    let mut template_parameters = parameters.clone();
383    let mut cache_values = BTreeMap::new();
384    let mut slot_count = 0;
385
386    for (name, value) in parameters {
387        if folded_parameters.contains(name) {
388            cache_values.insert(name.clone(), ParameterCacheValue::Exact(value.clone()));
389            continue;
390        }
391        let marker = parameter_marker(name, value, &[]);
392        let mut candidate_parameters = parameters.clone();
393        candidate_parameters.insert(name.clone(), marker.clone());
394        let candidate = plan_parameter_bindings(statement, &candidate_parameters).ok();
395        if candidate.as_ref().is_some_and(|candidate| {
396            marker_use_in_logical_plan(candidate, name) == MarkerUse::None && candidate == &actual
397        }) {
398            // Prove all omissions together below. Absence from one marked plan
399            // alone does not establish that removing the binding is harmless.
400            template_parameters.remove(name);
401            continue;
402        }
403        let marker_use = candidate.map_or(MarkerUse::Unsafe, |mut candidate| {
404            let marker_use = marker_use_in_logical_plan(&candidate, name);
405            if marker_use.is_safe()
406                && bind_logical_plan(&mut candidate, BindingAction::Execute(parameters)).is_ok()
407                && candidate == actual
408            {
409                marker_use
410            } else {
411                MarkerUse::Unsafe
412            }
413        });
414        if marker_use.is_safe() {
415            template_parameters.insert(name.clone(), marker);
416            cache_values.insert(name.clone(), marker_use.cache_value(value));
417            slot_count += 1;
418        } else {
419            cache_values.insert(name.clone(), ParameterCacheValue::Exact(value.clone()));
420        }
421    }
422
423    let logical = if slot_count == 0 && template_parameters.len() == parameters.len() {
424        actual.clone()
425    } else {
426        let candidate = plan_parameter_bindings(statement, &template_parameters)
427            .ok()
428            .filter(|candidate| {
429                let all_slots_are_safe = cache_values.iter_mut().all(|(name, cached)| {
430                    matches!(cached, ParameterCacheValue::Exact(_))
431                        || cached.validate_slot_use(marker_use_in_logical_plan(candidate, name))
432                });
433                let mut rebound = candidate.clone();
434                all_slots_are_safe
435                    && bind_logical_plan(&mut rebound, BindingAction::Execute(parameters)).is_ok()
436                    && rebound == actual
437            });
438        if let Some(candidate) = candidate {
439            candidate
440        } else {
441            cache_values = parameters
442                .iter()
443                .map(|(name, value)| (name.clone(), ParameterCacheValue::Exact(value.clone())))
444                .collect();
445            slot_count = 0;
446            actual.clone()
447        }
448    };
449    Ok(ParameterizedLogicalPlan {
450        logical: Arc::new(logical),
451        cache_key: Arc::new(PlanParameterCacheKey {
452            values: cache_values,
453        }),
454        slot_count,
455    })
456}
457
458/// Prove a complete binding wave before trying individual parameters. Some
459/// syntactic positions (for example LIMIT) cannot accept markers; those retain
460/// the conservative per-parameter path below. Exact values and omissions are
461/// checked together by rebinding the completed template to the actual plan.
462fn parameterize_together(
463    statement: &cypher::Statement,
464    parameters: &BTreeMap<String, Value>,
465    actual: &LogicalPlan,
466    folded_parameters: &BTreeSet<String>,
467) -> Option<ParameterizedLogicalPlan> {
468    let mut template_parameters = parameters
469        .iter()
470        .map(|(name, value)| {
471            (
472                name.clone(),
473                if folded_parameters.contains(name) {
474                    value.clone()
475                } else {
476                    parameter_marker(name, value, &[])
477                },
478            )
479        })
480        .collect::<BTreeMap<_, _>>();
481    let marked = plan_parameter_bindings(statement, &template_parameters).ok()?;
482    let mut values = BTreeMap::new();
483    let mut slot_count = 0;
484    let mut changed = false;
485    for (name, value) in parameters {
486        match marker_use_in_logical_plan(&marked, name) {
487            marker_use @ (MarkerUse::Safe | MarkerUse::SafeCase) => {
488                values.insert(name.clone(), marker_use.cache_value(value));
489                slot_count += 1;
490            }
491            MarkerUse::None if folded_parameters.contains(name) => {
492                // Predicate binding erased these markers. Preserve the exact
493                // inputs even when other occurrences could remain slots.
494                template_parameters.insert(name.clone(), value.clone());
495                values.insert(name.clone(), ParameterCacheValue::Exact(value.clone()));
496                changed = true;
497            }
498            MarkerUse::None => {
499                template_parameters.remove(name);
500                changed = true;
501            }
502            MarkerUse::Unsafe => {
503                template_parameters.insert(name.clone(), value.clone());
504                values.insert(name.clone(), ParameterCacheValue::Exact(value.clone()));
505                changed = true;
506            }
507        }
508    }
509    let logical = if changed {
510        plan_parameter_bindings(statement, &template_parameters).ok()?
511    } else {
512        marked
513    };
514    // Restoring exact inputs must not turn a previously safe marker into a
515    // value-dependent specialized expression.
516    if !values.iter_mut().all(|(name, value)| {
517        matches!(value, ParameterCacheValue::Exact(_))
518            || value.validate_slot_use(marker_use_in_logical_plan(&logical, name))
519    }) {
520        return None;
521    }
522    let mut rebound = logical.clone();
523    bind_logical_plan(&mut rebound, BindingAction::Execute(parameters)).ok()?;
524    if &rebound != actual {
525        return None;
526    }
527    Some(ParameterizedLogicalPlan {
528        logical: Arc::new(logical),
529        cache_key: Arc::new(PlanParameterCacheKey { values }),
530        slot_count,
531    })
532}
533
534/// Binding folds these predicate inputs before their markers can reach the
535/// logical plan. Another use (notably simple CASE) may still retain a marker;
536/// logical marker presence therefore cannot prove the input's whole domain.
537fn folded_predicate_parameters(statement: &cypher::Statement) -> BTreeSet<String> {
538    fn collect_value(value: &cypher::ValueExpression, exact: &mut BTreeSet<String>) {
539        match &value.kind {
540            cypher::ValueExpressionKind::Parameter(name) => {
541                exact.insert(name.clone());
542            }
543            cypher::ValueExpressionKind::List(values) => {
544                for item in values {
545                    collect_value(item, exact);
546                }
547            }
548            cypher::ValueExpressionKind::Timestamp(inner)
549            | cypher::ValueExpressionKind::Conversion {
550                argument: inner, ..
551            } => collect_value(inner, exact),
552            // Temporal calls are evaluated while binding: like `timestamp()`,
553            // their inputs are folded and must be exact cache keys.
554            cypher::ValueExpressionKind::Temporal { arguments, .. } => {
555                for argument in arguments {
556                    collect_value(argument, exact);
557                }
558            }
559            cypher::ValueExpressionKind::Map(entries) => {
560                for value in entries.values() {
561                    collect_value(value, exact);
562                }
563            }
564            cypher::ValueExpressionKind::Literal(_)
565            | cypher::ValueExpressionKind::Binding(_)
566            | cypher::ValueExpressionKind::BindingProperty { .. }
567            | cypher::ValueExpressionKind::BindingIndex { .. }
568            | cypher::ValueExpressionKind::CurrentTimestamp => {}
569        }
570    }
571    fn collect_predicate(predicate: &cypher::PropertyPredicate, exact: &mut BTreeSet<String>) {
572        use cypher::PropertyPredicate as P;
573        match predicate {
574            P::And(items) | P::Or(items) => {
575                for item in items {
576                    collect_predicate(item, exact);
577                }
578            }
579            P::Not(inner) => collect_predicate(inner, exact),
580            P::ParameterEq { left, right } | P::ParameterNotEq { left, right } => {
581                exact.insert(left.clone());
582                collect_value(right, exact);
583            }
584            P::RelationshipExists { .. }
585            | P::BoundRelationshipExists { .. }
586            | P::IdEq { .. }
587            | P::IdNotEq { .. }
588            | P::IdCompare { .. }
589            | P::IdIn { .. }
590            | P::Eq { .. }
591            | P::NotEq { .. }
592            | P::Compare { .. }
593            | P::ExpressionEq { .. }
594            | P::ExpressionNotEq { .. }
595            | P::ExpressionCompare { .. }
596            | P::ExpressionContains { .. }
597            | P::ExpressionIn { .. }
598            | P::ListContains { .. }
599            | P::ListContainsLower { .. }
600            | P::Contains { .. }
601            | P::StartsWith { .. }
602            | P::EndsWith { .. }
603            | P::RegexMatch { .. }
604            // Nullness is already fixed by the complete parameter shape.
605            | P::ParameterIsNull { .. }
606            | P::ParameterIsNotNull { .. }
607            | P::IsNull { .. }
608            | P::IsNotNull { .. }
609            | P::In { .. } => {}
610        }
611    }
612    fn pipeline(query: &cypher::QueryPipeline, exact: &mut BTreeSet<String>) {
613        for clause in &query.clauses {
614            let condition = match &clause.kind {
615                cypher::ClauseKind::Match { predicate, .. } => predicate.as_ref(),
616                cypher::ClauseKind::With(projection) | cypher::ClauseKind::Return(projection) => {
617                    projection.predicate.as_ref()
618                }
619                _ => None,
620            };
621            if let Some(condition) = condition {
622                collect_predicate(&condition.kind, exact);
623            }
624        }
625    }
626    let mut exact = BTreeSet::new();
627    match statement {
628        cypher::Statement::Pipeline(query) | cypher::Statement::UnwindMutation(query) => {
629            pipeline(query, &mut exact)
630        }
631        cypher::Statement::CypherQuery(query) => {
632            return folded_predicate_parameters(&query.statement)
633        }
634        cypher::Statement::Explain(explain) => {
635            return folded_predicate_parameters(&explain.statement)
636        }
637        cypher::Statement::ProjectGraph(query) => {
638            for condition in query.relationship_predicates.values() {
639                collect_predicate(condition, &mut exact);
640            }
641        }
642        _ => {}
643    }
644    exact
645}
646
647/// Creates internal parameter markers for a list whose shape is part of a
648/// cached plan while its values are bound for every execution.
649///
650/// The caller must include `Value::List(values.to_vec())` under `name` when
651/// calling `bind_physical_plan_parameters`.
652pub fn parameterize_value_list(name: &str, values: &[Value]) -> Vec<Value> {
653    match parameter_marker(name, &Value::List(values.to_vec()), &[]) {
654        Value::List(markers) => markers,
655        _ => unreachable!("list parameterization always produces a list"),
656    }
657}
658
659pub fn bind_physical_plan_parameters(
660    template: &PhysicalPlan,
661    parameters: &BTreeMap<String, Value>,
662    has_slots: bool,
663) -> Result<PhysicalPlan> {
664    let mut plan = template.clone();
665    if has_slots {
666        bind_physical_plan(&mut plan, BindingAction::Execute(parameters))?;
667    }
668    Ok(plan)
669}
670
671/// Resolves a borrowed cost input from the same template as the physical plan.
672/// Keep marker interpretation here so planning never reconstructs its encoding.
673#[doc(hidden)]
674pub fn resolve_plan_template_value<'a>(
675    template: &'a Value,
676    parameters: &'a BTreeMap<String, Value>,
677    has_slots: bool,
678) -> Result<&'a Value> {
679    if has_slots && let Some((name, path)) = marker_name_and_path(template) {
680        return resolve_parameter_marker(parameters, name, path);
681    }
682    Ok(template)
683}
684
685/// Returns scalar type proofs using the same private marker owner as binding.
686/// The caller must use a parameterized plan whose cache key retains value shapes.
687#[doc(hidden)]
688pub fn parameter_scalar_types(
689    plan: &ParameterizedLogicalPlan,
690    parameters: &BTreeMap<String, Value>,
691) -> BTreeMap<Value, hawdb_core::PropertyType> {
692    fn visit(
693        name: &str,
694        value: &Value,
695        path: &mut Vec<usize>,
696        output: &mut BTreeMap<Value, hawdb_core::PropertyType>,
697    ) {
698        use hawdb_core::PropertyType;
699        if let Value::List(values) = value {
700            for (index, value) in values.iter().enumerate() {
701                path.push(index);
702                visit(name, value, path, output);
703                path.pop();
704            }
705        } else {
706            let kind = match value {
707                Value::Int(_) => PropertyType::Int,
708                Value::String(_) => PropertyType::String,
709                Value::Bool(_) => PropertyType::Bool,
710                _ => return,
711            };
712            output.insert(parameter_marker(name, value, path), kind);
713        }
714    }
715    let mut output = BTreeMap::new();
716    for name in plan.cache_key.values.keys() {
717        if let Some(value) = parameters.get(name) {
718            visit(name, value, &mut Vec::new(), &mut output);
719        }
720    }
721    output
722}
723
724fn parameter_value_shape(value: &Value) -> ParameterValueShape {
725    match value {
726        Value::Null => ParameterValueShape::Null,
727        Value::Bool(_) => ParameterValueShape::Bool,
728        Value::Int(_) => ParameterValueShape::Int,
729        Value::Float(_) => ParameterValueShape::Float,
730        Value::Decimal(value) => ParameterValueShape::Decimal(value.decimal_type()),
731        Value::String(_) => ParameterValueShape::String,
732        Value::Binary(_) => ParameterValueShape::Binary,
733        Value::Vector(value) => ParameterValueShape::Vector(value.dimension()),
734        Value::Uuid(_) => ParameterValueShape::Uuid,
735        Value::Date(_) => ParameterValueShape::Date,
736        Value::LocalTime(_) => ParameterValueShape::LocalTime,
737        Value::LocalDateTime(_) => ParameterValueShape::LocalDateTime,
738        Value::DateTime(_) => ParameterValueShape::DateTime,
739        Value::Duration(_) => ParameterValueShape::Duration,
740        Value::List(values) => {
741            ParameterValueShape::List(values.iter().map(parameter_value_shape).collect())
742        }
743        Value::Map(values) => ParameterValueShape::Map(
744            values
745                .iter()
746                .map(|(key, value)| (key.clone(), parameter_value_shape(value)))
747                .collect(),
748        ),
749    }
750}
751
752fn parameter_marker(name: &str, value: &Value, path: &[usize]) -> Value {
753    match value {
754        Value::List(values) => Value::List(
755            values
756                .iter()
757                .enumerate()
758                .map(|(index, value)| {
759                    let mut nested_path = path.to_vec();
760                    nested_path.push(index);
761                    parameter_marker(name, value, &nested_path)
762                })
763                .collect(),
764        ),
765        _ => Value::Map(BTreeMap::from([
766            (
767                PARAMETER_SLOT_NAME_KEY.to_string(),
768                Value::String(name.to_string()),
769            ),
770            (
771                PARAMETER_SLOT_PATH_KEY.to_string(),
772                Value::List(path.iter().map(|index| Value::Int(*index as i64)).collect()),
773            ),
774        ])),
775    }
776}
777
778fn marker_name_and_path(value: &Value) -> Option<(&str, Vec<usize>)> {
779    let Value::Map(values) = value else {
780        return None;
781    };
782    if values.len() != 2 {
783        return None;
784    }
785    let Value::String(name) = values.get(PARAMETER_SLOT_NAME_KEY)? else {
786        return None;
787    };
788    let Value::List(path) = values.get(PARAMETER_SLOT_PATH_KEY)? else {
789        return None;
790    };
791    let path = path
792        .iter()
793        .map(|index| match index {
794            Value::Int(index) if *index >= 0 => usize::try_from(*index).ok(),
795            _ => None,
796        })
797        .collect::<Option<Vec<_>>>()?;
798    Some((name, path))
799}
800
801fn value_contains_marker(value: &Value, name: &str) -> bool {
802    if marker_name_and_path(value).is_some_and(|(marker_name, _)| marker_name == name) {
803        return true;
804    }
805    match value {
806        Value::List(values) => values
807            .iter()
808            .any(|value| value_contains_marker(value, name)),
809        Value::Map(values) => values
810            .values()
811            .any(|value| value_contains_marker(value, name)),
812        _ => false,
813    }
814}
815
816fn value_contains_any_marker(value: &Value) -> bool {
817    if marker_name_and_path(value).is_some() {
818        return true;
819    }
820    match value {
821        Value::List(values) => values.iter().any(value_contains_any_marker),
822        Value::Map(values) => values.values().any(value_contains_any_marker),
823        _ => false,
824    }
825}
826
827fn values_marker_use<'a>(values: impl IntoIterator<Item = &'a Value>, name: &str) -> MarkerUse {
828    if values
829        .into_iter()
830        .any(|value| value_contains_marker(value, name))
831    {
832        MarkerUse::Safe
833    } else {
834        MarkerUse::None
835    }
836}
837
838fn marker_use_in_logical_plan(plan: &LogicalPlan, name: &str) -> MarkerUse {
839    match plan {
840        LogicalPlan::Unwind { rows, .. } => values_marker_use(rows, name),
841        LogicalPlan::UnwindRows {
842            expression, input, ..
843        } => marker_use_in_projection_expression(expression, name, true)
844            .combine(marker_use_in_logical_plan(input, name)),
845        LogicalPlan::NodeScan { .. } | LogicalPlan::ThreadRepairStats { .. } => MarkerUse::None,
846        LogicalPlan::NodeCartesianProduct { left, right } => {
847            marker_use_in_logical_plan(left, name).combine(marker_use_in_logical_plan(right, name))
848        }
849        LogicalPlan::GraphMatch { program, input } => {
850            let mut marker_use = input.as_ref().map_or(MarkerUse::None, |input| {
851                marker_use_in_logical_plan(input, name)
852            });
853            for step in &program.steps {
854                let node = match step {
855                    GraphMatchStep::Node(node) => node,
856                    GraphMatchStep::Expand {
857                        target, properties, ..
858                    } => {
859                        marker_use =
860                            marker_use.combine(values_marker_use(properties.values(), name));
861                        target
862                    }
863                    // Hop bounds and types are literals; endpoints are Node steps.
864                    GraphMatchStep::ShortestPath(_) => continue,
865                };
866                marker_use = marker_use.combine(values_marker_use(node.properties.values(), name));
867            }
868            if let Some(predicate) = &program.predicate {
869                marker_use = marker_use.combine(marker_use_in_predicate(predicate, name));
870            }
871            marker_use
872        }
873        LogicalPlan::NodeColumnLookup {
874            input,
875            node_visibility_predicate,
876            ..
877        } => {
878            let policy = node_visibility_predicate
879                .as_ref()
880                .map_or(MarkerUse::None, |p| marker_use_in_predicate(p, name));
881            policy.combine(marker_use_in_logical_plan(input, name))
882        }
883        LogicalPlan::Distinct { input } | LogicalPlan::Limit { input, .. } => {
884            marker_use_in_logical_plan(input, name)
885        }
886        LogicalPlan::Expand {
887            rel_properties,
888            input,
889            ..
890        } => values_marker_use(rel_properties.values(), name)
891            .combine(marker_use_in_logical_plan(input, name)),
892        LogicalPlan::OptionalDegree {
893            rel_properties,
894            target_properties,
895            input,
896            ..
897        } => values_marker_use(rel_properties.values(), name)
898            .combine(values_marker_use(target_properties.values(), name))
899            .combine(marker_use_in_logical_plan(input, name)),
900        LogicalPlan::OptionalRelationshipCountSum {
901            properties, legs, ..
902        } => {
903            let mut marker_use = values_marker_use(properties.values(), name);
904            for leg in legs {
905                if let Some(RelationshipCountFilter::PropertyNotEqOrEmpty { value, .. }) =
906                    &leg.filter
907                {
908                    marker_use = marker_use.combine(if value_contains_marker(value, name) {
909                        MarkerUse::Safe
910                    } else {
911                        MarkerUse::None
912                    });
913                }
914            }
915            marker_use
916        }
917        LogicalPlan::Filter {
918            predicate, input, ..
919        } => marker_use_in_predicate(predicate, name)
920            .combine(marker_use_in_logical_plan(input, name)),
921        LogicalPlan::Project { items, input } => marker_use_in_projections(items, name, false)
922            .combine(marker_use_in_logical_plan(input, name)),
923        LogicalPlan::Aggregate {
924            group_keys,
925            items,
926            input,
927        } => marker_use_in_projections(group_keys, name, false)
928            .combine(marker_use_in_aggregations(items, name))
929            .combine(marker_use_in_logical_plan(input, name)),
930        LogicalPlan::Sort { items, input } => {
931            let marker_use = items.iter().fold(MarkerUse::None, |marker_use, item| {
932                marker_use.combine(marker_use_in_sort_item(item, name))
933            });
934            marker_use.combine(marker_use_in_logical_plan(input, name))
935        }
936        LogicalPlan::ShortestPath {
937            source_id,
938            source_visibility_predicate,
939            target_id,
940            target_visibility_predicate,
941            ..
942        } => {
943            let mut marker_use = values_marker_use([source_id, target_id], name);
944            if marker_use.is_safe() {
945                marker_use = MarkerUse::Unsafe;
946            }
947            for predicate in [source_visibility_predicate, target_visibility_predicate]
948                .into_iter()
949                .flatten()
950            {
951                marker_use = marker_use.combine(marker_use_in_predicate(predicate, name));
952            }
953            marker_use
954        }
955        LogicalPlan::VectorIndexSearch(scan) => {
956            let visibility = scan
957                .node_visibility_predicate
958                .as_ref()
959                .map_or(MarkerUse::None, |predicate| {
960                    marker_use_in_predicate(predicate, name)
961                });
962            visibility.combine(scan.input.as_deref().map_or(MarkerUse::None, |input| {
963                marker_use_in_logical_plan(input, name)
964            }))
965        }
966        LogicalPlan::GraphAlgorithmOutput(output) => output
967            .node_visibility_predicate
968            .as_ref()
969            .map(|predicate| marker_use_in_predicate(predicate, name))
970            .unwrap_or(MarkerUse::None),
971        LogicalPlan::GraphAlgorithm {
972            node_visibility_predicate,
973            ..
974        }
975        | LogicalPlan::GraphSeed {
976            node_visibility_predicate,
977            ..
978        } => node_visibility_predicate
979            .as_ref()
980            .map(|predicate| marker_use_in_predicate(predicate, name))
981            .unwrap_or(MarkerUse::None),
982        _ => MarkerUse::None,
983    }
984}
985
986fn marker_use_in_predicate(predicate: &Predicate, name: &str) -> MarkerUse {
987    match predicate {
988        Predicate::And(predicates) | Predicate::Or(predicates) => predicates
989            .iter()
990            .fold(MarkerUse::None, |marker_use, predicate| {
991                marker_use.combine(marker_use_in_predicate(predicate, name))
992            }),
993        Predicate::Not(predicate) => marker_use_in_predicate(predicate, name),
994        Predicate::PropertyEq { value, .. } | Predicate::PropertyNotEq { value, .. } => {
995            values_marker_use([value], name)
996        }
997        Predicate::PropertyIn { values, .. } => values_marker_use(values, name),
998        Predicate::IdEq { value, .. }
999        | Predicate::IdNotEq { value, .. }
1000        | Predicate::IdCompare { value, .. }
1001        | Predicate::PropertyCompare { value, .. }
1002        | Predicate::PropertyListContains { value, .. } => {
1003            if value_contains_marker(value, name) {
1004                MarkerUse::Unsafe
1005            } else {
1006                MarkerUse::None
1007            }
1008        }
1009        Predicate::IdIn { values, .. } => {
1010            if values
1011                .iter()
1012                .any(|value| value_contains_marker(value, name))
1013            {
1014                MarkerUse::Unsafe
1015            } else {
1016                MarkerUse::None
1017            }
1018        }
1019        Predicate::ExpressionEq { expression, value }
1020        | Predicate::ExpressionNotEq { expression, value }
1021        | Predicate::ExpressionContains { expression, value } => {
1022            marker_use_in_projection_expression(expression, name, false)
1023                .combine(marker_use_in_projection_expression(value, name, false))
1024        }
1025        Predicate::ExpressionIn { expression, values } => {
1026            marker_use_in_projection_expression(expression, name, false)
1027                .combine(values_marker_use(values, name))
1028        }
1029        Predicate::ExpressionCompare {
1030            expression, value, ..
1031        } => marker_use_in_projection_expression(expression, name, false)
1032            .combine(marker_use_in_projection_expression(value, name, false)),
1033        _ => MarkerUse::None,
1034    }
1035}
1036
1037fn marker_use_in_projections(projections: &[Projection], name: &str, safe: bool) -> MarkerUse {
1038    projections
1039        .iter()
1040        .fold(MarkerUse::None, |marker_use, projection| {
1041            marker_use.combine(marker_use_in_projection_expression(
1042                &projection.expression,
1043                name,
1044                safe,
1045            ))
1046        })
1047}
1048
1049fn marker_use_in_aggregations(items: &[Aggregation], name: &str) -> MarkerUse {
1050    items.iter().fold(MarkerUse::None, |marker_use, item| {
1051        marker_use.combine(match &item.target {
1052            AggregateTarget::Expression(expression) => {
1053                marker_use_in_projection_expression(expression, name, false)
1054            }
1055            _ => MarkerUse::None,
1056        })
1057    })
1058}
1059
1060fn marker_use_in_sort_item(item: &SortItem, name: &str) -> MarkerUse {
1061    match &item.key {
1062        SortKey::Expression(expression) => {
1063            marker_use_in_projection_expression(expression, name, false)
1064        }
1065        _ => MarkerUse::None,
1066    }
1067}
1068
1069fn marker_use_in_projection_expression(
1070    expression: &ProjectionExpression,
1071    name: &str,
1072    safe: bool,
1073) -> MarkerUse {
1074    if let ProjectionExpression::Case {
1075        operand: Some(operand),
1076        branches,
1077        otherwise,
1078    } = expression
1079        && matches!(
1080            operand.as_ref(),
1081            ProjectionExpression::Property { .. } | ProjectionExpression::Column(_)
1082        )
1083        && branches.iter().all(|(condition, result)| {
1084            matches!(condition, ProjectionExpression::Literal(_))
1085                && matches!(result, ProjectionExpression::Literal(_))
1086        })
1087        && otherwise
1088            .as_deref()
1089            .is_none_or(|value| matches!(value, ProjectionExpression::Literal(_)))
1090    {
1091        // Simple CASE with literal branches has no value-driven planner
1092        // specialization. Binding changes values, never its branch structure.
1093        let marker_use = values_marker_use(
1094            branches
1095                .iter()
1096                .flat_map(|(condition, result)| [condition, result])
1097                .chain(otherwise.iter().map(Box::as_ref))
1098                .filter_map(|value| match value {
1099                    ProjectionExpression::Literal(value) => Some(value),
1100                    _ => None,
1101                }),
1102            name,
1103        );
1104        return if marker_use == MarkerUse::Safe {
1105            MarkerUse::SafeCase
1106        } else {
1107            marker_use
1108        };
1109    }
1110    let marker_use = match expression {
1111        ProjectionExpression::Case { .. }
1112        | ProjectionExpression::VectorDistance { .. }
1113        | ProjectionExpression::Binary { .. }
1114        | ProjectionExpression::Not(_)
1115        | ProjectionExpression::IsNull { .. }
1116        | ProjectionExpression::ListFunction { .. }
1117        | ProjectionExpression::StringFunction { .. }
1118        | ProjectionExpression::ListComprehension(_)
1119        | ProjectionExpression::List(_)
1120        | ProjectionExpression::ListIndex { .. }
1121        | ProjectionExpression::Conversion { .. }
1122        | ProjectionExpression::ListSlice { .. }
1123        | ProjectionExpression::TemporalFunction { .. }
1124        | ProjectionExpression::PropertyAccess { .. }
1125        | ProjectionExpression::MapLiteral(_) => {
1126            let mut result = MarkerUse::None;
1127            expression.all_children(|child| {
1128                result = result.combine(marker_use_in_projection_expression(child, name, safe));
1129                true
1130            });
1131            result
1132        }
1133
1134        ProjectionExpression::Literal(value) => values_marker_use([value], name),
1135        ProjectionExpression::Coalesce(expressions) => {
1136            expressions
1137                .iter()
1138                .fold(MarkerUse::None, |marker_use, expression| {
1139                    marker_use.combine(marker_use_in_projection_expression(expression, name, safe))
1140                })
1141        }
1142        ProjectionExpression::Left { expression, .. }
1143        | ProjectionExpression::Lower(expression)
1144        | ProjectionExpression::JsonValue { expression, .. } => {
1145            marker_use_in_projection_expression(expression, name, safe)
1146        }
1147        ProjectionExpression::DefaultIfNullOrEq { empty, default, .. }
1148        | ProjectionExpression::ColumnDefaultIfNullOrEq { empty, default, .. } => {
1149            values_marker_use([empty, default], name)
1150        }
1151        ProjectionExpression::DefaultIfNull { default, .. }
1152        | ProjectionExpression::CaseLowerPropertyDefault { default, .. }
1153        | ProjectionExpression::ColumnValueDefaultIfNull { default, .. } => {
1154            values_marker_use([default], name)
1155        }
1156        ProjectionExpression::CasePropertyNotNullOrEq {
1157            empty,
1158            non_empty,
1159            null_or_empty,
1160            ..
1161        }
1162        | ProjectionExpression::ColumnValueCasePropertyNotNullOrEq {
1163            empty,
1164            non_empty,
1165            null_or_empty,
1166            ..
1167        } => values_marker_use([empty, non_empty, null_or_empty], name),
1168        ProjectionExpression::CasePropertyEqualsRank {
1169            branches, default, ..
1170        } => values_marker_use(
1171            branches
1172                .iter()
1173                .flat_map(|(left, right)| [left, right])
1174                .chain([default]),
1175            name,
1176        ),
1177        ProjectionExpression::CaseCoalesceDifferenceFloorZero { terms, .. } => {
1178            values_marker_use(terms.iter().map(|term| &term.default), name)
1179        }
1180        ProjectionExpression::CaseEntitySearchRank(expression) => values_marker_use(
1181            [
1182                &expression.raw_query,
1183                &expression.normalized_query,
1184                &expression.raw_input,
1185                &expression.exact_rank,
1186                &expression.alias_rank,
1187                &expression.fallback_rank,
1188            ],
1189            name,
1190        ),
1191        ProjectionExpression::CaseColumnSearchRank(expression) => values_marker_use(
1192            [
1193                &expression.raw_query,
1194                &expression.normalized_query,
1195                &expression.exact_rank,
1196                &expression.contains_rank,
1197                &expression.fallback_rank,
1198            ],
1199            name,
1200        ),
1201        _ => MarkerUse::None,
1202    };
1203    if !safe && marker_use.is_safe() {
1204        MarkerUse::Unsafe
1205    } else {
1206        marker_use
1207    }
1208}
1209
1210#[derive(Clone, Copy)]
1211enum BindingAction<'a> {
1212    Execute(&'a BTreeMap<String, Value>),
1213    PrepareRegex,
1214    RetainRegex(&'a std::cell::Cell<bool>),
1215}
1216
1217/// Retain validated pattern sources without compiled automata in a cache owner.
1218/// Returns whether execution binding must prepare regex state, even without slots.
1219#[doc(hidden)]
1220pub fn prepare_physical_plan_for_cache(plan: &mut PhysicalPlan) -> Result<bool> {
1221    let found = std::cell::Cell::new(false);
1222    bind_physical_plan(plan, BindingAction::RetainRegex(&found))?;
1223    Ok(found.get())
1224}
1225
1226/// Prepare only source-backed regex state in an execution clone. Literal values
1227/// are left untouched when the template has no actual parameter slots.
1228#[doc(hidden)]
1229pub fn prepare_physical_regexes_for_execution(plan: &mut PhysicalPlan) -> Result<()> {
1230    bind_physical_plan(plan, BindingAction::PrepareRegex)
1231}
1232
1233fn bind_physical_plan(plan: &mut PhysicalPlan, parameters: BindingAction<'_>) -> Result<()> {
1234    match plan {
1235        PhysicalPlan::VectorIndexScan(scan) => {
1236            bind_optional_predicate(&mut scan.node_visibility_predicate, parameters)?;
1237            if let Some(input) = &mut scan.input {
1238                bind_physical_plan(input, parameters)?;
1239            }
1240        }
1241        PhysicalPlan::GraphAlgorithmOutput(output) => {
1242            bind_optional_predicate(&mut output.node_visibility_predicate, parameters)?
1243        }
1244        PhysicalPlan::GraphAlgorithm {
1245            node_visibility_predicate,
1246            ..
1247        }
1248        | PhysicalPlan::GraphSeedScan {
1249            node_visibility_predicate,
1250            ..
1251        } => bind_optional_predicate(node_visibility_predicate, parameters)?,
1252        PhysicalPlan::SourceSegmentScan { predicate, .. } => {
1253            bind_predicate(predicate, parameters)?;
1254        }
1255        PhysicalPlan::FilterExec { predicate, input } => {
1256            bind_predicate(predicate, parameters)?;
1257            bind_physical_plan(input, parameters)?;
1258        }
1259        PhysicalPlan::UnwindRowsExec {
1260            expression, input, ..
1261        } => {
1262            bind_projection_expression(expression, parameters)?;
1263            bind_physical_plan(input, parameters)?;
1264        }
1265        PhysicalPlan::NodeProjectionScanExec {
1266            access,
1267            predicate,
1268            items,
1269            ..
1270        } => {
1271            bind_node_projection_access(access, parameters)?;
1272            bind_optional_predicate(predicate, parameters)?;
1273            bind_projections(items, parameters)?;
1274        }
1275        PhysicalPlan::NodeCartesianProductExec { left, right }
1276        | PhysicalPlan::HashJoinExec { left, right, .. } => {
1277            bind_physical_plan(left, parameters)?;
1278            bind_physical_plan(right, parameters)?;
1279        }
1280        PhysicalPlan::GraphMatchExec { program, input } => {
1281            for step in &mut program.steps {
1282                let node = match step {
1283                    GraphMatchStep::Node(node) => node,
1284                    GraphMatchStep::Expand {
1285                        target, properties, ..
1286                    } => {
1287                        bind_value_map(properties, parameters)?;
1288                        target
1289                    }
1290                    GraphMatchStep::ShortestPath(_) => continue,
1291                };
1292                bind_value_map(&mut node.properties, parameters)?;
1293            }
1294            bind_optional_predicate(&mut program.predicate, parameters)?;
1295            if let Some(input) = input {
1296                bind_physical_plan(input, parameters)?;
1297            }
1298        }
1299        PhysicalPlan::NodeColumnLookupExec {
1300            input,
1301            node_visibility_predicate,
1302            ..
1303        } => {
1304            bind_optional_predicate(node_visibility_predicate, parameters)?;
1305            bind_physical_plan(input, parameters)?;
1306        }
1307        PhysicalPlan::AdjacencyExistsExec { input, .. }
1308        | PhysicalPlan::DistinctExec { input }
1309        | PhysicalPlan::ScoringRerankExec { input, .. }
1310        | PhysicalPlan::ScoringProgramExec { input, .. }
1311        | PhysicalPlan::HostScoringExec { input, .. }
1312        | PhysicalPlan::LimitExec { input, .. } => bind_physical_plan(input, parameters)?,
1313        PhysicalPlan::IndexNodeSeek { value, .. } => bind_value(value, parameters)?,
1314        PhysicalPlan::UnwindExec { rows: values, .. }
1315        | PhysicalPlan::IndexNodeMultiSeek { values, .. } => {
1316            bind_values(values, parameters)?;
1317        }
1318        PhysicalPlan::IndexNodeUnionSeek { branches, .. } => {
1319            for branch in branches {
1320                bind_values(&mut branch.values, parameters)?;
1321            }
1322        }
1323        PhysicalPlan::IndexNodeCompositeSeek { predicates, .. } => {
1324            for (_, value) in predicates {
1325                bind_value(value, parameters)?;
1326            }
1327        }
1328        PhysicalPlan::IndexNodeCompositeRangeSeek { seek, .. } => {
1329            bind_composite_range_seek(seek, parameters)?;
1330        }
1331        PhysicalPlan::IndexNodeRangeSeek { lower, upper, .. } => {
1332            for (value, _) in lower.iter_mut().chain(upper.iter_mut()) {
1333                bind_value(value, parameters)?;
1334            }
1335        }
1336        PhysicalPlan::AdjacencyExpandExec {
1337            rel_properties,
1338            input,
1339            ..
1340        } => {
1341            bind_value_map(rel_properties, parameters)?;
1342            bind_physical_plan(input, parameters)?;
1343        }
1344        PhysicalPlan::OptionalDegreeExec {
1345            rel_properties,
1346            target_properties,
1347            input,
1348            ..
1349        } => {
1350            bind_value_map(rel_properties, parameters)?;
1351            bind_value_map(target_properties, parameters)?;
1352            bind_physical_plan(input, parameters)?;
1353        }
1354        PhysicalPlan::OptionalRelationshipCountSumExec {
1355            properties, legs, ..
1356        } => {
1357            bind_value_map(properties, parameters)?;
1358            for leg in legs {
1359                if let Some(RelationshipCountFilter::PropertyNotEqOrEmpty { value, .. }) =
1360                    &mut leg.filter
1361                {
1362                    bind_value(value, parameters)?;
1363                }
1364            }
1365        }
1366        PhysicalPlan::ShortestPathExec {
1367            source_id,
1368            source_visibility_predicate,
1369            target_id,
1370            target_visibility_predicate,
1371            ..
1372        } => {
1373            bind_value(source_id, parameters)?;
1374            bind_optional_predicate(source_visibility_predicate, parameters)?;
1375            bind_value(target_id, parameters)?;
1376            bind_optional_predicate(target_visibility_predicate, parameters)?;
1377        }
1378        PhysicalPlan::ProjectExec { items, input } => {
1379            bind_projections(items, parameters)?;
1380            bind_physical_plan(input, parameters)?;
1381        }
1382        PhysicalPlan::AggregateExec {
1383            group_keys,
1384            items,
1385            input,
1386        } => {
1387            bind_projections(group_keys, parameters)?;
1388            bind_aggregations(items, parameters)?;
1389            bind_physical_plan(input, parameters)?;
1390        }
1391        PhysicalPlan::SortExec { items, input } | PhysicalPlan::TopNExec { items, input, .. } => {
1392            bind_sort_items(items, parameters)?;
1393            bind_physical_plan(input, parameters)?;
1394        }
1395        PhysicalPlan::CreateNodeLabel { .. }
1396        | PhysicalPlan::CreateRelationshipType { .. }
1397        | PhysicalPlan::CreateNodeTable { .. }
1398        | PhysicalPlan::CreateRelationshipTable { .. }
1399        | PhysicalPlan::CreateProperty { .. }
1400        | PhysicalPlan::AlterTableState { .. }
1401        | PhysicalPlan::AlterPropertyState { .. }
1402        | PhysicalPlan::CreateIndex { .. }
1403        | PhysicalPlan::CreateCompositeIndex { .. }
1404        | PhysicalPlan::CreateRangeIndex { .. }
1405        | PhysicalPlan::CreateFullTextIndex { .. }
1406        | PhysicalPlan::CreateUniqueConstraint { .. }
1407        | PhysicalPlan::CreateNodePropertyExistsConstraint { .. }
1408        | PhysicalPlan::CreateRelationshipUniqueConstraint { .. }
1409        | PhysicalPlan::CreateRelationshipPropertyExistsConstraint { .. }
1410        | PhysicalPlan::ProjectGraph { .. }
1411        | PhysicalPlan::VectorSeedScan { .. }
1412        | PhysicalPlan::TextSeedScan { .. }
1413        | PhysicalPlan::CreateNode { .. }
1414        | PhysicalPlan::UnwindMutation { .. }
1415        // LOAD CSV keeps its parameter name, resolved again at execution.
1416        | PhysicalPlan::LoadCsvMutation { .. }
1417        | PhysicalPlan::LoadCsvExec { .. }
1418        | PhysicalPlan::MergeNode { .. }
1419        | PhysicalPlan::MergeRelationship { .. }
1420        | PhysicalPlan::MergeMatchedRelationship { .. }
1421        | PhysicalPlan::MergeRelationshipFromMatchedRelationship { .. }
1422        | PhysicalPlan::MergeRelationshipToMatchedTarget { .. }
1423        | PhysicalPlan::MergeRelationshipFromMatchedTarget { .. }
1424        | PhysicalPlan::CreateMatchedRelationship { .. }
1425        | PhysicalPlan::SetNodeProperty { .. }
1426        | PhysicalPlan::SetNodeProperties { .. }
1427        | PhysicalPlan::SetNodePropertiesReturn { .. }
1428        | PhysicalPlan::SetRelationshipProperty { .. }
1429        | PhysicalPlan::SetRelationshipProperties { .. }
1430        | PhysicalPlan::DeleteNode { .. }
1431        | PhysicalPlan::DeleteRelationship { .. }
1432        | PhysicalPlan::DeleteRelationshipTargetNodes { .. }
1433        | PhysicalPlan::CreateRelationship { .. }
1434        | PhysicalPlan::EmptyExec
1435        | PhysicalPlan::SeqNodeScan { .. }
1436        | PhysicalPlan::IndexNodeTextSeek { .. }
1437        | PhysicalPlan::NodeCountExec { .. }
1438        | PhysicalPlan::RelationshipCountExec { .. }
1439        | PhysicalPlan::ThreadRepairStatsExec { .. } => {}
1440    }
1441    Ok(())
1442}
1443
1444fn bind_node_projection_access(
1445    access: &mut hawdb_plan_cypher::NodeProjectionAccess,
1446    parameters: BindingAction<'_>,
1447) -> Result<()> {
1448    match access {
1449        hawdb_plan_cypher::NodeProjectionAccess::LabelScan => Ok(()),
1450        hawdb_plan_cypher::NodeProjectionAccess::PropertyValues { values, .. } => {
1451            bind_values(values, parameters)
1452        }
1453        hawdb_plan_cypher::NodeProjectionAccess::PropertyUnion { branches } => {
1454            for branch in branches {
1455                bind_values(&mut branch.values, parameters)?;
1456            }
1457            Ok(())
1458        }
1459        hawdb_plan_cypher::NodeProjectionAccess::CompositeEquality { predicates } => {
1460            for (_, value) in predicates {
1461                bind_value(value, parameters)?;
1462            }
1463            Ok(())
1464        }
1465        hawdb_plan_cypher::NodeProjectionAccess::CompositeRange { seek } => {
1466            bind_composite_range_seek(seek, parameters)
1467        }
1468        hawdb_plan_cypher::NodeProjectionAccess::CompositeOrdered { seek } => {
1469            for (_, value) in &mut seek.equality_prefix {
1470                bind_value(value, parameters)?;
1471            }
1472            if let Some(after) = &mut seek.after {
1473                bind_values(after, parameters)?;
1474            }
1475            Ok(())
1476        }
1477        hawdb_plan_cypher::NodeProjectionAccess::PropertyRange { lower, upper, .. } => {
1478            for (value, _) in lower.iter_mut().chain(upper.iter_mut()) {
1479                bind_value(value, parameters)?;
1480            }
1481            Ok(())
1482        }
1483        hawdb_plan_cypher::NodeProjectionAccess::FullText { .. } => Ok(()),
1484    }
1485}
1486
1487fn bind_composite_range_seek(
1488    seek: &mut hawdb_plan_cypher::CompositeRangeSeek,
1489    parameters: BindingAction<'_>,
1490) -> Result<()> {
1491    for (_, value) in &mut seek.equality_prefix {
1492        bind_value(value, parameters)?;
1493    }
1494    for (value, _) in seek.lower.iter_mut().chain(seek.upper.iter_mut()) {
1495        bind_value(value, parameters)?;
1496    }
1497    Ok(())
1498}
1499
1500fn bind_logical_plan(plan: &mut LogicalPlan, parameters: BindingAction<'_>) -> Result<()> {
1501    match plan {
1502        LogicalPlan::Unwind { rows, .. } => bind_values(rows, parameters)?,
1503        LogicalPlan::UnwindRows {
1504            expression, input, ..
1505        } => {
1506            bind_projection_expression(expression, parameters)?;
1507            bind_logical_plan(input, parameters)?;
1508        }
1509        LogicalPlan::VectorIndexSearch(scan) => {
1510            bind_optional_predicate(&mut scan.node_visibility_predicate, parameters)?;
1511            if let Some(input) = &mut scan.input {
1512                bind_logical_plan(input, parameters)?;
1513            }
1514        }
1515        LogicalPlan::GraphAlgorithmOutput(output) => {
1516            bind_optional_predicate(&mut output.node_visibility_predicate, parameters)?
1517        }
1518        LogicalPlan::GraphAlgorithm {
1519            node_visibility_predicate,
1520            ..
1521        }
1522        | LogicalPlan::GraphSeed {
1523            node_visibility_predicate,
1524            ..
1525        } => bind_optional_predicate(node_visibility_predicate, parameters)?,
1526        LogicalPlan::NodeCartesianProduct { left, right } => {
1527            bind_logical_plan(left, parameters)?;
1528            bind_logical_plan(right, parameters)?;
1529        }
1530        LogicalPlan::NodeColumnLookup {
1531            input,
1532            node_visibility_predicate,
1533            ..
1534        } => {
1535            bind_optional_predicate(node_visibility_predicate, parameters)?;
1536            bind_logical_plan(input, parameters)?;
1537        }
1538        LogicalPlan::Distinct { input } | LogicalPlan::Limit { input, .. } => {
1539            bind_logical_plan(input, parameters)?
1540        }
1541        LogicalPlan::Expand {
1542            rel_properties,
1543            input,
1544            ..
1545        } => {
1546            bind_value_map(rel_properties, parameters)?;
1547            bind_logical_plan(input, parameters)?;
1548        }
1549        LogicalPlan::OptionalDegree {
1550            rel_properties,
1551            target_properties,
1552            input,
1553            ..
1554        } => {
1555            bind_value_map(rel_properties, parameters)?;
1556            bind_value_map(target_properties, parameters)?;
1557            bind_logical_plan(input, parameters)?;
1558        }
1559        LogicalPlan::OptionalRelationshipCountSum {
1560            properties, legs, ..
1561        } => {
1562            bind_value_map(properties, parameters)?;
1563            for leg in legs {
1564                if let Some(RelationshipCountFilter::PropertyNotEqOrEmpty { value, .. }) =
1565                    &mut leg.filter
1566                {
1567                    bind_value(value, parameters)?;
1568                }
1569            }
1570        }
1571        LogicalPlan::ShortestPath {
1572            source_id,
1573            source_visibility_predicate,
1574            target_id,
1575            target_visibility_predicate,
1576            ..
1577        } => {
1578            bind_value(source_id, parameters)?;
1579            bind_optional_predicate(source_visibility_predicate, parameters)?;
1580            bind_value(target_id, parameters)?;
1581            bind_optional_predicate(target_visibility_predicate, parameters)?;
1582        }
1583        LogicalPlan::Filter {
1584            predicate, input, ..
1585        } => {
1586            bind_predicate(predicate, parameters)?;
1587            bind_logical_plan(input, parameters)?;
1588        }
1589        LogicalPlan::Project { items, input } => {
1590            bind_projections(items, parameters)?;
1591            bind_logical_plan(input, parameters)?;
1592        }
1593        LogicalPlan::Aggregate {
1594            group_keys,
1595            items,
1596            input,
1597        } => {
1598            bind_projections(group_keys, parameters)?;
1599            bind_aggregations(items, parameters)?;
1600            bind_logical_plan(input, parameters)?;
1601        }
1602        LogicalPlan::Sort { items, input } => {
1603            bind_sort_items(items, parameters)?;
1604            bind_logical_plan(input, parameters)?;
1605        }
1606        _ => {}
1607    }
1608    Ok(())
1609}
1610
1611fn bind_optional_predicate(
1612    predicate: &mut Option<Predicate>,
1613    parameters: BindingAction<'_>,
1614) -> Result<()> {
1615    if let Some(predicate) = predicate {
1616        bind_predicate(predicate, parameters)?;
1617    }
1618    Ok(())
1619}
1620
1621fn bind_predicate(predicate: &mut Predicate, parameters: BindingAction<'_>) -> Result<()> {
1622    match predicate {
1623        Predicate::And(predicates) | Predicate::Or(predicates) => {
1624            for predicate in predicates {
1625                bind_predicate(predicate, parameters)?;
1626            }
1627        }
1628        Predicate::Not(predicate) => bind_predicate(predicate, parameters)?,
1629        Predicate::PropertyRegexMatch { pattern, .. } => match parameters {
1630            BindingAction::Execute(_) | BindingAction::PrepareRegex => {
1631                pattern.prepare_for_execution()?
1632            }
1633            BindingAction::RetainRegex(found) => {
1634                pattern.retain_source_only();
1635                found.set(true);
1636            }
1637        },
1638        Predicate::IdEq { value, .. }
1639        | Predicate::IdNotEq { value, .. }
1640        | Predicate::IdCompare { value, .. }
1641        | Predicate::PropertyEq { value, .. }
1642        | Predicate::PropertyNotEq { value, .. }
1643        | Predicate::PropertyCompare { value, .. }
1644        | Predicate::PropertyListContains { value, .. } => bind_value(value, parameters)?,
1645        Predicate::IdIn { values, .. } | Predicate::PropertyIn { values, .. } => {
1646            bind_values(values, parameters)?;
1647        }
1648        Predicate::ExpressionIn { expression, values } => {
1649            bind_projection_expression(expression, parameters)?;
1650            bind_values(values, parameters)?;
1651        }
1652        Predicate::ExpressionEq { expression, value }
1653        | Predicate::ExpressionNotEq { expression, value }
1654        | Predicate::ExpressionContains { expression, value } => {
1655            bind_projection_expression(expression, parameters)?;
1656            bind_projection_expression(value, parameters)?;
1657        }
1658        Predicate::ExpressionCompare {
1659            expression, value, ..
1660        } => {
1661            bind_projection_expression(expression, parameters)?;
1662            bind_projection_expression(value, parameters)?;
1663        }
1664        _ => {}
1665    }
1666    Ok(())
1667}
1668
1669fn bind_projections(projections: &mut [Projection], parameters: BindingAction<'_>) -> Result<()> {
1670    for projection in projections {
1671        bind_projection_expression(&mut projection.expression, parameters)?;
1672    }
1673    Ok(())
1674}
1675
1676fn bind_aggregations(items: &mut [Aggregation], parameters: BindingAction<'_>) -> Result<()> {
1677    for item in items {
1678        if let AggregateTarget::Expression(expression) = &mut item.target {
1679            bind_projection_expression(expression, parameters)?;
1680        }
1681    }
1682    Ok(())
1683}
1684
1685fn bind_sort_items(items: &mut [SortItem], parameters: BindingAction<'_>) -> Result<()> {
1686    for item in items {
1687        if let SortKey::Expression(expression) = &mut item.key {
1688            bind_projection_expression(expression, parameters)?;
1689        }
1690    }
1691    Ok(())
1692}
1693
1694fn bind_projection_expression(
1695    expression: &mut ProjectionExpression,
1696    parameters: BindingAction<'_>,
1697) -> Result<()> {
1698    match expression {
1699        ProjectionExpression::StringFunction {
1700            function,
1701            arguments,
1702            pattern,
1703        } => {
1704            for argument in arguments.iter_mut() {
1705                bind_projection_expression(argument, parameters)?;
1706            }
1707            match parameters {
1708                BindingAction::RetainRegex(found) => {
1709                    if let Some(pattern) = pattern {
1710                        pattern.retain_source_only();
1711                        found.set(true);
1712                    }
1713                }
1714                BindingAction::Execute(_) | BindingAction::PrepareRegex => {
1715                    match (function, arguments.get(1)) {
1716                        (
1717                            hawdb_core::StringFunction::RegexpReplace,
1718                            Some(ProjectionExpression::Literal(Value::String(source))),
1719                        ) => {
1720                            if pattern
1721                                .as_ref()
1722                                .is_none_or(|pattern| pattern.as_str() != source)
1723                            {
1724                                *pattern = Some(Box::new(hawdb_core::ValidatedRegex::new(
1725                                    source.clone(),
1726                                )?));
1727                            } else if let Some(pattern) = pattern {
1728                                pattern.prepare_for_execution()?;
1729                            }
1730                        }
1731                        _ => *pattern = None,
1732                    }
1733                }
1734            }
1735        }
1736
1737        ProjectionExpression::Case { .. }
1738        | ProjectionExpression::VectorDistance { .. }
1739        | ProjectionExpression::Binary { .. }
1740        | ProjectionExpression::Not(_)
1741        | ProjectionExpression::IsNull { .. }
1742        | ProjectionExpression::ListFunction { .. }
1743        | ProjectionExpression::ListComprehension(_)
1744        | ProjectionExpression::List(_)
1745        | ProjectionExpression::ListIndex { .. }
1746        | ProjectionExpression::Conversion { .. }
1747        | ProjectionExpression::ListSlice { .. }
1748        | ProjectionExpression::TemporalFunction { .. }
1749        | ProjectionExpression::PropertyAccess { .. }
1750        | ProjectionExpression::MapLiteral(_) => expression
1751            .try_for_each_child_mut(|child| bind_projection_expression(child, parameters))?,
1752
1753        ProjectionExpression::Literal(value) => bind_value(value, parameters)?,
1754        ProjectionExpression::Coalesce(expressions) => {
1755            for expression in expressions {
1756                bind_projection_expression(expression, parameters)?;
1757            }
1758        }
1759        ProjectionExpression::Left { expression, .. }
1760        | ProjectionExpression::Lower(expression)
1761        | ProjectionExpression::JsonValue { expression, .. } => {
1762            bind_projection_expression(expression, parameters)?;
1763        }
1764        ProjectionExpression::DefaultIfNullOrEq { empty, default, .. }
1765        | ProjectionExpression::ColumnDefaultIfNullOrEq { empty, default, .. } => {
1766            bind_value(empty, parameters)?;
1767            bind_value(default, parameters)?;
1768        }
1769        ProjectionExpression::DefaultIfNull { default, .. }
1770        | ProjectionExpression::CaseLowerPropertyDefault { default, .. }
1771        | ProjectionExpression::ColumnValueDefaultIfNull { default, .. } => {
1772            bind_value(default, parameters)?;
1773        }
1774        ProjectionExpression::CasePropertyNotNullOrEq {
1775            empty,
1776            non_empty,
1777            null_or_empty,
1778            ..
1779        }
1780        | ProjectionExpression::ColumnValueCasePropertyNotNullOrEq {
1781            empty,
1782            non_empty,
1783            null_or_empty,
1784            ..
1785        } => {
1786            bind_value(empty, parameters)?;
1787            bind_value(non_empty, parameters)?;
1788            bind_value(null_or_empty, parameters)?;
1789        }
1790        ProjectionExpression::CasePropertyEqualsRank {
1791            branches, default, ..
1792        } => {
1793            for (left, right) in branches {
1794                bind_value(left, parameters)?;
1795                bind_value(right, parameters)?;
1796            }
1797            bind_value(default, parameters)?;
1798        }
1799        ProjectionExpression::CaseCoalesceDifferenceFloorZero { terms, .. } => {
1800            for term in terms {
1801                bind_value(&mut term.default, parameters)?;
1802            }
1803        }
1804        ProjectionExpression::CaseEntitySearchRank(expression) => {
1805            for value in [
1806                &mut expression.raw_query,
1807                &mut expression.normalized_query,
1808                &mut expression.raw_input,
1809                &mut expression.exact_rank,
1810                &mut expression.alias_rank,
1811                &mut expression.fallback_rank,
1812            ] {
1813                bind_value(value, parameters)?;
1814            }
1815        }
1816        ProjectionExpression::CaseColumnSearchRank(expression) => {
1817            for value in [
1818                &mut expression.raw_query,
1819                &mut expression.normalized_query,
1820                &mut expression.exact_rank,
1821                &mut expression.contains_rank,
1822                &mut expression.fallback_rank,
1823            ] {
1824                bind_value(value, parameters)?;
1825            }
1826        }
1827        _ => {}
1828    }
1829    Ok(())
1830}
1831
1832fn bind_value_map(
1833    values: &mut BTreeMap<String, Value>,
1834    parameters: BindingAction<'_>,
1835) -> Result<()> {
1836    for value in values.values_mut() {
1837        bind_value(value, parameters)?;
1838    }
1839    Ok(())
1840}
1841
1842fn bind_values(values: &mut [Value], parameters: BindingAction<'_>) -> Result<()> {
1843    for value in values {
1844        bind_value(value, parameters)?;
1845    }
1846    Ok(())
1847}
1848
1849fn resolve_parameter_marker<'a>(
1850    parameters: &'a BTreeMap<String, Value>,
1851    name: &str,
1852    path: Vec<usize>,
1853) -> Result<&'a Value> {
1854    let mut bound = parameters
1855        .get(name)
1856        .ok_or_else(|| HawDBError::Semantic(format!("missing parameter '${name}'")))?;
1857    for index in path {
1858        let Value::List(values) = bound else {
1859            return Err(HawDBError::Semantic(format!(
1860                "parameter '${name}' changed shape while binding a cached plan"
1861            )));
1862        };
1863        bound = values.get(index).ok_or_else(|| {
1864            HawDBError::Semantic(format!(
1865                "parameter '${name}' changed shape while binding a cached plan"
1866            ))
1867        })?;
1868    }
1869    Ok(bound)
1870}
1871
1872fn bind_value(value: &mut Value, parameters: BindingAction<'_>) -> Result<()> {
1873    let BindingAction::Execute(values) = parameters else {
1874        return Ok(());
1875    };
1876    if let Some((name, path)) = marker_name_and_path(value) {
1877        *value = resolve_parameter_marker(values, name, path)?.clone();
1878        return Ok(());
1879    }
1880    match value {
1881        Value::List(values) => bind_values(values, parameters),
1882        Value::Map(values) => bind_value_map(values, parameters),
1883        _ => Ok(()),
1884    }
1885}
1886
1887#[cfg(test)]
1888mod tests {
1889    use super::{
1890        bind_physical_plan_parameters, marker_use_in_logical_plan, parameter_marker,
1891        parameter_scalar_types, parameter_value_shape, parameterize_logical_plan,
1892        resolve_plan_template_value, MarkerUse, ParameterCacheValue, PARAMETER_SLOT_NAME_KEY,
1893        PARAMETER_SLOT_PATH_KEY,
1894    };
1895    use hawdb_core::Value;
1896    use hawdb_cypher as cypher;
1897    use hawdb_optimizer_graph::{CascadesOptimizer, OptimizerCatalog};
1898    use hawdb_plan_cypher::{
1899        CompositeRangeSeek, ExactPropertySeekBranch, LogicalPlanRoot, NodeProjectionAccess,
1900        PhysicalPlan,
1901    };
1902    use std::collections::BTreeMap;
1903
1904    #[test]
1905    fn unwind_read_parameters_rebind_in_logical_and_physical_templates() {
1906        let statement = cypher::parse(
1907            "UNWIND $ids AS candidate_id OPTIONAL MATCH (n:Item {id: candidate_id}) RETURN n.id",
1908        )
1909        .unwrap();
1910        let parameters = BTreeMap::from([(
1911            "ids".into(),
1912            Value::List(vec![Value::Int(1), Value::Int(1), Value::Null]),
1913        )]);
1914        let template = parameterize_logical_plan(&statement, &parameters).unwrap();
1915        assert_eq!(template.slot_count(), 1);
1916        let changed = BTreeMap::from([(
1917            "ids".into(),
1918            Value::List(vec![Value::Int(2), Value::Int(3), Value::Null]),
1919        )]);
1920        let mut rebound = template.logical().clone();
1921        super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed)).unwrap();
1922        assert_eq!(
1923            rebound,
1924            hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap()
1925        );
1926        let physical = CascadesOptimizer::default().optimize(template.logical());
1927        let physical = bind_physical_plan_parameters(&physical, &changed, true).unwrap();
1928        let mut sources = 0;
1929        hawdb_plan_cypher::visit_plan(&physical, &mut |node| {
1930            if let PhysicalPlan::UnwindExec { rows, .. } = node {
1931                assert_eq!(rows, &[Value::Int(2), Value::Int(3), Value::Null]);
1932                sources += 1;
1933            }
1934        });
1935        assert_eq!(sources, 1);
1936    }
1937
1938    #[test]
1939    fn row_unwind_parameters_rebind_in_logical_and_physical_templates() {
1940        let statement =
1941            cypher::parse("MATCH (n:Item) UNWIND [$candidate, n.id, null] AS item RETURN item")
1942                .unwrap();
1943        let parameters = BTreeMap::from([("candidate".into(), Value::String("first".into()))]);
1944        let changed = BTreeMap::from([("candidate".into(), Value::String("second".into()))]);
1945        let template = parameterize_logical_plan(&statement, &parameters).unwrap();
1946        assert_eq!(template.slot_count(), 1);
1947        let mut rebound = template.logical().clone();
1948        super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed)).unwrap();
1949        let expected = hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap();
1950        assert_eq!(rebound, expected);
1951        let physical = CascadesOptimizer::default().optimize(template.logical());
1952        let bound = bind_physical_plan_parameters(&physical, &changed, true).unwrap();
1953        assert_eq!(bound, CascadesOptimizer::default().optimize(&expected));
1954        let mut sources = 0;
1955        hawdb_plan_cypher::visit_plan(&bound, &mut |node| {
1956            if let PhysicalPlan::UnwindRowsExec { .. } = node {
1957                sources += 1;
1958            }
1959        });
1960        assert_eq!(sources, 1);
1961    }
1962
1963    #[test]
1964    fn proven_binding_template_skips_planning_and_validates_complete_signature() {
1965        let statement =
1966            cypher::parse("MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id LIMIT $limit")
1967                .unwrap();
1968        let parameters = BTreeMap::from([
1969            ("id".into(), Value::String("a".into())),
1970            ("limit".into(), Value::Int(3)),
1971        ]);
1972        let first = parameterize_logical_plan(&statement, &parameters).unwrap();
1973        let template = super::ParameterBindingTemplate::new(&first, &parameters).unwrap();
1974        let mut changed = parameters.clone();
1975        changed.insert("id".into(), Value::String("b".into()));
1976        super::PARAMETER_PLANNING_CALLS.with(|calls| calls.set(0));
1977        let reused = template.reuse(&changed).unwrap();
1978        assert!(std::sync::Arc::ptr_eq(&first.logical, &reused.logical));
1979        assert!(std::sync::Arc::ptr_eq(&first.cache_key, &reused.cache_key));
1980        assert_eq!(
1981            super::PARAMETER_PLANNING_CALLS.with(std::cell::Cell::get),
1982            0
1983        );
1984        let mut rebound = reused.logical().clone();
1985        super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed)).unwrap();
1986        assert_eq!(
1987            rebound,
1988            hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap()
1989        );
1990        changed.insert("limit".into(), Value::Int(4));
1991        assert!(template.reuse(&changed).is_none());
1992        changed = parameters.clone();
1993        changed.insert("id".into(), Value::Int(1));
1994        assert!(template.reuse(&changed).is_none());
1995        changed = parameters.clone();
1996        changed.remove("id");
1997        assert!(template.reuse(&changed).is_none());
1998        changed = parameters.clone();
1999        changed.insert("extra".into(), Value::Int(1));
2000        assert!(template.reuse(&changed).is_none());
2001        let unused = parameterize_logical_plan(&statement, &changed).unwrap();
2002        assert!(super::ParameterBindingTemplate::new(&unused, &changed).is_none());
2003    }
2004
2005    #[test]
2006    fn decimal_exact_cache_keys_keep_scale_inside_nested_values() {
2007        let value = |text: &str| {
2008            Value::List(vec![Value::Map(BTreeMap::from([(
2009                "amount".into(),
2010                Value::Decimal(text.parse().unwrap()),
2011            )]))])
2012        };
2013        let first = value("1.0");
2014        let second = value("1.00");
2015        assert_eq!(first, second);
2016        let keys = [
2017            ParameterCacheValue::Exact(first),
2018            ParameterCacheValue::Exact(second),
2019        ];
2020        assert_eq!(
2021            keys.iter()
2022                .cloned()
2023                .collect::<std::collections::BTreeSet<_>>()
2024                .len(),
2025            2
2026        );
2027        assert_eq!(
2028            keys.into_iter()
2029                .collect::<std::collections::HashSet<_>>()
2030                .len(),
2031            2
2032        );
2033    }
2034
2035    #[test]
2036    fn folded_null_guards_keep_shape_valid_rebinding() {
2037        for predicate in ["$gate IS NULL", "$gate IS NOT NULL"] {
2038            let statement = cypher::parse(&format!(
2039                "MATCH (n:Item) WHERE ({predicate} OR n.id = $gate) \
2040                 RETURN CASE n.id WHEN 'a' THEN $gate ELSE $gate END AS gate"
2041            ))
2042            .unwrap();
2043            let parameters = BTreeMap::from([("gate".into(), Value::Int(1))]);
2044            let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2045            let template = super::ParameterBindingTemplate::new(&plan, &parameters).unwrap();
2046            let changed = BTreeMap::from([("gate".into(), Value::Int(2))]);
2047            super::PARAMETER_PLANNING_CALLS.with(|calls| calls.set(0));
2048            let reused = template.reuse(&changed).unwrap();
2049            assert_eq!(
2050                super::PARAMETER_PLANNING_CALLS.with(std::cell::Cell::get),
2051                0
2052            );
2053            let mut rebound = reused.logical().clone();
2054            super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed))
2055                .unwrap();
2056            assert_eq!(
2057                rebound,
2058                hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap()
2059            );
2060            assert!(template
2061                .reuse(&BTreeMap::from([("gate".into(), Value::Null)]))
2062                .is_none());
2063        }
2064    }
2065
2066    #[test]
2067    fn folded_predicate_parameters_are_exact_even_when_also_projected() {
2068        for (predicate, initial, changed) in [
2069            ("$gate = 0", Value::Int(1), Value::Int(0)),
2070            ("$gate <> 1", Value::Int(2), Value::Int(1)),
2071            ("$gate = true", Value::Bool(false), Value::Bool(true)),
2072            ("$gate <> false", Value::Bool(true), Value::Bool(false)),
2073            ("$other = $gate", Value::Int(1), Value::Int(0)),
2074            ("$other <> $gate", Value::Int(1), Value::Int(0)),
2075        ] {
2076            let statement = cypher::parse(&format!(
2077                "MATCH (n:Item) WHERE ({predicate} OR n.id = $gate) \
2078                 RETURN n.id AS id, CASE n.id WHEN 'a' THEN $gate ELSE $gate END AS gate, \
2079                 CASE n.id WHEN 'a' THEN $other ELSE $other END AS other, \
2080                 CASE n.id WHEN 'a' THEN $score ELSE $score END AS score"
2081            ))
2082            .unwrap();
2083            let parameters = BTreeMap::from([
2084                ("gate".into(), initial),
2085                ("other".into(), Value::Int(0)),
2086                ("score".into(), Value::Float(0.5)),
2087            ]);
2088            let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2089            let template = super::ParameterBindingTemplate::new(&plan, &parameters).unwrap();
2090            let mut altered = parameters.clone();
2091            altered.insert("gate".into(), changed);
2092            assert!(
2093                template.reuse(&altered).is_none(),
2094                "folded guard {predicate}"
2095            );
2096            altered = parameters.clone();
2097            altered.insert("score".into(), Value::Float(0.75));
2098            let reused = template.reuse(&altered).unwrap();
2099            let mut rebound = reused.logical().clone();
2100            super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&altered))
2101                .unwrap();
2102            assert_eq!(
2103                rebound,
2104                hawdb_plan_cypher::plan_with_params(&statement, &altered).unwrap()
2105            );
2106        }
2107    }
2108
2109    #[test]
2110    fn scoped_case_template_retains_folded_booleans_as_exact_guards() {
2111        let mut query = "MATCH (n:Item) WHERE n.id IN $ids AND ($cross_space = true OR \
2112            n.space_id IN $spaces OR ($default_requested = true AND \
2113            (n.space_id IS NULL OR n.space_id = ''))) RETURN CASE n.id"
2114            .to_owned();
2115        let mut parameters = BTreeMap::from([
2116            ("cross_space".into(), Value::Bool(false)),
2117            (
2118                "spaces".into(),
2119                Value::List(vec![Value::String("default".into())]),
2120            ),
2121            ("default_requested".into(), Value::Bool(true)),
2122        ]);
2123        let mut ids = Vec::new();
2124        for index in 0..20 {
2125            query.push_str(&format!(" WHEN $id_{index} THEN $score_{index}"));
2126            let id = Value::String(format!("a{index}"));
2127            ids.push(id.clone());
2128            parameters.insert(format!("id_{index}"), id);
2129            parameters.insert(format!("score_{index}"), Value::Float(0.5));
2130        }
2131        query.push_str(" ELSE null END AS score");
2132        parameters.insert("ids".into(), Value::List(ids));
2133        let statement = cypher::parse(&query).unwrap();
2134        let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2135        let template = super::ParameterBindingTemplate::new(&plan, &parameters)
2136            .expect("folded boolean scope guards must permit safe template reuse");
2137        let mut changed = parameters.clone();
2138        changed.insert("score_0".into(), Value::Float(0.75));
2139        super::PARAMETER_PLANNING_CALLS.with(|calls| calls.set(0));
2140        let reused = template.reuse(&changed).unwrap();
2141        assert_eq!(
2142            super::PARAMETER_PLANNING_CALLS.with(std::cell::Cell::get),
2143            0
2144        );
2145        let mut rebound = reused.logical().clone();
2146        super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed)).unwrap();
2147        assert_eq!(
2148            rebound,
2149            hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap()
2150        );
2151        for name in ["cross_space", "default_requested"] {
2152            let mut altered = changed.clone();
2153            let Value::Bool(value) = altered[name] else {
2154                panic!("boolean fixture")
2155            };
2156            altered.insert(name.into(), Value::Bool(!value));
2157            assert!(template.reuse(&altered).is_none(), "changed scope {name}");
2158            altered.remove(name);
2159            assert!(template.reuse(&altered).is_none(), "missing scope {name}");
2160            altered.insert(name.into(), Value::Int(i64::from(value)));
2161            assert!(
2162                template.reuse(&altered).is_none(),
2163                "changed scope type {name}"
2164            );
2165        }
2166    }
2167
2168    #[test]
2169    fn simple_case_cohorts_parameterize_without_per_value_replanning() {
2170        for count in [20, 100, 512] {
2171            let mut query = "MATCH (n:Item) WHERE n.id IN $ids RETURN CASE n.id".to_owned();
2172            let mut parameters = BTreeMap::new();
2173            let mut ids = Vec::new();
2174            for index in 0..count {
2175                query.push_str(&format!(" WHEN $id_{index} THEN $score_{index}"));
2176                let id = Value::String(format!("item-{index}"));
2177                ids.push(id.clone());
2178                parameters.insert(format!("id_{index}"), id);
2179                parameters.insert(format!("score_{index}"), Value::Float(index as f64));
2180            }
2181            query.push_str(" ELSE null END AS score");
2182            parameters.insert("ids".into(), Value::List(ids));
2183            let statement = cypher::parse(&query).unwrap();
2184            super::PARAMETER_PLANNING_CALLS.with(|calls| calls.set(0));
2185            let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2186            let calls = super::PARAMETER_PLANNING_CALLS.with(std::cell::Cell::get);
2187            assert!(
2188                calls <= 3,
2189                "{count} candidates required {calls} logical plans"
2190            );
2191            assert_eq!(plan.slot_count(), parameters.len());
2192            assert!(plan.has_case_parameter_slots());
2193            let mut changed = parameters.clone();
2194            changed.insert("score_0".into(), Value::Float(-3.0));
2195            assert_eq!(
2196                plan.cache_key(),
2197                parameterize_logical_plan(&statement, &changed)
2198                    .unwrap()
2199                    .cache_key()
2200            );
2201            let mut rebound = plan.logical().clone();
2202            super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&changed))
2203                .unwrap();
2204            assert_eq!(
2205                rebound,
2206                hawdb_plan_cypher::plan_with_params(&statement, &changed).unwrap()
2207            );
2208        }
2209    }
2210
2211    #[test]
2212    fn case_retention_classification_preserves_non_case_slots_and_fallback() {
2213        for (query, parameters, case_slots) in [
2214            (
2215                "MATCH (n:Item) WHERE n.id = $id RETURN CASE n.id WHEN 'a' THEN 1 ELSE 0 END AS rank",
2216                BTreeMap::from([("id".into(), Value::String("a".into()))]),
2217                false,
2218            ),
2219            (
2220                "MATCH (n:Item) RETURN CASE n.id WHEN 'a' THEN $score ELSE 0 END AS rank LIMIT $take",
2221                BTreeMap::from([("score".into(), Value::Int(1)), ("take".into(), Value::Int(2))]),
2222                true,
2223            ),
2224        ] {
2225            let statement = cypher::parse(query).unwrap();
2226            let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2227            assert!(plan.slot_count() > 0);
2228            assert_eq!(plan.has_case_parameter_slots(), case_slots, "{query}");
2229            let mut rebound = plan.logical().clone();
2230            super::bind_logical_plan(&mut rebound, super::BindingAction::Execute(&parameters)).unwrap();
2231            assert_eq!(rebound, hawdb_plan_cypher::plan_with_params(&statement, &parameters).unwrap());
2232        }
2233    }
2234
2235    #[test]
2236    fn parameter_type_proofs_share_binding_markers_and_distinguish_numeric_shapes() {
2237        use hawdb_core::PropertyType;
2238        let parameters = BTreeMap::from([
2239            ("rank".into(), Value::Int(12)),
2240            (
2241                "keys".into(),
2242                Value::List(vec![
2243                    Value::String("id".into()),
2244                    Value::List(vec![Value::Bool(true), Value::Float(12.5)]),
2245                ]),
2246            ),
2247        ]);
2248        let mut parameters = parameters;
2249        parameters.insert(
2250            "unused".into(),
2251            Value::List(vec![Value::String("omitted".into()); 64]),
2252        );
2253        let statement = cypher::parse(
2254            "MATCH (n:Item) WHERE n.rank > $rank AND n.id IN $keys RETURN n.id AS id",
2255        )
2256        .unwrap();
2257        let plan = parameterize_logical_plan(&statement, &parameters).unwrap();
2258        let types = parameter_scalar_types(&plan, &parameters);
2259        assert_eq!(types.len(), 3);
2260        for (marker, kind) in &types {
2261            let value = resolve_plan_template_value(marker, &parameters, true).unwrap();
2262            assert!(matches!(
2263                (kind, value),
2264                (PropertyType::Int, Value::Int(_))
2265                    | (PropertyType::String, Value::String(_))
2266                    | (PropertyType::Bool, Value::Bool(_))
2267            ));
2268        }
2269        let int_marker = parameter_marker("rank", &Value::Int(12), &[]);
2270        assert_eq!(types.get(&int_marker), Some(&PropertyType::Int));
2271        let mut changed = parameters.clone();
2272        changed.insert("rank".into(), Value::Float(12.5));
2273        let changed_plan = parameterize_logical_plan(&statement, &changed).unwrap();
2274        assert!(!parameter_scalar_types(&changed_plan, &changed).contains_key(&int_marker));
2275        assert_ne!(plan.cache_key(), changed_plan.cache_key());
2276        assert_ne!(
2277            parameter_value_shape(&parameters["rank"]),
2278            parameter_value_shape(&changed["rank"])
2279        );
2280    }
2281
2282    #[test]
2283    fn cost_operand_resolution_borrows_values_and_preserves_literal_markers() {
2284        let parameters = BTreeMap::from([("id".into(), Value::String("point".into()))]);
2285        let marker = parameter_marker("id", &parameters["id"], &[]);
2286        let resolved = resolve_plan_template_value(&marker, &parameters, true).unwrap();
2287        assert!(std::ptr::eq(resolved, &parameters["id"]));
2288        assert!(std::ptr::eq(
2289            resolve_plan_template_value(&marker, &BTreeMap::new(), false).unwrap(),
2290            &marker
2291        ));
2292        assert!(resolve_plan_template_value(&marker, &BTreeMap::new(), true).is_err());
2293        let parameters = BTreeMap::from([("ids".into(), Value::List(vec![Value::Int(7)]))]);
2294        let Value::List(markers) = parameter_marker("ids", &parameters["ids"], &[]) else {
2295            panic!("expected list markers")
2296        };
2297        let resolved = resolve_plan_template_value(&markers[0], &parameters, true).unwrap();
2298        let Value::List(values) = &parameters["ids"] else {
2299            panic!("expected list operand")
2300        };
2301        assert!(std::ptr::eq(resolved, &values[0]));
2302        assert!(resolve_plan_template_value(
2303            &markers[0],
2304            &BTreeMap::from([("ids".into(), Value::Int(7))]),
2305            true
2306        )
2307        .is_err());
2308    }
2309
2310    #[test]
2311    fn unused_bindings_share_a_template_without_hiding_exact_parameters() {
2312        let statement =
2313            cypher::parse("MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id LIMIT $limit")
2314                .unwrap();
2315        let first = BTreeMap::from([
2316            ("id".into(), Value::Int(1)),
2317            ("limit".into(), Value::Int(3)),
2318            ("score".into(), Value::String("unused".into())),
2319        ]);
2320        let mut second = first.clone();
2321        second.insert("id".into(), Value::Int(2));
2322        second.insert("score".into(), Value::List(vec![Value::Int(9)]));
2323        let first_plan = parameterize_logical_plan(&statement, &first).unwrap();
2324        let second_plan = parameterize_logical_plan(&statement, &second).unwrap();
2325        assert_eq!(first_plan.cache_key(), second_plan.cache_key());
2326        assert!(!first_plan.cache_key.values.contains_key("score"));
2327        assert_eq!(first_plan.exact_variant_count(), 1);
2328        assert_eq!(first_plan.slot_count(), 1);
2329        second.remove("score");
2330        assert_eq!(
2331            first_plan.cache_key(),
2332            parameterize_logical_plan(&statement, &second)
2333                .unwrap()
2334                .cache_key()
2335        );
2336        second.insert("limit".into(), Value::Int(4));
2337        assert_ne!(
2338            first_plan.cache_key(),
2339            parameterize_logical_plan(&statement, &second)
2340                .unwrap()
2341                .cache_key()
2342        );
2343        second.remove("id");
2344        assert!(parameterize_logical_plan(&statement, &second).is_err());
2345    }
2346
2347    #[test]
2348    fn unused_only_bindings_leave_no_slots_and_preserve_literal_values() {
2349        let statement = cypher::parse("MATCH (n:Item) WHERE n.id = 1 RETURN n.id").unwrap();
2350        let empty = parameterize_logical_plan(&statement, &BTreeMap::new()).unwrap();
2351        let extra = parameterize_logical_plan(
2352            &statement,
2353            &BTreeMap::from([("unused".into(), Value::String("payload".into()))]),
2354        )
2355        .unwrap();
2356        assert_eq!(empty, extra);
2357        assert_eq!(extra.slot_count(), 0);
2358        assert_eq!(extra.exact_variant_count(), 0);
2359    }
2360
2361    #[test]
2362    fn general_case_preserves_exact_cache_keys_and_rebinds_explicit_template_slots() {
2363        let statement = cypher::parse("MATCH (n:Item) RETURN CASE WHEN n.id = $chosen THEN lower($label) ELSE $fallback END AS result").unwrap();
2364        let parameters = BTreeMap::from([
2365            ("chosen".into(), Value::Int(1)),
2366            ("label".into(), Value::String("FIRST".into())),
2367            ("fallback".into(), Value::String("old".into())),
2368        ]);
2369        let parameterized = parameterize_logical_plan(&statement, &parameters).unwrap();
2370        assert_eq!(parameterized.slot_count, 0);
2371        assert!(parameterized
2372            .cache_key
2373            .values
2374            .values()
2375            .all(|value| matches!(value, ParameterCacheValue::Exact(_))));
2376        // Projection parameters keep their existing conservative cache policy.
2377        // Explicit templates must nevertheless rebind all scalar descendants.
2378        let markers = parameters
2379            .iter()
2380            .map(|(name, value)| (name.clone(), parameter_marker(name, value, &[])))
2381            .collect();
2382        let logical = hawdb_plan_cypher::plan_with_params(&statement, &markers).unwrap();
2383        let root = CascadesOptimizer::default().optimize_root_with_catalog(
2384            &LogicalPlanRoot::new(logical),
2385            &OptimizerCatalog::default(),
2386        );
2387        let (template, _) = root.into_parts();
2388        let parameters = BTreeMap::from([
2389            ("chosen".into(), Value::Int(2)),
2390            ("label".into(), Value::String("SECOND".into())),
2391            ("fallback".into(), Value::String("new".into())),
2392        ]);
2393        let rebound = bind_physical_plan_parameters(&template, &parameters, true).unwrap();
2394        let text = format!("{rebound:?}");
2395        assert!(text.contains("SECOND") && text.contains("new"), "{text}");
2396        assert!(!text.contains("hawdb_parameter_slot"), "{text}");
2397    }
2398
2399    #[test]
2400    fn list_expression_parameters_are_detected_keyed_and_rebound() {
2401        let statement = cypher::parse(
2402            "MATCH (n:Item) WITH n, n.tags AS tags WHERE size(tags) > $min_size AND $needle IN tags \
2403             RETURN [x IN range($start, $end) WHERE x > $floor | coalesce(tags[x], $missing)] AS picked, \
2404             n.tags[$index..] AS rest ORDER BY head(tags[..$prefix]) DESC",
2405        )
2406        .unwrap();
2407        let names = [
2408            "min_size", "needle", "start", "end", "floor", "missing", "index", "prefix",
2409        ];
2410        let parameters = names
2411            .iter()
2412            .enumerate()
2413            .map(|(index, name)| {
2414                let value = if *name == "needle" || *name == "missing" {
2415                    Value::String(format!("old-{index}"))
2416                } else {
2417                    Value::Int(index as i64)
2418                };
2419                (name.to_string(), value)
2420            })
2421            .collect::<BTreeMap<_, _>>();
2422        let parameterized = parameterize_logical_plan(&statement, &parameters).unwrap();
2423        // Every parameter is seen; list expressions keep the conservative
2424        // exact-key policy of other scalar expressions, so no value is dropped.
2425        assert_eq!(parameterized.slot_count, 0);
2426        for name in names {
2427            assert!(
2428                matches!(
2429                    parameterized.cache_key.values.get(name),
2430                    Some(ParameterCacheValue::Exact(_))
2431                ),
2432                "{name}: {:?}",
2433                parameterized.cache_key
2434            );
2435        }
2436        let markers = parameters
2437            .iter()
2438            .map(|(name, value)| (name.clone(), parameter_marker(name, value, &[])))
2439            .collect::<BTreeMap<_, _>>();
2440        let logical = hawdb_plan_cypher::plan_with_params(&statement, &markers).unwrap();
2441        for name in names {
2442            assert_ne!(
2443                marker_use_in_logical_plan(&logical, name),
2444                MarkerUse::None,
2445                "{name}"
2446            );
2447        }
2448        let root = CascadesOptimizer::default().optimize_root_with_catalog(
2449            &LogicalPlanRoot::new(logical),
2450            &OptimizerCatalog::default(),
2451        );
2452        let (template, _) = root.into_parts();
2453        let rebound_parameters = names
2454            .iter()
2455            .map(|name| (name.to_string(), Value::String(format!("rebound-{name}"))))
2456            .collect::<BTreeMap<_, _>>();
2457        let rebound = bind_physical_plan_parameters(&template, &rebound_parameters, true).unwrap();
2458        let text = format!("{rebound:?}");
2459        for name in names {
2460            assert!(text.contains(&format!("rebound-{name}")), "{name}: {text}");
2461        }
2462        assert!(!text.contains("hawdb_parameter_slot"), "{text}");
2463        assert!(!text.contains("skein_parameter_slot"), "{text}");
2464    }
2465
2466    #[test]
2467    fn load_csv_plans_keep_parameter_sources_unbound_and_reusable() {
2468        let statement = cypher::parse(
2469            "LOAD CSV WITH HEADERS FROM $f AS row WITH row WHERE toInteger(row.id) > $min \
2470             RETURN row.name AS name",
2471        )
2472        .unwrap();
2473        let first = BTreeMap::from([
2474            ("f".to_string(), Value::String("/import/a.csv".into())),
2475            ("min".to_string(), Value::Int(1)),
2476        ]);
2477        let second = BTreeMap::from([
2478            ("f".to_string(), Value::String("/import/b.csv".into())),
2479            ("min".to_string(), Value::Int(1)),
2480        ]);
2481        let first = parameterize_logical_plan(&statement, &first).unwrap();
2482        let second = parameterize_logical_plan(&statement, &second).unwrap();
2483        // The file location is never part of the plan or its cache key, so one
2484        // cached plan serves every file; execution resolves `$f` again.
2485        assert_eq!(first.logical, second.logical);
2486        assert_eq!(first.cache_key, second.cache_key);
2487        assert!(
2488            !first.cache_key.values.contains_key("f"),
2489            "{:?}",
2490            first.cache_key
2491        );
2492        let text = format!("{:?}", first.logical);
2493        assert!(text.contains("Parameter(\"f\")"), "{text}");
2494        assert!(!text.contains("a.csv"), "{text}");
2495
2496        let physical = CascadesOptimizer::default().optimize(&first.logical);
2497        let rebound = bind_physical_plan_parameters(
2498            &physical,
2499            &BTreeMap::from([("min".to_string(), Value::Int(5))]),
2500            first.slot_count > 0,
2501        )
2502        .unwrap();
2503        let mut sources = Vec::new();
2504        hawdb_plan_cypher::visit_plan(&rebound, &mut |node| {
2505            if let PhysicalPlan::LoadCsvExec { source } = node {
2506                sources.push(source.clone());
2507            }
2508        });
2509        assert_eq!(sources.len(), 1, "{rebound:?}");
2510        assert_eq!(
2511            sources[0].location,
2512            hawdb_plan_cypher::CsvLocation::Parameter("f".to_string())
2513        );
2514    }
2515
2516    #[test]
2517    fn clause_match_rebinds_every_step_predicate_and_input() {
2518        let query = "MATCH (a:Item {id: $a}) OPTIONAL MATCH (a)-[r:LINK {code: $code}]->(b:Item {id: $b}) WHERE b.visible = $visible RETURN b";
2519        let slots = ["a", "b", "code", "visible"];
2520        let parameters = slots
2521            .into_iter()
2522            .map(|name| {
2523                (
2524                    name.to_string(),
2525                    parameter_marker(name, &Value::Int(0), &[]),
2526                )
2527            })
2528            .collect();
2529        let logical = hawdb_plan_cypher::plan_pipeline_query(query, &parameters).unwrap();
2530        for name in slots {
2531            assert_eq!(
2532                marker_use_in_logical_plan(&logical, name),
2533                MarkerUse::Safe,
2534                "{name}"
2535            );
2536        }
2537        let optimize = |logical| {
2538            CascadesOptimizer::default()
2539                .optimize_root_with_catalog(
2540                    &LogicalPlanRoot::new(logical),
2541                    &OptimizerCatalog::default(),
2542                )
2543                .into_parts()
2544                .0
2545        };
2546        let template = optimize(logical);
2547        let original = template.instance_fingerprint();
2548        for base in [10, 20] {
2549            let parameters = slots
2550                .into_iter()
2551                .enumerate()
2552                .map(|(index, name)| (name.to_string(), Value::Int(base + index as i64)))
2553                .collect();
2554            let rebound = bind_physical_plan_parameters(&template, &parameters, true).unwrap();
2555            let fresh =
2556                optimize(hawdb_plan_cypher::plan_pipeline_query(query, &parameters).unwrap());
2557            assert_eq!(rebound.instance_fingerprint(), fresh.instance_fingerprint());
2558            assert!(!rebound
2559                .instance_fingerprint()
2560                .contains("hawdb_parameter_slot"));
2561        }
2562        assert_eq!(template.instance_fingerprint(), original);
2563        assert!(bind_physical_plan_parameters(&template, &BTreeMap::new(), true).is_err());
2564    }
2565
2566    #[test]
2567    fn equality_parameters_become_rebindable_slots() {
2568        let statement =
2569            cypher::parse("MATCH (m:Memory) WHERE m.id = $id RETURN m.title AS title").unwrap();
2570        let first_parameters =
2571            BTreeMap::from([("id".to_string(), Value::String("first".to_string()))]);
2572        let parameterized = parameterize_logical_plan(&statement, &first_parameters).unwrap();
2573        assert!(matches!(
2574            parameterized.cache_key.values.get("id"),
2575            Some(ParameterCacheValue::Slot(_))
2576        ));
2577
2578        let root = CascadesOptimizer::default().optimize_root_with_catalog(
2579            &LogicalPlanRoot::new(parameterized.logical().clone()),
2580            &OptimizerCatalog::default(),
2581        );
2582        let (template, _) = root.into_parts();
2583        let rebound = bind_physical_plan_parameters(
2584            &template,
2585            &BTreeMap::from([("id".to_string(), Value::String("second".to_string()))]),
2586            true,
2587        )
2588        .unwrap();
2589
2590        assert!(rebound.explain(0).contains("second"));
2591        assert!(!rebound.explain(0).contains("hawdb_parameter_slot"));
2592    }
2593
2594    #[test]
2595    fn scoring_rerank_rebinds_its_input_and_rejects_missing_parameter_slots() {
2596        let spec = hawdb_core::graph_rag::ScoringSpec::weighted_scores(2.0, 1.0);
2597        let template = PhysicalPlan::ScoringRerankExec {
2598            score_column: "seed_score".into(),
2599            spec: spec.clone(),
2600            limit: 3,
2601            input: Box::new(PhysicalPlan::IndexNodeSeek {
2602                variable: "n".into(),
2603                label: "Item".into(),
2604                property: "scope".into(),
2605                value: parameter_marker("scope", &Value::String("template".into()), &[]),
2606            }),
2607        };
2608        for scope in ["first", "second"] {
2609            let rebound = bind_physical_plan_parameters(
2610                &template,
2611                &BTreeMap::from([("scope".into(), Value::String(scope.into()))]),
2612                true,
2613            )
2614            .unwrap();
2615            let PhysicalPlan::ScoringRerankExec {
2616                score_column,
2617                spec: rebound_spec,
2618                limit,
2619                input,
2620            } = rebound
2621            else {
2622                panic!("scoring operator must be preserved");
2623            };
2624            assert_eq!(score_column, "seed_score");
2625            assert_eq!(rebound_spec, spec);
2626            assert_eq!(limit, 3);
2627            let PhysicalPlan::IndexNodeSeek { value, .. } = *input else {
2628                panic!("scoring input seek must be preserved");
2629            };
2630            assert_eq!(
2631                value,
2632                Value::String(scope.into()),
2633                "scoring input must use current request values"
2634            );
2635        }
2636        assert!(bind_physical_plan_parameters(&template, &BTreeMap::new(), true).is_err());
2637        let PhysicalPlan::ScoringRerankExec { input, .. } = &template else {
2638            unreachable!()
2639        };
2640        let PhysicalPlan::IndexNodeSeek { value, .. } = input.as_ref() else {
2641            unreachable!()
2642        };
2643        assert_eq!(
2644            *value,
2645            parameter_marker("scope", &Value::String("template".into()), &[]),
2646            "binding must not mutate the retained template"
2647        );
2648    }
2649
2650    #[test]
2651    fn adjacency_exists_rebinds_its_input_and_rejects_missing_parameter_slots() {
2652        let marker = parameter_marker("scope", &Value::String("template".into()), &[]);
2653        let template = PhysicalPlan::AdjacencyExistsExec {
2654            source_variable: "n".into(),
2655            rel_type: "REL".into(),
2656            direction: cypher::RelationshipDirection::Outgoing,
2657            target_variable: "s".into(),
2658            input: Box::new(PhysicalPlan::IndexNodeSeek {
2659                variable: "n".into(),
2660                label: "Item".into(),
2661                property: "scope".into(),
2662                value: marker.clone(),
2663            }),
2664        };
2665        let original = template.clone();
2666        for scope in ["first", "second"] {
2667            let rebound = bind_physical_plan_parameters(
2668                &template,
2669                &BTreeMap::from([("scope".into(), Value::String(scope.into()))]),
2670                true,
2671            )
2672            .unwrap();
2673            let PhysicalPlan::AdjacencyExistsExec {
2674                source_variable,
2675                rel_type,
2676                direction,
2677                target_variable,
2678                input,
2679            } = rebound
2680            else {
2681                panic!("EXISTS operator must be preserved");
2682            };
2683            assert_eq!(source_variable, "n");
2684            assert_eq!(rel_type, "REL");
2685            assert_eq!(direction, cypher::RelationshipDirection::Outgoing);
2686            assert_eq!(target_variable, "s");
2687            let PhysicalPlan::IndexNodeSeek { value, .. } = *input else {
2688                panic!("EXISTS input seek must be preserved");
2689            };
2690            assert_eq!(value, Value::String(scope.into()));
2691        }
2692        assert!(bind_physical_plan_parameters(&template, &BTreeMap::new(), true).is_err());
2693        assert_eq!(
2694            template, original,
2695            "binding must preserve the cached template"
2696        );
2697    }
2698
2699    #[test]
2700    fn graph_hash_join_rebinds_both_inputs_without_changing_keys() {
2701        let seek = |variable: &str, parameter: &str| PhysicalPlan::IndexNodeSeek {
2702            variable: variable.into(),
2703            label: "Item".into(),
2704            property: "scope".into(),
2705            value: parameter_marker(parameter, &Value::Int(0), &[]),
2706        };
2707        let template = PhysicalPlan::HashJoinExec {
2708            left_key: hawdb_plan_cypher::HashJoinKey {
2709                variable: "a".into(),
2710                property: "key".into(),
2711            },
2712            right_key: hawdb_plan_cypher::HashJoinKey {
2713                variable: "b".into(),
2714                property: "key".into(),
2715            },
2716            left: Box::new(seek("a", "left_scope")),
2717            right: Box::new(seek("b", "right_scope")),
2718        };
2719        for (a, b) in [(1, 2), (3, 4)] {
2720            let bound = bind_physical_plan_parameters(
2721                &template,
2722                &BTreeMap::from([
2723                    ("left_scope".into(), Value::Int(a)),
2724                    ("right_scope".into(), Value::Int(b)),
2725                ]),
2726                true,
2727            )
2728            .unwrap();
2729            let PhysicalPlan::HashJoinExec {
2730                left_key,
2731                right_key,
2732                left,
2733                right,
2734            } = bound
2735            else {
2736                unreachable!()
2737            };
2738            assert_eq!(left_key.variable, "a");
2739            assert_eq!(right_key.variable, "b");
2740            assert!(
2741                matches!(*left, PhysicalPlan::IndexNodeSeek { value: Value::Int(value), .. } if value == a)
2742            );
2743            assert!(
2744                matches!(*right, PhysicalPlan::IndexNodeSeek { value: Value::Int(value), .. } if value == b)
2745            );
2746        }
2747    }
2748
2749    #[test]
2750    fn projected_index_access_rebinds_parameter_slots() {
2751        let template = PhysicalPlan::NodeProjectionScanExec {
2752            variable: "m".to_string(),
2753            label: "Memory".to_string(),
2754            access: NodeProjectionAccess::PropertyValues {
2755                property: "stable_id".to_string(),
2756                values: vec![parameter_marker(
2757                    "id",
2758                    &Value::String("first".to_string()),
2759                    &[],
2760                )],
2761            },
2762            required_properties: vec!["stable_id".to_string()],
2763            predicate: None,
2764            items: Vec::new(),
2765        };
2766
2767        let rebound = bind_physical_plan_parameters(
2768            &template,
2769            &BTreeMap::from([("id".to_string(), Value::String("second".to_string()))]),
2770            true,
2771        )
2772        .unwrap();
2773
2774        assert!(matches!(
2775            rebound,
2776            PhysicalPlan::NodeProjectionScanExec {
2777                access: NodeProjectionAccess::PropertyValues { values, .. },
2778                ..
2779            } if values == vec![Value::String("second".to_string())]
2780        ));
2781    }
2782
2783    #[test]
2784    fn projected_union_access_rebinds_every_branch() {
2785        let marker = || parameter_marker("id", &Value::String("first".to_string()), &[]);
2786        let template = PhysicalPlan::NodeProjectionScanExec {
2787            variable: "m".to_string(),
2788            label: "Memory".to_string(),
2789            access: NodeProjectionAccess::PropertyUnion {
2790                branches: vec![
2791                    ExactPropertySeekBranch {
2792                        property: "id".to_string(),
2793                        values: vec![marker()],
2794                    },
2795                    ExactPropertySeekBranch {
2796                        property: "external_id".to_string(),
2797                        values: vec![marker()],
2798                    },
2799                ],
2800            },
2801            required_properties: vec!["id".to_string(), "external_id".to_string()],
2802            predicate: None,
2803            items: Vec::new(),
2804        };
2805
2806        let rebound = bind_physical_plan_parameters(
2807            &template,
2808            &BTreeMap::from([("id".to_string(), Value::String("second".to_string()))]),
2809            true,
2810        )
2811        .unwrap();
2812
2813        let PhysicalPlan::NodeProjectionScanExec {
2814            access: NodeProjectionAccess::PropertyUnion { branches },
2815            ..
2816        } = rebound
2817        else {
2818            panic!("expected projected union access");
2819        };
2820        assert!(branches
2821            .iter()
2822            .all(|branch| { branch.values == vec![Value::String("second".to_string())] }));
2823    }
2824
2825    #[test]
2826    fn projected_composite_range_rebinds_prefix_and_bounds() {
2827        let template = PhysicalPlan::NodeProjectionScanExec {
2828            variable: "m".to_string(),
2829            label: "Memory".to_string(),
2830            access: NodeProjectionAccess::CompositeRange {
2831                seek: CompositeRangeSeek {
2832                    index_properties: vec!["space_id".to_string(), "created_at".to_string()],
2833                    equality_prefix: vec![(
2834                        "space_id".to_string(),
2835                        parameter_marker(
2836                            "space_id",
2837                            &Value::String("space:first".to_string()),
2838                            &[],
2839                        ),
2840                    )],
2841                    range_property: "created_at".to_string(),
2842                    lower: Some((parameter_marker("lower", &Value::Int(10), &[]), true)),
2843                    upper: Some((parameter_marker("upper", &Value::Int(20), &[]), false)),
2844                },
2845            },
2846            required_properties: vec!["space_id".to_string(), "created_at".to_string()],
2847            predicate: None,
2848            items: Vec::new(),
2849        };
2850
2851        let rebound = bind_physical_plan_parameters(
2852            &template,
2853            &BTreeMap::from([
2854                (
2855                    "space_id".to_string(),
2856                    Value::String("space:second".to_string()),
2857                ),
2858                ("lower".to_string(), Value::Int(30)),
2859                ("upper".to_string(), Value::Int(40)),
2860            ]),
2861            true,
2862        )
2863        .unwrap();
2864
2865        assert!(matches!(
2866            rebound,
2867            PhysicalPlan::NodeProjectionScanExec {
2868                access: NodeProjectionAccess::CompositeRange { seek },
2869                ..
2870            } if seek.equality_prefix
2871                == vec![(
2872                    "space_id".to_string(),
2873                    Value::String("space:second".to_string()),
2874                )]
2875                && seek.lower == Some((Value::Int(30), true))
2876                && seek.upper == Some((Value::Int(40), false))
2877        ));
2878    }
2879
2880    #[test]
2881    fn pagination_parameters_remain_exact_variants() {
2882        let statement =
2883            cypher::parse("MATCH (m:Memory) RETURN m.id AS id ORDER BY m.id LIMIT $limit").unwrap();
2884        let parameterized = parameterize_logical_plan(
2885            &statement,
2886            &BTreeMap::from([("limit".to_string(), Value::Int(10))]),
2887        )
2888        .unwrap();
2889
2890        assert_eq!(
2891            parameterized.cache_key.values.get("limit"),
2892            Some(&ParameterCacheValue::Exact(Value::Int(10)))
2893        );
2894    }
2895
2896    #[test]
2897    fn parameters_that_change_logical_simplification_remain_exact_variants() {
2898        let statement = cypher::parse(
2899            "MATCH (t:Thread) WHERE $source IS NULL OR t.source = $source RETURN t.id AS id",
2900        )
2901        .unwrap();
2902        let parameterized = parameterize_logical_plan(
2903            &statement,
2904            &BTreeMap::from([("source".to_string(), Value::Null)]),
2905        )
2906        .unwrap();
2907
2908        assert_eq!(
2909            parameterized.cache_key.values.get("source"),
2910            Some(&ParameterCacheValue::Exact(Value::Null))
2911        );
2912    }
2913
2914    #[test]
2915    fn multiple_equality_parameters_share_one_rebindable_template() {
2916        let statement =
2917            cypher::parse("MATCH (m:Memory) WHERE m.id = $id AND m.kind = $kind RETURN m.id AS id")
2918                .unwrap();
2919        let parameterized = parameterize_logical_plan(
2920            &statement,
2921            &BTreeMap::from([
2922                ("id".to_string(), Value::String("memory-1".to_string())),
2923                ("kind".to_string(), Value::String("note".to_string())),
2924            ]),
2925        )
2926        .unwrap();
2927
2928        assert_eq!(parameterized.slot_count, 2);
2929        assert!(parameterized
2930            .cache_key
2931            .values
2932            .values()
2933            .all(|cached| matches!(cached, ParameterCacheValue::Slot(_))));
2934    }
2935
2936    #[test]
2937    fn marker_shaped_parameter_values_disable_slots() {
2938        let statement =
2939            cypher::parse("MATCH (m:Memory) WHERE m.metadata = $metadata RETURN m.id AS id")
2940                .unwrap();
2941        let marker_shaped = Value::Map(BTreeMap::from([
2942            (
2943                PARAMETER_SLOT_NAME_KEY.to_string(),
2944                Value::String("other".to_string()),
2945            ),
2946            (PARAMETER_SLOT_PATH_KEY.to_string(), Value::List(Vec::new())),
2947        ]));
2948        let parameterized = parameterize_logical_plan(
2949            &statement,
2950            &BTreeMap::from([("metadata".to_string(), marker_shaped.clone())]),
2951        )
2952        .unwrap();
2953
2954        assert_eq!(parameterized.slot_count, 0);
2955        assert_eq!(
2956            parameterized.cache_key.values.get("metadata"),
2957            Some(&ParameterCacheValue::Exact(marker_shaped))
2958        );
2959    }
2960}
2961
2962// Retained query ownership: ParameterCacheValue.
2963impl hawdb_core::RetainedHeapBytes for ParameterCacheValue {
2964    fn retained_heap_bytes(&self) -> Option<usize> {
2965        match self {
2966            Self::Slot(value0) => hawdb_core::checked_retained_heap_sum([
2967                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
2968            ]),
2969            Self::CaseSlot(value0) => hawdb_core::checked_retained_heap_sum([
2970                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
2971            ]),
2972            Self::Exact(value0) => hawdb_core::checked_retained_heap_sum([
2973                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
2974            ]),
2975        }
2976    }
2977}
2978
2979// Retained query ownership: ParameterValueShape.
2980impl hawdb_core::RetainedHeapBytes for ParameterValueShape {
2981    fn retained_heap_bytes(&self) -> Option<usize> {
2982        match self {
2983            Self::Null => hawdb_core::checked_retained_heap_sum([]),
2984            Self::Bool => hawdb_core::checked_retained_heap_sum([]),
2985            Self::Int => hawdb_core::checked_retained_heap_sum([]),
2986            Self::Float => hawdb_core::checked_retained_heap_sum([]),
2987            Self::String => hawdb_core::checked_retained_heap_sum([]),
2988            Self::Binary => hawdb_core::checked_retained_heap_sum([]),
2989            Self::Decimal(kind) => hawdb_core::RetainedHeapBytes::retained_heap_bytes(kind),
2990            Self::Vector(value0) => hawdb_core::checked_retained_heap_sum([
2991                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
2992            ]),
2993            Self::Uuid => hawdb_core::checked_retained_heap_sum([]),
2994            Self::Date
2995            | Self::LocalTime
2996            | Self::LocalDateTime
2997            | Self::DateTime
2998            | Self::Duration => hawdb_core::checked_retained_heap_sum([]),
2999            Self::List(value0) => hawdb_core::checked_retained_heap_sum([
3000                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
3001            ]),
3002            Self::Map(value0) => hawdb_core::checked_retained_heap_sum([
3003                hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
3004            ]),
3005        }
3006    }
3007}
3008
3009// Retained query ownership: PlanParameterCacheKey.
3010hawdb_core::impl_retained_heap_for_struct!(PlanParameterCacheKey { values });