icydb-core 0.137.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
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//! Module: db::session::query
//! Responsibility: session-bound query planning, explain, and cursor execution
//! helpers that recover store visibility before delegating to query-owned logic.
//! Does not own: query intent construction or executor runtime semantics.
//! Boundary: resolves session visibility and cursor policy before handing work to the planner/executor.

mod cache;

#[cfg(feature = "diagnostics")]
use crate::db::executor::{
    GroupedCountAttribution, GroupedExecutePhaseAttribution, ScalarExecutePhaseAttribution,
};
use crate::{
    db::{
        DbSession, EntityResponse, LoadQueryResult, PagedGroupedExecutionWithTrace,
        PagedLoadExecutionWithTrace, PersistedRow, Query, QueryError, QueryTracePlan,
        TraceExecutionFamily,
        access::summarize_executable_access_plan,
        cursor::{
            CursorPlanError, decode_optional_cursor_token, decode_optional_grouped_cursor_token,
        },
        diagnostics::ExecutionTrace,
        executor::{
            ExecutionFamily, ExecutorPlanError, GroupedCursorPage, LoadExecutor,
            PreparedExecutionPlan, ScalarNumericFieldBoundaryRequest,
            ScalarProjectionBoundaryOutput, ScalarProjectionBoundaryRequest,
            ScalarTerminalBoundaryOutput, ScalarTerminalBoundaryRequest,
        },
        query::builder::{
            PreparedFluentAggregateExplainStrategy,
            PreparedFluentExistingRowsTerminalRuntimeRequest,
            PreparedFluentExistingRowsTerminalStrategy, PreparedFluentNumericFieldRuntimeRequest,
            PreparedFluentNumericFieldStrategy, PreparedFluentOrderSensitiveTerminalRuntimeRequest,
            PreparedFluentOrderSensitiveTerminalStrategy, PreparedFluentProjectionRuntimeRequest,
            PreparedFluentProjectionStrategy, PreparedFluentScalarTerminalRuntimeRequest,
            PreparedFluentScalarTerminalStrategy,
        },
        query::explain::{
            ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor, ExplainPlan,
        },
        query::fluent::load::{FluentProjectionTerminalOutput, FluentScalarTerminalOutput},
        query::{
            intent::{CompiledQuery, PlannedQuery},
            plan::{FieldSlot, QueryMode},
        },
        session::{finalize_grouped_paged_execution, finalize_scalar_paged_execution},
    },
    error::InternalError,
    traits::{CanisterKind, EntityKind, EntityValue, Path},
    types::{Decimal, Id},
    value::Value,
};
pub(in crate::db) use cache::QueryPlanCacheAttribution;
#[cfg(test)]
pub(in crate::db) use cache::QueryPlanVisibility;
pub(in crate::db::session) use cache::query_plan_cache_reuse_event;
#[cfg(feature = "diagnostics")]
use candid::CandidType;
#[cfg(feature = "diagnostics")]
use serde::Deserialize;

// Translate executor route-family selection into the query-owned trace label
// at the session boundary so trace DTOs do not depend on executor types.
const fn trace_execution_family_from_executor(family: ExecutionFamily) -> TraceExecutionFamily {
    match family {
        ExecutionFamily::PrimaryKey => TraceExecutionFamily::PrimaryKey,
        ExecutionFamily::Ordered => TraceExecutionFamily::Ordered,
        ExecutionFamily::Grouped => TraceExecutionFamily::Grouped,
    }
}

// Convert executor plan-surface failures at the session boundary so query error
// types do not import executor-owned error enums.
pub(in crate::db::session) fn query_error_from_executor_plan_error(
    err: ExecutorPlanError,
) -> QueryError {
    match err {
        ExecutorPlanError::Cursor(err) => QueryError::from_cursor_plan_error(*err),
    }
}

///
/// QueryExecutionAttribution
///
/// QueryExecutionAttribution records the top-level compile/execute split for
/// typed/fluent query execution at the session boundary.
/// Every field is an additive counter where zero means no observed work or no
/// observed event for that bucket. Future non-additive diagnostics must use an
/// explicit presence type instead of relying on `Default`.
///
#[cfg(feature = "diagnostics")]
#[derive(CandidType, Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct QueryExecutionAttribution {
    pub compile_local_instructions: u64,
    pub plan_lookup_local_instructions: u64,
    pub executor_invocation_local_instructions: u64,
    pub response_finalization_local_instructions: u64,
    pub runtime_local_instructions: u64,
    pub finalize_local_instructions: u64,
    pub direct_data_row_scan_local_instructions: u64,
    pub direct_data_row_key_stream_local_instructions: u64,
    pub direct_data_row_row_read_local_instructions: u64,
    pub direct_data_row_key_encode_local_instructions: u64,
    pub direct_data_row_store_get_local_instructions: u64,
    pub direct_data_row_order_window_local_instructions: u64,
    pub direct_data_row_page_window_local_instructions: u64,
    pub grouped_stream_local_instructions: u64,
    pub grouped_fold_local_instructions: u64,
    pub grouped_finalize_local_instructions: u64,
    pub grouped_count_borrowed_hash_computations: u64,
    pub grouped_count_bucket_candidate_checks: u64,
    pub grouped_count_existing_group_hits: u64,
    pub grouped_count_new_group_inserts: u64,
    pub grouped_count_row_materialization_local_instructions: u64,
    pub grouped_count_group_lookup_local_instructions: u64,
    pub grouped_count_existing_group_update_local_instructions: u64,
    pub grouped_count_new_group_insert_local_instructions: u64,
    pub response_decode_local_instructions: u64,
    pub execute_local_instructions: u64,
    pub total_local_instructions: u64,
    pub shared_query_plan_cache_hits: u64,
    pub shared_query_plan_cache_misses: u64,
}

