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
//! Module: db::query::plan::semantics::grouped_strategy
//! Responsibility: derive grouped-query execution semantics from grouped
//! projection, aggregate, and ordering contracts.
//! Does not own: grouped executor runtime implementation.
//! Boundary: keeps grouped planning semantics explicit before executor handoff.

use crate::db::{
    access::AccessPlan,
    query::plan::{
        AccessPlannedQuery, AggregateKind, FieldSlot, GroupAggregateSpec, OrderSpec,
        expr::{
            GroupedOrderTermAdmissibility, GroupedTopKOrderTermAdmissibility,
            classify_grouped_order_term_for_field, classify_grouped_top_k_order_term,
            grouped_top_k_order_term_requires_heap,
        },
    },
};

// Keep the raw grouped family selector internal so downstream code consumes the
// planner-owned `GroupedPlanStrategy` artifact instead of rebuilding behavior
// from a parallel hint surface.

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum GroupedPlanFamily {
    Hash,
    Ordered,
    TopK,
}

///
/// GroupedPlanAggregateFamily
///
/// Planner-owned grouped aggregate-family profile.
/// This is intentionally coarse and execution-oriented: it captures which
/// grouped aggregate family the planner admitted so runtime can select grouped
/// execution paths without rebuilding family policy from raw aggregate
/// expressions again.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum GroupedPlanAggregateFamily {
    CountRowsOnly,
    FieldTargetRows,
    GenericRows,
}

impl GroupedPlanAggregateFamily {
    /// Return the stable planner-owned aggregate-family code.
    #[must_use]
    pub(crate) const fn code(self) -> &'static str {
        match self {
            Self::CountRowsOnly => "count_rows_only",
            Self::FieldTargetRows => "field_target_rows",
            Self::GenericRows => "generic_rows",
        }
    }
}

///
/// GroupedPlanFallbackReason
///
/// Planner-authored grouped fallback taxonomy.
/// These reasons explain why grouped planning failed closed from the ordered
/// grouped family to the hash grouped family before route/runtime projection.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum GroupedPlanFallbackReason {
    DistinctGroupingNotAdmitted,
    ResidualPredicateBlocksGroupedOrder,
    AggregateStreamingNotSupported,
    HavingBlocksGroupedOrder,
    GroupKeyOrderPrefixMismatch,
    GroupKeyOrderExpressionNotAdmissible,
    GroupKeyOrderUnavailable,
}

impl GroupedPlanFallbackReason {
    /// Return the stable planner-owned fallback reason code.
    #[must_use]
    pub(in crate::db) const fn code(self) -> &'static str {
        match self {
            Self::DistinctGroupingNotAdmitted => "distinct_grouping_not_admitted",
            Self::ResidualPredicateBlocksGroupedOrder => "residual_predicate_blocks_grouped_order",
            Self::AggregateStreamingNotSupported => "aggregate_streaming_not_supported",
            Self::HavingBlocksGroupedOrder => "having_blocks_grouped_order",
            Self::GroupKeyOrderPrefixMismatch => "group_key_order_prefix_mismatch",
            Self::GroupKeyOrderExpressionNotAdmissible => {
                "group_key_order_expression_not_admissible"
            }
            Self::GroupKeyOrderUnavailable => "group_key_order_unavailable",
        }
    }
}

///
/// GroupedPlanStrategy
///
/// Planner-owned grouped strategy artifact carried into executor and explain.
/// This artifact now carries the planner-selected grouped family plus the
/// stable planner fallback reason when ordered grouped execution is not
/// admitted. Runtime and explain must project from this structure instead of
/// re-deriving grouped admission semantics downstream.
///
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct GroupedPlanStrategy {
    family: GroupedPlanFamily,
    aggregate_family: GroupedPlanAggregateFamily,
    fallback_reason: Option<GroupedPlanFallbackReason>,
}

