drive/query/aggregate_routing/mod.rs
1//! Versioned dispatcher for the
2//! `compute_aggregate_mode_and_check_limit` helper.
3//!
4//! The helper decides how a `SELECT COUNT` / `SUM` / `AVG` request
5//! against the v1 query surface is executed: as one of the four
6//! `(group_by × where)` grouped modes, or — from feature version 1 —
7//! as a *ranked* request when the request orders by the aggregate it
8//! selects (`GROUP BY p ORDER BY <the selected aggregate>`), or — from
9//! feature version 2 — as a *having-range* request when a grouped
10//! aggregate carries exactly one `having` clause. Routing here only
11//! asks which shape the request has; the direction, the bounds, the
12//! limit's contract and the offset are drive's call and are made in
13//! `detect_ranked_mode` / `detect_having_mode`. It also enforces the
14//! per-mode `accepts_limit()` contract on the grouped path.
15//!
16//! The routing rules it embeds are part of the query contract clients
17//! see on the wire — a change to which `(group_by × where_clauses ×
18//! order_by)` shapes are accepted becomes consensus-visible because the
19//! dispatcher runs on every v1 query request. Versioning it lets later
20//! protocol bumps adjust the routing table without breaking older
21//! nodes' replay of historical traffic, and is what keeps a
22//! mixed-version network in agreement across the ranked-query and
23//! having-range activations: protocol version 13 and earlier select v0,
24//! which has neither path, while protocol version 14 selects v2 and
25//! answers both.
26//!
27//! Lives in Drive, under `verify` as well as `server`, so drive-abci's v1
28//! query handler and a client's check before sending route one request
29//! the same way. It is dispatched via the
30//! `DriveAbciDocumentQueryHelperVersions` slot in `PlatformVersion`, the
31//! query version the handler runs at. Each generation refuses with
32//! Drive's `Error::Query` (an unknown version with `Error::Drive`), which
33//! drive-abci reports as `QueryError::Query` (`QueryError::Drive`), the
34//! errors its handler answers these refusals with at every protocol
35//! version.
36
37mod v0;
38mod v1;
39mod v2;
40
41use crate::error::drive::DriveError;
42use crate::error::query::QuerySyntaxError;
43use crate::error::Error;
44use crate::query::{CountMode, HavingClause, OrderClause, SelectProjection, WhereClause};
45use dpp::version::PlatformVersion;
46
47/// What the helper decided a request should execute as.
48///
49/// `Grouped` is the pre-existing outcome — the `(group_by × where)`
50/// mode the count / sum / average executors take. `Ranked` is the
51/// feature-version-1 addition: the request orders by the aggregate it
52/// selects and belongs to `Drive::execute_document_ranked_request`,
53/// which re-derives `(axis, direction, k, offset)` from the same
54/// `(select, group_by, order_by, limit, offset)` inputs.
55///
56/// The ranked variant deliberately carries no data. Everything the
57/// ranked dispatcher needs is already owned by the handler (the
58/// decoded `select`, `group_by`, `order_by`, `limit` and `offset`), and
59/// duplicating the resolved axis / direction / `k` here would create a
60/// second place where the ranking grammar is interpreted — drive owns
61/// that grammar (`detect_ranked_mode`), and a routing-layer copy could
62/// disagree with it after a version bump. Routing decides *where* a
63/// request goes; drive decides what it means.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum AggregateRouting {
66 /// Non-ranked aggregate: execute with this `(group_by × where)` mode.
67 Grouped(CountMode),
68 /// Ranked aggregate: execute through the ranked (top-k) surface.
69 Ranked,
70 /// Boolean-`HAVING` range: a grouped aggregate carrying exactly one
71 /// `having` clause, executed through
72 /// `Drive::execute_document_having_request` as a value-bounded range
73 /// read of the covering ranked index's axis secondary. The
74 /// feature-version-2 addition. Carries no data for the same reason
75 /// `Ranked` carries none: drive owns the having grammar
76 /// (`detect_having_mode`), and routing only decides *where* the
77 /// request goes.
78 HavingRange,
79}
80
81/// Decide how a `SELECT COUNT` / `SUM` / `AVG` request executes.
82///
83/// All three aggregate functions share the same SQL-shape contract
84/// (empty group_by → Aggregate; one-field group_by → GroupByIn or
85/// GroupByRange depending on whether the field is `In`-bound or
86/// range-bound; two-field group_by `(in_field, range_field)` →
87/// GroupByCompound). The `function_name` arg ("COUNT" / "SUM" / "AVG")
88/// is woven into rejection messages for clarity.
89///
90/// On the grouped path it also runs the `accepts_limit()` check:
91/// `Aggregate` and `GroupByIn` can't honor a caller-supplied limit and
92/// reject with `QuerySyntaxError::InvalidLimit` if one is set. The
93/// ranked path deliberately does *not* check `limit` here — on that
94/// path `limit` is the ranking's `k`, and drive owns both its
95/// mandatoriness and its `1 ..= 100` bound; duplicating those rules at
96/// the routing layer would mean two error messages for one contract.
97///
98/// Routes through `platform_version.drive_abci.query.document_query_helpers.compute_aggregate_mode_and_check_limit`.
99#[allow(clippy::too_many_arguments)]
100pub fn compute_aggregate_mode_and_check_limit(
101 select: &SelectProjection,
102 group_by: &[String],
103 where_clauses: &[WhereClause],
104 order_by: &[OrderClause],
105 limit: Option<u32>,
106 having: &[HavingClause],
107 function_name: &str,
108 platform_version: &PlatformVersion,
109) -> Result<AggregateRouting, Error> {
110 match platform_version
111 .drive_abci
112 .query
113 .document_query_helpers
114 .compute_aggregate_mode_and_check_limit
115 {
116 // v0 predates the ranked surface entirely: it has no `order_by`
117 // input because ordering played no part in its routing
118 // decision, and passing one would be the first step toward
119 // changing what an already-shipped protocol version accepts.
120 0 => v0::compute_aggregate_mode_and_check_limit_v0(
121 group_by,
122 where_clauses,
123 limit,
124 having,
125 function_name,
126 ),
127 1 => v1::compute_aggregate_mode_and_check_limit_v1(
128 select,
129 group_by,
130 where_clauses,
131 order_by,
132 limit,
133 having,
134 function_name,
135 ),
136 2 => v2::compute_aggregate_mode_and_check_limit_v2(
137 select,
138 group_by,
139 where_clauses,
140 order_by,
141 limit,
142 having,
143 function_name,
144 ),
145 version => Err(Error::Drive(DriveError::UnknownVersionMismatch {
146 method: "compute_aggregate_mode_and_check_limit".to_string(),
147 known_versions: vec![0, 1, 2],
148 received: version,
149 })),
150 }
151}
152
153/// The refusal of a shape the wire carries but no node evaluates yet: a
154/// capability rather than a malformed request.
155fn not_yet_implemented(feature: &str) -> Error {
156 Error::Query(QuerySyntaxError::Unsupported(format!(
157 "{} is not yet implemented",
158 feature
159 )))
160}