icydb-core 0.198.2

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
//! Module: db::query::plan::access_choice::model
//! Responsibility: define access-choice scoring and rejection models used by
//! planner candidate evaluation.
//! Does not own: candidate enumeration or final execution-plan assembly.
//! Boundary: keeps planner access-choice data structures separate from evaluator logic.

use crate::db::query::plan::PlannedNonIndexAccessReason;

pub(super) use crate::db::query::plan::planner::AccessCandidateScore as CandidateScore;

///
/// AccessChoiceExplainSnapshot
///
/// Planner-owned access-choice explain projection consumed by executor
/// descriptor assembly without re-deriving planner ranking policies.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct AccessChoiceExplainSnapshot {
    pub(in crate::db) chosen_reason: AccessChoiceSelectedReason,
    pub(in crate::db) candidates: Vec<AccessChoiceCandidateExplainSummary>,
    pub(in crate::db) alternatives: Vec<String>,
    pub(in crate::db) rejected: Vec<String>,
    pub(in crate::db) primary_key_input_resource: Option<PrimaryKeyInputResourceSummary>,
}

impl AccessChoiceExplainSnapshot {
    /// Construct one planner snapshot for composite non-index access paths
    /// whose concrete winner family is not distinguished more precisely.
    #[must_use]
    pub(in crate::db) const fn non_index_access() -> Self {
        Self {
            chosen_reason: AccessChoiceSelectedReason::NonIndexAccess,
            candidates: Vec::new(),
            alternatives: Vec::new(),
            rejected: Vec::new(),
            primary_key_input_resource: None,
        }
    }

    /// Construct one fail-closed snapshot for manually assembled index plans
    /// that never passed through planner-owned candidate projection.
    #[must_use]
    pub(in crate::db) const fn selected_index_not_projected() -> Self {
        Self {
            chosen_reason: AccessChoiceSelectedReason::SelectedIndexNotProjected,
            candidates: Vec::new(),
            alternatives: Vec::new(),
            rejected: Vec::new(),
            primary_key_input_resource: None,
        }
    }

    /// Construct one planner-owned snapshot from one frozen non-index winner
    /// reason already chosen during access planning.
    #[must_use]
    pub(in crate::db) const fn from_planned_non_index_reason(
        reason: PlannedNonIndexAccessReason,
    ) -> Self {
        let chosen_reason = match reason {
            PlannedNonIndexAccessReason::IntentKeyAccessOverride => {
                AccessChoiceSelectedReason::IntentKeyAccessOverride
            }
            PlannedNonIndexAccessReason::PlannerPrimaryKeyLookup => {
                AccessChoiceSelectedReason::PlannerPrimaryKeyLookup
            }
            PlannedNonIndexAccessReason::PlannerKeySetAccess => {
                AccessChoiceSelectedReason::PlannerKeySetAccess
            }
            PlannedNonIndexAccessReason::PlannerPrimaryKeyRange => {
                AccessChoiceSelectedReason::PlannerPrimaryKeyRange
            }
            PlannedNonIndexAccessReason::EmptyChildAccessPreferred => {
                AccessChoiceSelectedReason::EmptyChildAccessPreferred
            }
            PlannedNonIndexAccessReason::ConflictingPrimaryKeyChildrenAccessPreferred => {
                AccessChoiceSelectedReason::ConflictingPrimaryKeyChildrenAccessPreferred
            }
            PlannedNonIndexAccessReason::SingletonPrimaryKeyChildAccessPreferred => {
                AccessChoiceSelectedReason::SingletonPrimaryKeyChildAccessPreferred
            }
            PlannedNonIndexAccessReason::RequiredOrderPrimaryKeyRangePreferred => {
                AccessChoiceSelectedReason::RequiredOrderPrimaryKeyRangePreferred
            }
            PlannedNonIndexAccessReason::LimitZeroWindow => {
                AccessChoiceSelectedReason::LimitZeroWindow
            }
            PlannedNonIndexAccessReason::ConstantFalsePredicate => {
                AccessChoiceSelectedReason::ConstantFalsePredicate
            }
            PlannedNonIndexAccessReason::PlannerFullScanFallback => {
                AccessChoiceSelectedReason::PlannerFullScanFallback
            }
            PlannedNonIndexAccessReason::PlannerCompositeNonIndex => {
                AccessChoiceSelectedReason::PlannerCompositeNonIndex
            }
        };

        Self {
            chosen_reason,
            candidates: Vec::new(),
            alternatives: Vec::new(),
            rejected: Vec::new(),
            primary_key_input_resource: None,
        }
    }

