drive/query/drive_document_ranked_query/path.rs
1//! The grove path a ranked read / proof / verification is issued against.
2//!
3//! This is one half of the **prover/verifier-agreement boundary** for
4//! the ranked surface: both sides build the same axis `PathQuery` —
5//! these path segments plus the traversal (`axis, k, offset,
6//! descending`) — and grovedb re-executes the proof against that
7//! reconstruction at verification time. Prover and verifier
8//! both call [`DriveDocumentRankedQuery::indexed_property_name_tree_path`];
9//! a divergence here surfaces as a failed root-hash reconstruction, not a
10//! wrong answer, but it is still the one place the two sides must not
11//! drift.
12//!
13//! Gated `any(server, verify)` so the verifier crate reaches it through
14//! `DriveDocumentRankedQuery::*` method syntax.
15
16use super::DriveDocumentRankedQuery;
17use crate::drive::RootTree;
18use crate::error::drive::DriveError;
19use crate::error::Error;
20use dpp::data_contract::document_type::{Index, IndexProperty};
21
22/// The ranked level a request with `pin_count` pins addresses, split
23/// into the leading properties (one pin each) and the ranked property
24/// itself. An index can host secondaries at up to TWO levels — its
25/// `rankedCountable.at` property and, independently, its terminal
26/// property (the boolean axes) — so the level cannot be derived from
27/// the index alone: the request's pin count names it, since every
28/// property before the ranked level must be pinned and none after it
29/// may appear. Fails closed when the pin count lands on a level that
30/// hosts no secondary.
31///
32/// Shared by the path builder and the prefix encoder — and, through
33/// them, by the server executors and the SDK verifier — so both sides
34/// agree on where a request's secondary lives without re-deriving it.
35pub(crate) fn ranked_level_split(
36 index: &Index,
37 pin_count: usize,
38) -> Result<(&[IndexProperty], &IndexProperty), Error> {
39 let Some(ranked_property) = index.properties.get(pin_count) else {
40 return Err(Error::Drive(DriveError::NotSupported(
41 "ranked and having-range queries require exactly one pinned value per property \
42 before the ranked level — the resolved pin set addresses no index property",
43 )));
44 };
45 let is_at_level = index
46 .ranked_at_levels()
47 .any(|at| at == &ranked_property.name);
48 let is_terminal = pin_count + 1 == index.properties.len();
49 if !is_at_level && !is_terminal {
50 return Err(Error::Drive(DriveError::NotSupported(
51 "ranked and having-range queries must land on a level hosting a ranking \
52 secondary — one of the index's ranking `at` properties or its terminal property; \
53 the resolved pin set addresses an intermediate level",
54 )));
55 }
56 Ok((&index.properties[..pin_count], ranked_property))
57}
58
59/// Path of an index's **ranked-level** property-name tree — the terminal
60/// one for the boolean ranking axes, the `at` level for a prefix-level
61/// `rankedCountable`. Shared by the ranked and having-range query
62/// surfaces, which read the same indexed tree. See
63/// [`DriveDocumentRankedQuery::indexed_property_name_tree_path`]
64/// for the segment layout.
65///
66/// The branch's prefix segments carry the **encoded index-key bytes** of
67/// each leading property's pinned value, in index-property order — one
68/// per property before the ranked one. Empty for an index ranked at its
69/// first property. The arity must match exactly: the ranked level's
70/// tree sits under one prefix value tree per leading property, and only
71/// a `where` pin (an equality, or one element of the single permitted
72/// `IN`) can name those values, so a missing or surplus value means the
73/// caller resolved the wrong index — a typed error, not a guess.
74pub(crate) fn indexed_property_name_tree_path_for_index(
75 contract_id: &[u8; 32],
76 document_type_name: &str,
77 index: &Index,
78 equality_prefix_values: &[Vec<u8>],
79) -> Result<Vec<Vec<u8>>, Error> {
80 // The pin count names the ranked level (see `ranked_level_split`),
81 // which also makes the leading-property arity match by construction;
82 // the split's fail-closed error replaces the old arity backstop.
83 let (leading_properties, terminal_property) =
84 ranked_level_split(index, equality_prefix_values.len())?;
85 let mut path = Vec::with_capacity(5 + 2 * leading_properties.len());
86 path.push(vec![RootTree::DataContractDocuments as u8]);
87 path.push(contract_id.to_vec());
88 path.push(vec![1u8]);
89 path.push(document_type_name.as_bytes().to_vec());
90 // Level segments go through `Index::level_key`, the single source of
91 // the level-key rule: a bucketed (timeRange) first level is keyed by
92 // the grid-qualified `storage_key`, every other level by its bare
93 // property name. The pinned value under a bucketed level is the
94 // resolved bucket start, encoded exactly like the timestamp itself.
95 for (position, (property, value)) in leading_properties
96 .iter()
97 .zip(equality_prefix_values)
98 .enumerate()
99 {
100 path.push(index.level_key(position, &property.name).into_bytes());
101 path.push(value.clone());
102 }
103 path.push(
104 index
105 .level_key(leading_properties.len(), &terminal_property.name)
106 .into_bytes(),
107 );
108 Ok(path)
109}
110
111impl DriveDocumentRankedQuery<'_> {
112 /// Path of the **terminal property-name tree** — the indexed tree
113 /// whose primary holds one value tree per group and whose per-axis
114 /// secondaries hold the ranking.
115 ///
116 /// For a single-property index:
117 ///
118 /// ```text
119 /// [ RootTree::DataContractDocuments as u8 ] // 0x01
120 /// / <contract_id: 32 bytes>
121 /// / [ 0x01 ] // "documents", not "contract"
122 /// / <document_type_name: utf-8>
123 /// / <index property name: utf-8>
124 /// ```
125 ///
126 /// For a compound index `[p1, …, pn]`, each leading property
127 /// contributes two segments — its name and the **encoded index-key
128 /// bytes of its pinned value** (from
129 /// [`Self::prefix_branches`]) — and the terminal property
130 /// name closes the path:
131 ///
132 /// ```text
133 /// … / <p1 name> / <p1 pinned value bytes> / … / <pn name>
134 /// ```
135 ///
136 /// so the ranking read lands on **that prefix's** indexed tree: the
137 /// per-prefix secondary orders only the pinned prefix's groups.
138 ///
139 /// The children of the terminal tree are the groups, keyed by the
140 /// raw index-key bytes of the terminal property value — the same
141 /// bytes that come back as [`super::RankedEntry::key`].
142 ///
143 /// Errors when the number of encoded prefix values does not match
144 /// the index's leading-property count — the fail-closed backstop
145 /// for a caller that resolved the query against the wrong index.
146 ///
147 /// `branch` indexes into [`Self::prefix_branches`]; single-branch
148 /// queries (no `IN` pin) always pass `0`.
149 pub fn indexed_property_name_tree_path(&self, branch: usize) -> Result<Vec<Vec<u8>>, Error> {
150 let prefix_values =
151 self.prefix_branches
152 .get(branch)
153 .ok_or(Error::Drive(DriveError::NotSupported(
154 "ranked and having-range queries addressed a prefix branch outside the \
155 query's resolved branch set",
156 )))?;
157 indexed_property_name_tree_path_for_index(
158 &self.contract_id,
159 &self.document_type_name,
160 self.index,
161 prefix_values,
162 )
163 }
164}