hawdb 0.3.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    optimizer_config_from_database_config, statement_body, DatabaseConfig,
    QueryAccessControlContext, SharedState,
};
use crate::cypher;
use crate::error::{HawDBError, Result};
use crate::optimizer::{
    CascadesOptimizer, LogicalPlanRoot, OptimizerCatalog, OptimizerSearchDirective, OptimizerTrace,
    PhysicalPlan,
};
use crate::planner::{self, LogicalPlan, Predicate};
use crate::schema::{Catalog, GraphStatistics, IndexKind};
use crate::store::GraphStore;
use crate::value::Value;
use hawdb_optimizer::graph::optimizer_catalog_from_graph_statistics;
use hawdb_plan_cache::{
    bind_physical_plan_parameters, parameterize_logical_plan, parameterize_value_list, LfuCache,
    PlanParameterCacheKey,
};
pub use hawdb_plan_cache::{PlanCacheBypassReason, PlanCacheLookup, PlanCacheStats};
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::Arc;

pub(crate) const DEFAULT_PLAN_CACHE_MAX_ENTRIES: usize = 128;
const ACCESS_CONTROL_VALUES_PARAMETER: &str = "\0hawdb_access_control_visibility_values";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PlanCacheMode {
    Use,
    Bypass(PlanCacheBypassReason),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PlanTraceMode {
    Template,
    Bound,
}

pub(super) struct PlanCacheContext<'a, S = GraphStore> {
    pub(super) catalog: &'a Catalog,
    pub(super) store: &'a S,
    pub(super) optimizer: &'a CascadesOptimizer,
    pub(super) config: &'a DatabaseConfig,
    pub(super) cache: &'a SharedState<PlanCache>,
    pub(super) planning_cache: &'a SharedState<OptimizerPlanningCache>,
    pub(super) access_control: Option<&'a QueryAccessControlContext>,
    pub(super) optimizer_search: OptimizerSearchDirective,
}

