icydb-core 0.259.5

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Module: db::session::query::cache
//! Responsibility: session-owned shared query-plan cache and planner-visibility handoff.
//! Does not own: query planning semantics, execution, or cache-key fingerprint generation.
//! Boundary: resolves store visibility and memoizes prepared plans for typed and SQL callers.

mod identity;
mod template;

use crate::db::commit::CommitSchemaFingerprint;
use crate::{
    db::{
        DbSession, QueryError,
        executor::{
            EntityAuthority, SharedPreparedExecutionPlan,
            budget::{HardExecutionContext, direct_read_execution_context},
        },
        predicate::predicate_fingerprint_normalized,
        query::{
            intent::StructuralQuery,
            plan::{CardinalityTiebreakRoutePin, PreparedQueryParameterContract, VisibleIndexes},
            preparation::PreparationWork,
        },
        schema::{AcceptedSchemaSnapshot, SchemaInfo},
        session::{AcceptedSchemaCatalogContext, CacheEntryWeight, bounded_cache::BoundedCache},
    },
    error::InternalError,
    retained::RetainedBytes,
    traits::CanisterKind,
};
use icydb_diagnostic_code::{DiagnosticExecutionBudgetResource, DiagnosticExecutionLane};
use std::{cell::RefCell, collections::HashMap, rc::Rc};

pub(in crate::db) use identity::QueryPlanVisibility;
use identity::{QueryPlanCacheKey, SchemaCacheIdentity};
use template::PreparedQueryTemplate;

const SHARED_QUERY_PLAN_CACHE_MAX_ENTRIES: usize = 1024;
const SHARED_QUERY_PLAN_CACHE_MAX_RETAINED_BYTES: usize = 4 * 1024 * 1024;
const REQUEST_PLANNING_SHAPE_DOMAIN: u64 = 0x2210_0006_0000_0001;

/// Internal shared-plan cache outcome retained only for verbose `EXPLAIN`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum QueryPlanCacheReuse {
    Hit,
    Miss,
}

impl QueryPlanCacheReuse {
    pub(in crate::db) const fn is_hit(self) -> bool {
        matches!(self, Self::Hit)
    }
}

type QueryPlanCache = BoundedCache<QueryPlanCacheKey, CachedQueryArtifact>;
type CachedPreparedPlanLookup = Option<(SharedPreparedExecutionPlan, QueryPlanCacheReuse)>;

#[derive(Clone, Debug)]
enum CachedQueryArtifact {
    PreparedPlan(SharedPreparedExecutionPlan),
    ParameterizedTemplate(PreparedQueryTemplate),
}

impl CachedQueryArtifact {
    const fn prepared_plan(&self) -> Option<&SharedPreparedExecutionPlan> {
        match self {
            Self::PreparedPlan(plan) => Some(plan),
            Self::ParameterizedTemplate(_) => None,
        }
    }

    const fn parameterized_template(&self) -> Option<&PreparedQueryTemplate> {
        match self {
            Self::PreparedPlan(_) => None,
            Self::ParameterizedTemplate(template) => Some(template),
        }
    }

    fn retained_plan(&self) -> Option<&SharedPreparedExecutionPlan> {
        match self {
            Self::PreparedPlan(plan) => Some(plan),
            Self::ParameterizedTemplate(template) => template.retained_plan(),
        }
    }
}

crate::retained::retained_fields!(CachedQueryArtifact {
    Self::PreparedPlan(plan) => [plan],
    Self::ParameterizedTemplate(template) => [template],
});

// Account both the map key and its FIFO copy. Shared subgraphs may be counted
// repeatedly, conservatively; HashMap/VecDeque spare buckets and allocator
// metadata are separate entry-count-bounded bookkeeping, not this payload cap.
fn artifact_retained_bytes(
    key: &QueryPlanCacheKey,
    artifact: &CachedQueryArtifact,
) -> Option<usize> {
    let mut bytes = RetainedBytes::new(SHARED_QUERY_PLAN_CACHE_MAX_RETAINED_BYTES);
    bytes.add(
        2 * size_of::<QueryPlanCacheKey>()
            + size_of::<CachedQueryArtifact>()
            + size_of::<CacheEntryWeight>()
            + 3 * size_of::<usize>(),
    )?;
    let before_key = bytes.total();
    bytes.visit(key)?;
    // The FIFO copy has the same retained graph: charge it without walking again.
    let key_heap_bytes = bytes.total() - before_key;
    bytes.add(key_heap_bytes)?;
    bytes.visit(artifact)?;
    Some(bytes.total())
}

