Skip to main content

drive/query/drive_document_average_query/
proof_plan.rs

1//! The request-only half of a proved average: which proof answers the
2//! request, what that proof reads, and the limit and walk direction its
3//! path query carries.
4//!
5//! An average reads the trees a sum reads, through the same path queries,
6//! so it is planned as a [`SumProofPlan`]; its range and carrier proofs read
7//! each element's count beside its sum. It is planned apart from a sum
8//! because the server routes it by its [`AverageMode`] and whether a range
9//! clause constrains it, not by sum's resolved mode, with its own refusals.
10//! The server's average dispatcher proves what the plan names, and the SDK's
11//! verifier rebuilds the path query from the same plan; a client refuses
12//! before sending what the plan refuses, in the server's words. The planner
13//! reads no version table, so every protocol version that serves a proved
14//! average plans the same proof for the same request.
15
16use super::AverageMode;
17use crate::config::DEFAULT_QUERY_LIMIT;
18use crate::error::query::QuerySyntaxError;
19use crate::error::Error;
20use crate::query::drive_document_sum_query::index_picker::{
21    find_range_summable_index_with_counts_for_where_clauses,
22    find_summable_index_with_counts_for_where_clauses,
23};
24use crate::query::drive_document_sum_query::{
25    is_range_operator, DriveDocumentSumQuery, SumProofPlan,
26};
27use crate::query::{OrderClause, ResolvedTimeRange, WhereClause};
28use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters};
29use dpp::data_contract::document_type::DocumentTypeRef;
30
31impl DriveDocumentSumQuery<'_> {
32    /// The [`SumProofPlan`] of a proved average of `sum_property` over
33    /// `document_type`: each proof reads an element's count beside its sum.
34    ///
35    /// A range picks an index that is both range-countable and
36    /// range-summable (one `rangeAverageable: true` declares both), no range
37    /// an index that sums the property and counts its terminator. The
38    /// arguments are [`DriveDocumentSumQuery::proof_plan`]'s, except that
39    /// `mode` is the request's SQL-shape [`AverageMode`] and that an average
40    /// picks its index *before* it checks the limit against
41    /// `max_query_limit`: a request with both problems is refused for the
42    /// index.
43    #[allow(clippy::too_many_arguments)]
44    pub fn average_proof_plan<'a>(
45        document_type: &'a DocumentTypeRef<'_>,
46        where_clauses: &[WhereClause],
47        resolved_time_ranges: &[ResolvedTimeRange],
48        sum_property: &str,
49        mode: AverageMode,
50        order_clauses: &[OrderClause],
51        limit: Option<u32>,
52        max_query_limit: Option<u16>,
53    ) -> Result<SumProofPlan<'a>, Error> {
54        let has_range = where_clauses
55            .iter()
56            .any(|wc| is_range_operator(wc.operator));
57        let left_to_right = order_clauses.first().map(|c| c.ascending).unwrap_or(true);
58
59        // An unfiltered average over a type that counts its documents and
60        // sums them by the requested property proves the primary-key
61        // count-sum-bearing element directly.
62        if matches!(mode, AverageMode::Aggregate)
63            && where_clauses.is_empty()
64            && document_type.documents_countable()
65            && document_type
66                .documents_summable()
67                .map(|p| p == sum_property)
68                .unwrap_or(false)
69        {
70            return Ok(SumProofPlan::PrimaryKeySumTree);
71        }
72
73        match (mode, has_range) {
74            (AverageMode::Aggregate | AverageMode::GroupByIn, true) => {
75                let index = find_range_summable_index_with_counts_for_where_clauses(
76                    document_type.indexes(),
77                    where_clauses,
78                    sum_property,
79                    resolved_time_ranges,
80                )
81                .ok_or_else(|| {
82                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
83                        "prove AVG requires an index that declares BOTH `rangeCountable: \
84                         true` AND `rangeSummable: true` (a `rangeAverageable: true` \
85                         index is the shorthand) whose last property matches the range \
86                         field and whose summable property matches the request's \
87                         `sum_property`"
88                            .to_string(),
89                    ))
90                })?;
91                if matches!(mode, AverageMode::Aggregate) {
92                    return Ok(SumProofPlan::Range(index));
93                }
94                // Carrier: one (count, sum) per `In` branch. Validate-don't-
95                // clamp, as for sum's carrier; an unset limit stays unset.
96                let limit = limit
97                    .map(|l| {
98                        if let Some(max_query_limit) = max_query_limit {
99                            if l > max_query_limit as u32 {
100                                return Err(Error::Query(QuerySyntaxError::InvalidLimit(format!(
101                                    "limit {} exceeds max_query_limit {} on the prove + \
102                                         carrier-aggregate path (GROUP BY In + range, AVG); \
103                                         reduce the requested limit or use prove = false",
104                                    l, max_query_limit
105                                ))));
106                            }
107                        }
108                        u16::try_from(l).map_err(|_| {
109                            Error::Query(QuerySyntaxError::Unsupported(format!(
110                                "limit {} exceeds u16::MAX for carrier-aggregate \
111                                 count+sum (AVG) proof",
112                                l
113                            )))
114                        })
115                    })
116                    .transpose()?;
117                Ok(SumProofPlan::RangeAggregateCarrier {
118                    index,
119                    limit,
120                    left_to_right,
121                })
122            }
123            (AverageMode::GroupByRange | AverageMode::GroupByCompound, true) => {
124                let index = find_range_summable_index_with_counts_for_where_clauses(
125                    document_type.indexes(),
126                    where_clauses,
127                    sum_property,
128                    resolved_time_ranges,
129                )
130                .ok_or_else(|| {
131                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
132                        "prove distinct AVG requires an index that declares BOTH \
133                         `rangeCountable: true` AND `rangeSummable: true` (a \
134                         `rangeAverageable: true` index is the shorthand) whose last \
135                         property matches the range field and whose summable property \
136                         matches the request's `sum_property`"
137                            .to_string(),
138                    ))
139                })?;
140                // Validate-don't-clamp, as for sum's distinct walk; an unset
141                // limit falls back to the compile-time `DEFAULT_QUERY_LIMIT`.
142                let effective_limit = limit.unwrap_or(DEFAULT_QUERY_LIMIT as u32);
143                if let Some(max_query_limit) = max_query_limit {
144                    if effective_limit > max_query_limit as u32 {
145                        return Err(Error::Query(QuerySyntaxError::InvalidLimit(format!(
146                            "limit {} exceeds max_query_limit {} on the prove + distinct-walk \
147                             path (GROUP BY a range field, AVG); reduce the requested limit \
148                             or use prove = false",
149                            effective_limit, max_query_limit
150                        ))));
151                    }
152                }
153                let limit = u16::try_from(effective_limit).map_err(|_| {
154                    Error::Query(QuerySyntaxError::Unsupported(format!(
155                        "limit {} exceeds u16::MAX for distinct AVG proof",
156                        effective_limit
157                    )))
158                })?;
159                Ok(SumProofPlan::RangeDistinct {
160                    index,
161                    limit,
162                    left_to_right,
163                })
164            }
165            // Equal / `In`, no range: one count-sum-bearing element per matched
166            // branch, collapsed into one aggregate by `DocumentAverage` or kept
167            // per branch by `DocumentSplitAverages` (the same proof either way).
168            (AverageMode::Aggregate | AverageMode::GroupByIn, false) => {
169                find_summable_index_with_counts_for_where_clauses(
170                    document_type.indexes(),
171                    where_clauses,
172                    sum_property,
173                    resolved_time_ranges,
174                )
175                .map(SumProofPlan::PointLookup)
176                .ok_or_else(|| {
177                    Error::Query(QuerySyntaxError::WhereClauseOnNonIndexedProperty(
178                        "prove point-lookup AVG requires an index that declares BOTH \
179                         `summable: \"<prop>\"` AND a countable terminator (`countable: \
180                         \"countable\"` or `\"countableAllowingOffset\"`) whose properties \
181                         exactly match the where clause fields"
182                            .to_string(),
183                    ))
184                })
185            }
186            // A grouped walk with no range to walk: routing never sends one, so
187            // only a direct Drive caller reaches this.
188            (AverageMode::GroupByRange | AverageMode::GroupByCompound, false) => {
189                Err(Error::Query(QuerySyntaxError::Unsupported(format!(
190                    "execute_document_average_request prove=true: the (mode = {:?}, has_range \
191                     = {}) combination is not yet supported on the prove path. \
192                     This is likely a new AverageMode variant that hasn't been wired \
193                     into the prove dispatcher.",
194                    mode, has_range,
195                ))))
196            }
197        }
198    }
199}