Skip to main content

docling_core/
chunker.rs

1//! Document chunking for RAG pipelines — the Rust port of docling-core's
2//! `docling_core.transforms.chunker`.
3//!
4//! Two chunkers, matching docling's semantics output-for-output:
5//!
6//! * [`HierarchicalChunker`] walks the document tree and yields one chunk per
7//!   top-level item (paragraph, whole list, table, picture caption, …), each
8//!   carrying the heading path it sits under. Tables are serialized in
9//!   docling's *triplet* form (`row, column = value`), pictures contribute
10//!   their captions.
11//! * [`HybridChunker`] refines the hierarchical chunks with a tokenizer:
12//!   oversized chunks are split (at item boundaries first, then within the
13//!   text by docling's `semchunk` algorithm), and undersized neighbours that
14//!   share the same headings are merged back together.
15//!
16//! [`contextualize`] renders a chunk to the string an embedding model should
17//! see: the heading path plus the chunk text.
18//!
19//! Anything tokenizer-related is abstracted behind [`ChunkTokenizer`]; a
20//! HuggingFace `tokenizers` implementation ships behind the `chunking` cargo
21//! feature as [`HuggingFaceTokenizer`].
22
23use std::collections::{BTreeMap, VecDeque};
24
25use crate::document::{DoclingDocument, Node, Table};
26
27/// What kind of document item a [`ChunkItem`] points at — only what the
28/// hybrid splitting logic needs to know.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ChunkItemKind {
31    /// A text-ish item (paragraph, list item, code, formula, caption, …).
32    Text,
33    /// A table item (single-item oversized chunks re-split per line, repeating
34    /// docling's header handling).
35    Table,
36    /// A picture item.
37    Picture,
38}
39
40/// One document item contributing to a chunk — the analogue of an entry in
41/// docling's `DocMeta.doc_items`.
42#[derive(Debug, Clone, PartialEq)]
43pub struct ChunkItem {
44    /// The item's ref in [`DoclingDocument::export_to_json`] output
45    /// (`#/texts/12`, `#/tables/0`, `#/pictures/1`, …).
46    pub self_ref: String,
47    pub kind: ChunkItemKind,
48    /// The item serialized *standalone* (docling re-serializes individual
49    /// items when splitting an oversized multi-item chunk — e.g. a nested
50    /// list item flattens to `- text` with no indentation).
51    pub text: String,
52}
53
54/// One chunk — the analogue of docling's `DocChunk` (text + `DocMeta`).
55#[derive(Debug, Clone, PartialEq)]
56pub struct DocChunk {
57    /// The chunk body (markdown-flavoured, unescaped — same text docling puts
58    /// in `DocChunk.text`).
59    pub text: String,
60    /// The heading path above this chunk, outermost first (`DocMeta.headings`;
61    /// `None` when the chunk sits above any heading).
62    pub headings: Option<Vec<String>>,
63    /// The document items the chunk was built from (`DocMeta.doc_items`).
64    pub doc_items: Vec<ChunkItem>,
65}
66
67/// Render a chunk for embedding: the heading path, then the text, joined with
68/// newlines — docling's `BaseChunker.contextualize()`.
69pub fn contextualize(chunk: &DocChunk) -> String {
70    let mut parts: Vec<&str> = Vec::new();
71    if let Some(h) = &chunk.headings {
72        parts.extend(h.iter().map(String::as_str));
73    }
74    parts.push(&chunk.text);
75    parts.join("\n")
76}
77
78// ---------------------------------------------------------------------------
79// Hierarchical chunker
80// ---------------------------------------------------------------------------
81
82/// Structure-driven chunker: one chunk per document item, lists and inline
83/// groups kept whole, heading path tracked as metadata — docling-core's
84/// `HierarchicalChunker` with default parameters.
85#[derive(Debug, Clone, Default)]
86pub struct HierarchicalChunker;
87
88impl HierarchicalChunker {
89    /// Chunk the document.
90    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
91        let mut chunks = Vec::new();
92        self.chunk_with(doc, &mut |c| {
93            chunks.push(c);
94            true
95        });
96        chunks
97    }
98
99    /// Stream the chunks: `sink` is called with each chunk as the document
100    /// walk produces it, so a consumer can process (embed, forward) chunks
101    /// without materializing the whole `Vec` first. A `false` return from
102    /// `sink` cancels the walk. [`Self::chunk`] is this with a collecting
103    /// sink — the chunks and their order are identical.
104    ///
105    /// Each chunk's [`ChunkItem::self_ref`] is the item's ref in the
106    /// document's [JSON export](DoclingDocument::export_to_json_value)
107    /// (#1041): the walk numbers the flat nodes, which is the JSON's
108    /// numbering only for a document without an item tree, so the refs are
109    /// mapped onto the export's items ([`RefMapper`]).
110    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
111        let mut mapper = RefMapper::new(&doc.export_to_json_value());
112        Self::walk_nodes(doc, &mut |c| sink(mapper.remap(c)));
113    }
114
115    /// The walk itself, its refs in the flat nodes' numbering — what
116    /// [`HybridChunker`] splits and merges before the refs are mapped.
117    fn walk_nodes(doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
118        // The Markdown-fallback marks (#1205) are the Markdown export's alone.
119        let strip = crate::fallback::any_marks();
120        let mut sink = |mut c: DocChunk| {
121            if strip {
122                c.text = crate::fallback::strip_owned(std::mem::take(&mut c.text));
123                for h in c.headings.iter_mut().flatten() {
124                    *h = crate::fallback::strip_owned(std::mem::take(h));
125                }
126                for it in &mut c.doc_items {
127                    it.text = crate::fallback::strip_owned(std::mem::take(&mut it.text));
128                }
129            }
130            sink(c)
131        };
132        let mut w = Walker {
133            alloc: Alloc::default(),
134            headings: BTreeMap::new(),
135            stopped: false,
136            sink: &mut sink,
137        };
138        w.walk(&doc.nodes);
139    }
140}
141
142/// Maps the walk's chunk items onto the document's JSON export — a port of
143/// `docling_rs.chunking._RefMapper`, which the Python binding has applied to
144/// the caller's document since #1012.
145///
146/// The walk numbers the flat nodes the way the JSON export numbers a
147/// document *without* an item tree; a backend's tree (HTML, DOCX, ODF, JATS,
148/// LaTeX, …) is numbered by its own structure — a furniture title first, an
149/// inline paragraph as several runs, empty items kept — so the refs drift
150/// (#1041: on the corpus half of the text refs pointed at another item). The
151/// items still arrive in (nearly) reading order with their kind and Markdown
152/// text, so each is matched against the export's items walked in the same
153/// order (the `body` tree, pictures and tables not descended): a table or
154/// picture to the next untaken one of its kind, a text to an item it renders
155/// exactly (`Section 2` for `[Section 2](#s2)`, `x` for `- x`), else by
156/// containment close to the last match — an inline paragraph the walk
157/// reports as one item then maps to the run of items it contains. Candidates
158/// lie in a window around the last match, so an item emitted out of tree
159/// order (a caption next to its float) neither strands the rest nor goes
160/// unmatched; an item repeated across the chunks it is split into maps to
161/// the same items again. An item that matches nothing is left out rather
162/// than pointed at the wrong item.
163struct RefMapper {
164    /// The export's items in reading order: `(ref, kind, normalized text)`.
165    order: Vec<(String, ChunkItemKind, String)>,
166    /// Per item, a list item's marker and text as its Markdown prints them
167    /// (`甲. 甲项`), the marker being a field of its own in the JSON.
168    marked: Vec<Option<String>>,
169    taken: Vec<bool>,
170    /// The earliest untaken item.
171    low: usize,
172    /// One past the latest match.
173    last: usize,
174    seen: std::collections::HashMap<(String, ChunkItemKind, String), Vec<usize>>,
175}
176
177impl RefMapper {
178    const WINDOW: usize = 64;
179    const NEAR: usize = 16;
180    const MIN_CONTAINED: usize = 4;
181
182    fn new(doc: &serde_json::Value) -> Self {
183        use serde_json::Value;
184        let mut index: std::collections::HashMap<&str, &Value> = std::collections::HashMap::new();
185        for key in [
186            "texts",
187            "tables",
188            "pictures",
189            "groups",
190            "field_regions",
191            "field_items",
192            "key_value_items",
193            "form_items",
194        ] {
195            for it in doc.get(key).and_then(Value::as_array).into_iter().flatten() {
196                if let Some(r) = it.get("self_ref").and_then(Value::as_str) {
197                    index.insert(r, it);
198                }
199            }
200        }
201        let children = |v: &Value| -> Vec<String> {
202            v.get("children")
203                .and_then(Value::as_array)
204                .into_iter()
205                .flatten()
206                .filter_map(|c| c.get("$ref").or_else(|| c.get("cref")))
207                .filter_map(Value::as_str)
208                .map(str::to_string)
209                .collect()
210        };
211        let mut order = Vec::new();
212        let mut marked: Vec<Option<String>> = Vec::new();
213        let mut stack: Vec<std::vec::IntoIter<String>> = doc
214            .get("body")
215            .map(|b| vec![children(b).into_iter()])
216            .unwrap_or_default();
217        // A crafted document can list an item twice or cyclically: each is
218        // walked once.
219        let mut visited = std::collections::HashSet::new();
220        while let Some(top) = stack.last_mut() {
221            let Some(r) = top.next() else {
222                stack.pop();
223                continue;
224            };
225            let Some(it) = index.get(r.as_str()).copied() else {
226                continue;
227            };
228            if !visited.insert(r.clone()) {
229                continue;
230            }
231            let text_of = |it: &Value| norm(it.get("text").and_then(Value::as_str).unwrap_or(""));
232            if r.starts_with("#/texts/") {
233                let marker = it.get("marker").and_then(Value::as_str).unwrap_or("");
234                while marked.len() < order.len() {
235                    marked.push(None);
236                }
237                marked
238                    .push((!marker.is_empty()).then(|| norm(&format!("{marker} {}", text_of(it)))));
239                order.push((r, ChunkItemKind::Text, text_of(it)));
240            } else if r.starts_with("#/tables/") || r.starts_with("#/pictures/") {
241                // A float is not descended, but its captions and footnotes are
242                // chunked with it — wherever they hang (a PDF caption is the
243                // float's child, a declarative one the body's).
244                let refs = |key: &str| -> Vec<String> {
245                    it.get(key)
246                        .and_then(Value::as_array)
247                        .into_iter()
248                        .flatten()
249                        .filter_map(|c| c.get("$ref").and_then(Value::as_str))
250                        .map(str::to_string)
251                        .collect()
252                };
253                let mut sat = |order: &mut Vec<(String, ChunkItemKind, String)>, key: &str| {
254                    for c in refs(key) {
255                        if let Some(t) = index.get(c.as_str()) {
256                            if visited.insert(c.clone()) {
257                                order.push((c, ChunkItemKind::Text, text_of(t)));
258                            }
259                        }
260                    }
261                };
262                sat(&mut order, "captions");
263                let kind = if r.starts_with("#/tables/") {
264                    ChunkItemKind::Table
265                } else {
266                    ChunkItemKind::Picture
267                };
268                order.push((r, kind, String::new()));
269                sat(&mut order, "footnotes");
270                continue;
271            }
272            stack.push(children(it).into_iter());
273        }
274        let n = order.len();
275        marked.resize(n, None);
276        RefMapper {
277            order,
278            marked,
279            taken: vec![false; n],
280            low: 0,
281            last: 0,
282            seen: std::collections::HashMap::new(),
283        }
284    }
285
286    /// Untaken items of `kind` in `[lo, hi)`, nearest-first: forward from
287    /// the last match, then backward.
288    fn near(&self, lo: usize, hi: usize, used: &[usize], kind: ChunkItemKind) -> Vec<usize> {
289        let last = self.last.max(lo).min(hi);
290        (last..hi)
291            .chain((lo..last).rev())
292            .filter(|&i| !self.taken[i] && !used.contains(&i) && self.order[i].1 == kind)
293            .collect()
294    }
295
296    fn find(
297        &self,
298        (lo, hi): (usize, usize),
299        used: &[usize],
300        kind: ChunkItemKind,
301        text: &str,
302    ) -> Option<usize> {
303        if kind != ChunkItemKind::Text {
304            return self.near(lo, hi, used, kind).first().copied();
305        }
306        let plain = plain(text);
307        if let Some(i) = self
308            .near(lo, hi, used, kind)
309            .into_iter()
310            .find(|&i| self.matches(i, text, &plain))
311        {
312            return Some(i);
313        }
314        // Containment only close to the last match and for texts long enough
315        // to mean something: a short one ("duck", ")") is contained in many
316        // renderings and would pull the mapping out of step.
317        let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
318        let near_hi = hi.min(self.last + Self::NEAR);
319        if near_lo >= near_hi {
320            return None;
321        }
322        self.near(near_lo, near_hi, used, kind)
323            .into_iter()
324            .find(|&i| {
325                let t = &self.order[i].2;
326                t.chars().count() >= Self::MIN_CONTAINED && text.contains(t.as_str())
327            })
328    }
329
330    /// Whether item `i` is what `text` (or its plain form) renders exactly.
331    fn matches(&self, i: usize, text: &str, plain: &str) -> bool {
332        let t = &self.order[i].2;
333        t == text || t == plain || self.marked[i].as_deref().is_some_and(|m| m == plain)
334    }
335
336    /// Past the window, forward from the last match: an item matched
337    /// exactly, or a long one the rendering contains — what is left when the
338    /// walk skipped more of the export than the window spans (a large
339    /// region it does not chunk). Short texts never match this far.
340    fn find_far(&self, used: &[usize], kind: ChunkItemKind, text: &str) -> Option<usize> {
341        const FAR_CONTAINED: usize = 16;
342        // Bounded, so a document whose walk emits many items the export
343        // lacks stays linear.
344        const FAR: usize = 4096;
345        if kind != ChunkItemKind::Text || text.chars().count() < FAR_CONTAINED {
346            return None;
347        }
348        let plain = plain(text);
349        let free = |i: &usize| !self.taken[*i] && !used.contains(i) && self.order[*i].1 == kind;
350        let end = self.order.len().min(self.last + FAR);
351        let far = || (self.last..end).filter(free);
352        far().find(|&i| self.matches(i, text, &plain)).or_else(|| {
353            far().find(|&i| {
354                let t = &self.order[i].2;
355                t.chars().count() >= FAR_CONTAINED && text.contains(t.as_str())
356            })
357        })
358    }
359
360    /// A text the walk split off one of the export's items (a paragraph cut
361    /// at what its inline parser took for markup): the item that contains
362    /// it — the latest match first, though already taken, then an untaken
363    /// one close to it. Only for texts long enough to place.
364    fn part_of(&self, lo: usize, hi: usize, text: &str) -> Option<usize> {
365        let piece = plain(text);
366        if piece.chars().count() < 2 * Self::MIN_CONTAINED {
367            return None;
368        }
369        let contains = |i: usize| {
370            self.order[i].1 == ChunkItemKind::Text && self.order[i].2.contains(piece.as_str())
371        };
372        if let Some(prev) = self.last.checked_sub(1).filter(|&p| contains(p)) {
373            return Some(prev);
374        }
375        let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
376        let near_hi = hi.min(self.last + Self::NEAR);
377        (near_lo..near_hi).find(|&i| !self.taken[i] && contains(i))
378    }
379
380    /// The text items after a containment match that the same rendering
381    /// also contains, in order — the runs of an inline paragraph.
382    fn runs_after(&self, hit: usize, hi: usize, used: &[usize], text: &str) -> Vec<usize> {
383        let first = &self.order[hit].2;
384        let mut pos = text.find(first.as_str()).map_or(0, |p| p + first.len());
385        let mut extra = Vec::new();
386        let mut j = hit + 1;
387        while j < hi
388            && !self.taken[j]
389            && !used.contains(&j)
390            && self.order[j].1 == ChunkItemKind::Text
391        {
392            let t = &self.order[j].2;
393            let Some(at) = (!t.is_empty())
394                .then(|| text.get(pos..).and_then(|rest| rest.find(t.as_str())))
395                .flatten()
396            else {
397                break;
398            };
399            extra.push(j);
400            pos += at + t.len();
401            j += 1;
402        }
403        extra
404    }
405
406    fn remap(&mut self, mut chunk: DocChunk) -> DocChunk {
407        let n = chunk.doc_items.len();
408        let lo = self.low.max(self.last.saturating_sub(Self::WINDOW));
409        let hi = self.order.len().min(self.last + Self::WINDOW + n);
410        let mut used: Vec<usize> = Vec::new();
411        let mut items = Vec::with_capacity(n);
412        for item in std::mem::take(&mut chunk.doc_items) {
413            let text = norm(&item.text);
414            let key = (item.self_ref.clone(), item.kind, text.clone());
415            let mut runs = self
416                .seen
417                .get(&key)
418                .filter(|r| !r.iter().any(|h| used.contains(h)))
419                .cloned();
420            if runs.is_none() && lo < hi {
421                let hit = self
422                    .find((lo, hi), &used, item.kind, &text)
423                    .or_else(|| self.find_far(&used, item.kind, &text));
424                if let Some(hit) = hit {
425                    let mut r = vec![hit];
426                    if item.kind == ChunkItemKind::Text && !self.matches(hit, &text, &plain(&text))
427                    {
428                        r.extend(self.runs_after(hit, hi, &used, &text));
429                    }
430                    self.seen.insert(key, r.clone());
431                    runs = Some(r);
432                } else if item.kind == ChunkItemKind::Text {
433                    runs = self.part_of(lo, hi, &text).map(|h| vec![h]);
434                }
435            }
436            let Some(runs) = runs else {
437                crate::debug_log!(
438                    "chunker: no JSON item for {} ({:?}) in [{lo}, {hi}), last {}",
439                    item.self_ref,
440                    text.chars().take(60).collect::<String>(),
441                    self.last
442                );
443                continue;
444            };
445            for (k, &h) in runs.iter().enumerate() {
446                if items
447                    .iter()
448                    .any(|i: &ChunkItem| i.self_ref == self.order[h].0)
449                {
450                    continue; // another piece of the same item
451                }
452                used.push(h);
453                self.taken[h] = true;
454                self.last = self.last.max(h + 1);
455                // The walk's item keeps its own text (what the hybrid splitter
456                // re-serializes); the runs after it are the export's items.
457                items.push(ChunkItem {
458                    self_ref: self.order[h].0.clone(),
459                    kind: item.kind,
460                    text: if k == 0 {
461                        item.text.clone()
462                    } else {
463                        self.order[h].2.clone()
464                    },
465                });
466            }
467        }
468        while self.low < self.taken.len() && self.taken[self.low] {
469            self.low += 1;
470        }
471        chunk.doc_items = items;
472        chunk
473    }
474}
475
476/// `_norm`: an item text comparable to its Markdown rendering — entities
477/// decoded, escapes dropped, whitespace collapsed.
478fn norm(text: &str) -> String {
479    crate::doclang_xml::decode_entities(text)
480        .replace('\\', "")
481        .split_whitespace()
482        .collect::<Vec<_>>()
483        .join(" ")
484}
485
486/// `_plain`: a Markdown item rendering reduced toward the item's plain text —
487/// link targets, emphasis and code markers and a heading or list prefix
488/// dropped.
489fn plain(md: &str) -> String {
490    use std::sync::OnceLock;
491    static LINK: OnceLock<regex::Regex> = OnceLock::new();
492    static PREFIX: OnceLock<regex::Regex> = OnceLock::new();
493    let link = LINK.get_or_init(|| regex::Regex::new(r"!?\[([^\]]*)\]\([^)]*\)").expect("static"));
494    let prefix = PREFIX.get_or_init(|| {
495        regex::Regex::new(r"^(#{1,6}(\s+|$)|[-*+](\s+\[[ xX]\])?(\s+|$)|\d+[.)](\s+|$))")
496            .expect("static")
497    });
498    let mut text = link.replace_all(md, "$1").into_owned();
499    for marker in ["**", "~~", "`", "*"] {
500        text = text.replace(marker, "");
501    }
502    let text = prefix.replace(&text, "");
503    // A formula renders in `$$…$$` / `$…$`.
504    let text = text.trim();
505    let text = text
506        .strip_prefix("$$")
507        .and_then(|t| t.strip_suffix("$$"))
508        .or_else(|| text.strip_prefix('$').and_then(|t| t.strip_suffix('$')))
509        .unwrap_or(text);
510    text.trim().to_string()
511}
512
513/// Ref allocator mirroring the numbering `json.rs` gives every item, so
514/// `ChunkItem::self_ref` matches the document's JSON export.
515#[derive(Debug, Default)]
516struct Alloc {
517    texts: usize,
518    groups: usize,
519    tables: usize,
520    pictures: usize,
521    field_regions: usize,
522    field_items: usize,
523}
524
525impl Alloc {
526    fn text(&mut self) -> String {
527        let r = format!("#/texts/{}", self.texts);
528        self.texts += 1;
529        r
530    }
531    fn group(&mut self) -> String {
532        let r = format!("#/groups/{}", self.groups);
533        self.groups += 1;
534        r
535    }
536    fn table(&mut self) -> String {
537        let r = format!("#/tables/{}", self.tables);
538        self.tables += 1;
539        r
540    }
541    fn picture(&mut self) -> String {
542        let r = format!("#/pictures/{}", self.pictures);
543        self.pictures += 1;
544        r
545    }
546    fn field_region(&mut self) -> String {
547        let r = format!("#/field_regions/{}", self.field_regions);
548        self.field_regions += 1;
549        r
550    }
551    fn field_item(&mut self) -> String {
552        let r = format!("#/field_items/{}", self.field_items);
553        self.field_items += 1;
554        r
555    }
556}
557
558struct Walker<'s> {
559    alloc: Alloc,
560    /// Active heading per docling level (title = 0, `section_header` = its
561    /// `level`), pruned like docling's `heading_by_level`.
562    headings: BTreeMap<u8, String>,
563    /// Set once the sink refuses a chunk; the walk unwinds without emitting.
564    stopped: bool,
565    sink: &'s mut dyn FnMut(DocChunk) -> bool,
566}
567
568impl Walker<'_> {
569    fn emit(&mut self, text: String, doc_items: Vec<ChunkItem>) {
570        if self.stopped || text.is_empty() {
571            return;
572        }
573        let headings: Vec<String> = self.headings.values().cloned().collect();
574        self.stopped = !(self.sink)(DocChunk {
575            text,
576            headings: (!headings.is_empty()).then_some(headings),
577            doc_items,
578        });
579    }
580
581    /// Emit a text chunk whose doc items follow docling's inline granularity:
582    /// mixed inline content (a paragraph docling represents as an inline group)
583    /// contributes one item per span, plain text one item.
584    fn emit_inline(&mut self, md_text: &str, self_ref: String) {
585        self.emit_inline_with_runs(md_text, self_ref, &[]);
586    }
587
588    fn emit_inline_with_runs(
589        &mut self,
590        md_text: &str,
591        self_ref: String,
592        runs: &[crate::InlineRun],
593    ) {
594        let body = unescape_text(md_text);
595        if body.is_empty() {
596            return;
597        }
598        let segments: Vec<String> = inline_segments_tagged(md_text, runs)
599            .into_iter()
600            .flat_map(|(text, is_plain)| {
601                if is_plain {
602                    if let Some(split) = split_plain_by_runs(&text, runs) {
603                        return split;
604                    }
605                }
606                vec![text]
607            })
608            .collect();
609        let items: Vec<ChunkItem> = if segments.len() <= 1 {
610            vec![ChunkItem {
611                self_ref,
612                kind: ChunkItemKind::Text,
613                text: body.clone(),
614            }]
615        } else {
616            segments
617                .into_iter()
618                .map(|text| ChunkItem {
619                    self_ref: self_ref.clone(),
620                    kind: ChunkItemKind::Text,
621                    text,
622                })
623                .collect()
624        };
625        self.emit(body, items);
626    }
627
628    fn set_heading(&mut self, doc_level: u8, text: String) {
629        self.headings.retain(|k, _| *k < doc_level);
630        self.headings.insert(doc_level, text);
631    }
632
633    fn walk(&mut self, nodes: &[Node]) {
634        let mut i = 0;
635        while i < nodes.len() {
636            if self.stopped {
637                return;
638            }
639            if matches!(nodes[i], Node::ListItem { .. }) {
640                let start = i;
641                i += 1;
642                loop {
643                    match nodes.get(i) {
644                        Some(Node::ListItem { .. }) => i += 1,
645                        // An empty paragraph between two list items is absorbed
646                        // into the run (mirrors json.rs / markdown.rs).
647                        Some(Node::Paragraph { text })
648                            if text.is_empty()
649                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
650                        {
651                            i += 1
652                        }
653                        _ => break,
654                    }
655                }
656                self.sibling_lists(&nodes[start..i]);
657            } else {
658                self.one(&nodes[i]);
659                i += 1;
660            }
661        }
662    }
663
664    /// Split a run of list items into sibling lists exactly like
665    /// `json.rs::add_sibling_lists`, chunking each list separately (docling
666    /// yields one chunk per `ListGroup`).
667    fn sibling_lists(&mut self, run: &[Node]) {
668        let base = level_of(&run[0]);
669        let mut seg = 0;
670        for k in 0..run.len() {
671            let Node::ListItem {
672                first_in_list,
673                level,
674                ..
675            } = &run[k]
676            else {
677                continue;
678            };
679            if *level != base {
680                continue; // nested item — handled inside `list`
681            }
682            // The backend's list boundary, as in `json.rs::add_sibling_lists`.
683            if k > seg && *first_in_list {
684                self.list(&run[seg..k]);
685                seg = k;
686            }
687        }
688        self.list(&run[seg..]);
689    }
690
691    /// One `ListGroup`: allocate refs in `json.rs::add_list` order (group,
692    /// then per top item its text ref followed by any nested groups) and emit
693    /// a single chunk whose text is the indented markdown list.
694    fn list(&mut self, items: &[Node]) {
695        self.alloc.group();
696        let mut chunk_items = Vec::new();
697        self.list_refs(items, &mut chunk_items);
698        let text = render_list(items);
699        self.emit(text, chunk_items);
700    }
701
702    /// Allocate refs for one list's items (and nested sibling lists), mirroring
703    /// `json.rs::add_list` / `add_sibling_lists` recursion, collecting the
704    /// non-furniture items in allocation (= document) order.
705    fn list_refs(&mut self, items: &[Node], out: &mut Vec<ChunkItem>) {
706        let base = level_of(&items[0]);
707        let mut i = 0;
708        while i < items.len() {
709            let Node::ListItem {
710                ordered,
711                number,
712                text,
713                level,
714                layer,
715                ..
716            } = &items[i]
717            else {
718                i += 1;
719                continue;
720            };
721            if *level > base {
722                i += 1;
723                continue;
724            }
725            let item_ref = self.alloc.text();
726            let mut j = i + 1;
727            while j < items.len() && level_of(&items[j]) > base {
728                j += 1;
729            }
730            let has_nested = j > i + 1;
731            if layer.is_none() {
732                let marker = if *ordered {
733                    format!("{number}.")
734                } else {
735                    "-".to_string()
736                };
737                // An item that carries both inline spans and a nested list is an
738                // empty list item wrapping an inline group in docling's model:
739                // its marker and each inline span are separate doc items.
740                // docling represents a list item whose content is not pure
741                // inline text (it carries a nested list or child pictures) as
742                // an empty item wrapping an inline group: its marker and each
743                // inline span become separate doc items.
744                // docling represents a list item whose content is not pure
745                // inline text (it carries a nested list or its own images) as
746                // an empty item wrapping an inline group: its marker and each
747                // inline span become separate doc items. The chunker's
748                // image placeholder is empty, so the markers are stripped from
749                // the text before segmentation.
750                let has_pics = text.contains("<!-- image -->");
751                let text = strip_image_markers(text);
752                let text = text.as_str();
753                let segments = inline_segments(text);
754                if (has_nested || has_pics) && segments.len() > 1 && text.contains("](") {
755                    out.push(ChunkItem {
756                        self_ref: item_ref.clone(),
757                        kind: ChunkItemKind::Text,
758                        text: format!("{marker} "),
759                    });
760                    for seg in segments {
761                        out.push(ChunkItem {
762                            self_ref: item_ref.clone(),
763                            kind: ChunkItemKind::Text,
764                            text: seg,
765                        });
766                    }
767                } else {
768                    out.push(ChunkItem {
769                        self_ref: item_ref.clone(),
770                        kind: ChunkItemKind::Text,
771                        text: format!("{marker} {}", unescape_text(text)),
772                    });
773                }
774            }
775            // nested items group under this one; each nested sibling list is a
776            // fresh group ref
777            if j > i + 1 {
778                self.nested_sibling_lists(&items[i + 1..j], out);
779            }
780            i = j;
781        }
782    }
783
784    fn nested_sibling_lists(&mut self, run: &[Node], out: &mut Vec<ChunkItem>) {
785        let base = level_of(&run[0]);
786        let mut seg = 0;
787        for k in 0..run.len() {
788            let Node::ListItem {
789                first_in_list,
790                level,
791                ..
792            } = &run[k]
793            else {
794                continue;
795            };
796            if *level != base {
797                continue;
798            }
799            if k > seg && *first_in_list {
800                self.alloc.group();
801                self.list_refs(&run[seg..k], out);
802                seg = k;
803            }
804        }
805        self.alloc.group();
806        self.list_refs(&run[seg..], out);
807    }
808
809    fn one(&mut self, node: &Node) {
810        match node {
811            Node::Heading { level, text } => {
812                let doc_level = if *level == 1 {
813                    0
814                } else {
815                    level.saturating_sub(1)
816                };
817                self.alloc.text();
818                // docling stores heading text unformatted: a heading that is one
819                // uniformly formatted span keeps its plain text; a *partially*
820                // formatted heading becomes an empty heading whose only child is
821                // an inline group. docling-core 2.106 (docling-core#924, #1012)
822                // serializes that child as the heading's context and consumes
823                // it, so it is no longer a body chunk under an empty heading.
824                let runs = crate::inline_runs_from_markdown(text);
825                let heading = if runs.len() <= 1 {
826                    runs.first()
827                        .map(|r| r.text.clone())
828                        .unwrap_or_else(|| text.clone())
829                } else {
830                    text.clone()
831                };
832                self.set_heading(doc_level, unescape_text(&heading));
833            }
834            Node::Paragraph { text } | Node::ListText { text, .. } => {
835                let t = text.trim();
836                let self_ref = self.alloc.text();
837                // A whole-paragraph display equation is a formula item; docling's
838                // chunk serializer re-wraps the raw latex in `$$…$$`.
839                if let Some(inner) = t
840                    .strip_prefix("$$")
841                    .and_then(|s| s.strip_suffix("$$"))
842                    .filter(|s| !s.is_empty())
843                {
844                    let body = format!("$${inner}$$");
845                    self.emit(
846                        body.clone(),
847                        vec![ChunkItem {
848                            self_ref,
849                            kind: ChunkItemKind::Text,
850                            text: body,
851                        }],
852                    );
853                    return;
854                }
855                self.emit_inline(text, self_ref);
856            }
857            // A standalone caption chunks like any text item (docling's chunker
858            // does not treat `caption` specially outside a table/picture).
859            Node::Caption { text, .. } => {
860                let self_ref = self.alloc.text();
861                self.emit_inline(text, self_ref);
862            }
863            Node::LabeledText { .. } => self.one(&node.labeled_as_paragraph()),
864            Node::CheckboxItem { checked, text } => {
865                let self_ref = self.alloc.text();
866                let mark = if *checked { "- [x] " } else { "- [ ] " };
867                let body = format!("{mark}{}", unescape_text(text));
868                self.emit(
869                    body.clone(),
870                    vec![ChunkItem {
871                        self_ref,
872                        kind: ChunkItemKind::Text,
873                        text: body,
874                    }],
875                );
876            }
877            // An enriched display formula chunks like docling's formula item:
878            // the LaTeX is the chunk text.
879            Node::Formula { latex, orig, .. } => {
880                // The item takes its `#/texts/N` slot whatever it prints.
881                let self_ref = self.alloc.text();
882                // An undecoded formula (#1120) chunks as the Markdown
883                // serializer prints it — the placeholder — and one with no
884                // text at all is no chunk.
885                let body = if !latex.is_empty() {
886                    format!("$${}$$", latex)
887                } else if !orig.is_empty() {
888                    crate::markdown::FORMULA_NOT_DECODED.to_string()
889                } else {
890                    return;
891                };
892                self.emit(
893                    body.clone(),
894                    vec![ChunkItem {
895                        self_ref,
896                        kind: ChunkItemKind::Text,
897                        text: body,
898                    }],
899                );
900            }
901            Node::Code { text, .. } => {
902                let self_ref = self.alloc.text();
903                let body = crate::markdown::code_fence("", &unescape_text(text));
904                self.emit(
905                    body.clone(),
906                    vec![ChunkItem {
907                        self_ref,
908                        kind: ChunkItemKind::Text,
909                        text: body,
910                    }],
911                );
912            }
913            Node::Table(t) => {
914                // `TripletTableSerializer`: the captions open the table's
915                // chunk and are among its doc items — the caption is the
916                // `#/texts/N` item the JSON writes ahead of the table (#1041:
917                // it took no ref here, so every later text ref pointed one
918                // item too early).
919                let mut items = Vec::new();
920                let mut parts = Vec::new();
921                if let Some(cap) = t.caption.as_deref().filter(|c| !c.is_empty()) {
922                    let text = unescape_text(cap);
923                    parts.push(text.clone());
924                    items.push(ChunkItem {
925                        self_ref: self.alloc.text(),
926                        kind: ChunkItemKind::Text,
927                        text,
928                    });
929                }
930                let self_ref = self.alloc.table();
931                let body = triplet_table_text(t);
932                items.push(ChunkItem {
933                    self_ref,
934                    kind: ChunkItemKind::Table,
935                    text: body.clone(),
936                });
937                // docling-core#675: the table's footnotes (the `footnote`
938                // texts the JSON writes after it) close its chunk, one
939                // paragraph each, and are among its doc items.
940                parts.push(body);
941                for note in t.footnotes.iter().filter(|n| !n.is_empty()) {
942                    let text = unescape_text(note);
943                    parts.push(text.clone());
944                    items.push(ChunkItem {
945                        self_ref: self.alloc.text(),
946                        kind: ChunkItemKind::Text,
947                        text,
948                    });
949                }
950                let body = parts
951                    .into_iter()
952                    .filter(|p| !p.is_empty())
953                    .collect::<Vec<_>>()
954                    .join("\n\n");
955                self.emit(body, items);
956            }
957            Node::Picture {
958                caption,
959                description,
960                ..
961            } => {
962                let cap = caption.as_deref().filter(|c| !c.is_empty());
963                let cap_item = cap.map(|c| ChunkItem {
964                    self_ref: self.alloc.text(),
965                    kind: ChunkItemKind::Text,
966                    text: unescape_text(c),
967                });
968                let pic_ref = self.alloc.picture();
969                // The picture itself serializes to the (empty) chunking image
970                // placeholder, and its caption is already consumed by the
971                // caption chunk — so only the caption text is emitted. A
972                // description (the picture-OCR text, #645) is the picture's
973                // own annotation text — docling's chunker serializes the
974                // picture through the Markdown picture serializer, so the
975                // description lands in the chunk after the caption.
976                let desc = description
977                    .as_ref()
978                    .map(|d| d.text.as_str())
979                    .filter(|t| !t.is_empty());
980                match (cap_item, desc) {
981                    (Some(cap_item), None) => {
982                        let body = cap_item.text.clone();
983                        self.emit(body, vec![cap_item]);
984                    }
985                    (Some(cap_item), Some(desc)) => {
986                        let body = format!("{}\n\n{desc}", cap_item.text);
987                        let pic_item = ChunkItem {
988                            self_ref: pic_ref,
989                            kind: ChunkItemKind::Picture,
990                            text: desc.to_string(),
991                        };
992                        self.emit(body, vec![cap_item, pic_item]);
993                    }
994                    (None, Some(desc)) => {
995                        let pic_item = ChunkItem {
996                            self_ref: pic_ref,
997                            kind: ChunkItemKind::Picture,
998                            text: desc.to_string(),
999                        };
1000                        self.emit(desc.to_string(), vec![pic_item]);
1001                    }
1002                    (None, None) => {}
1003                }
1004            }
1005            Node::Chart {
1006                kind,
1007                table,
1008                caption,
1009                ..
1010            } => {
1011                let cap = caption.as_deref().filter(|c| !c.is_empty());
1012                let cap_item = cap.map(|c| ChunkItem {
1013                    self_ref: self.alloc.text(),
1014                    kind: ChunkItemKind::Text,
1015                    text: unescape_text(c),
1016                });
1017                let pic_ref = self.alloc.picture();
1018                // caption, humanized classification, then the chart's data grid
1019                // as a (padded) markdown table — docling's picture serializer
1020                // parts, joined with blank lines.
1021                let mut parts: Vec<String> = Vec::new();
1022                if let Some(ci) = &cap_item {
1023                    parts.push(ci.text.clone());
1024                }
1025                parts.push(humanize_label(kind));
1026                let grid = crate::markdown::render_table(table, false);
1027                if !grid.is_empty() {
1028                    parts.push(unescape_text(&grid));
1029                }
1030                let body = parts.join("\n\n");
1031                // Re-serialized standalone (the hybrid window join), the picture
1032                // carries its caption itself, while the caption *item* renders
1033                // empty — docling's markdown serializer emits caption-label text
1034                // only through the picture.
1035                let pic_item = ChunkItem {
1036                    self_ref: pic_ref,
1037                    kind: ChunkItemKind::Picture,
1038                    text: body.clone(),
1039                };
1040                let items = match cap_item {
1041                    Some(mut ci) => {
1042                        ci.text = String::new();
1043                        vec![ci, pic_item]
1044                    }
1045                    None => vec![pic_item],
1046                };
1047                self.emit(body, items);
1048            }
1049            // A group on a non-body layer (a hidden spreadsheet sheet) carries
1050            // no chunkable content, like every other non-body item.
1051            Node::Group { layer: Some(_), .. } => {}
1052            Node::Group { children, .. } => {
1053                // A generic group is a structural container: docling recurses
1054                // into it rather than chunking it whole.
1055                self.alloc.group();
1056                self.walk(children);
1057            }
1058            // A key-value graph holds no text items, so no chunk comes of it.
1059            Node::KeyValueGraph { .. } => {}
1060            Node::FieldRegion { items } => {
1061                // Each field part (marker / key / value) is its own text item,
1062                // and docling chunks each one individually.
1063                self.alloc.field_region();
1064                for item in items {
1065                    self.alloc.field_item();
1066                    for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1067                        let self_ref = self.alloc.text();
1068                        let body = unescape_text(part);
1069                        self.emit(
1070                            body.clone(),
1071                            vec![ChunkItem {
1072                                self_ref,
1073                                kind: ChunkItemKind::Text,
1074                                text: body,
1075                            }],
1076                        );
1077                    }
1078                }
1079            }
1080            Node::InlineGroup { md_text, runs, .. } => {
1081                let self_ref = self.alloc.text();
1082                self.emit_inline_with_runs(md_text, self_ref, runs);
1083            }
1084            Node::TextDump(text) => {
1085                let self_ref = self.alloc.text();
1086                let body = unescape_text(text);
1087                self.emit(
1088                    body.clone(),
1089                    vec![ChunkItem {
1090                        self_ref,
1091                        kind: ChunkItemKind::Text,
1092                        text: body,
1093                    }],
1094                );
1095            }
1096            // Layout provenance and comment annotations are transparent.
1097            Node::Located { inner, .. }
1098            | Node::Prov { inner, .. }
1099            | Node::Track { inner, .. }
1100            | Node::ScriptText { inner, .. }
1101            | Node::Commented { inner, .. } => self.one(inner),
1102            // A PDF page header/footer is a furniture-layer JSON text item:
1103            // never chunked (docling's chunker reads the body layer), but it
1104            // takes a `#/texts/N` number, so later refs keep matching the JSON.
1105            Node::PageFurniture { .. } | Node::FurnitureText { .. } => {
1106                self.alloc.text();
1107            }
1108            // A picture's children are JSON items docling's chunker never
1109            // reaches (it iterates without `traverse_pictures`): allocate
1110            // their refs only — one text each, plus the list group `json.rs`
1111            // opens for each list item (each starts its own list) — so later
1112            // refs keep matching the JSON.
1113            Node::PictureChildren(children) => {
1114                for child in children {
1115                    match child {
1116                        // A header/footer child is numbered exactly as a
1117                        // top-level one is, whatever the JSON does with it.
1118                        Node::PageFurniture { .. } => self.one(child),
1119                        Node::ListItem { .. } => {
1120                            self.alloc.group();
1121                            self.alloc.text();
1122                        }
1123                        _ => {
1124                            self.alloc.text();
1125                        }
1126                    }
1127                }
1128            }
1129            // Non-body layers and doclang-only nodes don't reach the chunker
1130            // (nor the JSON body).
1131            Node::CommentSection { .. }
1132            | Node::Furniture { .. }
1133            | Node::PageBreak
1134            | Node::PageInfo { .. }
1135            | Node::ProvContinuation { .. }
1136            | Node::Anchor { .. }
1137            | Node::DoclangOnly(_) => {}
1138            // Runs are grouped by `walk`; a stray single item (hand-built
1139            // document, `Located` wrapper) still chunks instead of panicking.
1140            Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
1141        }
1142    }
1143}
1144
1145fn level_of(node: &Node) -> u8 {
1146    match node {
1147        Node::ListItem { level, .. } => *level,
1148        _ => 0,
1149    }
1150}
1151
1152/// Render one sibling list as its markdown chunk text (indented items, same
1153/// rules as the full markdown serializer's list rendering).
1154fn render_list(items: &[Node]) -> String {
1155    let mut lines: Vec<String> = Vec::new();
1156    for item in items {
1157        let Node::ListItem {
1158            ordered,
1159            number,
1160            text,
1161            level,
1162            layer,
1163            ..
1164        } = item
1165        else {
1166            continue;
1167        };
1168        if layer.is_some() {
1169            continue;
1170        }
1171        let indent = "    ".repeat(*level as usize);
1172        let marker = if *ordered {
1173            format!("{number}.")
1174        } else {
1175            "-".to_string()
1176        };
1177        lines.push(format!(
1178            "{indent}{marker} {}",
1179            unescape_text(&strip_image_markers(text))
1180        ));
1181    }
1182    lines.join("\n")
1183}
1184
1185/// Strip the Markdown image placeholders a list item's own images fold into
1186/// its text (the chunking serializer's `image_placeholder` is empty, so
1187/// docling's chunk text carries no marker), collapsing the newlines that
1188/// carried them.
1189fn strip_image_markers(text: &str) -> String {
1190    if !text.contains("<!-- image -->") {
1191        return text.to_string();
1192    }
1193    let cleaned: Vec<&str> = text
1194        .split('\n')
1195        .map(str::trim_end)
1196        .filter(|l| *l != "<!-- image -->")
1197        .collect();
1198    cleaned.join("\n").trim_end().to_string()
1199}
1200
1201/// docling-core's `_humanize_text`: underscores to spaces, first letter
1202/// capitalized (`line_chart` → `Line chart`).
1203fn humanize_label(label: &str) -> String {
1204    let text = label.replace('_', " ");
1205    let mut chars = text.chars();
1206    match chars.next() {
1207        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1208        None => text,
1209    }
1210}
1211
1212/// docling's `TripletTableSerializer` over `export_to_dataframe` semantics: the
1213/// leading rows carrying column-header cells become the dataframe's column
1214/// names (multiple header rows join per column with `.`; no header rows at all
1215/// yield pandas' integer column names), the rest are data rows; the dataframe
1216/// is then rendered as `row, column = value` sentences (with the header-only /
1217/// single-column special cases and the plain-text flatten fallback).
1218fn triplet_table_text(t: &Table) -> String {
1219    let anchors = t.span_anchors();
1220    let rows: Vec<Vec<String>> = t
1221        .rows
1222        .iter()
1223        .enumerate()
1224        .map(|(ri, r)| {
1225            (0..r.len())
1226                .map(|ci| cell_chunk_text(t, &anchors, ri, ci))
1227                .collect()
1228        })
1229        .collect();
1230    let num_rows = rows.len();
1231    let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
1232    if num_rows == 0 || num_cols == 0 {
1233        return String::new();
1234    }
1235    let cell = |r: usize, c: usize| -> &str {
1236        rows.get(r)
1237            .and_then(|row| row.get(c))
1238            .map(String::as_str)
1239            .unwrap_or("")
1240    };
1241
1242    // The header block is the one the Markdown serializer uses
1243    // (`Table::column_header_row_count`, docling-core#767), without its
1244    // "no flags -> row 0" fallback: pandas then gets integer column names.
1245    let num_headers = t.column_header_row_count().min(num_rows);
1246
1247    // Column names: header-row texts joined per column with '.', or the integer
1248    // positions when there are no header rows.
1249    let columns: Vec<String> = if num_headers > 0 {
1250        (0..num_cols)
1251            .map(|c| {
1252                let mut name = String::new();
1253                for r in 0..num_headers {
1254                    if !name.is_empty() {
1255                        name.push('.');
1256                    }
1257                    name.push_str(cell(r, c));
1258                }
1259                name
1260            })
1261            .collect()
1262    } else {
1263        (0..num_cols).map(|c| c.to_string()).collect()
1264    };
1265    let data_rows = num_headers..num_rows;
1266    let n_data = data_rows.len();
1267
1268    // Header-only table: emit the header texts directly.
1269    if n_data == 0 {
1270        return columns
1271            .iter()
1272            .map(|s| s.trim())
1273            .filter(|s| !s.is_empty())
1274            .collect::<Vec<_>>()
1275            .join(". ");
1276    }
1277
1278    let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
1279    let text = if num_cols == 1 {
1280        // Single-column: the first data row is the column name, the rest are
1281        // values (a single data row emits its cell text alone).
1282        let col_name = data(0, 0).trim().to_string();
1283        if n_data == 1 {
1284            col_name
1285        } else {
1286            (1..n_data)
1287                .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
1288                .collect::<Vec<_>>()
1289                .join(". ")
1290        }
1291    } else {
1292        // Triplets over the dataframe with the column names copied as row 0.
1293        let mut parts = Vec::new();
1294        for r in 0..n_data {
1295            for (c, col_name) in columns.iter().enumerate().skip(1) {
1296                parts.push(format!(
1297                    "{}, {} = {}",
1298                    data(r, 0).trim(),
1299                    col_name.trim(),
1300                    data(r, c).trim()
1301                ));
1302            }
1303        }
1304        parts.join(". ")
1305    };
1306    if !text.is_empty() {
1307        return text;
1308    }
1309
1310    // Last-resort flatten: the data rows' non-blank cells joined with '. '
1311    // (the header rows are the dataframe's columns, so they are not included).
1312    (0..n_data)
1313        .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1314        .map(|(r, c)| data(r, c).trim())
1315        .filter(|s| !s.is_empty())
1316        .collect::<Vec<_>>()
1317        .join(". ")
1318}
1319
1320/// Split a markdown-flavoured text into docling's inline-item granularity: a
1321/// hyperlink / formatted span / inline formula is its own document item in
1322/// docling's model, with plain text runs between them. Returns the standalone
1323/// serialization of each item (`[text](url)`, `**bold**`, a formula re-wrapped
1324/// as `$$latex$$`, plain text), or a single-element vector when the text is one
1325/// uniform item. The single space docling's serializer inserts between inline
1326/// items is stripped from the adjacent plain runs.
1327fn inline_segments(md: &str) -> Vec<String> {
1328    inline_segments_tagged(md, &[])
1329        .into_iter()
1330        .map(|(t, _)| t)
1331        .collect()
1332}
1333
1334/// Like [`inline_segments`], with each segment tagged `true` when it came from
1335/// plain (unmarked) text — those may still need splitting at run boundaries
1336/// invisible in markdown (underline, soft breaks).
1337///
1338/// `runs` are the node's structured inline runs (empty for a plain
1339/// paragraph). The flat text cannot tell an inline formula's `$…$` from a
1340/// literal dollar sign (`a bet of $5 … has won $6`, #1065), so a `$…$` span
1341/// is a formula only when it is one: when the node carries `formula` runs,
1342/// the span's LaTeX must be one of them; otherwise it must satisfy Pandoc's
1343/// `tex_math_dollars` delimiter rule ([`dollar_math_closer`]), which no
1344/// currency amount does.
1345fn inline_segments_tagged(md: &str, runs: &[crate::InlineRun]) -> Vec<(String, bool)> {
1346    let formula_runs: Vec<&str> = runs
1347        .iter()
1348        .filter(|r| r.formula)
1349        .map(|r| r.text.trim())
1350        .collect();
1351    let chars: Vec<char> = md.chars().collect();
1352    let n = chars.len();
1353    let find = |from: usize, pat: &str| -> Option<usize> {
1354        let hay: String = chars[from..].iter().collect();
1355        hay.find(pat).map(|p| from + hay[..p].chars().count())
1356    };
1357    let mut out: Vec<(String, bool)> = Vec::new();
1358    let mut plain = String::new();
1359    let mut after_span = false;
1360
1361    fn flush(
1362        out: &mut Vec<(String, bool)>,
1363        plain: &mut String,
1364        before_span: bool,
1365        after_span: bool,
1366    ) {
1367        let mut p = std::mem::take(plain);
1368        if after_span {
1369            if let Some(rest) = p.strip_prefix(' ') {
1370                p = rest.to_string();
1371            }
1372        }
1373        if before_span {
1374            if let Some(rest) = p.strip_suffix(' ') {
1375                p = rest.to_string();
1376            }
1377        }
1378        if !p.is_empty() {
1379            out.push((unescape_text(&p), true));
1380        }
1381    }
1382
1383    let mut i = 0;
1384    while i < n {
1385        let rest: String = chars[i..].iter().collect();
1386        // A hyperlink span (not an image): the whole `[text](url)` is one item.
1387        // The URL may itself contain balanced parentheses (`/Duck_(film)`),
1388        // so the closing `)` is found by paren depth, not first match.
1389        if chars[i] == '[' && !rest.starts_with("[](") {
1390            // The label may itself contain balanced brackets (`[[ 1 ]](#ref)`
1391            // has label `[ 1 ]`), but an *unbalanced* `[` means this bracket is
1392            // plain text preceding a real link (`[ [*note*](url) ]`).
1393            let balanced = |c: usize| {
1394                let mut d = 0i32;
1395                for &ch in &chars[i + 1..c] {
1396                    match ch {
1397                        '[' => d += 1,
1398                        ']' => d -= 1,
1399                        _ => {}
1400                    }
1401                }
1402                d == 0
1403            };
1404            if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
1405                let mut depth = 0usize;
1406                let mut url_end = None;
1407                for (k, &c) in chars.iter().enumerate().skip(close + 2) {
1408                    match c {
1409                        '(' => depth += 1,
1410                        ')' => {
1411                            if depth == 0 {
1412                                url_end = Some(k);
1413                                break;
1414                            }
1415                            depth -= 1;
1416                        }
1417                        _ => {}
1418                    }
1419                }
1420                if let Some(endp) = url_end {
1421                    // An unsafe destination (`javascript:`, #860) is plain
1422                    // text, not a hyperlink item.
1423                    let url: String = chars[close + 2..endp].iter().collect();
1424                    if !crate::hyperlink::is_safe_hyperlink(&url) {
1425                        plain.extend(&chars[i + 1..close]);
1426                        i = endp + 1;
1427                        continue;
1428                    }
1429                    flush(&mut out, &mut plain, true, after_span);
1430                    out.push((
1431                        unescape_text(&chars[i..=endp].iter().collect::<String>()),
1432                        false,
1433                    ));
1434                    i = endp + 1;
1435                    after_span = true;
1436                    continue;
1437                }
1438            }
1439        }
1440        // An inline code span is a code item in docling's model, whose
1441        // standalone form is a fenced block; its backticks may run longer
1442        // than one (#859).
1443        if chars[i] == '`' {
1444            if let Some((s, e, after)) = crate::markdown::code_span_bounds(&chars, i) {
1445                if e > s && !chars[s..e].iter().all(|c| c.is_whitespace()) {
1446                    flush(&mut out, &mut plain, true, after_span);
1447                    let inner: String = chars[s..e].iter().collect();
1448                    out.push((
1449                        crate::markdown::code_fence("", &unescape_text(&inner)),
1450                        false,
1451                    ));
1452                    i = after;
1453                    after_span = true;
1454                    continue;
1455                }
1456            }
1457        }
1458        // A formatted span; longest markers first.
1459        let mut matched = false;
1460        for marker in ["***", "**", "*", "~~"] {
1461            if rest.starts_with(marker) {
1462                let mlen = marker.chars().count();
1463                if let Some(end) = find(i + mlen, marker) {
1464                    // A whitespace-only span (`* *` from a literal asterisk in
1465                    // running text next to a real italic) is not a docling run:
1466                    // treat the marker as plain text.
1467                    let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
1468                    if end > i + mlen && !inner_blank {
1469                        flush(&mut out, &mut plain, true, after_span);
1470                        out.push((
1471                            unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
1472                            false,
1473                        ));
1474                        i = end + mlen;
1475                        after_span = true;
1476                        matched = true;
1477                    }
1478                }
1479                break;
1480            }
1481        }
1482        if matched {
1483            continue;
1484        }
1485        // A literal `$$` inside running text is not an inline formula: copy it
1486        // through as plain characters.
1487        if rest.starts_with("$$") {
1488            plain.push_str("$$");
1489            i += 2;
1490            continue;
1491        }
1492        // An inline formula: standalone it re-serializes in display form.
1493        if chars[i] == '$' {
1494            let end = if formula_runs.is_empty() {
1495                dollar_math_closer(&chars, i)
1496            } else {
1497                find(i + 1, "$").filter(|&end| {
1498                    let latex: String = chars[i + 1..end].iter().collect();
1499                    formula_runs.contains(&latex.trim())
1500                })
1501            };
1502            if let Some(end) = end {
1503                if end > i + 1 {
1504                    flush(&mut out, &mut plain, true, after_span);
1505                    let latex: String = chars[i + 1..end].iter().collect();
1506                    out.push((format!("$${latex}$$"), false));
1507                    i = end + 1;
1508                    after_span = true;
1509                    continue;
1510                }
1511            }
1512        }
1513        plain.push(chars[i]);
1514        i += 1;
1515    }
1516    flush(&mut out, &mut plain, false, after_span);
1517    if out.is_empty() {
1518        out.push((unescape_text(md), true));
1519    }
1520    out
1521}
1522
1523/// The closing `$` of an inline formula opened at `open`, by Pandoc's
1524/// `tex_math_dollars` rule: the opener has a non-space character right after
1525/// it, the closer is the next `$`, has a non-space character right before it
1526/// and is not followed by a digit. `$5 riding … won $6` fails it twice (a
1527/// space before the second `$`, a digit after it), so a price is never a
1528/// formula, while `$x$`, `$a+b$` and `$E=mc^2$` still are.
1529fn dollar_math_closer(chars: &[char], open: usize) -> Option<usize> {
1530    let first = *chars.get(open + 1)?;
1531    if first.is_whitespace() || first == '$' {
1532        return None;
1533    }
1534    let end = open + 1 + chars[open + 1..].iter().position(|&c| c == '$')?;
1535    let before_ok = !chars[end - 1].is_whitespace();
1536    let after_ok = !chars.get(end + 1).is_some_and(|c| c.is_ascii_digit());
1537    (before_ok && after_ok).then_some(end)
1538}
1539
1540/// Split a plain markdown segment at run boundaries the markdown cannot show
1541/// (an underlined run, a `<sub>`/`<sup>` run): when a consecutive window of
1542/// two or more unmarked runs exactly covers the segment, each run is its own
1543/// document item.
1544fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1545    let target = segment.trim();
1546    if target.is_empty() {
1547        return None;
1548    }
1549    let plainish =
1550        |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1551    let fully_plain =
1552        |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1553    let unmarked: Vec<(&str, bool)> = runs
1554        .iter()
1555        .filter(|r| plainish(r))
1556        .map(|r| (r.text.as_str(), fully_plain(r)))
1557        .collect();
1558    for start in 0..unmarked.len() {
1559        let mut rest = target;
1560        let mut taken: Vec<(String, bool)> = Vec::new();
1561        for (t, fully) in &unmarked[start..] {
1562            let t = t.trim();
1563            if t.is_empty() {
1564                continue;
1565            }
1566            match rest.strip_prefix(t) {
1567                Some(r) => {
1568                    taken.push((unescape_text(t), *fully));
1569                    rest = r.trim_start();
1570                    if rest.is_empty() {
1571                        break;
1572                    }
1573                }
1574                None => break,
1575            }
1576        }
1577        if rest.is_empty() && taken.len() >= 2 {
1578            // Consecutive fully-plain pieces (no underline / sub / sup) are one
1579            // annotation in docling's model — `simplify_text_elements` merges
1580            // them joined with a space, so they never split between themselves.
1581            // Only an underline / sub / sup run is a genuine boundary.
1582            let mut merged: Vec<(String, bool)> = Vec::new();
1583            for (t, fully) in taken {
1584                match merged.last_mut() {
1585                    Some((last, true)) if fully => {
1586                        last.push(' ');
1587                        last.push_str(&t);
1588                    }
1589                    _ => merged.push((t, fully)),
1590                }
1591            }
1592            if merged.len() >= 2 {
1593                return Some(merged.into_iter().map(|(t, _)| t).collect());
1594            }
1595            return None;
1596        }
1597    }
1598    None
1599}
1600
1601/// A table cell's text for the triplet serializer. A *rich* cell (one carrying
1602/// block content) is re-serialized the way docling's chunking serializer sees
1603/// it: paragraphs joined with blank lines, a nested table as its own triplet
1604/// sentences, pictures as an empty placeholder. Plain cells use the flat text
1605/// with the markdown image placeholder stripped (the chunking serializer's
1606/// `image_placeholder` is empty).
1607fn cell_chunk_text(t: &Table, anchors: &[Vec<(usize, usize)>], r: usize, c: usize) -> String {
1608    // A rich cell's blocks live on its anchor; every position it covers
1609    // reads them (docling-core#857, #777).
1610    let (ar, ac) = anchors
1611        .get(r)
1612        .and_then(|row| row.get(c))
1613        .copied()
1614        .unwrap_or((r, c));
1615    if let Some(blocks) = t
1616        .cell_blocks
1617        .as_ref()
1618        .and_then(|b| b.get(ar))
1619        .and_then(|row| row.get(ac))
1620        .filter(|b| !b.is_empty())
1621    {
1622        let mut parts: Vec<String> = Vec::new();
1623        for node in blocks.iter() {
1624            let part = block_chunk_text(node);
1625            if !part.is_empty() {
1626                parts.push(part);
1627            }
1628        }
1629        return parts.join("\n\n");
1630    }
1631    let flat = t
1632        .rows
1633        .get(r)
1634        .and_then(|row| row.get(c))
1635        .map(String::as_str)
1636        .unwrap_or("");
1637    unescape_text(flat)
1638        .replace("<!-- image -->", "")
1639        .trim()
1640        .to_string()
1641}
1642
1643/// One block of a rich cell, serialized for chunking.
1644fn block_chunk_text(node: &Node) -> String {
1645    match node {
1646        Node::Paragraph { text } | Node::ListText { text, .. } => unescape_text(text),
1647        Node::LabeledText { .. } => block_chunk_text(&node.labeled_as_paragraph()),
1648        Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1649        Node::Code { text, .. } => crate::markdown::code_fence("", &unescape_text(text)),
1650        Node::Table(inner) => triplet_table_text(inner),
1651        Node::Picture { caption, .. } => caption
1652            .as_deref()
1653            .filter(|c| !c.is_empty())
1654            .map(unescape_text)
1655            .unwrap_or_default(),
1656        Node::ListItem {
1657            ordered,
1658            number,
1659            text,
1660            ..
1661        } => {
1662            let marker = if *ordered {
1663                format!("{number}.")
1664            } else {
1665                "-".to_string()
1666            };
1667            format!("{marker} {}", unescape_text(text))
1668        }
1669        Node::CheckboxItem { checked, text } => {
1670            let mark = if *checked { "- [x] " } else { "- [ ] " };
1671            format!("{mark}{}", unescape_text(text))
1672        }
1673        Node::Heading { text, .. } => unescape_text(text),
1674        Node::Located { inner, .. }
1675        | Node::Prov { inner, .. }
1676        | Node::Track { inner, .. }
1677        | Node::ScriptText { inner, .. }
1678        | Node::Commented { inner, .. } => block_chunk_text(inner),
1679        Node::Group { layer: Some(_), .. } => String::new(),
1680        Node::Group { children, .. } => children
1681            .iter()
1682            .map(block_chunk_text)
1683            .filter(|s| !s.is_empty())
1684            .collect::<Vec<_>>()
1685            .join("\n"),
1686        _ => String::new(),
1687    }
1688}
1689
1690/// Reverse the model's baked markdown text escaping — same mapping as the JSON
1691/// exporter (docling chunks carry raw text).
1692fn unescape_text(s: &str) -> String {
1693    s.replace("&lt;", "<")
1694        .replace("&gt;", ">")
1695        .replace("&amp;", "&")
1696        .replace("\\_", "_")
1697}
1698
1699// ---------------------------------------------------------------------------
1700// Hybrid chunker
1701// ---------------------------------------------------------------------------
1702
1703/// Token counting for [`HybridChunker`] — docling's `BaseTokenizer`.
1704pub trait ChunkTokenizer {
1705    /// Number of tokens in `text` (no special tokens).
1706    fn count_tokens(&self, text: &str) -> usize;
1707    /// The chunk budget (docling's `max_tokens`, e.g. 256 for MiniLM).
1708    fn max_tokens(&self) -> usize;
1709}
1710
1711/// Tokenization-aware chunker on top of [`HierarchicalChunker`] — docling's
1712/// `HybridChunker` with default parameters (`merge_peers`,
1713/// `repeat_table_header` on; `omit_header_on_overflow` off).
1714pub struct HybridChunker<T: ChunkTokenizer> {
1715    tokenizer: T,
1716    merge_peers: bool,
1717}
1718
1719impl<T: ChunkTokenizer> HybridChunker<T> {
1720    pub fn new(tokenizer: T) -> Self {
1721        Self {
1722            tokenizer,
1723            merge_peers: true,
1724        }
1725    }
1726
1727    /// Disable merging of undersized same-heading neighbours.
1728    pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1729        self.merge_peers = merge_peers;
1730        self
1731    }
1732
1733    pub fn max_tokens(&self) -> usize {
1734        self.tokenizer.max_tokens()
1735    }
1736
1737    /// The tokenizer the chunks are budgeted with — docling's
1738    /// `HybridChunker.tokenizer`, which docling-serve counts each chunk's
1739    /// `num_tokens` with (#1259).
1740    pub fn tokenizer(&self) -> &T {
1741        &self.tokenizer
1742    }
1743
1744    /// Chunk the document.
1745    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1746        let mut chunks = Vec::new();
1747        self.chunk_with(doc, &mut |c| {
1748            chunks.push(c);
1749            true
1750        });
1751        chunks
1752    }
1753
1754    /// Stream the chunks: each hierarchical chunk is split against the token
1755    /// budget as the document walk produces it, and the peer merge flushes a
1756    /// merged chunk to `sink` as soon as its window closes (a chunk with
1757    /// different headings arrives, or the budget fills). A `false` return from
1758    /// `sink` cancels the chunking. [`Self::chunk`] is this with a collecting
1759    /// sink — the chunks and their order are identical.
1760    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1761        // The refs are mapped onto the JSON export last, on the chunks as
1762        // emitted: the splitting re-serializes the walk's items (#1041).
1763        let mut mapper = RefMapper::new(&doc.export_to_json_value());
1764        let sink = &mut |c: DocChunk| sink(mapper.remap(c));
1765        let mut merger = PeerMerger::default();
1766        let mut alive = true;
1767        HierarchicalChunker::walk_nodes(doc, &mut |c| {
1768            for split in self.split_by_doc_items(c) {
1769                for chunk in self.split_using_plain_text(split) {
1770                    if !alive {
1771                        return false;
1772                    }
1773                    alive = if self.merge_peers {
1774                        self.merge_push(&mut merger, chunk, sink)
1775                    } else {
1776                        sink(chunk)
1777                    };
1778                }
1779            }
1780            alive
1781        });
1782        if alive {
1783            self.merge_flush(&mut merger, sink);
1784        }
1785    }
1786
1787    fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1788        self.tokenizer.count_tokens(&contextualize(chunk))
1789    }
1790
1791    /// docling's `_make_chunk_from_doc_items`: single-item chunks keep their
1792    /// text; multi-item windows re-join the items' standalone serializations.
1793    fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1794        let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1795        let text = if chunk.doc_items.len() == 1 {
1796            chunk.text.clone()
1797        } else {
1798            doc_items
1799                .iter()
1800                .filter(|it| !it.text.is_empty())
1801                .map(|it| it.text.as_str())
1802                .collect::<Vec<_>>()
1803                .join("\n")
1804        };
1805        DocChunk {
1806            text,
1807            headings: chunk.headings.clone(),
1808            doc_items,
1809        }
1810    }
1811
1812    fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1813        if chunk.doc_items.is_empty() {
1814            return vec![chunk];
1815        }
1816        let max = self.max_tokens();
1817        let num_items = chunk.doc_items.len();
1818        let mut chunks = Vec::new();
1819        let mut window_start = 0usize;
1820        let mut window_end = 0usize; // inclusive
1821        while window_end < num_items {
1822            let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1823            if self.count_chunk_tokens(&new_chunk) <= max {
1824                if window_end < num_items - 1 {
1825                    window_end += 1;
1826                    continue;
1827                } else {
1828                    window_end = num_items; // last loop
1829                }
1830            } else if window_start == window_end {
1831                // One item that doesn't fit: keep it; the plain-text splitter
1832                // takes over.
1833                window_end += 1;
1834                window_start = window_end;
1835            } else {
1836                // The window without its last item fit; flush that and start a
1837                // new window at the current item.
1838                new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1839                window_start = window_end;
1840            }
1841            chunks.push(new_chunk);
1842        }
1843        chunks
1844    }
1845
1846    fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1847        let total = self.count_chunk_tokens(&chunk);
1848        let max = self.max_tokens();
1849        if total <= max {
1850            return vec![chunk];
1851        }
1852        let text_len = self.tokenizer.count_tokens(&chunk.text);
1853        let other_len = total - text_len;
1854        if other_len >= max {
1855            // Headings alone exceed the budget: drop them and retry.
1856            let stripped = DocChunk {
1857                headings: None,
1858                ..chunk
1859            };
1860            return self.split_using_plain_text(stripped);
1861        }
1862        let available = max - other_len;
1863
1864        let make = |segments: Vec<String>| -> Vec<DocChunk> {
1865            segments
1866                .into_iter()
1867                .map(|s| DocChunk {
1868                    text: s,
1869                    headings: chunk.headings.clone(),
1870                    doc_items: chunk.doc_items.clone(),
1871                })
1872                .collect()
1873        };
1874        if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1875            // Table: split line-based. The triplet serializer has no header
1876            // lines, so this is a line-preserving split of the table text.
1877            // docling-core ≥ 2.103 (docling-core#690, docling.rs#987) budgets
1878            // the pieces at `available` (the window minus the heading path),
1879            // like text, and re-splits with a smaller budget when a piece's
1880            // `contextualize()` still overshoots — token counts are not
1881            // additive, so the subtraction alone can leave a piece a token
1882            // or two over. (≤ 2.102 packed the full window, so every piece
1883            // overran by the heading length — a deliberate fix here.)
1884            let lines: Vec<String> = chunk
1885                .text
1886                .split('\n')
1887                .filter(|l| !l.trim().is_empty())
1888                .map(|l| l.to_string())
1889                .collect();
1890            let mut budget = available;
1891            loop {
1892                let pieces = make(line_chunk_text(&lines, &self.tokenizer, budget));
1893                let overflow = pieces
1894                    .iter()
1895                    .map(|p| self.count_chunk_tokens(p).saturating_sub(max))
1896                    .max()
1897                    .unwrap_or(0);
1898                if overflow == 0 || budget <= overflow {
1899                    return pieces;
1900                }
1901                budget -= overflow;
1902            }
1903        }
1904        make(semchunk(&chunk.text, available, &self.tokenizer))
1905    }
1906
1907    /// One step of docling's `_merge_chunks_with_matching_metadata`, streamed:
1908    /// extend the window with `chunk` when its headings match the window's and
1909    /// the merged window stays within budget, otherwise flush the window to
1910    /// `sink` and start a new one at `chunk`. Returns `false` once the sink
1911    /// cancels.
1912    ///
1913    /// Linear, as docling-core 2.102 has it (docling-core#823, #782): each
1914    /// chunk's text is counted once, the window grows on a running estimate
1915    /// (text tokens, the delimiter's cost, the headings' overhead), an exact
1916    /// count of the merged window runs only where the estimate overflows, and
1917    /// the final window is verified exactly — shrunk back to the largest one
1918    /// that fits when the estimate under-counted, the chunks it gives up
1919    /// starting the next window. Rebuilding and re-tokenizing the whole window
1920    /// for every chunk was quadratic in the window's length.
1921    fn merge_push(
1922        &self,
1923        m: &mut PeerMerger,
1924        chunk: DocChunk,
1925        sink: &mut dyn FnMut(DocChunk) -> bool,
1926    ) -> bool {
1927        self.merge_feed(m, VecDeque::from([(chunk, None)]), sink)
1928    }
1929
1930    /// Feed chunks (with their text token count when already known) to the
1931    /// merge window, closing it whenever a chunk cannot join.
1932    fn merge_feed(
1933        &self,
1934        m: &mut PeerMerger,
1935        mut pending: VecDeque<(DocChunk, Option<usize>)>,
1936        sink: &mut dyn FnMut(DocChunk) -> bool,
1937    ) -> bool {
1938        while let Some((chunk, tokens)) = pending.pop_front() {
1939            let tokens = tokens.unwrap_or_else(|| self.tokenizer.count_tokens(&chunk.text));
1940            if let Err(chunk) = self.merge_extend(m, chunk, tokens) {
1941                let (alive, rest) = self.merge_close(m, sink);
1942                if !alive {
1943                    return false;
1944                }
1945                pending.push_front((chunk, Some(tokens)));
1946                for item in rest.into_iter().rev() {
1947                    pending.push_front(item);
1948                }
1949            }
1950        }
1951        true
1952    }
1953
1954    /// Add `chunk` (of `tokens` text tokens) to the window, or hand it back
1955    /// when its headings differ or the window would overflow.
1956    fn merge_extend(
1957        &self,
1958        m: &mut PeerMerger,
1959        chunk: DocChunk,
1960        tokens: usize,
1961    ) -> Result<(), DocChunk> {
1962        let max = self.max_tokens() as i64;
1963        if m.window.is_empty() {
1964            // The headings' overhead around the joined text is shared by every
1965            // candidate of this window (it may be negative).
1966            m.overhead = self.count_chunk_tokens(&chunk) as i64 - tokens as i64;
1967            m.running = tokens as i64;
1968            m.window.push((chunk, tokens));
1969            return Ok(());
1970        }
1971        if chunk.headings != m.window[0].0.headings {
1972            return Err(chunk);
1973        }
1974        let delim = *m.delim.get_or_insert_with(|| {
1975            // `_estimate_delimiter_tokens`: what joining two texts adds.
1976            let t = &self.tokenizer;
1977            t.count_tokens("a\nb") as i64 - t.count_tokens("a") as i64 - t.count_tokens("b") as i64
1978        });
1979        m.running += tokens as i64 + delim;
1980        if m.running + m.overhead > max {
1981            let exact = self.count_chunk_tokens(&merged_chunk(
1982                m.window.iter().map(|(c, _)| c).chain([&chunk]),
1983            )) as i64;
1984            if exact > max {
1985                return Err(chunk);
1986            }
1987            // The estimate overshot; re-anchor it on the exact count.
1988            m.running = exact - m.overhead;
1989        }
1990        m.window.push((chunk, tokens));
1991        Ok(())
1992    }
1993
1994    /// Close the window: verify it exactly, shrinking it back to the largest
1995    /// prefix that fits, emit that (a single chunk unchanged), and return the
1996    /// chunks given up, which start the next window.
1997    fn merge_close(
1998        &self,
1999        m: &mut PeerMerger,
2000        sink: &mut dyn FnMut(DocChunk) -> bool,
2001    ) -> (bool, Vec<(DocChunk, Option<usize>)>) {
2002        if m.window.is_empty() {
2003            return (true, Vec::new());
2004        }
2005        let max = self.max_tokens();
2006        let mut fit = m.window.len() - 1;
2007        while fit > 0
2008            && self.count_chunk_tokens(&merged_chunk(m.window[..=fit].iter().map(|(c, _)| c))) > max
2009        {
2010            fit -= 1;
2011        }
2012        let rest = m
2013            .window
2014            .split_off(fit + 1)
2015            .into_iter()
2016            .map(|(c, t)| (c, Some(t)))
2017            .collect();
2018        let out = if m.window.len() == 1 {
2019            m.window.pop().expect("single-chunk window").0
2020        } else {
2021            let merged = merged_chunk(m.window.iter().map(|(c, _)| c));
2022            m.window.clear();
2023            merged
2024        };
2025        (sink(out), rest)
2026    }
2027
2028    /// Flush the merge window at the end of the stream (feeding back what a
2029    /// shrunk window gave up). Returns `false` once the sink cancels.
2030    fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
2031        while !m.window.is_empty() {
2032            let (alive, rest) = self.merge_close(m, sink);
2033            if !alive || !self.merge_feed(m, rest.into(), sink) {
2034                return false;
2035            }
2036        }
2037        true
2038    }
2039}
2040
2041/// docling's merged peer chunk: the texts joined by `\n`, every chunk's doc
2042/// items, the first chunk's headings.
2043fn merged_chunk<'a>(chunks: impl Iterator<Item = &'a DocChunk> + Clone) -> DocChunk {
2044    let mut first = chunks.clone();
2045    DocChunk {
2046        text: chunks
2047            .clone()
2048            .map(|c| c.text.as_str())
2049            .collect::<Vec<_>>()
2050            .join("\n"),
2051        headings: first.next().and_then(|c| c.headings.clone()),
2052        doc_items: chunks.flat_map(|c| c.doc_items.iter().cloned()).collect(),
2053    }
2054}
2055
2056/// The in-flight peer-merge window of [`HybridChunker::chunk_with`]: the
2057/// window's chunks with their text token counts, the running token estimate
2058/// of the joined text, the window's headings overhead, and the delimiter's
2059/// token cost (measured once).
2060#[derive(Default)]
2061struct PeerMerger {
2062    window: Vec<(DocChunk, usize)>,
2063    running: i64,
2064    overhead: i64,
2065    delim: Option<i64>,
2066}
2067
2068// ---------------------------------------------------------------------------
2069// Line-based token chunking (docling's LineBasedTokenChunker, empty prefix)
2070// ---------------------------------------------------------------------------
2071
2072/// Pack lines into chunks of at most `max_tokens`, splitting a line only when
2073/// it exceeds the budget on its own — docling's `LineBasedTokenChunker
2074/// .chunk_text` with an empty prefix (which is what the triplet table
2075/// serializer yields). Reproduces its exact output, including the `\n` it
2076/// prepends to a carried-over segment of an oversized line.
2077fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
2078    let mut chunks: Vec<String> = Vec::new();
2079    let mut current = String::new();
2080    let mut current_len = 0usize;
2081
2082    for line in lines {
2083        let mut remaining: Vec<char> = line.chars().collect();
2084        loop {
2085            let rem_str: String = remaining.iter().collect();
2086            let line_tokens = tok.count_tokens(&rem_str);
2087            let available = max_tokens.saturating_sub(current_len);
2088
2089            if line_tokens <= available {
2090                current.push_str(&rem_str);
2091                current_len += line_tokens;
2092                break;
2093            }
2094            if line_tokens <= max_tokens {
2095                chunks.push(std::mem::take(&mut current));
2096                current_len = 0;
2097                continue;
2098            }
2099            // Too large even for an empty chunk: split off what fits.
2100            let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
2101            let mut rest = rest;
2102            if take.is_empty() {
2103                if rest.is_empty() {
2104                    break;
2105                }
2106                take = rest[..1].iter().collect();
2107                rest = rest[1..].to_vec();
2108            }
2109            current.push('\n');
2110            current.push_str(&take);
2111            chunks.push(std::mem::take(&mut current));
2112            current_len = 0;
2113            remaining = rest;
2114        }
2115    }
2116    if !current.is_empty() {
2117        chunks.push(current);
2118    }
2119    chunks
2120}
2121
2122/// Binary-search the longest char-prefix of `text` within `token_limit`
2123/// tokens, preferring to break at the last ASCII space — docling's
2124/// `split_by_token_limit`.
2125fn split_by_token_limit<T: ChunkTokenizer>(
2126    text: &[char],
2127    token_limit: usize,
2128    tok: &T,
2129) -> (String, Vec<char>) {
2130    if token_limit == 0 || text.is_empty() {
2131        return (String::new(), text.to_vec());
2132    }
2133    let full: String = text.iter().collect();
2134    if tok.count_tokens(&full) <= token_limit {
2135        return (full, Vec::new());
2136    }
2137    let (mut lo, mut hi) = (0usize, text.len());
2138    let mut best: Option<usize> = None;
2139    while lo <= hi {
2140        let mid = (lo + hi) / 2;
2141        let head: String = text[..mid].iter().collect();
2142        if tok.count_tokens(&head) <= token_limit {
2143            best = Some(mid);
2144            lo = mid + 1;
2145        } else {
2146            if mid == 0 {
2147                break;
2148            }
2149            hi = mid - 1;
2150        }
2151    }
2152    let mut best_idx = match best {
2153        Some(b) if b > 0 => b,
2154        _ => return (String::new(), text.to_vec()),
2155    };
2156    // Snap back to the last space, if that leaves a non-empty head.
2157    if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
2158        if pos > 0 {
2159            best_idx = pos;
2160        }
2161    }
2162    (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
2163}
2164
2165// ---------------------------------------------------------------------------
2166// semchunk port (the plain-text splitter HybridChunker delegates to)
2167// ---------------------------------------------------------------------------
2168
2169/// Semantically meaningful non-whitespace splitters, most desirable first.
2170const NON_WS_SPLITTERS: &[&str] = &[
2171    ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
2172    "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
2173];
2174
2175/// Split `text` into chunks of at most `chunk_size` tokens using the most
2176/// semantically meaningful splitter available — the `semchunk` algorithm
2177/// docling's HybridChunker delegates plain-text splitting to.
2178pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
2179    let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
2180    let mut counter = |s: &str| -> usize {
2181        if let Some(n) = cache.get(s) {
2182            return *n;
2183        }
2184        let n = tok.count_tokens(s);
2185        cache.insert(s.to_string(), n);
2186        n
2187    };
2188    let chunks = semchunk_rec(text, chunk_size, &mut counter);
2189    // top-level: drop empty / all-whitespace chunks
2190    chunks
2191        .into_iter()
2192        .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
2193        .collect()
2194}
2195
2196/// One recursion level of semchunk: split, merge windows back up to size, and
2197/// recurse into oversized splits.
2198fn semchunk_rec(
2199    text: &str,
2200    chunk_size: usize,
2201    counter: &mut dyn FnMut(&str) -> usize,
2202) -> Vec<String> {
2203    let (splitter, splitter_is_ws, splits) = split_text(text);
2204
2205    let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
2206    let mut cum_lens = Vec::with_capacity(splits.len() + 1);
2207    cum_lens.push(0usize);
2208    for l in &split_lens {
2209        cum_lens.push(cum_lens.last().unwrap() + l);
2210    }
2211    let num_splits_plus_one = splits.len() + 1;
2212
2213    let mut chunks: Vec<String> = Vec::new();
2214    let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
2215
2216    for i in 0..splits.len() {
2217        if skips.contains(&i) {
2218            continue;
2219        }
2220        let split = &splits[i];
2221        if counter(split) > chunk_size {
2222            let inner = semchunk_rec(split, chunk_size, counter);
2223            chunks.extend(inner);
2224        } else {
2225            let (end, merged) = merge_splits(
2226                &splits,
2227                &cum_lens,
2228                chunk_size,
2229                &splitter,
2230                counter,
2231                i,
2232                num_splits_plus_one,
2233            );
2234            for j in (i + 1)..end {
2235                skips.insert(j);
2236            }
2237            chunks.push(merged);
2238        }
2239        // Re-attach a non-whitespace splitter to the last chunk (or emit it as
2240        // its own chunk if it doesn't fit).
2241        let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
2242        if !splitter_is_ws && !is_last {
2243            let with_splitter = format!(
2244                "{}{}",
2245                chunks.last().map(String::as_str).unwrap_or(""),
2246                splitter
2247            );
2248            if counter(&with_splitter) <= chunk_size {
2249                if let Some(last) = chunks.last_mut() {
2250                    *last = with_splitter;
2251                } else {
2252                    chunks.push(with_splitter);
2253                }
2254            } else {
2255                chunks.push(splitter.clone());
2256            }
2257        }
2258    }
2259    chunks
2260}
2261
2262/// docling/semchunk's `merge_splits`: extend the window with a cum-length-guided
2263/// binary search until the token budget is hit.
2264fn merge_splits(
2265    splits: &[String],
2266    cum_lens: &[usize],
2267    chunk_size: usize,
2268    splitter: &str,
2269    counter: &mut dyn FnMut(&str) -> usize,
2270    start: usize,
2271    high_init: usize,
2272) -> (usize, String) {
2273    let mut average = 0.2f64;
2274    let mut low = start;
2275    let mut high = high_init;
2276    let offset = cum_lens[start];
2277    let mut target = offset as f64 + (chunk_size as f64 * average);
2278
2279    while low < high {
2280        let i = bisect_left(cum_lens, target, low, high);
2281        let midpoint = i.min(high - 1);
2282        let joined = splits[start..midpoint.max(start)].join(splitter);
2283        let tokens = counter(&joined);
2284        let local_cum = cum_lens[midpoint] - offset;
2285        if local_cum > 0 && tokens > 0 {
2286            average = local_cum as f64 / tokens as f64;
2287            target = offset as f64 + (chunk_size as f64 * average);
2288        }
2289        if tokens > chunk_size {
2290            high = midpoint;
2291        } else {
2292            low = midpoint + 1;
2293        }
2294    }
2295    let end = low - 1;
2296    (end, splits[start..end.max(start)].join(splitter))
2297}
2298
2299fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
2300    while low < high {
2301        let mid = (low + high) / 2;
2302        if (sorted[mid] as f64) < target {
2303            low = mid + 1;
2304        } else {
2305            high = mid;
2306        }
2307    }
2308    low
2309}
2310
2311/// semchunk's `_split_text`: pick the most desirable splitter present.
2312fn split_text(text: &str) -> (String, bool, Vec<String>) {
2313    // Longest run of newlines/carriage returns.
2314    if text.contains('\n') || text.contains('\r') {
2315        let splitter = longest_run(text, |c| c == '\n' || c == '\r');
2316        return (splitter.clone(), true, split_on(text, &splitter));
2317    }
2318    // Longest run of tabs.
2319    if text.contains('\t') {
2320        let splitter = longest_run(text, |c| c == '\t');
2321        return (splitter.clone(), true, split_on(text, &splitter));
2322    }
2323    // Longest run of whitespace.
2324    if text.chars().any(char::is_whitespace) {
2325        let splitter = longest_run(text, char::is_whitespace);
2326        if splitter.chars().count() == 1 {
2327            // Prefer a whitespace char preceded by a semantic splitter.
2328            for preceder in NON_WS_SPLITTERS {
2329                if let Some((ws, parts)) = split_after_preceder(text, preceder) {
2330                    return (ws, true, parts);
2331                }
2332            }
2333        }
2334        return (splitter.clone(), true, split_on(text, &splitter));
2335    }
2336    // Most desirable semantic splitter present.
2337    for s in NON_WS_SPLITTERS {
2338        if text.contains(s) {
2339            return (s.to_string(), false, split_on(text, s));
2340        }
2341    }
2342    // No splitter at all: split into characters.
2343    (
2344        String::new(),
2345        true,
2346        text.chars().map(|c| c.to_string()).collect(),
2347    )
2348}
2349
2350/// The longest maximal run of chars matching `pred` (first one wins ties).
2351fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
2352    let mut best = String::new();
2353    let mut cur = String::new();
2354    for c in text.chars() {
2355        if pred(c) {
2356            cur.push(c);
2357        } else {
2358            if cur.chars().count() > best.chars().count() {
2359                best = cur.clone();
2360            }
2361            cur.clear();
2362        }
2363    }
2364    if cur.chars().count() > best.chars().count() {
2365        best = cur;
2366    }
2367    best
2368}
2369
2370fn split_on(text: &str, splitter: &str) -> Vec<String> {
2371    text.split(splitter).map(str::to_string).collect()
2372}
2373
2374/// Python: `re.search(rf'{p}(\s)', text)` → the first whitespace char preceded
2375/// by `p`; then `re.split(rf'(?<={p}){s}', text)` — split at every occurrence
2376/// of that whitespace char immediately preceded by `p`.
2377fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
2378    let chars: Vec<char> = text.chars().collect();
2379    let p: Vec<char> = preceder.chars().collect();
2380    let mut ws: Option<char> = None;
2381    for i in p.len()..chars.len() {
2382        if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
2383            ws = Some(chars[i]);
2384            break;
2385        }
2386    }
2387    let ws = ws?;
2388    let mut parts = Vec::new();
2389    let mut cur = String::new();
2390    let mut i = 0usize;
2391    while i < chars.len() {
2392        if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
2393            parts.push(std::mem::take(&mut cur));
2394            i += 1;
2395            continue;
2396        }
2397        cur.push(chars[i]);
2398        i += 1;
2399    }
2400    parts.push(cur);
2401    Some((ws.to_string(), parts))
2402}
2403
2404// ---------------------------------------------------------------------------
2405// HuggingFace tokenizer (feature `chunking`)
2406// ---------------------------------------------------------------------------
2407
2408#[cfg(feature = "chunking")]
2409mod hf {
2410    use super::ChunkTokenizer;
2411
2412    /// Where `scripts/install/download_dependencies.sh` puts the hybrid
2413    /// chunker's default tokenizer (all-MiniLM-L6-v2's `tokenizer.json`),
2414    /// relative to the process's working directory — the same convention as
2415    /// the `.models/` ONNX files.
2416    pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
2417
2418    /// Resolve the tokenizer path for the hybrid chunker: an explicit path
2419    /// wins; otherwise fall back to [`DEFAULT_TOKENIZER_PATH`] when it exists
2420    /// on disk. Errors with the download instructions when neither is
2421    /// available.
2422    pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
2423        if let Some(p) = explicit {
2424            return Ok(p.to_string());
2425        }
2426        let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
2427        if std::path::Path::new(&resolved).exists() {
2428            return Ok(resolved);
2429        }
2430        Err(format!(
2431            "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
2432             {DEFAULT_TOKENIZER_PATH} does not exist — run \
2433             scripts/install/download_dependencies.sh (or pass an explicit path)"
2434        ))
2435    }
2436
2437    /// [`ChunkTokenizer`] backed by a HuggingFace `tokenizer.json` — the Rust
2438    /// analogue of docling's `HuggingFaceTokenizer` (whose default is
2439    /// `sentence-transformers/all-MiniLM-L6-v2` with `max_tokens` 256).
2440    pub struct HuggingFaceTokenizer {
2441        tok: tokenizers::Tokenizer,
2442        max_tokens: usize,
2443    }
2444
2445    impl HuggingFaceTokenizer {
2446        /// Load the tokenizer from an explicit path, or from
2447        /// [`DEFAULT_TOKENIZER_PATH`] when `path` is `None` (see
2448        /// [`resolve_tokenizer_path`]).
2449        pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
2450            Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
2451        }
2452
2453        /// Load a `tokenizer.json`. `max_tokens` is the chunk budget (docling
2454        /// resolves it from the model's `sentence_bert_config.json`; for the
2455        /// default MiniLM model that is 256).
2456        pub fn from_file(
2457            path: impl AsRef<std::path::Path>,
2458            max_tokens: usize,
2459        ) -> Result<Self, String> {
2460            let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
2461                .map_err(|e| format!("failed to load tokenizer: {e}"))?;
2462            // Counting must see the full text (docling tokenizes without
2463            // truncation, padding, or special tokens — MiniLM's tokenizer.json
2464            // ships with fixed-length padding enabled, which would make every
2465            // short string count as the padded length).
2466            let _ = tok.with_truncation(None);
2467            tok.with_padding(None);
2468            Ok(Self { tok, max_tokens })
2469        }
2470    }
2471
2472    impl ChunkTokenizer for HuggingFaceTokenizer {
2473        fn count_tokens(&self, text: &str) -> usize {
2474            self.tok
2475                .encode(text, false)
2476                .map(|e| e.get_tokens().len())
2477                .unwrap_or(0)
2478        }
2479        fn max_tokens(&self) -> usize {
2480            self.max_tokens
2481        }
2482    }
2483}
2484
2485#[cfg(feature = "chunking")]
2486pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
2487
2488// ---------------------------------------------------------------------------
2489// Window chunker (feature `chunking`) — docling-rag's Markdown window chunker
2490// ---------------------------------------------------------------------------
2491
2492#[cfg(feature = "chunking")]
2493mod window {
2494    use super::DocChunk;
2495    use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
2496
2497    /// A contiguous run of body text under a heading path.
2498    #[derive(Debug, Clone, Default)]
2499    pub struct Section {
2500        /// The heading stack in effect for this section, outermost first
2501        /// (e.g. `["Guide", "Setup"]`). Empty for pre-heading / body-only text.
2502        pub heading_path: Vec<String>,
2503        /// The plain words of the section body, markup stripped.
2504        pub words: Vec<String>,
2505    }
2506
2507    impl Section {
2508        /// The heading path rendered as a single context line, e.g.
2509        /// `# Guide > Setup`. Empty string when there is no heading.
2510        pub fn heading_context(&self) -> String {
2511            if self.heading_path.is_empty() {
2512                String::new()
2513            } else {
2514                format!("# {}", self.heading_path.join(" > "))
2515            }
2516        }
2517    }
2518
2519    fn level_index(level: HeadingLevel) -> usize {
2520        match level {
2521            HeadingLevel::H1 => 1,
2522            HeadingLevel::H2 => 2,
2523            HeadingLevel::H3 => 3,
2524            HeadingLevel::H4 => 4,
2525            HeadingLevel::H5 => 5,
2526            HeadingLevel::H6 => 6,
2527        }
2528    }
2529
2530    /// Parse Markdown into heading-bounded sections. A new section starts at
2531    /// every heading; the heading path is maintained as a stack keyed by
2532    /// heading level.
2533    pub fn parse_sections(markdown: &str) -> Vec<Section> {
2534        parse_sections_with_stack(markdown, Vec::new()).0
2535    }
2536
2537    /// [`parse_sections`] with an explicit initial heading stack, returning the
2538    /// final stack — lets a streaming caller carry heading context across
2539    /// pieces. `heading_stack[i]` holds the current heading text at level `i+1`
2540    /// (may be empty when a level was skipped).
2541    pub fn parse_sections_with_stack(
2542        markdown: &str,
2543        initial_stack: Vec<String>,
2544    ) -> (Vec<Section>, Vec<String>) {
2545        let mut heading_stack: Vec<String> = initial_stack;
2546        let mut sections: Vec<Section> = Vec::new();
2547        // Text before the first heading of this piece continues the carried-over
2548        // section, so it keeps the heading path in effect at the split point.
2549        let mut current = Section {
2550            heading_path: heading_stack
2551                .iter()
2552                .filter(|h| !h.is_empty())
2553                .cloned()
2554                .collect(),
2555            words: Vec::new(),
2556        };
2557
2558        let mut in_heading = false;
2559        let mut heading_level = 0usize;
2560        let mut heading_buf = String::new();
2561
2562        let push_words = |section: &mut Section, text: &str| {
2563            for w in text.split_whitespace() {
2564                section.words.push(w.to_string());
2565            }
2566        };
2567
2568        let flush = |sections: &mut Vec<Section>, section: &mut Section| {
2569            if !section.words.is_empty() {
2570                sections.push(std::mem::take(section));
2571            } else {
2572                *section = Section::default();
2573            }
2574        };
2575
2576        for event in Parser::new(markdown) {
2577            match event {
2578                Event::Start(Tag::Heading { level, .. }) => {
2579                    in_heading = true;
2580                    heading_level = level_index(level);
2581                    heading_buf.clear();
2582                }
2583                Event::End(TagEnd::Heading(_)) => {
2584                    in_heading = false;
2585                    // Update the heading stack: set this level, drop anything deeper.
2586                    let idx = heading_level.saturating_sub(1);
2587                    if heading_stack.len() <= idx {
2588                        heading_stack.resize(idx + 1, String::new());
2589                    } else {
2590                        heading_stack.truncate(idx + 1);
2591                    }
2592                    heading_stack[idx] = heading_buf.trim().to_string();
2593                    // A heading begins a new section.
2594                    flush(&mut sections, &mut current);
2595                    current.heading_path = heading_stack
2596                        .iter()
2597                        .filter(|h| !h.is_empty())
2598                        .cloned()
2599                        .collect();
2600                }
2601                Event::Text(t) | Event::Code(t) => {
2602                    if in_heading {
2603                        if !heading_buf.is_empty() {
2604                            heading_buf.push(' ');
2605                        }
2606                        heading_buf.push_str(&t);
2607                    } else {
2608                        push_words(&mut current, &t);
2609                    }
2610                }
2611                // Treat hard/soft breaks and rules as whitespace (words already split).
2612                Event::SoftBreak | Event::HardBreak | Event::Rule => {}
2613                _ => {}
2614            }
2615        }
2616        flush(&mut sections, &mut current);
2617        (sections, heading_stack)
2618    }
2619
2620    /// docling-rag's Markdown **window chunker**: the document is split into
2621    /// heading-bounded [`Section`]s of plain words (markup stripped), and a
2622    /// fixed-size window of [`Self::max_words`] words slides over each section
2623    /// with [`Self::overlap`] fractional overlap. A chunk never crosses a
2624    /// heading boundary; [`Self::contextualize`] prefixes the heading path.
2625    #[derive(Debug, Clone)]
2626    pub struct WindowChunker {
2627        /// Window size in words (docling-rag's default 300).
2628        pub max_words: usize,
2629        /// Fractional overlap between consecutive windows (default 0.05 = 5%).
2630        pub overlap: f32,
2631    }
2632
2633    impl Default for WindowChunker {
2634        fn default() -> Self {
2635            WindowChunker {
2636                max_words: 300,
2637                overlap: 0.05,
2638            }
2639        }
2640    }
2641
2642    impl WindowChunker {
2643        pub fn new(max_words: usize, overlap: f32) -> Self {
2644            WindowChunker { max_words, overlap }
2645        }
2646
2647        /// The window size, kept ≥ 1.
2648        fn word_budget(&self) -> usize {
2649            self.max_words.max(1)
2650        }
2651
2652        /// Number of words carried from one window into the next; capped so
2653        /// the window always advances.
2654        fn overlap_words(&self, budget: usize) -> usize {
2655            let o = (budget as f32 * self.overlap).round() as usize;
2656            o.min(budget.saturating_sub(1))
2657        }
2658
2659        /// Chunk a Markdown document.
2660        pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
2661            let mut chunks = Vec::new();
2662            self.chunk_with(markdown, &mut |c| {
2663                chunks.push(c);
2664                true
2665            });
2666            chunks
2667        }
2668
2669        /// Stream the chunks: `sink` receives each window as it is cut, and a
2670        /// `false` return cancels. [`Self::chunk`] is this with a collecting
2671        /// sink — the chunks and their order are identical.
2672        pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2673            let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2674            for section in &sections {
2675                if !self.pack_section(section, sink) {
2676                    return;
2677                }
2678            }
2679        }
2680
2681        /// Slide the window over one completed section, feeding each chunk to
2682        /// `sink`. Returns `false` once the sink cancels — exposed so a
2683        /// streaming caller (docling-rag) can pack sections as they complete.
2684        pub fn pack_section(
2685            &self,
2686            section: &Section,
2687            sink: &mut dyn FnMut(DocChunk) -> bool,
2688        ) -> bool {
2689            let words = &section.words;
2690            if words.is_empty() {
2691                return true;
2692            }
2693            let budget = self.word_budget();
2694            let step = budget - self.overlap_words(budget); // ≥ 1 by construction
2695            let mut start = 0;
2696            loop {
2697                let end = (start + budget).min(words.len());
2698                let chunk = DocChunk {
2699                    text: words[start..end].join(" "),
2700                    headings: (!section.heading_path.is_empty())
2701                        .then(|| section.heading_path.clone()),
2702                    doc_items: Vec::new(),
2703                };
2704                if !sink(chunk) {
2705                    return false;
2706                }
2707                if end >= words.len() {
2708                    return true;
2709                }
2710                start += step;
2711            }
2712        }
2713
2714        /// Render a window chunk for embedding — docling-rag's rendering: the
2715        /// heading path as a `# Outer > Inner` context line, a blank line,
2716        /// then the body (just the body above any heading). Note this differs
2717        /// from the docling chunkers' [`contextualize`](super::contextualize),
2718        /// matching docling-rag instead.
2719        pub fn contextualize(chunk: &DocChunk) -> String {
2720            match &chunk.headings {
2721                Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2722                _ => chunk.text.clone(),
2723            }
2724        }
2725    }
2726
2727    #[cfg(test)]
2728    mod tests {
2729        use super::*;
2730
2731        #[test]
2732        fn splits_on_headings_and_tracks_path() {
2733            let md = "\
2734intro words
2735# Chapter 1
2736para one
2737## Section 1.1
2738para two
2739# Chapter 2
2740para three";
2741            let secs = parse_sections(md);
2742            // pre-heading intro, Chapter 1, Section 1.1, Chapter 2.
2743            assert_eq!(secs.len(), 4);
2744            assert!(secs[0].heading_path.is_empty());
2745            assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2746            assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2747            // A deeper heading is dropped when we return to H1.
2748            assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2749        }
2750
2751        #[test]
2752        fn strips_markup_to_plain_words() {
2753            let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2754            let secs = parse_sections(md);
2755            let words = &secs[0].words;
2756            assert!(words.contains(&"bold".to_string()));
2757            assert!(words.contains(&"code".to_string()));
2758            assert!(words.contains(&"link".to_string()));
2759            // No markdown punctuation survives as its own token.
2760            assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2761        }
2762
2763        #[test]
2764        fn windows_overlap_and_never_cross_headings() {
2765            let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2766            let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2767            let chunker = WindowChunker::new(10, 0.2); // step 8, overlap 2
2768            let chunks = chunker.chunk(&md);
2769            // Section A: 25 words → windows [0..10), [8..18), [16..25).
2770            let a: Vec<_> = chunks
2771                .iter()
2772                .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2773                .collect();
2774            assert_eq!(a.len(), 3);
2775            assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2776            assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2777            assert!(a[2].text.ends_with(" w24"));
2778            // Section B stays its own chunk; nothing crosses the heading.
2779            let b: Vec<_> = chunks
2780                .iter()
2781                .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2782                .collect();
2783            assert_eq!(b.len(), 1);
2784            assert_eq!(b[0].text, "short tail");
2785            assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2786        }
2787
2788        #[test]
2789        fn sink_false_cancels_the_window_walk() {
2790            let md = format!(
2791                "# A\n\n{}\n",
2792                (0..50)
2793                    .map(|i| format!("w{i}"))
2794                    .collect::<Vec<_>>()
2795                    .join(" ")
2796            );
2797            let chunker = WindowChunker::new(10, 0.0);
2798            let mut n = 0;
2799            chunker.chunk_with(&md, &mut |_| {
2800                n += 1;
2801                false
2802            });
2803            assert_eq!(n, 1);
2804        }
2805    }
2806}
2807
2808#[cfg(feature = "chunking")]
2809pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2810
2811#[cfg(test)]
2812mod tests {
2813    use super::*;
2814
2815    /// A whitespace "tokenizer" for algorithm tests.
2816    struct WordTok(usize);
2817    impl ChunkTokenizer for WordTok {
2818        fn count_tokens(&self, text: &str) -> usize {
2819            text.split_whitespace().count()
2820        }
2821        fn max_tokens(&self) -> usize {
2822            self.0
2823        }
2824    }
2825
2826    fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2827        let mut d = DoclingDocument::new("t");
2828        for n in nodes {
2829            d.push(n);
2830        }
2831        d
2832    }
2833
2834    #[test]
2835    fn hierarchical_headings_and_items() {
2836        let doc = doc_with(vec![
2837            Node::Heading {
2838                level: 1,
2839                text: "Title".into(),
2840            },
2841            Node::Paragraph {
2842                text: "Intro".into(),
2843            },
2844            Node::Heading {
2845                level: 2,
2846                text: "Sec".into(),
2847            },
2848            Node::Paragraph {
2849                text: "Body".into(),
2850            },
2851        ]);
2852        let chunks = HierarchicalChunker.chunk(&doc);
2853        assert_eq!(chunks.len(), 2);
2854        assert_eq!(chunks[0].text, "Intro");
2855        assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2856        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2857        assert_eq!(
2858            chunks[1].headings.as_deref(),
2859            Some(&["Title".into(), "Sec".into()][..])
2860        );
2861        assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2862    }
2863
2864    /// A page footer is a JSON text item (furniture layer) the chunker never
2865    /// chunks; the refs of the items after it still match the JSON.
2866    #[test]
2867    fn page_furniture_keeps_refs_aligned_with_json() {
2868        let doc = doc_with(vec![
2869            Node::Paragraph {
2870                text: "Before".into(),
2871            },
2872            Node::PageFurniture {
2873                footer: true,
2874                location: [0, 490, 100, 512],
2875                text: "1.10.2".into(),
2876            },
2877            Node::Paragraph {
2878                text: "After".into(),
2879            },
2880        ]);
2881        let chunks = HierarchicalChunker.chunk(&doc);
2882        assert_eq!(chunks.len(), 2);
2883        assert_eq!(chunks[1].text, "After");
2884        let json: serde_json::Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2885        assert_eq!(json["texts"][2]["text"], "After");
2886        assert_eq!(chunks[1].doc_items[0].self_ref, "#/texts/2");
2887    }
2888
2889    /// #1041: a table's caption is the `#/texts/N` item the JSON writes
2890    /// ahead of the table — it opens the table's chunk (docling's
2891    /// `TripletTableSerializer`), and the text refs after it stay aligned.
2892    #[test]
2893    fn captioned_table_keeps_the_text_refs_aligned() {
2894        let table = Table {
2895            rows: vec![
2896                vec!["Year".into(), "Revenue".into()],
2897                vec!["2024".into(), "10".into()],
2898            ],
2899            caption: Some("Table 1: Revenue".into()),
2900            ..Table::default()
2901        };
2902        let doc = doc_with(vec![
2903            Node::Table(table.clone()),
2904            Node::Paragraph {
2905                text: "Revenue grew in 2024.".into(),
2906            },
2907            Node::Table(table),
2908            Node::Paragraph {
2909                text: "Costs were flat.".into(),
2910            },
2911        ]);
2912        let chunks = HierarchicalChunker.chunk(&doc);
2913        assert_eq!(chunks[0].text, "Table 1: Revenue\n\n2024, Revenue = 10");
2914        let refs: Vec<Vec<&str>> = chunks
2915            .iter()
2916            .map(|c| c.doc_items.iter().map(|i| i.self_ref.as_str()).collect())
2917            .collect();
2918        assert_eq!(
2919            refs,
2920            [
2921                vec!["#/texts/0", "#/tables/0"],
2922                vec!["#/texts/1"],
2923                vec!["#/texts/2", "#/tables/1"],
2924                vec!["#/texts/3"],
2925            ]
2926        );
2927        let json = doc.export_to_json_value();
2928        assert_eq!(json["texts"][1]["text"], "Revenue grew in 2024.");
2929        assert_eq!(json["texts"][3]["text"], "Costs were flat.");
2930    }
2931
2932    /// #1041: an item tree numbers the export by its own structure (a
2933    /// furniture title first, an inline paragraph as runs); the refs are
2934    /// mapped onto it, so each names the item its chunk was built from.
2935    #[test]
2936    fn refs_follow_an_item_tree() {
2937        use crate::tree::{ItemTree, TreeKind};
2938        let text = |label: &str, t: &str| TreeKind::Text {
2939            label: label.into(),
2940            text: t.into(),
2941            orig: None,
2942            formatting: None,
2943            hyperlink: None,
2944            level: None,
2945            list: None,
2946        };
2947        let mut doc = doc_with(vec![
2948            Node::Paragraph {
2949                text: "Lead **bold** tail".into(),
2950            },
2951            Node::Paragraph {
2952                text: "Second.".into(),
2953            },
2954        ]);
2955        let mut t = ItemTree {
2956            inline_whitespace: true,
2957            ..Default::default()
2958        };
2959        t.add(
2960            None,
2961            Some(crate::ContentLayer::Furniture),
2962            text("title", "Page"),
2963        );
2964        let g = t.add(
2965            None,
2966            None,
2967            TreeKind::Group {
2968                label: "inline".into(),
2969                name: "group".into(),
2970            },
2971        );
2972        t.add(Some(g), None, text("text", "Lead "));
2973        t.add(Some(g), None, text("text", "bold"));
2974        t.add(Some(g), None, text("text", " tail"));
2975        t.add(None, None, text("text", "Second."));
2976        doc.tree = Some(t);
2977        let refs: Vec<Vec<String>> = HierarchicalChunker
2978            .chunk(&doc)
2979            .iter()
2980            .map(|c| c.doc_items.iter().map(|i| i.self_ref.clone()).collect())
2981            .collect();
2982        assert_eq!(
2983            refs,
2984            [
2985                vec![
2986                    "#/texts/1".to_string(),
2987                    "#/texts/2".into(),
2988                    "#/texts/3".into()
2989                ],
2990                vec!["#/texts/4".to_string()],
2991            ]
2992        );
2993    }
2994
2995    /// A picture's children are never chunked, but they take `#/texts/N`
2996    /// (and list-group) slots in the JSON — the refs after them must still
2997    /// point at the right items.
2998    #[test]
2999    fn picture_children_are_not_chunked_but_keep_refs_aligned() {
3000        let doc = doc_with(vec![
3001            Node::Picture {
3002                caption: None,
3003                caption_href: None,
3004                image: None,
3005                classification: None,
3006                description: None,
3007                caption_parent: crate::CaptionParent::Item,
3008                caption_location: None,
3009            },
3010            Node::PictureChildren(vec![
3011                Node::Paragraph {
3012                    text: "axis label".into(),
3013                },
3014                Node::ListItem {
3015                    ordered: false,
3016                    number: 0,
3017                    first_in_list: true,
3018                    text: "callout".into(),
3019                    level: 0,
3020                    marker: None,
3021                    location: None,
3022                    split: None,
3023                    dclx: None,
3024                    href: None,
3025                    layer: None,
3026                },
3027            ]),
3028            Node::Paragraph {
3029                text: "Body".into(),
3030            },
3031        ]);
3032        let chunks = HierarchicalChunker.chunk(&doc);
3033        assert_eq!(chunks.len(), 1);
3034        assert_eq!(chunks[0].text, "Body");
3035        let json = doc.export_to_json_value();
3036        assert_eq!(json["texts"][2]["text"], "Body");
3037        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3038    }
3039
3040    #[test]
3041    fn heading_shadowing_prunes_deeper_levels() {
3042        let doc = doc_with(vec![
3043            Node::Heading {
3044                level: 2,
3045                text: "A".into(),
3046            },
3047            Node::Heading {
3048                level: 3,
3049                text: "A.1".into(),
3050            },
3051            Node::Heading {
3052                level: 2,
3053                text: "B".into(),
3054            },
3055            Node::Paragraph { text: "p".into() },
3056        ]);
3057        let chunks = HierarchicalChunker.chunk(&doc);
3058        assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
3059    }
3060
3061    /// #1012 (docling-core#924, `test_rich_heading_chunk_metadata`): a
3062    /// partially formatted heading — an empty heading over an inline group
3063    /// in docling — is the heading context of the body, not a chunk of its
3064    /// own under an empty heading.
3065    #[test]
3066    fn rich_heading_is_the_heading_context() {
3067        for body in [Some("Body."), None] {
3068            let mut nodes = vec![Node::Heading {
3069                level: 1,
3070                text: "Hello **bold** world".into(),
3071            }];
3072            if let Some(b) = body {
3073                nodes.push(Node::Paragraph { text: b.into() });
3074            }
3075            let doc = doc_with(nodes);
3076            for chunks in [
3077                HierarchicalChunker.chunk(&doc),
3078                HybridChunker::new(WordTok(64)).chunk(&doc),
3079            ] {
3080                let got: Vec<_> = chunks
3081                    .iter()
3082                    .map(|c| (c.text.as_str(), c.headings.clone()))
3083                    .collect();
3084                let want: Vec<_> = body
3085                    .map(|b| (b, Some(vec!["Hello **bold** world".to_string()])))
3086                    .into_iter()
3087                    .collect();
3088                assert_eq!(got, want);
3089            }
3090        }
3091    }
3092
3093    /// #1012 (docling-core#924,
3094    /// `test_rich_heading_is_emitted_before_a_sibling_heading`): a rich
3095    /// heading shadowed by a sibling leaves no chunk, and the sibling's body
3096    /// carries only the sibling.
3097    #[test]
3098    fn rich_heading_shadowed_by_a_sibling() {
3099        let doc = doc_with(vec![
3100            Node::Heading {
3101                level: 1,
3102                text: "Energy *E* here".into(),
3103            },
3104            Node::Heading {
3105                level: 1,
3106                text: "Next".into(),
3107            },
3108            Node::Paragraph {
3109                text: "Body.".into(),
3110            },
3111        ]);
3112        let chunks = HierarchicalChunker.chunk(&doc);
3113        assert_eq!(chunks.len(), 1);
3114        assert_eq!(chunks[0].text, "Body.");
3115        assert_eq!(chunks[0].headings.as_deref(), Some(&["Next".into()][..]));
3116        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3117    }
3118
3119    /// docling.rs#987 (docling-core#690): table pieces are budgeted at the
3120    /// window minus the heading path, so `contextualize()` stays in budget.
3121    #[test]
3122    fn split_table_pieces_fit_with_headings() {
3123        let rows: Vec<Vec<String>> = std::iter::once(vec!["".to_string(), "A".into(), "B".into()])
3124            .chain((0..40).map(|i| vec![format!("R{i}"), format!("{i}"), format!("v{i}")]))
3125            .collect();
3126        let doc = doc_with(vec![
3127            Node::Heading {
3128                level: 1,
3129                text: "one two three four five six".into(),
3130            },
3131            Node::Table(Table {
3132                rows,
3133                ..Default::default()
3134            }),
3135        ]);
3136        let h = HybridChunker::new(WordTok(20));
3137        let chunks = h.chunk(&doc);
3138        assert!(chunks.len() > 1);
3139        for c in &chunks {
3140            assert!(
3141                h.count_chunk_tokens(c) <= 20,
3142                "over budget: {}",
3143                h.count_chunk_tokens(c)
3144            );
3145        }
3146    }
3147
3148    #[test]
3149    fn triplet_table() {
3150        let t = Table {
3151            rows: vec![
3152                vec!["".into(), "Col1".into()],
3153                vec!["Row1".into(), "v".into()],
3154            ],
3155            ..Default::default()
3156        };
3157        assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
3158        // Single-column: row 0 is the dataframe header, the first data row
3159        // becomes the column name, the rest the values.
3160        let single = Table {
3161            rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
3162            ..Default::default()
3163        };
3164        assert_eq!(triplet_table_text(&single), "a = b");
3165    }
3166
3167    /// The peer merge before docling-core#823 (#782): rebuild and re-count
3168    /// the whole window for every chunk. The linear merge must give the
3169    /// same chunks.
3170    fn quadratic_merge<T: ChunkTokenizer>(
3171        h: &HybridChunker<T>,
3172        chunks: Vec<DocChunk>,
3173    ) -> Vec<DocChunk> {
3174        let mut out = Vec::new();
3175        let mut window: Vec<DocChunk> = Vec::new();
3176        let flush = |window: &mut Vec<DocChunk>, out: &mut Vec<DocChunk>| match window.len() {
3177            0 => {}
3178            1 => out.push(window.pop().unwrap()),
3179            _ => {
3180                out.push(merged_chunk(window.iter()));
3181                window.clear();
3182            }
3183        };
3184        for chunk in chunks {
3185            if window.is_empty() {
3186                window.push(chunk);
3187                continue;
3188            }
3189            let candidate = merged_chunk(window.iter().chain([&chunk]));
3190            if chunk.headings == window[0].headings
3191                && h.count_chunk_tokens(&candidate) <= h.max_tokens()
3192            {
3193                window.push(chunk);
3194            } else {
3195                flush(&mut window, &mut out);
3196                window.push(chunk);
3197            }
3198        }
3199        flush(&mut window, &mut out);
3200        out
3201    }
3202
3203    fn linear_merge<T: ChunkTokenizer>(
3204        h: &HybridChunker<T>,
3205        chunks: Vec<DocChunk>,
3206    ) -> Vec<DocChunk> {
3207        let mut out = Vec::new();
3208        let mut sink = |c| {
3209            out.push(c);
3210            true
3211        };
3212        let mut m = PeerMerger::default();
3213        for c in chunks {
3214            assert!(h.merge_push(&mut m, c, &mut sink));
3215        }
3216        assert!(h.merge_flush(&mut m, &mut sink));
3217        out
3218    }
3219
3220    /// A non-additive "tokenizer": a token per started 4 characters, so the
3221    /// joined text counts differently from the sum of its parts and the
3222    /// delimiter's measured cost is negative — the running estimate is
3223    /// re-anchored and the final window shrunk back.
3224    struct QuadCharTok(usize);
3225    impl ChunkTokenizer for QuadCharTok {
3226        fn count_tokens(&self, text: &str) -> usize {
3227            text.chars().count().div_ceil(4)
3228        }
3229        fn max_tokens(&self) -> usize {
3230            self.0
3231        }
3232    }
3233
3234    /// Pseudo-random chunks: short texts of 1–12 words under one of three
3235    /// heading paths (runs of equal headings, as the walk yields them).
3236    fn random_chunks(seed: u64, n: usize) -> Vec<DocChunk> {
3237        let mut state = seed;
3238        let mut next = move |m: u64| {
3239            state = state
3240                .wrapping_mul(6364136223846793005)
3241                .wrapping_add(1442695040888963407);
3242            (state >> 33) % m
3243        };
3244        let headings = [
3245            None,
3246            Some(vec!["A".to_string()]),
3247            Some(vec!["A".into(), "B".into()]),
3248        ];
3249        let mut current = 0;
3250        (0..n)
3251            .map(|i| {
3252                if next(4) == 0 {
3253                    current = next(3) as usize;
3254                }
3255                let words = 1 + next(12) as usize;
3256                let text = (0..words)
3257                    .map(|w| ["x", "lorem", "ipsum", "dolor", "sit"][(w + i) % 5])
3258                    .collect::<Vec<_>>()
3259                    .join(" ");
3260                DocChunk {
3261                    text,
3262                    headings: headings[current].clone(),
3263                    doc_items: vec![ChunkItem {
3264                        self_ref: format!("#/texts/{i}"),
3265                        kind: ChunkItemKind::Text,
3266                        text: String::new(),
3267                    }],
3268                }
3269            })
3270            .collect()
3271    }
3272
3273    /// #782 (docling-core#823): the linear peer merge gives exactly the
3274    /// chunks of the quadratic one, with an additive and a non-additive
3275    /// tokenizer, over many budgets.
3276    #[test]
3277    fn linear_peer_merge_matches_the_quadratic_one() {
3278        for seed in 0..40 {
3279            let chunks = random_chunks(seed, 60);
3280            for max in [3, 8, 16, 40, 200] {
3281                let h = HybridChunker::new(WordTok(max));
3282                assert_eq!(
3283                    linear_merge(&h, chunks.clone()),
3284                    quadratic_merge(&h, chunks.clone()),
3285                    "words, seed {seed}, max {max}"
3286                );
3287                let h = HybridChunker::new(QuadCharTok(max));
3288                assert_eq!(
3289                    linear_merge(&h, chunks.clone()),
3290                    quadratic_merge(&h, chunks.clone()),
3291                    "chars/4, seed {seed}, max {max}"
3292                );
3293            }
3294        }
3295    }
3296
3297    /// 10k tiny paragraphs at an 8192-token budget — docling-core#823's
3298    /// benchmark. `cargo test -p docling-core --release -- --ignored
3299    /// peer_merge_bench --nocapture` prints both timings.
3300    #[test]
3301    #[ignore]
3302    fn peer_merge_bench() {
3303        let chunks: Vec<DocChunk> = (0..10_000)
3304            .map(|i| DocChunk {
3305                text: format!("Paragraph number {i} is short."),
3306                headings: Some(vec!["Section".into()]),
3307                doc_items: Vec::new(),
3308            })
3309            .collect();
3310        let h = HybridChunker::new(WordTok(8192));
3311        let t = std::time::Instant::now();
3312        let fast = linear_merge(&h, chunks.clone());
3313        let linear = t.elapsed();
3314        let t = std::time::Instant::now();
3315        let slow = quadratic_merge(&h, chunks);
3316        let quadratic = t.elapsed();
3317        assert_eq!(fast, slow);
3318        println!(
3319            "linear {linear:?}, quadratic {quadratic:?}, {} chunks",
3320            fast.len()
3321        );
3322    }
3323
3324    /// A table from first-class cells `(text, row, col, row_span,
3325    /// column_header)`, its grid repeating a spanning cell's text.
3326    fn cell_table(
3327        num_rows: usize,
3328        num_cols: usize,
3329        cells: &[(&str, usize, usize, usize, bool)],
3330    ) -> Table {
3331        let mut rows = vec![vec![String::new(); num_cols]; num_rows];
3332        for &(text, r, c, span, _) in cells {
3333            for row in rows.iter_mut().skip(r).take(span) {
3334                row[c] = text.into();
3335            }
3336        }
3337        Table {
3338            rows,
3339            cells: Some(
3340                cells
3341                    .iter()
3342                    .map(|&(text, r, c, span, ched)| crate::TableCell {
3343                        text: text.into(),
3344                        bbox: None,
3345                        start_row: r,
3346                        start_col: c,
3347                        row_span: span,
3348                        col_span: 1,
3349                        column_header: ched,
3350                        row_header: false,
3351                        row_section: false,
3352                    })
3353                    .collect(),
3354            ),
3355            ..Default::default()
3356        }
3357    }
3358
3359    /// #778 (docling-core#767, 2.102): the Markdown table and the triplet
3360    /// chunk agree on the header rows — upstream's parametrized
3361    /// `test_table_header_rows_in_markdown_and_dataframe`, plus the issue's
3362    /// two tables. Expected texts are docling-core 2.102.0's (compact
3363    /// Markdown, `HierarchicalChunker` chunk text).
3364    #[test]
3365    fn markdown_and_triplets_share_the_header_rows() {
3366        type Case<'a> = (
3367            &'a str,
3368            usize,
3369            usize,
3370            Vec<(&'a str, usize, usize, usize, bool)>,
3371            &'a str,
3372            &'a str,
3373        );
3374        let cases: Vec<Case> = vec![
3375            (
3376                "rows under a row-spanning header stay in the body",
3377                2,
3378                2,
3379                vec![("Price", 0, 0, 1, true), ("Category", 0, 1, 2, true), ("10.00", 1, 0, 1, false)],
3380                "| Price | Category |\n| - | - |\n| 10.00 | Category |",
3381                "10.00, Category = Category",
3382            ),
3383            (
3384                "a row header flagged as column header stays in the body",
3385                3,
3386                3,
3387                vec![
3388                    ("Year", 0, 0, 1, true),
3389                    ("Month", 0, 1, 1, true),
3390                    ("Revenue", 0, 2, 1, true),
3391                    ("2025", 1, 0, 2, true),
3392                    ("January", 1, 1, 1, false),
3393                    ("$134", 1, 2, 1, false),
3394                    ("February", 2, 1, 1, false),
3395                    ("$150", 2, 2, 1, false),
3396                ],
3397                "| Year | Month | Revenue |\n| - | - | - |\n| 2025 | January | $134 |\n| 2025 | February | $150 |",
3398                "2025, Month = January. 2025, Revenue = $134. 2025, Month = February. 2025, Revenue = $150",
3399            ),
3400            (
3401                "stacked header with an unmarked row label",
3402                3,
3403                3,
3404                vec![
3405                    ("", 0, 0, 1, true),
3406                    ("% of Total", 0, 1, 1, true),
3407                    ("% of Total", 0, 2, 1, true),
3408                    ("class label", 1, 0, 1, false),
3409                    ("Train", 1, 1, 1, true),
3410                    ("Test", 1, 2, 1, true),
3411                    ("Caption", 2, 0, 1, false),
3412                    ("2.5", 2, 1, 1, false),
3413                    ("2.4", 2, 2, 1, false),
3414                ],
3415                "| class label | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.5 | 2.4 |",
3416                "Caption, % of Total.Train = 2.5. Caption, % of Total.Test = 2.4",
3417            ),
3418            (
3419                "a partially flagged first row stays the header",
3420                2,
3421                2,
3422                vec![("Name", 0, 0, 1, true), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3423                "| Name | Value |\n| - | - |\n| A | 1 |",
3424                "A, Value = 1",
3425            ),
3426            (
3427                "no flags: Markdown promotes row 0, triplets do not",
3428                2,
3429                2,
3430                vec![("Name", 0, 0, 1, false), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3431                "| Name | Value |\n| - | - |\n| A | 1 |",
3432                "Name, 1 = Value. A, 1 = 1",
3433            ),
3434            (
3435                "row headers flagged as column headers stay in the body",
3436                2,
3437                2,
3438                vec![("2025", 0, 0, 1, true), ("$134", 0, 1, 1, false), ("2026", 1, 0, 1, true), ("$150", 1, 1, 1, false)],
3439                "|  |  |\n| - | - |\n| 2025 | $134 |\n| 2026 | $150 |",
3440                "2025, 1 = $134. 2026, 1 = $150",
3441            ),
3442            (
3443                "a form with flagged first-column labels is all data",
3444                3,
3445                2,
3446                vec![
3447                    ("Name", 0, 0, 1, true),
3448                    ("Bob", 0, 1, 1, false),
3449                    ("Age", 1, 0, 1, true),
3450                    ("42", 1, 1, 1, false),
3451                    ("City", 2, 0, 1, true),
3452                    ("Paris", 2, 1, 1, false),
3453                ],
3454                "|  |  |\n| - | - |\n| Name | Bob |\n| Age | 42 |\n| City | Paris |",
3455                "Name, 1 = Bob. Age, 1 = 42. City, 1 = Paris",
3456            ),
3457            (
3458                "a partly flagged row 0 above a stacked header row",
3459                3,
3460                3,
3461                vec![
3462                    ("Region", 0, 0, 1, true),
3463                    ("2025", 0, 1, 1, false),
3464                    ("", 0, 2, 1, false),
3465                    ("", 1, 0, 1, false),
3466                    ("Q1", 1, 1, 1, true),
3467                    ("Q2", 1, 2, 1, true),
3468                    ("North", 2, 0, 1, false),
3469                    ("1", 2, 1, 1, false),
3470                    ("2", 2, 2, 1, false),
3471                ],
3472                "| Region | 2025 - Q1 | Q2 |\n| - | - | - |\n| North | 1 | 2 |",
3473                "North, 2025.Q1 = 1. North, Q2 = 2",
3474            ),
3475        ];
3476        for (name, rows, cols, cells, md, triplets) in cases {
3477            let t = cell_table(rows, cols, &cells);
3478            assert_eq!(
3479                crate::markdown::render_table(&t, true),
3480                md,
3481                "{name}: markdown"
3482            );
3483            assert_eq!(triplet_table_text(&t), triplets, "{name}: triplets");
3484        }
3485    }
3486
3487    /// #777 (docling-core#857, 2.102): a rich header cell spanning two
3488    /// columns repeats in both — upstream's `col_span_rich_table_doc`. Its
3489    /// blocks sit on the anchor only and the covered position's flat text is
3490    /// blank, so LaTeX and the triplets must resolve the anchor themselves.
3491    #[test]
3492    fn a_column_spanning_rich_cell_repeats_in_every_column() {
3493        let mut t = cell_table(
3494            2,
3495            3,
3496            &[
3497                ("", 0, 0, 1, true),
3498                ("Partner", 0, 1, 1, true),
3499                ("Status", 1, 0, 1, false),
3500                ("Done", 1, 1, 1, false),
3501                ("Open", 1, 2, 1, false),
3502            ],
3503        );
3504        if let Some(cells) = t.cells.as_mut() {
3505            cells[1].col_span = 2;
3506        }
3507        let mut blocks = vec![vec![Vec::new(); 3]; 2];
3508        blocks[0][1] = vec![Node::Paragraph {
3509            text: "Partner".into(),
3510        }];
3511        t.cell_blocks = Some(blocks);
3512        assert_eq!(
3513            t.rows[0][2], "",
3514            "the covered position carries no text of its own"
3515        );
3516        assert_eq!(
3517            triplet_table_text(&t),
3518            "Status, Partner = Done. Status, Partner = Open"
3519        );
3520        let latex = crate::latex::render_table(&t);
3521        assert!(
3522            latex.contains(" & Partner & Partner \\\\ \\hline\nStatus & Done & Open \\\\ \\hline"),
3523            "{latex}"
3524        );
3525        // Markdown reads the flat text, which the backends now fill.
3526        t.rows[0][2] = "Partner".into();
3527        assert_eq!(
3528            crate::markdown::render_table(&t, true),
3529            "|  | Partner | Partner |\n| - | - | - |\n| Status | Done | Open |"
3530        );
3531    }
3532
3533    #[test]
3534    fn hybrid_merges_small_peers_and_splits_large() {
3535        let doc = doc_with(vec![
3536            Node::Heading {
3537                level: 2,
3538                text: "S".into(),
3539            },
3540            Node::Paragraph { text: "a b".into() },
3541            Node::Paragraph { text: "c d".into() },
3542        ]);
3543        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3544        assert_eq!(chunks.len(), 1, "peers under one heading merge");
3545        assert_eq!(chunks[0].text, "a b\nc d");
3546
3547        let long = "w ".repeat(40).trim().to_string();
3548        let doc = doc_with(vec![Node::Paragraph { text: long }]);
3549        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3550        assert!(chunks.len() > 1, "oversized paragraph splits");
3551        for c in &chunks {
3552            assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
3553        }
3554    }
3555
3556    #[test]
3557    fn semchunk_prefers_newlines_then_sentences() {
3558        let tok = WordTok(4);
3559        let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
3560        assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
3561    }
3562
3563    /// #1065: a literal `$` in running text (prices) is not an inline-formula
3564    /// delimiter — the paragraph stays one item, its text verbatim.
3565    #[test]
3566    fn dollar_amounts_are_not_inline_formulas() {
3567        for text in [
3568            "costs $5 and $0.25",
3569            "a bet of $5 riding on the game. The player has just won $6 on the game.",
3570            "pay $10, get $ 3 back",
3571        ] {
3572            assert_eq!(
3573                inline_segments(text),
3574                vec![text.to_string()],
3575                "{text:?} was split"
3576            );
3577            let doc = doc_with(vec![Node::Paragraph { text: text.into() }]);
3578            let chunks = HierarchicalChunker.chunk(&doc);
3579            assert_eq!(chunks.len(), 1);
3580            assert_eq!(chunks[0].text, text);
3581            assert_eq!(chunks[0].doc_items.len(), 1);
3582            assert_eq!(chunks[0].doc_items[0].text, text);
3583        }
3584    }
3585
3586    /// Real inline formulas keep their own item, re-wrapped as `$$…$$`.
3587    #[test]
3588    fn dollar_math_inline_formulas_still_split() {
3589        assert_eq!(
3590            inline_segments("where $E=mc^2$ holds"),
3591            vec!["where", "$$E=mc^2$$", "holds"]
3592        );
3593        assert_eq!(inline_segments("$x$"), vec!["$$x$$"]);
3594    }
3595
3596    /// With structured runs, only a `formula` run's LaTeX is a formula — a
3597    /// price next to a real equation stays plain text.
3598    #[test]
3599    fn formula_runs_decide_inline_formulas() {
3600        let runs = vec![
3601            crate::InlineRun {
3602                text: "costs $5, and".into(),
3603                ..Default::default()
3604            },
3605            crate::InlineRun {
3606                text: "x + 1".into(),
3607                formula: true,
3608                ..Default::default()
3609            },
3610            crate::InlineRun {
3611                text: "is $6".into(),
3612                ..Default::default()
3613            },
3614        ];
3615        let segs: Vec<String> = inline_segments_tagged("costs $5, and $x + 1$ is $6", &runs)
3616            .into_iter()
3617            .map(|(t, _)| t)
3618            .collect();
3619        assert_eq!(segs, vec!["costs $5, and", "$$x + 1$$", "is $6"]);
3620    }
3621}