icydb-core 0.94.0

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
//! Module: query::plan::model
//! Responsibility: pure logical query-plan data contracts.
//! Does not own: constructors, plan assembly, or semantic interpretation.
//! Boundary: data-only types shared by plan builder/semantics/validation layers.

use crate::{
    db::{
        cursor::ContinuationSignature,
        direction::Direction,
        predicate::{CompareOp, MissingRowPolicy, PredicateExecutionModel},
        query::plan::{
            expr::Expr, order_contract::DeterministicSecondaryOrderContract,
            semantics::LogicalPushdownEligibility,
        },
    },
    model::field::FieldKind,
    value::Value,
};

///
/// QueryMode
///
/// Discriminates load vs delete intent at planning time.
/// Encodes mode-specific fields so invalid states are unrepresentable.
/// Mode checks are explicit and stable at execution time.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueryMode {
    Load(LoadSpec),
    Delete(DeleteSpec),
}

///
/// LoadSpec
///
/// Mode-specific fields for load intents.
/// Encodes pagination without leaking into delete intents.
///
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct LoadSpec {
    pub(crate) limit: Option<u32>,
    pub(crate) offset: u32,
}

impl LoadSpec {
    /// Return optional row-limit bound for this load-mode spec.
    #[must_use]
    pub const fn limit(&self) -> Option<u32> {
        self.limit
    }

    /// Return zero-based pagination offset for this load-mode spec.
    #[must_use]
    pub const fn offset(&self) -> u32 {
        self.offset
    }
}

///
/// DeleteSpec
///
/// Mode-specific fields for delete intents.
/// Encodes delete limits without leaking into load intents.
///

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct DeleteSpec {
    pub(crate) limit: Option<u32>,
    pub(crate) offset: u32,
}

impl DeleteSpec {
    /// Return optional row-limit bound for this delete-mode spec.
    #[must_use]
    pub const fn limit(&self) -> Option<u32> {
        self.limit
    }

    /// Return zero-based ordered delete offset for this delete-mode spec.
    #[must_use]
    pub const fn offset(&self) -> u32 {
        self.offset
    }
}

///
/// OrderDirection
/// Executor-facing ordering direction (applied after filtering).
///
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OrderDirection {
    Asc,
    Desc,
}

///
/// OrderSpec
/// Executor-facing ordering specification.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct OrderSpec {
    pub(crate) fields: Vec<(String, OrderDirection)>,
}

///
/// DeleteLimitSpec
/// Executor-facing ordered delete window.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct DeleteLimitSpec {
    pub(crate) limit: Option<u32>,
    pub(crate) offset: u32,
}

///
/// DistinctExecutionStrategy
///
/// Planner-owned scalar DISTINCT execution strategy.
/// This is execution-mechanics only and must not be used for semantic
/// admissibility decisions.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DistinctExecutionStrategy {
    None,
    PreOrdered,
    HashMaterialize,
}

impl DistinctExecutionStrategy {
    /// Return true when scalar DISTINCT execution is enabled.
    #[must_use]
    pub(crate) const fn is_enabled(self) -> bool {
        !matches!(self, Self::None)
    }
}

///
/// PlannerRouteProfile
///
/// Planner-projected route profile consumed by executor route planning.
/// Carries planner-owned continuation policy plus deterministic order/pushdown
/// contracts that route/load layers must honor without recomputing order shape.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct PlannerRouteProfile {
    continuation_policy: ContinuationPolicy,
    logical_pushdown_eligibility: LogicalPushdownEligibility,
    secondary_order_contract: Option<DeterministicSecondaryOrderContract>,
}

impl PlannerRouteProfile {
    /// Construct one planner-projected route profile.
    #[must_use]
    pub(in crate::db) const fn new(
        continuation_policy: ContinuationPolicy,
        logical_pushdown_eligibility: LogicalPushdownEligibility,
        secondary_order_contract: Option<DeterministicSecondaryOrderContract>,
    ) -> Self {
        Self {
            continuation_policy,
            logical_pushdown_eligibility,
            secondary_order_contract,
        }
    }

    /// Construct one fail-closed route profile for manually assembled plans
    /// that have not yet been finalized against model authority.
    #[must_use]
    pub(in crate::db) const fn seeded_unfinalized(is_grouped: bool) -> Self {
        Self {
            continuation_policy: ContinuationPolicy::new(true, true, !is_grouped),
            logical_pushdown_eligibility: LogicalPushdownEligibility::new(false, is_grouped, false),
            secondary_order_contract: None,
        }
    }

