1use std::fmt::Write as _;
26
27use serde::{Deserialize, Serialize};
28use sha2::{Digest, Sha256};
29
30use crate::model::{Block, Document};
31use crate::render;
32
33pub const DEFAULT_CHUNK_SIZE: usize = 800;
35
36#[derive(Debug, Clone)]
38pub struct ChunkOpts {
39 pub size: usize,
41 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct Chunk {
62 pub text: String,
63 pub heading_path: Vec<String>,
65 pub source: Option<String>,
67 pub byte_range: (usize, usize),
69 pub hash: String,
71}
72
73const PATH_SEPARATOR: char = '\u{1F}';
75const FIELD_SEPARATOR: char = '\u{1E}';
77
78pub 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 let _ = write!(out, "{byte:02x}");
107 }
108 out
109}
110
111pub fn chunk(doc: &Document, opts: &ChunkOpts) -> Vec<Chunk> {
113 let size = opts.size.max(1);
114 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 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
149struct Segment {
152 start: usize,
153 end: usize,
154 chars: usize,
156 path: Vec<String>,
158 heading: bool,
160}
161
162fn 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 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
205fn 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 let skipped = rest[cut..].len() - rest[cut..].trim_start().len();
234 cursor += cut + skipped;
235 }
236
237 out
238}
239
240fn 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
265fn byte_len(text: &str, chars: usize) -> usize {
267 text.char_indices()
268 .nth(chars)
269 .map_or(text.len(), |(index, _)| index)
270}
271
272fn 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
313fn 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
338fn 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 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 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 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 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 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 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 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 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 #[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 assert_eq!(
665 first[0].hash,
666 chunk_hash(&first[0].heading_path, &first[0].text)
667 );
668 }
669
670 #[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 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 #[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 "hash": "sha256:4e9b39d64994e392fa7a19bc795b4272591d5442c2fc6b90ec432ff2bbf9efe9",
714 })
715 );
716 }
717}