#[cfg(feature = "diagnostics")]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct QueryExecutePhaseAttribution {
    executor_invocation_local_instructions: u64,
    response_finalization_local_instructions: u64,
    runtime_local_instructions: u64,
    finalize_local_instructions: u64,
    direct_data_row_scan_local_instructions: u64,
    direct_data_row_key_stream_local_instructions: u64,
    direct_data_row_row_read_local_instructions: u64,
    direct_data_row_key_encode_local_instructions: u64,
    direct_data_row_store_get_local_instructions: u64,
    direct_data_row_order_window_local_instructions: u64,
    direct_data_row_page_window_local_instructions: u64,
    grouped_stream_local_instructions: u64,
    grouped_fold_local_instructions: u64,
    grouped_finalize_local_instructions: u64,
    grouped_count: GroupedCountAttribution,
}

#[cfg(feature = "diagnostics")]
#[expect(
    clippy::missing_const_for_fn,
    reason = "the wasm32 branch reads the runtime performance counter and cannot be const"
)]
fn read_query_local_instruction_counter() -> u64 {
    #[cfg(target_arch = "wasm32")]
    {
        canic_cdk::api::performance_counter(1)
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        0
    }
}

#[cfg(feature = "diagnostics")]
fn measure_query_stage<T, E>(run: impl FnOnce() -> Result<T, E>) -> (u64, Result<T, E>) {
    let start = read_query_local_instruction_counter();
    let result = run();
    let delta = read_query_local_instruction_counter().saturating_sub(start);

    (delta, result)
}

impl<C: CanisterKind> DbSession<C> {
    #[cfg(feature = "diagnostics")]
    const fn empty_query_execute_phase_attribution() -> QueryExecutePhaseAttribution {
        QueryExecutePhaseAttribution {
            executor_invocation_local_instructions: 0,
            response_finalization_local_instructions: 0,
            runtime_local_instructions: 0,
            finalize_local_instructions: 0,
            direct_data_row_scan_local_instructions: 0,
            direct_data_row_key_stream_local_instructions: 0,
            direct_data_row_row_read_local_instructions: 0,
            direct_data_row_key_encode_local_instructions: 0,
            direct_data_row_store_get_local_instructions: 0,
            direct_data_row_order_window_local_instructions: 0,
            direct_data_row_page_window_local_instructions: 0,
            grouped_stream_local_instructions: 0,
            grouped_fold_local_instructions: 0,
            grouped_finalize_local_instructions: 0,
            grouped_count: GroupedCountAttribution::none(),
        }
    }

    #[cfg(feature = "diagnostics")]
    const fn scalar_query_execute_phase_attribution(
        phase: ScalarExecutePhaseAttribution,
        executor_invocation_local_instructions: u64,
    ) -> QueryExecutePhaseAttribution {
        QueryExecutePhaseAttribution {
            executor_invocation_local_instructions,
            response_finalization_local_instructions: 0,
            runtime_local_instructions: phase.runtime_local_instructions,
            finalize_local_instructions: phase.finalize_local_instructions,
            direct_data_row_scan_local_instructions: phase.direct_data_row_scan_local_instructions,
            direct_data_row_key_stream_local_instructions: phase
                .direct_data_row_key_stream_local_instructions,
            direct_data_row_row_read_local_instructions: phase
                .direct_data_row_row_read_local_instructions,
            direct_data_row_key_encode_local_instructions: phase
                .direct_data_row_key_encode_local_instructions,
            direct_data_row_store_get_local_instructions: phase
                .direct_data_row_store_get_local_instructions,
            direct_data_row_order_window_local_instructions: phase
                .direct_data_row_order_window_local_instructions,
            direct_data_row_page_window_local_instructions: phase
                .direct_data_row_page_window_local_instructions,
            grouped_stream_local_instructions: 0,
            grouped_fold_local_instructions: 0,
            grouped_finalize_local_instructions: 0,
            grouped_count: GroupedCountAttribution::none(),
        }
    }

    #[cfg(feature = "diagnostics")]
    const fn grouped_query_execute_phase_attribution(
        phase: GroupedExecutePhaseAttribution,
        executor_invocation_local_instructions: u64,
        response_finalization_local_instructions: u64,
    ) -> QueryExecutePhaseAttribution {
        QueryExecutePhaseAttribution {
            executor_invocation_local_instructions,
            response_finalization_local_instructions,
            runtime_local_instructions: phase
                .stream_local_instructions
                .saturating_add(phase.fold_local_instructions),
            finalize_local_instructions: phase.finalize_local_instructions,
            direct_data_row_scan_local_instructions: 0,
            direct_data_row_key_stream_local_instructions: 0,
            direct_data_row_row_read_local_instructions: 0,
            direct_data_row_key_encode_local_instructions: 0,
            direct_data_row_store_get_local_instructions: 0,
            direct_data_row_order_window_local_instructions: 0,
            direct_data_row_page_window_local_instructions: 0,
            grouped_stream_local_instructions: phase.stream_local_instructions,
            grouped_fold_local_instructions: phase.fold_local_instructions,
            grouped_finalize_local_instructions: phase.finalize_local_instructions,
            grouped_count: phase.grouped_count,
        }
    }

