1use tracing::warn;
14
15use crate::document::{Chunk, Document};
16use crate::error::{RagError, Result};
17
18fn floor_char_boundary(s: &str, index: usize) -> usize {
21 if index >= s.len() {
22 return s.len();
23 }
24 let mut i = index;
25 while i > 0 && !s.is_char_boundary(i) {
26 i -= 1;
27 }
28 i
29}
30
31fn next_char_boundary(s: &str, index: usize) -> usize {
33 s[index..].chars().next().map_or(s.len(), |c| index + c.len_utf8())
34}
35
36fn validate_sizes(chunk_size: usize, chunk_overlap: usize) -> Result<()> {
38 if chunk_size == 0 {
39 return Err(RagError::ConfigError("chunk_size must be greater than zero".to_string()));
40 }
41 if chunk_overlap >= chunk_size {
42 return Err(RagError::ConfigError(format!(
43 "chunk_overlap ({chunk_overlap}) must be less than chunk_size ({chunk_size})"
44 )));
45 }
46 Ok(())
47}
48
49fn normalize_sizes(chunker: &str, chunk_size: usize, chunk_overlap: usize) -> (usize, usize) {
55 match validate_sizes(chunk_size, chunk_overlap) {
56 Ok(()) => (chunk_size, chunk_overlap),
57 Err(error) => {
58 let size = chunk_size.max(1);
59 let overlap = if chunk_overlap < size { chunk_overlap } else { 0 };
60 warn!(
61 chunker,
62 error = %error,
63 chunk_size = size,
64 chunk_overlap = overlap,
65 "invalid chunker sizes; use try_new to reject them"
66 );
67 (size, overlap)
68 }
69 }
70}
71
72pub trait Chunker: Send + Sync {
77 fn chunk(&self, document: &Document) -> Vec<Chunk>;
82}
83
84#[derive(Debug, Clone)]
102pub struct FixedSizeChunker {
103 chunk_size: usize,
104 chunk_overlap: usize,
105}
106
107impl FixedSizeChunker {
108 pub fn new(chunk_size: usize, chunk_overlap: usize) -> Self {
119 let (chunk_size, chunk_overlap) =
120 normalize_sizes("FixedSizeChunker", chunk_size, chunk_overlap);
121 Self { chunk_size, chunk_overlap }
122 }
123
124 pub fn try_new(chunk_size: usize, chunk_overlap: usize) -> Result<Self> {
145 validate_sizes(chunk_size, chunk_overlap)?;
146 Ok(Self { chunk_size, chunk_overlap })
147 }
148}
149
150impl Chunker for FixedSizeChunker {
151 fn chunk(&self, document: &Document) -> Vec<Chunk> {
152 split_by_size(&document.text, self.chunk_size, self.chunk_overlap)
153 .into_iter()
154 .enumerate()
155 .map(|(chunk_index, text)| {
156 Chunk::from_document(document, format!("{}_{chunk_index}", document.id), text)
157 .with_metadata("chunk_index", chunk_index.to_string())
158 })
159 .collect()
160 }
161}
162
163#[derive(Debug, Clone)]
179pub struct RecursiveChunker {
180 chunk_size: usize,
181 chunk_overlap: usize,
182}
183
184impl RecursiveChunker {
185 pub fn new(chunk_size: usize, chunk_overlap: usize) -> Self {
196 let (chunk_size, chunk_overlap) =
197 normalize_sizes("RecursiveChunker", chunk_size, chunk_overlap);
198 Self { chunk_size, chunk_overlap }
199 }
200
201 pub fn try_new(chunk_size: usize, chunk_overlap: usize) -> Result<Self> {
222 validate_sizes(chunk_size, chunk_overlap)?;
223 Ok(Self { chunk_size, chunk_overlap })
224 }
225}
226
227fn split_and_merge(
231 text: &str,
232 chunk_size: usize,
233 chunk_overlap: usize,
234 separators: &[&str],
235) -> Vec<String> {
236 if text.len() <= chunk_size || separators.is_empty() {
237 return split_by_size(text, chunk_size, chunk_overlap);
238 }
239
240 let separator = separators[0];
241 let remaining_separators = &separators[1..];
242
243 let segments: Vec<&str> = if separator == " " {
244 text.split(' ').collect()
245 } else {
246 split_keeping_separator(text, separator)
247 };
248
249 let mut chunks = Vec::new();
250 let mut current = String::new();
251
252 for segment in segments {
253 if current.is_empty() {
254 current = segment.to_string();
255 } else if current.len() + segment.len() <= chunk_size {
256 current.push_str(segment);
257 } else {
258 if current.len() > chunk_size {
260 chunks.extend(split_and_merge(
261 ¤t,
262 chunk_size,
263 chunk_overlap,
264 remaining_separators,
265 ));
266 } else {
267 chunks.push(current);
268 }
269 current = segment.to_string();
271 }
272 }
273
274 if !current.is_empty() {
275 if current.len() > chunk_size {
276 chunks.extend(split_and_merge(
277 ¤t,
278 chunk_size,
279 chunk_overlap,
280 remaining_separators,
281 ));
282 } else {
283 chunks.push(current);
284 }
285 }
286
287 chunks
288}
289
290fn split_keeping_separator<'a>(text: &'a str, separator: &str) -> Vec<&'a str> {
292 let mut result = Vec::new();
293 let mut start = 0;
294
295 while let Some(pos) = text[start..].find(separator) {
296 let end = start + pos + separator.len();
297 result.push(&text[start..end]);
298 start = end;
299 }
300
301 if start < text.len() {
302 result.push(&text[start..]);
303 }
304
305 result
306}
307
308fn split_by_size(text: &str, chunk_size: usize, chunk_overlap: usize) -> Vec<String> {
315 let step = chunk_size.saturating_sub(chunk_overlap);
316 let mut chunks = Vec::new();
317 let mut start = 0;
318
319 while start < text.len() {
320 let mut end = floor_char_boundary(text, start.saturating_add(chunk_size));
321 if end <= start {
322 end = next_char_boundary(text, start);
323 }
324 chunks.push(text[start..end].to_string());
325
326 let next = floor_char_boundary(text, start.saturating_add(step));
327 start = if next > start { next } else { next_char_boundary(text, start) };
328 }
329
330 chunks
331}
332
333impl Chunker for RecursiveChunker {
334 fn chunk(&self, document: &Document) -> Vec<Chunk> {
335 if document.text.is_empty() {
336 return Vec::new();
337 }
338
339 let separators = ["\n\n", ". ", "! ", "? ", " "];
340 let raw_chunks =
341 split_and_merge(&document.text, self.chunk_size, self.chunk_overlap, &separators);
342
343 raw_chunks
344 .into_iter()
345 .enumerate()
346 .map(|(i, text)| {
347 Chunk::from_document(document, format!("{}_{i}", document.id), text)
348 .with_metadata("chunk_index", i.to_string())
349 })
350 .collect()
351 }
352}
353
354#[derive(Debug, Clone)]
369pub struct MarkdownChunker {
370 chunk_size: usize,
371 chunk_overlap: usize,
372}
373
374impl MarkdownChunker {
375 pub fn new(chunk_size: usize, chunk_overlap: usize) -> Self {
386 let (chunk_size, chunk_overlap) =
387 normalize_sizes("MarkdownChunker", chunk_size, chunk_overlap);
388 Self { chunk_size, chunk_overlap }
389 }
390
391 pub fn try_new(chunk_size: usize, chunk_overlap: usize) -> Result<Self> {
412 validate_sizes(chunk_size, chunk_overlap)?;
413 Ok(Self { chunk_size, chunk_overlap })
414 }
415}
416
417struct MarkdownSection {
419 header_path: String,
420 text: String,
421}
422
423fn parse_markdown_sections(text: &str) -> Vec<MarkdownSection> {
425 let mut sections = Vec::new();
426 let mut headers: Vec<String> = Vec::new();
427 let mut current_body = String::new();
428 let mut current_header_path = String::new();
429
430 for line in text.lines() {
431 let trimmed = line.trim_start();
432 if trimmed.starts_with('#') {
433 if !current_body.is_empty() || !current_header_path.is_empty() {
435 sections.push(MarkdownSection {
436 header_path: current_header_path.clone(),
437 text: current_body.trim().to_string(),
438 });
439 current_body = String::new();
440 }
441
442 let level = trimmed.chars().take_while(|c| *c == '#').count();
444 let header_text = trimmed[level..].trim().to_string();
445
446 headers.truncate(level.saturating_sub(1));
448 headers.push(header_text);
449 current_header_path = headers.join(" > ");
450 } else {
451 if !current_body.is_empty() {
452 current_body.push('\n');
453 }
454 current_body.push_str(line);
455 }
456 }
457
458 if !current_body.is_empty() || !current_header_path.is_empty() {
460 sections.push(MarkdownSection {
461 header_path: current_header_path,
462 text: current_body.trim().to_string(),
463 });
464 }
465
466 sections
467}
468
469impl Chunker for MarkdownChunker {
470 fn chunk(&self, document: &Document) -> Vec<Chunk> {
471 if document.text.is_empty() {
472 return Vec::new();
473 }
474
475 let sections = parse_markdown_sections(&document.text);
476 let mut chunks = Vec::new();
477 let mut chunk_index = 0;
478
479 for section in sections {
480 let section_text = if section.header_path.is_empty() {
482 section.text.clone()
483 } else if section.text.is_empty() {
484 section.header_path.clone()
485 } else {
486 format!("{}\n{}", section.header_path, section.text)
487 };
488
489 if section_text.is_empty() {
490 continue;
491 }
492
493 let sub_chunks = if section_text.len() > self.chunk_size {
494 let separators = ["\n\n", ". ", "! ", "? ", " "];
496 split_and_merge(§ion_text, self.chunk_size, self.chunk_overlap, &separators)
497 } else {
498 vec![section_text]
499 };
500
501 for text in sub_chunks {
502 chunks.push(
503 Chunk::from_document(document, format!("{}_{chunk_index}", document.id), text)
504 .with_metadata("chunk_index", chunk_index.to_string())
505 .with_metadata("header_path", section.header_path.clone()),
506 );
507 chunk_index += 1;
508 }
509 }
510
511 chunks
512 }
513}
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518 use crate::Document;
519 use proptest::prelude::*;
520
521 fn doc(text: &str) -> Document {
522 Document::new("test", text)
523 }
524
525 #[test]
526 fn every_chunker_copies_provenance_and_metadata_to_each_chunk() {
527 let document =
528 Document::new("guide", "# Setup\n\nInstall it. Then run it.\n\n# Use\n\nCall it.")
529 .with_source_uri("https://example.com/guide")
530 .with_title("Guide")
531 .with_metadata("lang", "en");
532 let chunkers: [(&str, Box<dyn Chunker>); 3] = [
533 ("fixed", Box::new(FixedSizeChunker::new(16, 0))),
534 ("recursive", Box::new(RecursiveChunker::new(16, 0))),
535 ("markdown", Box::new(MarkdownChunker::new(16, 0))),
536 ];
537 for (name, chunker) in chunkers {
538 let chunks = chunker.chunk(&document);
539 assert!(chunks.len() > 1, "{name} splits the document");
540 for (index, chunk) in chunks.iter().enumerate() {
541 assert_eq!(chunk.id, format!("guide_{index}"), "{name}");
542 assert_eq!(chunk.document_id, "guide", "{name}");
543 assert_eq!(
544 chunk.source_uri.as_deref(),
545 Some("https://example.com/guide"),
546 "{name}"
547 );
548 assert_eq!(chunk.title.as_deref(), Some("Guide"), "{name}");
549 assert_eq!(chunk.metadata["lang"], "en", "{name}");
550 assert_eq!(chunk.metadata["chunk_index"], index.to_string(), "{name}");
551 }
552 }
553 }
554
555 #[test]
556 fn fixed_chunker_utf8_multibyte() {
557 let chunker = FixedSizeChunker::new(5, 0);
561 let chunks = chunker.chunk(&doc("你好世界测试文本"));
562 for chunk in &chunks {
564 assert!(chunk.text.is_char_boundary(0));
565 let _ = chunk.text.chars().count();
567 }
568 assert!(chunks.len() > 1);
570 }
571
572 #[test]
573 fn fixed_chunker_utf8_emoji() {
574 let chunker = FixedSizeChunker::new(6, 0);
576 let chunks = chunker.chunk(&doc("🦀🚀🎉✨🌟💫"));
577 for chunk in &chunks {
578 let _ = chunk.text.chars().count();
579 }
580 assert!(chunks.len() > 1);
581 }
582
583 #[test]
584 fn fixed_chunker_utf8_mixed() {
585 let text = "Hello café 你好 🦀";
587 let chunker = FixedSizeChunker::new(7, 2);
588 let chunks = chunker.chunk(&doc(text));
589 for chunk in &chunks {
590 let _ = chunk.text.chars().count();
591 }
592 assert!(!chunks.is_empty());
593 }
594
595 #[test]
596 fn split_by_size_utf8() {
597 let text = "日本語のテスト文字列です";
598 let chunks = split_by_size(text, 10, 3);
599 for chunk in &chunks {
600 let _ = chunk.chars().count();
601 }
602 assert!(chunks.len() > 1);
603 }
604
605 #[test]
606 fn recursive_chunker_utf8() {
607 let text = "第一段落。这是中文文本。\n\n第二段落。更多中文内容在这里。";
608 let chunker = RecursiveChunker::new(15, 3);
609 let chunks = chunker.chunk(&doc(text));
610 for chunk in &chunks {
611 let _ = chunk.text.chars().count();
612 }
613 assert!(!chunks.is_empty());
614 }
615
616 fn texts(chunks: &[Chunk]) -> Vec<&str> {
617 chunks.iter().map(|c| c.text.as_str()).collect()
618 }
619
620 #[test]
621 fn fixed_chunker_advances_when_step_is_narrower_than_a_character() {
622 let chunks = FixedSizeChunker::new(5, 3).chunk(&doc("你好世界"));
624 assert_eq!(texts(&chunks), ["你", "好", "世", "界"]);
625
626 let chunks = FixedSizeChunker::new(6, 5).chunk(&doc("🦀🚀"));
628 assert_eq!(texts(&chunks), ["🦀", "🚀"]);
629 }
630
631 #[test]
632 fn fixed_chunker_emits_characters_wider_than_chunk_size_whole() {
633 let chunks = FixedSizeChunker::new(2, 0).chunk(&doc("a你b"));
634 assert_eq!(texts(&chunks), ["a", "你", "b"]);
635 }
636
637 #[test]
638 fn split_by_size_advances_when_step_is_narrower_than_a_character() {
639 assert_eq!(split_by_size("日本語", 4, 3), ["日", "本", "語"]);
640 }
641
642 #[test]
643 fn recursive_and_markdown_chunkers_terminate_on_narrow_steps() {
644 let text = "# 标题\n\n第一段落很长很长很长。第二句也很长很长。\n\n🦀🦀🦀🦀🦀🦀";
645 let recursive = RecursiveChunker::new(5, 4).chunk(&doc(text));
646 let markdown = MarkdownChunker::new(5, 4).chunk(&doc(text));
647 assert!(!recursive.is_empty());
648 assert!(!markdown.is_empty());
649 }
650
651 #[test]
652 fn try_new_rejects_invalid_sizes() {
653 for (size, overlap) in [(0, 0), (10, 10), (10, 11)] {
654 assert!(
655 matches!(FixedSizeChunker::try_new(size, overlap), Err(RagError::ConfigError(_))),
656 "FixedSizeChunker accepted ({size}, {overlap})"
657 );
658 assert!(
659 matches!(RecursiveChunker::try_new(size, overlap), Err(RagError::ConfigError(_))),
660 "RecursiveChunker accepted ({size}, {overlap})"
661 );
662 assert!(
663 matches!(MarkdownChunker::try_new(size, overlap), Err(RagError::ConfigError(_))),
664 "MarkdownChunker accepted ({size}, {overlap})"
665 );
666 }
667 assert!(FixedSizeChunker::try_new(10, 9).is_ok());
668 }
669
670 #[test]
671 fn new_normalizes_invalid_sizes_instead_of_truncating() {
672 let chunks = FixedSizeChunker::new(4, 4).chunk(&doc("abcdefghij"));
674 assert_eq!(texts(&chunks), ["abcd", "efgh", "ij"]);
675
676 let chunks = FixedSizeChunker::new(0, 0).chunk(&doc("abc"));
677 assert_eq!(texts(&chunks), ["a", "b", "c"]);
678 }
679
680 fn arb_text() -> impl Strategy<Value = String> {
681 prop_oneof![
682 "\\PC{0,120}",
683 "[a 你好世界🦀é\\n.!?#]{0,120}",
684 proptest::collection::vec(any::<char>(), 0..60)
685 .prop_map(|chars| chars.into_iter().collect::<String>()),
686 ]
687 }
688
689 proptest! {
690 #![proptest_config(ProptestConfig::with_cases(256))]
691
692 #[test]
695 fn prop_chunkers_terminate_for_any_text_and_sizes(
696 text in arb_text(),
697 chunk_size in 0usize..24,
698 chunk_overlap in 0usize..32,
699 ) {
700 let document = doc(&text);
701
702 let fixed = FixedSizeChunker::new(chunk_size, chunk_overlap).chunk(&document);
703 prop_assert!(fixed.len() <= text.len());
704 prop_assert!(fixed.iter().all(|c| !c.text.is_empty()));
705 if let (Some(first), Some(last)) = (fixed.first(), fixed.last()) {
706 prop_assert!(text.starts_with(&first.text));
707 prop_assert!(text.ends_with(&last.text));
708 }
709
710 let recursive = RecursiveChunker::new(chunk_size, chunk_overlap).chunk(&document);
711 prop_assert!(recursive.iter().all(|c| !c.text.is_empty()));
712
713 let markdown = MarkdownChunker::new(chunk_size, chunk_overlap).chunk(&document);
714 prop_assert!(markdown.iter().all(|c| !c.text.is_empty()));
715 }
716
717 #[test]
720 fn prop_fixed_chunks_without_overlap_partition_the_text(
721 text in arb_text(),
722 chunk_size in 1usize..24,
723 ) {
724 let chunks = FixedSizeChunker::try_new(chunk_size, 0)
725 .expect("valid sizes")
726 .chunk(&doc(&text));
727 prop_assert_eq!(texts(&chunks).concat(), text.clone());
728 for chunk in &chunks {
729 prop_assert!(
730 chunk.text.len() <= chunk_size || chunk.text.chars().count() == 1,
731 "chunk {:?} exceeds {} bytes", chunk.text, chunk_size
732 );
733 }
734 }
735 }
736}