impl GroupedPlanStrategy {
    /// Return the stable planner-owned grouped strategy code.
    #[must_use]
    pub(crate) const fn code(self) -> &'static str {
        match self.family {
            GroupedPlanFamily::Hash => "hash_group",
            GroupedPlanFamily::Ordered => "ordered_group",
            GroupedPlanFamily::TopK => "top_k_group",
        }
    }

    /// Construct one hash-group planner strategy artifact with one planner-authored fallback reason.
    #[cfg(test)]
    #[must_use]
    pub(crate) const fn hash_group(reason: GroupedPlanFallbackReason) -> Self {
        Self::hash_group_with_aggregate_family(reason, GroupedPlanAggregateFamily::CountRowsOnly)
    }

    /// Construct one hash-group planner strategy artifact with one explicit grouped aggregate-family profile.
    #[must_use]
    pub(crate) const fn hash_group_with_aggregate_family(
        reason: GroupedPlanFallbackReason,
        aggregate_family: GroupedPlanAggregateFamily,
    ) -> Self {
        Self {
            family: GroupedPlanFamily::Hash,
            aggregate_family,
            fallback_reason: Some(reason),
        }
    }

    /// Construct one ordered-group planner strategy artifact.
    #[cfg(test)]
    #[must_use]
    pub(crate) const fn ordered_group() -> Self {
        Self::ordered_group_with_aggregate_family(GroupedPlanAggregateFamily::CountRowsOnly)
    }

    /// Construct one ordered-group planner strategy artifact with one explicit grouped aggregate-family profile.
    #[must_use]
    pub(crate) const fn ordered_group_with_aggregate_family(
        aggregate_family: GroupedPlanAggregateFamily,
    ) -> Self {
        Self {
            family: GroupedPlanFamily::Ordered,
            aggregate_family,
            fallback_reason: None,
        }
    }

    /// Construct one bounded grouped Top-K planner strategy artifact with one explicit grouped aggregate-family profile.
    #[must_use]
    pub(crate) const fn top_k_group_with_aggregate_family(
        aggregate_family: GroupedPlanAggregateFamily,
    ) -> Self {
        Self {
            family: GroupedPlanFamily::TopK,
            aggregate_family,
            fallback_reason: None,
        }
    }

    /// Return whether the planner selected the ordered grouped family.
    #[must_use]
    pub(crate) const fn is_ordered_group(self) -> bool {
        matches!(self.family, GroupedPlanFamily::Ordered)
    }

    /// Return whether the planner selected the bounded grouped Top-K family.
    #[must_use]
    pub(crate) const fn is_top_k_group(self) -> bool {
        matches!(self.family, GroupedPlanFamily::TopK)
    }

    /// Return whether the planner admitted the ordered grouped family.
    #[must_use]
    pub(crate) const fn ordered_group_admitted(self) -> bool {
        self.is_ordered_group()
    }

    /// Return the planner-owned grouped aggregate-family profile.
    #[must_use]
    pub(crate) const fn aggregate_family(self) -> GroupedPlanAggregateFamily {
        self.aggregate_family
    }

    /// Return whether the planner admitted the dedicated grouped `COUNT(*)` family.
    #[must_use]
    pub(crate) const fn is_single_count_rows(self) -> bool {
        matches!(
            self.aggregate_family,
            GroupedPlanAggregateFamily::CountRowsOnly
        )
    }

    /// Return the stable planner-authored fallback reason when ordered grouped execution was not admitted.
    #[must_use]
    pub(crate) const fn fallback_reason(self) -> Option<GroupedPlanFallbackReason> {
        self.fallback_reason
    }
}

