Skip to main content

drive/query/drive_document_sum_query/
proof_plan.rs

1//! The request-only half of a proved sum or average: which proof answers
2//! the request, what that proof reads, and the limit and walk direction its
3//! path query carries.
4//!
5//! A sum and an average read the same trees through the same path queries;
6//! an average's range and carrier proofs read each element's count beside
7//! its sum. They share [`SumProofPlan`], and each surface keeps its own
8//! planner, since the server routes a sum by its resolved
9//! [`DocumentSumMode`] and an average by its mode and whether a range
10//! constrains it, each with its own refusals: this module plans a sum, and
11//! [`crate::query::drive_document_average_query::proof_plan`] an average.
12//! The server's dispatchers
13//! prove what the plan names, and the SDK's verifiers rebuild the path query
14//! from the same plan, so the two cannot read one request differently; a
15//! client refuses before sending what the plan refuses, in the server's
16//! words. The planners read no version table, so every protocol version
17//! that serves a proved sum or average plans the same proof for the same
18//! request.
19
20use super::index_picker::{
21    find_range_summable_index_for_where_clauses, find_summable_index_for_where_clauses,
22};
23use super::{DocumentSumMode, DriveDocumentSumQuery};
24use crate::config::DEFAULT_QUERY_LIMIT;
25use crate::error::drive::DriveError;
26use crate::error::query::QuerySyntaxError;
27use crate::error::Error;
28use crate::query::{OrderClause, ResolvedTimeRange, WhereClause};
29use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters};
30use dpp::data_contract::document_type::{DocumentTypeRef, Index};
31use dpp::version::PlatformVersion;
32use grovedb::PathQuery;
33
34/// What a proved sum or average reads, decided from its request alone.
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub enum SumProofPlan<'a> {
37    /// An unfiltered total over a type summed by the requested property (for
38    /// an average, also `documentsCountable`): the type's primary-key sum
39    /// tree.
40    PrimaryKeySumTree,
41    /// `Equal` / `In` clauses on a summable index: one sum-bearing element
42    /// per matched branch.
43    PointLookup(&'a Index),
44    /// A range on a range-summable index, ungrouped: one aggregate over the
45    /// range.
46    Range(&'a Index),
47    /// A range grouped by its values: one entry per distinct value, walking
48    /// at most `limit` of them.
49    RangeDistinct {
50        /// The range-summable index the walk reads.
51        index: &'a Index,
52        /// The `SizedQuery` limit of the walk.
53        limit: u16,
54        /// The walk's direction, `Query::left_to_right`.
55        left_to_right: bool,
56    },
57    /// A range grouped by an outer `In` or range: one aggregate per outer
58    /// key.
59    RangeAggregateCarrier {
60        /// The range-summable index the carrier reads.
61        index: &'a Index,
62        /// The `SizedQuery` limit of the outer walk; `None` leaves it
63        /// unbounded.
64        limit: Option<u16>,
65        /// The outer walk's direction, `Query::left_to_right`.
66        left_to_right: bool,
67    },
68}
69
70impl DriveDocumentSumQuery<'_> {
71    /// The [`SumProofPlan`] of a proved sum of `sum_property` over
72    /// `document_type`.
73    ///
74    /// `where_clauses` are the request's clauses as the dispatcher reads them
75    /// (typed array elements keyed, canonicalized), `resolved_time_ranges`
76    /// their window provenance, and `mode` the proof mode
77    /// [`detect_sum_mode_from_inputs`](super::mode_detection::detect_sum_mode_from_inputs)
78    /// resolved them to. `order_clauses` and `limit` are the request's,
79    /// `limit` `None` when unset; a distinct or carrier walk runs in the
80    /// first order clause's direction, ascending by default.
81    ///
82    /// `max_query_limit` is the node's configured cap on a proved walk's
83    /// limit, checked before the index is picked. A client, which cannot
84    /// know a node's configuration, passes `None`; the node refuses a limit
85    /// above its own cap.
86    #[allow(clippy::too_many_arguments)]
87    pub fn proof_plan<'a>(
88        document_type: &'a DocumentTypeRef<'_>,
89        where_clauses: &[WhereClause],
90        resolved_time_ranges: &[ResolvedTimeRange],
91        sum_property: &str,
92        mode: DocumentSumMode,
93        order_clauses: &[OrderClause],
94        limit: Option<u32>,
95        max_query_limit: Option<u16>,
96    ) -> Result<SumProofPlan<'a>, Error> {
97        let left_to_right = order_clauses.first().map(|c| c.ascending).unwrap_or(true);
98        let range_index = || {
99            find_range_summable_index_for_where_clauses(
100                document_type.indexes(),
101                where_clauses,
102                sum_property,
103                resolved_time_ranges,
104            )
105            .ok_or_else(|| {
106                Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
107                    "range sum requires a `rangeSummable: true` index whose last \
108                     property matches the range field"
109                        .to_string(),
110                ))
111            })
112        };
113        match mode {
114            DocumentSumMode::RangeProof => Ok(SumProofPlan::Range(range_index()?)),
115            DocumentSumMode::RangeDistinctProof => {
116                // Validate-don't-clamp: the verifier rebuilds the walk's
117                // `SizedQuery::limit` byte for byte, so an over-cap limit is
118                // refused rather than clamped. An unset limit falls back to
119                // the compile-time `DEFAULT_QUERY_LIMIT`, never the
120                // operator-tunable `default_query_limit`, which a verifier
121                // cannot know.
122                let effective_limit = limit.unwrap_or(DEFAULT_QUERY_LIMIT as u32);
123                if let Some(max_query_limit) = max_query_limit {
124                    if effective_limit > max_query_limit as u32 {
125                        return Err(Error::Query(QuerySyntaxError::InvalidLimit(format!(
126                            "limit {} exceeds max_query_limit {} on the prove + \
127                             distinct-walk path (GROUP BY a range field, SUM); \
128                             reduce the requested limit or use prove = false",
129                            effective_limit, max_query_limit
130                        ))));
131                    }
132                }
133                let limit = u16::try_from(effective_limit).map_err(|_| {
134                    Error::Query(QuerySyntaxError::Unsupported(format!(
135                        "limit {} exceeds u16::MAX for range-distinct sum proof",
136                        effective_limit
137                    )))
138                })?;
139                Ok(SumProofPlan::RangeDistinct {
140                    index: range_index()?,
141                    limit,
142                    left_to_right,
143                })
144            }
145            DocumentSumMode::PointLookupProof => {
146                // An unfiltered sum over a type summed by the requested
147                // property proves the primary-key sum tree directly.
148                if where_clauses.is_empty()
149                    && document_type
150                        .documents_summable()
151                        .map(|p| p == sum_property)
152                        .unwrap_or(false)
153                {
154                    return Ok(SumProofPlan::PrimaryKeySumTree);
155                }
156                find_summable_index_for_where_clauses(
157                    document_type.indexes(),
158                    where_clauses,
159                    sum_property,
160                    resolved_time_ranges,
161                )
162                .map(SumProofPlan::PointLookup)
163                .ok_or_else(|| {
164                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
165                        "prove sum requires a `summable: \"<prop>\"` index whose properties \
166                         exactly match the where clause fields and whose summed property \
167                         matches the request's `sum_property`, or `documentsSummable: \
168                         \"<prop>\"` on the document type for unfiltered total sums — same \
169                         requirement as the no-proof path"
170                            .to_string(),
171                    ))
172                })
173            }
174            DocumentSumMode::RangeAggregateCarrierProof => {
175                // Validate-don't-clamp, as for the distinct walk; an unset
176                // limit stays unset (an unbounded outer walk) rather than
177                // falling back to a default.
178                let limit = limit
179                    .map(|l| {
180                        if let Some(max_query_limit) = max_query_limit {
181                            if l > max_query_limit as u32 {
182                                return Err(Error::Query(QuerySyntaxError::InvalidLimit(format!(
183                                    "limit {} exceeds max_query_limit {} on the prove + \
184                                         carrier-aggregate path (GROUP BY In + range, SUM); \
185                                         reduce the requested limit or use prove = false",
186                                    l, max_query_limit
187                                ))));
188                            }
189                        }
190                        u16::try_from(l).map_err(|_| {
191                            Error::Query(QuerySyntaxError::Unsupported(format!(
192                                "limit {} exceeds u16::MAX for carrier-aggregate sum proof",
193                                l
194                            )))
195                        })
196                    })
197                    .transpose()?;
198                let index = find_range_summable_index_for_where_clauses(
199                    document_type.indexes(),
200                    where_clauses,
201                    sum_property,
202                    resolved_time_ranges,
203                )
204                .ok_or_else(|| {
205                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
206                        "carrier-aggregate sum requires a `rangeSummable: true` index whose first \
207                         property carries the outer In or range clause and whose last property \
208                         carries the inner ASOR range clause"
209                            .to_string(),
210                    ))
211                })?;
212                Ok(SumProofPlan::RangeAggregateCarrier {
213                    index,
214                    limit,
215                    left_to_right,
216                })
217            }
218            DocumentSumMode::Total
219            | DocumentSumMode::PerInValue
220            | DocumentSumMode::RangeNoProof => {
221                Err(Error::Drive(DriveError::CorruptedCodeExecution(
222                    "a sum proof plan is made only for a proof mode; mode detection with \
223                     prove = true never returns a no-proof mode",
224                )))
225            }
226        }
227    }
228}
229
230impl SumProofPlan<'_> {
231    /// The path query a proof of this plan answers. The server proves it
232    /// (`Drive::execute_document_sum_proof`), and a client builds it from the
233    /// same plan before sending and before it verifies an answer, so a
234    /// request whose path query cannot be built is refused in the server's
235    /// words.
236    ///
237    /// `with_counts` is whether the request is an average, whose range and
238    /// carrier proofs read each element's count beside its sum; its point
239    /// lookups and distinct walks read the count-sum-bearing elements the
240    /// index's terminators already hold. The other arguments are the
241    /// request's, as the planner read them.
242    #[allow(clippy::too_many_arguments)]
243    pub fn path_query(
244        &self,
245        contract_id: [u8; 32],
246        document_type: DocumentTypeRef,
247        document_type_name: String,
248        where_clauses: Vec<WhereClause>,
249        sum_property: String,
250        with_counts: bool,
251        platform_version: &PlatformVersion,
252    ) -> Result<PathQuery, Error> {
253        let sum_query = |index| DriveDocumentSumQuery {
254            document_type,
255            contract_id,
256            document_type_name,
257            index,
258            where_clauses,
259            sum_property,
260        };
261        match *self {
262            SumProofPlan::PrimaryKeySumTree => {
263                Ok(DriveDocumentSumQuery::primary_key_sum_path_query(
264                    contract_id,
265                    document_type.name(),
266                ))
267            }
268            SumProofPlan::PointLookup(index) => {
269                sum_query(index).point_lookup_sum_path_query(platform_version)
270            }
271            SumProofPlan::Range(index) if with_counts => {
272                sum_query(index).aggregate_count_and_sum_path_query(platform_version)
273            }
274            SumProofPlan::Range(index) => {
275                sum_query(index).aggregate_sum_path_query(platform_version)
276            }
277            SumProofPlan::RangeDistinct {
278                index,
279                limit,
280                left_to_right,
281            } => sum_query(index).distinct_sum_path_query(
282                Some(limit),
283                left_to_right,
284                platform_version,
285            ),
286            SumProofPlan::RangeAggregateCarrier {
287                index,
288                limit,
289                left_to_right,
290            } if with_counts => sum_query(index).carrier_aggregate_count_and_sum_path_query(
291                limit,
292                left_to_right,
293                platform_version,
294            ),
295            SumProofPlan::RangeAggregateCarrier {
296                index,
297                limit,
298                left_to_right,
299            } => sum_query(index).carrier_aggregate_sum_path_query(
300                limit,
301                left_to_right,
302                platform_version,
303            ),
304        }
305    }
306}