thread_local! {
    // Keep one in-heap query-plan cache per store registry so fresh `DbSession`
    // facades can share prepared logical plans across update/query calls while
    // tests and multi-registry host processes remain isolated by registry
    // identity.
    static QUERY_PLAN_CACHES: RefCell<HashMap<usize, QueryPlanCache>> =
        RefCell::new(HashMap::default());
}

// A compiled front-end artifact may retain an exact or policy-fallback plan,
// but an unavailable-evidence plan must keep flowing through this shared cache
// so the existing lifecycle-stamp check can observe a later Ready transition.
#[cfg(feature = "sql")]
pub(in crate::db::session) fn query_plan_requires_cardinality_lifecycle_recheck(
    prepared_plan: &SharedPreparedExecutionPlan,
) -> bool {
    prepared_plan
        .logical_plan()
        .cardinality_tiebreak()
        .unavailable_stamp()
        .is_some()
}

impl<C: CanisterKind> DbSession<C> {
    #[cfg(test)]
    pub(in crate::db::session) fn shared_query_cache_usage_for_tests(&self) -> (usize, usize) {
        self.with_query_plan_cache(|cache| {
            for (key, artifact, charged) in cache.retained_entries() {
                let key_bytes = RetainedBytes::measure(key, usize::MAX).expect("accountable key");
                let value_bytes =
                    RetainedBytes::measure(artifact, usize::MAX).expect("accountable artifact");
                // Independent composition includes the FIFO key copy and the
                // entry's reference-counted bookkeeping after lazy execution.
                let expected = 2 * key_bytes
                    + value_bytes
                    + size_of::<CacheEntryWeight>()
                    + 3 * size_of::<usize>();
                assert!(charged >= expected);
            }
            (cache.len(), cache.retained_weight())
        })
    }

    #[cfg(test)]
    pub(in crate::db::session) fn clear_shared_query_cache_for_tests(&self, limit: usize) {
        self.with_query_plan_cache(|cache| {
            *cache = QueryPlanCache::new_weighted(SHARED_QUERY_PLAN_CACHE_MAX_ENTRIES, limit);
        });
    }

    #[cfg(all(test, feature = "sql"))]
    pub(in crate::db::session) fn retry_shared_query_cache_insertion_for_tests(
        &self,
        lane: DiagnosticExecutionLane,
        before_insert: impl FnOnce(),
    ) -> Result<(), QueryError> {
        let (key, artifact) = self.with_query_plan_cache(|cache| {
            cache
                .retained_entries()
                .next()
                .map(|(key, artifact, _)| (key.clone(), artifact.clone()))
                .expect("fixture has a prepared artifact")
        });
        // Isolate the final insertion boundary from earlier planner checks.
        before_insert();
        self.insert_shared_query_artifact(lane, key, artifact)
    }

    fn cached_cardinality_tiebreak_is_current(
        &self,
        authority: &EntityAuthority,
        prepared_plan: &SharedPreparedExecutionPlan,
    ) -> Result<bool, QueryError> {
        let Some(retained_stamp) = prepared_plan
            .logical_plan()
            .cardinality_tiebreak()
            .unavailable_stamp()
        else {
            return Ok(true);
        };
        let store = self
            .db
            .recovered_store(authority.store_path())
            .map_err(QueryError::execute)?;
        let current_stamp = store.exact_user_index_prefix_evidence_lifecycle_stamp();

        Ok(current_stamp == retained_stamp)
    }

    fn charge_request_planning_resource(
        &self,
        context: HardExecutionContext,
        resource: DiagnosticExecutionBudgetResource,
    ) -> Result<(), QueryError> {
        self.db
            .request_execution_scope()
            .charge(context, resource, 1)
            .map_err(InternalError::from)
            .map_err(QueryError::execute)
    }

