Skip to content

knowledge.add reads headings and fences as CommonMark does - #171

Merged
zlareb1 merged 8 commits into
mainfrom
fix/knowledge-chunker-commonmark
Nov 1, 2026
Merged

zlareb1 merged 8 commits into
mainfrom
fix/knowledge-chunker-commonmark

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Related: #157

Changelog category (leave one):

  • Bug Fix

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

knowledge.add reads headings and fences as CommonMark does, so a fence that closes on a longer info string, an HTML block, a list item over --- or a code identifier in a heading no longer moves chunk boundaries or garbles section paths, and a heading line with a long run of blanks no longer takes seconds to read. A document's chunks change when it is next written or re-chunked.

Why

The heading splitter behind knowledge.add, upsert and bulk_add read Markdown with ad-hoc patterns. They closed a fence on any line starting with three backticks, stripped every <...>, _ and * from titles (Option<String>, max_rows, __init__, 2 * 3), took list items, HTML blocks and comment lines over --- as headings, missed setext headings in CRLF files, and backtracked on an ATX line with a long run of blanks: 40 KB of blanks took 25 s. These rules were found while building the document parser for the file-ingestion proposal; that parser now lives in the extractor service, so the splitter's fixes stand on their own here.

The splitter now follows CommonMark's line rules for what it reads: ATX and setext headings, fenced code (a fence closes only on a bare run of its own character at least as long), list items, thematic breaks and HTML blocks (each kind ends where CommonMark ends it). A title drops only inline HTML tags from a fixed list, code-span backticks and matched * emphasis; underscores are kept, since they are names far more often than emphasis. Markup is read in a title's first 500 characters, so the patterns stay bounded on hostile input, and the rest of the title is kept as written.

Scope and risk

Only the splitter in server/knowledge/domain/chunking.py changes behaviour; its tests and one sentence of docs/features/knowledge.md follow. The heading, fence and title helpers are rewritten (private, as before; __all__ is unchanged), and detect_sections reads lines through a small _Opaque state that knows when a fence or an HTML block is open. All toward CommonMark; a document changes on its next write or loom rechunk --apply only if it has one of these, and then its chunks change, not only their section paths: a fence that closes elsewhere or a line that is now or no longer a heading moves chunk boundaries, text, char_start and the embedding input.

Input Before Now
a ```python line inside an open ``` fence closes the fence is fence content (a fence closes only on a bare run of its character at least as long)
```js``` is inline opens a fence text (a backtick info string holds no backtick)
## `max_rows` maxrows max_rows
## Option<String> fields, Promise<T>, Into<S>, Map<a, b>, <your token>, <Badge text="beta" />, <wbr> tags stripped kept as text (only lowercase inline tags in a fixed list go: <img ...>, <br/>, <code>x</code>, <b>, ...)
## Using C# Using C Using C#
__init__, max_rows, a lone * (2 * 3) underscores and stars stripped kept
## _Note_, ## __Bold__ (underscore emphasis) Note, Bold _Note_, __Bold__ (underscores are kept: names far more often than emphasis)
<!-- note --> Install over --- a heading Install no heading (a line starting an HTML comment opens an HTML block)
--> over --- no heading (a line starting with - was refused) no heading
Next step --> over --- a heading titled Next step --> no heading: a heuristic, not CommonMark (which would make it a title), since a comment opened inside a paragraph is not tracked and a line ending in --> may close one
## a*b*c (stars inside a word) abc a*b*c (only matched emphasis is dropped)
## a<br/>b, ## a<img src=x>b (an inline tag between words) ab a b (a tag is replaced by a space)
``ab`` ` ab ab` (a code span closes on a backtick run of its own length)
## Don`t, ## **Note (an unmatched backtick or **) Dont, Note kept as written
# #, a bare # (an empty heading), also over --- a heading titled # no heading: an empty ATX line is markup and is never a setext title
## Closed ## in a CRLF file Closed ## Closed
a setext heading in a CRLF file not found found
an underline indented one to three spaces not an underline an underline (a tab is not)
**Warning**, *Note*, *args, --force, -1 is negative over --- or === not a heading (any line starting with - or * was refused) a heading (only a list item, a rule, a quote, an ATX line, or a line starting an HTML comment, ending one (-->), opening with a block-level tag or holding one tag alone is refused)
1. Overview, 2) Setup, + x over --- a heading no heading (any list item; *** and - were never one and still are not)
<p>Title</p>, <p align="center"><img ...></p>, <div></div> over --- Title, or no heading (every tag was stripped and an empty title refused) no heading: a line opening with a block-level tag starts an HTML block (CommonMark); a line of several inline tags is a paragraph whose title cleans to nothing
<https://example.com> over ---; ## See <https://x> no heading (every <...> stripped, so an empty title); See a heading https://example.com; See https://x (an autolink keeps its URL)
<pre>x</pre>, <!DOCTYPE html> over --- a heading x; no heading no heading (a raw-text block or a <!...> line starts an HTML block)
## Draft inside a multi-line <!-- ... -->, <pre>, or a <div> block before its blank line a heading text of the HTML block (each kind ends where CommonMark ends it: at its end marker, or a blank line for block tags and a line holding one tag alone; such a line does not interrupt a paragraph, and a line of several tags, such as a README's badge link, is a paragraph a heading below it interrupts)
# Setup (indented up to three spaces) text a heading Setup (four spaces is still not one)
Title over -- or = text text, as before: an underline of fewer than three characters is kept as text (CommonMark would take it; the docs say so)
# B right after <h2>A</h2> a heading B text: a one-line <hN> is a heading and opens a block-tag HTML block to the next blank line, as in CommonMark
a ``` line inside a ```` fence closes the fence is fence content (a fence closes only on a run at least as long)
a closing fence with trailing text (``` # end) closes the fence is fence content: the fence stays open, and later headings are inside it
a heading longer than 500 characters every * and tag stripped markup read in the first 500 characters, the rest kept as written
an ATX line with a 40 KB run of blanks 25 s under 1 ms
a 1 MB backtick line 3 ms 3 ms (the backtick info-string check runs after the match)

