Skip to main content

adk_core/
schema_cache.rs

1//! Schema normalization cache for LLM provider adapters.
2//!
3//! Binds one adapter to each cache and stores normalized schemas by content hash,
4//! avoiding redundant normalization without allowing one adapter's result to be
5//! returned for another adapter. The hash ignores the order object keys were
6//! written in, so when `serde_json/preserve_order` is enabled — where insertion
7//! order would otherwise change the key — one schema built two different ways is
8//! one entry.
9//!
10//! # Example
11//!
12//! ```rust
13//! use adk_core::{GenericSchemaAdapter, SchemaCache};
14//! use serde_json::json;
15//! use std::sync::Arc;
16//!
17//! let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
18//! let schema = json!({"type": "object", "properties": {"name": {"type": "string"}}});
19//!
20//! // First call normalizes and caches
21//! let result1 = cache.normalize(&schema);
22//!
23//! // Second call returns cached value without re-normalizing
24//! let result2 = cache.normalize(&schema);
25//! assert_eq!(result1, result2);
26//! ```
27
28use std::collections::HashMap;
29use std::hash::{DefaultHasher, Hash, Hasher};
30use std::sync::{Arc, Mutex};
31
32use serde_json::Value;
33
34use crate::{GenericSchemaAdapter, SchemaAdapter};
35
36/// A thread-safe cache for normalized JSON Schemas.
37///
38/// An adapter-bound cache stores normalized schemas keyed by a 64-bit hash of the
39/// input schema. Binding the adapter at construction prevents results produced by
40/// different adapter instances from sharing an entry.
41///
42/// # Thread Safety
43///
44/// Uses [`std::sync::Mutex`] internally, making it safe to share across threads.
45/// The lock is held only for the lookup and the insertion, never while the adapter
46/// normalizes, so a slow schema delays only the request that carries it.
47///
48/// # Placement
49///
50/// Intended to live on model instances so each provider adapter maintains its own
51/// cache of normalized schemas. Use [`SchemaCache::new`] for the generic adapter
52/// or [`SchemaCache::for_adapter`] for a provider-specific adapter.
53#[derive(Debug)]
54pub struct SchemaCache {
55    adapter: Arc<dyn SchemaAdapter>,
56    entries: Mutex<HashMap<CacheKey, Value>>,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60enum CacheKey {
61    Bound(u64),
62    Legacy { schema: u64, normalized: u64 },
63}
64
65/// Adds a value to the hash in a fixed order.
66///
67/// - **Object keys are sorted first.** The order they were written in cannot
68///   change the hash.
69/// - **No JSON values are cloned.** Object members are collected into a
70///   temporary `Vec` for sorting; this runs on every lookup, including hits.
71/// - **Each kind of value gets its own marker.** The text `"1"` and the number
72///   `1` hash differently.
73fn hash_canonical(value: &Value, hasher: &mut DefaultHasher) {
74    match value {
75        Value::Null => 0u8.hash(hasher),
76        Value::Bool(flag) => {
77            1u8.hash(hasher);
78            flag.hash(hasher);
79        }
80        Value::Number(number) => {
81            2u8.hash(hasher);
82            // The textual form, because it is exact in every build. Going
83            // through `as_f64` loses precision when `serde_json` is built with
84            // `arbitrary_precision`, where a literal wider than f64 is kept
85            // verbatim: distinct numbers would round together and share a cache
86            // entry, and a literal outside f64 entirely would hash to nothing.
87            number.to_string().hash(hasher);
88        }
89        Value::String(text) => {
90            3u8.hash(hasher);
91            text.hash(hasher);
92        }
93        Value::Array(items) => {
94            4u8.hash(hasher);
95            items.len().hash(hasher);
96            for item in items {
97                hash_canonical(item, hasher);
98            }
99        }
100        Value::Object(members) => {
101            5u8.hash(hasher);
102            members.len().hash(hasher);
103            let mut entries: Vec<(&String, &Value)> = members.iter().collect();
104            entries.sort_unstable_by_key(|(key, _)| *key);
105            for (key, member) in entries {
106                key.hash(hasher);
107                hash_canonical(member, hasher);
108            }
109        }
110    }
111}
112
113impl SchemaCache {
114    /// Creates an empty cache bound to [`GenericSchemaAdapter`].
115    ///
116    /// Use [`SchemaCache::for_adapter`] when normalization requires a
117    /// provider-specific adapter.
118    ///
119    /// # Example
120    ///
121    /// ```rust
122    /// use adk_core::SchemaCache;
123    /// use serde_json::json;
124    ///
125    /// let cache = SchemaCache::new();
126    /// let normalized = cache.normalize(&json!({"type": "string"}));
127    /// ```
128    pub fn new() -> Self {
129        Self::for_adapter(Arc::new(GenericSchemaAdapter))
130    }
131
132    /// Creates an empty cache bound to one schema adapter.
133    ///
134    /// The cache owns the adapter, so every entry is guaranteed to have been
135    /// produced by that adapter instance.
136    ///
137    /// # Example
138    ///
139    /// ```rust
140    /// use adk_core::{GenericSchemaAdapter, SchemaCache};
141    /// use std::sync::Arc;
142    ///
143    /// let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
144    /// assert!(cache.is_empty());
145    /// ```
146    pub fn for_adapter(adapter: Arc<dyn SchemaAdapter>) -> Self {
147        Self { adapter, entries: Mutex::new(HashMap::new()) }
148    }
149
150    /// Returns the schema normalized by this cache's adapter.
151    ///
152    /// If the same input schema has been normalized before, the cached result is
153    /// returned. Otherwise, the bound adapter normalizes the schema and the
154    /// result is stored.
155    ///
156    /// # Example
157    ///
158    /// ```rust
159    /// use adk_core::{GenericSchemaAdapter, SchemaCache};
160    /// use serde_json::json;
161    /// use std::sync::Arc;
162    ///
163    /// let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
164    /// let schema = json!({"$schema": "draft-07", "type": "string"});
165    ///
166    /// let normalized = cache.normalize(&schema);
167    /// assert!(normalized.get("$schema").is_none());
168    /// ```
169    pub fn normalize(&self, schema: &Value) -> Value {
170        let key = CacheKey::Bound(Self::hash_schema(schema));
171        if let Some(cached) = self.lock_entries().get(&key) {
172            return cached.clone();
173        }
174        // Normalized without the lock, so one slow schema does not stall every other
175        // request sharing this cache; two threads may then both normalize it once.
176        let normalized = self.adapter.normalize_schema(schema.clone());
177        self.lock_entries().entry(key).or_insert(normalized).clone()
178    }
179
180    fn lock_entries(&self) -> std::sync::MutexGuard<'_, HashMap<CacheKey, Value>> {
181        self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
182    }
183
184    /// Returns a schema normalized by the supplied adapter.
185    ///
186    /// This compatibility path normalizes before looking up the result because a
187    /// borrowed trait object has no stable identity that the cache can safely
188    /// retain. Use [`SchemaCache::for_adapter`] and [`SchemaCache::normalize`] to
189    /// avoid repeated normalization.
190    #[deprecated(
191        note = "bind the adapter with SchemaCache::for_adapter and call SchemaCache::normalize"
192    )]
193    pub fn get_or_normalize(&self, schema: &Value, adapter: &dyn SchemaAdapter) -> Value {
194        let schema_hash = Self::hash_schema(schema);
195        let normalized = adapter.normalize_schema(schema.clone());
196        let key =
197            CacheKey::Legacy { schema: schema_hash, normalized: Self::hash_schema(&normalized) };
198        self.lock_entries().entry(key).or_insert(normalized).clone()
199    }
200
201    /// Clears all cached entries.
202    ///
203    /// Call this when the set of tools changes (e.g., MCP server advertises
204    /// updated schemas) to force re-normalization on the next request.
205    ///
206    /// # Example
207    ///
208    /// ```rust
209    /// use adk_core::{GenericSchemaAdapter, SchemaCache};
210    /// use serde_json::json;
211    /// use std::sync::Arc;
212    ///
213    /// let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
214    /// let schema = json!({"type": "string"});
215    ///
216    /// // Populate cache
217    /// cache.normalize(&schema);
218    ///
219    /// // Invalidate all entries
220    /// cache.clear();
221    /// ```
222    pub fn clear(&self) {
223        self.lock_entries().clear();
224    }
225
226    /// Returns the number of cached entries.
227    pub fn len(&self) -> usize {
228        self.lock_entries().len()
229    }
230
231    /// Returns `true` if the cache contains no entries.
232    pub fn is_empty(&self) -> bool {
233        self.len() == 0
234    }
235
236    /// Computes a 64-bit hash of the schema's contents.
237    ///
238    /// Object keys are sorted before hashing, so the order they were written in
239    /// does not change the result. When `serde_json/preserve_order` is enabled,
240    /// keys stay in insertion order, and without sorting the same schema built
241    /// two different ways would occupy two entries and be normalized twice.
242    ///
243    /// Numbers are hashed as written: `5` and `5.0` are separate entries. That
244    /// costs an extra normalization and never returns the wrong schema.
245    fn hash_schema(schema: &Value) -> u64 {
246        let mut hasher = DefaultHasher::new();
247        hash_canonical(schema, &mut hasher);
248        hasher.finish()
249    }
250}
251
252impl Default for SchemaCache {
253    fn default() -> Self {
254        Self::new()
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use serde_json::json;
262    use std::sync::atomic::{AtomicUsize, Ordering};
263
264    use crate::GenericSchemaAdapter;
265
266    fn generic_cache() -> SchemaCache {
267        SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter))
268    }
269
270    #[derive(Debug)]
271    struct TaggedAdapter(&'static str);
272
273    impl SchemaAdapter for TaggedAdapter {
274        fn normalize_schema(&self, mut schema: Value) -> Value {
275            schema
276                .as_object_mut()
277                .expect("test schema should be an object")
278                .insert("normalized_by".to_string(), Value::String(self.0.to_string()));
279            schema
280        }
281    }
282
283    #[derive(Debug)]
284    struct CountingAdapter(Arc<AtomicUsize>);
285
286    impl SchemaAdapter for CountingAdapter {
287        fn normalize_schema(&self, schema: Value) -> Value {
288            self.0.fetch_add(1, Ordering::Relaxed);
289            schema
290        }
291    }
292
293    #[test]
294    fn test_cache_returns_normalized_schema() {
295        let cache = generic_cache();
296        let schema = json!({
297            "$schema": "http://json-schema.org/draft-07/schema#",
298            "type": "object",
299            "properties": { "name": { "type": "string" } }
300        });
301
302        let result = cache.normalize(&schema);
303        assert!(result.get("$schema").is_none());
304        assert_eq!(result["type"], "object");
305    }
306
307    #[test]
308    fn test_cache_returns_same_result_on_repeated_calls() {
309        let cache = generic_cache();
310        let schema = json!({
311            "type": "object",
312            "properties": { "x": { "type": "integer", "const": 42 } }
313        });
314
315        let first = cache.normalize(&schema);
316        let second = cache.normalize(&schema);
317        assert_eq!(first, second);
318    }
319
320    #[test]
321    fn repeated_calls_only_invoke_the_bound_adapter_once() {
322        let calls = Arc::new(AtomicUsize::new(0));
323        let cache = SchemaCache::for_adapter(Arc::new(CountingAdapter(Arc::clone(&calls))));
324        let schema = json!({"type": "string"});
325
326        cache.normalize(&schema);
327        cache.normalize(&schema);
328
329        assert_eq!(calls.load(Ordering::Relaxed), 1);
330    }
331
332    #[test]
333    fn adapter_instances_cannot_share_entries() {
334        let schema = json!({"type": "object"});
335        let alpha = SchemaCache::for_adapter(Arc::new(TaggedAdapter("alpha")));
336        let beta = SchemaCache::for_adapter(Arc::new(TaggedAdapter("beta")));
337
338        assert_eq!(alpha.normalize(&schema)["normalized_by"], "alpha");
339        assert_eq!(beta.normalize(&schema)["normalized_by"], "beta");
340        assert_eq!(alpha.len(), 1);
341        assert_eq!(beta.len(), 1);
342    }
343
344    #[test]
345    #[allow(deprecated)]
346    fn deprecated_api_keeps_adapter_results_separate() {
347        let cache = SchemaCache::new();
348        let schema = json!({"type": "object"});
349
350        let alpha = cache.get_or_normalize(&schema, &TaggedAdapter("alpha"));
351        let beta = cache.get_or_normalize(&schema, &TaggedAdapter("beta"));
352
353        assert_eq!(alpha["normalized_by"], "alpha");
354        assert_eq!(beta["normalized_by"], "beta");
355        assert_eq!(cache.len(), 2);
356    }
357
358    #[test]
359    fn test_cache_stores_entries() {
360        let cache = generic_cache();
361
362        assert!(cache.is_empty());
363        assert_eq!(cache.len(), 0);
364
365        let schema1 = json!({"type": "string"});
366        let schema2 = json!({"type": "number"});
367
368        cache.normalize(&schema1);
369        assert_eq!(cache.len(), 1);
370
371        cache.normalize(&schema2);
372        assert_eq!(cache.len(), 2);
373
374        // Same schema doesn't add a new entry
375        cache.normalize(&schema1);
376        assert_eq!(cache.len(), 2);
377    }
378
379    #[test]
380    fn test_cache_clear_removes_all_entries() {
381        let cache = generic_cache();
382
383        cache.normalize(&json!({"type": "string"}));
384        cache.normalize(&json!({"type": "number"}));
385        assert_eq!(cache.len(), 2);
386
387        cache.clear();
388        assert!(cache.is_empty());
389    }
390
391    #[test]
392    fn test_cache_different_schemas_produce_different_entries() {
393        let cache = generic_cache();
394
395        let schema_a = json!({"type": "string", "format": "hostname"});
396        let schema_b = json!({"type": "string", "format": "email"});
397
398        let result_a = cache.normalize(&schema_a);
399        let result_b = cache.normalize(&schema_b);
400
401        // "hostname" is stripped, "email" is preserved
402        assert!(result_a.get("format").is_none());
403        assert_eq!(result_b["format"], "email");
404        assert_eq!(cache.len(), 2);
405    }
406
407    #[test]
408    fn test_cache_new_is_empty() {
409        let cache = SchemaCache::new();
410        assert!(cache.is_empty());
411        assert_eq!(cache.len(), 0);
412    }
413
414    #[test]
415    fn test_cache_default_is_empty() {
416        let cache = SchemaCache::default();
417        assert!(cache.is_empty());
418    }
419
420    #[test]
421    fn test_cache_handles_empty_schema() {
422        let cache = generic_cache();
423        let schema = json!({});
424
425        let result = cache.normalize(&schema);
426        assert_eq!(result, json!({}));
427        assert_eq!(cache.len(), 1);
428    }
429
430    #[test]
431    fn test_cache_handles_null_schema() {
432        let cache = generic_cache();
433        let schema = Value::Null;
434
435        let result = cache.normalize(&schema);
436        // GenericSchemaAdapter passes through non-object values
437        assert_eq!(result, Value::Null);
438        assert_eq!(cache.len(), 1);
439    }
440
441    /// Two schemas differing only in key order are one schema, so they share a
442    /// cache entry rather than each paying for normalization.
443    #[test]
444    fn key_order_does_not_create_a_second_entry() {
445        let cache = generic_cache();
446
447        cache.normalize(&json!({ "type": "object", "properties": { "a": {}, "b": {} } }));
448        cache.normalize(&json!({ "properties": { "b": {}, "a": {} }, "type": "object" }));
449
450        assert_eq!(cache.len(), 1, "key order must not change a schema's identity");
451    }
452
453    #[test]
454    fn genuinely_different_schemas_keep_separate_entries() {
455        let cache = generic_cache();
456
457        cache.normalize(&json!({ "type": "string" }));
458        cache.normalize(&json!({ "type": "integer" }));
459
460        assert_eq!(cache.len(), 2);
461    }
462
463    /// A property name containing pointer or escape syntax must not collapse
464    /// two schemas onto one key.
465    #[test]
466    fn unusual_property_names_stay_distinct() {
467        let cache = generic_cache();
468
469        cache.normalize(&json!({ "properties": { "a/b": {} } }));
470        cache.normalize(&json!({ "properties": { "a~b": {} } }));
471
472        assert_eq!(cache.len(), 2);
473    }
474
475    /// Text and a number that render alike must not collide.
476    #[test]
477    fn a_string_and_a_number_hash_differently() {
478        let cache = generic_cache();
479
480        cache.normalize(&json!({ "const": "1" }));
481        cache.normalize(&json!({ "const": 1 }));
482
483        assert_eq!(cache.len(), 2);
484    }
485
486    /// Numbers are identified by their written form, so `5` and `5.0` are
487    /// different schemas.
488    ///
489    /// This also closes an `arbitrary_precision` hazard that cannot be
490    /// exercised here: with that feature a literal wider than f64 is kept
491    /// verbatim, and identifying numbers by `as_f64` would round distinct
492    /// values onto one cache entry. Without the feature `serde_json` already
493    /// collapses such literals during parsing, so reproducing it would mean
494    /// enabling the feature for every crate in the build.
495    #[test]
496    fn numbers_are_identified_by_their_written_form() {
497        let cache = generic_cache();
498
499        cache.normalize(&json!({ "const": 5 }));
500        cache.normalize(&json!({ "const": 5.0 }));
501
502        assert_eq!(cache.len(), 2);
503    }
504
505    /// Blocks normalizing any schema carrying `"slow": true` until released.
506    #[derive(Debug)]
507    struct GatedAdapter(std::sync::Mutex<std::sync::mpsc::Receiver<()>>);
508
509    impl SchemaAdapter for GatedAdapter {
510        fn normalize_schema(&self, schema: Value) -> Value {
511            if schema.get("slow").is_some() {
512                let _ = self.0.lock().map(|release| release.recv());
513            }
514            schema
515        }
516    }
517
518    #[test]
519    fn a_slow_normalization_does_not_block_other_schemas() {
520        let (release, gate) = std::sync::mpsc::channel();
521        let cache =
522            Arc::new(SchemaCache::for_adapter(Arc::new(GatedAdapter(std::sync::Mutex::new(gate)))));
523        let slow = {
524            let cache = cache.clone();
525            std::thread::spawn(move || cache.normalize(&json!({"slow": true})))
526        };
527        std::thread::sleep(std::time::Duration::from_millis(50));
528
529        let (done, finished) = std::sync::mpsc::channel();
530        let fast = {
531            let cache = cache.clone();
532            std::thread::spawn(move || {
533                let _ = done.send(cache.normalize(&json!({"type": "string"})));
534            })
535        };
536        let result = finished.recv_timeout(std::time::Duration::from_secs(5));
537        release.send(()).expect("release the slow normalization");
538        slow.join().expect("slow normalization thread");
539        fast.join().expect("fast normalization thread");
540
541        assert_eq!(result, Ok(json!({"type": "string"})));
542        assert_eq!(cache.len(), 2);
543    }
544}