    /// Borrow planner-projected continuation policy contract.
    #[must_use]
    pub(in crate::db) const fn continuation_policy(&self) -> &ContinuationPolicy {
        &self.continuation_policy
    }

    /// Borrow planner-owned logical pushdown eligibility contract.
    #[must_use]
    pub(in crate::db) const fn logical_pushdown_eligibility(&self) -> LogicalPushdownEligibility {
        self.logical_pushdown_eligibility
    }

    /// Borrow the planner-owned deterministic secondary-order contract, if one exists.
    #[must_use]
    pub(in crate::db) const fn secondary_order_contract(
        &self,
    ) -> Option<&DeterministicSecondaryOrderContract> {
        self.secondary_order_contract.as_ref()
    }
}

///
/// ContinuationPolicy
///
/// Planner-projected continuation contract carried into route/executor layers.
/// This contract captures static continuation invariants and must not be
/// rederived by route/load orchestration code.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct ContinuationPolicy {
    requires_anchor: bool,
    requires_strict_advance: bool,
    is_grouped_safe: bool,
}

impl ContinuationPolicy {
    /// Construct one planner-projected continuation policy contract.
    #[must_use]
    pub(in crate::db) const fn new(
        requires_anchor: bool,
        requires_strict_advance: bool,
        is_grouped_safe: bool,
    ) -> Self {
        Self {
            requires_anchor,
            requires_strict_advance,
            is_grouped_safe,
        }
    }

    /// Return true when continuation resume paths require an anchor boundary.
    #[must_use]
    pub(in crate::db) const fn requires_anchor(self) -> bool {
        self.requires_anchor
    }

    /// Return true when continuation resume paths require strict advancement.
    #[must_use]
    pub(in crate::db) const fn requires_strict_advance(self) -> bool {
        self.requires_strict_advance
    }

    /// Return true when grouped continuation usage is semantically safe.
    #[must_use]
    pub(in crate::db) const fn is_grouped_safe(self) -> bool {
        self.is_grouped_safe
    }
}

///
/// ExecutionShapeSignature
///
/// Immutable planner-projected semantic shape signature contract.
/// Continuation transport encodes this contract; route/load consume it as a
/// read-only execution identity boundary without re-deriving semantics.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct ExecutionShapeSignature {
    continuation_signature: ContinuationSignature,
}

impl ExecutionShapeSignature {
    /// Construct one immutable execution-shape signature contract.
    #[must_use]
    pub(in crate::db) const fn new(continuation_signature: ContinuationSignature) -> Self {
        Self {
            continuation_signature,
        }
    }

    /// Borrow the canonical continuation signature for this execution shape.
    #[must_use]
    pub(in crate::db) const fn continuation_signature(self) -> ContinuationSignature {
        self.continuation_signature
    }
}

///
/// PageSpec
/// Executor-facing pagination specification.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PageSpec {
    pub(crate) limit: Option<u32>,
    pub(crate) offset: u32,
}

///
/// AggregateKind
///
/// Canonical aggregate terminal taxonomy owned by query planning.
/// All layers (query, explain, fingerprint, executor) must interpret aggregate
/// terminal semantics through this single enum authority.
/// Executor must derive traversal and fold direction exclusively from this enum.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AggregateKind {
    Count,
    Sum,
    Avg,
    Exists,
    Min,
    Max,
    First,
    Last,
}

