Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(splitter): keep syntax nodes that fit whole, and headers with their bodies (#2716)

LJ 🥥🌴b8a2e072b0ff
diff --git a/docs/src/content/docs/ops/text.mdx b/docs/src/content/docs/ops/text.mdx
index adb9613e..c1ffbda3 100644
--- a/docs/src/content/docs/ops/text.mdx
+++ b/docs/src/content/docs/ops/text.mdx
@@ -143,7 +143,7 @@ Advanced text chunking with language awareness and syntax-aware splitting for co
**Features:**
- Supports many programming languages
-- Preserves code structure
+- Preserves code structure: a function, class or block that fits in `chunk_size` stays in one chunk, and a header, such as a `def` or `if` line or a Markdown heading, stays with the start of its body
- Customizable chunk sizes and overlap
- Returns [`Chunk`](../common_resources/data_types#chunk) objects with start/end positions (line, column, byte/char offsets)
@@ -203,7 +203,7 @@ for chunk in &chunks {
let chunks = splitter.split("Short text.", 100);
```
-`RecursiveSplitter::new()` returns a `Result`. `split(text, chunk_size)` uses the defaults; `split_with(text, config)` takes a `RecursiveChunkConfig` with `chunk_size`, `min_chunk_size` (default `chunk_size / 2`), `chunk_overlap` and `language`. Sizes are in bytes.
+`RecursiveSplitter::new()` returns a `Result`. `split(text, chunk_size)` uses the defaults; `split_with(text, config)` takes a `RecursiveChunkConfig` with `chunk_size`, `min_chunk_size` (a soft floor, default `chunk_size / 2`), `chunk_overlap` and `language`. Sizes are in bytes.
</Fragment>
</LangTabs>
diff --git a/python/cocoindex/ops/text.py b/python/cocoindex/ops/text.py
index 3fc67155..c20f2658 100644
--- a/python/cocoindex/ops/text.py
+++ b/python/cocoindex/ops/text.py
@@ -168,7 +168,9 @@ class RecursiveSplitter:
:class:`~cocoindex.ops.code.CodeSource` whose cached parse is
reused (and populated for later consumers of the same source).
chunk_size: Target chunk size in bytes.
- min_chunk_size: Minimum chunk size in bytes. Defaults to chunk_size / 2.
+ min_chunk_size: Minimum chunk size in bytes. It is a soft floor: a chunk
+ may be smaller where that avoids a worse split point. Defaults to
+ chunk_size / 2.
chunk_overlap: Overlap between consecutive chunks in bytes.
language: Language name or file extension for syntax-aware splitting
(e.g., "python", "rust", ".py", ".rs"). If provided and the language
diff --git a/rust/ops_text/src/split/recursive.rs b/rust/ops_text/src/split/recursive.rs
index c7d066a0..abd58f42 100644
--- a/rust/ops_text/src/split/recursive.rs
+++ b/rust/ops_text/src/split/recursive.rs
@@ -2,6 +2,7 @@
use regex::{Matches, Regex};
use std::collections::HashMap;
+use std::num::NonZeroU16;
use std::sync::{Arc, LazyLock};
use unicase::UniCase;
@@ -13,7 +14,38 @@ use cocoindex_code_ast::{CodeSource, ParseOutcome};
const SYNTAX_LEVEL_GAP_COST: usize = 512;
const MISSING_OVERLAP_COST: usize = 512;
const PER_LINE_BREAK_LEVEL_GAP_COST: usize = 64;
-const TOO_SMALL_CHUNK_COST: usize = 1048576;
+/// The cost of a chunk with no content at all: as much as 16 syntax-level gaps.
+/// A chunk under `min_chunk_size` pays this times its squared shortfall.
+const TOO_SMALL_CHUNK_COST: u64 = 16 * SYNTAX_LEVEL_GAP_COST as u64;
+/// Extra cost of a chunk under a quarter of `chunk_size` that is also under
+/// `min_chunk_size`. A chunk at or over `min_chunk_size` pays nothing, so an
+/// explicit floor below `chunk_size / 4` stays authoritative.
+const TINY_CHUNK_COST: usize = 6 * SYNTAX_LEVEL_GAP_COST;
+/// The same with overlap on: a chunk that is mostly overlap adds little.
+const TINY_CHUNK_WITH_OVERLAP_COST: usize = 16 * SYNTAX_LEVEL_GAP_COST;
+/// Cost per side of a chunk boundary inside a syntax node that fits in
+/// `chunk_size`. Both chunks that meet at the boundary pay it, as they do
+/// `SYNTAX_LEVEL_GAP_COST`, so one cut costs twice this in total.
+const CUT_FITTING_NODE_COST: u32 = 8 * SYNTAX_LEVEL_GAP_COST as u32;
+/// Cost per side of a chunk boundary just after a node's header, which leaves
+/// the header without its body (see `node_header`). Both chunks that meet at
+/// the boundary pay it, so one cut costs twice this.
+const CUT_AFTER_HEADER_COST: u32 = 2 * SYNTAX_LEVEL_GAP_COST as u32;
+/// Cost per side of a chunk boundary inside a node's header, which splits it:
+/// worse than leaving the header whole without its body, so a cut never moves
+/// into the header to avoid `CUT_AFTER_HEADER_COST`.
+const CUT_INSIDE_HEADER_COST: u32 = 2 * CUT_AFTER_HEADER_COST;
+/// The fields that name the child a header introduces: a definition's or a
+/// loop's `body`, an `if` or `elif` branch's `consequence`, and the
+/// `definition` that Python decorators precede.
+const BODY_FIELD_NAMES: [&str; 3] = ["body", "consequence", "definition"];
+/// The cost is computed in fixed point, without a division per chunk:
+/// `(shortfall · (2³² - 1) / min_chunk_size)² >> TOO_SMALL_CHUNK_COST_SHIFT`,
+/// which is `TOO_SMALL_CHUNK_COST · (shortfall / min_chunk_size)²`. The scaled
+/// shortfall is under 2³², as `shortfall <= min_chunk_size`, so its square
+/// fits in a `u64`.
+const TOO_SMALL_CHUNK_COST_SHIFT: u32 = 64 - TOO_SMALL_CHUNK_COST.ilog2();
+const _: () = assert!(TOO_SMALL_CHUNK_COST.is_power_of_two());
/// Configuration for a custom language with regex-based separators.
#[derive(Debug, Clone)]
@@ -39,7 +71,8 @@ pub struct RecursiveSplitConfig {
pub struct RecursiveChunkConfig {
/// Target chunk size in bytes.
pub chunk_size: usize,
- /// Minimum chunk size in bytes. Defaults to chunk_size / 2.
+ /// Minimum chunk size in bytes. It is a soft floor: a chunk may be smaller
+ /// where that avoids a worse split point. Defaults to chunk_size / 2.
pub min_chunk_size: Option<usize>,
/// Overlap between consecutive chunks in bytes.
pub chunk_overlap: Option<usize>,
@@ -266,6 +299,10 @@ struct AtomChunk {
boundary_syntax_level: usize,
internal_lb_level: LineBreakLevel,
boundary_lb_level: LineBreakLevel,
+ /// Cost of ending a chunk, or starting one, at this atom's start: the
+ /// boundary is inside a syntax node that fits in `chunk_size`, or inside
+ /// or just after a node's header.
+ boundary_cut_cost: u32,
}
struct AtomChunksCollector<'s> {
@@ -276,7 +313,7 @@ struct AtomChunksCollector<'s> {
}
impl<'s> AtomChunksCollector<'s> {
- fn collect(&mut self, range: TextRange) {
+ fn collect(&mut self, range: TextRange, boundary_cut_cost: u32) {
// Trim trailing whitespaces.
let end_trimmed_text = &self.full_text[range.start..range.end].trim_end();
if end_trimmed_text.is_empty() {
@@ -304,6 +341,7 @@ impl<'s> AtomChunksCollector<'s> {
boundary_syntax_level: self.min_level,
internal_lb_level: line_break_level(trimmed_text),
boundary_lb_level,
+ boundary_cut_cost,
});
self.min_level = self.curr_level;
}
@@ -314,6 +352,7 @@ impl<'s> AtomChunksCollector<'s> {
boundary_syntax_level: self.min_level,
internal_lb_level: LineBreakLevel::Inline,
boundary_lb_level: LineBreakLevel::DoubleNewline,
+ boundary_cut_cost: 0,
});
self.atom_chunks
}
@@ -329,24 +368,228 @@ struct InternalRecursiveChunker<'s> {
chunk_size: usize,
chunk_overlap: usize,
min_chunk_size: usize,
+ /// `(2³² - 1) / min_chunk_size`: the fixed-point scale for `too_small_chunk_cost`.
+ too_small_chunk_cost_scale: u64,
min_atom_chunk_size: usize,
+ tiny_chunk_cost: usize,
+ /// See `body_field_ids`; empty without a syntax tree.
+ body_field_ids: Vec<NonZeroU16>,
+}
+
+/// A node's header and the body it introduces (see `node_header`).
+#[derive(Clone, Copy)]
+struct NodeHeader {
+ /// A chunk boundary at any position `p` with `start < p <= end` splits
+ /// the header or leaves it without its body.
+ range: TextRange,
+ body: TextRange,
+}
+
+/// The header of `node`: the text that introduces its body on a later line,
+/// such as `def f(x) -> int:`, `if x {` or a Markdown heading.
+///
+/// The range starts at the first content on the line where `node` starts,
+/// so the header line as a whole stays together, as in `} else {`. It ends
+/// at the body's first content, past any `{`, `(` or `[` that opens it.
+///
+/// The body is the child in one of `BODY_FIELD_NAMES`, given as the tree's
+/// `body_field_ids`; else the last named child, if it opens with a bracket
+/// and a keyword or operator token comes just before it (`else {`,
+/// `return [`, `x = {`); else, if the first named child is a heading, the
+/// child after it.
+fn node_header(
+ full_text: &str,
+ body_field_ids: &[NonZeroU16],
+ node: tree_sitter::Node<'_>,
+) -> Option<NodeHeader> {
+ let bytes = full_text.as_bytes();
+ let body = body_field_ids
+ .iter()
+ .find_map(|&field| node.child_by_field_id(field.get()))
+ .or_else(|| {
+ let last = node.named_child(node.named_child_count().checked_sub(1)?)?;
+ let opens_with_bracket =
+ matches!(bytes.get(last.start_byte()), Some(b'{' | b'(' | b'['));
+ (opens_with_bracket && last.prev_sibling().is_some_and(|token| !token.is_named()))
+ .then_some(last)
+ })
+ .or_else(|| {
+ let first = node.named_child(0)?;
+ if first.kind().ends_with("heading") {
+ first.next_named_sibling()
+ } else {
+ None
+ }
+ })?;
+ if body.start_byte() <= node.start_byte() {
+ return None;
+ }
+ let mut end = body.start_byte();
+ while end < node.end_byte()
+ && (bytes[end].is_ascii_whitespace() || matches!(bytes[end], b'{' | b'(' | b'['))
+ {
+ end += 1;
+ }
+ // A header ends a line: a body whose content starts on the header's line,
+ // as in `{x}` or `f(x)`, can't be left in the next chunk by a line break.
+ if end >= node.end_byte() || !bytes[node.start_byte()..end].contains(&b'\n') {
+ return None;
+ }
+ let mut start = bytes[..node.start_byte()]
+ .iter()
+ .rposition(|&b| b == b'\n')
+ .map_or(0, |i| i + 1);
+ while start < node.start_byte() && matches!(bytes[start], b' ' | b'\t') {
+ start += 1;
+ }
+ Some(NodeHeader {
+ range: TextRange::new(start, end),
+ body: TextRange::new(body.start_byte(), body.end_byte()),
+ })
+}
+
+/// The ids of `BODY_FIELD_NAMES` in the language of `tree`, resolved once per
+/// split: resolving a field name scans all of the grammar's field names.
+fn body_field_ids(tree: &tree_sitter::Tree) -> Vec<NonZeroU16> {
+ let language = tree.language();
+ BODY_FIELD_NAMES
+ .iter()
+ .filter_map(|name| language.field_id_for_name(name))
+ .collect()
+}
+
+/// A frame of the syntax walk in `collect_atom_chunks`.
+struct WalkFrame<'t, 's: 't> {
+ iter: ChunkIterator<'t, 's>,
+ /// The syntax node this frame walks inside of, if it fits in `chunk_size`:
+ /// a cut inside it is avoidable, since the node can stay whole.
+ fitting_node: Option<TextRange>,
+ /// The header of that syntax node, if it has one.
+ header: Option<NodeHeader>,
+ /// The content of that syntax node, trimmed, if it is the body of a node
+ /// that does not fit, or all of such a body's text: it may fit, but is not
+ /// kept whole (see `node_frame`).
+ unfitting_body: Option<TextRange>,
}
impl<'t, 's: 't> InternalRecursiveChunker<'s> {
+ /// `range`, a syntax node's range, if the node fits in `chunk_size`. A
+ /// chunk that starts after only indentation on its line starts at the
+ /// line's beginning, so the indentation counts toward the node's size.
+ fn fitting_node(&self, range: TextRange) -> Option<TextRange> {
+ if range.len() > self.chunk_size {
+ return None;
+ }
+ let bytes = self.full_text.as_bytes();
+ let mut line_start = range.start;
+ while line_start > 0 && matches!(bytes[line_start - 1], b' ' | b'\t') {
+ line_start -= 1;
+ }
+ if line_start > 0 && bytes[line_start - 1] != b'\n' {
+ line_start = range.start;
+ }
+ (range.end - line_start <= self.chunk_size).then_some(range)
+ }
+
+ /// `range` without its leading and trailing whitespace.
+ fn trimmed(&self, range: TextRange) -> TextRange {
+ let text = &self.full_text[range.start..range.end];
+ let start = range.start + (text.len() - text.trim_start().len());
+ TextRange::new(start, range.start + text.trim_end().len())
+ }
+
+ /// The frame that walks inside `node`, a child of the `parent` frame.
+ ///
+ /// The body of a node that does not fit is not kept whole, even if it fits
+ /// on its own: the unit is the header with its body, and keeping the body
+ /// whole would leave the header alone in a chunk. The header cost keeps
+ /// the header with the start of the body instead. The same holds for a
+ /// node that is all of such a body's content and `splits_as_text`, such as
+ /// the `inline` text of a Markdown paragraph, which splits at sentences.
+ /// A body with a header of its own, such as a decorated `def`, is a unit
+ /// itself and stays whole where it fits.
+ fn node_frame(
+ &self,
+ iter: ChunkIterator<'t, 's>,
+ node: tree_sitter::Node<'_>,
+ splits_as_text: bool,
+ parent: Option<&WalkFrame<'t, 's>>,
+ ) -> WalkFrame<'t, 's> {
+ let range = TextRange::new(node.start_byte(), node.end_byte());
+ let content = self.trimmed(range);
+ let header = node_header(self.full_text, &self.body_field_ids, node);
+ let unfitting_body = (header.is_none()
+ && parent.is_some_and(|parent| {
+ (parent.fitting_node.is_none() && parent.header.is_some_and(|h| h.body == range))
+ || (splits_as_text && parent.unfitting_body == Some(content))
+ }))
+ .then_some(content);
+ WalkFrame {
+ iter,
+ fitting_node: if unfitting_body.is_some() {
+ None
+ } else {
+ self.fitting_node(range)
+ },
+ header,
+ unfitting_body,
+ }
+ }
+
+ /// The cost of cutting at the start of the atom at `range`, given the
+ /// frames of the syntax walk that the atom is inside of.
+ ///
+ /// A cut inside a node that fits in `chunk_size` costs
+ /// `CUT_FITTING_NODE_COST`, a cut inside a node's header costs
+ /// `CUT_INSIDE_HEADER_COST`, and one just after it `CUT_AFTER_HEADER_COST`,
+ /// however many such nodes there are.
+ fn boundary_cut_cost(&self, frames: &[WalkFrame<'t, 's>], range: TextRange) -> u32 {
+ let text = &self.full_text[range.start..range.end];
+ let pos = range.start + (text.len() - text.trim_start().len());
+ let mut cost = 0;
+ let headers = || frames.iter().filter_map(|frame| frame.header);
+ if headers().any(|h| h.range.start < pos && pos < h.range.end) {
+ cost += CUT_INSIDE_HEADER_COST;
+ } else if headers().any(|h| pos == h.range.end) {
+ cost += CUT_AFTER_HEADER_COST;
+ }
+ if frames
+ .iter()
+ .filter_map(|frame| frame.fitting_node)
+ .any(|node| node.start < pos && pos < node.end)
+ {
+ cost += CUT_FITTING_NODE_COST;
+ }
+ cost
+ }
+
fn collect_atom_chunks(
&self,
chunk: InternalChunk<'t, 's>,
atom_collector: &mut AtomChunksCollector<'s>,
) {
- let mut iter_stack: Vec<ChunkIterator<'t, 's>> =
- vec![ChunkIterator::Once(std::iter::once(chunk))];
+ let root_node = match &chunk.kind {
+ ChunkKind::TreeSitterNode { node, .. } => Some(*node),
+ ChunkKind::RegexpSepChunk { .. } => None,
+ };
+ let root_iter = ChunkIterator::Once(std::iter::once(chunk));
+ let mut frames = vec![match root_node {
+ Some(node) => self.node_frame(root_iter, node, false, None),
+ None => WalkFrame {
+ iter: root_iter,
+ fitting_node: None,
+ header: None,
+ unfitting_body: None,
+ },
+ }];
- while !iter_stack.is_empty() {
- atom_collector.curr_level = iter_stack.len();
+ while !frames.is_empty() {
+ atom_collector.curr_level = frames.len();
- if let Some(current_chunk) = iter_stack.last_mut().unwrap().next() {
+ if let Some(current_chunk) = frames.last_mut().unwrap().iter.next() {
if current_chunk.range.len() <= self.min_atom_chunk_size {
- atom_collector.collect(current_chunk.range);
+ let cost = self.boundary_cut_cost(&frames, current_chunk.range);
+ atom_collector.collect(current_chunk.range, cost);
} else {
match current_chunk.kind {
ChunkKind::TreeSitterNode {
@@ -356,52 +599,62 @@ impl<'t, 's: 't> InternalRecursiveChunker<'s> {
if !lang_config.terminal_node_kind_ids.contains(&node.kind_id()) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
- iter_stack.push(ChunkIterator::TreeSitter(
- TreeSitterNodeIter {
- lang_config,
- full_text: self.full_text,
- cursor: Some(cursor),
- // The chunk's range, not the node's:
- // a root node may not span the whole
- // text (YAML's stops before a stray
- // BOM), and the gaps around its
- // children must still be covered.
- next_start_pos: current_chunk.range.start,
- end_pos: current_chunk.range.end,
- },
- ));
+ let iter = ChunkIterator::TreeSitter(TreeSitterNodeIter {
+ lang_config,
+ full_text: self.full_text,
+ cursor: Some(cursor),
+ // The chunk's range, not the node's: a
+ // root node may not span the whole text
+ // (YAML's stops before a stray BOM), and
+ // the gaps around its children must
+ // still be covered.
+ next_start_pos: current_chunk.range.start,
+ end_pos: current_chunk.range.end,
+ });
+ let frame = self.node_frame(iter, node, false, frames.last());
+ frames.push(frame);
continue;
}
}
- iter_stack.push(ChunkIterator::Once(std::iter::once(InternalChunk {
+ // A terminal node, or one with no children, is split
+ // as text; a cut inside it still cuts the node.
+ let iter = ChunkIterator::Once(std::iter::once(InternalChunk {
full_text: self.full_text,
range: current_chunk.range,
kind: ChunkKind::RegexpSepChunk {
lang_config: &DEFAULT_LANGUAGE_CONFIG,
next_regexp_sep_id: 0,
},
- })));
+ }));
+ let frame = self.node_frame(iter, node, true, frames.last());
+ frames.push(frame);
}
ChunkKind::RegexpSepChunk {
lang_config,
next_regexp_sep_id,
} => {
if next_regexp_sep_id >= lang_config.separator_regex.len() {
- atom_collector.collect(current_chunk.range);
+ let cost = self.boundary_cut_cost(&frames, current_chunk.range);
+ atom_collector.collect(current_chunk.range, cost);
} else {
- iter_stack.push(ChunkIterator::Text(TextChunksIter::new(
- lang_config,
- current_chunk.full_text,
- current_chunk.range,
- next_regexp_sep_id,
- )));
+ frames.push(WalkFrame {
+ iter: ChunkIterator::Text(TextChunksIter::new(
+ lang_config,
+ current_chunk.full_text,
+ current_chunk.range,
+ next_regexp_sep_id,
+ )),
+ fitting_node: None,
+ header: None,
+ unfitting_body: None,
+ });
}
}
}
}
} else {
- iter_stack.pop();
- let level_after_pop = iter_stack.len();
+ frames.pop();
+ let level_after_pop = frames.len();
atom_collector.curr_level = level_after_pop;
if level_after_pop < atom_collector.min_level {
atom_collector.min_level = level_after_pop;
@@ -411,6 +664,25 @@ impl<'t, 's: 't> InternalRecursiveChunker<'s> {
atom_collector.curr_level = 0;
}
+ /// The cost of a chunk of `chunk_size` bytes for falling short of
+ /// `min_chunk_size`: `TOO_SMALL_CHUNK_COST` times the square of the
+ /// shortfall as a fraction of `min_chunk_size`. A chunk a little under the
+ /// floor costs less than a cut through a syntax node, so it wins over one;
+ /// a chunk far under it costs as much as many such cuts, so it doesn't.
+ fn too_small_chunk_cost(&self, chunk_size: usize) -> usize {
+ if chunk_size >= self.min_chunk_size {
+ return 0;
+ }
+ let scaled_shortfall =
+ (self.min_chunk_size - chunk_size) as u64 * self.too_small_chunk_cost_scale;
+ let graded = ((scaled_shortfall * scaled_shortfall) >> TOO_SMALL_CHUNK_COST_SHIFT) as usize;
+ if chunk_size.saturating_mul(4) < self.chunk_size {
+ graded + self.tiny_chunk_cost
+ } else {
+ graded
+ }
+ }
+
fn get_overlap_cost_base(&self, offset: usize) -> usize {
((self.full_text.len() - offset) * MISSING_OVERLAP_COST)
.checked_div(self.chunk_overlap)
@@ -456,6 +728,7 @@ impl<'t, 's: 't> InternalRecursiveChunker<'s> {
let end_syntax_level = atom_chunks[i + 1].boundary_syntax_level;
let end_lb_level = atom_chunks[i + 1].boundary_lb_level;
+ let end_cut_cost = atom_chunks[i + 1].boundary_cut_cost;
let mut internal_syntax_level = usize::MAX;
let mut internal_lb_level = LineBreakLevel::Inline;
@@ -475,12 +748,11 @@ impl<'t, 's: 't> InternalRecursiveChunker<'s> {
cost +=
syntax_level_gap_cost(start_chunk.boundary_syntax_level, internal_syntax_level);
cost += syntax_level_gap_cost(end_syntax_level, internal_syntax_level);
+ cost += (start_chunk.boundary_cut_cost + end_cut_cost) as usize;
cost += (lb_level_gap(start_chunk.boundary_lb_level, internal_lb_level)
+ lb_level_gap(end_lb_level, internal_lb_level))
* PER_LINE_BREAK_LEVEL_GAP_COST;
- if chunk_size < self.min_chunk_size {
- cost += TOO_SMALL_CHUNK_COST;
- }
+ cost += self.too_small_chunk_cost(chunk_size);
if chunk_size > self.chunk_size {
if min_cost == usize::MAX {
@@ -647,25 +919,44 @@ impl RecursiveChunker {
let min_chunk_size = config.min_chunk_size.unwrap_or(config.chunk_size / 2);
let chunk_overlap = std::cmp::min(config.chunk_overlap.unwrap_or(0), min_chunk_size);
+ let language = UniCase::new(source.requested_language().unwrap_or_default().to_string());
+ let custom_language = self.custom_languages.get(&language);
+ // A custom language never parses.
+ let tree = match custom_language {
+ Some(_) => None,
+ None => match source.tree() {
+ ParseOutcome::Parsed(tree) => Some(tree),
+ _ => None,
+ },
+ };
+
let internal_chunker = InternalRecursiveChunker {
full_text: text,
chunk_size: config.chunk_size,
chunk_overlap,
min_chunk_size,
+ too_small_chunk_cost_scale: u64::from(u32::MAX)
+ .checked_div(min_chunk_size as u64)
+ .unwrap_or(0),
min_atom_chunk_size: if chunk_overlap > 0 {
chunk_overlap
} else {
min_chunk_size
},
+ tiny_chunk_cost: if chunk_overlap > 0 {
+ TINY_CHUNK_WITH_OVERLAP_COST
+ } else {
+ TINY_CHUNK_COST
+ },
+ body_field_ids: tree.map_or_else(Vec::new, body_field_ids),
};
- let language = UniCase::new(source.requested_language().unwrap_or_default().to_string());
- let output = if let Some(lang_config) = self.custom_languages.get(&language) {
+ let output = if let Some(lang_config) = custom_language {
internal_chunker.split_root_chunk(ChunkKind::RegexpSepChunk {
lang_config,
next_regexp_sep_id: 0,
})
- } else if let ParseOutcome::Parsed(tree) = source.tree() {
+ } else if let Some(tree) = tree {
let tree_sitter_info = source
.treesitter_info()
.expect("a parsed tree implies tree-sitter info");
@@ -817,6 +1108,370 @@ mod tests {
assert!(!chunk_text.starts_with(" "));
}
+ const PYTHON_SAMPLE: &str = r#"class Inventory:
+ """Stock levels for one warehouse."""
+
+ def __init__(self, name):
+ self.name = name
+ self.items = {}
+
+ def add_item(self, sku, qty):
+ if qty <= 0:
+ raise ValueError("qty must be positive")
+ self.items[sku] = self.items.get(sku, 0) + qty
+
+ def remove_item(self, sku, qty):
+ have = self.items.get(sku, 0)
+ if qty > have:
+ raise ValueError(f"only {have} of {sku} left")
+ self.items[sku] = have - qty
+
+ class Report:
+ def __init__(self, inventory):
+ self.inventory = inventory
+
+ def low_stock(self, limit=5):
+ items = self.inventory.items
+ return [k for k in items if items[k] < limit]
+
+ def total(self):
+ return sum(self.inventory.items.values())
+
+
+def load(path):
+ inv = Inventory(path.stem)
+ for line in path.read_text().splitlines():
+ sku, qty = line.split(",")
+ inv.add_item(sku, int(qty))
+ return inv
+"#;
+
+ /// A byte range's size in a chunk: a node on its own line counts its indentation.
+ fn size_with_indent(text: &str, range: &TextRange) -> usize {
+ let line_start = text[..range.start].rfind('\n').map_or(0, |p| p + 1);
+ if text[line_start..range.start].trim().is_empty() {
+ range.end - line_start
+ } else {
+ range.end - range.start
+ }
+ }
+
+ fn python_nodes(tree: &tree_sitter::Tree, kinds: &[&str]) -> Vec<TextRange> {
+ fn walk(node: tree_sitter::Node, kinds: &[&str], out: &mut Vec<TextRange>) {
+ if kinds.contains(&node.kind()) {
+ out.push(TextRange::new(node.start_byte(), node.end_byte()));
+ }
+ let mut cursor = node.walk();
+ for child in node.children(&mut cursor) {
+ walk(child, kinds, out);
+ }
+ }
+ let mut out = Vec::new();
+ walk(tree.root_node(), kinds, &mut out);
+ out
+ }
+
+ /// A function or class that fits in `chunk_size` is never cut: the splitter
+ /// leaves a chunk under `min_chunk_size` rather than split it. Here
+ /// `class Report:` with its `__init__` is ~95 bytes, under the default
+ /// floor at chunk sizes 200-250, and the old flat penalty cut `low_stock`
+ /// from its signature to avoid it.
+ #[test]
+ fn test_split_python_keeps_fitting_functions_whole() {
+ let text = PYTHON_SAMPLE;
+ let source = CodeSource::with_language(text, "python");
+ let ParseOutcome::Parsed(tree) = source.tree() else {
+ panic!("python must parse");
+ };
+ let nodes = python_nodes(tree, &["function_definition", "class_definition"]);
+
+ let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
+ for chunk_size in (100..=1100).step_by(25) {
+ let chunks = chunker.split(
+ &source,
+ RecursiveChunkConfig {
+ chunk_size,
+ min_chunk_size: None,
+ chunk_overlap: None,
+ },
+ );
+ for chunk in &chunks {
+ for node in nodes
+ .iter()
+ .filter(|n| size_with_indent(text, n) <= chunk_size)
+ {
+ assert!(
+ !(node.start < chunk.range.start && chunk.range.start < node.end),
+ "chunk_size {chunk_size}: a chunk starts inside a function or class \
+ that fits, at line {}:\n{}",
+ chunk.start.line,
+ &text[chunk.range.start..chunk.range.end],
+ );
+ }
+ }
+ }
+ }
+
+ const RUST_SAMPLE: &str = r#"use std::collections::HashMap;
+
+/// Items in stock, by name.
+pub struct Inventory {
+ items: HashMap<String, u32>,
+}
+
+impl Inventory {
+ pub fn new() -> Self {
+ Self {
+ items: HashMap::new(),
+ }
+ }
+
+ pub fn add(&mut self, name: &str, count: u32) {
+ *self.items.entry(name.to_string()).or_insert(0) += count;
+ }
+
+ pub fn remove(&mut self, name: &str, count: u32) -> Result<(), String> {
+ let have = self.items.get_mut(name).ok_or_else(|| format!("no {name}"))?;
+ if *have < count {
+ return Err(format!("only {have} of {name}, asked for {count}"));
+ }
+ *have -= count;
+ Ok(())
+ }
+
+ pub fn low_stock(&self, limit: u32) -> Vec<&str> {
+ let mut names: Vec<&str> = self
+ .items
+ .iter()
+ .filter(|(_, count)| **count < limit)
+ .map(|(name, _)| name.as_str())
+ .collect();
+ names.sort();
+ names
+ }
+}
+
+pub fn total(inventory: &Inventory) -> u32 {
+ inventory.items.values().sum()
+}
+"#;
+
+ const PYTHON_BRANCHES_SAMPLE: &str = r#"import functools
+
+
+class Cache:
+ """A small cache with a size limit and hit counters."""
+
+ @functools.cached_property
+ def capacity(self) -> int:
+ return self.settings.get("capacity", 128)
+
+ @staticmethod
+ def key_of(request, *, include_headers: bool = False) -> str:
+ if include_headers:
+ return f"{request.method} {request.path} {sorted(request.headers.items())}"
+ elif request.query:
+ return f"{request.method} {request.path}?{request.query}"
+ else:
+ return f"{request.method} {request.path}"
+
+ def get(self, request):
+ key = self.key_of(request)
+ if key in self.entries:
+ self.hits += 1
+ return self.entries[key]
+ self.misses += 1
+ return None
+"#;
+
+ const MARKDOWN_SAMPLE: &str = r#"# Inventory service
+
+The inventory service keeps stock levels for every warehouse and answers
+queries from the storefront and from the planning tools.
+
+## Setup
+
+Install the package, then point it at a database. The service reads its
+settings from the environment and refuses to start without a database URL.
+
+## Usage
+
+Call `add_item` to record a delivery and `remove_item` to record a sale. A sale
+that asks for more than the warehouse holds fails and changes nothing.
+
+### Reports
+
+`low_stock` lists the items under a limit. `total` counts every item in the
+warehouse, across all of its locations.
+"#;
+
+ /// Where the first unit of `body` ends: the first child of a body that
+ /// has no header of its own, else the first unit of what that header
+ /// introduces (a decorated `def`'s first statement, not its name).
+ fn first_unit_end(text: &str, ids: &[NonZeroU16], body: tree_sitter::Node) -> usize {
+ if let Some(header) = node_header(text, ids, body) {
+ let mut cursor = body.walk();
+ let inner = body
+ .children(&mut cursor)
+ .find(|c| c.start_byte() == header.body.start && c.end_byte() == header.body.end);
+ if let Some(inner) = inner {
+ return first_unit_end(text, ids, inner);
+ }
+ }
+ body.named_child(0)
+ .map_or(body.end_byte(), |c| c.end_byte())
+ }
+
+ /// Asserts, at every chunk size from 100 to 1100, that no chunk boundary
+ /// falls inside a node's header (see `node_header`), and that a header
+ /// ends a chunk only where it and the first unit of its body don't fit in
+ /// `chunk_size` together.
+ fn assert_headers_kept_whole_with_body(text: &str, language: &str) {
+ let source = CodeSource::with_language(text, language);
+ let ParseOutcome::Parsed(tree) = source.tree() else {
+ panic!("{language} must parse");
+ };
+ let ids = body_field_ids(tree);
+ let mut headers = Vec::new();
+ let mut stack = vec![tree.root_node()];
+ while let Some(node) = stack.pop() {
+ if let Some(header) = node_header(text, &ids, node) {
+ let mut cursor = node.walk();
+ let body = node
+ .children(&mut cursor)
+ .find(|c| {
+ c.start_byte() == header.body.start && c.end_byte() == header.body.end
+ })
+ .unwrap();
+ let line_start = text[..header.range.start].rfind('\n').map_or(0, |p| p + 1);
+ headers.push((header.range, first_unit_end(text, &ids, body) - line_start));
+ }
+ let mut cursor = node.walk();
+ stack.extend(node.children(&mut cursor));
+ }
+ let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
+ for chunk_size in (100..=1100).step_by(25) {
+ let chunks = chunker.split(
+ &source,
+ RecursiveChunkConfig {
+ chunk_size,
+ min_chunk_size: None,
+ chunk_overlap: None,
+ },
+ );
+ for chunk in &chunks[1..] {
+ let chunk_text = &text[chunk.range.start..chunk.range.end];
+ let start = chunk.range.end - chunk_text.trim_start().len();
+ for &(header, with_first_unit) in &headers {
+ let header_text = &text[header.start..header.end];
+ assert!(
+ !(header.start < start && start < header.end),
+ "chunk_size {chunk_size}: a chunk splits the header {header_text:?}, \
+ at line {}:\n{chunk_text}",
+ chunk.start.line,
+ );
+ assert!(
+ !(start == header.end && with_first_unit <= chunk_size),
+ "chunk_size {chunk_size}: the header {header_text:?} ends a chunk, \
+ though it fits with its body's first {with_first_unit} bytes",
+ );
+ }
+ }
+ }
+ }
+
+ /// A cut never splits a header, as in `def f(x) -> int` | `:` or
+ /// `fn f()` | `{`, and leaves a header without its body only where the
+ /// two can't share a chunk.
+ #[test]
+ fn test_split_keeps_headers_whole_with_body() {
+ assert_headers_kept_whole_with_body(PYTHON_SAMPLE, "python");
+ assert_headers_kept_whole_with_body(PYTHON_BRANCHES_SAMPLE, "python");
+ assert_headers_kept_whole_with_body(RUST_SAMPLE, "rust");
+ assert_headers_kept_whole_with_body(MARKDOWN_SAMPLE, "markdown");
+ }
+
+ /// A Markdown heading stays with the text of its section.
+ #[test]
+ fn test_split_markdown_keeps_heading_with_section() {
+ let text = MARKDOWN_SAMPLE;
+ let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
+ for chunk_size in (100..=1100).step_by(25) {
+ let chunks = chunker.split(
+ &CodeSource::with_language(text, "markdown"),
+ RecursiveChunkConfig {
+ chunk_size,
+ min_chunk_size: None,
+ chunk_overlap: None,
+ },
+ );
+ for chunk in &chunks[..chunks.len() - 1] {
+ let chunk_text = text[chunk.range.start..chunk.range.end].trim_end();
+ let last_line = chunk_text.rsplit('\n').next().unwrap();
+ assert!(
+ !last_line.starts_with('#'),
+ "chunk_size {chunk_size}: a chunk ends on a heading, at line {}:\n{chunk_text}",
+ chunk.end.line,
+ );
+ }
+ }
+ }
+
+ /// A node of a terminal kind is split as text, but a cut inside it still
+ /// cuts the node: a doc comment that fits stays whole.
+ #[test]
+ fn test_split_javascript_keeps_fitting_comment_whole() {
+ let comment = format!(
+ "/**\n{} */",
+ " * Adds two numbers and returns their sum, for the totals.\n".repeat(4)
+ );
+ let text = format!(
+ "{comment}\nfunction add(a, b) {{\n const sum = a + b;\n return sum;\n}}\n\
+ function sub(a, b) {{\n return a - b;\n}}\n"
+ );
+ let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
+ let chunks = chunker.split(
+ &CodeSource::with_language(&text, "javascript"),
+ RecursiveChunkConfig {
+ chunk_size: 300,
+ min_chunk_size: None,
+ chunk_overlap: None,
+ },
+ );
+ assert_eq!(
+ &text[chunks[0].range.start..chunks[0].range.end],
+ comment,
+ "chunks: {:?}",
+ chunks.iter().map(|c| c.range).collect::<Vec<_>>(),
+ );
+ }
+
+ /// The fixed-point too-small cost stays in range at any `min_chunk_size`,
+ /// including one larger than 2³² bytes, where its scale is zero.
+ #[test]
+ fn test_split_too_small_cost_in_range_at_extreme_sizes() {
+ let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
+ let text = "Linea 1.\nLinea 2.\n\nLinea 3.";
+ for (chunk_size, min_chunk_size) in [
+ (15, Some(1)),
+ (15, Some(14)),
+ (15, Some(15)),
+ (1 << 20, Some((1 << 20) - 1)),
+ (1 << 40, None),
+ (usize::MAX, Some(usize::MAX)),
+ ] {
+ let chunks = chunker.split(
+ &CodeSource::new(text),
+ RecursiveChunkConfig {
+ chunk_size,
+ min_chunk_size,
+ chunk_overlap: None,
+ },
+ );
+ assert!(!chunks.is_empty(), "chunk_size {chunk_size}");
+ }
+ }
+
#[test]
fn test_split_with_rust_language() {
let chunker = RecursiveChunker::new(RecursiveSplitConfig::default()).unwrap();
@@ -1028,10 +1683,13 @@ in {
.iter()
.map(|chunk| &text[chunk.range.start..chunk.range.end])
.collect();
+ // The 18-byte header falls a little short of `min_chunk_size`, which
+ // costs less than splitting the `let` bindings apart.
assert_eq!(chunk_texts.len(), 3);
+ assert_eq!(chunk_texts[0], "{ pkgs, ... }:\nlet");
assert_eq!(
chunk_texts[1],
- " greeting = \"hello ${package-name}\";\nin"
+ " package-name = pkgs.hello;\n greeting = \"hello ${package-name}\";\nin"
);
assert!(chunk_texts[2].starts_with("{\n inherit package-name;"));
}
diff --git a/rust/py/src/ops.rs b/rust/py/src/ops.rs
index a03c930d..6b884b0e 100644
--- a/rust/py/src/ops.rs
+++ b/rust/py/src/ops.rs
@@ -197,7 +197,9 @@ impl PyRecursiveSplitter {
/// text: The text to split — a `str`, or a `CodeSource` whose cached
/// parse is reused (and populated for later consumers).
/// chunk_size: Target chunk size in bytes.
- /// min_chunk_size: Minimum chunk size in bytes. Defaults to chunk_size / 2.
+ /// min_chunk_size: Minimum chunk size in bytes. It is a soft floor: a
+ /// chunk may be smaller where that avoids a worse split point.
+ /// Defaults to chunk_size / 2.
/// chunk_overlap: Overlap between consecutive chunks in bytes.
/// language: Language name or file extension for syntax-aware splitting.
/// Only valid when `text` is a `str` — a `CodeSource` carries its own.
diff --git a/rust/sdk/cocoindex/src/ops/code.rs b/rust/sdk/cocoindex/src/ops/code.rs
index 9e2bfa06..7d2addda 100644
--- a/rust/sdk/cocoindex/src/ops/code.rs
+++ b/rust/sdk/cocoindex/src/ops/code.rs
@@ -319,7 +319,7 @@ impl CodeAst {
/// Split into syntax-aware chunks, reusing the parse.
///
/// - `chunk_size`: target size in bytes.
- /// - `min_chunk_size`: minimum size in bytes (defaults to `chunk_size / 2`).
+ /// - `min_chunk_size`: soft minimum size in bytes (defaults to `chunk_size / 2`).
/// - `chunk_overlap`: overlap between consecutive chunks in bytes.
pub fn split(
&self,
diff --git a/rust/sdk/cocoindex/src/ops/text.rs b/rust/sdk/cocoindex/src/ops/text.rs
index c3161b00..fb9cc02c 100644
--- a/rust/sdk/cocoindex/src/ops/text.rs
+++ b/rust/sdk/cocoindex/src/ops/text.rs
@@ -23,7 +23,8 @@ pub use cocoindex_ops_text::split::{CustomLanguageConfig, KeepSeparator, Separat
pub struct RecursiveChunkConfig {
/// Target chunk size in bytes.
pub chunk_size: usize,
- /// Minimum chunk size in bytes. Defaults to `chunk_size / 2`.
+ /// Minimum chunk size in bytes. It is a soft floor: a chunk may be smaller
+ /// where that avoids a worse split point. Defaults to `chunk_size / 2`.
pub min_chunk_size: Option<usize>,
/// Overlap between consecutive chunks in bytes.
pub chunk_overlap: Option<usize>,