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//!
21//! Every chunk also carries a `hash` of its own content, so an index can tell
22//! which chunks a parser upgrade actually changed instead of re-embedding a
23//! whole corpus. See [`chunk_hash`] for what goes into it.
24
25use std::fmt::Write as _;
26
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29
30use crate::model::{Block, Document};
31use crate::render;
32
33/// Default chunk size, in characters (see `docs/PRD/02-cli-spec.md`).
34pub const DEFAULT_CHUNK_SIZE: usize = 800;
35
36/// Options for [`chunk`].
37#[derive(Debug, Clone)]
38pub struct ChunkOpts {
39    /// Target chunk size, in characters.
40    pub size: usize,
41    /// Overlap between neighbouring chunks, in characters.
42    pub overlap: usize,
43}
44
45impl Default for ChunkOpts {
46    fn default() -> Self {
47        Self {
48            size: DEFAULT_CHUNK_SIZE,
49            overlap: 0,
50        }
51    }
52}
53
54/// One RAG chunk.
55///
56/// The field names are the public JSON schema (`docs/PRD/02-cli-spec.md`).
57/// `source` repeats the document path on purpose: chunks are usually flattened
58/// into a vector store one by one, and a chunk that cannot say where it came
59/// from is a citation you cannot follow back.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct Chunk {
62    pub text: String,
63    /// Enclosing headings, outermost first (`["Introduction", "Method"]`).
64    pub heading_path: Vec<String>,
65    /// Path the document was read from, when it is known.
66    pub source: Option<String>,
67    /// Byte range of the chunk inside the rendered Markdown.
68    pub byte_range: (usize, usize),
69    /// Content hash, `"sha256:<hex>"` — see [`chunk_hash`].
70    pub hash: String,
71}
72
73/// Separator between the heading path's own entries.
74const PATH_SEPARATOR: char = '\u{1F}';
75/// Separator between the heading path and the text.
76const FIELD_SEPARATOR: char = '\u{1E}';
77
78/// The content hash of a chunk: `"sha256:<hex>"` over its heading path and its
79/// text together.
80///
81/// The point of the hash is to answer "did this chunk change?" without
82/// re-embedding a corpus. That question is about what the chunk *means* in an
83/// index, and a chunk's meaning is not only its text: the enclosing headings
84/// (`Handbook > Onboarding > Day one`) travel with it and sit **outside** `text`
85/// for every chunk that does not open with its own heading. A document
86/// reorganised under new headings gives the same text a different context — the
87/// exact case the hash exists to catch — so the path is hashed too.
88///
89/// The two parts are joined with the ASCII unit and record separators, which do
90/// not occur in extracted text, so no text can spell out a different split.
91pub fn chunk_hash(heading_path: &[String], text: &str) -> String {
92    let mut hasher = Sha256::new();
93    for (index, heading) in heading_path.iter().enumerate() {
94        if index > 0 {
95            hasher.update([PATH_SEPARATOR as u8]);
96        }
97        hasher.update(heading.as_bytes());
98    }
99    hasher.update([FIELD_SEPARATOR as u8]);
100    hasher.update(text.as_bytes());
101
102    let mut out = String::with_capacity("sha256:".len() + 64);
103    out.push_str("sha256:");
104    for byte in hasher.finalize() {
105        // Writing into a String cannot fail.
106        let _ = write!(out, "{byte:02x}");
107    }
108    out
109}
110
111/// Split a document into chunks. Pure.
112pub fn chunk(doc: &Document, opts: &ChunkOpts) -> Vec<Chunk> {
113    let size = opts.size.max(1);
114    // The overlap must leave room for new text, or two neighbours would say
115    // almost the same thing and the second one would carry the work forward
116    // hardly at all.
117    let overlap = opts.overlap.min(size / 2);
118
119    let (markdown, ranges) = render::markdown_with_ranges(&doc.blocks);
120    let segments = segments(&markdown, &doc.blocks, &ranges, size);
121    let groups = pack(&markdown, &segments, size);
122
123    let source = doc.meta.source_path.clone();
124    let mut chunks = Vec::with_capacity(groups.len());
125
126    for (position, &(first, end)) in groups.iter().enumerate() {
127        let start = match position {
128            0 => first,
129            _ => overlap_start(&markdown, &segments, groups[position - 1].0, first, overlap),
130        };
131        let (from, to) = (segments[start].start, segments[end - 1].end);
132        let text = markdown[from..to].to_string();
133        // The path of the chunk's own first block: text pulled in as overlap
134        // belongs to the chunk before it.
135        let heading_path = segments[first].path.clone();
136
137        chunks.push(Chunk {
138            hash: chunk_hash(&heading_path, &text),
139            text,
140            heading_path,
141            source: source.clone(),
142            byte_range: (from, to),
143        });
144    }
145
146    chunks
147}
148
149/// A unit that a chunk is built from: one block, or one piece of an oversized
150/// block.
151struct Segment {
152    start: usize,
153    end: usize,
154    /// Length in characters — what `size` is measured in.
155    chars: usize,
156    /// Enclosing headings at this point in the document.
157    path: Vec<String>,
158    /// True when the segment is a heading, and so opens a section.
159    heading: bool,
160}
161
162/// Walk the blocks, tracking the heading stack, and cut oversized blocks up.
163fn segments(
164    markdown: &str,
165    blocks: &[Block],
166    ranges: &[Option<(usize, usize)>],
167    size: usize,
168) -> Vec<Segment> {
169    let mut out = Vec::new();
170    let mut stack: Vec<(u8, String)> = Vec::new();
171
172    for (block, range) in blocks.iter().zip(ranges) {
173        let Some((start, end)) = *range else { continue };
174
175        if let Block::Heading { level, text } = block {
176            // Levels are clamped the same way the Markdown renderer clamps
177            // them, so `#######` and `######` close the same sections.
178            let level = (*level).clamp(1, 6);
179            while stack.last().is_some_and(|(open, _)| *open >= level) {
180                stack.pop();
181            }
182            stack.push((level, render::one_line(&text.plain_text())));
183        }
184
185        let path: Vec<String> = stack.iter().map(|(_, text)| text.clone()).collect();
186        let heading = matches!(block, Block::Heading { .. });
187
188        for (index, (start, end)) in split_block(&markdown[start..end], start, size)
189            .into_iter()
190            .enumerate()
191        {
192            out.push(Segment {
193                start,
194                end,
195                chars: markdown[start..end].chars().count(),
196                path: path.clone(),
197                heading: heading && index == 0,
198            });
199        }
200    }
201
202    out
203}
204
205/// Cut one oversized block into pieces of at most `size` characters.
206///
207/// Returns absolute ranges into the rendered Markdown. A block that already
208/// fits comes back whole — the common case, and the one the block-boundary
209/// promise is about.
210fn split_block(text: &str, base: usize, size: usize) -> Vec<(usize, usize)> {
211    if text.chars().count() <= size {
212        return vec![(base, base + text.len())];
213    }
214
215    let mut out = Vec::new();
216    let mut cursor = 0;
217
218    while cursor < text.len() {
219        let rest = &text[cursor..];
220        if rest.chars().count() <= size {
221            out.push((base + cursor, base + text.len()));
222            break;
223        }
224
225        let window = &rest[..byte_len(rest, size)];
226        let cut = cut_point(window);
227        let piece = rest[..cut].trim_end();
228        if !piece.is_empty() {
229            out.push((base + cursor, base + cursor + piece.len()));
230        }
231
232        // Step over the whitespace at the seam so the next piece starts on text.
233        let skipped = rest[cut..].len() - rest[cut..].trim_start().len();
234        cursor += cut + skipped;
235    }
236
237    out
238}
239
240/// Where to cut a window of text: the last line break, else the last sentence
241/// end, else the last word boundary, else the window itself.
242fn cut_point(window: &str) -> usize {
243    if let Some(index) = window.rfind('\n').filter(|index| *index > 0) {
244        return index + 1;
245    }
246
247    let sentence_end = window.char_indices().rfind(|(index, ch)| {
248        *index > 0
249            && matches!(ch, '.' | '!' | '?' | '…')
250            && window[index + ch.len_utf8()..]
251                .chars()
252                .next()
253                .is_none_or(char::is_whitespace)
254    });
255    if let Some((index, ch)) = sentence_end {
256        return index + ch.len_utf8();
257    }
258
259    window
260        .char_indices()
261        .rfind(|(index, ch)| *index > 0 && ch.is_whitespace())
262        .map_or(window.len(), |(index, _)| index)
263}
264
265/// Byte length of the first `chars` characters.
266fn byte_len(text: &str, chars: usize) -> usize {
267    text.char_indices()
268        .nth(chars)
269        .map_or(text.len(), |(index, _)| index)
270}
271
272/// Greedily group segments into chunks; returns half-open index ranges.
273///
274/// A chunk grows until the next segment would overflow it. Headings also break
275/// chunks, but not every heading: a document of many two-line sections would
276/// otherwise chunk into a crowd of fragments too small to embed. So a heading
277/// starts a new chunk when
278///
279/// * the current chunk is already worth keeping on its own (half the target), or
280/// * the heading climbs back out of the section running just before it —
281///   sibling and nested sections can share a chunk, `## Payroll` after
282///   `### Tools` cannot, or the chunk's heading path would lie about half its
283///   own text.
284fn pack(markdown: &str, segments: &[Segment], size: usize) -> Vec<(usize, usize)> {
285    let mut groups = Vec::new();
286    let mut start = 0;
287    let mut chars = 0;
288
289    for (index, segment) in segments.iter().enumerate() {
290        if index > start {
291            let gap = gap_chars(markdown, &segments[index - 1], segment);
292            let overflows = chars + gap + segment.chars > size;
293            let new_section = segment.heading
294                && (chars * 2 >= size || segment.path.len() < segments[index - 1].path.len());
295
296            if overflows || new_section {
297                groups.push((start, index));
298                start = index;
299                chars = 0;
300            } else {
301                chars += gap;
302            }
303        }
304        chars += segment.chars;
305    }
306
307    if start < segments.len() {
308        groups.push((start, segments.len()));
309    }
310    groups
311}
312
313/// Where a chunk starts once `overlap` characters of the previous one are
314/// pulled in: whole segments only, and never the previous chunk entire.
315fn overlap_start(
316    markdown: &str,
317    segments: &[Segment],
318    previous: usize,
319    first: usize,
320    overlap: usize,
321) -> usize {
322    let mut start = first;
323    let mut taken = 0;
324
325    while start > previous + 1 {
326        let segment = &segments[start - 1];
327        let gap = gap_chars(markdown, segment, &segments[start]);
328        if taken + gap + segment.chars > overlap {
329            break;
330        }
331        taken += gap + segment.chars;
332        start -= 1;
333    }
334
335    start
336}
337
338/// Characters of separator (usually the blank line) between two segments.
339fn gap_chars(markdown: &str, left: &Segment, right: &Segment) -> usize {
340    markdown[left.end..right.start].chars().count()
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346    use crate::model::{Block, Inline, Metadata, Row};
347    use crate::render::{RenderOpts, to_markdown};
348
349    fn doc(blocks: Vec<Block>) -> Document {
350        Document {
351            meta: Metadata::default(),
352            blocks,
353        }
354    }
355
356    fn heading(level: u8, text: &str) -> Block {
357        Block::Heading {
358            level,
359            text: Inline::text(text),
360        }
361    }
362
363    fn opts(size: usize, overlap: usize) -> ChunkOpts {
364        ChunkOpts { size, overlap }
365    }
366
367    /// Every chunk must be a verbatim slice of the Markdown the CLI prints —
368    /// that is what `byte_range` promises.
369    fn check_ranges(doc: &Document, chunks: &[Chunk]) {
370        let markdown = to_markdown(doc, &RenderOpts::default());
371        for chunk in chunks {
372            let (start, end) = chunk.byte_range;
373            assert_eq!(
374                &markdown[start..end],
375                chunk.text,
376                "byte_range does not point at the chunk's text"
377            );
378        }
379    }
380
381    #[test]
382    fn empty_document_yields_no_chunks() {
383        let doc = Document::new(Metadata::default());
384        assert!(chunk(&doc, &ChunkOpts::default()).is_empty());
385    }
386
387    #[test]
388    fn a_short_document_is_one_chunk() {
389        let doc = doc(vec![Block::paragraph("hello")]);
390        let chunks = chunk(&doc, &ChunkOpts::default());
391        assert_eq!(chunks.len(), 1);
392        assert_eq!(chunks[0].text, "hello");
393        assert_eq!(chunks[0].byte_range, (0, 5));
394        check_ranges(&doc, &chunks);
395    }
396
397    #[test]
398    fn chunks_cut_on_block_boundaries() {
399        let doc = doc(vec![
400            Block::paragraph("a".repeat(40)),
401            Block::paragraph("b".repeat(40)),
402            Block::paragraph("c".repeat(40)),
403        ]);
404        let chunks = chunk(&doc, &opts(90, 0));
405
406        // Two paragraphs fit (40 + 2 + 40); the third opens the next chunk
407        // rather than being cut in half.
408        assert_eq!(chunks.len(), 2);
409        assert_eq!(
410            chunks[0].text,
411            format!("{}\n\n{}", "a".repeat(40), "b".repeat(40))
412        );
413        assert_eq!(chunks[1].text, "c".repeat(40));
414        check_ranges(&doc, &chunks);
415    }
416
417    #[test]
418    fn a_table_is_never_split_when_it_fits() {
419        let doc = doc(vec![
420            Block::paragraph("intro"),
421            Block::Table {
422                header: Some(Row::from_texts(["part", "qty"])),
423                rows: vec![Row::from_texts(["bolt", "4"])],
424            },
425        ]);
426        // Room for the table (44 characters) but not for the paragraph too.
427        let chunks = chunk(&doc, &opts(46, 0));
428        assert_eq!(chunks.len(), 2);
429        assert_eq!(chunks[0].text, "intro");
430        assert!(chunks[1].text.starts_with("| part | qty |"));
431        assert!(chunks[1].text.ends_with("| bolt | 4   |"));
432        check_ranges(&doc, &chunks);
433    }
434
435    #[test]
436    fn a_table_too_big_for_a_chunk_is_cut_between_rows() {
437        let rows: Vec<Row> = (0..20)
438            .map(|n| Row::from_texts([format!("row {n}"), n.to_string()]))
439            .collect();
440        let doc = doc(vec![Block::Table {
441            header: Some(Row::from_texts(["part", "qty"])),
442            rows,
443        }]);
444        let chunks = chunk(&doc, &opts(80, 0));
445
446        assert!(chunks.len() > 1);
447        for chunk in &chunks {
448            for line in chunk.text.lines() {
449                assert!(line.starts_with('|') && line.ends_with('|'), "{line:?}");
450            }
451        }
452        check_ranges(&doc, &chunks);
453    }
454
455    #[test]
456    fn heading_path_follows_the_outline() {
457        let doc = doc(vec![
458            heading(1, "Handbook"),
459            Block::paragraph("intro"),
460            heading(2, "Onboarding"),
461            Block::paragraph("day one"),
462            heading(3, "Tools"),
463            Block::paragraph("laptop"),
464            heading(2, "Payroll"),
465            Block::paragraph("monthly"),
466        ]);
467        // One block per chunk, so every path is easy to read off.
468        let chunks = chunk(&doc, &opts(12, 0));
469        let paths: Vec<Vec<String>> = chunks.iter().map(|c| c.heading_path.clone()).collect();
470
471        assert_eq!(paths[0], ["Handbook"]);
472        assert_eq!(paths[1], ["Handbook"]);
473        assert_eq!(paths[2], ["Handbook", "Onboarding"]);
474        assert_eq!(paths[3], ["Handbook", "Onboarding"]);
475        assert_eq!(paths[4], ["Handbook", "Onboarding", "Tools"]);
476        assert_eq!(paths[5], ["Handbook", "Onboarding", "Tools"]);
477        // A second `##` closes both `## Onboarding` and its `### Tools`.
478        assert_eq!(paths[6], ["Handbook", "Payroll"]);
479        check_ranges(&doc, &chunks);
480    }
481
482    #[test]
483    fn a_heading_starts_a_new_chunk_once_the_current_one_is_worth_keeping() {
484        let doc = doc(vec![
485            heading(2, "One"),
486            Block::paragraph("a".repeat(60)),
487            heading(2, "Two"),
488            Block::paragraph("b".repeat(20)),
489        ]);
490        let chunks = chunk(&doc, &opts(100, 0));
491
492        assert_eq!(chunks.len(), 2);
493        assert!(chunks[0].text.starts_with("## One"));
494        assert!(chunks[1].text.starts_with("## Two"));
495        assert_eq!(chunks[1].heading_path, ["Two"]);
496        check_ranges(&doc, &chunks);
497    }
498
499    #[test]
500    fn short_sections_are_merged_rather_than_left_as_fragments() {
501        let doc = doc(vec![
502            heading(2, "One"),
503            Block::paragraph("first"),
504            heading(2, "Two"),
505            Block::paragraph("second"),
506        ]);
507        let chunks = chunk(&doc, &opts(200, 0));
508        assert_eq!(chunks.len(), 1);
509        assert_eq!(chunks[0].heading_path, ["One"]);
510    }
511
512    #[test]
513    fn a_heading_that_leaves_the_section_breaks_the_chunk() {
514        let doc = doc(vec![
515            heading(1, "Handbook"),
516            heading(2, "Onboarding"),
517            heading(3, "Tools"),
518            Block::paragraph("laptop"),
519            heading(2, "Payroll"),
520            Block::paragraph("monthly"),
521        ]);
522        // Everything would fit in one chunk, but `## Payroll` climbs back out
523        // of `### Tools`: keeping them together would leave half the chunk
524        // filed under a heading path it has nothing to do with.
525        let chunks = chunk(&doc, &opts(500, 0));
526        assert_eq!(chunks.len(), 2);
527        assert_eq!(chunks[0].heading_path, ["Handbook"]);
528        assert!(chunks[0].text.ends_with("laptop"));
529        assert_eq!(chunks[1].heading_path, ["Handbook", "Payroll"]);
530        check_ranges(&doc, &chunks);
531    }
532
533    #[test]
534    fn overlap_repeats_whole_blocks() {
535        let doc = doc(vec![
536            Block::paragraph("a".repeat(30)),
537            Block::paragraph("b".repeat(30)),
538            Block::paragraph("c".repeat(30)),
539        ]);
540        let chunks = chunk(&doc, &opts(64, 32));
541
542        assert_eq!(chunks.len(), 2);
543        assert_eq!(
544            chunks[0].text,
545            format!("{}\n\n{}", "a".repeat(30), "b".repeat(30))
546        );
547        // The second chunk opens with the block that closed the first one.
548        assert_eq!(
549            chunks[1].text,
550            format!("{}\n\n{}", "b".repeat(30), "c".repeat(30))
551        );
552        check_ranges(&doc, &chunks);
553    }
554
555    #[test]
556    fn overlap_never_swallows_the_previous_chunk_whole() {
557        let doc = doc(vec![
558            Block::paragraph("a".repeat(20)),
559            Block::paragraph("b".repeat(20)),
560            Block::paragraph("c".repeat(20)),
561            Block::paragraph("d".repeat(20)),
562        ]);
563        // An overlap as large as the chunk itself is clamped, and at least one
564        // block always stays behind.
565        let chunks = chunk(&doc, &opts(44, 1000));
566        assert_eq!(chunks.len(), 2);
567        assert!(chunks[1].text.starts_with(&"b".repeat(20)));
568        check_ranges(&doc, &chunks);
569    }
570
571    #[test]
572    fn an_oversized_paragraph_is_cut_at_a_sentence_end() {
573        let sentence = format!("{}. ", "word ".repeat(9).trim_end());
574        let doc = doc(vec![Block::paragraph(sentence.repeat(4).trim_end())]);
575        let chunks = chunk(&doc, &opts(120, 0));
576
577        assert!(chunks.len() > 1);
578        for chunk in &chunks {
579            assert!(chunk.text.chars().count() <= 120, "{}", chunk.text);
580            assert!(
581                chunk.text.ends_with('.'),
582                "cut mid-sentence: {}",
583                chunk.text
584            );
585        }
586        check_ranges(&doc, &chunks);
587    }
588
589    #[test]
590    fn an_oversized_block_without_sentences_is_cut_between_words() {
591        let doc = doc(vec![Block::paragraph(
592            "alpha bravo charlie delta echo foxtrot",
593        )]);
594        let chunks = chunk(&doc, &opts(20, 0));
595
596        assert!(chunks.len() > 1);
597        for chunk in &chunks {
598            assert!(!chunk.text.starts_with(' ') && !chunk.text.ends_with(' '));
599            assert!(chunk.text.split_whitespace().all(|word| {
600                ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"].contains(&word)
601            }));
602        }
603        check_ranges(&doc, &chunks);
604    }
605
606    #[test]
607    fn a_single_unbreakable_run_is_cut_on_a_character_boundary() {
608        let doc = doc(vec![Block::paragraph("é".repeat(50))]);
609        let chunks = chunk(&doc, &opts(20, 0));
610        assert_eq!(chunks.len(), 3);
611        assert!(chunks.iter().all(|c| c.text.chars().count() <= 20));
612        check_ranges(&doc, &chunks);
613    }
614
615    #[test]
616    fn chunks_carry_the_source_path() {
617        let doc = Document {
618            meta: Metadata {
619                source_path: Some("handbook.pdf".into()),
620                ..Metadata::default()
621            },
622            blocks: vec![Block::paragraph("hello")],
623        };
624        let chunks = chunk(&doc, &ChunkOpts::default());
625        assert_eq!(chunks[0].source.as_deref(), Some("handbook.pdf"));
626    }
627
628    #[test]
629    fn every_chunk_carries_a_sha256_hash() {
630        let doc = doc(vec![
631            heading(1, "Handbook"),
632            Block::paragraph("a".repeat(60)),
633            heading(2, "Payroll"),
634            Block::paragraph("b".repeat(60)),
635        ]);
636        let chunks = chunk(&doc, &opts(80, 0));
637
638        assert!(chunks.len() > 1);
639        for chunk in &chunks {
640            let hex = chunk.hash.strip_prefix("sha256:").expect("prefixed hash");
641            assert_eq!(hex.len(), 64, "{}", chunk.hash);
642            assert!(
643                hex.chars()
644                    .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase())
645            );
646        }
647    }
648
649    /// The whole point of the hash: the same input must give the same one, run
650    /// after run and process after process.
651    #[test]
652    fn the_hash_is_deterministic() {
653        let doc = doc(vec![
654            heading(2, "Payroll"),
655            Block::paragraph("Salaries are paid monthly."),
656        ]);
657        let first = chunk(&doc, &ChunkOpts::default());
658        let second = chunk(&doc, &ChunkOpts::default());
659
660        let hashes: Vec<&str> = first.iter().map(|c| c.hash.as_str()).collect();
661        let again: Vec<&str> = second.iter().map(|c| c.hash.as_str()).collect();
662        assert_eq!(hashes, again);
663        // And it is the hash of the fields, not of some run-local state.
664        assert_eq!(
665            first[0].hash,
666            chunk_hash(&first[0].heading_path, &first[0].text)
667        );
668    }
669
670    /// The heading path is part of a chunk's identity: reorganising a document
671    /// changes what the same sentence means in an index, and that has to show.
672    #[test]
673    fn moving_a_chunk_under_a_new_heading_changes_the_hash() {
674        let text = "Salaries are paid monthly.";
675        let under_payroll = chunk_hash(&["Handbook".into(), "Payroll".into()], text);
676        let under_benefits = chunk_hash(&["Handbook".into(), "Benefits".into()], text);
677        assert_ne!(under_payroll, under_benefits);
678
679        // And the path is hashed as a path, not as a run of concatenated words:
680        // splitting one heading in two is a different chunk.
681        assert_ne!(
682            chunk_hash(&["Handbook".into(), "Payroll".into()], text),
683            chunk_hash(&["HandbookPayroll".into()], text)
684        );
685    }
686
687    #[test]
688    fn the_same_text_under_the_same_path_hashes_the_same() {
689        let path = vec!["Handbook".to_string()];
690        assert_eq!(chunk_hash(&path, "hello"), chunk_hash(&path, "hello"));
691        assert_ne!(chunk_hash(&path, "hello"), chunk_hash(&path, "hello "));
692    }
693
694    /// The chunk JSON schema is a public contract — this is what breaks when a
695    /// field is renamed.
696    #[test]
697    fn json_schema_snapshot() {
698        let chunk = Chunk {
699            text: "Body.".into(),
700            heading_path: vec!["Introduction".into()],
701            source: Some("paper.pdf".into()),
702            byte_range: (0, 5),
703            hash: chunk_hash(&["Introduction".to_string()], "Body."),
704        };
705        assert_eq!(
706            serde_json::to_value(&chunk).unwrap(),
707            serde_json::json!({
708                "text": "Body.",
709                "heading_path": ["Introduction"],
710                "source": "paper.pdf",
711                "byte_range": [0, 5],
712                // sha256 of "Introduction\u{1E}Body." — the path, then the text.
713                "hash": "sha256:4e9b39d64994e392fa7a19bc795b4272591d5442c2fc6b90ec432ff2bbf9efe9",
714            })
715        );
716    }
717}