Skip to content

Commit 23c311e

Browse files
fix(service-knowledge): the splitter matches each document line in linear time (#38383)
Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:知识库把文档切成段落时,每一行的标题识别和表格分隔行识别改为只随行长线性增长的读法,普通文档切出的段落前后一字不变。 - 属于知识库检索的切分加固,替维护知识库的管理员把切分耗时控制在随文档长度增长的范围内。 - 若有误,碰到的是知识库管理员:个别标题或表格的切分与以前不同;可直接撤回,已建的索引无需重建。 - 无 ## What changes The knowledge splitter matches each document line in time linear in its length. - The `markdown` strategy reads each line outside a code fence for an ATX heading through `matchHeading`, a scan from both ends of the line. - The table split decides whether its second row is a separator row through `isTableSeparatorRow`, one scan from the start of the row. - Both readings are unchanged for every line: a heading reads to the same level and text, and a row is a separator row in exactly the same cases. No passage changes, so `SPLIT_ALGORITHM_VERSION_BY_STRATEGY` is not bumped and no index needs rebuilding. - The two helpers are exported from `split/splitter.ts` for their tests only (marked `@internal`); the package's entry points export nothing new. Read first, by risk: 1. `packages/services/service-knowledge/src/split/splitter.ts`, `matchHeading`: the heading text keeps its first character, and a line of only `#` and spaces or tabs is a heading only when something follows the first space or tab. These two edge rules are the readings the old code gave, pinned by the capture table. 2. `packages/services/service-knowledge/src/split/splitter.ts`, `isTableSeparatorRow`. 3. `packages/services/service-knowledge/src/__tests__/split-linear-time.test.ts`, the two capture tables. ## Tests New file `src/__tests__/split-linear-time.test.ts`, 18 tests: - **Captures.** 53 heading lines and 27 table rows (closing `#` runs with and without spaces, trailing spaces and tabs, CJK headings, `#` with no text, seven `#`, indented lines, line-ending characters inside a line; separator rows with and without leading pipes, colons and spaces). Each table entry is the reading the splitter gave that line on `main` 9b783ee, captured before the edit; the new code gives every one of them unchanged. - **Linear time, line match.** Eight shapes of a 100,000-character heading line and six shapes of a 100,000-character table row: the best of 5 runs is under 50 ms (measured here: 0.2 ms to 2 ms). - **Linear time, whole split.** A markdown document carrying each long heading line, and a table carrying each long second row, split end to end: the best of 3 runs is under 1,000 ms. The end-to-end time at this length is about 30 ms on this box, nearly all of it the passage cutting the splitter already did, which is itself linear; that is why the end-to-end bound is wider than the line-match bound. - The existing split suite and its golden files pass byte-identical (no golden file is in the diff). Additional, not committed: a seeded differential run of 400,000 generated lines (an alphabet of `#`, spaces, tabs, letters, CJK, line-ending characters, `:`, `-`, `|`) read identically by the old and new line matching, 0 mismatches. Reverse verification, against the committed fix: each of the two line matchers was put back to its pre-change reading on disk in turn, through `scripts/ablation-replace.mjs`. Both legs: the 2 capture tests green (the tables are the pre-change readings), the 100,000-character tests red; then restored, blob equal to `HEAD` and `git diff HEAD` empty. ## Acceptance notes - No card: this is a no-card hardening order. - The end-to-end split of a 100,000-character line is asserted under 1,000 ms rather than 50 ms, for the reason given under Tests; the 50 ms bound is asserted on the line match itself. ## Verification Two minutes: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/split-linear-time.test.ts`. Expected: 1 file, 18 tests passed, in a few seconds. <details><summary>Local readings at 7382828</summary> - `pnpm --filter @objectstack/service-knowledge test`: Test Files 21 passed (21), Tests 725 passed (725). - `pnpm --filter @objectstack/service-knowledge typecheck`: exit 0; `check:test-typecheck: OK`, and `tsc -p tsconfig.test.json --listFiles` lists the new test file. - Derived gate list (`dispatch-gates.mjs --commands`, 63 commands): 61 exit 0; 2 exit 3, NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test` (reason: the shallow checkout cannot reach its pinned positive-control commit) and `check:dual-build-cjs-loads` (reason: it reads every package's built output, and only this package's dependency closure was built). Both run in CI. `--ran` reconciliation: 63 derived, 61 run, 2 NOT-MEASURED, 0 UNRUN. - `check-platform-checklist.mjs --changed-from origin/main`: exit 0, no anchored file in the change set. </details> <!-- signed: repo:objectstack#8 · sunhaolin · session_017xRBcSSm1UGomShRsemA1N --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 61cde6d commit 23c311e

3 files changed

Lines changed: 269 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): the splitter matches each document line in time linear in its length
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The knowledge splitter reads every line of a document to find Markdown headings and table separator rows. It now does so in time linear in the line's length, so a document with a very long line splits as quickly as any other document of its size.
11+
12+
Every passage is unchanged: a heading reads to the same level and text, and a table row is a separator row in exactly the same cases as before. `SPLIT_ALGORITHM_VERSION_BY_STRATEGY` does not move, and no index needs rebuilding.
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The splitter reads each document line in time linear in its length: the
5+
* markdown strategy's heading match and the table split's separator-row test
6+
* finish quickly on a line of any length, whatever characters it repeats.
7+
*
8+
* The capture tables below are the readings the splitter gave these lines
9+
* before the line matching was rewritten; they pin that every ordinary
10+
* heading and separator row still reads exactly the same, so no passage of an
11+
* existing index changes.
12+
*/
13+
14+
import { describe, expect, it } from 'vitest';
15+
import { isTableSeparatorRow, matchHeading } from '../split/splitter.js';
16+
import { resolveSplit, splitDocument, type ResolvedSplit } from '../split/index.js';
17+
18+
const HEADING_CAPTURES: Array<[line: string, reading: { level: number; text: string } | null]> = [
19+
['# a', { level: 1, text: 'a' }],
20+
['#a', null],
21+
['# ', null],
22+
['#', null],
23+
['# ', { level: 1, text: ' ' }],
24+
['#\t', null],
25+
['#\t\t', { level: 1, text: '\t' }],
26+
['# \t', { level: 1, text: '\t' }],
27+
['## Title', { level: 2, text: 'Title' }],
28+
['###### six', { level: 6, text: 'six' }],
29+
['####### seven', null],
30+
['# spaced', { level: 1, text: 'spaced' }],
31+
['#\ttab', { level: 1, text: 'tab' }],
32+
['# trailing ', { level: 1, text: 'trailing' }],
33+
['# trailing\t', { level: 1, text: 'trailing' }],
34+
['# closing #', { level: 1, text: 'closing' }],
35+
['# closing ## ', { level: 1, text: 'closing' }],
36+
['# closing\t##\t', { level: 1, text: 'closing' }],
37+
['# C#', { level: 1, text: 'C' }],
38+
['# a#b', { level: 1, text: 'a#b' }],
39+
['# a # b', { level: 1, text: 'a # b' }],
40+
['# #', { level: 1, text: '#' }],
41+
['# ##', { level: 1, text: '#' }],
42+
['# # #', { level: 1, text: '#' }],
43+
['# ## ', { level: 1, text: '#' }],
44+
['# #', { level: 1, text: '#' }],
45+
['# 第一章 总则', { level: 1, text: '第一章 总则' }],
46+
['## 第二条 定义 ##', { level: 2, text: '第二条 定义' }],
47+
['# 中文 标题 ', { level: 1, text: '中文 标题' }],
48+
['### 1.2 小节 ###', { level: 3, text: '1.2 小节' }],
49+
['# a\r', null],
50+
['# a
b', null],
51+
['# 
', null],
52+
['# \r', null],
53+
[' # indented', null],
54+
['\t# x', null],
55+
['# nbsp', null],
56+
['# a b c', { level: 1, text: 'a b c' }],
57+
['# a # ', { level: 1, text: 'a' }],
58+
['# ###x', { level: 1, text: '###x' }],
59+
['# x###', { level: 1, text: 'x' }],
60+
['#\t#\t', { level: 1, text: '#' }],
61+
['## ', null],
62+
['## x ## y', { level: 2, text: 'x ## y' }],
63+
['text', null],
64+
['', null],
65+
['#hashtag', null],
66+
['# 🙂 emoji', { level: 1, text: '🙂 emoji' }],
67+
['# a ', { level: 1, text: 'a' }],
68+
['# ', { level: 1, text: ' ' }],
69+
['# a\t \t#\t \t', { level: 1, text: 'a' }],
70+
['#### ####', { level: 4, text: '#' }],
71+
['# -', { level: 1, text: '-' }],
72+
];
73+
74+
const SEPARATOR_CAPTURES: Array<[row: string, isSeparator: boolean]> = [
75+
['| --- | --- |\n', true],
76+
['|---|---|\n', true],
77+
['---\n', true],
78+
['--\n', false],
79+
[' | :--- | ---: |\n', true],
80+
[':---\n', true],
81+
['|:-:|\n', false],
82+
[' | ---\n', true],
83+
['\t|\t:---\n', true],
84+
['| -- |\n', false],
85+
['| : ---\n', false],
86+
['||---\n', false],
87+
['| a | b |\n', false],
88+
['', false],
89+
['|\n', false],
90+
[' \t ---', true],
91+
['|---', true],
92+
[':--', false],
93+
['::---', false],
94+
['| ---', true],
95+
[' ---', false],
96+
['-|-|-', false],
97+
['| : --- |\n', false],
98+
['|:---|\n', true],
99+
[' --- \n', true],
100+
['| ----------\n', true],
101+
['| ===\n', false],
102+
];
103+
104+
/** Lines of 100,000 characters, each a long run of one shape. */
105+
const LINE_LENGTH = 100_000;
106+
const pad = (prefix: string, unit: string, suffix: string): string =>
107+
prefix + unit.repeat(Math.ceil((LINE_LENGTH - prefix.length - suffix.length) / unit.length)) + suffix;
108+
109+
const LONG_HEADING_LINES: Array<[shape: string, line: string]> = [
110+
['spaces inside the text', pad('# a', ' ', 'x')],
111+
['tabs inside the text', pad('# a', '\t', 'x')],
112+
['spaces and tabs inside the text', pad('# a', ' \t', 'x')],
113+
['a run of hashes inside the text', pad('# a ', '#', ' x')],
114+
['spaces and hashes inside the text', pad('# a', ' #', 'x')],
115+
['spaces after the hashes', pad('#', ' ', 'x')],
116+
['spaces only', pad('#', ' ', '')],
117+
['a closing run', pad('# a ', '#', '')],
118+
];
119+
120+
const LONG_SEPARATOR_ROWS: Array<[shape: string, row: string]> = [
121+
['spaces before the pipe', pad('', ' ', '|x\n')],
122+
['tabs before the pipe', pad('', '\t', '|x\n')],
123+
['spaces and tabs before the pipe', pad('', ' \t', '| x\n')],
124+
['spaces after the pipe', pad('|', ' ', 'x\n')],
125+
['spaces before a colon', pad(' ', ' ', '| :x\n')],
126+
['a run of dashes', pad('| ', '-', '\n')],
127+
];
128+
129+
/** The best of several runs, so one slow scheduler tick does not decide. */
130+
function bestOf(runs: number, work: () => void): number {
131+
let best = Number.POSITIVE_INFINITY;
132+
for (let r = 0; r < runs; r++) {
133+
const started = performance.now();
134+
work();
135+
best = Math.min(best, performance.now() - started);
136+
}
137+
return best;
138+
}
139+
140+
/**
141+
* The line match alone: microseconds to a few milliseconds per line on a
142+
* developer machine, so this bound is generous.
143+
*/
144+
const LINE_MATCH_BOUND_MS = 50;
145+
/**
146+
* The whole split of a document of that length, passage cutting included
147+
* (itself linear in the text and tens of milliseconds at this length): the
148+
* bound only has to separate linear time from a stall.
149+
*/
150+
const SPLIT_BOUND_MS = 1_000;
151+
152+
function chunksOf(content: string, split: ResolvedSplit) {
153+
const out = splitDocument({ id: 'doc', content }, split);
154+
if (!out.ok) throw new Error(`unexpected split failure: ${out.reason}`);
155+
return out.chunks;
156+
}
157+
158+
describe('the splitter matches each document line in linear time', () => {
159+
it('an ordinary heading line reads to the same level and text as its capture', () => {
160+
for (const [line, reading] of HEADING_CAPTURES) {
161+
expect({ line, reading: matchHeading(line) }).toEqual({ line, reading });
162+
}
163+
});
164+
165+
it('an ordinary table row is a separator row exactly when its capture says so', () => {
166+
for (const [row, isSeparator] of SEPARATOR_CAPTURES) {
167+
expect({ row, isSeparator: isTableSeparatorRow(row) }).toEqual({ row, isSeparator });
168+
}
169+
});
170+
171+
it.each(LONG_HEADING_LINES)('a 100,000-character heading line (%s) is matched in linear time', (_shape, line) => {
172+
expect(line.length).toBeGreaterThanOrEqual(LINE_LENGTH);
173+
expect(bestOf(5, () => matchHeading(line))).toBeLessThan(LINE_MATCH_BOUND_MS);
174+
});
175+
176+
it.each(LONG_SEPARATOR_ROWS)('a 100,000-character table row (%s) is matched in linear time', (_shape, row) => {
177+
expect(row.length).toBeGreaterThanOrEqual(LINE_LENGTH);
178+
expect(bestOf(5, () => isTableSeparatorRow(row))).toBeLessThan(LINE_MATCH_BOUND_MS);
179+
});
180+
181+
it('a markdown document with a 100,000-character heading line splits in linear time', () => {
182+
const split = resolveSplit({ split: { strategy: 'markdown' } });
183+
for (const [, line] of LONG_HEADING_LINES) {
184+
const doc = `${line}\nThe body under the heading.\n`;
185+
expect(bestOf(3, () => chunksOf(doc, split))).toBeLessThan(SPLIT_BOUND_MS);
186+
}
187+
});
188+
189+
it('a table with a 100,000-character second row splits in linear time', () => {
190+
const split = resolveSplit({ split: { strategy: 'recursive' } });
191+
const body = '| c | d |\n'.repeat(200);
192+
for (const [, row] of LONG_SEPARATOR_ROWS) {
193+
const doc = `| a | b |\n${row}${body}`;
194+
expect(bestOf(3, () => chunksOf(doc, split))).toBeLessThan(SPLIT_BOUND_MS);
195+
}
196+
});
197+
});

‎packages/services/service-knowledge/src/split/splitter.ts‎

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ function stripNewline(line: string): string {
379379
function splitTable(text: string, b: Bounds): string[] {
380380
const rows = splitKeepingNewlines(text);
381381
let headerRows = 1;
382-
if (rows.length > 1 && /^[ \t]*\|?[ \t]*:?-{3,}/.test(rows[1])) headerRows = 2;
382+
if (rows.length > 1 && isTableSeparatorRow(rows[1])) headerRows = 2;
383383
const header = rows.slice(0, headerRows).join('');
384384
const body = rows.slice(headerRows);
385385
if (body.length === 0 || !fits(header, b)) return splitDown(text, b, 0);
@@ -406,6 +406,31 @@ function ensureNewline(s: string): string {
406406
return s.endsWith('\n') ? s : `${s}\n`;
407407
}
408408

409+
/**
410+
* Whether a table row is a separator row: optional spaces or tabs, an optional
411+
* `|` and more optional spaces or tabs, an optional `:`, then at least three
412+
* `-`. Read by one scan from the start, so a row of any length costs time
413+
* linear in its length.
414+
*
415+
* @internal exported for its tests only.
416+
*/
417+
export function isTableSeparatorRow(row: string): boolean {
418+
let at = skipSpacesAndTabs(row, 0);
419+
if (row[at] === '|') at = skipSpacesAndTabs(row, at + 1);
420+
if (row[at] === ':') at++;
421+
return row.startsWith('---', at);
422+
}
423+
424+
function isSpaceOrTab(c: string | undefined): boolean {
425+
return c === ' ' || c === '\t';
426+
}
427+
428+
function skipSpacesAndTabs(s: string, from: number): number {
429+
let at = from;
430+
while (isSpaceOrTab(s[at])) at++;
431+
return at;
432+
}
433+
409434
// ── Lines, sentences, clauses, characters ────────────────────────────
410435

411436
function splitLines(text: string): string[] {
@@ -502,8 +527,37 @@ function countLeadingSpace(cps: string[], from: number): number {
502527

503528
// ── markdown ─────────────────────────────────────────────────────────
504529

505-
const HEADING = /^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/;
506530
const FENCE = /^[ \t]*(```|~~~)/;
531+
/** A character that ends a line: a heading line holding one is no heading. */
532+
const LINE_END_CHAR = /[\n\r\u2028\u2029]/;
533+
534+
/**
535+
* An ATX heading line (without its line break), or `null`: one to six `#`,
536+
* at least one space or tab, then the text. The text drops a closing run of
537+
* `#` and the spaces and tabs around it, but always keeps its first
538+
* character; a line of only `#` and spaces or tabs is a heading only when
539+
* something follows the first space or tab. Read by scans from both ends, so a
540+
* line of any length costs time linear in its length.
541+
*
542+
* @internal exported for its tests only.
543+
*/
544+
export function matchHeading(line: string): { level: number; text: string } | null {
545+
let level = 0;
546+
while (line[level] === '#') level++;
547+
if (level < 1 || level > 6) return null;
548+
const start = skipSpacesAndTabs(line, level);
549+
if (start === level || LINE_END_CHAR.test(line)) return null;
550+
if (start === line.length) {
551+
// Spaces or tabs alone: the text is the last of them, and there is none
552+
// when there is only one.
553+
return start - level >= 2 ? { level, text: line[start - 1] } : null;
554+
}
555+
let end = line.length;
556+
while (end > start && isSpaceOrTab(line[end - 1])) end--;
557+
while (end > start && line[end - 1] === '#') end--;
558+
while (end > start && isSpaceOrTab(line[end - 1])) end--;
559+
return { level, text: line.slice(start, Math.max(end, start + 1)) };
560+
}
507561

508562
/**
509563
* The `markdown` strategy: one section per ATX heading outside a code fence;
@@ -532,15 +586,14 @@ export function splitMarkdown(
532586
for (const line of splitKeepingNewlines(text)) {
533587
const bare = stripNewline(line);
534588
if (FENCE.test(bare)) inFence = !inFence;
535-
const m = inFence ? null : HEADING.exec(bare);
536-
if (!m) {
589+
const heading = inFence ? null : matchHeading(bare);
590+
if (!heading) {
537591
body += line;
538592
continue;
539593
}
540594
flush();
541-
const level = m[1].length;
542-
while (stack.length > 0 && stack[stack.length - 1].level >= level) stack.pop();
543-
stack.push({ level, text: m[2] });
595+
while (stack.length > 0 && stack[stack.length - 1].level >= heading.level) stack.pop();
596+
stack.push(heading);
544597
}
545598
flush();
546599

0 commit comments

Comments
 (0)