Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/38351-markdown-fitting-section.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/service-knowledge': minor
'@objectstack/spec': minor
'@objectstack/platform-objects': minor
---

feat(service-knowledge): under the `markdown` split, a section that fits is one passage

Clause-②: no
Metadata-protocol: semantic
Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md

On `split.strategy: 'markdown'`, a section was cut as `recursive` cuts, and its pieces were merged only while the merged piece stayed shorter than `minChars` (default 200). A section that fit `maxChars` but held several paragraphs of 200 characters or more was therefore cut into several passages, so a search hit only part of an article.

Now a section whose text, together with the heading path it is given, fits the effective `maxChars` and the embedder's token budget is one passage, whatever `minChars` is (`minChars: 0` included). Only a section that does not fit is cut as before, with `minChars` merging its short pieces; such a section gives exactly the passages it gave before. The text before the first heading, and a heading's text before its first sub-heading, are sections and follow the same rule. `recursive` and `whole` are unchanged. The `@objectstack/spec` docblocks, the `minChars` description and the knowledge source form's help text now say this, and the Setup bundles in `@objectstack/platform-objects` carry the new help text (regenerated for en, re-translated for zh-CN, ja-JP and es-ES); no key, value or default changes.

Which passages change: on `markdown` sources only, the passages of sections that fit but were cut. Each such section becomes one passage, so a table and its note inside a fitting section are always one passage.

The `markdown` split algorithm version stays 2: this change rides the version move to 2 that the body-less heading fix already makes in this release train, so every `markdown` source rebuilds once for both, not twice.

What to do: nothing.
2 changes: 1 addition & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ source: {
```

- `recursive` (the default) cuts at blank lines, then line breaks, then sentence ends, then semicolons, then characters. It reads Chinese and English sentence ends — 「3.2 条」 and 「400.50 元」 stay whole — and never cuts inside a Markdown table or list item that fits.
- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it.
- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it. A section that fits in one passage (its text together with the heading path it is given, within the length below) is one passage; only a section that does not fit is cut as `recursive` cuts, and `minChars` (default 200) merges the short pieces of that cut.
- `whole` keeps each document as one passage.

A passage is at most `split.maxChars` characters — else the **Knowledge → Target chunk size** setting, else 800 — and, when the adapter reports its embedder's input limit, within 80% of that limit by the shared token estimate below. A `whole` document over that budget is **removed from the index and reported** (`failed` and `failures` on the reindex result, an `error` log on the event sync), never truncated; because the estimate runs high, a `whole` document can use about 60% of the model's limit. The full rules are in [the protocol's split section](/docs/protocol/knowledge#35-the-split).
Expand Down
9 changes: 6 additions & 3 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -564,15 +564,16 @@ them. The object source's `split` key chooses how:
split: {
strategy: 'recursive', // 'whole' | 'recursive' | 'markdown'
maxChars: 600, // optional: longest passage, in characters
minChars: 200, // optional: merge adjacent pieces shorter than this (default 200)
minChars: 200, // optional: merge adjacent pieces shorter than this (default 200);
// under 'markdown', only in a section that does not fit
}
```

| Strategy | How it cuts |
|----------|-------------|
| `whole` | One passage per document. |
| `recursive` (the default) | At blank lines, then line breaks, then sentence ends, then semicolons, then characters — each next level only for a piece still too long. A Markdown table or list item is one unit while it fits; a table that does not fit is cut between rows, each piece repeating the header row. Adjacent pieces are merged while the merged piece is shorter than `minChars`; a short title block leads the text after it. |
| `markdown` | One section per heading (a `#` inside a code fence is no heading), each cut as `recursive` cuts. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A heading with no text of its own joins the next passage. |
| `markdown` | One section per heading (a `#` inside a code fence is no heading); the text before the first heading, and a heading's text before its first sub-heading, are sections too. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A section that fits — its text together with the heading path it is given (the whole path, or the innermost heading when the whole path is too long), within the effective `maxChars` and the token budget — is **one passage, whatever `minChars` is**; only a section that does not fit is cut as `recursive` cuts, its pieces merged up to `minChars`. A heading with no text of its own is named by the path of the section after it when it is that section's ancestor, and is a passage of its own otherwise. |

**Sentence ends, for Chinese and English text.** `。?!` end a sentence
wherever they stand. `. ? !` end one only before whitespace or the end of the
Expand All @@ -588,7 +589,9 @@ embedder's `maxInputTokens`, every passage's token estimate (the shared
`estimateTokens` from `@objectstack/spec/shared`) also stays within **80%** of
that limit. A passage keeps both bounds, so the effective length is the
smaller one; with no limit known, only `maxChars` applies. A `minChars` above
the effective `maxChars` reads as `maxChars`. The splitter never overlaps
the effective `maxChars` reads as `maxChars`; under `markdown` it merges only
the pieces of a section that does not fit, so `minChars: 0` still leaves a
fitting section whole. The splitter never overlaps
passages.

**`whole` over the limit.** A `whole` document whose estimate is over the 80%
Expand Down
4 changes: 2 additions & 2 deletions content/docs/references/ai/knowledge-source.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data);
| :--- | :--- | :--- | :--- |
| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown |
| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it |
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars |
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars |


---
Expand Down Expand Up @@ -135,7 +135,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data);
| :--- | :--- | :--- | :--- |
| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown |
| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it |
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars |
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars |


---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3576,7 +3576,7 @@ export const enMetadataForms: NonNullable<TranslationData['metadataForms']> = {
},
"source.split.minChars": {
label: "Shortest passage",
helpText: "In characters. Needs a strategy. Adjacent pieces shorter than this are merged, up to this length (default 200). Recursive and Markdown only."
helpText: "In characters. Needs a strategy. Adjacent pieces shorter than this are merged, up to this length (default 200). Recursive and Markdown only; under Markdown a section that fits is one passage, so this merges only the pieces of a section that does not."
},
refresh: {
label: "Refresh",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3576,7 +3576,7 @@ export const esESMetadataForms: NonNullable<TranslationData['metadataForms']> =
},
"source.split.minChars": {
label: "Pasaje más corto",
helpText: "En caracteres. Requiere una estrategia. Las piezas adyacentes más cortas que esto se fusionan, hasta esta longitud (200 de forma predeterminada). Solo Recursiva y Markdown."
helpText: "En caracteres. Requiere una estrategia. Las piezas adyacentes más cortas que esto se fusionan, hasta esta longitud (200 de forma predeterminada). Solo Recursiva y Markdown; en Markdown una sección que cabe es un solo pasaje, así que solo se fusionan las piezas de una sección que no cabe."
},
refresh: {
label: "Actualización",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3576,7 +3576,7 @@ export const jaJPMetadataForms: NonNullable<TranslationData['metadataForms']> =
},
"source.split.minChars": {
label: "最短パッセージ",
helpText: "文字数。戦略が必要です。この長さより短い隣接する断片は、この長さまで結合されます(既定 200)。再帰と Markdown のみ。"
helpText: "文字数。戦略が必要です。この長さより短い隣接する断片は、この長さまで結合されます(既定 200)。再帰と Markdown のみ。Markdown では収まるセクションは 1 パッセージになるため、結合されるのは収まらないセクションの断片だけです。"
},
refresh: {
label: "更新",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3576,7 +3576,7 @@ export const zhCNMetadataForms: NonNullable<TranslationData['metadataForms']> =
},
"source.split.minChars": {
label: "最短段落",
helpText: "以字符计。需要选择策略。短于此长度的相邻片段会被合并,直至达到此长度(默认 200)。仅适用于递归和 Markdown。"
helpText: "以字符计。需要选择策略。短于此长度的相邻片段会被合并,直至达到此长度(默认 200)。仅适用于递归和 Markdown;在 Markdown 下,放得下的小节整节为一个段落,因此只合并放不下的小节切出的片段。"
},
refresh: {
label: "刷新",
Expand Down
131 changes: 131 additions & 0 deletions packages/services/service-knowledge/src/__tests__/split.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,137 @@ describe('splitter — markdown: headings with no body', () => {
});
});