    fn with_query_plan_cache<R>(&self, f: impl FnOnce(&mut QueryPlanCache) -> R) -> R {
        let scope_id = self.db.cache_scope_id();

        QUERY_PLAN_CACHES.with(|caches| {
            let mut caches = caches.borrow_mut();
            let cache = caches.entry(scope_id).or_insert_with(|| {
                QueryPlanCache::new_weighted(
                    SHARED_QUERY_PLAN_CACHE_MAX_ENTRIES,
                    SHARED_QUERY_PLAN_CACHE_MAX_RETAINED_BYTES,
                )
            });

            f(cache)
        })
    }

    fn lookup_shared_query_template(
        &self,
        cache_key: &QueryPlanCacheKey,
    ) -> Option<PreparedQueryTemplate> {
        self.with_query_plan_cache(|cache| {
            cache
                .get(cache_key)
                .and_then(CachedQueryArtifact::parameterized_template)
                .cloned()
        })
    }

    fn insert_shared_query_artifact(
        &self,
        lane: DiagnosticExecutionLane,
        cache_key: QueryPlanCacheKey,
        artifact: CachedQueryArtifact,
    ) -> Result<(), QueryError> {
        let retained_plan = artifact.retained_plan().cloned();
        // Finish sizing's instruction charge before changing cache contents or
        // attaching a lazy-growth handle. Retention ineligibility is not an error.
        let weight = PreparationWork::run(self.db.request_execution_scope(), lane, |_| {
            // An attached core cannot acquire another independent charge owner.
            if retained_plan
                .as_ref()
                .is_some_and(|plan| !plan.cache_retention_available())
            {
                return Ok(None);
            }
            Ok(artifact_retained_bytes(&cache_key, &artifact))
        })?;
        let Some(weight) = weight else {
            return Ok(());
        };
        self.with_query_plan_cache(|cache| {
            let admitted_entry = cache.insert_weighted(cache_key, artifact, weight);
            if let Some(entry) = admitted_entry
                && let Some(plan) = retained_plan
            {
                plan.attach_cache_retention(entry);
            }
        });
        Ok(())
    }

    fn lookup_shared_query_plan_for_authority(
        &self,
        authority: &EntityAuthority,
        cache_key: &QueryPlanCacheKey,
    ) -> Result<CachedPreparedPlanLookup, QueryError> {
        let cached = self.with_query_plan_cache(|cache| {
            cache
                .get(cache_key)
                .and_then(CachedQueryArtifact::prepared_plan)
                .cloned()
        });
        if let Some(prepared_plan) = cached
            && self.cached_cardinality_tiebreak_is_current(authority, &prepared_plan)?
        {
            return Ok(Some((prepared_plan, QueryPlanCacheReuse::Hit)));
        }

        Ok(None)
    }

    // A current lookup already missed. Compile and publish only after the
    // complete preparation interval succeeds, without probing the cache again.
    fn compile_shared_query_plan_on_miss(
        &self,
        cache_key: QueryPlanCacheKey,
        planning_context: HardExecutionContext,
        build_prepared_plan: impl FnOnce(
            &PreparationWork<'_>,
        ) -> Result<SharedPreparedExecutionPlan, QueryError>,
    ) -> Result<(SharedPreparedExecutionPlan, QueryPlanCacheReuse), QueryError> {
        self.charge_request_planning_resource(
            planning_context,
            DiagnosticExecutionBudgetResource::PlanCompilations,
        )?;

        // Finish the request's instruction watermark before publishing an
        // artifact. A failed final charge must leave the cache without it.
        let prepared_plan = PreparationWork::run(
            self.db.request_execution_scope(),
            planning_context.lane(),
            build_prepared_plan,
        )?;
        self.insert_shared_query_artifact(
            planning_context.lane(),
            cache_key,
            CachedQueryArtifact::PreparedPlan(prepared_plan.clone()),
        )?;

        Ok((prepared_plan, QueryPlanCacheReuse::Miss))
    }

