Skip to main content

poly_kv/
fallback.rs

1use crate::codec::{CompressedBlock, ExactFallbackCodec, KVecCodec};
2use crate::error::Result;
3
4/// Exact (uncompressed) fallback storage for verification and debug.
5///
6/// Stores raw f32 KV vectors without any compression. Used to verify
7/// that the compression/decompression paths are correct.
8pub struct ExactFallbackStore {
9    /// The codec (always ExactFallbackCodec).
10    codec: ExactFallbackCodec,
11}
12
13impl ExactFallbackStore {
14    /// Create a new exact fallback store for the given head dimension.
15    pub fn new(head_dim: usize) -> Self {
16        Self {
17            codec: ExactFallbackCodec::new(head_dim),
18        }
19    }
20
21    /// Encode a key/value vector into a CompressedBlock (no actual compression).
22    pub fn encode_block(&self, vector: &[f32], _seed: u64) -> Result<CompressedBlock> {
23        let encoded = self.codec.encode(vector, 0)?;
24        Ok(CompressedBlock::new(
25            self.codec.codec_id(),
26            encoded,
27            vector.len(),
28        ))
29    }
30
31    /// Decode a CompressedBlock back to the original f32 vector.
32    pub fn decode_block(&self, block: &CompressedBlock) -> Result<Vec<f32>> {
33        self.codec.decode(&block.encoded_payload, 0)
34    }
35
36    /// Verify that encoding then decoding produces the original vector.
37    pub fn verify_roundtrip(&self, original: &[f32], _seed: u64) -> Result<bool> {
38        let decoded = self.decode_block(&self.encode_block(original, 0)?)?;
39        Ok(original
40            .iter()
41            .zip(decoded.iter())
42            .all(|(a, b)| (a - b).abs() < 1e-6))
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_exact_fallback_roundtrip() {
52        let store = ExactFallbackStore::new(8);
53        let vec: Vec<f32> = vec![0.5, -0.25, 0.75, 1.0, -1.0, 0.1, 0.9, -0.5];
54        let block = store.encode_block(&vec, 0).unwrap();
55        let decoded = store.decode_block(&block).unwrap();
56        assert_eq!(vec, decoded);
57    }
58
59    #[test]
60    fn test_exact_fallback_dimension_mismatch() {
61        let store = ExactFallbackStore::new(8);
62        let vec: Vec<f32> = vec![0.1, 0.2, 0.3]; // wrong size
63        let result = store.encode_block(&vec, 0);
64        assert!(result.is_err());
65    }
66}