Skip to main content

adk_rag/
chunking.rs

1//! Document chunking strategies.
2//!
3//! This module provides the [`Chunker`] trait and three implementations:
4//!
5//! - [`FixedSizeChunker`] — splits by byte length with configurable overlap
6//! - [`RecursiveChunker`] — splits hierarchically by paragraphs, sentences, then words
7//! - [`MarkdownChunker`] — splits by markdown headers, preserving header context
8//!
9//! Sizes are measured in bytes of UTF-8, not characters. Chunks never split a
10//! character, so a chunk is at most `chunk_size` bytes unless a single character
11//! is wider than `chunk_size`, in which case that character forms a chunk alone.
12
13use tracing::warn;
14
15use crate::document::{Chunk, Document};
16use crate::error::{RagError, Result};
17
18/// MSRV-compatible replacement for `str::floor_char_boundary` (stable since 1.91.0).
19/// Returns the largest byte index `<= index` that is a valid char boundary.
20fn 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
31/// Returns the byte index just past the character that starts at `index`.
32fn next_char_boundary(s: &str, index: usize) -> usize {
33    s[index..].chars().next().map_or(s.len(), |c| index + c.len_utf8())
34}
35
36/// Checks that `chunk_size` is positive and `chunk_overlap` is smaller than it.
37fn 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
49/// Replaces an invalid size pair with the nearest configuration that still advances.
50///
51/// A zero `chunk_size` becomes one byte and an overlap that is not smaller than
52/// `chunk_size` is dropped, so chunking covers the whole document instead of
53/// stopping after the first chunk.
54fn 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
72/// A strategy for splitting documents into chunks.
73///
74/// Implementations produce [`Chunk`]s with text and metadata but no embeddings.
75/// Embeddings are attached later by the pipeline.
76pub trait Chunker: Send + Sync {
77    /// Split a document into chunks.
78    ///
79    /// Returns an empty `Vec` if the document has empty text.
80    /// Each returned chunk has an empty embedding vector.
81    fn chunk(&self, document: &Document) -> Vec<Chunk>;
82}
83
84/// Splits text into fixed-size chunks by byte length with configurable overlap.
85///
86/// Each chunk holds at most `chunk_size` bytes of UTF-8 and starts
87/// `chunk_size - chunk_overlap` bytes after the previous one, rounded down to a
88/// character boundary and always at least one character further on.
89///
90/// Chunk IDs are generated as `{document_id}_{chunk_index}`. Each chunk inherits
91/// the parent document's metadata plus a `chunk_index` field.
92///
93/// # Example
94///
95/// ```rust,ignore
96/// use adk_rag::FixedSizeChunker;
97///
98/// let chunker = FixedSizeChunker::try_new(256, 50)?;
99/// let chunks = chunker.chunk(&document);
100/// ```
101#[derive(Debug, Clone)]
102pub struct FixedSizeChunker {
103    chunk_size: usize,
104    chunk_overlap: usize,
105}
106
107impl FixedSizeChunker {
108    /// Create a new `FixedSizeChunker`.
109    ///
110    /// # Arguments
111    ///
112    /// * `chunk_size` — maximum number of bytes per chunk
113    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
114    ///
115    /// An invalid pair is normalised rather than rejected: a zero `chunk_size`
116    /// becomes 1 and a `chunk_overlap` that is not smaller than `chunk_size` is
117    /// ignored, with a warning logged. Use [`try_new`](Self::try_new) to reject it.
118    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    /// Create a new `FixedSizeChunker`, rejecting an invalid size pair.
125    ///
126    /// # Arguments
127    ///
128    /// * `chunk_size` — maximum number of bytes per chunk
129    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
130    ///
131    /// # Errors
132    ///
133    /// Returns [`RagError::ConfigError`] when `chunk_size` is zero or
134    /// `chunk_overlap` is not smaller than `chunk_size`.
135    ///
136    /// # Example
137    ///
138    /// ```rust
139    /// use adk_rag::FixedSizeChunker;
140    ///
141    /// assert!(FixedSizeChunker::try_new(512, 100).is_ok());
142    /// assert!(FixedSizeChunker::try_new(100, 100).is_err());
143    /// ```
144    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/// Splits text hierarchically: paragraphs → sentences → words.
164///
165/// First splits by paragraph separators (`\n\n`). If a paragraph exceeds
166/// `chunk_size` bytes, splits by sentence boundaries (`. `, `! `, `? `). If a
167/// sentence still exceeds `chunk_size`, splits by word boundaries, and a single
168/// word longer than `chunk_size` is split by byte length with overlap.
169///
170/// # Example
171///
172/// ```rust,ignore
173/// use adk_rag::RecursiveChunker;
174///
175/// let chunker = RecursiveChunker::new(512, 100);
176/// let chunks = chunker.chunk(&document);
177/// ```
178#[derive(Debug, Clone)]
179pub struct RecursiveChunker {
180    chunk_size: usize,
181    chunk_overlap: usize,
182}
183
184impl RecursiveChunker {
185    /// Create a new `RecursiveChunker`.
186    ///
187    /// # Arguments
188    ///
189    /// * `chunk_size` — maximum number of bytes per chunk
190    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
191    ///
192    /// An invalid pair is normalised rather than rejected: a zero `chunk_size`
193    /// becomes 1 and a `chunk_overlap` that is not smaller than `chunk_size` is
194    /// ignored, with a warning logged. Use [`try_new`](Self::try_new) to reject it.
195    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    /// Create a new `RecursiveChunker`, rejecting an invalid size pair.
202    ///
203    /// # Arguments
204    ///
205    /// * `chunk_size` — maximum number of bytes per chunk
206    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
207    ///
208    /// # Errors
209    ///
210    /// Returns [`RagError::ConfigError`] when `chunk_size` is zero or
211    /// `chunk_overlap` is not smaller than `chunk_size`.
212    ///
213    /// # Example
214    ///
215    /// ```rust
216    /// use adk_rag::RecursiveChunker;
217    ///
218    /// assert!(RecursiveChunker::try_new(512, 100).is_ok());
219    /// assert!(RecursiveChunker::try_new(100, 100).is_err());
220    /// ```
221    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
227/// Split text by a separator, then merge segments into chunks that respect
228/// `chunk_size`. If a segment exceeds `chunk_size`, it is split further
229/// using the next-level separator.
230fn 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            // Current chunk is full — process it
259            if current.len() > chunk_size {
260                chunks.extend(split_and_merge(
261                    &current,
262                    chunk_size,
263                    chunk_overlap,
264                    remaining_separators,
265                ));
266            } else {
267                chunks.push(current);
268            }
269            // Start new chunk with overlap
270            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                &current,
278                chunk_size,
279                chunk_overlap,
280                remaining_separators,
281            ));
282        } else {
283            chunks.push(current);
284        }
285    }
286
287    chunks
288}
289
290/// Split text at a separator while keeping the separator attached to the preceding segment.
291fn 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
308/// Byte-length splitting with overlap that never splits a character.
309///
310/// Both the chunk end and the next start are rounded down to a character
311/// boundary, then pushed one character forward if rounding left them at
312/// `start`. Without that, a step narrower than a multibyte character would
313/// leave `start` in place forever.
314fn 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/// Splits text by markdown headers, keeping each section as a chunk.
355///
356/// Each section is prefixed with its header hierarchy. Sections exceeding
357/// `chunk_size` bytes are further split using [`RecursiveChunker`] logic.
358/// The `header_path` metadata field records the header hierarchy for each chunk.
359///
360/// # Example
361///
362/// ```rust,ignore
363/// use adk_rag::MarkdownChunker;
364///
365/// let chunker = MarkdownChunker::new(512, 100);
366/// let chunks = chunker.chunk(&document);
367/// ```
368#[derive(Debug, Clone)]
369pub struct MarkdownChunker {
370    chunk_size: usize,
371    chunk_overlap: usize,
372}
373
374impl MarkdownChunker {
375    /// Create a new `MarkdownChunker`.
376    ///
377    /// # Arguments
378    ///
379    /// * `chunk_size` — maximum number of bytes per chunk
380    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
381    ///
382    /// An invalid pair is normalised rather than rejected: a zero `chunk_size`
383    /// becomes 1 and a `chunk_overlap` that is not smaller than `chunk_size` is
384    /// ignored, with a warning logged. Use [`try_new`](Self::try_new) to reject it.
385    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    /// Create a new `MarkdownChunker`, rejecting an invalid size pair.
392    ///
393    /// # Arguments
394    ///
395    /// * `chunk_size` — maximum number of bytes per chunk
396    /// * `chunk_overlap` — number of bytes shared by consecutive chunks
397    ///
398    /// # Errors
399    ///
400    /// Returns [`RagError::ConfigError`] when `chunk_size` is zero or
401    /// `chunk_overlap` is not smaller than `chunk_size`.
402    ///
403    /// # Example
404    ///
405    /// ```rust
406    /// use adk_rag::MarkdownChunker;
407    ///
408    /// assert!(MarkdownChunker::try_new(512, 100).is_ok());
409    /// assert!(MarkdownChunker::try_new(100, 100).is_err());
410    /// ```
411    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
417/// A markdown section with its header hierarchy and body text.
418struct MarkdownSection {
419    header_path: String,
420    text: String,
421}
422
423/// Parse markdown text into sections split by headers.
424fn 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            // Save previous section
434            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            // Determine header level
443            let level = trimmed.chars().take_while(|c| *c == '#').count();
444            let header_text = trimmed[level..].trim().to_string();
445
446            // Update header stack
447            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    // Save final section
459    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            // Build section text with header prefix
481            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                // Further split using recursive logic
495                let separators = ["\n\n", ". ", "! ", "? ", " "];
496                split_and_merge(&section_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        // Chinese characters are 3 bytes each in UTF-8.
558        // "你好世界" = 4 chars, 12 bytes.
559        // With chunk_size=5 (bytes), naive slicing would panic mid-character.
560        let chunker = FixedSizeChunker::new(5, 0);
561        let chunks = chunker.chunk(&doc("你好世界测试文本"));
562        // Should not panic and all chunks should be valid UTF-8
563        for chunk in &chunks {
564            assert!(chunk.text.is_char_boundary(0));
565            // Verify it's valid UTF-8 by iterating chars
566            let _ = chunk.text.chars().count();
567        }
568        // Should produce multiple chunks
569        assert!(chunks.len() > 1);
570    }
571
572    #[test]
573    fn fixed_chunker_utf8_emoji() {
574        // Emoji are 4 bytes each. "🦀🚀🎉" = 3 chars, 12 bytes.
575        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        // Mix of ASCII (1 byte), accented (2 bytes), CJK (3 bytes), emoji (4 bytes)
586        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        // Step 2 bytes, characters 3 bytes: rounding down used to leave `start` in place.
623        let chunks = FixedSizeChunker::new(5, 3).chunk(&doc("你好世界"));
624        assert_eq!(texts(&chunks), ["你", "好", "世", "界"]);
625
626        // Step 1 byte, characters 4 bytes.
627        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        // An overlap equal to chunk_size used to stop after the first chunk.
673        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        /// Chunking terminates for any UTF-8 text and any size pair, and every
693        /// chunk is a non-empty slice that advances through the text.
694        #[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        /// With no overlap the chunks partition the text, and none exceeds
718        /// `chunk_size` unless it is a single wider character.
719        #[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}