realizar 0.8.4

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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

    #[test]
    fn test_cov_fragmentation_stats_trailing_free_region() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Allocate only at the beginning
        let seq = cache.allocate_sequence(16).expect("alloc");
        cache.update_tokens(seq, 16).expect("update");

        let stats = cache.fragmentation_stats();
        // Large trailing free region
        assert_eq!(stats.largest_free_region, 99);
    }

    // --- Test should_defragment conditions ---

    #[test]
    fn test_cov_should_defragment_waste_ratio_trigger() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Create multiple sequences with low fill rates
        for _ in 0..10 {
            let seq = cache.allocate_sequence(32).expect("alloc"); // 2 pages each
            // Only fill 1 token per sequence (high waste)
            cache.update_tokens(seq, 1).expect("update");
        }

        // Free some to create holes
        // This creates: used pages with low fill rate + holes
        // The waste_ratio check requires holes > 2
        let stats = cache.fragmentation_stats();
        let _ = stats; // Stats computed, code path covered
    }

    #[test]
    fn test_cov_should_defragment_low_free_with_holes() {
        let mut cache = PagedKvCache::new(10, 16, 8, 64);

        // Allocate 9 sequences (90% full)
        let mut seqs = Vec::new();
        for _ in 0..9 {
            seqs.push(cache.allocate_sequence(16).expect("alloc"));
        }

        // Free one in the middle to create a hole
        cache.free_sequence(seqs[4]);

        // At 90% full with a hole, free_ratio < 0.1 and holes > 0
        let should = cache.should_defragment();
        // The actual result depends on exact conditions
        let _ = should;
    }

    // --- Test quantization edge cases ---

    #[test]
    fn test_cov_quantized_kv_data_write_beyond_capacity() {
        let mut data = QuantizedKvData::new(KvQuantType::FP32, 4, 2, 4); // Small: 4*2*4=32 elements

        // Try to write data larger than capacity
        let large_data: Vec<f32> = (0..100).map(|i| i as f32).collect();
        data.write_keys(0, &large_data);

        // Should truncate to capacity
        let read = data.read_keys(0, 100);
        assert!(read.len() <= 32);
    }

    #[test]
    fn test_cov_quantized_kv_data_read_beyond_capacity() {
        let data = QuantizedKvData::new(KvQuantType::FP32, 4, 2, 4);

        // Try to read beyond capacity
        let read = data.read_keys(0, 1000);
        assert!(read.len() <= 32);
    }

    #[test]
    fn test_cov_q8_write_spanning_multiple_blocks() {
        let mut data = QuantizedKvData::new(KvQuantType::Q8, 16, 8, 64);

        // Write data that spans multiple quantization blocks
        let test_data: Vec<f32> = (0..200).map(|i| (i as f32 - 100.0) * 0.01).collect();
        data.write_keys(50, &test_data);

        // Read back
        let read = data.read_keys(50, 200);
        assert_eq!(read.len(), 200);
    }

    #[test]
    fn test_cov_q4_write_spanning_multiple_blocks() {
        let mut data = QuantizedKvData::new(KvQuantType::Q4, 16, 8, 64);

        // Write data spanning blocks
        let test_data: Vec<f32> = (0..100).map(|i| (i as f32 - 50.0) * 0.05).collect();
        data.write_values(30, &test_data);

        let read = data.read_values(30, 100);
        assert_eq!(read.len(), 100);
    }

    #[test]
    fn test_cov_quantized_page_write_at_different_positions() {
        let mut page = QuantizedKvPage::new(PageId::new(0), KvQuantType::Q8, 16, 8, 64);

        // Write to multiple token positions
        for pos in 0..4 {
            let keys: Vec<f32> = (0..512).map(|i| (i + pos * 100) as f32 * 0.001).collect();
            page.write_keys(pos, &keys);
            page.num_tokens = pos + 1;
        }

        // Read back from each position
        for pos in 0..4 {
            let read = page.read_keys(pos);
            assert_eq!(read.len(), 512);
        }
    }

    // --- Test quantized cache operations ---

    #[test]
    fn test_cov_quantized_cache_get_page_mut_not_found() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);
        let fake_seq = SeqId::new();

        let result = cache.get_page_mut(fake_seq, 0);
        assert!(matches!(result, Err(PagedCacheError::SequenceNotFound(_))));
    }

    #[test]
    fn test_cov_quantized_cache_fp32_operations() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::FP32);
        let seq_id = cache.allocate_sequence(32).expect("alloc");

        // Get pages and write data
        {
            let page = cache.get_page_mut(seq_id, 0).expect("get");
            let keys: Vec<f32> = (0..512).map(|i| i as f32).collect();
            page.write_keys(0, &keys);
            page.num_tokens = 1;
        }

        // Read back
        let page = cache.get_page(seq_id, 0).expect("get_read");
        let read_keys = page.read_keys(0);
        assert_eq!(read_keys[0], 0.0);
        assert_eq!(read_keys[1], 1.0);
    }

    #[test]
    fn test_cov_quantized_cache_q4_operations() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q4);
        let seq_id = cache.allocate_sequence(16).expect("alloc");

        {
            let page = cache.get_page_mut(seq_id, 0).expect("get");
            let values: Vec<f32> = (0..512).map(|i| (i as f32 - 256.0) * 0.01).collect();
            page.write_values(0, &values);
        }

        let page = cache.get_page(seq_id, 0).expect("read");
        let read = page.read_values(0);
        assert_eq!(read.len(), 512);
    }

    // --- Test prefix cache LRU with all referenced entries ---

    #[test]
    fn test_cov_prefix_cache_evict_lru_all_referenced() {
        let mut cache = PrefixCache::new(2);

        // Insert with ref_count = 1 (default)
        cache.insert(CachedPrefix::new(1, 1, vec![]));
        cache.insert(CachedPrefix::new(2, 2, vec![]));

        assert_eq!(cache.len(), 2);

        // Both have ref_count = 1, so eviction won't find anything
        // Try to insert third
        let inserted = cache.insert(CachedPrefix::new(3, 3, vec![]));
        assert!(!inserted);
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_cov_prefix_cache_insert_existing_hash() {
        let mut cache = PrefixCache::new(10);

        // Insert initial
        cache.insert(CachedPrefix::new(42, 5, vec![]));
        assert_eq!(cache.len(), 1);

        // Insert same hash - should overwrite
        cache.insert(CachedPrefix::new(42, 10, vec![PageId::new(0)]));
        assert_eq!(cache.len(), 1);

        // Verify it was updated
        let lookup = cache.lookup(42);
        assert!(lookup.is_some());
        assert_eq!(lookup.unwrap().num_tokens, 10);
    }

    // --- Test memory calculations ---

    #[test]
    fn test_cov_memory_usage_multiple_sequences() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);

        // Allocate multiple sequences
        for _ in 0..5 {
            let _ = cache.allocate_sequence(32).expect("alloc");
        }

        let usage = cache.memory_usage();
        let capacity = cache.total_capacity();

        // Usage should be 10% of capacity (10 pages out of 100)
        assert_eq!(usage * 10, capacity);
    }

    #[test]
    fn test_cov_quantized_memory_usage_after_free() {
        let mut cache = QuantizedPagedKvCache::new(100, 16, 8, 64, KvQuantType::Q8);

        let seq1 = cache.allocate_sequence(16).expect("alloc1");
        let seq2 = cache.allocate_sequence(16).expect("alloc2");

        let usage_before = cache.memory_usage();
        cache.free_sequence(seq1);
        let usage_after = cache.memory_usage();

        // Usage should decrease after freeing
        assert!(usage_after < usage_before);

        // Free second sequence
        cache.free_sequence(seq2);
        let usage_final = cache.memory_usage();
        assert_eq!(usage_final, 0);
    }

    // --- Test CachedPrefix serialization ---

    #[test]
    fn test_cov_cached_prefix_serialization() {
        let prefix = CachedPrefix::new(12345, 10, vec![PageId::new(0), PageId::new(1)]);

        let json = serde_json::to_string(&prefix).expect("serialize");
        let parsed: CachedPrefix = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(parsed.hash, 12345);
        assert_eq!(parsed.num_tokens, 10);
        assert_eq!(parsed.page_ids.len(), 2);
    }

    // --- Test tokens_to_pages edge cases ---

    #[test]
    fn test_cov_tokens_to_pages_various_sizes() {
        let cache = PagedKvCache::new(100, 16, 8, 64);

        // These trigger tokens_to_pages internally
        assert!(cache.free_page_count() == 100);

        // Allocate with various token counts to test div_ceil
        let mut cache2 = PagedKvCache::new(100, 16, 8, 64);
        let _ = cache2.allocate_sequence(1); // 1 token -> 1 page
        assert_eq!(cache2.free_page_count(), 99);

        let _ = cache2.allocate_sequence(16); // 16 tokens -> 1 page
        assert_eq!(cache2.free_page_count(), 98);

        let _ = cache2.allocate_sequence(17); // 17 tokens -> 2 pages
        assert_eq!(cache2.free_page_count(), 96);

        let _ = cache2.allocate_sequence(32); // 32 tokens -> 2 pages
        assert_eq!(cache2.free_page_count(), 94);

        let _ = cache2.allocate_sequence(33); // 33 tokens -> 3 pages
        assert_eq!(cache2.free_page_count(), 91);
    }

    // --- Test is_page_free ---

    #[test]
    fn test_cov_is_page_free_verification() {
        let mut cache = PagedKvCache::new(10, 16, 8, 64);

        // Initially all pages are free
        let seq = cache.allocate_sequence(16).expect("alloc");

        // After allocation, some pages are not free
        cache.free_sequence(seq);

        // After free, pages return to free list
        assert_eq!(cache.free_page_count(), 10);
    }

    // --- Test fragmentation ratio capping ---

    #[test]
    fn test_cov_fragmentation_ratio_max_one() {
        let mut cache = PagedKvCache::new(5, 16, 8, 64);

        // Create a very fragmented scenario
        let seq1 = cache.allocate_sequence(16).expect("s1");
        let seq2 = cache.allocate_sequence(16).expect("s2");
        let seq3 = cache.allocate_sequence(16).expect("s3");

        cache.free_sequence(seq2);

        let stats = cache.fragmentation_stats();
        // Ratio should be capped at 1.0
        assert!(stats.fragmentation_ratio <= 1.0);

        // Clean up
        cache.free_sequence(seq1);
        cache.free_sequence(seq3);
    }

    // --- Test compact sequence with single page ---

    #[test]
    fn test_cov_compact_single_page_sequence() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq = cache.allocate_sequence(10).expect("alloc"); // Single page

        // Single page sequence is always contiguous
        let moved = cache.compact_sequence(seq);
        assert_eq!(moved, 0);
    }

    // --- Test update_tokens edge case - tokens fewer than block_size ---

    #[test]
    fn test_cov_update_tokens_exact_block_boundary() {
        let mut cache = PagedKvCache::new(100, 16, 8, 64);
        let seq = cache.allocate_sequence(32).expect("alloc"); // 2 pages

        // Update to exactly block_size
        cache.update_tokens(seq, 16).expect("update");
        assert_eq!(cache.get_sequence_tokens(seq).expect("get"), 16);

        // Update to exactly 2 * block_size
        cache.update_tokens(seq, 32).expect("update2");
        assert_eq!(cache.get_sequence_tokens(seq).expect("get2"), 32);
    }

    // --- Test QuantizedKvPage is_shared ---

    #[test]
    fn test_cov_quantized_kv_page_shared_state() {
        let mut page = QuantizedKvPage::new(PageId::new(0), KvQuantType::Q8, 16, 8, 64);

        assert!(!page.is_shared()); // ref_count = 0 initially

        page.ref_count = 1;
        assert!(!page.is_shared()); // ref_count = 1 is not shared

        page.ref_count = 2;
        assert!(page.is_shared()); // ref_count > 1 is shared
    }

    // --- Test KvQuantType Display/Debug coverage via serialization ---

    #[test]
    fn test_cov_kv_quant_type_serialization() {
        for quant in [KvQuantType::FP32, KvQuantType::Q8, KvQuantType::Q4] {
            let json = serde_json::to_string(&quant).expect("serialize");
            let parsed: KvQuantType = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(parsed, quant);
        }
    }

    // --- Test compute_prefix_hash with longer sequences ---

    #[test]
    fn test_cov_compute_prefix_hash_collision_resistance() {
        // Different sequences should produce different hashes (with high probability)
        let hashes: Vec<u64> = (0..100)
            .map(|i| {
                let tokens: Vec<u32> = (0..=i).map(|j| j as u32).collect();
                compute_prefix_hash(&tokens)
            })
            .collect();

        // Check for uniqueness
        let mut unique = hashes.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(unique.len(), hashes.len(), "All hashes should be unique");
    }

    // --- Test find_longest_prefix with various scenarios ---

    #[test]
    fn test_cov_find_longest_prefix_empty_tokens() {
        let mut cache = PrefixCache::new(100);

        let result = find_longest_prefix(&mut cache, &[]);
        assert!(result.is_none());
    }

    #[test]
    fn test_cov_find_longest_prefix_single_token() {
        let mut cache = PrefixCache::new(100);

        let hash = compute_prefix_hash(&[42]);
        cache.insert(CachedPrefix::new(hash, 1, vec![]));

        let result = find_longest_prefix(&mut cache, &[42, 43, 44]);
        assert!(result.is_some());
        let (found_hash, len) = result.unwrap();
        assert_eq!(found_hash, hash);
        assert_eq!(len, 1);
    }

    // --- Test PagedCacheError fields ---

    #[test]
    fn test_cov_error_out_of_memory_fields() {
        let err = PagedCacheError::OutOfMemory {
            needed: 100,
            available: 5,
        };
        let msg = err.to_string();
        assert!(msg.contains("100"));
        assert!(msg.contains("5"));
    }

    #[test]
    fn test_cov_error_invalid_page_access_fields() {
        let err = PagedCacheError::InvalidPageAccess {
            page_id: 42,
            offset: 999,
        };
        let msg = err.to_string();
        assert!(msg.contains("42"));
        assert!(msg.contains("999"));
    }

    #[test]
    fn test_cov_error_page_table_corruption_field() {
        let err = PagedCacheError::PageTableCorruption { seq_id: 123 };
        let msg = err.to_string();
        assert!(msg.contains("123"));
    }