    /// Return the planner-owned reason for the selected access family.
    #[must_use]
    pub(in crate::db) const fn chosen_reason(&self) -> AccessChoiceSelectedReason {
        self.chosen_reason
    }

    /// Return planner-owned primary-key literal resource facts, when the
    /// selected access route came from a primary-key predicate.
    #[must_use]
    pub(in crate::db) const fn primary_key_input_resource(
        &self,
    ) -> Option<PrimaryKeyInputResourceSummary> {
        self.primary_key_input_resource
    }

    /// Attach primary-key literal resource facts to this planner snapshot.
    #[must_use]
    pub(in crate::db) const fn with_primary_key_input_resource(
        mut self,
        resource: PrimaryKeyInputResourceSummary,
    ) -> Self {
        self.primary_key_input_resource = Some(resource);
        self
    }
}

///
/// PrimaryKeyInputResourceSummary
///
/// Planner-owned resource facts for primary-key predicate literal inputs.
/// The deduplicated access path remains semantic authority for row bounds;
/// this summary lets admission also cap pre-execution key-list work.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct PrimaryKeyInputResourceSummary {
    raw_term_count: u32,
    estimated_payload_bytes: u32,
}

impl PrimaryKeyInputResourceSummary {
    /// Build one primary-key literal resource summary.
    #[must_use]
    pub(in crate::db) const fn new(raw_term_count: u32, estimated_payload_bytes: u32) -> Self {
        Self {
            raw_term_count,
            estimated_payload_bytes,
        }
    }

    /// Return the number of input key terms at the planner predicate boundary.
    #[must_use]
    pub(in crate::db) const fn raw_term_count(self) -> u32 {
        self.raw_term_count
    }

    /// Return the conservative estimated key-literal payload bytes.
    #[must_use]
    pub(in crate::db) const fn estimated_payload_bytes(self) -> u32 {
        self.estimated_payload_bytes
    }
}

///
/// AccessChoiceResidualBurden
///
/// AccessChoiceResidualBurden classifies the bounded residual-work categories
/// surfaced by `0.106.1` route ranking and verbose explain output.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum AccessChoiceResidualBurden {
    None,
    PredicateOnly,
    ScalarExpression,
}

impl AccessChoiceResidualBurden {
    #[must_use]
    pub(in crate::db) const fn label(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::PredicateOnly => "predicate_only",
            Self::ScalarExpression => "scalar_expression",
        }
    }
}

///
/// AccessChoiceCandidateExplainSummary
///
/// AccessChoiceCandidateExplainSummary carries one planner-owned eligible
/// access-candidate summary for verbose explain rendering.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct AccessChoiceCandidateExplainSummary {
    pub(in crate::db) label: String,
    pub(in crate::db) exact: bool,
    pub(in crate::db) filtered: bool,
    pub(in crate::db) range_bound_count: usize,
    pub(in crate::db) order_compatible: bool,
    pub(in crate::db) residual_burden: AccessChoiceResidualBurden,
    pub(in crate::db) residual_predicate_terms: usize,
}

///
/// AccessChoiceRankingReason
///
/// Shared ranking reason taxonomy for planner tie-break decisions.
/// Selection and rejection surfaces carry polarity separately so explain
/// output can reuse the same canonical ranking reason codes.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum AccessChoiceRankingReason {
    ExactMatchPreferred,
    FilteredPredicatePreferred,
    StrongerRangeBoundsPreferred,
    ResidualBurdenPreferred,
    OrderCompatiblePreferred,
    LexicographicTiebreak,
}