impl AggregateKind {
    /// Return the canonical uppercase SQL/render label for this aggregate kind.
    #[must_use]
    pub(in crate::db) const fn sql_label(self) -> &'static str {
        match self {
            Self::Count => "COUNT",
            Self::Sum => "SUM",
            Self::Avg => "AVG",
            Self::Exists => "EXISTS",
            Self::First => "FIRST",
            Self::Last => "LAST",
            Self::Min => "MIN",
            Self::Max => "MAX",
        }
    }

    /// Return whether this terminal kind is `COUNT`.
    #[must_use]
    pub(crate) const fn is_count(self) -> bool {
        matches!(self, Self::Count)
    }

    /// Return whether this terminal kind belongs to the SUM/AVG numeric fold family.
    #[must_use]
    pub(in crate::db) const fn is_sum(self) -> bool {
        matches!(self, Self::Sum | Self::Avg)
    }

    /// Return whether this terminal kind belongs to the extrema family.
    #[must_use]
    pub(in crate::db) const fn is_extrema(self) -> bool {
        matches!(self, Self::Min | Self::Max)
    }

    /// Return whether reducer updates for this kind require a decoded id payload.
    #[must_use]
    pub(in crate::db) const fn requires_decoded_id(self) -> bool {
        !matches!(self, Self::Count | Self::Sum | Self::Avg | Self::Exists)
    }

    /// Return whether grouped aggregate DISTINCT is supported for this kind.
    #[must_use]
    pub(in crate::db) const fn supports_grouped_distinct_v1(self) -> bool {
        matches!(
            self,
            Self::Count | Self::Min | Self::Max | Self::Sum | Self::Avg
        )
    }

    /// Return whether global DISTINCT aggregate shape is supported without GROUP BY keys.
    #[must_use]
    pub(in crate::db) const fn supports_global_distinct_without_group_keys(self) -> bool {
        matches!(self, Self::Count | Self::Sum | Self::Avg)
    }

    /// Return the canonical extrema traversal direction for this kind.
    #[must_use]
    pub(crate) const fn extrema_direction(self) -> Option<Direction> {
        match self {
            Self::Min => Some(Direction::Asc),
            Self::Max => Some(Direction::Desc),
            Self::Count | Self::Sum | Self::Avg | Self::Exists | Self::First | Self::Last => None,
        }
    }

    /// Return the canonical materialized fold direction for this kind.
    #[must_use]
    pub(crate) const fn materialized_fold_direction(self) -> Direction {
        match self {
            Self::Min => Direction::Desc,
            Self::Count
            | Self::Sum
            | Self::Avg
            | Self::Exists
            | Self::Max
            | Self::First
            | Self::Last => Direction::Asc,
        }
    }

    /// Return true when this kind can use bounded aggregate probe hints.
    #[must_use]
    pub(crate) const fn supports_bounded_probe_hint(self) -> bool {
        !self.is_count() && !self.is_sum()
    }

    /// Derive a bounded aggregate probe fetch hint for this kind.
    #[must_use]
    pub(crate) fn bounded_probe_fetch_hint(
        self,
        direction: Direction,
        offset: usize,
        page_limit: Option<usize>,
    ) -> Option<usize> {
        match self {
            Self::Exists | Self::First => Some(offset.saturating_add(1)),
            Self::Min if direction == Direction::Asc => Some(offset.saturating_add(1)),
            Self::Max if direction == Direction::Desc => Some(offset.saturating_add(1)),
            Self::Last => page_limit.map(|limit| offset.saturating_add(limit)),
            Self::Count | Self::Sum | Self::Avg | Self::Min | Self::Max => None,
        }
    }

    /// Return the explain projection mode label for this kind and projection surface.
    #[must_use]
    pub(in crate::db) const fn explain_projection_mode_label(
        self,
        has_projected_field: bool,
        covering_projection: bool,
    ) -> &'static str {
        if has_projected_field {
            if covering_projection {
                "field_idx"
            } else {
                "field_mat"
            }
        } else if matches!(self, Self::Min | Self::Max | Self::First | Self::Last) {
            "entity_term"
        } else {
            "scalar_agg"
        }
    }

    /// Return whether this terminal kind can remain covering on existing-row plans.
    #[must_use]
    pub(in crate::db) const fn supports_covering_existing_rows_terminal(self) -> bool {
        matches!(self, Self::Count | Self::Exists)
    }
}

///
/// GroupAggregateSpec
///
/// One grouped aggregate terminal specification declared at query-plan time.
/// `input_expr` is the single semantic source for grouped aggregate identity.
/// Field-target behavior is derived from plain `Expr::Field` leaves so grouped
/// semantics, explain, fingerprinting, and runtime do not carry a second
/// compatibility shape beside the canonical aggregate input expression.
///

#[derive(Clone, Debug)]
pub(crate) struct GroupAggregateSpec {
    pub(crate) kind: AggregateKind,
    #[cfg(test)]
    #[allow(dead_code)]
    #[cfg(test)]
    pub(crate) target_field: Option<String>,
    pub(crate) input_expr: Option<Box<Expr>>,
    pub(crate) filter_expr: Option<Box<Expr>>,
    pub(crate) distinct: bool,
}

impl PartialEq for GroupAggregateSpec {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind
            && self.input_expr == other.input_expr
            && self.filter_expr == other.filter_expr
            && self.distinct == other.distinct
    }
}