    pub(in crate::db::session) fn visible_indexes_for_accepted_schema(
        schema_info: &SchemaInfo,
        visibility: QueryPlanVisibility,
    ) -> Result<VisibleIndexes, QueryError> {
        Ok(match visibility {
            QueryPlanVisibility::StoreReady => {
                let visible_indexes = VisibleIndexes::accepted_schema_visible(schema_info)
                    .map_err(QueryError::execute)?;
                debug_assert!(visible_indexes.accepted_field_path_contracts_are_consistent());
                debug_assert!(visible_indexes.accepted_expression_contracts_are_consistent());
                debug_assert!(visible_indexes.accepted_semantic_contracts_are_consistent());
                debug_assert_eq!(
                    visible_indexes.accepted_expression_index_count(),
                    Some(visible_indexes.accepted_expression_indexes().len()),
                );

                visible_indexes
            }
            #[cfg(feature = "sql")]
            QueryPlanVisibility::PrimaryOnly => VisibleIndexes::accepted_schema_primary_only(),
            QueryPlanVisibility::StoreNotReady => VisibleIndexes::none(),
        })
    }

    pub(in crate::db) fn query_plan_visibility_for_store_path(
        &self,
        store_path: &'static str,
    ) -> Result<QueryPlanVisibility, QueryError> {
        let store = self
            .db
            .recovered_store(store_path)
            .map_err(QueryError::execute)?;
        let visibility = if store.index_state() == crate::db::IndexState::Ready {
            QueryPlanVisibility::StoreReady
        } else {
            QueryPlanVisibility::StoreNotReady
        };

        Ok(visibility)
    }

    pub(in crate::db) fn cached_shared_query_plan_for_accepted_authority_with_schema_fingerprint(
        &self,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        schema_fingerprint: CommitSchemaFingerprint,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
    ) -> Result<SharedPreparedExecutionPlan, QueryError> {
        let visibility = self.query_plan_visibility_for_store_path(authority.store_path())?;
        let schema = SchemaCacheIdentity::from_accepted_schema_with_fingerprint(
            accepted_schema,
            schema_fingerprint,
            authority.accepted_runtime_root_identity(),
            authority.accepted_schema_authority().revision(),
        );
        self.cached_shared_query_plan_for_accepted_authority_with_schema_and_visibility(
            authority, schema, visibility, query, lane,
        )
        .map(|(plan, _reuse)| plan)
    }

    /// Compile one authenticated cardinality-selected continuation route without
    /// consulting current cardinality or replacing the ordinary initial-query cache entry.
    pub(in crate::db) fn shared_query_plan_for_accepted_authority_with_route_pin(
        &self,
        authority: EntityAuthority,
        schema_fingerprint: CommitSchemaFingerprint,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
        route_pin: CardinalityTiebreakRoutePin,
    ) -> Result<Option<SharedPreparedExecutionPlan>, QueryError> {
        let visibility = self.query_plan_visibility_for_store_path(authority.store_path())?;
        let planning_context =
            direct_read_execution_context(&authority, lane, REQUEST_PLANNING_SHAPE_DOMAIN);
        self.charge_request_planning_resource(
            planning_context,
            DiagnosticExecutionBudgetResource::PlanningSteps,
        )?;
        self.charge_request_planning_resource(
            planning_context,
            DiagnosticExecutionBudgetResource::PlanCompilations,
        )?;
        PreparationWork::run(self.db.request_execution_scope(), lane, |work| {
            let schema_info = authority.accepted_schema_info_handle();
            let planning_state =
                query.prepare_scalar_planning_state_with_schema_info(schema_info, work)?;
            let visible_indexes = Self::visible_indexes_for_accepted_schema(
                planning_state.schema_info(),
                visibility,
            )?;
            let plan = query.build_plan_with_indexes_from_scalar_planning_state(
                visible_indexes.accepted_semantic_index_contracts(),
                planning_state,
                work,
            )?;
            let Some(plan) = Self::apply_pinned_cardinality_tiebreak(
                &authority,
                visible_indexes.accepted_semantic_index_contracts(),
                plan,
                route_pin,
                work,
            )?
            else {
                return Ok(None);
            };
            let prepared_plan =
                SharedPreparedExecutionPlan::from_plan(authority, plan, schema_fingerprint, work)
                    .map_err(QueryError::execute)?;

            Ok(Some(prepared_plan))
        })
    }

