Skip to main content

deepdoc_core/
chunk.rs

1//! RAG chunking: `Document` → chunks that carry their heading context.
2//!
3//! Two ideas carry the whole module:
4//!
5//! * **Cut on block boundaries.** A paragraph, a table or a code block is never
6//!   split down the middle — only a single block bigger than the target size is,
7//!   and then at the friendliest boundary it offers (line, sentence, word).
8//! * **Every chunk knows where it sits.** The chain of enclosing headings
9//!   (`Handbook > Onboarding > Day one`) travels with the text, so an embedding
10//!   of "it takes two days" still carries what "it" was.
11//!
12//! Sizes are counted in **characters**, not tokens: a tokenizer means a model
13//! file or a large table inside a binary whose whole promise is that there is
14//! nothing to install. Roughly four characters per token is close enough to aim
15//! at an embedding model's window.
16//!
17//! `byte_range` indexes the Markdown rendering of the document — exactly what
18//! `deepdoc file --format md` prints, without front matter — and slicing it with
19//! the range gives the chunk's text back.
20
21use serde::{Deserialize, Serialize};
22
23use crate::model::{Block, Document};
24use crate::render;
25
26/// Default chunk size, in characters (see `docs/PRD/02-cli-spec.md`).
27pub const DEFAULT_CHUNK_SIZE: usize = 800;
28
29/// Options for [`chunk`].
30#[derive(Debug, Clone)]
31pub struct ChunkOpts {
32    /// Target chunk size, in characters.
33    pub size: usize,
34    /// Overlap between neighbouring chunks, in characters.
35    pub overlap: usize,
36}
37
38impl Default for ChunkOpts {
39    fn default() -> Self {
40        Self {
41            size: DEFAULT_CHUNK_SIZE,
42            overlap: 0,
43        }
44    }
45}
46
47/// One RAG chunk.
48///
49/// The field names are the public JSON schema (`docs/PRD/02-cli-spec.md`).
50/// `source` repeats the document path on purpose: chunks are usually flattened
51/// into a vector store one by one, and a chunk that cannot say where it came
52/// from is a citation you cannot follow back.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct Chunk {
55    pub text: String,
56    /// Enclosing headings, outermost first (`["Introduction", "Method"]`).
57    pub heading_path: Vec<String>,
58    /// Path the document was read from, when it is known.
59    pub source: Option<String>,
60    /// Byte range of the chunk inside the rendered Markdown.
61    pub byte_range: (usize, usize),
62}
63
64/// Split a document into chunks. Pure.
65pub fn chunk(doc: &Document, opts: &ChunkOpts) -> Vec<Chunk> {
66    let size = opts.size.max(1);
67    // The overlap must leave room for new text, or two neighbours would say
68    // almost the same thing and the second one would carry the work forward
69    // hardly at all.
70    let overlap = opts.overlap.min(size / 2);
71
72    let (markdown, ranges) = render::markdown_with_ranges(&doc.blocks);
73    let segments = segments(&markdown, &doc.blocks, &ranges, size);
74    let groups = pack(&markdown, &segments, size);
75
76    let source = doc.meta.source_path.clone();
77    let mut chunks = Vec::with_capacity(groups.len());
78
79    for (position, &(first, end)) in groups.iter().enumerate() {
80        let start = match position {
81            0 => first,
82            _ => overlap_start(&markdown, &segments, groups[position - 1].0, first, overlap),
83        };
84        let (from, to) = (segments[start].start, segments[end - 1].end);
85
86        chunks.push(Chunk {
87            text: markdown[from..to].to_string(),
88            // The path of the chunk's own first block: text pulled in as
89            // overlap belongs to the chunk before it.
90            heading_path: segments[first].path.clone(),
91            source: source.clone(),
92            byte_range: (from, to),
93        });
94    }
95
96    chunks
97}
98
99/// A unit that a chunk is built from: one block, or one piece of an oversized
100/// block.
101struct Segment {
102    start: usize,
103    end: usize,
104    /// Length in characters — what `size` is measured in.
105    chars: usize,
106    /// Enclosing headings at this point in the document.
107    path: Vec<String>,
108    /// True when the segment is a heading, and so opens a section.
109    heading: bool,
110}
111
112/// Walk the blocks, tracking the heading stack, and cut oversized blocks up.
113fn segments(
114    markdown: &str,
115    blocks: &[Block],
116    ranges: &[Option<(usize, usize)>],
117    size: usize,
118) -> Vec<Segment> {
119    let mut out = Vec::new();
120    let mut stack: Vec<(u8, String)> = Vec::new();
121
122    for (block, range) in blocks.iter().zip(ranges) {
123        let Some((start, end)) = *range else { continue };
124
125        if let Block::Heading { level, text } = block {
126            // Levels are clamped the same way the Markdown renderer clamps
127            // them, so `#######` and `######` close the same sections.
128            let level = (*level).clamp(1, 6);
129            while stack.last().is_some_and(|(open, _)| *open >= level) {
130                stack.pop();
131            }
132            stack.push((level, render::one_line(&text.plain_text())));
133        }
134
135        let path: Vec<String> = stack.iter().map(|(_, text)| text.clone()).collect();
136        let heading = matches!(block, Block::Heading { .. });
137
138        for (index, (start, end)) in split_block(&markdown[start..end], start, size)
139            .into_iter()
140            .enumerate()
141        {
142            out.push(Segment {
143                start,
144                end,
145                chars: markdown[start..end].chars().count(),
146                path: path.clone(),
147                heading: heading && index == 0,
148            });
149        }
150    }
151
152    out
153}
154
155/// Cut one oversized block into pieces of at most `size` characters.
156///
157/// Returns absolute ranges into the rendered Markdown. A block that already
158/// fits comes back whole — the common case, and the one the block-boundary
159/// promise is about.
160fn split_block(text: &str, base: usize, size: usize) -> Vec<(usize, usize)> {
161    if text.chars().count() <= size {
162        return vec![(base, base + text.len())];
163    }
164
165    let mut out = Vec::new();
166    let mut cursor = 0;
167
168    while cursor < text.len() {
169        let rest = &text[cursor..];
170        if rest.chars().count() <= size {
171            out.push((base + cursor, base + text.len()));
172            break;
173        }
174
175        let window = &rest[..byte_len(rest, size)];
176        let cut = cut_point(window);
177        let piece = rest[..cut].trim_end();
178        if !piece.is_empty() {
179            out.push((base + cursor, base + cursor + piece.len()));
180        }
181
182        // Step over the whitespace at the seam so the next piece starts on text.
183        let skipped = rest[cut..].len() - rest[cut..].trim_start().len();
184        cursor += cut + skipped;
185    }
186
187    out
188}
189
190/// Where to cut a window of text: the last line break, else the last sentence
191/// end, else the last word boundary, else the window itself.
192fn cut_point(window: &str) -> usize {
193    if let Some(index) = window.rfind('\n').filter(|index| *index > 0) {
194        return index + 1;
195    }
196
197    let sentence_end = window.char_indices().rfind(|(index, ch)| {
198        *index > 0
199            && matches!(ch, '.' | '!' | '?' | '…')
200            && window[index + ch.len_utf8()..]
201                .chars()
202                .next()
203                .is_none_or(char::is_whitespace)
204    });
205    if let Some((index, ch)) = sentence_end {
206        return index + ch.len_utf8();
207    }
208
209    window
210        .char_indices()
211        .rfind(|(index, ch)| *index > 0 && ch.is_whitespace())
212        .map_or(window.len(), |(index, _)| index)
213}
214
215/// Byte length of the first `chars` characters.
216fn byte_len(text: &str, chars: usize) -> usize {
217    text.char_indices()
218        .nth(chars)
219        .map_or(text.len(), |(index, _)| index)
220}
221
222/// Greedily group segments into chunks; returns half-open index ranges.
223///
224/// A chunk grows until the next segment would overflow it. Headings also break
225/// chunks, but not every heading: a document of many two-line sections would
226/// otherwise chunk into a crowd of fragments too small to embed. So a heading
227/// starts a new chunk when
228///
229/// * the current chunk is already worth keeping on its own (half the target), or
230/// * the heading climbs back out of the section running just before it —
231///   sibling and nested sections can share a chunk, `## Payroll` after
232///   `### Tools` cannot, or the chunk's heading path would lie about half its
233///   own text.
234fn pack(markdown: &str, segments: &[Segment], size: usize) -> Vec<(usize, usize)> {
235    let mut groups = Vec::new();
236    let mut start = 0;
237    let mut chars = 0;
238
239    for (index, segment) in segments.iter().enumerate() {
240        if index > start {
241            let gap = gap_chars(markdown, &segments[index - 1], segment);
242            let overflows = chars + gap + segment.chars > size;
243            let new_section = segment.heading
244                && (chars * 2 >= size || segment.path.len() < segments[index - 1].path.len());
245
246            if overflows || new_section {
247                groups.push((start, index));
248                start = index;
249                chars = 0;
250            } else {
251                chars += gap;
252            }
253        }
254        chars += segment.chars;
255    }
256
257    if start < segments.len() {
258        groups.push((start, segments.len()));
259    }
260    groups
261}
262
263/// Where a chunk starts once `overlap` characters of the previous one are
264/// pulled in: whole segments only, and never the previous chunk entire.
265fn overlap_start(
266    markdown: &str,
267    segments: &[Segment],
268    previous: usize,
269    first: usize,
270    overlap: usize,
271) -> usize {
272    let mut start = first;
273    let mut taken = 0;
274
275    while start > previous + 1 {
276        let segment = &segments[start - 1];
277        let gap = gap_chars(markdown, segment, &segments[start]);
278        if taken + gap + segment.chars > overlap {
279            break;
280        }
281        taken += gap + segment.chars;
282        start -= 1;
283    }
284
285    start
286}
287
288/// Characters of separator (usually the blank line) between two segments.
289fn gap_chars(markdown: &str, left: &Segment, right: &Segment) -> usize {
290    markdown[left.end..right.start].chars().count()
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::model::{Block, Inline, Metadata, Row};
297    use crate::render::{RenderOpts, to_markdown};
298
299    fn doc(blocks: Vec<Block>) -> Document {
300        Document {
301            meta: Metadata::default(),
302            blocks,
303        }
304    }
305
306    fn heading(level: u8, text: &str) -> Block {
307        Block::Heading {
308            level,
309            text: Inline::text(text),
310        }
311    }
312
313    fn opts(size: usize, overlap: usize) -> ChunkOpts {
314        ChunkOpts { size, overlap }
315    }
316
317    /// Every chunk must be a verbatim slice of the Markdown the CLI prints —
318    /// that is what `byte_range` promises.
319    fn check_ranges(doc: &Document, chunks: &[Chunk]) {
320        let markdown = to_markdown(doc, &RenderOpts::default());
321        for chunk in chunks {
322            let (start, end) = chunk.byte_range;
323            assert_eq!(
324                &markdown[start..end],
325                chunk.text,
326                "byte_range does not point at the chunk's text"
327            );
328        }
329    }
330
331    #[test]
332    fn empty_document_yields_no_chunks() {
333        let doc = Document::new(Metadata::default());
334        assert!(chunk(&doc, &ChunkOpts::default()).is_empty());
335    }
336
337    #[test]
338    fn a_short_document_is_one_chunk() {
339        let doc = doc(vec![Block::paragraph("hello")]);
340        let chunks = chunk(&doc, &ChunkOpts::default());
341        assert_eq!(chunks.len(), 1);
342        assert_eq!(chunks[0].text, "hello");
343        assert_eq!(chunks[0].byte_range, (0, 5));
344        check_ranges(&doc, &chunks);
345    }
346
347    #[test]
348    fn chunks_cut_on_block_boundaries() {
349        let doc = doc(vec![
350            Block::paragraph("a".repeat(40)),
351            Block::paragraph("b".repeat(40)),
352            Block::paragraph("c".repeat(40)),
353        ]);
354        let chunks = chunk(&doc, &opts(90, 0));
355
356        // Two paragraphs fit (40 + 2 + 40); the third opens the next chunk
357        // rather than being cut in half.
358        assert_eq!(chunks.len(), 2);
359        assert_eq!(
360            chunks[0].text,
361            format!("{}\n\n{}", "a".repeat(40), "b".repeat(40))
362        );
363        assert_eq!(chunks[1].text, "c".repeat(40));
364        check_ranges(&doc, &chunks);
365    }
366
367    #[test]
368    fn a_table_is_never_split_when_it_fits() {
369        let doc = doc(vec![
370            Block::paragraph("intro"),
371            Block::Table {
372                header: Some(Row::from_texts(["part", "qty"])),
373                rows: vec![Row::from_texts(["bolt", "4"])],
374            },
375        ]);
376        // Room for the table (44 characters) but not for the paragraph too.
377        let chunks = chunk(&doc, &opts(46, 0));
378        assert_eq!(chunks.len(), 2);
379        assert_eq!(chunks[0].text, "intro");
380        assert!(chunks[1].text.starts_with("| part | qty |"));
381        assert!(chunks[1].text.ends_with("| bolt | 4   |"));
382        check_ranges(&doc, &chunks);
383    }
384
385    #[test]
386    fn a_table_too_big_for_a_chunk_is_cut_between_rows() {
387        let rows: Vec<Row> = (0..20)
388            .map(|n| Row::from_texts([format!("row {n}"), n.to_string()]))
389            .collect();
390        let doc = doc(vec![Block::Table {
391            header: Some(Row::from_texts(["part", "qty"])),
392            rows,
393        }]);
394        let chunks = chunk(&doc, &opts(80, 0));
395
396        assert!(chunks.len() > 1);
397        for chunk in &chunks {
398            for line in chunk.text.lines() {
399                assert!(line.starts_with('|') && line.ends_with('|'), "{line:?}");
400            }
401        }
402        check_ranges(&doc, &chunks);
403    }
404
405    #[test]
406    fn heading_path_follows_the_outline() {
407        let doc = doc(vec![
408            heading(1, "Handbook"),
409            Block::paragraph("intro"),
410            heading(2, "Onboarding"),
411            Block::paragraph("day one"),
412            heading(3, "Tools"),
413            Block::paragraph("laptop"),
414            heading(2, "Payroll"),
415            Block::paragraph("monthly"),
416        ]);
417        // One block per chunk, so every path is easy to read off.
418        let chunks = chunk(&doc, &opts(12, 0));
419        let paths: Vec<Vec<String>> = chunks.iter().map(|c| c.heading_path.clone()).collect();
420
421        assert_eq!(paths[0], ["Handbook"]);
422        assert_eq!(paths[1], ["Handbook"]);
423        assert_eq!(paths[2], ["Handbook", "Onboarding"]);
424        assert_eq!(paths[3], ["Handbook", "Onboarding"]);
425        assert_eq!(paths[4], ["Handbook", "Onboarding", "Tools"]);
426        assert_eq!(paths[5], ["Handbook", "Onboarding", "Tools"]);
427        // A second `##` closes both `## Onboarding` and its `### Tools`.
428        assert_eq!(paths[6], ["Handbook", "Payroll"]);
429        check_ranges(&doc, &chunks);
430    }
431
432    #[test]
433    fn a_heading_starts_a_new_chunk_once_the_current_one_is_worth_keeping() {
434        let doc = doc(vec![
435            heading(2, "One"),
436            Block::paragraph("a".repeat(60)),
437            heading(2, "Two"),
438            Block::paragraph("b".repeat(20)),
439        ]);
440        let chunks = chunk(&doc, &opts(100, 0));
441
442        assert_eq!(chunks.len(), 2);
443        assert!(chunks[0].text.starts_with("## One"));
444        assert!(chunks[1].text.starts_with("## Two"));
445        assert_eq!(chunks[1].heading_path, ["Two"]);
446        check_ranges(&doc, &chunks);
447    }
448
449    #[test]
450    fn short_sections_are_merged_rather_than_left_as_fragments() {
451        let doc = doc(vec![
452            heading(2, "One"),
453            Block::paragraph("first"),
454            heading(2, "Two"),
455            Block::paragraph("second"),
456        ]);
457        let chunks = chunk(&doc, &opts(200, 0));
458        assert_eq!(chunks.len(), 1);
459        assert_eq!(chunks[0].heading_path, ["One"]);
460    }
461
462    #[test]
463    fn a_heading_that_leaves_the_section_breaks_the_chunk() {
464        let doc = doc(vec![
465            heading(1, "Handbook"),
466            heading(2, "Onboarding"),
467            heading(3, "Tools"),
468            Block::paragraph("laptop"),
469            heading(2, "Payroll"),
470            Block::paragraph("monthly"),
471        ]);
472        // Everything would fit in one chunk, but `## Payroll` climbs back out
473        // of `### Tools`: keeping them together would leave half the chunk
474        // filed under a heading path it has nothing to do with.
475        let chunks = chunk(&doc, &opts(500, 0));
476        assert_eq!(chunks.len(), 2);
477        assert_eq!(chunks[0].heading_path, ["Handbook"]);
478        assert!(chunks[0].text.ends_with("laptop"));
479        assert_eq!(chunks[1].heading_path, ["Handbook", "Payroll"]);
480        check_ranges(&doc, &chunks);
481    }
482
483    #[test]
484    fn overlap_repeats_whole_blocks() {
485        let doc = doc(vec![
486            Block::paragraph("a".repeat(30)),
487            Block::paragraph("b".repeat(30)),
488            Block::paragraph("c".repeat(30)),
489        ]);
490        let chunks = chunk(&doc, &opts(64, 32));
491
492        assert_eq!(chunks.len(), 2);
493        assert_eq!(
494            chunks[0].text,
495            format!("{}\n\n{}", "a".repeat(30), "b".repeat(30))
496        );
497        // The second chunk opens with the block that closed the first one.
498        assert_eq!(
499            chunks[1].text,
500            format!("{}\n\n{}", "b".repeat(30), "c".repeat(30))
501        );
502        check_ranges(&doc, &chunks);
503    }
504
505    #[test]
506    fn overlap_never_swallows_the_previous_chunk_whole() {
507        let doc = doc(vec![
508            Block::paragraph("a".repeat(20)),
509            Block::paragraph("b".repeat(20)),
510            Block::paragraph("c".repeat(20)),
511            Block::paragraph("d".repeat(20)),
512        ]);
513        // An overlap as large as the chunk itself is clamped, and at least one
514        // block always stays behind.
515        let chunks = chunk(&doc, &opts(44, 1000));
516        assert_eq!(chunks.len(), 2);
517        assert!(chunks[1].text.starts_with(&"b".repeat(20)));
518        check_ranges(&doc, &chunks);
519    }
520
521    #[test]
522    fn an_oversized_paragraph_is_cut_at_a_sentence_end() {
523        let sentence = format!("{}. ", "word ".repeat(9).trim_end());
524        let doc = doc(vec![Block::paragraph(sentence.repeat(4).trim_end())]);
525        let chunks = chunk(&doc, &opts(120, 0));
526
527        assert!(chunks.len() > 1);
528        for chunk in &chunks {
529            assert!(chunk.text.chars().count() <= 120, "{}", chunk.text);
530            assert!(
531                chunk.text.ends_with('.'),
532                "cut mid-sentence: {}",
533                chunk.text
534            );
535        }
536        check_ranges(&doc, &chunks);
537    }
538
539    #[test]
540    fn an_oversized_block_without_sentences_is_cut_between_words() {
541        let doc = doc(vec![Block::paragraph(
542            "alpha bravo charlie delta echo foxtrot",
543        )]);
544        let chunks = chunk(&doc, &opts(20, 0));
545
546        assert!(chunks.len() > 1);
547        for chunk in &chunks {
548            assert!(!chunk.text.starts_with(' ') && !chunk.text.ends_with(' '));
549            assert!(chunk.text.split_whitespace().all(|word| {
550                ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"].contains(&word)
551            }));
552        }
553        check_ranges(&doc, &chunks);
554    }
555
556    #[test]
557    fn a_single_unbreakable_run_is_cut_on_a_character_boundary() {
558        let doc = doc(vec![Block::paragraph("é".repeat(50))]);
559        let chunks = chunk(&doc, &opts(20, 0));
560        assert_eq!(chunks.len(), 3);
561        assert!(chunks.iter().all(|c| c.text.chars().count() <= 20));
562        check_ranges(&doc, &chunks);
563    }
564
565    #[test]
566    fn chunks_carry_the_source_path() {
567        let doc = Document {
568            meta: Metadata {
569                source_path: Some("handbook.pdf".into()),
570                ..Metadata::default()
571            },
572            blocks: vec![Block::paragraph("hello")],
573        };
574        let chunks = chunk(&doc, &ChunkOpts::default());
575        assert_eq!(chunks[0].source.as_deref(), Some("handbook.pdf"));
576    }
577
578    /// The chunk JSON schema is a public contract — this is what breaks when a
579    /// field is renamed.
580    #[test]
581    fn json_schema_snapshot() {
582        let chunk = Chunk {
583            text: "Body.".into(),
584            heading_path: vec!["Introduction".into()],
585            source: Some("paper.pdf".into()),
586            byte_range: (0, 5),
587        };
588        assert_eq!(
589            serde_json::to_value(&chunk).unwrap(),
590            serde_json::json!({
591                "text": "Body.",
592                "heading_path": ["Introduction"],
593                "source": "paper.pdf",
594                "byte_range": [0, 5],
595            })
596        );
597    }
598}