    // Compile one typed query using only the indexes currently visible for the
    // query's recovered store.
    pub(in crate::db) fn compile_query_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<CompiledQuery<E>, QueryError>
    where
        E: EntityKind<Canister = C>,
    {
        self.map_cached_shared_query_plan_for_entity(query, CompiledQuery::<E>::from_plan)
    }

    // Build one logical planned-query shell using only the indexes currently
    // visible for the query's recovered store.
    pub(in crate::db) fn planned_query_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<PlannedQuery<E>, QueryError>
    where
        E: EntityKind<Canister = C>,
    {
        self.map_cached_shared_query_plan_for_entity(query, PlannedQuery::<E>::from_plan)
    }

    // Project one logical explain payload using only planner-visible indexes.
    pub(in crate::db) fn explain_query_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<ExplainPlan, QueryError>
    where
        E: EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, Query::<E>::explain_with_visible_indexes)
    }

    // Hash one typed query plan using only the indexes currently visible for
    // the query's recovered store.
    pub(in crate::db) fn query_plan_hash_hex_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<String, QueryError>
    where
        E: EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, Query::<E>::plan_hash_hex_with_visible_indexes)
    }

    // Explain one load execution shape using only planner-visible
    // indexes from the recovered store state.
    pub(in crate::db) fn explain_query_execution_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
    where
        E: EntityValue + EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, Query::<E>::explain_execution_with_visible_indexes)
    }

    // Render one load execution descriptor plus route diagnostics using
    // only planner-visible indexes from the recovered store state.
    pub(in crate::db) fn explain_query_execution_verbose_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
    ) -> Result<String, QueryError>
    where
        E: EntityValue + EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, |query, visible_indexes| {
            let (prepared_plan, cache_attribution) =
                self.cached_prepared_query_plan_for_entity(query)?;
            let mut plan = prepared_plan.logical_plan().clone();

            // Freeze the same planner-owned explain access-choice snapshot used
            // by the direct non-cached explain path before rendering verbose
            // diagnostics from the reused logical plan.
            plan.finalize_access_choice_for_model_with_indexes(
                query.structural().model(),
                visible_indexes.as_slice(),
            );

            query
                .structural()
                .finalized_execution_diagnostics_from_plan_with_descriptor_mutator(
                    &plan,
                    Some(query_plan_cache_reuse_event(cache_attribution)),
                    |_| {},
                )
                .map(|diagnostics| diagnostics.render_text_verbose())
        })
    }

    // Explain one prepared fluent aggregate terminal using only
    // planner-visible indexes from the recovered store state.
    pub(in crate::db) fn explain_query_prepared_aggregate_terminal_with_visible_indexes<E, S>(
        &self,
        query: &Query<E>,
        strategy: &S,
    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
    where
        E: EntityValue + EntityKind<Canister = C>,
        S: PreparedFluentAggregateExplainStrategy,
    {
        self.with_query_visible_indexes(query, |query, visible_indexes| {
            query
                .explain_prepared_aggregate_terminal_with_visible_indexes(visible_indexes, strategy)
        })
    }

    // Explain one `bytes_by(field)` terminal using only planner-visible
    // indexes from the recovered store state.
    pub(in crate::db) fn explain_query_bytes_by_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
        target_field: &str,
    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
    where
        E: EntityValue + EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, |query, visible_indexes| {
            query.explain_bytes_by_with_visible_indexes(visible_indexes, target_field)
        })
    }

    // Explain one prepared fluent projection terminal using only
    // planner-visible indexes from the recovered store state.
    pub(in crate::db) fn explain_query_prepared_projection_terminal_with_visible_indexes<E>(
        &self,
        query: &Query<E>,
        strategy: &PreparedFluentProjectionStrategy,
    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
    where
        E: EntityValue + EntityKind<Canister = C>,
    {
        self.with_query_visible_indexes(query, |query, visible_indexes| {
            query.explain_prepared_projection_terminal_with_visible_indexes(
                visible_indexes,
                strategy,
            )
        })
    }

    // Validate that one execution strategy is admissible for scalar paged load
    // execution and fail closed on grouped/primary-key-only routes.
    fn ensure_scalar_paged_execution_family(family: ExecutionFamily) -> Result<(), QueryError> {
        match family {
            ExecutionFamily::PrimaryKey => Err(QueryError::invariant(
                CursorPlanError::cursor_requires_explicit_or_grouped_ordering_message(),
            )),
            ExecutionFamily::Ordered => Ok(()),
            ExecutionFamily::Grouped => Err(QueryError::invariant(
                "grouped queries execute via execute(), not page().execute()",
            )),
        }
    }

    // Validate that one execution strategy is admissible for the grouped
    // execution surface.
    fn ensure_grouped_execution_family(family: ExecutionFamily) -> Result<(), QueryError> {
        match family {
            ExecutionFamily::Grouped => Ok(()),
            ExecutionFamily::PrimaryKey | ExecutionFamily::Ordered => Err(QueryError::invariant(
                "grouped execution requires grouped logical plans",
            )),
        }
    }

    // Finalize one grouped cursor page into the outward grouped execution
    // payload so grouped cursor encoding and continuation-shape validation
    // stay owned by the session boundary.
    fn finalize_grouped_execution_page(
        page: GroupedCursorPage,
        trace: Option<ExecutionTrace>,
    ) -> Result<PagedGroupedExecutionWithTrace, QueryError> {
        finalize_grouped_paged_execution(page, trace)
    }

    /// Execute one scalar load/delete query and return materialized response rows.
    pub fn execute_query<E>(&self, query: &Query<E>) -> Result<EntityResponse<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: compile typed intent into one prepared execution-plan contract.
        let mode = query.mode();
        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;

        // Phase 2: delegate execution to the shared compiled-plan entry path.
        self.execute_query_dyn(mode, plan)
    }

    /// Execute one typed query while reporting the compile/execute split at
    /// the shared fluent query seam.
    #[cfg(feature = "diagnostics")]
    #[doc(hidden)]
    #[expect(
        clippy::too_many_lines,
        reason = "the diagnostics-only attribution path keeps grouped and scalar execution on one explicit compile/execute accounting seam"
    )]
    #[expect(
        clippy::needless_update,
        reason = "diagnostics attribution literals stay default-backed so future counters do not break every initializer"
    )]
    pub fn execute_query_result_with_attribution<E>(
        &self,
        query: &Query<E>,
    ) -> Result<(LoadQueryResult<E>, QueryExecutionAttribution), QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: measure compile work at the typed/fluent boundary,
        // including the shared lower query-plan cache lookup/build exactly
        // once. This preserves honest hit/miss attribution without
        // double-building plans on one-shot cache misses.
        let (plan_lookup_local_instructions, plan_and_cache) =
            measure_query_stage(|| self.cached_prepared_query_plan_for_entity::<E>(query));
        let (plan, cache_attribution) = plan_and_cache?;
        let compile_local_instructions = plan_lookup_local_instructions;

        // Phase 2: execute one query result using the prepared plan produced
        // by the compile/cache boundary above.
        let result =
            || -> Result<(LoadQueryResult<E>, QueryExecutePhaseAttribution, u64), QueryError> {
                if query.has_grouping() {
                    let (executor_invocation_local_instructions, grouped_page) =
                        measure_query_stage(|| {
                            self.execute_grouped_plan_with(plan, None, |executor, plan, cursor| {
                                executor
                                    .execute_grouped_paged_with_cursor_traced_with_phase_attribution(
                                        plan, cursor,
                                    )
                            })
                        });
                    let (page, trace, phase_attribution) = grouped_page?;
                    let (response_finalization_local_instructions, grouped) =
                        measure_query_stage(|| Self::finalize_grouped_execution_page(page, trace));
                    let grouped = grouped?;

                    Ok((
                        LoadQueryResult::Grouped(grouped),
                        Self::grouped_query_execute_phase_attribution(
                            phase_attribution,
                            executor_invocation_local_instructions,
                            response_finalization_local_instructions,
                        ),
                        0,
                    ))
                } else {
                    match query.mode() {
                        QueryMode::Load(_) => {
                            let (executor_invocation_local_instructions, executed) =
                                measure_query_stage(|| {
                                    self.load_executor::<E>()
                                        .execute_with_phase_attribution(plan)
                                        .map_err(QueryError::execute)
                                });
                            let (rows, phase_attribution, response_decode_local_instructions) =
                                executed?;

                            Ok((
                                LoadQueryResult::Rows(rows),
                                Self::scalar_query_execute_phase_attribution(
                                    phase_attribution,
                                    executor_invocation_local_instructions,
                                ),
                                response_decode_local_instructions,
                            ))
                        }
                        QueryMode::Delete(_) => {
                            let (executor_invocation_local_instructions, result) =
                                measure_query_stage(|| self.execute_query_dyn(query.mode(), plan));
                            let result = result?;

                            Ok((
                                LoadQueryResult::Rows(result),
                                QueryExecutePhaseAttribution {
                                    executor_invocation_local_instructions,
                                    ..Self::empty_query_execute_phase_attribution()
                                },
                                0,
                            ))
                        }
                    }
                }
            }();
        let (result, execute_phase_attribution, response_decode_local_instructions) = result?;
        let execute_local_instructions = execute_phase_attribution
            .executor_invocation_local_instructions
            .saturating_add(execute_phase_attribution.response_finalization_local_instructions);
        let total_local_instructions =
            compile_local_instructions.saturating_add(execute_local_instructions);

        Ok((
            result,
            QueryExecutionAttribution {
                compile_local_instructions,
                plan_lookup_local_instructions,
                executor_invocation_local_instructions: execute_phase_attribution
                    .executor_invocation_local_instructions,
                response_finalization_local_instructions: execute_phase_attribution
                    .response_finalization_local_instructions,
                runtime_local_instructions: execute_phase_attribution.runtime_local_instructions,
                finalize_local_instructions: execute_phase_attribution.finalize_local_instructions,
                direct_data_row_scan_local_instructions: execute_phase_attribution
                    .direct_data_row_scan_local_instructions,
                direct_data_row_key_stream_local_instructions: execute_phase_attribution
                    .direct_data_row_key_stream_local_instructions,
                direct_data_row_row_read_local_instructions: execute_phase_attribution
                    .direct_data_row_row_read_local_instructions,
                direct_data_row_key_encode_local_instructions: execute_phase_attribution
                    .direct_data_row_key_encode_local_instructions,
                direct_data_row_store_get_local_instructions: execute_phase_attribution
                    .direct_data_row_store_get_local_instructions,
                direct_data_row_order_window_local_instructions: execute_phase_attribution
                    .direct_data_row_order_window_local_instructions,
                direct_data_row_page_window_local_instructions: execute_phase_attribution
                    .direct_data_row_page_window_local_instructions,
                grouped_stream_local_instructions: execute_phase_attribution
                    .grouped_stream_local_instructions,
                grouped_fold_local_instructions: execute_phase_attribution
                    .grouped_fold_local_instructions,
                grouped_finalize_local_instructions: execute_phase_attribution
                    .grouped_finalize_local_instructions,
                grouped_count_borrowed_hash_computations: execute_phase_attribution
                    .grouped_count
                    .borrowed_hash_computations,
                grouped_count_bucket_candidate_checks: execute_phase_attribution
                    .grouped_count
                    .bucket_candidate_checks,
                grouped_count_existing_group_hits: execute_phase_attribution
                    .grouped_count
                    .existing_group_hits,
                grouped_count_new_group_inserts: execute_phase_attribution
                    .grouped_count
                    .new_group_inserts,
                grouped_count_row_materialization_local_instructions: execute_phase_attribution
                    .grouped_count
                    .row_materialization_local_instructions,
                grouped_count_group_lookup_local_instructions: execute_phase_attribution
                    .grouped_count
                    .group_lookup_local_instructions,
                grouped_count_existing_group_update_local_instructions: execute_phase_attribution
                    .grouped_count
                    .existing_group_update_local_instructions,
                grouped_count_new_group_insert_local_instructions: execute_phase_attribution
                    .grouped_count
                    .new_group_insert_local_instructions,
                response_decode_local_instructions,
                execute_local_instructions,
                total_local_instructions,
                shared_query_plan_cache_hits: cache_attribution.hits,
                shared_query_plan_cache_misses: cache_attribution.misses,
                ..QueryExecutionAttribution::default()
            },
        ))
    }

    // Execute one typed query through the unified row/grouped result surface so
    // higher layers do not need to branch on grouped shape themselves.
    #[doc(hidden)]
    pub fn execute_query_result<E>(
        &self,
        query: &Query<E>,
    ) -> Result<LoadQueryResult<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        if query.has_grouping() {
            return self
                .execute_grouped(query, None)
                .map(LoadQueryResult::Grouped);
        }

        self.execute_query(query).map(LoadQueryResult::Rows)
    }

    /// Execute one typed delete query and return only the affected-row count.
    #[doc(hidden)]
    pub fn execute_delete_count<E>(&self, query: &Query<E>) -> Result<u32, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: fail closed if the caller routes a non-delete query here.
        if !query.mode().is_delete() {
            return Err(QueryError::unsupported_query(
                "delete count execution requires delete query mode",
            ));
        }

        // Phase 2: resolve one cached prepared execution-plan contract directly
        // from the shared lower boundary instead of rebuilding it through the
        // typed compiled-query wrapper.
        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;

        // Phase 3: execute the shared delete core while skipping response-row materialization.
        self.with_metrics(|| self.delete_executor::<E>().execute_count(plan))
            .map_err(QueryError::execute)
    }

    /// Execute one scalar query from one pre-built prepared execution contract.
    ///
    /// This is the shared compiled-plan entry boundary used by the typed
    /// `execute_query(...)` surface and adjacent query execution facades.
    pub(in crate::db) fn execute_query_dyn<E>(
        &self,
        mode: QueryMode,
        plan: PreparedExecutionPlan<E>,
    ) -> Result<EntityResponse<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let result = match mode {
            QueryMode::Load(_) => self.with_metrics(|| self.load_executor::<E>().execute(plan)),
            QueryMode::Delete(_) => self.with_metrics(|| self.delete_executor::<E>().execute(plan)),
        };

        result.map_err(QueryError::execute)
    }

    // Shared load-query terminal wrapper: build plan, run under metrics, map
    // execution errors into query-facing errors.
    pub(in crate::db) fn execute_load_query_with<E, T>(
        &self,
        query: &Query<E>,
        op: impl FnOnce(LoadExecutor<E>, PreparedExecutionPlan<E>) -> Result<T, InternalError>,
    ) -> Result<T, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;

        self.with_metrics(|| op(self.load_executor::<E>(), plan))
            .map_err(QueryError::execute)
    }

    // Execute one scalar terminal boundary and keep the executor-specific
    // request/output types contained inside the session adapter.
    fn execute_scalar_terminal_boundary<E>(
        &self,
        query: &Query<E>,
        request: ScalarTerminalBoundaryRequest,
    ) -> Result<ScalarTerminalBoundaryOutput, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            load.execute_scalar_terminal_request(plan, request)
        })
    }

    // Execute one projection terminal boundary and keep field projection
    // executor details out of fluent query modules.
    fn execute_scalar_projection_boundary<E>(
        &self,
        query: &Query<E>,
        target_field: FieldSlot,
        request: ScalarProjectionBoundaryRequest,
    ) -> Result<ScalarProjectionBoundaryOutput, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            load.execute_scalar_projection_boundary(plan, target_field, request)
        })
    }

    // Execute one fluent count/exists terminal through a query-owned result
    // shape so fluent terminals do not import executor aggregate outputs.
    pub(in crate::db) fn execute_fluent_existing_rows_terminal<E>(
        &self,
        query: &Query<E>,
        strategy: PreparedFluentExistingRowsTerminalStrategy,
    ) -> Result<FluentScalarTerminalOutput<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        match strategy.into_runtime_request() {
            PreparedFluentExistingRowsTerminalRuntimeRequest::CountRows => self
                .execute_scalar_terminal_boundary(query, ScalarTerminalBoundaryRequest::Count)?
                .into_count()
                .map(FluentScalarTerminalOutput::Count)
                .map_err(QueryError::execute),
            PreparedFluentExistingRowsTerminalRuntimeRequest::ExistsRows => self
                .execute_scalar_terminal_boundary(query, ScalarTerminalBoundaryRequest::Exists)?
                .into_exists()
                .map(FluentScalarTerminalOutput::Exists)
                .map_err(QueryError::execute),
        }
    }

    // Execute one fluent id/extrema terminal through a query-owned result
    // shape after the session adapter has decoded storage keys into typed ids.
    pub(in crate::db) fn execute_fluent_scalar_terminal<E>(
        &self,
        query: &Query<E>,
        strategy: PreparedFluentScalarTerminalStrategy,
    ) -> Result<FluentScalarTerminalOutput<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let request = match strategy.into_runtime_request() {
            PreparedFluentScalarTerminalRuntimeRequest::IdTerminal { kind } => {
                ScalarTerminalBoundaryRequest::IdTerminal { kind }
            }
            PreparedFluentScalarTerminalRuntimeRequest::IdBySlot { kind, target_field } => {
                ScalarTerminalBoundaryRequest::IdBySlot { kind, target_field }
            }
        };

        self.execute_scalar_terminal_boundary(query, request)?
            .into_id::<E>()
            .map(FluentScalarTerminalOutput::Id)
            .map_err(QueryError::execute)
    }

    // Execute one fluent order-sensitive terminal through the session adapter.
    // The min/max pair request remains distinguished because it returns two ids.
    pub(in crate::db) fn execute_fluent_order_sensitive_terminal<E>(
        &self,
        query: &Query<E>,
        strategy: PreparedFluentOrderSensitiveTerminalStrategy,
    ) -> Result<FluentScalarTerminalOutput<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        match strategy.into_runtime_request() {
            PreparedFluentOrderSensitiveTerminalRuntimeRequest::ResponseOrder { kind } => self
                .execute_scalar_terminal_boundary(
                    query,
                    ScalarTerminalBoundaryRequest::IdTerminal { kind },
                )?
                .into_id::<E>()
                .map(FluentScalarTerminalOutput::Id)
                .map_err(QueryError::execute),
            PreparedFluentOrderSensitiveTerminalRuntimeRequest::NthBySlot { target_field, nth } => {
                self.execute_scalar_terminal_boundary(
                    query,
                    ScalarTerminalBoundaryRequest::NthBySlot { target_field, nth },
                )?
                .into_id::<E>()
                .map(FluentScalarTerminalOutput::Id)
                .map_err(QueryError::execute)
            }
            PreparedFluentOrderSensitiveTerminalRuntimeRequest::MedianBySlot { target_field } => {
                self.execute_scalar_terminal_boundary(
                    query,
                    ScalarTerminalBoundaryRequest::MedianBySlot { target_field },
                )?
                .into_id::<E>()
                .map(FluentScalarTerminalOutput::Id)
                .map_err(QueryError::execute)
            }
            PreparedFluentOrderSensitiveTerminalRuntimeRequest::MinMaxBySlot { target_field } => {
                self.execute_scalar_terminal_boundary(
                    query,
                    ScalarTerminalBoundaryRequest::MinMaxBySlot { target_field },
                )?
                .into_id_pair::<E>()
                .map(FluentScalarTerminalOutput::IdPair)
                .map_err(QueryError::execute)
            }
        }
    }

    // Execute one fluent numeric-field terminal through the session-owned
    // request conversion layer.
    pub(in crate::db) fn execute_fluent_numeric_field_terminal<E>(
        &self,
        query: &Query<E>,
        strategy: PreparedFluentNumericFieldStrategy,
    ) -> Result<Option<Decimal>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let (target_field, runtime_request) = strategy.into_runtime_parts();
        let request = match runtime_request {
            PreparedFluentNumericFieldRuntimeRequest::Sum => ScalarNumericFieldBoundaryRequest::Sum,
            PreparedFluentNumericFieldRuntimeRequest::SumDistinct => {
                ScalarNumericFieldBoundaryRequest::SumDistinct
            }
            PreparedFluentNumericFieldRuntimeRequest::Avg => ScalarNumericFieldBoundaryRequest::Avg,
            PreparedFluentNumericFieldRuntimeRequest::AvgDistinct => {
                ScalarNumericFieldBoundaryRequest::AvgDistinct
            }
        };

        self.execute_load_query_with(query, move |load, plan| {
            load.execute_numeric_field_boundary(plan, target_field, request)
        })
    }

    // Execute one fluent projection terminal through a query-owned output
    // shape after the session adapter has decoded any data keys into typed ids.
    pub(in crate::db) fn execute_fluent_projection_terminal<E>(
        &self,
        query: &Query<E>,
        strategy: PreparedFluentProjectionStrategy,
    ) -> Result<FluentProjectionTerminalOutput<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        let (target_field, runtime_request) = strategy.into_runtime_parts();

        match runtime_request {
            PreparedFluentProjectionRuntimeRequest::Values => self
                .execute_scalar_projection_boundary(
                    query,
                    target_field,
                    ScalarProjectionBoundaryRequest::Values,
                )?
                .into_values()
                .map(FluentProjectionTerminalOutput::Values)
                .map_err(QueryError::execute),
            PreparedFluentProjectionRuntimeRequest::DistinctValues => self
                .execute_scalar_projection_boundary(
                    query,
                    target_field,
                    ScalarProjectionBoundaryRequest::DistinctValues,
                )?
                .into_values()
                .map(FluentProjectionTerminalOutput::Values)
                .map_err(QueryError::execute),
            PreparedFluentProjectionRuntimeRequest::CountDistinct => self
                .execute_scalar_projection_boundary(
                    query,
                    target_field,
                    ScalarProjectionBoundaryRequest::CountDistinct,
                )?
                .into_count()
                .map(FluentProjectionTerminalOutput::Count)
                .map_err(QueryError::execute),
            PreparedFluentProjectionRuntimeRequest::ValuesWithIds => self
                .execute_scalar_projection_boundary(
                    query,
                    target_field,
                    ScalarProjectionBoundaryRequest::ValuesWithIds,
                )?
                .into_values_with_ids::<E>()
                .map(FluentProjectionTerminalOutput::ValuesWithIds)
                .map_err(QueryError::execute),
            PreparedFluentProjectionRuntimeRequest::TerminalValue { terminal_kind } => self
                .execute_scalar_projection_boundary(
                    query,
                    target_field,
                    ScalarProjectionBoundaryRequest::TerminalValue { terminal_kind },
                )?
                .into_terminal_value()
                .map(FluentProjectionTerminalOutput::TerminalValue)
                .map_err(QueryError::execute),
        }
    }

    // Execute the fluent `bytes()` terminal without leaking `LoadExecutor`
    // closure assembly into query fluent code.
    pub(in crate::db) fn execute_fluent_bytes<E>(&self, query: &Query<E>) -> Result<u64, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, |load, plan| load.bytes(plan))
    }

    // Execute the fluent `bytes_by(field)` terminal at the session boundary.
    pub(in crate::db) fn execute_fluent_bytes_by_slot<E>(
        &self,
        query: &Query<E>,
        target_slot: FieldSlot,
    ) -> Result<u64, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            load.bytes_by_slot(plan, target_slot)
        })
    }

    // Execute the fluent `take(k)` terminal at the session boundary.
    pub(in crate::db) fn execute_fluent_take<E>(
        &self,
        query: &Query<E>,
        take_count: u32,
    ) -> Result<EntityResponse<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| load.take(plan, take_count))
    }

    // Execute one row-returning fluent top/bottom-k terminal at the session boundary.
    pub(in crate::db) fn execute_fluent_ranked_rows_by_slot<E>(
        &self,
        query: &Query<E>,
        target_slot: FieldSlot,
        take_count: u32,
        descending: bool,
    ) -> Result<EntityResponse<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            if descending {
                load.top_k_by_slot(plan, target_slot, take_count)
            } else {
                load.bottom_k_by_slot(plan, target_slot, take_count)
            }
        })
    }

    // Execute one value-returning fluent top/bottom-k terminal at the session boundary.
    pub(in crate::db) fn execute_fluent_ranked_values_by_slot<E>(
        &self,
        query: &Query<E>,
        target_slot: FieldSlot,
        take_count: u32,
        descending: bool,
    ) -> Result<Vec<Value>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            if descending {
                load.top_k_by_values_slot(plan, target_slot, take_count)
            } else {
                load.bottom_k_by_values_slot(plan, target_slot, take_count)
            }
        })
    }

    // Execute one id/value-returning fluent top/bottom-k terminal at the session boundary.
    pub(in crate::db) fn execute_fluent_ranked_values_with_ids_by_slot<E>(
        &self,
        query: &Query<E>,
        target_slot: FieldSlot,
        take_count: u32,
        descending: bool,
    ) -> Result<Vec<(Id<E>, Value)>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_load_query_with(query, move |load, plan| {
            if descending {
                load.top_k_by_with_ids_slot(plan, target_slot, take_count)
            } else {
                load.bottom_k_by_with_ids_slot(plan, target_slot, take_count)
            }
        })
    }

    /// Build one trace payload for a query without executing it.
    ///
    /// This lightweight surface is intended for developer diagnostics:
    /// plan hash, access strategy summary, and planner/executor route shape.
    pub fn trace_query<E>(&self, query: &Query<E>) -> Result<QueryTracePlan, QueryError>
    where
        E: EntityKind<Canister = C>,
    {
        let visibility = self.query_plan_visibility_for_store_path(E::Store::PATH)?;
        let visible_indexes = Self::visible_indexes_for_model(E::MODEL, visibility);
        let (prepared_plan, cache_attribution) =
            self.cached_prepared_query_plan_for_entity::<E>(query)?;
        let logical_plan = prepared_plan.logical_plan();
        let explain = logical_plan.explain();
        let plan_hash = query.plan_hash_hex_with_visible_indexes(&visible_indexes)?;
        let executable_access = prepared_plan.access().executable_contract();
        let access_strategy = summarize_executable_access_plan(&executable_access);
        let execution_family = match query.mode() {
            QueryMode::Load(_) => Some(trace_execution_family_from_executor(
                prepared_plan
                    .execution_family()
                    .map_err(QueryError::execute)?,
            )),
            QueryMode::Delete(_) => None,
        };
        let reuse = query_plan_cache_reuse_event(cache_attribution);

        Ok(QueryTracePlan::new(
            plan_hash,
            access_strategy,
            execution_family,
            reuse,
            explain,
        ))
    }

    /// Execute one scalar paged load query and return optional continuation cursor plus trace.
    pub(crate) fn execute_load_query_paged_with_trace<E>(
        &self,
        query: &Query<E>,
        cursor_token: Option<&str>,
    ) -> Result<PagedLoadExecutionWithTrace<E>, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: build/validate prepared execution plan and reject grouped plans.
        let plan = self.cached_prepared_query_plan_for_entity::<E>(query)?.0;
        Self::ensure_scalar_paged_execution_family(
            plan.execution_family().map_err(QueryError::execute)?,
        )?;

        // Phase 2: decode external cursor token and validate it against plan surface.
        let cursor_bytes = decode_optional_cursor_token(cursor_token)
            .map_err(QueryError::from_cursor_plan_error)?;
        let cursor = plan
            .prepare_cursor(cursor_bytes.as_deref())
            .map_err(query_error_from_executor_plan_error)?;

        // Phase 3: execute one traced page and encode outbound continuation token.
        let (page, trace) = self
            .with_metrics(|| {
                self.load_executor::<E>()
                    .execute_paged_with_cursor_traced(plan, cursor)
            })
            .map_err(QueryError::execute)?;
        finalize_scalar_paged_execution(page, trace)
    }

    /// Execute one grouped query page with optional grouped continuation cursor.
    ///
    /// This is the explicit grouped execution boundary; scalar load APIs reject
    /// grouped plans to preserve scalar response contracts.
    pub(in crate::db) fn execute_grouped<E>(
        &self,
        query: &Query<E>,
        cursor_token: Option<&str>,
    ) -> Result<PagedGroupedExecutionWithTrace, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: build the prepared execution plan once from the typed query.
        let plan = self.cached_prepared_query_plan_for_entity::<E>(query)?.0;

        // Phase 2: reuse the shared prepared grouped execution path and then
        // finalize the outward grouped payload at the session boundary.
        let (page, trace) = self.execute_grouped_plan_with_trace(plan, cursor_token)?;

        Self::finalize_grouped_execution_page(page, trace)
    }

    // Execute one grouped prepared plan page with optional grouped cursor
    // while letting the caller choose the final grouped-runtime dispatch.
    fn execute_grouped_plan_with<E, T>(
        &self,
        plan: PreparedExecutionPlan<E>,
        cursor_token: Option<&str>,
        op: impl FnOnce(
            LoadExecutor<E>,
            PreparedExecutionPlan<E>,
            crate::db::cursor::GroupedPlannedCursor,
        ) -> Result<T, InternalError>,
    ) -> Result<T, QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        // Phase 1: validate the prepared plan shape before decoding cursors.
        Self::ensure_grouped_execution_family(
            plan.execution_family().map_err(QueryError::execute)?,
        )?;

        // Phase 2: decode external grouped cursor token and validate against plan.
        let cursor = decode_optional_grouped_cursor_token(cursor_token)
            .map_err(QueryError::from_cursor_plan_error)?;
        let cursor = plan
            .prepare_grouped_cursor_token(cursor)
            .map_err(query_error_from_executor_plan_error)?;

        // Phase 3: execute one grouped page while preserving the structural
        // grouped cursor payload for whichever outward cursor format the caller needs.
        self.with_metrics(|| op(self.load_executor::<E>(), plan, cursor))
            .map_err(QueryError::execute)
    }

    // Execute one grouped prepared plan page with optional grouped cursor.
    fn execute_grouped_plan_with_trace<E>(
        &self,
        plan: PreparedExecutionPlan<E>,
        cursor_token: Option<&str>,
    ) -> Result<(GroupedCursorPage, Option<ExecutionTrace>), QueryError>
    where
        E: PersistedRow<Canister = C> + EntityValue,
    {
        self.execute_grouped_plan_with(plan, cursor_token, |executor, plan, cursor| {
            executor.execute_grouped_paged_with_cursor_traced(plan, cursor)
        })
    }
}