/// Project one planner-owned grouped strategy from one access-planned query.
#[must_use]
pub(in crate::db) fn grouped_plan_strategy(
    plan: &AccessPlannedQuery,
) -> Option<GroupedPlanStrategy> {
    // Phase 1: project the grouped ORDER BY lane early so aggregate-streaming
    // compatibility only gates the canonical ordered-group family. The bounded
    // Top-K family runs through grouped fold/finalize instead of ordered
    // grouped streaming, so widened aggregate-input expressions must not get
    // rejected here before the planner can reserve that lane.
    let grouped = plan.grouped_plan()?;
    let aggregate_family = grouped_plan_aggregate_family(grouped.group.aggregates.as_slice());
    let order_strategy_projection = grouped_order_strategy_projection(
        grouped.scalar.order.as_ref(),
        grouped.group.group_fields.as_slice(),
    );

    if grouped.scalar.distinct {
        return Some(hash_group_fallback_strategy(
            GroupedPlanFallbackReason::DistinctGroupingNotAdmitted,
            aggregate_family,
        ));
    }

    // Reserve the bounded Top-K lane before checking residual-filter streaming
    // compatibility. Residual predicates still block the older canonical
    // ordered-group path, but post-aggregate Top-K runs through grouped fold
    // and finalize rather than direct ordered streaming.
    if matches!(
        order_strategy_projection,
        GroupedOrderStrategyProjection::TopK
    ) {
        return Some(GroupedPlanStrategy::top_k_group_with_aggregate_family(
            aggregate_family,
        ));
    }

    if plan.has_residual_predicate() {
        return Some(hash_group_fallback_strategy(
            GroupedPlanFallbackReason::ResidualPredicateBlocksGroupedOrder,
            aggregate_family,
        ));
    }
    if !matches!(
        order_strategy_projection,
        GroupedOrderStrategyProjection::TopK
    ) && !grouped_aggregates_streaming_compatible(grouped.group.aggregates.as_slice())
    {
        return Some(hash_group_fallback_strategy(
            GroupedPlanFallbackReason::AggregateStreamingNotSupported,
            aggregate_family,
        ));
    }
    if !crate::db::query::plan::semantics::group_having::grouped_having_streaming_compatible(
        grouped.having_expr.as_ref(),
    ) {
        return Some(hash_group_fallback_strategy(
            GroupedPlanFallbackReason::HavingBlocksGroupedOrder,
            aggregate_family,
        ));
    }

    // Phase 2: require logical ORDER BY alignment and physical access-order proof for ordered grouping.
    match order_strategy_projection {
        GroupedOrderStrategyProjection::Canonical => {}
        GroupedOrderStrategyProjection::TopK => unreachable!(
            "bounded grouped Top-K lane should be reserved before streaming-only fallback checks"
        ),
        GroupedOrderStrategyProjection::HashFallback(reason) => {
            return Some(hash_group_fallback_strategy(reason, aggregate_family));
        }
    }
    if grouped_access_path_proves_group_order(grouped.group.group_fields.as_slice(), &plan.access) {
        return Some(GroupedPlanStrategy::ordered_group_with_aggregate_family(
            aggregate_family,
        ));
    }

    Some(hash_group_fallback_strategy(
        GroupedPlanFallbackReason::GroupKeyOrderUnavailable,
        aggregate_family,
    ))
}

pub(in crate::db) fn grouped_plan_aggregate_family(
    aggregates: &[GroupAggregateSpec],
) -> GroupedPlanAggregateFamily {
    if matches!(aggregates, [aggregate] if aggregate.kind() == AggregateKind::Count
        && aggregate.target_field().is_none()
        && !aggregate.distinct())
    {
        return GroupedPlanAggregateFamily::CountRowsOnly;
    }

    if aggregates.iter().all(|aggregate| {
        aggregate.target_field().is_some()
            && matches!(
                aggregate.kind(),
                AggregateKind::Count
                    | AggregateKind::Sum
                    | AggregateKind::Avg
                    | AggregateKind::Min
                    | AggregateKind::Max
            )
    }) {
        return GroupedPlanAggregateFamily::FieldTargetRows;
    }

    if aggregates.iter().all(|aggregate| {
        aggregate.target_field().is_none()
            && matches!(
                aggregate.kind(),
                AggregateKind::Exists
                    | AggregateKind::Min
                    | AggregateKind::Max
                    | AggregateKind::First
                    | AggregateKind::Last
            )
    }) {
        return GroupedPlanAggregateFamily::GenericRows;
    }

    GroupedPlanAggregateFamily::GenericRows
}

fn grouped_aggregates_streaming_compatible(aggregates: &[GroupAggregateSpec]) -> bool {
    aggregates
        .iter()
        .all(GroupAggregateSpec::streaming_compatible_v1)
}

// Lift the repeated hash-group fallback constructor so grouped strategy
// selection reads as planner policy gates instead of repeated artifact wiring.
const fn hash_group_fallback_strategy(
    reason: GroupedPlanFallbackReason,
    aggregate_family: GroupedPlanAggregateFamily,
) -> GroupedPlanStrategy {
    GroupedPlanStrategy::hash_group_with_aggregate_family(reason, aggregate_family)
}

///
/// GroupedOrderStrategyProjection
///
/// Planner-local grouped order-strategy projection result.
/// This keeps `0.87` canonical grouped-key proof and `0.88` Top-K reservation
/// under one owner so grouped strategy selection does not fork those decisions
/// through parallel helper trees.
///
enum GroupedOrderStrategyProjection {
    Canonical,
    TopK,
    HashFallback(GroupedPlanFallbackReason),
}