describe('splitter — markdown: a section that fits is one passage', () => {
// A paragraph of exactly `n` characters, ending in a sentence mark, with a
// tag so the paragraphs of one text are told apart.
const para = (tag: string, n: number): string => {
const head = `${tag} `;
return `${head}${'word '.repeat(Math.ceil(n / 5)).slice(0, n - head.length - 1)}.`;
};
const three = [para('P1', 250), para('P2', 250), para('P3', 250)];
const sectionOf = (paras: string[]) => `## Article 1\n\n${paras.join('\n\n')}\n`;
const shape = (content: string, split: ResolvedSplit) =>
chunksOf(content, split).map((c) => ({ headingPath: c.headingPath, content: c.content }));

it('three paragraphs of 250 characters under one heading, at the default minChars: one passage, prefix first', () => {
const split = resolveSplit({ split: { strategy: 'markdown' } });
expect(split.minChars).toBe(DEFAULT_SPLIT_MIN_CHARS);
expect(shape(sectionOf(three), split)).toEqual([
{ headingPath: ['Article 1'], content: `Article 1\n\n${three.join('\n\n')}` },
]);
});

it('minChars: 0 is not an opt-out: the fitting section is still one passage', () => {
const split = resolveSplit({ split: { strategy: 'markdown', minChars: 0 } });
expect(shape(sectionOf(three), split)).toEqual([
{ headingPath: ['Article 1'], content: `Article 1\n\n${three.join('\n\n')}` },
]);
});

it('a section that does not fit is cut exactly as before, minChars merging its pieces', () => {
const four = [...three, para('P4', 250)];
const split = resolveSplit({ split: { strategy: 'markdown' } });
expect(shape(sectionOf(four), split)).toEqual(
four.map((p) => ({ headingPath: ['Article 1'], content: `Article 1\n\n${p}` })),
);
// Pieces under minChars still merge in a section that does not fit.
const short = [para('S1', 60), para('S2', 60), para('L1', 700)];
expect(shape(sectionOf(short), split)).toEqual([
{ headingPath: ['Article 1'], content: `Article 1\n\n${short[0]}\n\n${short[1]}` },
{ headingPath: ['Article 1'], content: `Article 1\n\n${short[2]}` },
]);
});

it('"fits" counts the heading-path prefix: exactly maxChars is one passage, one character more is cut', () => {
const split = resolveSplit({ split: { strategy: 'markdown' } });
const lead = 'Article 1\n\n';
const tail = (n: number) => para('P3', n);
const exact = [three[0], three[1], tail(DEFAULT_SPLIT_MAX_CHARS - lead.length - 2 * 250 - 4)];
expect(`${lead}${exact.join('\n\n')}`).toHaveLength(DEFAULT_SPLIT_MAX_CHARS);
expect(chunksOf(sectionOf(exact), split)).toHaveLength(1);
const over = [three[0], three[1], tail(DEFAULT_SPLIT_MAX_CHARS - lead.length - 2 * 250 - 3)];
expect(chunksOf(sectionOf(over), split).map((c) => c.content)).toEqual(over.map((p) => `${lead}${p}`));
});

it('the prefix is the one withPrefix selects: a path too long falls back to the innermost heading, and that passage fits', () => {
const long = 'Chapter with a long title '.repeat(18).trim();
const split = resolveSplit({ split: { strategy: 'markdown' } });
const text = `# ${long}\n\n## Article 9\n\n${three.join('\n\n')}\n`;
expect(shape(text, split)).toEqual([
{ headingPath: [long, 'Article 9'], content: `Article 9\n\n${three.join('\n\n')}` },
]);
});

it('a table and its note inside a fitting section are one passage', () => {
const table = [
'| City tier | Lodging per night | Meals per day |',
'| --- | --- | --- |',
'| Tier 1 | 600 | 120 |',
'| Tier 2 | 450 | 100 |',
'| Tier 3 | 350 | 80 |',
'| Tier 4 | 300 | 70 |',
'| Tier 5 | 250 | 60 |',
'| Overseas | 900 | 200 |',
].join('\n');
// Both over minChars, so before a fitting section was one passage they
// were two.
expect(table.length).toBeGreaterThan(DEFAULT_SPLIT_MIN_CHARS);
const note = para('Note: amounts are per person, tax included, and', 260);
const split = resolveSplit({ split: { strategy: 'markdown' } });
expect(shape(`## Lodging\n\n${table}\n\n${note}\n`, split)).toEqual([
{ headingPath: ['Lodging'], content: `Lodging\n\n${table}\n\n${note}` },
]);
});

it('the token budget counts: a section under maxChars but over the budget is still cut, each piece within it', () => {
const split = resolveSplit({ split: { strategy: 'markdown' }, maxInputTokens: 200 });
const whole = `Article 1\n\n${three.join('\n\n')}`;
expect(whole.length).toBeLessThanOrEqual(split.maxChars);
expect(estimateTokens(whole)).toBeGreaterThan(split.maxTokens!);
const chunks = chunksOf(sectionOf(three), split);
expect(chunks.length).toBeGreaterThan(1);
for (const c of chunks) {
expect(c.content.startsWith('Article 1\n\n')).toBe(true);
expect(estimateTokens(c.content)).toBeLessThanOrEqual(split.maxTokens!);
}
});

it('"fits" reads the passage as emitted: a body over the budget left after the prefix only by rounding is one passage', () => {
// estimateTokens rounds up per text, so the prefix and the body estimate
// one token more apart than together: body 10 + prefix 2 > budget 11,
// while the passage they make estimates 11.
const body = 'abcd abcd abcd abcd\n\nabcd abcd abcd abcd abcd';
const split = resolveSplit({ split: { strategy: 'markdown' }, maxInputTokens: 14 });
expect(split.maxTokens).toBe(11);
expect(estimateTokens('A\n\n') + estimateTokens(body)).toBeGreaterThan(split.maxTokens!);
expect(estimateTokens(`A\n\n${body}`)).toBe(split.maxTokens);
expect(shape(`# A\n\n${body}\n`, split)).toEqual([{ headingPath: ['A'], content: `A\n\n${body}` }]);
});

it('text before the first heading that fits is one passage with no path', () => {
const split = resolveSplit({ split: { strategy: 'markdown' } });
const chunks = chunksOf(`${three.join('\n\n')}\n\n## Article 1\n\nOne line.\n`, split);
expect(chunks.map((c) => ({ headingPath: c.headingPath, content: c.content }))).toEqual([
{ headingPath: undefined, content: three.join('\n\n') },
{ headingPath: ['Article 1'], content: 'Article 1\n\nOne line.' },
]);
});

it("a parent's own text before its first child is a section of its own, one passage when it fits", () => {
const split = resolveSplit({ split: { strategy: 'markdown' } });
const text = `# Chapter 1\n\n${three.join('\n\n')}\n\n## Article 1\n\nOne line.\n`;
expect(shape(text, split)).toEqual([
{ headingPath: ['Chapter 1'], content: `Chapter 1\n\n${three.join('\n\n')}` },
{ headingPath: ['Chapter 1', 'Article 1'], content: 'Chapter 1 > Article 1\n\nOne line.' },
]);
});

it('recursive is unchanged: the same paragraphs, at the default minChars, are three passages', () => {
const split = resolveSplit({ split: { strategy: 'recursive' } });
expect(chunksOf(three.join('\n\n'), split).map((c) => c.content)).toEqual(three);
});
});

describe('splitter — whole', () => {
it('one passage per document', () => {
const text = fixture('regulation-zh.txt');
Expand Down
Loading
Loading