Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(docs): a document with long unbroken passages can be indexed again

purple9ff019d4eef3
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 4787b64f..dec861c4 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -182,6 +182,18 @@ pub(crate) fn build_embed_args(model_path: &str, port: u16) -> Vec<String> {
"mean".into(),
"-ngl".into(),
"999".into(),
+ // One chunk is embedded in a single batch, and llama-server's default
+ // physical batch is 512 tokens. A document whose text has few sentence
+ // breaks produced longer chunks and Document Chat died on
+ // "input (658 tokens) is too large to process, increase the physical
+ // batch size" (ChrisMcSheehy, D#91). The chunker keeps chunks well
+ // under this now; the headroom means a near-miss is not a failed
+ // import. Cheap: these models are small and the batch only bounds a
+ // scratch buffer.
+ "-b".into(),
+ "2048".into(),
+ "-ub".into(),
+ "2048".into(),
]
}
@@ -1023,6 +1035,8 @@ mod tests {
"--embeddings",
"--pooling", "mean",
"-ngl", "999",
+ "-b", "2048",
+ "-ub", "2048",
]
);
// The whole point of P5: the embed server must NOT carry --ctx-size
@@ -1031,6 +1045,19 @@ mod tests {
assert!(!args.iter().any(|a| a == "--ctx-size"));
}
+ /// D#91: the default physical batch is 512 tokens and one chunk is one
+ /// batch, so a document with long unbroken passages failed to index with
+ /// "input (658 tokens) is too large to process".
+ #[test]
+ fn embed_args_raise_the_physical_batch_past_the_512_default() {
+ let args = build_embed_args("/models/nomic-embed.gguf", 8128);
+ for flag in ["-b", "-ub"] {
+ let at = args.iter().position(|a| a == flag).unwrap_or_else(|| panic!("{flag} missing"));
+ let value: u32 = args[at + 1].parse().expect("batch size is a number");
+ assert!(value > 512, "{flag} must clear the 512 default, got {value}");
+ }
+ }
+
#[test]
fn host_triple_is_platform_shaped() {
let t = host_target_triple();
diff --git a/src/api/__tests__/rag-chunk-ceiling.test.ts b/src/api/__tests__/rag-chunk-ceiling.test.ts
new file mode 100644
index 00000000..07c19638
--- /dev/null
+++ b/src/api/__tests__/rag-chunk-ceiling.test.ts
@@ -0,0 +1,92 @@
+/**
+ * No chunk may be bigger than the embedder can swallow (ChrisMcSheehy, D#91,
+ * 2026-07-27). Document Chat answered an upload with:
+ *
+ * Embedding failed (HTTP 500): input (658 tokens) is too large to process.
+ * increase the physical batch size (current batch size: 512)
+ *
+ * They read that as a setting they were supposed to find. It was ours: the
+ * splitter only broke text at sentence ends, so a PDF table, a bullet list,
+ * OCR output or a code block, none of which carry a full stop, stayed one
+ * "sentence" and went to the embedder whole. One oversized chunk fails the
+ * entire document, not just that passage.
+ *
+ * Run: npx vitest run src/api/__tests__/rag-chunk-ceiling.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { chunkText } from '../rag'
+
+/** The ceiling the implementation promises, in characters. */
+const MAX = 1200
+
+const longest = (chunks: string[]) => Math.max(0, ...chunks.map((c) => c.length))
+
+describe('chunkText — the ceiling holds for text that has no sentence breaks', () => {
+ it('splits a long passage with no full stop at all (the D#91 shape)', () => {
+ // A table dump: 400 rows, no punctuation the splitter could use.
+ const table = Array.from({ length: 400 }, (_, i) => `row${i} value${i} 12.5 ok`).join(' ')
+ const chunks = chunkText(table)
+ expect(chunks.length).toBeGreaterThan(1)
+ expect(longest(chunks)).toBeLessThanOrEqual(MAX)
+ })
+
+ it('splits a bullet list where every line ends without punctuation', () => {
+ const list = Array.from({ length: 300 }, (_, i) => `- item number ${i} about something`).join('\n')
+ expect(longest(chunkText(list))).toBeLessThanOrEqual(MAX)
+ })
+
+ it('splits a code block', () => {
+ const code = Array.from({ length: 200 }, (_, i) => `const value${i} = compute(${i}, options)`).join('\n')
+ expect(longest(chunkText(code))).toBeLessThanOrEqual(MAX)
+ })
+
+ it('splits text with no spaces at all (CJK, a long URL, minified output)', () => {
+ const wall = 'x'.repeat(9000)
+ const chunks = chunkText(wall)
+ expect(chunks.length).toBeGreaterThan(1)
+ expect(longest(chunks)).toBeLessThanOrEqual(MAX)
+ })
+
+ it('holds the ceiling even where the overlap prefix is added back', () => {
+ // Alternating short sentences and a huge unbroken run: the overlap is
+ // prepended to the next chunk, which is where a near-limit chunk could
+ // tip over.
+ const text = Array.from({ length: 30 }, (_, i) =>
+ `Sentence ${i} is short. ${'padding word '.repeat(120)}`,
+ ).join(' ')
+ expect(longest(chunkText(text))).toBeLessThanOrEqual(MAX)
+ })
+
+ it('a 20 page document of ordinary prose stays under the ceiling', () => {
+ const prose = 'This is a sentence about the subject at hand. '.repeat(1200)
+ expect(longest(chunkText(prose))).toBeLessThanOrEqual(MAX)
+ })
+})
+
+describe('chunkText — ordinary behaviour is unchanged', () => {
+ it('still chunks prose at sentence boundaries around the target size', () => {
+ const prose = 'Alpha beta gamma delta. Epsilon zeta eta theta. Iota kappa lambda mu. '.repeat(20)
+ const chunks = chunkText(prose)
+ expect(chunks.length).toBeGreaterThan(1)
+ // Target is 500 characters; sentence-aligned chunks land near it.
+ expect(longest(chunks)).toBeLessThan(700)
+ })
+
+ it('still drops scraps shorter than the minimum', () => {
+ expect(chunkText('tiny')).toEqual([])
+ })
+
+ it('keeps a short document as a single chunk', () => {
+ const one = 'A single paragraph that is comfortably over the twenty character minimum.'
+ expect(chunkText(one)).toEqual([one])
+ })
+
+ it('loses no words when it has to split hard', () => {
+ const words = Array.from({ length: 500 }, (_, i) => `w${i}`)
+ const chunks = chunkText(words.join(' '))
+ const seen = chunks.join(' ')
+ for (const w of [words[0], words[250], words[499]]) {
+ expect(seen).toContain(w)
+ }
+ })
+})
diff --git a/src/api/rag.ts b/src/api/rag.ts
index 0ac5b154..dd5dd06b 100644
--- a/src/api/rag.ts
+++ b/src/api/rag.ts
@@ -38,13 +38,46 @@ async function extractTextFromDOCX(file: File): Promise<string> {
return result.value
}
+/**
+ * Hard ceiling per chunk, in characters. The embedding server processes one
+ * chunk in a single batch, and llama-server's default physical batch is 512
+ * tokens, so an oversized chunk comes back as
+ * "input (658 tokens) is too large to process" and the whole document fails
+ * to index (ChrisMcSheehy, D#91, 2026-07-27). ~4 chars per token puts 1200
+ * characters near 300 tokens, comfortably inside 512 even for token-dense
+ * text like code or CJK.
+ */
+const MAX_CHUNK_CHARS = 1200
+
+/** Split a run of text that carries no sentence break into pieces that fit,
+ * preferring word boundaries. A PDF table, a bullet list, OCR output or a
+ * code block is one "sentence" to the splitter below, and before this it
+ * went to the embedder whole. */
+function splitOversized(text: string, limit: number): string[] {
+ if (text.length <= limit) return [text]
+ const out: string[] = []
+ let rest = text
+ while (rest.length > limit) {
+ const window = rest.slice(0, limit)
+ const cut = window.lastIndexOf(" ")
+ // No space in a whole window (CJK, a long URL, minified text) — cut hard.
+ const at = cut > limit * 0.5 ? cut : limit
+ out.push(rest.slice(0, at).trim())
+ rest = rest.slice(at).trim()
+ }
+ if (rest) out.push(rest)
+ return out.filter(Boolean)
+}
+
export function chunkText(
text: string,
chunkSize = 500,
overlap = 50
): string[] {
const chunks: string[] = []
- const sentences = text.split(/(?<=[.!?])\s+/)
+ const sentences = text
+ .split(/(?<=[.!?])\s+/)
+ .flatMap((s) => splitOversized(s, MAX_CHUNK_CHARS))
let current = ""
for (const sentence of sentences) {
@@ -58,7 +91,11 @@ export function chunkText(
}
}
if (current.trim()) chunks.push(current.trim())
- return chunks.filter((c) => c.length > 20)
+ // Final guarantee: the overlap prefix can push a chunk back over the ceiling,
+ // and one oversized chunk fails the whole document at the embedder.
+ return chunks
+ .flatMap((c) => splitOversized(c, MAX_CHUNK_CHARS))
+ .filter((c) => c.length > 20)
}
export async function generateEmbeddings(