    #[cfg(feature = "sql")]
    pub(in crate::db) fn cached_primary_only_query_plan_for_accepted_authority_with_schema_fingerprint(
        &self,
        authority: EntityAuthority,
        accepted_schema: &AcceptedSchemaSnapshot,
        schema_fingerprint: CommitSchemaFingerprint,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
    ) -> Result<SharedPreparedExecutionPlan, QueryError> {
        let visibility = match self.query_plan_visibility_for_store_path(authority.store_path())? {
            QueryPlanVisibility::StoreReady | QueryPlanVisibility::PrimaryOnly => {
                QueryPlanVisibility::PrimaryOnly
            }
            QueryPlanVisibility::StoreNotReady => QueryPlanVisibility::StoreNotReady,
        };
        let schema = SchemaCacheIdentity::from_accepted_schema_with_fingerprint(
            accepted_schema,
            schema_fingerprint,
            authority.accepted_runtime_root_identity(),
            authority.accepted_schema_authority().revision(),
        );

        self.cached_shared_query_plan_for_accepted_authority_with_schema_and_visibility(
            authority, schema, visibility, query, lane,
        )
        .map(|(plan, _reuse)| plan)
    }

    pub(in crate::db) fn cached_shared_query_plan_for_accepted_authority_with_catalog(
        &self,
        authority: EntityAuthority,
        catalog: &AcceptedSchemaCatalogContext,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
    ) -> Result<SharedPreparedExecutionPlan, QueryError> {
        self.cached_shared_query_plan_for_accepted_authority_with_catalog_and_reuse(
            authority, catalog, query, lane,
        )
        .map(|(plan, _reuse)| plan)
    }

    pub(in crate::db) fn cached_shared_query_plan_for_accepted_authority_with_catalog_and_reuse(
        &self,
        authority: EntityAuthority,
        catalog: &AcceptedSchemaCatalogContext,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
    ) -> Result<(SharedPreparedExecutionPlan, QueryPlanCacheReuse), QueryError> {
        let visibility = self.query_plan_visibility_for_store_path(authority.store_path())?;
        let schema = SchemaCacheIdentity::from_catalog(catalog);

        self.cached_shared_query_plan_for_accepted_authority_with_schema_and_visibility(
            authority, schema, visibility, query, lane,
        )
    }