impl AccessChoiceRankingReason {
    #[must_use]
    pub(in crate::db) const fn code(self) -> &'static str {
        match self {
            Self::ExactMatchPreferred => "exact_match_preferred",
            Self::FilteredPredicatePreferred => "filtered_predicate_preferred",
            Self::StrongerRangeBoundsPreferred => "stronger_range_bounds_preferred",
            Self::ResidualBurdenPreferred => "residual_burden_preferred",
            Self::OrderCompatiblePreferred => "order_compatible_preferred",
            Self::LexicographicTiebreak => "lexicographic_tiebreak",
        }
    }
}

///
/// AccessChoiceSelectedReason
///
/// Canonical reason code taxonomy for selected access candidates.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum AccessChoiceSelectedReason {
    NonIndexAccess,
    IntentKeyAccessOverride,
    PlannerPrimaryKeyLookup,
    PlannerKeySetAccess,
    PlannerPrimaryKeyRange,
    ByKeyAccess,
    ByKeysAccess,
    PrimaryKeyRangeAccess,
    EmptyChildAccessPreferred,
    ConflictingPrimaryKeyChildrenAccessPreferred,
    SingletonPrimaryKeyChildAccessPreferred,
    RequiredOrderPrimaryKeyRangePreferred,
    LimitZeroWindow,
    ConstantFalsePredicate,
    PlannerFullScanFallback,
    PlannerCompositeNonIndex,
    FullScanAccess,
    SelectedIndexNotProjected,
    SingleCandidate,
    BestPrefixLen,
    Ranked(AccessChoiceRankingReason),
}

impl AccessChoiceSelectedReason {
    #[must_use]
    pub(in crate::db) const fn code(self) -> &'static str {
        match self {
            Self::NonIndexAccess => "non_index_access",
            Self::IntentKeyAccessOverride => "intent_key_access_override",
            Self::PlannerPrimaryKeyLookup => "planner_primary_key_lookup",
            Self::PlannerKeySetAccess => "planner_key_set_access",
            Self::PlannerPrimaryKeyRange => "planner_primary_key_range",
            Self::ByKeyAccess => "by_key_access",
            Self::ByKeysAccess => "by_keys_access",
            Self::PrimaryKeyRangeAccess => "primary_key_range_access",
            Self::EmptyChildAccessPreferred => "empty_child_access_preferred",
            Self::ConflictingPrimaryKeyChildrenAccessPreferred => {
                "conflicting_primary_key_children_access_preferred"
            }
            Self::SingletonPrimaryKeyChildAccessPreferred => {
                "singleton_primary_key_child_access_preferred"
            }
            Self::RequiredOrderPrimaryKeyRangePreferred => {
                "required_order_primary_key_range_preferred"
            }
            Self::LimitZeroWindow => "limit_zero_window",
            Self::ConstantFalsePredicate => "constant_false_predicate",
            Self::PlannerFullScanFallback => "planner_full_scan_fallback",
            Self::PlannerCompositeNonIndex => "planner_composite_non_index",
            Self::FullScanAccess => "full_scan_access",
            Self::SelectedIndexNotProjected => "selected_index_not_projected",
            Self::SingleCandidate => "single_candidate",
            Self::BestPrefixLen => "best_prefix_len",
            Self::Ranked(reason) => reason.code(),
        }
    }
}

///
/// AccessChoiceRejectedReason
///
/// Canonical reason code taxonomy for rejected access candidates.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum AccessChoiceRejectedReason {
    PredicateAbsent,
    NonIndexAccess,
    PredicateShapeNotPrefixEligible,
    PredicateShapeNotMultiLookup,
    PredicateShapeNotBranchSet,
    PredicateShapeNotRangeEligible,
    NonStrictCoercion,
    OperatorNotPrefixEq,
    OperatorNotMultiLookupIn,
    OperatorNotRangeSupported,
    OperatorNotSupported,
    LeadingFieldMismatch,
    LiteralIncompatible,
    InLiteralNotList,
    InLiteralEmpty,
    InLiteralIncompatible,
    SingleFieldRangeRequired,
    StartsWithPrefixInvalid,
    EqRangeConflict,
    ConflictingEqConstraints,
    NoEqConstraints,
    LeadingFieldUnconstrained,
    MissingContiguousPrefixOrRange,
    NonContiguousRangeConstraints,
    MissingRangeConstraint,
    ShorterPrefix,
    Ranked(AccessChoiceRankingReason),
}