pub(super) struct OptimizedQueryPlan {
    pub(super) physical_plan: PhysicalPlan,
    pub(super) trace: OptimizerTrace,
    pub(super) plan_cache_lookup: PlanCacheLookup,
    pub(super) optimizer_environment: OptimizerEnvironmentKey,
    pub(super) configured_max_optimizer_groups: Option<usize>,
    pub(super) effective_max_optimizer_groups: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub(super) struct CachedPlan {
    physical_template: PhysicalPlan,
    trace: OptimizerTrace,
    has_parameter_slots: bool,
}

pub(super) type PlanCache = LfuCache<PlanCacheKey, CachedPlan>;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) struct PlanCacheKey {
    normalized_query: String,
    parameters: PlanParameterCacheKey,
    environment: OptimizerEnvironmentKey,
    max_optimizer_groups: Option<usize>,
    access_control: Option<AccessControlPlanCacheKey>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct AccessControlPlanCacheKey {
    policy_epoch: u64,
    visibility_property: String,
    visibility_value_count: usize,
}

impl From<&QueryAccessControlContext> for AccessControlPlanCacheKey {
    fn from(access_control: &QueryAccessControlContext) -> Self {
        Self {
            policy_epoch: access_control.policy_epoch(),
            visibility_property: access_control.visibility_property().to_string(),
            visibility_value_count: access_control.allowed_visibility_values().len(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) struct OptimizerEnvironmentKey {
    schema: OptimizerSchemaKey,
    statistics_generation: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct OptimizerSchemaKey {
    labels: Vec<String>,
    relationship_types: Vec<String>,
    equality_indexes: Vec<(String, String)>,
    range_indexes: Vec<(String, String)>,
    full_text_indexes: Vec<(String, String)>,
    composite_indexes: Vec<(String, Vec<String>)>,
}

#[derive(Debug, Clone)]
struct CachedOptimizerCatalog {
    environment: OptimizerEnvironmentKey,
    source_graph_commit_epoch: u64,
    catalog: Arc<OptimizerCatalog>,
}

/// Identity of a published advanced-statistics snapshot.
///
/// Live basic counts may change while this identity remains stable. Those changes
/// rebuild the optimizer catalog without invalidating otherwise reusable plans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct StatisticsPublicationKey {
    computed_at_commit_epoch: u64,
    advanced_statistics_complete: bool,
}

impl From<&GraphStatistics> for StatisticsPublicationKey {
    fn from(statistics: &GraphStatistics) -> Self {
        Self {
            computed_at_commit_epoch: statistics.computed_at_commit_epoch,
            advanced_statistics_complete: statistics.advanced_statistics_complete,
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct StatisticsCacheRefresh {
    snapshot_refreshed: bool,
    publication_changed: bool,
}

#[derive(Debug, Clone, Default)]
pub(super) struct OptimizerPlanningCache {
    statistics: Option<Arc<GraphStatistics>>,
    statistics_schema: Option<OptimizerSchemaKey>,
    statistics_source_graph_commit_epoch: Option<u64>,
    statistics_publication: Option<StatisticsPublicationKey>,
    statistics_generation: u64,
    catalog: Option<CachedOptimizerCatalog>,
}

struct OptimizerCatalogAccess {
    environment: OptimizerEnvironmentKey,
    catalog: Arc<OptimizerCatalog>,
    decisions: Vec<String>,
}

impl OptimizerSchemaKey {
    fn from_catalog(catalog: &Catalog) -> Self {
        let labels = catalog.labels().map(|label| label.name.clone()).collect();
        let relationship_types = catalog
            .rel_types()
            .map(|rel_type| rel_type.name.clone())
            .collect();
        let mut equality_indexes = Vec::new();
        let mut range_indexes = Vec::new();
        let mut full_text_indexes = Vec::new();
        for index in catalog.property_indexes() {
            let Some(label) = catalog.label_name(index.label_id) else {
                continue;
            };
            let descriptor = (label.to_string(), index.property.clone());
            match index.kind {
                IndexKind::Equality => equality_indexes.push(descriptor),
                IndexKind::Range => range_indexes.push(descriptor),
                IndexKind::FullText => full_text_indexes.push(descriptor),
            }
        }
        let composite_indexes = catalog
            .composite_property_indexes()
            .filter_map(|index| {
                catalog
                    .label_name(index.label_id)
                    .map(|label| (label.to_string(), index.properties.clone()))
            })
            .collect();
        Self {
            labels,
            relationship_types,
            equality_indexes,
            range_indexes,
            full_text_indexes,
            composite_indexes,
        }
    }
}

impl OptimizerEnvironmentKey {
    /// A prepared query may reuse a physical plan across data and statistics
    /// generations because those affect cost only. Schema changes can alter an
    /// operator's legality and therefore require re-planning.
    pub(super) fn is_execution_compatible(&self, catalog: &Catalog) -> bool {
        self.schema == OptimizerSchemaKey::from_catalog(catalog)
    }
}

impl OptimizerPlanningCache {
    pub(super) fn invalidate(&mut self) {
        self.statistics = None;
        self.statistics_schema = None;
        self.statistics_source_graph_commit_epoch = None;
        self.statistics_publication = None;
        // In-flight snapshots can still publish plans after invalidation. Keep
        // generations monotonic so a refreshed environment cannot reuse their key.
        self.catalog = None;
    }

    pub(super) fn environment_hint<R: hawdb_storage::graph_engine::GraphReadEngine>(
        &mut self,
        catalog: &Catalog,
        store: &R,
    ) -> OptimizerEnvironmentKey {
        // A cache lookup must retain the last published statistics generation:
        // ordinary data commits do not make a physical plan illegal. A cache
        // miss refreshes the snapshot before choosing a new plan instead.
        self.ensure_statistics(catalog, store, false);
        OptimizerEnvironmentKey {
            schema: OptimizerSchemaKey::from_catalog(catalog),
            statistics_generation: self.statistics_generation,
        }
    }

    fn ensure_statistics<R: hawdb_storage::graph_engine::GraphReadEngine>(
        &mut self,
        catalog: &Catalog,
        store: &R,
        refresh_for_data_change: bool,
    ) -> StatisticsCacheRefresh {
        let schema = OptimizerSchemaKey::from_catalog(catalog);
        let source_graph_commit_epoch = store.commit_epoch();
        let refresh_statistics = self.statistics.is_none()
            || self.statistics_schema.as_ref() != Some(&schema)
            || (refresh_for_data_change
                && self.statistics_source_graph_commit_epoch != Some(source_graph_commit_epoch));
        if !refresh_statistics {
            return StatisticsCacheRefresh::default();
        }

        let statistics = Arc::new(store.statistics(catalog));
        let publication = StatisticsPublicationKey::from(statistics.as_ref());
        let publication_changed = self.statistics_publication != Some(publication);
        self.statistics = Some(statistics);
        self.statistics_schema = Some(schema);
        self.statistics_source_graph_commit_epoch = Some(source_graph_commit_epoch);
        self.statistics_publication = Some(publication);
        if publication_changed {
            self.statistics_generation = self.statistics_generation.saturating_add(1);
        }
        self.catalog = None;
        StatisticsCacheRefresh {
            snapshot_refreshed: true,
            publication_changed,
        }
    }

    fn optimizer_catalog<R: hawdb_storage::graph_engine::GraphReadEngine>(
        &mut self,
        catalog: &Catalog,
        store: &R,
    ) -> OptimizerCatalogAccess {
        let mut decisions = Vec::new();
        // This path is reached only after the physical-plan cache missed or
        // was intentionally bypassed, so cost-based planning must observe the
        // latest committed graph statistics.
        let refresh = self.ensure_statistics(catalog, store, true);
        if refresh.snapshot_refreshed {
            let statistics = self
                .statistics
                .as_ref()
                .expect("statistics exist after refresh")
                .clone();
            decisions.push(format!(
                "optimizer statistics cache refresh: statistics_epoch={} statistics_generation={} graph_commit_epoch={} publication_changed={}",
                statistics.computed_at_commit_epoch,
                self.statistics_generation,
                store.commit_epoch(),
                refresh.publication_changed
            ));
        } else if let Some(statistics) = &self.statistics {
            decisions.push(format!(
                "optimizer statistics cache hit: statistics_epoch={} statistics_generation={} graph_commit_epoch={}",
                statistics.computed_at_commit_epoch,
                self.statistics_generation,
                store.commit_epoch()
            ));
        }

        let statistics = self
            .statistics
            .as_ref()
            .expect("optimizer statistics exist after refresh check");
        let freshness = statistics.advanced_statistics_freshness(store.commit_epoch());
        decisions.push(format!(
            "optimizer advanced statistics freshness: status={} statistics_epoch={} graph_commit_epoch={} commit_lag={} usable={}",
            freshness.as_str(),
            statistics.computed_at_commit_epoch,
            store.commit_epoch(),
            statistics.advanced_statistics_commit_lag(store.commit_epoch()),
            statistics.advanced_statistics_complete
        ));
        let environment = OptimizerEnvironmentKey {
            schema: OptimizerSchemaKey::from_catalog(catalog),
            statistics_generation: self.statistics_generation,
        };
        if let Some(cached) = &self.catalog
            && cached.environment == environment
            && cached.source_graph_commit_epoch == store.commit_epoch()
        {
            decisions.push(format!(
                "optimizer catalog cache hit: statistics_epoch={} statistics_generation={} graph_commit_epoch={}",
                statistics.computed_at_commit_epoch,
                self.statistics_generation,
                store.commit_epoch()
            ));
            return OptimizerCatalogAccess {
                environment,
                catalog: cached.catalog.clone(),
                decisions,
            };
        }

        let optimized = Arc::new(optimizer_catalog_from_graph_statistics(catalog, statistics));
        decisions.push(format!(
            "optimizer catalog cache refresh: statistics_epoch={} statistics_generation={} graph_commit_epoch={}",
            statistics.computed_at_commit_epoch,
            self.statistics_generation,
            store.commit_epoch()
        ));
        self.catalog = Some(CachedOptimizerCatalog {
            environment: environment.clone(),
            source_graph_commit_epoch: store.commit_epoch(),
            catalog: optimized.clone(),
        });
        OptimizerCatalogAccess {
            environment,
            catalog: optimized,
            decisions,
        }
    }
}

pub(super) fn optimized_query_plan_for<S: crate::executor::ExecutionStore>(
    cypher_text: &str,
    statement: &cypher::Statement,
    parameters: &BTreeMap<String, Value>,
    cache_mode: PlanCacheMode,
    trace_mode: PlanTraceMode,
    context: PlanCacheContext<'_, S>,
) -> Result<OptimizedQueryPlan> {
    let query_identity = hawdb_query::QueryIdentity::new("cypher", cypher_text);
    let query_optimizer =
        CascadesOptimizer::with_context(context.optimizer.context().clone().with_query_identity(
            query_identity.normalized_query(),
            query_identity.query_digest(),
        ));
    if let Some(access_control) = context.access_control {
        context
            .config
            .runtime_capabilities
            .require(hawdb_core::RuntimeCapability::AccessControl)?;
        access_control.validate()?;
    }
    if let Some(capability) = required_runtime_capability(statement_body(statement)) {
        context.config.runtime_capabilities.require(capability)?;
    }
    let effective_max_optimizer_groups =
        optimizer_config_from_database_config(context.config).max_groups;
    let normalized_plan_cache_query =
        hawdb_query::normalize_query_for_plan_cache("cypher", cypher_text);
    let access_control_cache_key = context.access_control.map(AccessControlPlanCacheKey::from);
    let execution_parameters = parameters_with_access_control(parameters, context.access_control);
    let environment_hint = (cache_mode == PlanCacheMode::Use).then(|| {
        context
            .planning_cache
            .borrow_mut()
            .environment_hint(context.catalog, context.store)
    });
    let parameterized = (cache_mode == PlanCacheMode::Use)
        .then(|| parameterize_logical_plan(statement_body(statement), parameters))
        .transpose()?;
    let mut key = parameterized.as_ref().map(|parameterized| PlanCacheKey {
        normalized_query: normalized_plan_cache_query,
        parameters: parameterized.cache_key().clone(),
        environment: environment_hint
            .clone()
            .expect("optimizer environment exists for a parameterized plan"),
        max_optimizer_groups: context.config.max_optimizer_groups,
        access_control: access_control_cache_key,
    });
    if cache_mode == PlanCacheMode::Use {
        let key = key.as_ref().expect("cache key exists in use mode");
        let cached = context.cache.borrow_mut().get(key);
        if let Some(cached) = cached {
            let physical_plan = bind_physical_plan_parameters(
                &cached.physical_template,
                execution_parameters.as_ref(),
                cached.has_parameter_slots,
            )?;
            let mut trace = cached.trace;
            trace.query_digest = Some(query_identity.query_digest().to_string());
            refresh_plan_trace(
                &query_optimizer,
                &mut trace,
                &physical_plan,
                trace_mode,
                &context,
            );
            trace
                .decisions
                .push("plan cache hit: parameterized physical plan template".to_string());
            record_access_control_plan_decision(&mut trace, context.access_control);
            return Ok(OptimizedQueryPlan {
                physical_plan,
                trace,
                plan_cache_lookup: PlanCacheLookup::Hit,
                optimizer_environment: key.environment.clone(),
                configured_max_optimizer_groups: context.config.max_optimizer_groups,
                effective_max_optimizer_groups,
            });
        }
    }
    let mut logical = if let Some(parameterized) = &parameterized {
        parameterized.logical().clone()
    } else {
        planner::plan_with_params(statement_body(statement), parameters)?
    };
    if let Some(access_control) = context.access_control {
        logical = apply_access_control_to_logical_plan(
            logical,
            access_control,
            cache_mode == PlanCacheMode::Use,
        );
    }
    let catalog_access = context
        .planning_cache
        .borrow_mut()
        .optimizer_catalog(context.catalog, context.store);
    let logical_root = LogicalPlanRoot::new(logical);
    let physical_root = query_optimizer
        .optimize_root_with_catalog_and_directive(
            &logical_root,
            &catalog_access.catalog,
            context.optimizer_search,
        )
        .map_err(|error| {
            HawDBError::Execution(format!(
                "optimizer search directive could not be honored: {error}"
            ))
        })?;
    let (physical_template, mut trace) = physical_root.into_parts();
    trace.decisions.extend(catalog_access.decisions);
    let has_parameter_slots = parameterized
        .as_ref()
        .is_some_and(|parameterized| parameterized.slot_count() > 0)
        || (cache_mode == PlanCacheMode::Use && context.access_control.is_some());
    let physical_plan = bind_physical_plan_parameters(
        &physical_template,
        execution_parameters.as_ref(),
        has_parameter_slots,
    )?;
    if let Some(parameterized) = &parameterized {
        trace.decisions.push(format!(
            "parameterized plan template: slots={} exact_variants={}",
            parameterized.slot_count(),
            parameterized.exact_variant_count()
        ));
    }
    let mut cached_trace = trace.clone();
    refresh_materialized_plan_trace(&mut cached_trace, &physical_template);
    match trace_mode {
        PlanTraceMode::Template => refresh_materialized_plan_trace(&mut trace, &physical_plan),
        PlanTraceMode::Bound => query_optimizer.refresh_trace_for_physical_plan(
            &mut trace,
            &physical_plan,
            &catalog_access.catalog,
        ),
    }
    record_access_control_plan_decision(&mut trace, context.access_control);
    if cache_mode == PlanCacheMode::Use {
        let mut key = key.take().expect("cache key exists in use mode");
        key.environment = catalog_access.environment.clone();
        context.cache.borrow_mut().insert(
            key,
            CachedPlan {
                physical_template,
                trace: cached_trace,
                has_parameter_slots,
            },
        );
        trace
            .decisions
            .push("plan cache miss: optimized parameterized physical plan template".to_string());
        return Ok(OptimizedQueryPlan {
            physical_plan,
            trace,
            plan_cache_lookup: PlanCacheLookup::Miss,
            optimizer_environment: catalog_access.environment,
            configured_max_optimizer_groups: context.config.max_optimizer_groups,
            effective_max_optimizer_groups,
        });
    } else if let PlanCacheMode::Bypass(reason) = cache_mode {
        context.cache.borrow_mut().record_bypass();
        trace
            .decisions
            .push(format!("plan cache bypass: {}", reason.as_str()));
        return Ok(OptimizedQueryPlan {
            physical_plan,
            trace,
            plan_cache_lookup: PlanCacheLookup::Bypass(reason),
            optimizer_environment: catalog_access.environment,
            configured_max_optimizer_groups: context.config.max_optimizer_groups,
            effective_max_optimizer_groups,
        });
    }
    unreachable!("plan cache mode must be either use or bypass")
}

fn refresh_materialized_plan_trace(trace: &mut OptimizerTrace, physical_plan: &PhysicalPlan) {
    trace.selected_plan = physical_plan.explain(0);
    trace.selected_plan_fingerprint = physical_plan.fingerprint();
}

fn refresh_plan_trace<S: crate::executor::ExecutionStore>(
    optimizer: &CascadesOptimizer,
    trace: &mut OptimizerTrace,
    physical_plan: &PhysicalPlan,
    trace_mode: PlanTraceMode,
    context: &PlanCacheContext<'_, S>,
) {
    match trace_mode {
        PlanTraceMode::Template => refresh_materialized_plan_trace(trace, physical_plan),
        PlanTraceMode::Bound => {
            let catalog = context
                .planning_cache
                .borrow_mut()
                .optimizer_catalog(context.catalog, context.store)
                .catalog;
            optimizer.refresh_trace_for_physical_plan(trace, physical_plan, &catalog);
            trace.decisions.push(
                "selected physical plan estimates refreshed for bound parameters".to_string(),
            );
        }
    }
}

fn required_runtime_capability(
    statement: &cypher::Statement,
) -> Option<hawdb_core::RuntimeCapability> {
    match statement {
        cypher::Statement::CreateFullTextIndex(_) => {
            Some(hawdb_core::RuntimeCapability::FullTextSearch)
        }
        cypher::Statement::VectorSearch(_) => Some(hawdb_core::RuntimeCapability::VectorSearch),
        cypher::Statement::MatchReturn(query) if query.vector_seed.is_some() => {
            Some(hawdb_core::RuntimeCapability::VectorSearch)
        }
        cypher::Statement::ProjectGraph(_) | cypher::Statement::GraphAlgorithm(_) => {
            Some(hawdb_core::RuntimeCapability::GraphAnalytics)
        }
        _ => None,
    }
}

fn record_access_control_plan_decision(
    trace: &mut OptimizerTrace,
    access_control: Option<&QueryAccessControlContext>,
) {
    if let Some(access_control) = access_control {
        trace.decisions.push(format!(
            "access control policy epoch {} bound to plan cache key",
            access_control.policy_epoch()
        ));
        trace
            .decisions
            .push("access control scope values bound for this execution".to_string());
    }
}

fn parameters_with_access_control<'a>(
    parameters: &'a BTreeMap<String, Value>,
    access_control: Option<&QueryAccessControlContext>,
) -> Cow<'a, BTreeMap<String, Value>> {
    let Some(access_control) = access_control else {
        return Cow::Borrowed(parameters);
    };
    let mut execution_parameters = parameters.clone();
    execution_parameters.insert(
        ACCESS_CONTROL_VALUES_PARAMETER.to_string(),
        Value::List(
            access_control
                .allowed_visibility_values()
                .iter()
                .cloned()
                .map(Value::String)
                .collect(),
        ),
    );
    Cow::Owned(execution_parameters)
}

fn apply_access_control_to_logical_plan(
    logical: LogicalPlan,
    access_control: &QueryAccessControlContext,
    parameterized_values: bool,
) -> LogicalPlan {
    hawdb_plan::apply_node_visibility_predicates(logical, &|variable| {
        access_control_node_predicate(variable, access_control, parameterized_values)
    })
}

fn access_control_node_predicate(
    variable: &str,
    access_control: &QueryAccessControlContext,
    parameterized_values: bool,
) -> Predicate {
    let values = access_control
        .allowed_visibility_values()
        .iter()
        .cloned()
        .map(Value::String)
        .collect::<Vec<_>>();
    Predicate::PropertyIn {
        variable: variable.to_string(),
        property: access_control.visibility_property().to_string(),
        values: if parameterized_values {
            parameterize_value_list(ACCESS_CONTROL_VALUES_PARAMETER, &values)
        } else {
            values
        },
    }
}

pub(super) fn statement_uses_plan_cache(statement: &cypher::Statement) -> bool {
    match statement_body(statement) {
        cypher::Statement::MatchReturn(query) => query.vector_seed.is_none(),
        cypher::Statement::ShortestPathReturn(_)
        | cypher::Statement::MatchNodesReturn(_)
        | cypher::Statement::MatchOptionalRelationshipCountSum(_)
        | cypher::Statement::Pipeline(_)
        | cypher::Statement::GraphAlgorithm(_) => true,
        _ => false,
    }
}