Skip to main content

is_it_slop_preprocessing/pre_processor/
chunker.rs

1//! Token-based text chunking for handling variable-length documents.
2//!
3//! This module provides [`TokenChunker`] for splitting token sequences into overlapping
4//! chunks of fixed size. Chunking enables consistent handling of both short and long
5//! documents by:
6//! - Processing all texts as similarly-sized segments
7//! - Capturing local patterns uniformly regardless of document length
8//! - Preventing information loss from overly long or short documents
9//!
10//! The chunker uses an **even distribution algorithm** that adjusts chunk size and
11//! overlap to avoid tiny trailing chunks, ensuring all chunks meet minimum size requirements.
12//!
13//! # Architecture
14//!
15//! Default configuration:
16//! - **Chunk size**: 150 tokens
17//! - **Overlap**: 15 tokens (10%)
18//! - **Minimum chunk size**: 30 tokens
19//!
20//! For documents shorter than `chunk_size`, a single chunk is returned.
21//!
22//! # Example
23//!
24//! ```rust
25//! use is_it_slop_preprocessing::pre_processor::TokenChunker;
26//!
27//! let chunker = TokenChunker::default();
28//! let tokens: Vec<u32> = (0..500).collect(); // 500 tokens
29//! let chunks = chunker.chunk(&tokens);
30//! // Returns ~4 chunks of ~130-150 tokens each with ~15 token overlap
31//! ```
32
33use rayon::prelude::*;
34
35/// Splits token sequences into overlapping chunks with even distribution.
36///
37/// Uses an optimization algorithm to evenly distribute tokens across chunks,
38/// avoiding tiny trailing chunks that would violate `min_chunk_size`.
39#[derive(Clone, Debug, Copy)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
41pub struct TokenChunker {
42    /// Size of each chunk in tokens, e.g., 150 tokens
43    pub chunk_size: usize,
44    /// Number of overlapping tokens between chunks, e.g., 15 tokens(10%)
45    pub overlap: usize,
46    /// Minimum size of a chunk to be included, e.g., 30 tokens
47    pub min_chunk_size: usize,
48}
49
50impl Default for TokenChunker {
51    fn default() -> Self {
52        Self {
53            chunk_size: 150,
54            overlap: 15,
55            min_chunk_size: 30,
56        }
57    }
58}
59
60impl TokenChunker {
61    /// Chunk a single token sequence with even distribution
62    #[must_use]
63    pub fn chunk(&self, tokens: &[u32]) -> Vec<Vec<u32>> {
64        if tokens.len() <= self.chunk_size {
65            return vec![tokens.to_vec()];
66        }
67        // Calculate optimal number of chunks
68        let num_chunks = self.calculate_num_chunks(tokens.len());
69        if num_chunks == 1 {
70            return vec![tokens.to_vec()];
71        }
72
73        // Calculate optimal chunk size and overlap to distribute evenly
74        let (chunk_size, overlap) = self.calculate_optimal_params(tokens.len(), num_chunks);
75        let chunk_size = chunk_size.min(tokens.len());
76        let overlap = overlap.min(chunk_size);
77
78        let mut chunks = Vec::with_capacity(num_chunks);
79        let step = chunk_size.saturating_sub(overlap);
80
81        let mut start = 0;
82        while start < tokens.len() {
83            let end = (start + chunk_size).min(tokens.len());
84            // Only add chunks that meet minimum size requirement
85            if end - start >= self.min_chunk_size || chunks.is_empty() {
86                chunks.push(tokens[start..end].to_vec());
87            }
88            start += step;
89            // Prevent infinite loop if step is 0
90            if step == 0 {
91                break;
92            }
93        }
94        chunks
95    }
96
97    /// Calculate the optimal number of chunks needed
98    fn calculate_num_chunks(&self, total_tokens: usize) -> usize {
99        if total_tokens <= self.chunk_size {
100            return 1;
101        }
102
103        // Calculate how many chunks we'd get with the standard approach
104        let step = self.chunk_size - self.overlap;
105
106        // The first chunk takes chunk_size tokens, then each subsequent chunk advances by step
107        let remaining_after_first = total_tokens.saturating_sub(self.chunk_size);
108        let additional_chunks = remaining_after_first.div_ceil(step);
109        let naive_chunks = 1 + additional_chunks;
110
111        // Check if the last chunk would be too small
112        let last_chunk_start = (naive_chunks - 1) * step;
113        let last_chunk_size = total_tokens.saturating_sub(last_chunk_start);
114
115        if last_chunk_size < self.min_chunk_size && naive_chunks > 1 {
116            // Last chunk too small, merge it with previous chunk
117            naive_chunks - 1
118        } else {
119            naive_chunks
120        }
121    }
122
123    /// Calculate optimal chunk size and overlap to evenly distribute tokens
124    fn calculate_optimal_params(&self, total_tokens: usize, num_chunks: usize) -> (usize, usize) {
125        if num_chunks == 1 {
126            return (total_tokens, 0);
127        }
128        // chunk_size = (total_tokens + overlap * (num_chunks - 1)) / num_chunks
129        // We'll iterate to find the best fit
130        let mut best_chunk_size = self.chunk_size;
131        let mut best_overlap = self.overlap;
132        let mut best_error = usize::MAX;
133
134        // Maximum chunk size cannot exceed total tokens
135        let max_chunk_size = total_tokens.min(self.chunk_size + 50);
136
137        // Try chunk sizes around the configured size
138        for chunk_size in (self.min_chunk_size..=max_chunk_size).rev() {
139            // Calculate overlap needed to fit exactly
140            // total_tokens = chunk_size + (num_chunks - 1) * step
141            // step = (total_tokens - chunk_size) / (num_chunks - 1)
142            if chunk_size > total_tokens {
143                continue; // Skip invalid configurations
144            }
145            let step = (total_tokens.saturating_sub(chunk_size)) / (num_chunks - 1);
146            let overlap = chunk_size.saturating_sub(step);
147
148            // Check if this is a valid configuration
149            if overlap < chunk_size && overlap <= self.overlap * 2 {
150                // Calculate actual coverage
151                let actual_coverage = chunk_size + (num_chunks - 1) * step;
152                let error = actual_coverage.abs_diff(total_tokens);
153
154                if error < best_error {
155                    best_error = error;
156                    best_chunk_size = chunk_size;
157                    best_overlap = overlap;
158                }
159
160                if error == 0 {
161                    break;
162                }
163            }
164        }
165
166        (best_chunk_size, best_overlap)
167    }
168
169    /// Chunk multiple token sequences in parallel with even distribution
170    #[must_use]
171    pub fn chunk_batch(&self, token_sequences: &[Vec<u32>]) -> Vec<Vec<Vec<u32>>> {
172        token_sequences
173            .par_iter()
174            .map(|tokens| self.chunk(tokens))
175            .collect()
176    }
177
178    /// Serialize the `TokenChunker` to a JSON string.
179    #[cfg(feature = "serde")]
180    pub fn from_json_str(json_str: &str) -> Result<Self, serde_json::Error> {
181        serde_json::from_str(json_str)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn test_even_chunk_distribution() {
191        let chunker = TokenChunker {
192            chunk_size: 100,
193            overlap: 10,
194            min_chunk_size: 30,
195        };
196
197        // 250 tokens should split evenly into 3 chunks
198        let tokens: Vec<u32> = (0..250).collect();
199        let chunks = chunker.chunk(&tokens);
200
201        println!("Chunks created: {}", chunks.len());
202        for (i, chunk) in chunks.iter().enumerate() {
203            println!("Chunk {}: size = {}", i, chunk.len());
204        }
205
206        // All chunks should be reasonably sized (no tiny last chunk)
207        for chunk in &chunks {
208            assert!(
209                chunk.len() >= chunker.min_chunk_size,
210                "Chunk size {} is below minimum {}",
211                chunk.len(),
212                chunker.min_chunk_size
213            );
214        }
215
216        // Verify coverage (with overlaps, total unique tokens should be close to input)
217        let first_token_positions: Vec<usize> =
218            chunks.iter().map(|chunk| chunk[0] as usize).collect();
219        println!("Chunk starting positions: {first_token_positions:?}");
220    }
221
222    #[test]
223    fn test_calculate_num_chunks() {
224        let chunker = TokenChunker {
225            chunk_size: 100,
226            overlap: 10,
227            min_chunk_size: 30,
228        };
229
230        // Test various input sizes
231        // For 50 tokens: fits in single chunk
232        assert_eq!(chunker.calculate_num_chunks(50), 1);
233
234        // For 100 tokens: exactly one chunk
235        assert_eq!(chunker.calculate_num_chunks(100), 1);
236
237        // For 150 tokens: step=90, first chunk 0-99, second starts at 90, covers 90-149 (60 tokens)
238        // 60 >= min_chunk_size(30), so 2 chunks
239        assert_eq!(chunker.calculate_num_chunks(150), 2);
240
241        // For 250 tokens: step=90
242        // Chunk 0: 0-99 (100 tokens)
243        // Chunk 1: 90-189 (100 tokens)
244        // Chunk 2: 180-249 (70 tokens) >= 30, so 3 chunks
245        assert_eq!(chunker.calculate_num_chunks(250), 3);
246
247        // For 500 tokens: step=90
248        // Positions: 0, 90, 180, 270, 360, 450
249        // Last chunk: 450-499 (50 tokens) >= 30, so 6 chunks
250        assert_eq!(chunker.calculate_num_chunks(500), 6);
251    }
252    #[test]
253    fn test_no_dropped_content() {
254        let chunker = TokenChunker {
255            chunk_size: 100,
256            overlap: 10,
257            min_chunk_size: 30,
258        };
259
260        let tokens: Vec<u32> = (0..275).collect();
261        let chunks = chunker.chunk(&tokens);
262
263        // Last chunk should include the final tokens
264        let last_chunk = chunks.last().unwrap();
265        assert_eq!(
266            last_chunk.last().unwrap(),
267            &274,
268            "Last token should be included"
269        );
270
271        // Verify reasonable chunk sizes
272        for (i, chunk) in chunks.iter().enumerate() {
273            println!("Chunk {}: {} tokens", i, chunk.len());
274            assert!(chunk.len() >= chunker.min_chunk_size);
275        }
276    }
277
278    #[test]
279    fn test_small_input_unchanged() {
280        let chunker = TokenChunker {
281            chunk_size: 150,
282            overlap: 15,
283            min_chunk_size: 30,
284        };
285
286        let tokens: Vec<u32> = (0..50).collect();
287        let chunks = chunker.chunk(&tokens);
288
289        assert_eq!(chunks.len(), 1);
290        assert_eq!(chunks[0].len(), 50);
291    }
292    #[test]
293    fn test_chunk_edge_cases() {
294        let chunker = TokenChunker {
295            chunk_size: 100,
296            overlap: 10,
297            min_chunk_size: 30,
298        };
299
300        // Test with tokens less than chunk_size but more than configured
301        let tokens_short: Vec<u32> = (0..75).collect();
302        let chunks = chunker.chunk(&tokens_short);
303        assert_eq!(chunks.len(), 1, "Should produce 1 chunk for 75 tokens");
304        assert_eq!(chunks[0].len(), 75);
305
306        // Test with tokens slightly over chunk_size
307        let tokens_medium: Vec<u32> = (0..120).collect();
308        let chunks = chunker.chunk(&tokens_medium);
309        assert!(!chunks.is_empty(), "Should produce at least one chunk");
310        for chunk in &chunks {
311            assert!(chunk.len() >= chunker.min_chunk_size);
312        }
313        assert_eq!(
314            chunks.last().unwrap().last().unwrap(),
315            &119,
316            "Last token should be included"
317        );
318
319        // Test with various small sizes that caused panics
320        for size in [169, 172, 177, 179, 191] {
321            let tokens: Vec<u32> = (0..size).collect();
322            let chunks = chunker.chunk(&tokens);
323            assert!(!chunks.is_empty(), "Size {size} should produce chunks");
324            assert_eq!(
325                chunks.last().unwrap().last().unwrap(),
326                &(size - 1),
327                "Size {size} should include last token"
328            );
329        }
330    }
331
332    // Serialization tests
333
334    #[test]
335    #[cfg(feature = "serde")]
336    fn test_json_round_trip() {
337        use serde_json;
338
339        let chunker = TokenChunker {
340            chunk_size: 100,
341            overlap: 10,
342            min_chunk_size: 25,
343        };
344
345        // Serialize to JSON
346        let json_str = serde_json::to_string(&chunker).expect("Should serialize");
347        assert!(json_str.contains("chunk_size"));
348        assert!(json_str.contains("100"));
349
350        // Deserialize from JSON
351        let loaded: TokenChunker = serde_json::from_str(&json_str).expect("Should deserialize");
352        assert_eq!(loaded.chunk_size, chunker.chunk_size);
353        assert_eq!(loaded.overlap, chunker.overlap);
354        assert_eq!(loaded.min_chunk_size, chunker.min_chunk_size);
355    }
356
357    #[test]
358    #[cfg(feature = "serde")]
359    fn test_from_json_str() {
360        let json = r#"{"chunk_size": 150, "overlap": 15, "min_chunk_size": 30}"#;
361        let chunker = TokenChunker::from_json_str(json).expect("Should parse JSON");
362
363        assert_eq!(chunker.chunk_size, 150);
364        assert_eq!(chunker.overlap, 15);
365        assert_eq!(chunker.min_chunk_size, 30);
366    }
367
368    #[test]
369    #[cfg(feature = "serde")]
370    fn test_json_serialization_format() {
371        // Verify JSON format is human-readable and correct
372        let chunker = TokenChunker {
373            chunk_size: 200,
374            overlap: 20,
375            min_chunk_size: 50,
376        };
377
378        let json = serde_json::to_string_pretty(&chunker).expect("Should serialize");
379        println!("JSON output:\n{json}");
380
381        // Verify structure
382        assert!(json.contains(r#""chunk_size": 200"#));
383        assert!(json.contains(r#""overlap": 20"#));
384        assert!(json.contains(r#""min_chunk_size": 50"#));
385    }
386
387    // Overlap validation tests
388
389    #[test]
390    fn test_overlap_validation_between_adjacent_chunks() {
391        let chunker = TokenChunker {
392            chunk_size: 100,
393            overlap: 10,
394            min_chunk_size: 30,
395        };
396
397        let tokens: Vec<u32> = (0..250).collect();
398        let chunks = chunker.chunk(&tokens);
399
400        assert!(chunks.len() >= 2, "Should produce multiple chunks");
401
402        // Verify chunks are sequential and cover the full range
403        for i in 0..chunks.len() - 1 {
404            let chunk1 = &chunks[i];
405            let chunk2 = &chunks[i + 1];
406
407            // Verify chunks are not empty
408            assert!(!chunk1.is_empty());
409            assert!(!chunk2.is_empty());
410
411            // Verify chunks are sequential (chunk2 starts after chunk1)
412            let last_token_chunk1 = *chunk1.last().unwrap();
413            let first_token_chunk2 = *chunk2.first().unwrap();
414
415            // Due to even distribution algorithm, overlap may vary
416            // Just verify sequential ordering
417            assert!(
418                last_token_chunk1 < first_token_chunk2 + 50, // Allow for overlap
419                "Chunks should be reasonably sequential"
420            );
421        }
422    }
423
424    #[test]
425    fn test_no_dropped_tokens_in_chunks() {
426        // Verify all tokens from input appear in at least one chunk
427        let chunker = TokenChunker {
428            chunk_size: 100,
429            overlap: 10,
430            min_chunk_size: 30,
431        };
432
433        let tokens: Vec<u32> = (0..275).collect();
434        let chunks = chunker.chunk(&tokens);
435
436        // First token should be in first chunk
437        assert_eq!(chunks[0][0], 0);
438
439        // Last token should be in last chunk
440        assert_eq!(*chunks.last().unwrap().last().unwrap(), 274);
441
442        // Verify chunks cover the full range
443        let all_unique_tokens: std::collections::HashSet<u32> =
444            chunks.iter().flat_map(|c| c.iter()).copied().collect();
445
446        // All original tokens should appear
447        for &token in &tokens {
448            assert!(
449                all_unique_tokens.contains(&token),
450                "Token {token} not found in any chunk"
451            );
452        }
453    }
454
455    // Invalid config tests
456
457    // Note: Invalid chunker configurations (overlap >= chunk_size) are not tested
458    // as they represent programmer errors that should be caught during development.
459    // The implementation will panic or produce incorrect results for such configs.
460
461    #[test]
462    fn test_invalid_config_min_chunk_greater_than_chunk_size() {
463        // min_chunk_size > chunk_size: logically inconsistent
464        let chunker = TokenChunker {
465            chunk_size: 100,
466            overlap: 10,
467            min_chunk_size: 150,
468        };
469
470        let tokens: Vec<u32> = (0..200).collect();
471        let chunks = chunker.chunk(&tokens);
472
473        // Should still produce chunks (first chunk always included)
474        assert!(!chunks.is_empty());
475    }
476
477    #[test]
478    fn test_zero_overlap_no_shared_tokens() {
479        // Zero overlap: chunks should be contiguous but not overlapping
480        let chunker = TokenChunker {
481            chunk_size: 100,
482            overlap: 0,
483            min_chunk_size: 30,
484        };
485
486        let tokens: Vec<u32> = (0..250).collect();
487        let chunks = chunker.chunk(&tokens);
488
489        assert!(chunks.len() >= 2);
490
491        // Verify no overlap: last token of chunk[i] + 1 == first token of chunk[i+1]
492        for i in 0..chunks.len() - 1 {
493            let last_token = *chunks[i].last().unwrap();
494            let next_first_token = *chunks[i + 1].first().unwrap();
495
496            // With even distribution, may not be exactly contiguous, but should be close
497            assert!(
498                next_first_token > last_token,
499                "Chunks should not overlap with zero overlap setting"
500            );
501        }
502    }
503
504    #[test]
505    fn test_chunking_with_custom_parameters() {
506        // Test various parameter combinations
507        let configs = vec![
508            (50, 5, 10),   // Small chunks
509            (200, 20, 40), // Large chunks
510            (150, 0, 30),  // No overlap
511            (150, 30, 30), // High overlap (20%)
512        ];
513
514        for (chunk_size, overlap, min_chunk_size) in configs {
515            let chunker = TokenChunker {
516                chunk_size,
517                overlap,
518                min_chunk_size,
519            };
520
521            let tokens: Vec<u32> = (0..300).collect();
522            let chunks = chunker.chunk(&tokens);
523
524            // Basic invariants
525            assert!(!chunks.is_empty());
526            for chunk in &chunks {
527                assert!(
528                    chunk.len() >= min_chunk_size || chunks.len() == 1,
529                    "Chunk size {} violates min_chunk_size {min_chunk_size}",
530                    chunk.len()
531                );
532            }
533
534            // Verify first and last tokens
535            assert_eq!(chunks[0][0], 0);
536            assert_eq!(*chunks.last().unwrap().last().unwrap(), 299);
537        }
538    }
539
540    #[test]
541    fn test_chunk_batch_equivalence() {
542        let chunker = TokenChunker::default();
543        let token_sequences: Vec<Vec<u32>> = (0..10)
544            .map(|i| (i * 100..i * 100 + 250).collect())
545            .collect();
546
547        let batched = chunker.chunk_batch(&token_sequences);
548        let sequential: Vec<Vec<Vec<u32>>> = token_sequences
549            .iter()
550            .map(|tokens| chunker.chunk(tokens))
551            .collect();
552
553        assert_eq!(batched.len(), sequential.len());
554        for (i, (batch_chunks, seq_chunks)) in batched.iter().zip(sequential.iter()).enumerate() {
555            assert_eq!(
556                batch_chunks, seq_chunks,
557                "chunk_batch and chunk disagree at index {i}"
558            );
559        }
560    }
561
562    #[test]
563    fn test_chunk_empty_input() {
564        let chunker = TokenChunker::default();
565        let result = chunker.chunk(&[]);
566        assert_eq!(result, vec![Vec::<u32>::new()]);
567
568        let batch_result = chunker.chunk_batch(&[Vec::new(), Vec::new()]);
569        assert_eq!(batch_result.len(), 2);
570        assert_eq!(batch_result[0], vec![Vec::<u32>::new()]);
571        assert_eq!(batch_result[1], vec![Vec::<u32>::new()]);
572    }
573
574    #[test]
575    fn test_chunk_exact_boundaries() {
576        let chunker = TokenChunker {
577            chunk_size: 100,
578            overlap: 10,
579            min_chunk_size: 30,
580        };
581
582        let tokens_exact: Vec<u32> = (0..100).collect();
583        let chunks = chunker.chunk(&tokens_exact);
584        assert_eq!(chunks.len(), 1);
585        assert_eq!(chunks[0].len(), 100);
586
587        let tokens_two_chunks: Vec<u32> = (0..200).collect();
588        let chunks = chunker.chunk(&tokens_two_chunks);
589        assert!(
590            chunks.len() >= 2,
591            "200 tokens should produce at least 2 chunks"
592        );
593        assert_eq!(*chunks.last().unwrap().last().unwrap(), 199);
594    }
595}