impl AccessChoiceRejectedReason {
    #[must_use]
    pub(in crate::db) const fn code(self) -> &'static str {
        match self {
            Self::PredicateAbsent => "predicate_absent",
            Self::NonIndexAccess => "non_index_access",
            Self::PredicateShapeNotPrefixEligible => "predicate_shape_not_prefix_eligible",
            Self::PredicateShapeNotMultiLookup => "predicate_shape_not_multi_lookup",
            Self::PredicateShapeNotBranchSet => "predicate_shape_not_branch_set",
            Self::PredicateShapeNotRangeEligible => "predicate_shape_not_range_eligible",
            Self::NonStrictCoercion => "non_strict_coercion",
            Self::OperatorNotPrefixEq => "operator_not_prefix_eq",
            Self::OperatorNotMultiLookupIn => "operator_not_multi_lookup_in",
            Self::OperatorNotRangeSupported => "operator_not_range_supported",
            Self::OperatorNotSupported => "operator_not_supported",
            Self::LeadingFieldMismatch => "leading_field_mismatch",
            Self::LiteralIncompatible => "literal_incompatible",
            Self::InLiteralNotList => "in_literal_not_list",
            Self::InLiteralEmpty => "in_literal_empty",
            Self::InLiteralIncompatible => "in_literal_incompatible",
            Self::SingleFieldRangeRequired => "single_field_range_required",
            Self::StartsWithPrefixInvalid => "startswith_prefix_invalid",
            Self::EqRangeConflict => "eq_range_conflict",
            Self::ConflictingEqConstraints => "conflicting_eq_constraints",
            Self::NoEqConstraints => "no_eq_constraints",
            Self::LeadingFieldUnconstrained => "leading_field_unconstrained",
            Self::MissingContiguousPrefixOrRange => "missing_contiguous_prefix_or_range",
            Self::NonContiguousRangeConstraints => "non_contiguous_range_constraints",
            Self::MissingRangeConstraint => "missing_range_constraint",
            Self::ShorterPrefix => "shorter_prefix",
            Self::Ranked(reason) => reason.code(),
        }
    }

    #[must_use]
    pub(in crate::db) fn render_for_index(self, index_name: &str) -> String {
        let reason = self.code();
        let mut out = String::with_capacity("index:".len() + index_name.len() + 1 + reason.len());
        out.push_str("index:");
        out.push_str(index_name);
        out.push('=');
        out.push_str(reason);
        out
    }
}

///
/// AccessChoiceFamily
///
/// AccessChoiceFamily groups the planner-visible access candidate shapes that
/// share one explain ranking policy.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum AccessChoiceFamily {
    NonIndex,
    Prefix,
    MultiLookup,
    BranchSet,
    Range,
}

///
/// RangeCompareKind
///
/// RangeCompareKind classifies the single-clause range forms that map to the
/// planner's range-family explain projection.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum RangeCompareKind {
    StartsWith,
    Ordered,
}

///
/// RangeFieldConstraint
///
/// RangeFieldConstraint accumulates the normalized equality-vs-range state for
/// one index field during ordered range scoring.
///

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(super) struct RangeFieldConstraint {
    pub(super) eq_value: Option<crate::value::Value>,
    pub(super) has_range: bool,
    pub(super) range_bound_count: u8,
}

///
/// CandidateEvaluation
///
/// CandidateEvaluation is the fail-closed evaluator result for one index
/// candidate under the chosen access family.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum CandidateEvaluation {
    Eligible(CandidateScore),
    Rejected(AccessChoiceRejectedReason),
}