Skip to main content

icydb_core/db/session/query/
dynamic.rs

1//! Module: db::session::query::dynamic
2//! Responsibility: lower and execute public dynamic reads against accepted schema.
3//! Does not own: query planning, accepted schema construction, or row projection.
4//! Boundary: entity-name requests converge on the shared structural read lane.
5
6use crate::{
7    db::{
8        DbSession, DynamicQuery, DynamicTypedEntityBinding, ExhaustiveQueryPageOutput,
9        ExhaustiveReadError, GroupedQueryOutput, LiveQueryPageOutput, MissingRowPolicy, QueryError,
10        ReadSetRevisionError, ReadSetRevisionProof, ScalarPageWork,
11        codec::{finalize_hash_sha256, new_hash_sha256_prefixed},
12        commit::{cursor_authentication_key, database_incarnation_id},
13        cursor::{
14            CursorBoundary, CursorBoundarySlot, CursorPlanError, ScalarOrderTermContract,
15            ScalarPageMode, ScalarPageToken, ScalarPageTokenAuthority, ScalarPageTokenProgress,
16            ScalarPageTokenWindow, decode_optional_cursor_token, encode_cursor,
17        },
18        data::{DecodedDataStoreKey, RawDataStoreKey},
19        executor::{
20            PageWorkEnvelope, ScalarContinuationContext, StructuralProjectionRequest,
21            execute_structural_projection_page,
22        },
23        query::{
24            admission::{
25                QueryAdmissionPolicy, QueryAdmissionSummary, input::validate_dynamic_query_input,
26            },
27            expr::{CompareOperator, FilterExpr, SetOperator},
28            intent::{IntentError, StructuralQuery},
29            plan::{
30                CardinalityTiebreakRoutePin, GroupAggregateSpec, OrderDirection, OrderSpec,
31                OrderTerm,
32                expr::{FieldId, ProjectionSelection},
33            },
34            preparation::PreparationWork,
35        },
36        session::AcceptedSchemaCatalogContext,
37    },
38    traits::CanisterKind,
39};
40use icydb_diagnostic_code::{
41    DiagnosticDecodeReason, DiagnosticExecutionBudgetResource, DiagnosticExecutionLane,
42    QueryReadAdmissionCode,
43};
44use sha2::Digest;
45#[cfg(test)]
46use std::cell::Cell;
47
48#[cfg(not(test))]
49const SCALAR_PAGE_OUTPUT_ROWS: usize = 1_024;
50#[cfg(test)]
51const SCALAR_PAGE_OUTPUT_ROWS: usize = 2;
52#[cfg(test)]
53const SCALAR_PAGE_KEY_ENTRIES: u64 = 4;
54
55#[cfg(test)]
56std::thread_local! {
57    static SCALAR_PAGE_RESULT_BYTES_LIMIT_OVERRIDE: Cell<Option<u64>> = const { Cell::new(None) };
58}
59
60#[cfg(test)]
61struct ScalarPageResultBytesLimitGuard(Option<u64>);
62
63#[cfg(test)]
64impl Drop for ScalarPageResultBytesLimitGuard {
65    fn drop(&mut self) {
66        SCALAR_PAGE_RESULT_BYTES_LIMIT_OVERRIDE.with(|limit| limit.set(self.0));
67    }
68}
69
70#[derive(Clone, Copy)]
71enum DynamicReadLane {
72    Public,
73    Trusted,
74}
75
76impl DynamicReadLane {
77    const fn execution_lane(self) -> DiagnosticExecutionLane {
78        match self {
79            Self::Public => DiagnosticExecutionLane::PublicRead,
80            Self::Trusted => DiagnosticExecutionLane::TrustedRead,
81        }
82    }
83}
84
85struct ScalarCursorContract {
86    signature: crate::db::cursor::ContinuationSignature,
87    authority: ScalarPageTokenAuthority,
88    route_pin: Option<CardinalityTiebreakRoutePin>,
89    window: ScalarPageTokenWindow,
90    order_terms: Vec<ScalarOrderTermContract>,
91}
92
93impl<C: CanisterKind> DbSession<C> {
94    fn may_select_exact_single_primary_key(
95        request: &DynamicQuery,
96        catalog: &AcceptedSchemaCatalogContext,
97    ) -> bool {
98        let [primary_key] = catalog.accepted_schema_info().primary_key_names() else {
99            return false;
100        };
101        // This is only a cheap candidate check, not normalization. Multi-value
102        // lists (including duplicates) use the ordinary paged preparation once.
103        let field = match request.filter_expr() {
104            Some(FilterExpr::Compare {
105                operator: CompareOperator::Eq,
106                field,
107                ..
108            }) => field,
109            Some(FilterExpr::Set {
110                operator: SetOperator::In,
111                field,
112                values,
113            }) if values.len() == 1 => field,
114            _ => return false,
115        };
116        field.eq_ignore_ascii_case(primary_key)
117    }
118
119    fn exact_primary_key_candidate_bound(
120        prepared_plan: &crate::db::executor::SharedPreparedExecutionPlan,
121    ) -> Option<usize> {
122        let access = &prepared_plan.logical_plan().access;
123        if access.as_by_key_path().is_some() {
124            return Some(1);
125        }
126
127        access.as_by_keys_path().map(<[crate::value::Value]>::len)
128    }
129
130    pub(super) fn structural_query_from_dynamic_request(
131        &self,
132        request: &DynamicQuery,
133        catalog: &AcceptedSchemaCatalogContext,
134        lane: DiagnosticExecutionLane,
135    ) -> Result<StructuralQuery, QueryError> {
136        self.structural_query_from_dynamic_request_with_page_limit(
137            request, catalog, None, false, lane,
138        )
139    }
140
141    fn structural_query_from_dynamic_request_with_page_limit(
142        &self,
143        request: &DynamicQuery,
144        catalog: &AcceptedSchemaCatalogContext,
145        page_limit: Option<u32>,
146        require_total_order: bool,
147        lane: DiagnosticExecutionLane,
148    ) -> Result<StructuralQuery, QueryError> {
149        validate_dynamic_query_input(request)?;
150        Self::validate_dynamic_query_shape(request)?;
151        PreparationWork::run(self.db.request_execution_scope(), lane, |work| {
152            let schema = catalog.accepted_schema_info();
153            let mut query = StructuralQuery::new(MissingRowPolicy::Ignore);
154            if let Some(filter) = request.filter_expr() {
155                query = query.filter_for_schema(schema, filter, work)?;
156            }
157            // Materialize each known-length clause once, then move it into
158            // intent. An absent order remains absent unless paging needs one.
159            let order_fields = if !request.order_terms().is_empty() {
160                work.copy_slice(request.order_terms(), |order| {
161                    Ok(order.copy_for_preparation(work)?.lower())
162                })?
163            } else if require_total_order {
164                work.copy_slice(schema.primary_key_names(), |field| {
165                    Ok(OrderTerm::field(
166                        work.copy_text(field)?,
167                        OrderDirection::Asc,
168                    ))
169                })?
170            } else {
171                Vec::new()
172            };
173            if !order_fields.is_empty() {
174                query = query.order_spec(OrderSpec {
175                    fields: order_fields,
176                });
177            }
178            if !request.selected_fields().is_empty() {
179                query = query.projection_selection(ProjectionSelection::Fields(
180                    work.copy_slice(request.selected_fields(), |field| {
181                        Ok(FieldId::new(work.copy_text(field)?))
182                    })?,
183                ));
184            }
185            #[cfg(test)]
186            if request.projection_is_distinct() {
187                query = query.distinct();
188            }
189            if let Some(limit) = page_limit.or_else(|| request.row_limit()) {
190                query = query.limit(limit);
191            }
192            if !request.group_fields().is_empty() {
193                query = query.group_fields_with_schema(request.group_fields(), schema, work)?;
194            }
195            if !request.aggregates().is_empty() {
196                query =
197                    query.group_aggregates(work.copy_slice(request.aggregates(), |aggregate| {
198                        Ok(GroupAggregateSpec::from_aggregate_expr(
199                            aggregate
200                                .copy_for_preparation(work)
201                                .map_err(QueryError::execute)?,
202                        ))
203                    })?);
204            }
205            if let Some((max_groups, max_group_bytes)) = request.grouped_execution_limits() {
206                if max_groups == 0 || max_group_bytes == 0 {
207                    return Err(QueryReadAdmissionCode::GroupedQueryRequiresLimits.into());
208                }
209                query = query.grouped_limits(u64::from(max_groups), u64::from(max_group_bytes));
210            }
211
212            Ok(query)
213        })
214    }
215
216    // Dynamic execution and typed diagnostics accept the same grouped shape.
217    // Execution-only scan/sort policy remains at the execution terminal.
218    fn validate_dynamic_query_shape(request: &DynamicQuery) -> Result<(), QueryError> {
219        if request.has_grouping() {
220            if request.grouped_execution_limits().is_none() {
221                return Err(QueryReadAdmissionCode::GroupedQueryRequiresLimits.into());
222            }
223            if !request.selected_fields().is_empty() {
224                return Err(QueryError::intent(
225                    IntentError::grouped_output_defined_by_group_and_aggregates(),
226                ));
227            }
228        } else if request.grouped_execution_limits().is_some() {
229            return Err(QueryError::intent(
230                IntentError::scalar_terminal_requires_scalar_query(),
231            ));
232        }
233        Ok(())
234    }
235
236    /// Project a logical query under the binding's current accepted authority.
237    /// `None` means the binding is stale. No row execution or cursor decoding occurs.
238    #[doc(hidden)]
239    pub fn explain_query_for_typed_binding(
240        &self,
241        binding: &DynamicTypedEntityBinding,
242        request: &DynamicQuery,
243    ) -> Result<Option<crate::db::ExplainPlan>, QueryError> {
244        let Some(catalog) = self
245            .current_typed_entity_binding_catalog(binding)
246            .map_err(QueryError::execute)?
247        else {
248            return Ok(None);
249        };
250        if request.continuation_cursor().is_some() {
251            return Err(QueryReadAdmissionCode::ExplainDoesNotAcceptCursor.into());
252        }
253        let lane = DiagnosticExecutionLane::Diagnostic;
254        let query = self.structural_query_from_dynamic_request(request, &catalog, lane)?;
255        let plan = self.cached_shared_query_plan_for_accepted_authority_with_catalog(
256            catalog.accepted_entity_authority(),
257            &catalog,
258            &query,
259            lane,
260        )?;
261        PreparationWork::run(self.db.request_execution_scope(), lane, |work| {
262            plan.explain(work).map(Some)
263        })
264    }
265
266    fn scalar_page_cursor_error() -> QueryError {
267        QueryError::from_cursor_plan_error(CursorPlanError::invalid_continuation_cursor_payload(
268            DiagnosticDecodeReason::CursorTokenDecode,
269        ))
270    }
271
272    fn scalar_cursor_contract(
273        request: &DynamicQuery,
274        catalog: &AcceptedSchemaCatalogContext,
275        envelope: PageWorkEnvelope,
276        prepared_plan: &crate::db::executor::SharedPreparedExecutionPlan,
277        mode: ScalarPageMode,
278        proof: Option<&ReadSetRevisionProof>,
279    ) -> Result<ScalarCursorContract, QueryError> {
280        let mut signature = prepared_plan
281            .continuation_signature_for_runtime()
282            .map_err(QueryError::execute)?;
283        match (mode, proof) {
284            (ScalarPageMode::Live, None) => {}
285            (ScalarPageMode::Exhaustive, Some(proof)) => {
286                let mut hasher = new_hash_sha256_prefixed(b"icydb.exhaustive-cursor-proof.v1");
287                hasher.update(signature.into_bytes());
288                hasher.update(proof.signature_bytes());
289                signature = crate::db::cursor::ContinuationSignature::from_bytes(
290                    finalize_hash_sha256(hasher),
291                );
292            }
293            _ => return Err(Self::scalar_page_cursor_error()),
294        }
295        let root_identity = catalog.runtime_root_identity();
296        let (root_fingerprint_method, root_fingerprint) = root_identity.fingerprint();
297        let authority = ScalarPageTokenAuthority::new(
298            database_incarnation_id()
299                .map_err(QueryError::execute)?
300                .to_bytes(),
301            root_identity.accepted_root_revision().get(),
302            root_fingerprint_method,
303            root_fingerprint,
304            catalog.fingerprint(),
305            prepared_plan.authority_ref().entity_tag(),
306        );
307        let window =
308            ScalarPageTokenWindow::new(0, request.row_limit(), envelope.profile_identity());
309        let canonical_order = prepared_plan
310            .logical_plan()
311            .scalar_plan()
312            .order
313            .as_ref()
314            .ok_or_else(Self::scalar_page_cursor_error)?;
315        let order_terms = canonical_order
316            .fields
317            .iter()
318            .map(|term| ScalarOrderTermContract::new(term.rendered_label(), term.direction()))
319            .collect::<Vec<_>>();
320
321        Ok(ScalarCursorContract {
322            signature,
323            authority,
324            route_pin: prepared_plan
325                .logical_plan()
326                .cardinality_tiebreak_route_pin(),
327            window,
328            order_terms,
329        })
330    }
331
332    fn validate_scalar_page_token(
333        token: &ScalarPageToken,
334        mode: ScalarPageMode,
335        contract: &ScalarCursorContract,
336        entity: &str,
337    ) -> Result<(), QueryError> {
338        if token.signature() != contract.signature {
339            return Err(QueryError::from_cursor_plan_error(
340                CursorPlanError::continuation_cursor_signature_mismatch(
341                    entity,
342                    &contract.signature,
343                    &token.signature(),
344                ),
345            ));
346        }
347        if token.mode() != mode
348            || token.authority() != contract.authority
349            || token.route_pin() != contract.route_pin
350            || token.window() != contract.window
351            || token.order_terms() != contract.order_terms.as_slice()
352        {
353            return Err(Self::scalar_page_cursor_error());
354        }
355
356        Ok(())
357    }
358
359    fn physical_primary_key_boundary(
360        bytes: &[u8],
361        catalog: &AcceptedSchemaCatalogContext,
362    ) -> Result<CursorBoundary, QueryError> {
363        let raw = RawDataStoreKey::from_persisted_bytes(bytes.to_vec());
364        let key = DecodedDataStoreKey::try_from_raw(&raw)
365            .map_err(|_| Self::scalar_page_cursor_error())?;
366        if key.entity_tag() != catalog.accepted_entity_authority().entity_tag() {
367            return Err(Self::scalar_page_cursor_error());
368        }
369        let primary_key_arity = catalog.accepted_schema_info().primary_key_names().len();
370        let mut slots = Vec::with_capacity(primary_key_arity);
371        for component_index in 0..primary_key_arity {
372            slots.push(CursorBoundarySlot::Present(
373                key.primary_key_component_runtime_value(component_index)
374                    .map_err(|_| Self::scalar_page_cursor_error())?,
375            ));
376        }
377
378        Ok(CursorBoundary { slots })
379    }
380
381    fn execute_dynamic_grouped_query_against_catalog(
382        &self,
383        request: &DynamicQuery,
384        lane: DynamicReadLane,
385        catalog: AcceptedSchemaCatalogContext,
386    ) -> Result<GroupedQueryOutput, QueryError> {
387        if !request.has_grouping() {
388            return Err(QueryError::intent(
389                IntentError::grouped_terminal_requires_grouped_query(),
390            ));
391        }
392        let query =
393            self.structural_query_from_dynamic_request(request, &catalog, lane.execution_lane())?;
394        let public_admission = match lane {
395            DynamicReadLane::Public => Some(QueryAdmissionPolicy::default_bounded_read()),
396            DynamicReadLane::Trusted => None,
397        };
398
399        self.execute_structural_grouped_from_query(
400            &query,
401            &catalog,
402            public_admission.as_ref(),
403            request.continuation_cursor(),
404        )
405    }
406
407    #[expect(
408        clippy::too_many_lines,
409        reason = "live-page orchestration keeps planning, cursor validation, execution, and response proof in one auditable boundary"
410    )]
411    fn execute_scalar_page_against_catalog(
412        &self,
413        request: &DynamicQuery,
414        continuation: Option<&str>,
415        lane: DynamicReadLane,
416        catalog: AcceptedSchemaCatalogContext,
417        mode: ScalarPageMode,
418        supplied_proof: Option<&ReadSetRevisionProof>,
419    ) -> Result<(LiveQueryPageOutput, Option<ReadSetRevisionProof>), ExhaustiveReadError> {
420        if request.has_grouping()
421            || request.grouped_execution_limits().is_some()
422            || request.continuation_cursor().is_some()
423        {
424            return Err(
425                QueryError::intent(IntentError::scalar_terminal_requires_scalar_query()).into(),
426            );
427        }
428
429        let exhaustive_proof = match mode {
430            ScalarPageMode::Live => None,
431            ScalarPageMode::Exhaustive => {
432                if continuation.is_some() && supplied_proof.is_none() {
433                    return Err(ReadSetRevisionError::ResumeProofRequired.into());
434                }
435                let proof = supplied_proof.cloned().map_or_else(
436                    || self.capture_entity_read_set_revision_proof(catalog.identity().store_path()),
437                    Ok,
438                )?;
439                Self::ensure_read_set_contains_store(&proof, catalog.identity().store_path())?;
440                self.verify_read_set_revision_proof(&proof)?;
441                Some(proof)
442            }
443        };
444
445        let envelope = match lane {
446            DynamicReadLane::Public => PageWorkEnvelope::public_scalar(),
447            DynamicReadLane::Trusted => PageWorkEnvelope::default_scalar(),
448        };
449        #[cfg(test)]
450        let envelope = SCALAR_PAGE_RESULT_BYTES_LIMIT_OVERRIDE.with(|limit| {
451            limit.get().map_or(envelope, |limit| {
452                envelope.with_limit_for_tests(DiagnosticExecutionBudgetResource::ResultBytes, limit)
453            })
454        });
455        #[cfg(test)]
456        let envelope = envelope.with_limit_for_tests(
457            DiagnosticExecutionBudgetResource::KeyIndexEntriesVisited,
458            SCALAR_PAGE_KEY_ENTRIES,
459        );
460        let page_row_limit = envelope
461            .limit(DiagnosticExecutionBudgetResource::ResultRows)
462            .and_then(|limit| usize::try_from(limit).ok())
463            .unwrap_or(SCALAR_PAGE_OUTPUT_ROWS)
464            .min(SCALAR_PAGE_OUTPUT_ROWS);
465        let decoded_token = decode_optional_cursor_token(continuation)
466            .map_err(QueryError::from_cursor_plan_error)?
467            .map(|bytes| {
468                ScalarPageToken::decode(
469                    bytes.as_slice(),
470                    &cursor_authentication_key().map_err(QueryError::execute)?,
471                )
472                .map_err(|error| {
473                    QueryError::from_cursor_plan_error(CursorPlanError::from_token_wire_error(
474                        error,
475                    ))
476                })
477            })
478            .transpose()?;
479        let prior_rows_emitted = decoded_token
480            .as_ref()
481            .map_or(0, |token| token.progress().rows_emitted());
482        let remaining_limit = request
483            .row_limit()
484            .map(|limit| u64::from(limit).saturating_sub(prior_rows_emitted));
485        let page_output_limit = remaining_limit
486            .unwrap_or(page_row_limit as u64)
487            .min(page_row_limit as u64);
488        let page_output_limit = usize::try_from(page_output_limit).unwrap_or(page_row_limit);
489        let execution_limit = u32::try_from(page_row_limit).unwrap_or(u32::MAX);
490        let execution_lane = lane.execution_lane();
491        let exact_candidate = decoded_token.is_none()
492            && page_output_limit > 0
493            && Self::may_select_exact_single_primary_key(request, &catalog);
494        let initial_plan = if exact_candidate {
495            let query =
496                self.structural_query_from_dynamic_request(request, &catalog, execution_lane)?;
497            Some(
498                self.structural_projection_prepared_plan_for_accepted_authority(
499                    &query,
500                    catalog.accepted_entity_authority(),
501                    catalog.snapshot(),
502                    execution_lane,
503                )?,
504            )
505        } else {
506            None
507        };
508        let initial_is_exact_exhaustion =
509            initial_plan.as_ref().is_some_and(|(prepared_plan, _)| {
510                Self::exact_primary_key_candidate_bound(prepared_plan)
511                    .is_some_and(|bound| bound == 1 && bound <= page_output_limit)
512            });
513        let (prepared_plan, projection) = if initial_is_exact_exhaustion {
514            initial_plan.ok_or_else(Self::scalar_page_cursor_error)?
515        } else {
516            let query = self.structural_query_from_dynamic_request_with_page_limit(
517                request,
518                &catalog,
519                Some(execution_limit),
520                true,
521                execution_lane,
522            )?;
523            if let Some(route_pin) = decoded_token.as_ref().and_then(ScalarPageToken::route_pin) {
524                self.structural_projection_prepared_plan_for_accepted_authority_with_route_pin(
525                    &query,
526                    catalog.accepted_entity_authority(),
527                    execution_lane,
528                    route_pin,
529                )?
530                .ok_or_else(Self::scalar_page_cursor_error)?
531            } else {
532                self.structural_projection_prepared_plan_for_accepted_authority(
533                    &query,
534                    catalog.accepted_entity_authority(),
535                    catalog.snapshot(),
536                    execution_lane,
537                )?
538            }
539        };
540        if matches!(lane, DynamicReadLane::Public) {
541            let policy = QueryAdmissionPolicy::default_bounded_read();
542            let summary = policy.evaluate(
543                QueryAdmissionSummary::from_plan(policy.lane(), prepared_plan.logical_plan())
544                    .map_err(QueryError::execute)?,
545            );
546            if let Some(rejection) = summary.rejection() {
547                return Err(QueryError::from(rejection.code()).into());
548            }
549        }
550        let exact_initial_exhaustion = initial_is_exact_exhaustion;
551        let cursor_contract = decoded_token
552            .as_ref()
553            .map(|token| {
554                let contract = Self::scalar_cursor_contract(
555                    request,
556                    &catalog,
557                    envelope,
558                    &prepared_plan,
559                    mode,
560                    exhaustive_proof.as_ref(),
561                )?;
562                Self::validate_scalar_page_token(token, mode, &contract, request.entity())?;
563                Ok::<_, QueryError>(contract)
564            })
565            .transpose()?;
566        let deferred_cursor_plan =
567            (!exact_initial_exhaustion && decoded_token.is_none()).then(|| prepared_plan.clone());
568        let continuation_context = match decoded_token.as_ref() {
569            None => ScalarContinuationContext::initial(),
570            Some(token) if token.progress().unconsumed_lookahead().is_some() => {
571                return Err(Self::scalar_page_cursor_error().into());
572            }
573            Some(token) => {
574                let logical = token.progress().last_emitted_logical().cloned();
575                match token.progress().last_consumed_physical() {
576                    Some(physical) => ScalarContinuationContext::resumed_with_primary_progress(
577                        logical,
578                        Self::physical_primary_key_boundary(physical, &catalog)?,
579                    ),
580                    None => logical.map_or_else(
581                        ScalarContinuationContext::initial,
582                        ScalarContinuationContext::resumed,
583                    ),
584                }
585            }
586        };
587        if decoded_token.is_some() && !continuation_context.has_progress() {
588            return Err(Self::scalar_page_cursor_error().into());
589        }
590
591        let value_catalog = prepared_plan
592            .authority_ref()
593            .accepted_schema_info()
594            .value_catalog_handle()
595            .clone();
596        let (columns, _fixed_scales) = projection.into_components();
597        let projection_request = StructuralProjectionRequest::new(prepared_plan, execution_lane)
598            .with_distinct_output_offset(usize::try_from(prior_rows_emitted).unwrap_or(usize::MAX))
599            .with_page_work_envelope(envelope);
600        let projection_request = if exact_initial_exhaustion {
601            projection_request
602        } else {
603            projection_request
604                .with_continuation(continuation_context)
605                .with_cursor_emission(page_output_limit)
606        };
607        let page = execute_structural_projection_page(&self.db, projection_request)
608            .map_err(QueryError::execute)?;
609        let row_count = page.rows.row_count();
610        let rows = page
611            .rows
612            .into_value_rows()
613            .into_iter()
614            .map(|row| {
615                row.into_iter()
616                    .map(|value| {
617                        crate::db::schema::output_value_from_runtime(
618                            value_catalog.enum_catalog(),
619                            value,
620                        )
621                        .map_err(|_| QueryError::invariant())
622                    })
623                    .collect::<Result<Vec<_>, _>>()
624            })
625            .collect::<Result<Vec<_>, _>>()?;
626        let rows_emitted = prior_rows_emitted.saturating_add(u64::from(row_count));
627        let total_limit_reached = request
628            .row_limit()
629            .is_some_and(|limit| rows_emitted >= u64::from(limit));
630        let continuation = if page.has_more && !total_limit_reached {
631            if page.last_emitted_logical.is_none() && page.last_consumed_physical.is_none() {
632                return Err(Self::scalar_page_cursor_error().into());
633            }
634            let cursor_contract = if let Some(contract) = cursor_contract {
635                contract
636            } else {
637                let prepared_plan = deferred_cursor_plan
638                    .as_ref()
639                    .ok_or_else(Self::scalar_page_cursor_error)?;
640                Self::scalar_cursor_contract(
641                    request,
642                    &catalog,
643                    envelope,
644                    prepared_plan,
645                    mode,
646                    exhaustive_proof.as_ref(),
647                )?
648            };
649            let token = ScalarPageToken::new(
650                mode,
651                cursor_contract.signature,
652                cursor_contract.authority,
653                cursor_contract.route_pin,
654                cursor_contract.window,
655                cursor_contract.order_terms,
656                ScalarPageTokenProgress::new(
657                    page.last_emitted_logical,
658                    page.last_consumed_physical,
659                    None,
660                    decoded_token
661                        .as_ref()
662                        .map_or(0, |token| token.progress().matching_rows_skipped()),
663                    rows_emitted,
664                ),
665            );
666            Some(encode_cursor(
667                token
668                    .encode(&cursor_authentication_key().map_err(QueryError::execute)?)
669                    .map_err(|error| {
670                        QueryError::from_cursor_plan_error(CursorPlanError::from_token_wire_error(
671                            error,
672                        ))
673                    })?
674                    .as_slice(),
675            ))
676        } else {
677            None
678        };
679
680        if let Some(proof) = exhaustive_proof.as_ref() {
681            self.verify_read_set_revision_proof(proof)?;
682        }
683
684        Ok((
685            LiveQueryPageOutput {
686                entity: catalog.snapshot().entity_name().to_string(),
687                columns,
688                rows,
689                row_count,
690                continuation,
691                work: ScalarPageWork {
692                    envelope_identity: envelope.identity(),
693                    entries_visited: page.scanned_keys as u64,
694                    result_rows: row_count,
695                },
696            },
697            exhaustive_proof,
698        ))
699    }
700
701    /// Execute one revision-tolerant bounded scalar page.
702    pub fn execute_public_live_page(
703        &self,
704        request: &DynamicQuery,
705        continuation: Option<&str>,
706    ) -> Result<LiveQueryPageOutput, QueryError> {
707        let catalog = self
708            .accepted_schema_catalog_context_for_entity_name(Some(request.entity()))
709            .map_err(QueryError::execute)?;
710        self.execute_scalar_page_against_catalog(
711            request,
712            continuation,
713            DynamicReadLane::Public,
714            catalog,
715            ScalarPageMode::Live,
716            None,
717        )
718        .map(|(page, _)| page)
719        .map_err(Self::live_page_error)
720    }
721
722    /// Execute one live page through a typed binding's immutable accepted
723    /// entity identity. `None` means the opaque binding is stale.
724    #[doc(hidden)]
725    pub fn execute_public_live_page_for_typed_binding(
726        &self,
727        binding: &DynamicTypedEntityBinding,
728        request: &DynamicQuery,
729        continuation: Option<&str>,
730    ) -> Result<Option<LiveQueryPageOutput>, QueryError> {
731        let Some(catalog) = self
732            .current_typed_entity_binding_catalog(binding)
733            .map_err(QueryError::execute)?
734        else {
735            return Ok(None);
736        };
737        self.execute_scalar_page_against_catalog(
738            request,
739            continuation,
740            DynamicReadLane::Public,
741            catalog,
742            ScalarPageMode::Live,
743            None,
744        )
745        .map(|(page, _)| Some(page))
746        .map_err(Self::live_page_error)
747    }
748
749    /// Execute one ordinary entity-name-driven bounded grouped read.
750    pub fn execute_public_dynamic_grouped_query(
751        &self,
752        request: &DynamicQuery,
753    ) -> Result<GroupedQueryOutput, QueryError> {
754        let catalog = self
755            .accepted_schema_catalog_context_for_entity_name(Some(request.entity()))
756            .map_err(QueryError::execute)?;
757        self.execute_dynamic_grouped_query_against_catalog(
758            request,
759            DynamicReadLane::Public,
760            catalog,
761        )
762    }
763
764    /// Execute one grouped typed read through the binding's immutable accepted
765    /// entity identity. `None` means the opaque binding is stale.
766    #[doc(hidden)]
767    pub fn execute_public_dynamic_grouped_query_for_typed_binding(
768        &self,
769        binding: &DynamicTypedEntityBinding,
770        request: &DynamicQuery,
771    ) -> Result<Option<GroupedQueryOutput>, QueryError> {
772        let Some(catalog) = self
773            .current_typed_entity_binding_catalog(binding)
774            .map_err(QueryError::execute)?
775        else {
776            return Ok(None);
777        };
778        self.execute_dynamic_grouped_query_against_catalog(
779            request,
780            DynamicReadLane::Public,
781            catalog,
782        )
783        .map(Some)
784    }
785
786    /// Execute one trusted entity-name-driven grouped read.
787    ///
788    /// This bypasses ordinary public admission but retains accepted-schema
789    /// planning, explicit grouped limits, cursor validation, and execution.
790    pub fn execute_trusted_dynamic_grouped_query(
791        &self,
792        request: &DynamicQuery,
793    ) -> Result<GroupedQueryOutput, QueryError> {
794        let catalog = self
795            .accepted_schema_catalog_context_for_entity_name(Some(request.entity()))
796            .map_err(QueryError::execute)?;
797        self.execute_dynamic_grouped_query_against_catalog(
798            request,
799            DynamicReadLane::Trusted,
800            catalog,
801        )
802    }
803
804    /// Execute one trusted revision-tolerant bounded dynamic page.
805    ///
806    /// Trusted execution bypasses public admission but retains the same
807    /// physical and aggregate request budgets as every other read lane.
808    pub fn execute_trusted_live_page(
809        &self,
810        request: &DynamicQuery,
811        continuation: Option<&str>,
812    ) -> Result<LiveQueryPageOutput, QueryError> {
813        let catalog = self
814            .accepted_schema_catalog_context_for_entity_name(Some(request.entity()))
815            .map_err(QueryError::execute)?;
816        self.execute_scalar_page_against_catalog(
817            request,
818            continuation,
819            DynamicReadLane::Trusted,
820            catalog,
821            ScalarPageMode::Live,
822            None,
823        )
824        .map(|(page, _)| page)
825        .map_err(Self::live_page_error)
826    }
827
828    #[cfg(test)]
829    pub(in crate::db) fn execute_trusted_live_page_with_result_bytes_limit_for_tests(
830        &self,
831        request: &DynamicQuery,
832        continuation: Option<&str>,
833        result_bytes_limit: u64,
834    ) -> Result<LiveQueryPageOutput, QueryError> {
835        let previous = SCALAR_PAGE_RESULT_BYTES_LIMIT_OVERRIDE
836            .with(|limit| limit.replace(Some(result_bytes_limit)));
837        let _guard = ScalarPageResultBytesLimitGuard(previous);
838        self.execute_trusted_live_page(request, continuation)
839    }
840
841    /// Execute one revision-strict bounded dynamic page.
842    pub fn execute_public_exhaustive_page(
843        &self,
844        request: &DynamicQuery,
845        continuation: Option<&str>,
846        proof: Option<&ReadSetRevisionProof>,
847    ) -> Result<ExhaustiveQueryPageOutput, ExhaustiveReadError> {
848        let catalog =
849            self.accepted_schema_catalog_context_for_entity_name(Some(request.entity()))?;
850        let (page, proof) = self.execute_scalar_page_against_catalog(
851            request,
852            continuation,
853            DynamicReadLane::Public,
854            catalog,
855            ScalarPageMode::Exhaustive,
856            proof,
857        )?;
858        let proof = proof.ok_or(ReadSetRevisionError::NonCanonical)?;
859        Ok(ExhaustiveQueryPageOutput::from_live_page(page, proof))
860    }
861
862    /// Execute one exhaustive page through a typed binding's accepted identity.
863    #[doc(hidden)]
864    pub fn execute_public_exhaustive_page_for_typed_binding(
865        &self,
866        binding: &DynamicTypedEntityBinding,
867        request: &DynamicQuery,
868        continuation: Option<&str>,
869        proof: Option<&ReadSetRevisionProof>,
870    ) -> Result<Option<ExhaustiveQueryPageOutput>, ExhaustiveReadError> {
871        let Some(catalog) = self.current_typed_entity_binding_catalog(binding)? else {
872            return Ok(None);
873        };
874        let (page, proof) = self.execute_scalar_page_against_catalog(
875            request,
876            continuation,
877            DynamicReadLane::Public,
878            catalog,
879            ScalarPageMode::Exhaustive,
880            proof,
881        )?;
882        let proof = proof.ok_or(ReadSetRevisionError::NonCanonical)?;
883        Ok(Some(ExhaustiveQueryPageOutput::from_live_page(page, proof)))
884    }
885
886    /// Execute one trusted revision-strict bounded dynamic page.
887    pub fn execute_trusted_exhaustive_page(
888        &self,
889        request: &DynamicQuery,
890        continuation: Option<&str>,
891        proof: Option<&ReadSetRevisionProof>,
892    ) -> Result<ExhaustiveQueryPageOutput, ExhaustiveReadError> {
893        let catalog =
894            self.accepted_schema_catalog_context_for_entity_name(Some(request.entity()))?;
895        let (page, proof) = self.execute_scalar_page_against_catalog(
896            request,
897            continuation,
898            DynamicReadLane::Trusted,
899            catalog,
900            ScalarPageMode::Exhaustive,
901            proof,
902        )?;
903        let proof = proof.ok_or(ReadSetRevisionError::NonCanonical)?;
904        Ok(ExhaustiveQueryPageOutput::from_live_page(page, proof))
905    }
906
907    fn live_page_error(error: ExhaustiveReadError) -> QueryError {
908        match error {
909            ExhaustiveReadError::Query(error) => error,
910            ExhaustiveReadError::Revision(_) => QueryError::invariant(),
911        }
912    }
913}