1#![allow(clippy::cast_possible_truncation)]
3
4use super::{
5 ExplainAccessPath, ExplainDeleteLimit, ExplainOrderBy, ExplainPagination, ExplainPlan,
6 ExplainPredicate, ExplainProjection,
7};
8use crate::db::index::fingerprint::hash_value;
9use crate::db::query::QueryMode;
10use crate::db::query::{
11 ReadConsistency,
12 predicate::{CompareOp, coercion::CoercionId},
13};
14use crate::key::Key;
15use sha2::{Digest, Sha256};
16
17#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub struct PlanFingerprint([u8; 32]);
25
26impl PlanFingerprint {
27 pub(crate) const fn from_bytes(bytes: [u8; 32]) -> Self {
28 Self(bytes)
29 }
30
31 #[must_use]
32 pub fn as_hex(&self) -> String {
33 let mut out = String::with_capacity(64);
34 for byte in self.0 {
35 use std::fmt::Write as _;
36 let _ = write!(out, "{byte:02x}");
37 }
38 out
39 }
40}
41
42impl std::fmt::Display for PlanFingerprint {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 f.write_str(&self.as_hex())
45 }
46}
47
48impl super::LogicalPlan {
49 #[must_use]
51 pub fn fingerprint(&self) -> PlanFingerprint {
52 self.explain().fingerprint()
53 }
54}
55
56impl ExplainPlan {
57 #[must_use]
59 pub fn fingerprint(&self) -> PlanFingerprint {
60 let mut hasher = Sha256::new();
61 hasher.update(b"planfp:v2");
62 hash_explain_plan(&mut hasher, self);
63 let digest = hasher.finalize();
64 let mut out = [0u8; 32];
65 out.copy_from_slice(&digest);
66 PlanFingerprint(out)
67 }
68}
69
70fn hash_explain_plan(hasher: &mut Sha256, plan: &ExplainPlan) {
71 write_tag(hasher, 0x01);
72 hash_access(hasher, &plan.access);
73
74 write_tag(hasher, 0x02);
75 hash_predicate(hasher, &plan.predicate);
76
77 write_tag(hasher, 0x03);
78 hash_order(hasher, &plan.order_by);
79
80 write_tag(hasher, 0x04);
81 hash_page(hasher, &plan.page);
82
83 write_tag(hasher, 0x05);
84 hash_delete_limit(hasher, &plan.delete_limit);
85
86 write_tag(hasher, 0x06);
87 hash_projection(hasher, &plan.projection);
88
89 write_tag(hasher, 0x07);
90 hash_consistency(hasher, plan.consistency);
91
92 write_tag(hasher, 0x08);
93 hash_mode(hasher, plan.mode);
94}
95
96fn hash_access(hasher: &mut Sha256, access: &ExplainAccessPath) {
97 match access {
98 ExplainAccessPath::ByKey { key } => {
99 write_tag(hasher, 0x10);
100 write_key(hasher, key);
101 }
102 ExplainAccessPath::ByKeys { keys } => {
103 write_tag(hasher, 0x11);
104 write_u32(hasher, keys.len() as u32);
105 for key in keys {
106 write_key(hasher, key);
107 }
108 }
109 ExplainAccessPath::KeyRange { start, end } => {
110 write_tag(hasher, 0x12);
111 write_key(hasher, start);
112 write_key(hasher, end);
113 }
114 ExplainAccessPath::IndexPrefix {
115 name,
116 fields,
117 prefix_len,
118 values,
119 } => {
120 write_tag(hasher, 0x13);
121 write_str(hasher, name);
122 write_u32(hasher, fields.len() as u32);
123 for field in fields {
124 write_str(hasher, field);
125 }
126 write_u32(hasher, *prefix_len as u32);
127 write_u32(hasher, values.len() as u32);
128 for value in values {
129 write_value(hasher, value);
130 }
131 }
132 ExplainAccessPath::FullScan => {
133 write_tag(hasher, 0x14);
134 }
135 ExplainAccessPath::Union(children) => {
136 write_tag(hasher, 0x15);
137 write_u32(hasher, children.len() as u32);
138 for child in children {
139 hash_access(hasher, child);
140 }
141 }
142 ExplainAccessPath::Intersection(children) => {
143 write_tag(hasher, 0x16);
144 write_u32(hasher, children.len() as u32);
145 for child in children {
146 hash_access(hasher, child);
147 }
148 }
149 }
150}
151
152fn hash_predicate(hasher: &mut Sha256, predicate: &ExplainPredicate) {
153 match predicate {
154 ExplainPredicate::None => write_tag(hasher, 0x20),
155 ExplainPredicate::True => write_tag(hasher, 0x21),
156 ExplainPredicate::False => write_tag(hasher, 0x22),
157 ExplainPredicate::And(children) => {
158 write_tag(hasher, 0x23);
159 write_u32(hasher, children.len() as u32);
160 for child in children {
161 hash_predicate(hasher, child);
162 }
163 }
164 ExplainPredicate::Or(children) => {
165 write_tag(hasher, 0x24);
166 write_u32(hasher, children.len() as u32);
167 for child in children {
168 hash_predicate(hasher, child);
169 }
170 }
171 ExplainPredicate::Not(inner) => {
172 write_tag(hasher, 0x25);
173 hash_predicate(hasher, inner);
174 }
175 ExplainPredicate::Compare {
176 field,
177 op,
178 value,
179 coercion,
180 } => {
181 write_tag(hasher, 0x26);
182 write_str(hasher, field);
183 write_tag(hasher, compare_op_tag(*op));
184 write_value(hasher, value);
185 hash_coercion(hasher, coercion.id, &coercion.params);
186 }
187 ExplainPredicate::IsNull { field } => {
188 write_tag(hasher, 0x27);
189 write_str(hasher, field);
190 }
191 ExplainPredicate::IsMissing { field } => {
192 write_tag(hasher, 0x28);
193 write_str(hasher, field);
194 }
195 ExplainPredicate::IsEmpty { field } => {
196 write_tag(hasher, 0x29);
197 write_str(hasher, field);
198 }
199 ExplainPredicate::IsNotEmpty { field } => {
200 write_tag(hasher, 0x2a);
201 write_str(hasher, field);
202 }
203 ExplainPredicate::MapContainsKey {
204 field,
205 key,
206 coercion,
207 } => {
208 write_tag(hasher, 0x2b);
209 write_str(hasher, field);
210 write_value(hasher, key);
211 hash_coercion(hasher, coercion.id, &coercion.params);
212 }
213 ExplainPredicate::MapContainsValue {
214 field,
215 value,
216 coercion,
217 } => {
218 write_tag(hasher, 0x2c);
219 write_str(hasher, field);
220 write_value(hasher, value);
221 hash_coercion(hasher, coercion.id, &coercion.params);
222 }
223 ExplainPredicate::MapContainsEntry {
224 field,
225 key,
226 value,
227 coercion,
228 } => {
229 write_tag(hasher, 0x2d);
230 write_str(hasher, field);
231 write_value(hasher, key);
232 write_value(hasher, value);
233 hash_coercion(hasher, coercion.id, &coercion.params);
234 }
235 }
236}
237
238fn hash_order(hasher: &mut Sha256, order: &ExplainOrderBy) {
239 match order {
240 ExplainOrderBy::None => write_tag(hasher, 0x30),
241 ExplainOrderBy::Fields(fields) => {
242 write_tag(hasher, 0x31);
243 write_u32(hasher, fields.len() as u32);
244 for field in fields {
245 write_str(hasher, &field.field);
246 write_tag(hasher, order_direction_tag(field.direction));
247 }
248 }
249 }
250}
251
252fn hash_page(hasher: &mut Sha256, page: &ExplainPagination) {
253 match page {
254 ExplainPagination::None => write_tag(hasher, 0x40),
255 ExplainPagination::Page { limit, offset } => {
256 write_tag(hasher, 0x41);
257 match limit {
258 Some(limit) => {
259 write_tag(hasher, 0x01);
260 write_u32(hasher, *limit);
261 }
262 None => write_tag(hasher, 0x00),
263 }
264 write_u64(hasher, *offset);
265 }
266 }
267}
268
269fn hash_delete_limit(hasher: &mut Sha256, limit: &ExplainDeleteLimit) {
270 match limit {
271 ExplainDeleteLimit::None => write_tag(hasher, 0x42),
272 ExplainDeleteLimit::Limit { max_rows } => {
273 write_tag(hasher, 0x43);
274 write_u32(hasher, *max_rows);
275 }
276 }
277}
278
279fn hash_projection(hasher: &mut Sha256, projection: &ExplainProjection) {
280 match projection {
281 ExplainProjection::All => write_tag(hasher, 0x40),
282 }
283}
284
285fn hash_consistency(hasher: &mut Sha256, consistency: ReadConsistency) {
286 match consistency {
287 ReadConsistency::MissingOk => write_tag(hasher, 0x50),
288 ReadConsistency::Strict => write_tag(hasher, 0x51),
289 }
290}
291
292fn hash_mode(hasher: &mut Sha256, mode: QueryMode) {
293 match mode {
294 QueryMode::Load => write_tag(hasher, 0x60),
295 QueryMode::Delete => write_tag(hasher, 0x61),
296 }
297}
298
299fn hash_coercion(
300 hasher: &mut Sha256,
301 id: CoercionId,
302 params: &std::collections::BTreeMap<String, String>,
303) {
304 write_tag(hasher, coercion_id_tag(id));
305 write_u32(hasher, params.len() as u32);
306 for (key, value) in params {
307 write_str(hasher, key);
308 write_str(hasher, value);
309 }
310}
311
312fn write_key(hasher: &mut Sha256, key: &Key) {
313 match key.to_bytes() {
314 Ok(bytes) => hasher.update(bytes),
315 Err(err) => {
316 write_tag(hasher, 0xED);
317 write_str(hasher, &err.to_string());
318 }
319 }
320}
321
322fn write_value(hasher: &mut Sha256, value: &crate::value::Value) {
323 match hash_value(value) {
324 Ok(digest) => hasher.update(digest),
325 Err(err) => {
326 write_tag(hasher, 0xEE);
327 write_str(hasher, &err.display_with_class());
328 }
329 }
330}
331
332fn write_str(hasher: &mut Sha256, value: &str) {
333 write_u32(hasher, value.len() as u32);
334 hasher.update(value.as_bytes());
335}
336
337fn write_u32(hasher: &mut Sha256, value: u32) {
338 hasher.update(value.to_be_bytes());
339}
340
341fn write_u64(hasher: &mut Sha256, value: u64) {
342 hasher.update(value.to_be_bytes());
343}
344
345fn write_tag(hasher: &mut Sha256, tag: u8) {
346 hasher.update([tag]);
347}
348
349const fn compare_op_tag(op: CompareOp) -> u8 {
350 match op {
351 CompareOp::Eq => 0x01,
352 CompareOp::Ne => 0x02,
353 CompareOp::Lt => 0x03,
354 CompareOp::Lte => 0x04,
355 CompareOp::Gt => 0x05,
356 CompareOp::Gte => 0x06,
357 CompareOp::In => 0x07,
358 CompareOp::NotIn => 0x08,
359 CompareOp::AnyIn => 0x09,
360 CompareOp::AllIn => 0x0a,
361 CompareOp::Contains => 0x0b,
362 CompareOp::StartsWith => 0x0c,
363 CompareOp::EndsWith => 0x0d,
364 }
365}
366
367const fn order_direction_tag(direction: crate::db::query::plan::OrderDirection) -> u8 {
368 match direction {
369 crate::db::query::plan::OrderDirection::Asc => 0x01,
370 crate::db::query::plan::OrderDirection::Desc => 0x02,
371 }
372}
373
374const fn coercion_id_tag(id: CoercionId) -> u8 {
375 match id {
376 CoercionId::Strict => 0x01,
377 CoercionId::NumericWiden => 0x02,
378 CoercionId::IdentifierText => 0x03,
379 CoercionId::TextCasefold => 0x04,
380 CoercionId::CollectionElement => 0x05,
381 }
382}
383
384#[cfg(test)]
385mod tests {
386 use crate::db::query::plan::planner::PlannerEntity;
387 use crate::db::query::plan::{AccessPath, DeleteLimitSpec, LogicalPlan};
388 use crate::db::query::{Query, QueryMode, ReadConsistency, eq};
389 use crate::model::index::IndexModel;
390 use crate::types::Ulid;
391 use crate::value::Value;
392
393 #[test]
394 fn fingerprint_is_deterministic_for_equivalent_predicates() {
395 let id = Ulid::default();
396 let query_a = Query::<PlannerEntity>::new(ReadConsistency::MissingOk)
397 .filter(eq("id", id))
398 .filter(eq("other", "x"));
399 let query_b = Query::<PlannerEntity>::new(ReadConsistency::MissingOk)
400 .filter(eq("other", "x"))
401 .filter(eq("id", id));
402
403 let plan_a = query_a.plan().expect("plan a");
404 let plan_b = query_b.plan().expect("plan b");
405
406 assert_eq!(plan_a.fingerprint(), plan_b.fingerprint());
407 }
408
409 #[test]
410 fn fingerprint_changes_with_index_choice() {
411 const INDEX_FIELDS: [&str; 1] = ["idx_a"];
412 const INDEX_A: IndexModel = IndexModel::new(
413 "fingerprint::idx_a",
414 "fingerprint::store",
415 &INDEX_FIELDS,
416 false,
417 );
418 const INDEX_B: IndexModel = IndexModel::new(
419 "fingerprint::idx_b",
420 "fingerprint::store",
421 &INDEX_FIELDS,
422 false,
423 );
424
425 let plan_a = LogicalPlan::new(
426 AccessPath::IndexPrefix {
427 index: INDEX_A,
428 values: vec![Value::Text("alpha".to_string())],
429 },
430 crate::db::query::ReadConsistency::MissingOk,
431 );
432 let plan_b = LogicalPlan::new(
433 AccessPath::IndexPrefix {
434 index: INDEX_B,
435 values: vec![Value::Text("alpha".to_string())],
436 },
437 crate::db::query::ReadConsistency::MissingOk,
438 );
439
440 assert_ne!(plan_a.fingerprint(), plan_b.fingerprint());
441 }
442
443 #[test]
444 fn fingerprint_changes_with_pagination() {
445 let mut plan_a = LogicalPlan::new(
446 AccessPath::FullScan,
447 crate::db::query::ReadConsistency::MissingOk,
448 );
449 let mut plan_b = LogicalPlan::new(
450 AccessPath::FullScan,
451 crate::db::query::ReadConsistency::MissingOk,
452 );
453 plan_a.page = Some(crate::db::query::plan::PageSpec {
454 limit: Some(10),
455 offset: 0,
456 });
457 plan_b.page = Some(crate::db::query::plan::PageSpec {
458 limit: Some(10),
459 offset: 1,
460 });
461
462 assert_ne!(plan_a.fingerprint(), plan_b.fingerprint());
463 }
464
465 #[test]
466 fn fingerprint_changes_with_delete_limit() {
467 let mut plan_a = LogicalPlan::new(
468 AccessPath::FullScan,
469 crate::db::query::ReadConsistency::MissingOk,
470 );
471 let mut plan_b = LogicalPlan::new(
472 AccessPath::FullScan,
473 crate::db::query::ReadConsistency::MissingOk,
474 );
475 plan_a.mode = QueryMode::Delete;
476 plan_b.mode = QueryMode::Delete;
477 plan_a.delete_limit = Some(DeleteLimitSpec { max_rows: 2 });
478 plan_b.delete_limit = Some(DeleteLimitSpec { max_rows: 3 });
479
480 assert_ne!(plan_a.fingerprint(), plan_b.fingerprint());
481 }
482
483 #[test]
484 fn fingerprint_is_stable_for_full_scan() {
485 let plan = LogicalPlan::new(
486 AccessPath::FullScan,
487 crate::db::query::ReadConsistency::MissingOk,
488 );
489 let fingerprint_a = plan.fingerprint();
490 let fingerprint_b = plan.fingerprint();
491 assert_eq!(fingerprint_a, fingerprint_b);
492 }
493}