Compatibility, rollout and rollback

  • Wire, schema, settings: none.
  • Re-chunking: a document's chunks (boundaries, text, section paths and vectors) change as the table lists when it is next written through knowledge.add, upsert or bulk_add, re-indexed by knowledge.update_metadata with reindex=true, or re-chunked with loom rechunk --apply. Chunk-level dedup (knowledge.dedup_list with chunk clusters, upsert's duplicate_chunk_count) compares chunk content hashes, so two identical documents chunked on either side of this change stop pairing at chunk level until both are re-chunked; document-level dedup is unaffected. During a rolling deploy, builds N-1 and N chunk such a document differently, each consistently.
  • Operator steps: none; loom rechunk --apply brings existing documents to the new rules if wanted.
  • Rollback: a revert restores the old rules; documents written under this build keep their chunks until written or re-chunked again.

Tests

  • tests/unit/test_knowledge_chunking.py: the existing tests pass; new ones cover a fence that does not close on a longer or info-string line, a bold or emphasised line over a rule as a heading, a rule over a rule, underlines indented up to three spaces (not four or a tab), list items over a rule, HTML block lines over a rule (block tags, tag-only lines, comments, raw-text blocks, <!DOCTYPE>, a line ending -->), HTML blocks ending at their end marker so the next line can be a title, headings inside a multi-line comment, <pre>, <div> or declaration read as block text, block-tag blocks ending at a blank line, a tag-only line not interrupting a paragraph, a one-line <h2> still a heading whose block runs to the blank line, an autolink over --- a heading, a badge line of several tags interrupted by an ATX heading, a lone tag after a closed comment or a rule opening a block, a <YOUR_API_KEY> placeholder read as text, every title row of the table above (code spans, generics, placeholders, C#, underscores, a lone or inner *, inline tags, unmatched backticks and **, *Note*, *args, --force, -1 is negative over a rule), a backtick run with a backtick after it opening no fence, an ATX heading indented up to three spaces, an underline shorter than three kept as text, autolinks kept in titles, a bare # as an empty heading, a long heading kept whole with its markup read in a bounded head, a heading with a 40 KB run of blanks read whole, and hostile lines (a 1 MB backtick run, 200 KB of blanks, 600 KB of unclosed emphasis, an HTML line over 50,000 underlines, 40 self-closing tags, an unclosed raw-text block) chunked in bounded time.

  • The two timing rows of the table, reproduced with:

    import time
    from server.knowledge.domain.chunking import detect_sections
    for line in ("# a" + " " * 40_000 + "b ##", "`" * 1_000_000 + "a`"):
        t = time.perf_counter(); detect_sections(line + "\n\nx\n"); print(round(time.perf_counter() - t, 4))
  • tests/unit/test_loom_ingest.py, test_doc_links.py, test_public_copy.py: pass.

  • make format-check, make lint, the mypy gate: pass. pytest tests/unit -k "chunk or knowledge or rechunk or outline or ingest or document or markdown or heading": 1,085 passed at the first push. pytest tests/unit -p randomly at b4abcad: 24,207 passed (the commits after it add three title cases and the underline test and move an import, and test_knowledge_chunking.py passes at the head); test_rmt_version_unit.py::test_no_writer_builds_a_millisecond_version was deselected, as it fails on main too.

  • Integration, since knowledge.add chunks change: pytest tests/integration -k "knowledge or outline or document or chunk" against a server and ClickHouse built from this branch: 58 passed; 36 skipped (the knowledge-sharing tests that need a test end-user issuer, and others that need settings this server does not set).

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

🤖 Generated with Claude Code

zlareb1 and others added 8 commits November 1, 2026 14:22
The heading splitter closes a fence only on a bare run of its character at
least as long, refuses list items, rules, HTML blocks and comment lines as
setext titles, finds setext headings in CRLF files and under an underline
indented up to three spaces, and drops only inline tags, code backticks and
matched * emphasis from a title, reading markup in its first 500
characters. A heading line with a long run of blanks is read in linear time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
A line inside a multi-line comment, raw-text block, declaration or block-tag
block is text, never a heading: the block ends at its end marker, or a blank
line for block tags and tag-only lines, and a tag-only line does not
interrupt a paragraph. The fence and HTML state move into _Opaque, the
unused _atx_body goes, and __all__ is back to the public names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ed, and a one-line <hN> opens its block

CommonMark's condition 7 takes one open or closing tag on a line, so a
badge line of several tags is a paragraph a heading below interrupts. Only a
paragraph's line keeps a tag-only line from opening a block (not a closed
block, a rule or an empty ATX line). An ATX heading may be indented up to
three spaces, and a one-line <hN> opens a block to the next blank line. The
-->-line refusal is named a heuristic.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…ceholder is text

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
…what the splitter reads

A parametrised test pins each title the change cleans differently, and a
backtick run with a backtick after it opens no fence. The long-heading test
checks a literal title, _atx is named for what it strips, and the docs name
the headings and the lines that are never headings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 merged commit 3180119 into main Nov 1, 2026
22 checks passed
@zlareb1
zlareb1 deleted the fix/knowledge-chunker-commonmark branch November 1, 2026 15:27
@pufit pufit mentioned this pull request Nov 2, 2026
9 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant