schemalint 1.1.0

Static analysis tool for JSON Schema compatibility with LLM structured-output providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
use std::collections::VecDeque;
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::RwLock;

use rustc_hash::FxHasher;
use std::hash::Hasher;

use crate::normalize::NormalizedSchema;

/// Monotonic counter used to disambiguate concurrent temp-file names within
/// the same process. Combined with the PID it guarantees uniqueness across
/// threads without relying on wall-clock time.
static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);

const CACHE_VERSION: u32 = 2;
const MAX_MEMORY_ENTRIES: usize = 1000;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CacheEntry {
    schema: NormalizedSchema,
    original_bytes: Vec<u8>,
}

/// In-memory content-hash cache for normalized schemas.
///
/// The cache is cleared between CLI invocations in CLI mode; in server mode
/// it persists for the lifetime of the process via [`DiskCache`].
///
/// # Design: stored bytes as a collision guard
///
/// Every [`CacheEntry`] retains `original_bytes` — a copy of the raw JSON that
/// was normalized and stored.  On a cache hit, `get` does a byte-for-byte
/// comparison of the caller's input against these stored bytes **before**
/// returning the cached schema.
///
/// This is intentional and necessary for correctness.  The content hash is
/// computed by [`FxHasher`], a non-cryptographic hash chosen for speed.
/// Non-cryptographic hashes have non-negligible collision probability at scale.
/// Without the byte comparison, a hash collision would cause `get` to return a
/// schema that does not correspond to the caller's input — a silent wrong-result
/// bug.  The byte comparison converts a potential wrong-result into a cache miss
/// (the caller re-normalizes), at a minor memory cost: each entry stores the raw
/// bytes in addition to the normalized schema.  Dropping the bytes would require
/// replacing [`FxHasher`] with a collision-resistant (e.g. cryptographic) hash
/// and would change the correctness path — so the stored bytes are kept.
#[derive(Debug, Default)]
pub struct Cache {
    inner: std::collections::HashMap<u64, CacheEntry>,
    order: VecDeque<u64>,
}

impl Cache {
    pub fn new() -> Self {
        Self::default()
    }

    /// Look up a normalized schema by its content hash, verifying the
    /// stored raw bytes match the provided bytes to prevent cache poisoning
    /// via hash collisions.
    pub fn get(&self, hash: u64, bytes: &[u8]) -> Option<&NormalizedSchema> {
        let entry = self.inner.get(&hash)?;
        if entry.original_bytes == bytes {
            Some(&entry.schema)
        } else {
            None
        }
    }

    pub fn insert(&mut self, hash: u64, bytes: Vec<u8>, schema: NormalizedSchema) {
        let is_new = !self.inner.contains_key(&hash);
        if is_new && self.inner.len() >= MAX_MEMORY_ENTRIES {
            if let Some(oldest) = self.order.pop_front() {
                self.inner.remove(&oldest);
            }
        }
        self.inner.insert(
            hash,
            CacheEntry {
                schema,
                original_bytes: bytes,
            },
        );
        if is_new {
            self.order.push_back(hash);
        }
    }

    pub fn clear(&mut self) {
        self.inner.clear();
        self.order.clear();
    }
}

/// Persistent disk-backed cache extending the in-memory cache.
///
/// Each cache entry is stored as a separate file under the system cache
/// directory (e.g. `~/.cache/schemalint/`). A 4-byte version header is
/// prepended to every file for future migration. If the version does not
/// match, the entry is treated as a miss and overwritten.
///
/// # Design: stored bytes as a collision guard (disk layer)
///
/// Like [`Cache`], every on-disk entry serializes `original_bytes` alongside
/// the normalized schema (see [`CacheEntry`]).  `get` re-verifies the stored
/// bytes against the caller's input after deserialization for the same reason:
/// guarding against [`FxHasher`] collisions without requiring a
/// collision-resistant hash.  A mismatch is silently treated as a miss —
/// never a wrong result.
///
/// # Design: PID-isolated disk directory
///
/// The disk cache directory is namespaced by the current process ID (e.g.
/// `schemalint-<pid>/`).  This means each process maintains its **own**
/// private on-disk cache; entries written by one process are not read by
/// another.  The isolation avoids write-write conflicts between concurrent
/// `schemalint` invocations without requiring file-level advisory locks.
///
/// Cross-process cache sharing (which would increase hit rates in scenarios
/// such as repeated CI runs) is a possible future enhancement — it would
/// require per-file locking or a different concurrency strategy, and is a
/// performance trade-off, not a correctness issue.
#[derive(Debug)]
pub struct DiskCache {
    memory: RwLock<Cache>,
    cache_dir: Option<PathBuf>,
    /// Serializes eviction runs (read_dir + sort + remove) across threads so
    /// two concurrent `insert` calls cannot race on file deletion and
    /// over-evict (~2× the intended entries removed).  The cache dir is
    /// PID-isolated, so this mutex only needs to cover intra-process races.
    evict_lock: std::sync::Mutex<()>,
}

impl Default for DiskCache {
    fn default() -> Self {
        Self::new()
    }
}

impl DiskCache {
    pub fn with_cache_dir(cache_dir: PathBuf) -> Self {
        // Isolate by PID to prevent concurrent process corruption.
        // Callers needing shared caches should use file-level advisory locks.
        let isolated = cache_dir.join(format!("pid-{}", std::process::id()));
        if let Err(e) = fs::create_dir_all(&isolated) {
            eprintln!(
                "warning: failed to create cache directory '{}': {}",
                isolated.display(),
                e
            );
            return Self {
                memory: RwLock::new(Cache::new()),
                cache_dir: None,
                evict_lock: std::sync::Mutex::new(()),
            };
        }
        Self {
            memory: RwLock::new(Cache::new()),
            cache_dir: Some(isolated),
            evict_lock: std::sync::Mutex::new(()),
        }
    }

    pub fn new() -> Self {
        let candidate =
            dirs::cache_dir().map(|d| d.join(format!("schemalint-{}", std::process::id())));
        match candidate {
            Some(ref dir) => {
                if let Err(e) = fs::create_dir_all(dir) {
                    eprintln!(
                        "warning: failed to create cache directory '{}': {}",
                        dir.display(),
                        e
                    );
                    return Self {
                        memory: RwLock::new(Cache::new()),
                        cache_dir: None,
                        evict_lock: std::sync::Mutex::new(()),
                    };
                }
                Self {
                    memory: RwLock::new(Cache::new()),
                    cache_dir: candidate,
                    evict_lock: std::sync::Mutex::new(()),
                }
            }
            None => Self {
                memory: RwLock::new(Cache::new()),
                cache_dir: None,
                evict_lock: std::sync::Mutex::new(()),
            },
        }
    }

    /// Look up a normalized schema by its content hash.
    ///
    /// Checks the in-memory cache first, then falls back to the on-disk
    /// cache. Disk entries are deserialized and inserted into memory on
    /// a successful read.  The stored raw bytes are verified against
    /// `bytes` on every hit to prevent cache poisoning via hash
    /// collisions.
    pub fn get(&self, hash: u64, bytes: &[u8]) -> Option<NormalizedSchema> {
        // In-memory hit
        {
            let memory = self.memory.read().unwrap();
            if let Some(cached) = memory.get(hash, bytes) {
                return Some(cached.clone());
            }
        }

        // Disk fallback
        let dir = self.cache_dir.as_ref()?;
        let path = dir.join(format!("{:016x}.bin", hash));
        let mut file = fs::File::open(&path).ok()?;
        let mut buf = Vec::new();
        file.read_to_end(&mut buf).ok()?;
        if buf.len() < 4 {
            return None;
        }
        let version = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
        if version != CACHE_VERSION {
            return None;
        }
        let entry: CacheEntry = serde_json::from_slice(&buf[4..]).ok()?;
        if entry.original_bytes != bytes {
            return None;
        }

        // Populate memory cache for future lookups
        self.memory.write().unwrap().insert(
            hash,
            entry.original_bytes.clone(),
            entry.schema.clone(),
        );
        Some(entry.schema)
    }

    /// Insert a normalized schema into both the in-memory and on-disk caches.
    ///
    /// Disk writes are atomic: the payload is written to a uniquely-named
    /// temporary file in the same directory and then renamed into place.
    /// `fs::rename` is atomic on POSIX filesystems (same device), so a
    /// concurrent reader will see either the old complete entry or the new
    /// complete entry — never a partial write.  On any error the temp file is
    /// cleaned up and the failure is reported as a non-fatal warning (identical
    /// to the previous behaviour).
    pub fn insert(&self, hash: u64, bytes: Vec<u8>, schema: NormalizedSchema) {
        // Memory
        self.memory
            .write()
            .unwrap()
            .insert(hash, bytes.clone(), schema.clone());

        // Disk — atomic write via temp file + rename
        if let Some(ref dir) = self.cache_dir {
            let final_path = dir.join(format!("{:016x}.bin", hash));
            let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
            let tmp_name = format!("{:016x}.bin.tmp.{}.{}", hash, std::process::id(), counter);
            let tmp_path = dir.join(&tmp_name);

            let mut buf = Vec::new();
            buf.extend_from_slice(&CACHE_VERSION.to_le_bytes());
            let entry = CacheEntry {
                schema,
                original_bytes: bytes,
            };
            match serde_json::to_vec(&entry) {
                Ok(serialized) => {
                    buf.extend_from_slice(&serialized);
                    // Write to temp file first.
                    if let Err(e) = fs::write(&tmp_path, &buf) {
                        eprintln!(
                            "warning: failed to write cache temp file '{}': {}",
                            tmp_path.display(),
                            e
                        );
                        // Attempt cleanup of any partially-written temp file.
                        let _ = fs::remove_file(&tmp_path);
                    } else {
                        // Atomically publish the entry.
                        if let Err(e) = fs::rename(&tmp_path, &final_path) {
                            eprintln!(
                                "warning: failed to rename cache file '{}' -> '{}': {}",
                                tmp_path.display(),
                                final_path.display(),
                                e
                            );
                            // Clean up orphaned temp file so it doesn't
                            // accumulate or confuse evict_if_needed.
                            let _ = fs::remove_file(&tmp_path);
                        }
                    }
                }
                Err(e) => {
                    eprintln!("warning: failed to serialize schema for cache: {}", e);
                }
            }
            self.evict_if_needed(dir);
        }
    }

    /// Returns the resolved cache directory path, if one was configured.
    ///
    /// Exposed for testing so tests can inspect directory contents without
    /// re-deriving the PID-namespaced path.
    #[cfg(test)]
    pub(crate) fn cache_dir(&self) -> Option<&PathBuf> {
        self.cache_dir.as_ref()
    }

    fn evict_if_needed(&self, dir: &PathBuf) {
        // Serialize the entire read-dir / sort / remove sequence so that two
        // concurrent inserts cannot both independently trim to the cap and
        // together remove ~2× the intended number of entries.
        // Poison tolerance: if a previous holder panicked inside this function
        // we still get the inner guard rather than propagating a poison error.
        let _guard = self.evict_lock.lock().unwrap_or_else(|e| e.into_inner());

        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(e) => {
                eprintln!(
                    "warning: failed to read cache directory '{}': {}",
                    dir.display(),
                    e
                );
                return;
            }
        };
        let mut files: Vec<(fs::DirEntry, std::time::SystemTime)> = Vec::new();
        for entry in entries.filter_map(|e| e.ok()) {
            // Only count and evict real cache entries — files ending in ".bin"
            // and NOT containing ".tmp." (the atomic-write temp-file suffix).
            // A transient temp file must never be counted toward the eviction
            // limit or mistakenly removed mid-write by a concurrent rename.
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if !name_str.ends_with(".bin") || name_str.contains(".tmp.") {
                continue;
            }
            let Ok(meta) = entry.metadata() else { continue };
            let Ok(mtime) = meta.modified() else { continue };
            files.push((entry, mtime));
        }
        if files.len() > 1000 {
            files.sort_by_key(|a| a.1);
            let to_remove = files.len() - 1000;
            for (entry, _) in files.into_iter().take(to_remove) {
                if let Err(e) = fs::remove_file(entry.path()) {
                    eprintln!("warning: failed to remove stale cache file: {}", e);
                }
            }
        }
    }
}

/// Compute a fast hash of raw JSON bytes for cache keys.
pub fn hash_bytes(bytes: &[u8]) -> u64 {
    let mut hasher = FxHasher::default();
    hasher.write(bytes);
    hasher.finish()
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    /// Build a minimal valid `NormalizedSchema` without duplicating the
    /// normalizer internals.  `true` is a valid boolean JSON Schema that
    /// passes through the full pipeline.
    fn make_schema() -> NormalizedSchema {
        crate::normalize::normalize(serde_json::Value::Bool(true))
            .expect("normalizing `true` must succeed")
    }

    /// Serialise schema bytes the same way the production code does so that
    /// hash_bytes produces a stable key we can use in tests.
    fn schema_bytes(val: &serde_json::Value) -> Vec<u8> {
        serde_json::to_vec(val).expect("serialization of test value must succeed")
    }

    // -----------------------------------------------------------------------
    // 1. Insert → get round-trip via disk
    // -----------------------------------------------------------------------

    /// Verify that a schema written by one `DiskCache` instance can be
    /// retrieved by a *second* instance pointing at the same directory.
    ///
    /// Using a fresh instance guarantees the warm-memory path is bypassed and
    /// the actual disk read is exercised.
    #[test]
    fn test_disk_round_trip() {
        let tmp = TempDir::new().unwrap();
        let raw = serde_json::json!({"type": "string"});
        let bytes = schema_bytes(&raw);
        let hash = hash_bytes(&bytes);
        let schema = make_schema();

        // Insert via the first instance.
        let cache1 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        cache1.insert(hash, bytes.clone(), schema);

        // Retrieve via a second instance — memory cache is cold.
        let cache2 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let result = cache2.get(hash, &bytes);
        assert!(
            result.is_some(),
            "disk round-trip: expected a cache hit on the second DiskCache instance"
        );
    }

    /// A collision-prevention check: the same hash with *different* bytes must
    /// not return a hit (the entry stores the original bytes and verifies them).
    #[test]
    fn test_disk_round_trip_collision_rejected() {
        let tmp = TempDir::new().unwrap();
        let raw = serde_json::json!({"type": "string"});
        let bytes = schema_bytes(&raw);
        let hash = hash_bytes(&bytes);
        let schema = make_schema();

        let cache1 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        cache1.insert(hash, bytes.clone(), schema);

        let different_bytes = schema_bytes(&serde_json::json!({"type": "integer"}));
        let cache2 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let result = cache2.get(hash, &different_bytes);
        assert!(
            result.is_none(),
            "collision guard: bytes mismatch must result in a cache miss"
        );
    }

    // -----------------------------------------------------------------------
    // 2. Atomic rename leaves no .tmp files behind
    // -----------------------------------------------------------------------

    /// After a successful insert the cache directory must contain exactly the
    /// final `.bin` file; no `.tmp` artefacts should remain.
    #[test]
    fn test_atomic_write_no_tmp_files_remain() {
        let tmp = TempDir::new().unwrap();
        let raw = serde_json::json!({"type": "object"});
        let bytes = schema_bytes(&raw);
        let hash = hash_bytes(&bytes);
        let schema = make_schema();

        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        cache.insert(hash, bytes, schema);

        // The cache dir is PID-namespaced; use the accessor to get the real path.
        let cache_dir = cache.cache_dir().expect("cache dir must be set");
        let entries: Vec<_> = fs::read_dir(cache_dir)
            .expect("read_dir must succeed")
            .filter_map(|e| e.ok())
            .collect();

        let tmp_files: Vec<_> = entries
            .iter()
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .collect();

        assert!(
            tmp_files.is_empty(),
            "expected no leftover .tmp files after successful insert, found: {:?}",
            tmp_files.iter().map(|e| e.file_name()).collect::<Vec<_>>()
        );

        // Also assert the final file was written.
        let bin_files: Vec<_> = entries
            .iter()
            .filter(|e| e.file_name().to_string_lossy().ends_with(".bin"))
            .collect();
        assert_eq!(
            bin_files.len(),
            1,
            "expected exactly one .bin cache file, found {:?}",
            bin_files.iter().map(|e| e.file_name()).collect::<Vec<_>>()
        );
    }

    // -----------------------------------------------------------------------
    // 3. Eviction trims the disk cache to ≤ 1000 entries
    // -----------------------------------------------------------------------

    /// Insert 1 001 distinct entries so `evict_if_needed` runs and must trim
    /// the directory back to exactly 1 000 files.
    ///
    /// Uniqueness of each entry is ensured by embedding the index into both
    /// the bytes (so `hash_bytes` produces a different key) and the raw JSON
    /// value used to look it up.  No wall-clock calls are made; the ordering
    /// used by eviction is filesystem mtime which is non-deterministic at
    /// millisecond granularity, so we only assert the *count* post-eviction.
    #[test]
    fn test_eviction_trims_to_limit() {
        let tmp = TempDir::new().unwrap();
        // Use a *shared* base dir; with_cache_dir appends `pid-<pid>` so all
        // inserts land in the same subdirectory.
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let cache_dir = cache.cache_dir().expect("cache dir must be set").clone();

        let total = 1_001usize;
        for i in 0..total {
            // Embed the index so every entry has a distinct hash.
            let raw = serde_json::json!({"__test_index": i});
            let bytes = schema_bytes(&raw);
            let hash = hash_bytes(&bytes);
            let schema = make_schema();
            // Insert directly; each call triggers evict_if_needed at the end,
            // which is correct — we want to exercise the trim path.
            cache.insert(hash, bytes, schema);
        }

        let file_count = fs::read_dir(&cache_dir)
            .expect("read_dir must succeed")
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().ends_with(".bin"))
            .count();

        assert_eq!(
            file_count, 1_000,
            "eviction must trim disk cache to exactly 1 000 entries, found {}",
            file_count
        );
    }

    // -----------------------------------------------------------------------
    // 4. In-memory Cache — direct get/insert/eviction paths
    // -----------------------------------------------------------------------

    /// `Cache::get` on an empty cache must return `None`.
    #[test]
    fn test_memory_cache_get_miss_absent_hash() {
        let cache = Cache::new();
        let bytes = b"hello";
        let result = cache.get(0xdeadbeef, bytes);
        assert!(result.is_none(), "get on absent hash must return None");
    }

    /// `Cache::get` with the correct hash but mismatched bytes must return
    /// `None` (collision guard in the in-memory layer).
    #[test]
    fn test_memory_cache_get_miss_bytes_mismatch() {
        let mut cache = Cache::new();
        let bytes_a = b"schema-a".to_vec();
        let hash = hash_bytes(&bytes_a);
        cache.insert(hash, bytes_a, make_schema());

        // Same hash, different bytes — must be rejected.
        let result = cache.get(hash, b"schema-b");
        assert!(
            result.is_none(),
            "bytes mismatch must result in None even when hash matches"
        );
    }

    /// `Cache::get` returns the schema when hash AND bytes both match.
    #[test]
    fn test_memory_cache_get_hit() {
        let mut cache = Cache::new();
        let bytes = b"schema-x".to_vec();
        let hash = hash_bytes(&bytes);
        cache.insert(hash, bytes.clone(), make_schema());

        let result = cache.get(hash, &bytes);
        assert!(result.is_some(), "get with matching hash+bytes must hit");
    }

    /// Re-inserting the same hash must update the stored schema and must not
    /// grow the `order` deque (dedup of is_new check).
    #[test]
    fn test_memory_cache_reinsertion_does_not_grow_order() {
        let mut cache = Cache::new();
        let bytes = b"same".to_vec();
        let hash = hash_bytes(&bytes);
        cache.insert(hash, bytes.clone(), make_schema());
        let order_len_after_first = cache.order.len();
        // Insert again with the same hash.
        cache.insert(hash, bytes.clone(), make_schema());
        assert_eq!(
            cache.order.len(),
            order_len_after_first,
            "re-inserting an existing hash must not append to the order deque"
        );
        // The entry must still be reachable.
        assert!(cache.get(hash, &bytes).is_some());
    }

    /// When MAX_MEMORY_ENTRIES + 1 entries are inserted the LRU entry (first
    /// inserted) must be evicted from `inner` AND removed from `order`.
    #[test]
    fn test_memory_cache_lru_eviction() {
        let mut cache = Cache::new();

        // Insert the sentinel entry first.
        let sentinel_bytes = b"sentinel".to_vec();
        let sentinel_hash = hash_bytes(&sentinel_bytes);
        cache.insert(sentinel_hash, sentinel_bytes.clone(), make_schema());

        // Fill up to the limit (one slot is already taken by the sentinel).
        for i in 0..MAX_MEMORY_ENTRIES {
            let bytes = format!("entry-{}", i).into_bytes();
            let hash = hash_bytes(&bytes);
            cache.insert(hash, bytes, make_schema());
        }

        // The in-memory map now has MAX_MEMORY_ENTRIES + 1 entries, but the
        // last insert must have triggered eviction, removing the sentinel.
        assert!(
            cache.get(sentinel_hash, &sentinel_bytes).is_none(),
            "sentinel entry must have been evicted after MAX_MEMORY_ENTRIES overflow"
        );
        // Total size must be capped at the limit.
        assert_eq!(
            cache.inner.len(),
            MAX_MEMORY_ENTRIES,
            "inner map size must equal MAX_MEMORY_ENTRIES after eviction"
        );
    }

    /// `Cache::clear` must remove all entries and allow no further hits.
    #[test]
    fn test_memory_cache_clear() {
        let mut cache = Cache::new();
        let bytes = b"to-be-cleared".to_vec();
        let hash = hash_bytes(&bytes);
        cache.insert(hash, bytes.clone(), make_schema());
        assert!(
            cache.get(hash, &bytes).is_some(),
            "pre-clear: must be a hit"
        );

        cache.clear();

        assert!(
            cache.get(hash, &bytes).is_none(),
            "post-clear: must be a miss"
        );
        assert!(
            cache.inner.is_empty(),
            "inner map must be empty after clear"
        );
        assert!(
            cache.order.is_empty(),
            "order deque must be empty after clear"
        );
    }

    // -----------------------------------------------------------------------
    // 5. with_cache_dir — graceful degradation when the path is unusable
    // -----------------------------------------------------------------------

    /// If `with_cache_dir` receives a path that cannot be created as a
    /// directory (because the parent is actually a regular file), it must
    /// return a `DiskCache` whose `cache_dir()` is `None` — the memory-only
    /// fallback.
    #[test]
    fn test_with_cache_dir_fallback_when_path_is_file() {
        let tmp = TempDir::new().unwrap();
        // Create a regular FILE where we want to use as a base directory.
        let file_path = tmp.path().join("not_a_dir");
        fs::write(&file_path, b"I am a file").expect("write must succeed");

        // Pass the file as the cache dir — `with_cache_dir` will attempt
        // `create_dir_all(file_path/pid-<pid>)` which must fail because the
        // path component `file_path` is a file, not a directory.
        let cache = DiskCache::with_cache_dir(file_path);
        assert!(
            cache.cache_dir().is_none(),
            "cache_dir must be None when directory creation fails"
        );

        // The fallback cache must still be usable in memory-only mode.
        let bytes = b"mem-only".to_vec();
        let hash = hash_bytes(&bytes);
        cache.insert(hash, bytes.clone(), make_schema());
        assert!(
            cache.get(hash, &bytes).is_some(),
            "memory-only fallback must still return hits"
        );
    }

    // -----------------------------------------------------------------------
    // 6. Disk read — CACHE_VERSION mismatch treated as miss
    // -----------------------------------------------------------------------

    /// Write a cache file with a wrong version prefix (99) into the cache
    /// directory and assert that `DiskCache::get` treats it as a miss.
    #[test]
    fn test_disk_get_version_mismatch_is_miss() {
        let tmp = TempDir::new().unwrap();
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let cache_dir = cache.cache_dir().expect("cache dir must be set").clone();

        let raw = serde_json::json!({"type": "boolean"});
        let bytes = schema_bytes(&raw);
        let hash = hash_bytes(&bytes);

        // Write the file manually with a wrong version (99 instead of CACHE_VERSION).
        let bad_version: u32 = 99;
        let mut buf = bad_version.to_le_bytes().to_vec();
        let schema = make_schema();
        let entry = CacheEntry {
            schema,
            original_bytes: bytes.clone(),
        };
        buf.extend_from_slice(&serde_json::to_vec(&entry).unwrap());
        let path = cache_dir.join(format!("{:016x}.bin", hash));
        fs::write(&path, &buf).expect("manual write must succeed");

        // A fresh DiskCache pointing at the same base dir must see a miss.
        let cache2 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let result = cache2.get(hash, &bytes);
        assert!(
            result.is_none(),
            "a disk entry with a wrong CACHE_VERSION must be treated as a miss"
        );
    }

    // -----------------------------------------------------------------------
    // 7. Disk read — file shorter than 4 bytes treated as miss
    // -----------------------------------------------------------------------

    /// Write a 3-byte file into the cache directory and assert that `get`
    /// returns `None` (the `buf.len() < 4` guard at line 159).
    #[test]
    fn test_disk_get_truncated_file_is_miss() {
        let tmp = TempDir::new().unwrap();
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let cache_dir = cache.cache_dir().expect("cache dir must be set").clone();

        let bytes = b"truncated-file-test".to_vec();
        let hash = hash_bytes(&bytes);
        let path = cache_dir.join(format!("{:016x}.bin", hash));
        // Only 3 bytes — too short to hold the 4-byte version prefix.
        fs::write(&path, &[0x01u8, 0x02, 0x03]).expect("write must succeed");

        let cache2 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let result = cache2.get(hash, &bytes);
        assert!(
            result.is_none(),
            "a file shorter than 4 bytes must be treated as a miss"
        );
    }

    // -----------------------------------------------------------------------
    // 8. Disk read — correct version but invalid JSON payload treated as miss
    // -----------------------------------------------------------------------

    /// Write a file with the correct 4-byte version prefix followed by garbage
    /// bytes that are not valid JSON. `serde_json::from_slice` must fail and
    /// `get` must return `None`.
    #[test]
    fn test_disk_get_corrupt_json_is_miss() {
        let tmp = TempDir::new().unwrap();
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let cache_dir = cache.cache_dir().expect("cache dir must be set").clone();

        let bytes = b"corrupt-json-test".to_vec();
        let hash = hash_bytes(&bytes);
        let path = cache_dir.join(format!("{:016x}.bin", hash));

        let mut buf = CACHE_VERSION.to_le_bytes().to_vec();
        buf.extend_from_slice(b"not valid json !!!");
        fs::write(&path, &buf).expect("write must succeed");

        let cache2 = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let result = cache2.get(hash, &bytes);
        assert!(
            result.is_none(),
            "a disk entry with corrupt JSON must be treated as a miss"
        );
    }

    // -----------------------------------------------------------------------
    // 9. Disk get on a hash that was never inserted → miss
    // -----------------------------------------------------------------------

    /// A fresh `DiskCache` has no file on disk for the requested hash;
    /// `File::open` returns `Err` and `get` returns `None`.
    #[test]
    fn test_disk_get_absent_entry_is_miss() {
        let tmp = TempDir::new().unwrap();
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());

        let bytes = b"never-written".to_vec();
        let hash = hash_bytes(&bytes);

        let result = cache.get(hash, &bytes);
        assert!(
            result.is_none(),
            "a hash that was never inserted must be a miss"
        );
    }

    // -----------------------------------------------------------------------
    // 10. rename failure path — pre-existing directory at the target path
    // -----------------------------------------------------------------------

    /// Create a directory at the location that `insert` would use for the
    /// final `.bin` file. The atomic rename (tmp → final) must fail, the
    /// warning must be non-fatal, and the `.tmp.` file must be cleaned up.
    #[test]
    fn test_disk_insert_rename_failure_cleans_up_tmp() {
        let tmp = TempDir::new().unwrap();
        let cache = DiskCache::with_cache_dir(tmp.path().to_path_buf());
        let cache_dir = cache.cache_dir().expect("cache dir must be set").clone();

        let raw = serde_json::json!({"type": "null"});
        let bytes = schema_bytes(&raw);
        let hash = hash_bytes(&bytes);

        // Pre-create a directory at the exact path `insert` would rename into.
        let final_path = cache_dir.join(format!("{:016x}.bin", hash));
        fs::create_dir_all(&final_path).expect("creating dir as rename target must succeed");

        // `insert` must not panic; the rename will fail (target is a dir),
        // and the temp file must be cleaned up.
        cache.insert(hash, bytes, make_schema());

        // No orphaned .tmp. files must remain.
        let tmp_count = fs::read_dir(&cache_dir)
            .expect("read_dir must succeed")
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
            .count();
        assert_eq!(
            tmp_count, 0,
            "rename failure must not leave orphaned .tmp files"
        );

        // The pre-existing directory must still be present (we did not remove it).
        assert!(
            final_path.is_dir(),
            "pre-existing directory at final path must still exist"
        );
    }
}