    #[expect(
        clippy::too_many_lines,
        reason = "keep early filterless reuse, normalized lookup and their shared miss handoff in one owner"
    )]
    fn cached_shared_query_plan_for_accepted_authority_with_schema_and_visibility(
        &self,
        authority: EntityAuthority,
        schema_identity: SchemaCacheIdentity,
        visibility: QueryPlanVisibility,
        query: &StructuralQuery,
        lane: DiagnosticExecutionLane,
    ) -> Result<(SharedPreparedExecutionPlan, QueryPlanCacheReuse), QueryError> {
        let planning_context =
            direct_read_execution_context(&authority, lane, REQUEST_PLANNING_SHAPE_DOMAIN);
        self.charge_request_planning_resource(
            planning_context,
            DiagnosticExecutionBudgetResource::PlanningSteps,
        )?;
        // Filterless hits bypass schema projection. Retain their miss key so
        // either construction path can publish without a second lookup.
        let filterless_key = if query.has_scalar_filter() {
            None
        } else {
            let (key, cached) = self.lookup_shared_query_plan_with_fingerprint(
                &authority,
                schema_identity,
                visibility,
                query,
                None,
                lane,
            )?;
            if let Some(cached) = cached {
                return Ok(cached);
            }
            Some(key)
        };
        let schema_info = authority.accepted_schema_info_handle();
        if query.trivial_scalar_load_fast_path_eligible_with_schema(&schema_info) {
            return self.compile_trivial_scalar_load_plan_on_miss(
                authority,
                filterless_key.ok_or_else(QueryError::invariant)?,
                schema_identity,
                schema_info,
                query,
                planning_context,
            );
        }

        // Filtered hits still normalize current operands and derive identity.
        // Finish their instruction interval before cache lookup; it must not
        // overlap the separate miss/rebind construction interval below.
        let (planning_state, parameter_contract, normalized_predicate_fingerprint) =
            PreparationWork::run(self.db.request_execution_scope(), lane, |work| {
                let planning_state =
                    query.prepare_scalar_planning_state_with_schema_info(schema_info, work)?;
                let parameter_contract = query
                    .filter_predicate_fully_covers_expression()
                    .then(|| planning_state.normalized_predicate())
                    .flatten()
                    .map(|predicate| {
                        PreparedQueryParameterContract::from_normalized_predicate(predicate, work)
                    })
                    .transpose()
                    .map_err(QueryError::execute)?
                    .flatten();
                let fingerprint = planning_state
                    .normalized_predicate()
                    .map(|predicate| predicate_fingerprint_normalized(predicate, work))
                    .transpose()
                    .map_err(QueryError::execute)?;

                Ok((planning_state, parameter_contract, fingerprint))
            })?;
        if let Some(parameter_contract) = parameter_contract {
            let bound_predicate_fingerprint =
                normalized_predicate_fingerprint.ok_or_else(QueryError::invariant)?;

            return self.resolve_parameterized_query_plan_for_authority(
                &authority,
                schema_identity,
                visibility,
                query,
                planning_state,
                parameter_contract,
                bound_predicate_fingerprint,
                planning_context,
            );
        }
        let visible_indexes =
            Self::visible_indexes_for_accepted_schema(planning_state.schema_info(), visibility)?;
        let cache_key = if let Some(key) = filterless_key {
            key
        } else {
            let (key, cached) = self.lookup_shared_query_plan_with_fingerprint(
                &authority,
                schema_identity,
                visibility,
                query,
                normalized_predicate_fingerprint,
                lane,
            )?;
            if let Some(cached) = cached {
                return Ok(cached);
            }
            key
        };
        self.compile_shared_query_plan_on_miss(cache_key, planning_context, |work| {
            let plan = query.build_plan_with_indexes_from_scalar_planning_state(
                visible_indexes.accepted_semantic_index_contracts(),
                planning_state,
                work,
            )?;
            let plan = self.apply_exact_cardinality_tiebreak(
                &authority,
                visible_indexes.accepted_semantic_index_contracts(),
                plan,
                work,
            )?;

            SharedPreparedExecutionPlan::from_plan(
                authority,
                plan,
                schema_identity.fingerprint(),
                work,
            )
            .map_err(QueryError::execute)
        })
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "parameterized cache binding keeps schema, visibility, and current values explicit"
    )]
    fn resolve_parameterized_query_plan_for_authority(
        &self,
        authority: &EntityAuthority,
        schema_identity: SchemaCacheIdentity,
        visibility: QueryPlanVisibility,
        query: &StructuralQuery,
        planning_state: crate::db::query::plan::PreparedScalarPlanningState<'_>,
        parameter_contract: PreparedQueryParameterContract,
        bound_predicate_fingerprint: [u8; 32],
        planning_context: HardExecutionContext,
    ) -> Result<(SharedPreparedExecutionPlan, QueryPlanCacheReuse), QueryError> {
        let (cache_key, cached_template, reused_plan) = PreparationWork::run(
            self.db.request_execution_scope(),
            planning_context.lane(),
            |work| {
                let cache_key = QueryPlanCacheKey::for_authority_with_parameter_contract(
                    authority,
                    schema_identity,
                    visibility,
                    query,
                    parameter_contract,
                    work,
                )?;
                let template = self.lookup_shared_query_template(&cache_key);
                let mut reused = template
                    .as_ref()
                    .and_then(|template| template.reused_bound_plan(bound_predicate_fingerprint));
                if let Some(plan) = &reused
                    && !self.cached_cardinality_tiebreak_is_current(authority, plan)?
                {
                    reused = None;
                }
                Ok((cache_key, template, reused))
            },
        )?;
        if let Some(prepared_plan) = reused_plan {
            return Ok((prepared_plan, QueryPlanCacheReuse::Hit));
        }
        if let Some(mut template) = cached_template {
            let prepared_plan = PreparationWork::run(
                self.db.request_execution_scope(),
                planning_context.lane(),
                |work| {
                    let bound = template.bind(query, planning_state, work)?;
                    let bound = self.apply_exact_cardinality_tiebreak(
                        authority,
                        template.candidate_indexes(),
                        bound,
                        work,
                    )?;
                    SharedPreparedExecutionPlan::from_plan(
                        authority.clone(),
                        bound,
                        schema_identity.fingerprint(),
                        work,
                    )
                    .map_err(QueryError::execute)
                },
            )?;
            // Binding is synchronous and does not publish into the cache. Keep
            // the checked-out memo unchanged until the complete plan succeeds.
            template.remember_bound_plan(bound_predicate_fingerprint, prepared_plan.clone());
            let artifact = CachedQueryArtifact::ParameterizedTemplate(template);
            self.insert_shared_query_artifact(planning_context.lane(), cache_key, artifact)?;

            return Ok((prepared_plan, QueryPlanCacheReuse::Hit));
        }

        self.charge_request_planning_resource(
            planning_context,
            DiagnosticExecutionBudgetResource::PlanCompilations,
        )?;

        let (prepared_plan, mut template) = PreparationWork::run(
            self.db.request_execution_scope(),
            planning_context.lane(),
            |work| {
                let visible_indexes = Self::visible_indexes_for_accepted_schema(
                    planning_state.schema_info(),
                    visibility,
                )?;
                let plan = query.build_plan_with_indexes_from_scalar_planning_state(
                    visible_indexes.accepted_semantic_index_contracts(),
                    planning_state,
                    work,
                )?;
                let plan = self.apply_exact_cardinality_tiebreak(
                    authority,
                    visible_indexes.accepted_semantic_index_contracts(),
                    plan,
                    work,
                )?;
                let template = PreparedQueryTemplate::new(
                    visible_indexes.accepted_semantic_index_contracts(),
                    work,
                )?;
                let prepared_plan = SharedPreparedExecutionPlan::from_plan(
                    authority.clone(),
                    plan,
                    schema_identity.fingerprint(),
                    work,
                )
                .map_err(QueryError::execute)?;
                Ok((prepared_plan, template))
            },
        )?;
        template.remember_bound_plan(bound_predicate_fingerprint, prepared_plan.clone());
        let artifact = CachedQueryArtifact::ParameterizedTemplate(template);
        self.insert_shared_query_artifact(planning_context.lane(), cache_key, artifact)?;

        Ok((prepared_plan, QueryPlanCacheReuse::Miss))
    }

    // Own key construction and current lifecycle checking for ordinary plans.
    // Returning the key lets a miss continue directly into construction.
    fn lookup_shared_query_plan_with_fingerprint(
        &self,
        authority: &EntityAuthority,
        schema_identity: SchemaCacheIdentity,
        visibility: QueryPlanVisibility,
        query: &StructuralQuery,
        normalized_predicate_fingerprint: Option<[u8; 32]>,
        lane: DiagnosticExecutionLane,
    ) -> Result<(QueryPlanCacheKey, CachedPreparedPlanLookup), QueryError> {
        PreparationWork::run(self.db.request_execution_scope(), lane, |work| {
            let cache_key = QueryPlanCacheKey::for_authority_with_normalized_predicate_fingerprint(
                authority,
                schema_identity,
                visibility,
                query,
                normalized_predicate_fingerprint,
                work,
            )?;
            let cached = self.lookup_shared_query_plan_for_authority(authority, &cache_key)?;
            Ok((cache_key, cached))
        })
    }

    fn compile_trivial_scalar_load_plan_on_miss(
        &self,
        authority: EntityAuthority,
        cache_key: QueryPlanCacheKey,
        schema_identity: SchemaCacheIdentity,
        schema_info: Rc<SchemaInfo>,
        query: &StructuralQuery,
        planning_context: HardExecutionContext,
    ) -> Result<(SharedPreparedExecutionPlan, QueryPlanCacheReuse), QueryError> {
        self.compile_shared_query_plan_on_miss(cache_key, planning_context, |work| {
            let Some(plan) =
                query.try_build_trivial_scalar_load_plan_with_schema_info(schema_info, work)?
            else {
                return Err(QueryError::invariant());
            };

            SharedPreparedExecutionPlan::from_plan(
                authority,
                plan,
                schema_identity.fingerprint(),
                work,
            )
            .map_err(QueryError::execute)
        })
    }
}