vlorql_core/cache/normalize.rs
1//! Normalisation helpers for deterministic cache-key generation.
2//!
3//! [`normalize_plan`] serialises a [`ValidatedPlan`] into a canonical
4//! JSON string so that two semantically equivalent plans (differing
5//! only in field ordering or whitespace) produce the same hash.
6
7use crate::validate::ValidatedPlan;
8use serde_json::Value;
9
10/// Serialises a validated plan into a canonical JSON string suitable
11/// for hashing.
12///
13/// The normalisation rules are:
14///
15/// 1. Serialise the [`QueryPlan`](crate::schema::QueryPlan) to a [`serde_json::Value`] (field
16/// order follows the struct definition — `serde_json` uses `BTreeMap`
17/// internally for `Value::Object`, so keys are already sorted).
18/// 2. Recursively sort the keys of every JSON object (defensive —
19/// `serde_json` already sorts, but this guards against future
20/// changes).
21/// 3. Serialise the sorted value to a compact string (no whitespace).
22///
23/// This ensures two plans that are semantically identical but have
24/// fields in different orders produce the same normalised string.
25///
26/// # Examples
27///
28/// ```
29/// use vlorql_core::cache::normalize_plan;
30/// use vlorql_core::schema::{QueryPlan, Projection, FromClause};
31/// use vlorql_core::validate::ValidatedPlan;
32/// use std::sync::Arc;
33///
34/// let plan = QueryPlan {
35/// select: vec![Projection::Column {
36/// table: None, column: "id".to_owned(), alias: None,
37/// }],
38/// from: FromClause { table: "users".to_owned(), alias: None },
39/// r#where: None, group_by: None, having: None,
40/// order_by: None, limit: None, offset: None,
41/// joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
42/// };
43/// let validated = ValidatedPlan(Arc::new(plan));
44/// let json = normalize_plan(&validated);
45/// assert!(json.contains("users"));
46/// assert!(json.contains("id"));
47/// ```
48pub fn normalize_plan(plan: &ValidatedPlan) -> String {
49 // Serialize to a serde_json::Value first. serde_json internally
50 // uses BTreeMap for objects, so keys are already sorted.
51 let value = serde_json::to_value(plan.as_plan())
52 .expect("ValidatedPlan should always serialize to JSON");
53
54 // Defensively sort keys recursively.
55 let sorted = sort_value(value);
56
57 // Compact serialisation — no whitespace.
58 serde_json::to_string(&sorted).expect("sorted JSON should serialize")
59}
60
61/// Maximum nesting depth for key sorting. Beyond this, `sort_value` returns
62/// the value as-is to prevent stack overflow from deeply nested JSON
63/// (e.g. plans with deeply nested CTEs).
64const MAX_SORT_DEPTH: usize = 64;
65
66/// Recursively sorts the keys of every JSON object in `value`, up to
67/// [`MAX_SORT_DEPTH`] levels deep.
68fn sort_value(value: Value) -> Value {
69 sort_value_with_depth(value, 0)
70}
71
72fn sort_value_with_depth(value: Value, depth: usize) -> Value {
73 if depth >= MAX_SORT_DEPTH {
74 return value;
75 }
76 let next_depth = depth + 1;
77 match value {
78 Value::Object(mut map) => {
79 let mut sorted = serde_json::Map::with_capacity(map.len());
80 let mut keys: Vec<String> = map.keys().cloned().collect();
81 keys.sort();
82 for key in keys {
83 // Use `remove` to move the value out of the map, avoiding a clone
84 // of the entire subtree for every key.
85 if let Some(val) = map.remove(&key) {
86 sorted.insert(key, sort_value_with_depth(val, next_depth));
87 }
88 }
89 Value::Object(sorted)
90 }
91 Value::Array(arr) => Value::Array(
92 arr.into_iter()
93 .map(|v| sort_value_with_depth(v, next_depth))
94 .collect(),
95 ),
96 other => other,
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use crate::schema::{FromClause, Projection, QueryPlan};
104 use std::sync::Arc;
105
106 /// Two plans with the same data produce the same normalised string.
107 #[test]
108 fn same_plan_same_normalized() {
109 let plan = || -> ValidatedPlan {
110 ValidatedPlan(Arc::new(QueryPlan {
111 select: vec![Projection::Column {
112 table: None,
113 column: "id".to_owned(),
114 alias: None,
115 }],
116 from: FromClause {
117 table: "users".to_owned(),
118 alias: None,
119 },
120 r#where: None,
121 group_by: None,
122 having: None,
123 order_by: None,
124 limit: None,
125 offset: None,
126 joins: None,
127 ctes: None,
128 distinct: false,
129 distinct_on: None,
130 set_operation: None, }))
131 };
132
133 assert_eq!(normalize_plan(&plan()), normalize_plan(&plan()));
134 }
135
136 /// Different plans produce different normalised strings.
137 #[test]
138 fn different_plan_different_normalized() {
139 let plan_a = ValidatedPlan(Arc::new(QueryPlan {
140 select: vec![Projection::Column {
141 table: None,
142 column: "id".to_owned(),
143 alias: None,
144 }],
145 from: FromClause {
146 table: "users".to_owned(),
147 alias: None,
148 },
149 r#where: None,
150 group_by: None,
151 having: None,
152 order_by: None,
153 limit: None,
154 offset: None,
155 joins: None,
156 ctes: None,
157 distinct: false,
158 distinct_on: None,
159 set_operation: None,
160 }));
161
162 let plan_b = ValidatedPlan(Arc::new(QueryPlan {
163 select: vec![Projection::Column {
164 table: None,
165 column: "email".to_owned(),
166 alias: None,
167 }],
168 from: FromClause {
169 table: "users".to_owned(),
170 alias: None,
171 },
172 r#where: None,
173 group_by: None,
174 having: None,
175 order_by: None,
176 limit: None,
177 offset: None,
178 joins: None,
179 ctes: None,
180 distinct: false,
181 distinct_on: None,
182 set_operation: None,
183 }));
184
185 assert_ne!(normalize_plan(&plan_a), normalize_plan(&plan_b));
186 }
187}