impl Eq for GroupAggregateSpec {}

///
/// FieldSlot
///
/// Canonical resolved field reference used by logical planning.
/// `index` is the stable slot in `EntityModel::fields`; `field` is retained
/// for diagnostics and explain surfaces.
/// `kind` freezes planner-resolved field metadata so executor boundaries do
/// not need to reopen `EntityModel` just to recover type/capability shape.
///

#[derive(Clone, Debug)]
pub(crate) struct FieldSlot {
    pub(crate) index: usize,
    pub(crate) field: String,
    pub(crate) kind: Option<FieldKind>,
}

impl PartialEq for FieldSlot {
    fn eq(&self, other: &Self) -> bool {
        self.index == other.index && self.field == other.field
    }
}

impl Eq for FieldSlot {}

///
/// GroupedExecutionConfig
///
/// Declarative grouped-execution budget policy selected by query planning.
/// This remains planner-owned input; executor policy bridges may still apply
/// defaults and enforcement strategy at runtime boundaries.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct GroupedExecutionConfig {
    pub(crate) max_groups: u64,
    pub(crate) max_group_bytes: u64,
}

///
/// GroupSpec
///
/// Declarative GROUP BY stage contract attached to a validated base plan.
/// This wrapper is intentionally semantic-only; field-slot resolution and
/// execution-mode derivation remain executor-owned boundaries.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct GroupSpec {
    pub(crate) group_fields: Vec<FieldSlot>,
    pub(crate) aggregates: Vec<GroupAggregateSpec>,
    pub(crate) execution: GroupedExecutionConfig,
}

///
/// GroupHavingSymbol
///
/// Reference to one grouped HAVING input symbol.
/// Group-field symbols reference resolved grouped key slots.
/// Aggregate symbols reference grouped aggregate outputs by declaration index.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum GroupHavingSymbol {
    GroupField(FieldSlot),
    AggregateIndex(usize),
}

///
/// GroupHavingClause
///
/// One conservative grouped HAVING clause.
/// This clause model intentionally supports one symbol-to-literal comparison
/// and excludes arbitrary expression trees in grouped v1.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct GroupHavingClause {
    pub(crate) symbol: GroupHavingSymbol,
    pub(crate) op: CompareOp,
    pub(crate) value: Value,
}

///
/// ScalarPlan
///
/// Pure scalar logical query intent produced by the planner.
///
/// A `ScalarPlan` represents the access-independent query semantics:
/// predicate/filter, ordering, distinct behavior, pagination/delete windows,
/// and read-consistency mode.
///
/// Design notes:
/// - Predicates are applied *after* data access
/// - Ordering is applied after filtering
/// - Pagination is applied after ordering (load only)
/// - Delete limits are applied after ordering (delete only)
/// - Missing-row policy is explicit and must not depend on access strategy
///
/// This struct is the logical compiler stage output and intentionally excludes
/// access-path details.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ScalarPlan {
    /// Load vs delete intent.
    pub(crate) mode: QueryMode,

    /// Optional residual predicate applied after access.
    pub(crate) predicate: Option<PredicateExecutionModel>,

    /// Optional ordering specification.
    pub(crate) order: Option<OrderSpec>,

    /// Optional distinct semantics over ordered rows.
    pub(crate) distinct: bool,

    /// Optional ordered delete window (delete intents only).
    pub(crate) delete_limit: Option<DeleteLimitSpec>,

    /// Optional pagination specification.
    pub(crate) page: Option<PageSpec>,

    /// Missing-row policy for execution.
    pub(crate) consistency: MissingRowPolicy,
}

///
/// GroupPlan
///
/// Pure grouped logical intent emitted by grouped planning.
/// Group metadata is carried through one canonical `GroupSpec` contract.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct GroupPlan {
    pub(crate) scalar: ScalarPlan,
    pub(crate) group: GroupSpec,
    pub(crate) having_expr: Option<Expr>,
}

///
/// LogicalPlan
///
/// Exclusive logical query intent emitted by planning.
/// Scalar and grouped semantics are distinct variants by construction.
///

// Logical plans keep scalar and grouped shapes inline because planner/executor handoff
// passes these variants by ownership and boxing would widen that boundary for little benefit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum LogicalPlan {
    Scalar(ScalarPlan),
    Grouped(GroupPlan),
}