fn grouped_order_strategy_projection(
    order: Option<&OrderSpec>,
    group_fields: &[FieldSlot],
) -> GroupedOrderStrategyProjection {
    let Some(order) = order else {
        return GroupedOrderStrategyProjection::Canonical;
    };
    let grouped_field_names = group_fields
        .iter()
        .map(FieldSlot::field)
        .collect::<Vec<_>>();
    let mut top_k_required = false;

    // Phase 1: walk the user-declared grouped ORDER BY list once and keep
    // canonical grouped-key proof separate from the broader grouped Top-K
    // expression family admitted by the `0.88` planner lane.
    for (index, (order_field, _)) in order.fields.iter().enumerate() {
        let aggregate_driven = grouped_top_k_order_term_requires_heap(order_field);

        if index < group_fields.len() {
            match classify_grouped_order_term_for_field(order_field, group_fields[index].field()) {
                GroupedOrderTermAdmissibility::Preserves(_) => continue,
                GroupedOrderTermAdmissibility::PrefixMismatch => {
                    if !aggregate_driven {
                        return GroupedOrderStrategyProjection::HashFallback(
                            GroupedPlanFallbackReason::GroupKeyOrderPrefixMismatch,
                        );
                    }
                }
                GroupedOrderTermAdmissibility::UnsupportedExpression => {
                    if !aggregate_driven {
                        return GroupedOrderStrategyProjection::HashFallback(
                            GroupedPlanFallbackReason::GroupKeyOrderExpressionNotAdmissible,
                        );
                    }
                }
            }
        }

        if !aggregate_driven {
            continue;
        }

        match classify_grouped_top_k_order_term(order_field, grouped_field_names.as_slice()) {
            GroupedTopKOrderTermAdmissibility::Admissible => {
                top_k_required = true;
            }
            GroupedTopKOrderTermAdmissibility::NonGroupFieldReference => {
                return GroupedOrderStrategyProjection::HashFallback(
                    GroupedPlanFallbackReason::GroupKeyOrderPrefixMismatch,
                );
            }
            GroupedTopKOrderTermAdmissibility::UnsupportedExpression => {
                return GroupedOrderStrategyProjection::HashFallback(
                    GroupedPlanFallbackReason::GroupKeyOrderExpressionNotAdmissible,
                );
            }
        }
    }

    if top_k_required {
        return GroupedOrderStrategyProjection::TopK;
    }

    if order.fields.len() < group_fields.len() {
        return GroupedOrderStrategyProjection::HashFallback(
            GroupedPlanFallbackReason::GroupKeyOrderPrefixMismatch,
        );
    }

    GroupedOrderStrategyProjection::Canonical
}

fn grouped_access_path_proves_group_order<K>(
    group_fields: &[FieldSlot],
    access: &AccessPlan<K>,
) -> bool {
    // Derive grouped-order evidence from the normalized executable access contract so
    // planner strategy hints do not branch on raw AccessPath variants directly.
    //
    // Both index-prefix and index-range shapes can preserve grouped key order:
    // - `IndexPrefix` proves one leading equality prefix plus ordered suffix traversal.
    // - `IndexRange` proves one ordered range traversal after its equality prefix.
    //
    // Grouped planning only needs the stable `(index, prefix_len)` contract here,
    // not the raw range bounds themselves.
    let executable = access.resolve_strategy();
    let Some(path) = executable.as_path() else {
        return false;
    };
    let Some((index, prefix_len)) = path
        .index_prefix_details()
        .or_else(|| path.index_range_details())
    else {
        return false;
    };
    let index_fields = index.fields();
    let mut cursor = 0usize;

    // Equality-bound prefix fields are fixed constants during traversal, so
    // grouped-order proof may skip them until the next declared grouped key.
    // Any gap beyond the equality prefix remains unfixed and therefore blocks
    // ordered grouping.
    for group_field in group_fields {
        while cursor < prefix_len
            && cursor < index_fields.len()
            && index_fields[cursor] != group_field.field()
        {
            cursor = cursor.saturating_add(1);
        }
        if cursor >= index_fields.len() || index_fields[cursor] != group_field.field() {
            return false;
        }
        cursor = cursor.saturating_add(1);
    }

    true
}