Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(chunker): CJK-aware oversize measurement + close capOversizedChunks' fallback-path gaps (#3477)

paul-032018ec732e1b1d
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index 8145e98acc..f9cdb93ca3 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -20,6 +20,7 @@
import { chunkText as recursiveChunk } from './recursive.ts';
import { buildQualifiedName } from './qualified-names.ts';
+import { CJK_SLUG_CHARS, CJK_RANGES_REGEX } from '../cjk.ts';
// Embed the tree-sitter runtime + per-language grammars as files.
// `with { type: 'file' }` returns a path (string) at runtime. Bun bundles
@@ -716,7 +717,7 @@ export async function chunkCodeTextFull(
}
if (chunks.length === 0) {
- return { chunks: capOversizedChunks(fallbackChunks(source, filePath, language, opts), filePath, language, opts), edges: rawEdges };
+ return { chunks: fallbackChunks(source, filePath, language, opts), edges: rawEdges };
}
return { chunks: capOversizedChunks(mergeSmallSiblings(chunks, chunkTarget), filePath, language, opts), edges: rawEdges };
} catch {
@@ -842,10 +843,10 @@ function capOversizedChunks(
opts: CodeChunkOptions,
): CodeChunk[] {
const cap = opts.maxChunkTokens ?? DEFAULT_MAX_CHUNK_TOKENS;
- if (!chunks.some((c) => estimateTokens(c.text) > cap)) return chunks;
+ if (!chunks.some((c) => estimateEmbedTokens(c.text) > cap)) return chunks;
const out: CodeChunk[] = [];
for (const c of chunks) {
- if (estimateTokens(c.text) <= cap) {
+ if (estimateEmbedTokens(c.text) <= cap) {
out.push({ ...c, index: out.length });
continue;
}
@@ -880,17 +881,43 @@ function splitToTokenBudget(text: string, cap: number, opts: CodeChunkOptions):
chunkOverlap: opts.fallbackOverlapWords ?? 50,
}).map((p) => p.text);
for (const piece of pieces) {
- if (estimateTokens(piece) <= cap) {
+ if (estimateEmbedTokens(piece) <= cap) {
out.push(piece);
continue;
}
- // ~3.5 chars/token is a conservative cl100k estimate for source text.
- const charBudget = Math.max(1, Math.floor(cap * 3.5));
+ // Hard-split slice size. Pure-ASCII pieces: ~3.5 chars/token is a
+ // conservative cl100k estimate for source text. CJK-containing pieces:
+ // the weighted estimate can reach 1 token/char, so budget 1 char/token
+ // to keep every slice under cap by construction.
+ const charBudget = Math.max(1, Math.floor(cap * (CJK_RANGES_REGEX.test(piece) ? 1 : 3.5)));
for (let i = 0; i < piece.length; i += charBudget) out.push(piece.slice(i, i + charBudget));
}
return out;
}
+const CJK_CHARS_G = new RegExp(`[${CJK_SLUG_CHARS}]`, 'g');
+
+/**
+ * Embedding-safe token estimate for the oversize cap. estimateTokens
+ * (cl100k) matches embedding-family tokenizers closely on pure-ASCII source
+ * (measured identical on English prose and JSON vs Qwen3-Embedding), but
+ * UNDERCOUNTS mixed CJK+ASCII chunks — measured −31% on URL-dense Korean
+ * text vs the Qwen3 embedding tokenizer, which is exactly the shape that
+ * overflows strict embedding backends (#2826). For chunks containing CJK,
+ * take the max of cl100k and a per-char-class overestimate (CJK 1.0/char,
+ * other non-whitespace 0.75/char, whitespace 0.1/char). CJK-DOMINANT text
+ * is unaffected too: cl100k already counts it above the weighted form, so
+ * max() returns the same value as today. Only mixed-script chunks — the
+ * measured divergence class — estimate higher.
+ */
+export function estimateEmbedTokens(text: string): number {
+ const cjk = (text.match(CJK_CHARS_G) || []).length;
+ if (cjk === 0) return estimateTokens(text);
+ const ws = (text.match(/\s/g) || []).length;
+ const weighted = Math.ceil(cjk + (text.length - cjk - ws) * 0.75 + ws * 0.1);
+ return Math.max(estimateTokens(text), weighted);
+}
+
// ---------- Internals ----------
function fallbackChunks(
@@ -901,7 +928,7 @@ function fallbackChunks(
): CodeChunk[] {
const size = opts.fallbackChunkSizeWords ?? 300;
const overlap = opts.fallbackOverlapWords ?? 50;
- return recursiveChunk(source, { chunkSize: size, chunkOverlap: overlap }).map((chunk, index) =>
+ const chunks = recursiveChunk(source, { chunkSize: size, chunkOverlap: overlap }).map((chunk, index) =>
buildChunk({
body: chunk.text, filePath, language,
symbolName: null, symbolType: 'module',
@@ -909,6 +936,14 @@ function fallbackChunks(
index,
}),
);
+ // Route every fallback emission through the oversize net. Previously only
+ // the empty-AST branch wrapped its fallback in capOversizedChunks — the
+ // no-language, parse-timeout, no-semantic-nodes (every JSON/YAML fence:
+ // their node types aren't in TOP_LEVEL_TYPES) and parse-throw branches
+ // shipped word-counted chunks unchecked, and the word pipeline undercounts
+ // exactly the dense content (JSON, minified, CJK-mixed) that overflows
+ // embedders. Hoisting the cap here covers all five paths at once.
+ return capOversizedChunks(chunks, filePath, language, opts);
}
function buildChunk(input: {
diff --git a/test/chunkers/cap-oversized-cjk.test.ts b/test/chunkers/cap-oversized-cjk.test.ts
new file mode 100644
index 0000000000..c4cfa6ae3d
--- /dev/null
+++ b/test/chunkers/cap-oversized-cjk.test.ts
@@ -0,0 +1,97 @@
+/**
+ * capOversizedChunks — CJK-aware oversize measurement (follow-up to #1675,
+ * shape requested in #3475's closing review).
+ *
+ * cl100k (estimateTokens) matches embedding-family tokenizers on pure-ASCII
+ * source (measured identical on English prose and JSON vs Qwen3-Embedding),
+ * but undercounts MIXED CJK+ASCII chunks — measured −31% on URL-dense Korean
+ * text (#2826's failure shape). estimateEmbedTokens lifts only that class:
+ * ASCII-only input short-circuits to estimateTokens verbatim, and max()
+ * keeps CJK-dominant text at the cl100k count it gets today.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { chunkCodeText, estimateTokens, estimateEmbedTokens } from '../../src/core/chunkers/code.ts';
+
+/** URL-dense Korean rollup lines — the measured −31% divergence shape. */
+function urlDenseKoreanMix(lines: number): string {
+ return Array.from({ length: lines }, (_, i) =>
+ `- 항목 ${i}: 검증용 한국어 문장 · 링크: https://docs.example.com/pages/${String(i).padStart(32, '0')}?v=abcdef0123456789&ref=sample`,
+ ).join('\n');
+}
+
+function bigJsonWithKoreanValues(targetChars: number): string {
+ const entries: string[] = [];
+ let i = 0;
+ let len = 0;
+ while (len < targetChars) {
+ const row =
+ ` "item_${i}": { "name": "예시-${i}", "url": "https://example.com/api/v2/items/${i}?token=abc${i}def", "qty": ${i % 100}, "memo": "한국어 값이 섞인 예시 데이터" }`;
+ entries.push(row);
+ len += row.length;
+ i++;
+ }
+ return `{\n${entries.join(',\n')}\n}`;
+}
+
+describe('estimateEmbedTokens — measurement gate', () => {
+ test('ASCII-only input is bit-identical to estimateTokens (no CJK → short-circuit)', () => {
+ const en = 'function ordinary() { return compute(42) + helper(); } '.repeat(80);
+ const json = '{"item": {"name": "sample", "url": "https://example.com/a?b=c", "qty": 42}}, '.repeat(60);
+ expect(estimateEmbedTokens(en)).toBe(estimateTokens(en));
+ expect(estimateEmbedTokens(json)).toBe(estimateTokens(json));
+ });
+
+ test('never estimates below estimateTokens (max composition)', () => {
+ for (const s of [urlDenseKoreanMix(20), '이 문장은 순수 한국어 산문 예시입니다. '.repeat(40), 'plain ascii ', '']) {
+ expect(estimateEmbedTokens(s)).toBeGreaterThanOrEqual(estimateTokens(s));
+ }
+ });
+
+ test('mixed CJK+ASCII (the measured divergence class) estimates strictly higher', () => {
+ const mix = urlDenseKoreanMix(20);
+ // Real Qwen3-Embedding count for this shape measures ~45% ABOVE cl100k;
+ // the weighted form stays above the real count (+15% measured margin).
+ expect(estimateEmbedTokens(mix)).toBeGreaterThan(estimateTokens(mix));
+ });
+});
+
+describe('capOversizedChunks with the CJK-aware estimate', () => {
+ test('oversized json fence with Korean values re-splits under the default cap', async () => {
+ const src = bigJsonWithKoreanValues(14_000);
+ const chunks = await chunkCodeText(src, 'fence.json');
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks) {
+ // Small slack for the "[JSON] fence.json:…" header buildChunk re-adds
+ // after the body-level split.
+ expect(estimateEmbedTokens(c.text)).toBeLessThanOrEqual(2000 + 60);
+ }
+ // Content preserved — spot-check first / last entries survive.
+ const joined = chunks.map((c) => c.text).join('\n');
+ expect(joined).toContain('"item_0"');
+ expect(joined).toContain('한국어 값이 섞인 예시 데이터');
+ });
+
+ test('hard-split fallback makes progress on whitespace-less CJK-mixed input and stays under cap', async () => {
+ const blob = '한a민b국c'.repeat(3_000); // 18K chars, no whitespace
+ const chunks = await chunkCodeText(`{"blob": "${blob}"}`, 'fence.json');
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks) {
+ expect(estimateEmbedTokens(c.text)).toBeLessThanOrEqual(2000 + 60);
+ }
+ });
+
+ test('pure-ASCII chunks are measured by the identical estimator (cap decisions unchanged)', async () => {
+ const entries = Array.from({ length: 120 }, (_, i) =>
+ ` "item_${i}": { "name": "sample-${i}", "url": "https://example.com/api/v2/items/${i}?token=abc${i}def", "qty": ${i % 100} }`,
+ );
+ const src = `{\n${entries.join(',\n')}\n}`;
+ const chunks = await chunkCodeText(src, 'fence.json');
+ expect(chunks.length).toBeGreaterThan(0);
+ for (const c of chunks) {
+ // For ASCII-only chunks the two estimators are identical (pinned
+ // above), so cap decisions — and therefore boundaries — are unchanged.
+ expect(estimateEmbedTokens(c.text)).toBe(estimateTokens(c.text));
+ }
+ });
+});