Skip to content

fix: preserve rich headings in exports and chunk metadata - #933

Merged
ceberam merged 12 commits into
docling-project:mainfrom
its-amann:fix/serialize-heading-inline-content-5034
Nov 26, 2026
Merged

ceberam merged 12 commits into
docling-project:mainfrom
its-amann:fix/serialize-heading-inline-content-5034

Conversation

@its-amann

@its-amann its-amann commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

A title or section header with empty text can keep its content in a leading InlineGroup (for example a heading that mixes text and an equation). When that heading also owns body content, the serializers only recognised the group if it was the heading's sole child. The heading was then rendered empty, the inline group leaked out as a separate paragraph after it, and chunk and outline metadata carried an empty heading.

The leading inline group is now the heading's content, even when body children follow it. The remaining children are serialized as the section body, and the existing visited set prevents duplicate output. Only the first inline group is the heading text: a second inline group under the same heading is body content.

Ordinary text items and list items keep their existing rule, where the group only counts if it is the sole child. DocLang already treated the leading inline group as content and is unchanged.

This is the core companion for docling#5076, which implements the DOCX representation requested in docling#5034. The parser PR needs a release containing this fix and a raised docling-core dependency.

Before and after

For an empty level 1 section header with the inline group "Heading eq " + formula y=2, followed by a paragraph "Body.":

Output Before After
Markdown ## then Heading eq $y=2$ then Body. as separate paragraphs ## Heading eq $y=2$ then Body.
HTML <h2></h2> followed by a bare <span> the inline content sits inside <h2>
DocTags <section_header_level_1></section_header_level_1> followed by a sibling <inline> the <inline> sits inside the heading element
LaTeX \section{} followed by the content as a paragraph \section{Heading eq $y=2$}
Outline (Markdown, JSON, ITXT) empty heading or title the heading or title is Heading eq $y=2$
Hierarchical and hybrid chunkers headings == [''] and the inline group emitted as its own chunk the chunk is Body. with headings == ['Heading eq $y=2$']

Changes

  • Add get_inline_content_group() to docling_core/transforms/serializer/common.py. It returns the leading inline group that holds the content of an item with empty text: titles and section headers accept it with any number of children, other items only as the sole child.
  • Use the helper in the Markdown, HTML, DocTags and LaTeX text serializers, in the outline and in HierarchicalChunker, replacing the copies of the condition. This also fixes the LaTeX serializer, which had the same defect.
  • In the Markdown serializer, the inline content of a title or section header is collapsed onto a single line like the text of a plain heading. Newlines inside the runs no longer produce hard line breaks that split the heading, for example ## Line1 Line2 $y=2$ instead of ## Line1 followed by Line2 $y=2$.
  • In the outline, the JSON and ITXT title of a rich heading is rendered with the plain-text serializer, so it has no Markdown formatting or link syntax, like the title of a plain heading.
  • In HierarchicalChunker, the leading inline group is consumed as the heading text so it no longer becomes a body chunk. A sole FormulaItem or CodeItem child keeps working as before. The lookup lives in a small _get_heading_content() helper.
  • Add regression tests next to the existing tests of each serializer and chunker, and not in a new test file. The shared fixture build_rich_heading_doc() lives in tests/test_serialization.py and is reused by the DocTags and outline tests.

Notes for reviewers

  • A second inline group under a rich heading renders as body content after the heading. A test pins this.
  • Chunk headings and the Markdown outline format still serialize the heading content as Markdown (for example [text](url) for a hyperlink). Only the JSON and ITXT outline titles are plain text.
  • No schema or dependency changes.
  • The whitespace between inline runs is the responsibility of the backend since feat: make inline serializers concatenate runs faithfully #693, so the test fixtures give the run its own trailing space ("Heading eq ").

Validation

  • The full suite passes: 1752 passed, 12 skipped, 53 expected failures.
  • The new tests (Markdown, HTML, DocTags, LaTeX, outline, hierarchical and hybrid chunker) fail on current main and pass with this change. The "no body" variants were already correct on main and are not tested. The test for an inline group that follows a body item passes on main too, and guards against the fix over-matching.
  • ruff check and ruff format --check pass, and ty reports no new diagnostics in the changed modules.

@github-actions

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

Thanks @its-amann, all your commits are properly signed off. 🎉

@mergify

mergify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 All 2 merge protections satisfied — ready to merge.

Show 2 satisfied protections

🟢 Enforce conventional commit

Make sure that we follow https://www.conventionalcommits.org/en/v1.0.0/

  • title ~= ^(fix|feat|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\(.+\))?(!)?:

🟢 Require two reviewer for test updates

When test data is updated, we require two reviewers

  • #approved-reviews-by >= 2

@its-amann its-amann changed the title fix: serialize rich headings before their section content fix: preserve rich headings in exports and chunk metadata Oct 28, 2026
@github-actions github-actions Bot added ai:ci-safe AI triage found no CI-safety concern (advisory) bug Something isn't working chunking Document chunking doctags DocTags / IDocTags token format serialization Output serializers: Markdown, HTML, LaTeX, JSON, plain-text, outline labels Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

AI triage (advisory)

Checked commit 81d42e72b2. The analysis read the diff only. It did not run code from this pull request.

Warning

The AI analysis did not finish. Only the deterministic checks are shown.

CI safety: needs maintainer care before you approve CI.

  • uv.lock: changes locked dependencies

Possibly related pull requests

PR State Signal Assessment
#1069 open changes the same code not assessed
#1062 open changes the same code not assessed
#1075 open changes the same code not assessed
#830 open changes the same code not assessed
#574 open changes the same code not assessed

The ai:* labels are advisory. They do not approve CI and they do not add tests:full. A new push runs this check again.

@github-actions github-actions Bot added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 3, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI first review (advisory): no blocker found

This review covers the full diff at ae39a863d9. It read the code and did not run it.

The fix is consistent across Markdown, HTML, DocTags, the outline and the hierarchical chunker. The same defect stays in the LaTeX serializer, which the PR does not touch. Check whether LaTeX is meant to stay out of scope.

A maintainer makes the merge decision. This review never approves the pull request.

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.36842% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ng_core/transforms/chunker/hierarchical_chunker.py 90.90% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@its-amann

Copy link
Copy Markdown
Contributor Author

Hi @PeterStaar-IBM and @vagenas, could you take a look when you have a chance? docling-project/docling#5076 is waiting on a release with this fix before it can merge. Thanks!

@ceberam ceberam left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @its-amann for the PR, and for splitting the work into a parser PR (docling-project/docling#5076) and a core PR. The core problem is real and the approach is reasonable, but the PR needs a rebase and a few changes before it can be merged. Details below.

Blocking points

1. The branch is stale and the tests fail against current main

The PR is based on 5582916 (v2.105.0). main has since merged #693 (faithful inline whitespace, schema 1.11.0), which changed how inline runs are concatenated. The merge is textually clean, but behavior changes. I merged the PR into current main and ran the new tests: 24 failed, 51 passed. All failures are the same assertion, for example '# Heading eq$y=2$' != '# Heading eq $y=2$' (also Heading eq$y=2$ in the plain-text, outline-JSON and chunk-heading assertions, and in test_rich_heading_with_body_keeps_hybrid_chunk_context).

Please rebase onto main, fix the fixtures, and re-run the tests.

2. LaTeX serializer still has the same defect

docling_core/transforms/serializer/latex.py has the same has_inline_repr check with len(item.children) == 1. The AI reviewer already flagged this and I confirmed it. The PR claims to cover "all exports" of rich headings, but a document with an inline-group heading plus body content still exports in LaTeX with the heading in the wrong place. Please, fix it in this PR, since it is the same change and keeps the exporters consistent.

3. The detection rule is copy-pasted five times; extract it

The same condition now appears (with small variations) in Markdown, HTML and DocTags, plus a differently shaped version in the chunker and in the outline code:

item.text == "" and len(item.children) > 0 and (len(item.children) == 1 or isinstance(item, TitleItem | SectionHeaderItem)) and isinstance(item.children[0].resolve(doc), InlineGroup)

This is exactly the kind of rule that will drift (as LaTeX already did, and as the chunker and outline variants are already slightly different). Please factor it into one small helper that returns the leading InlineGroup | None for an item, for example in docling_core/transforms/serializer/common.py, with a Google-style docstring and type annotations, and use it from all serializers, the chunker and the outline. This will also resolve the LaTeX point naturally and removes the long, hard-to-read inline conditions in outline.py (a walrus inside isinstance(...) on a ~120 character line) and hierarchical_chunker.py.

Other points

  • Outline title source. In outline.py the JSON/ITXT branch builds MarkdownDocSerializer(doc=doc).serialize(item=child).text. That creates a new serializer with default params and ignores the **kwargs/visited of the caller, and the result is Markdown ($y=2$, [text](url) for hyperlinks) while ordinary headings use the plain item.text in the same field. It is acceptable for equations, but a heading with a hyperlink inside the inline group would yield Markdown link syntax in a "title" field and this is unnecessary for outlines. Please, add a test (or amend an existing one) in tests/test_serialization_outline.py showing that a rich heading with a link does not serialize into an outline with a Markdown standard link syntax. The chunker has the same Markdown-flavoured behavior, but this is fine and consistent with existing chunk headings.
  • Chunker asymmetry. The chunker accepts InlineGroup as first child with any number of children, but FormulaItem/CodeItem only when they are the sole child. That seems intentional, but a short comment saying why would help future maintainers (the existing comment only explains consumption of the children).
  • Test structure. test_rich_heading_keeps_its_inline_content is a single parametrized test with about 25 assertions across five output formats, using string splitting and regexes on HTML and DocTags. When it fails you cannot tell which format broke (this is what happened with the 24 failures above). I suggest one small test per output format, sharing a fixture-building helper. Several assertions also couple to exact whitespace, which is what made them brittle against #693. Asserting on structure (heading text contained in the heading line or tag, body after it, no duplicates) is more robust than asserting exact "Heading eq $y=2$" strings.
  • Overlapping chunker tests. test_rich_heading_chunk_context (HierarchicalChunker) and the new test in tests/test_hybrid_chunker.py cover similar ground. That is fine since they exercise different public classes, but the hybrid one only covers the "paragraph" variant.
  • Edge case worth a test. A heading whose children are [InlineGroup, InlineGroup, text]: the first becomes the heading and the second is body content. This is correct, but it is a visible consequence of the "leading group" rule and should be pinned by a test and mentioned in the description.
  • PR description. The validation section refers to "six DocLang image fixture failures" reproducing on main. On current main in my environment the full suite passes (1444 passed), so these were probably environment-specific. Consider removing that line to avoid confusion. The description is also quite long. A short problem/fix/scope summary would be easier to review.

What is needed to merge

  1. Rebase onto current main; fix the test fixtures ("Heading eq "); confirm that the new tests pass.
  2. Cover the LaTeX serializer.
  3. Extract the shared "leading inline group of a heading" rule into one helper and use it everywhere.
  4. Address or comment the remaining points.

Happy to re-review once the above is updated.

@ceberam
ceberam force-pushed the fix/serialize-heading-inline-content-5034 branch from ae39a86 to f06328e Compare November 25, 2026 10:13
@github-actions github-actions Bot removed ai:ci-safe AI triage found no CI-safety concern (advisory) ai:review-lgtm AI first review found no blocker or major issue (advisory) labels Nov 25, 2026
@ceberam

ceberam commented Nov 25, 2026

Copy link
Copy Markdown
Member

@its-amann Since there has been no movement on this PR since 2 weeks ago and other PRs depend on it, I've just added few commits to address the points of the last review. I have also updated the PR description accordingly. Please, let me know if you see any further issue.

ceberam
ceberam previously approved these changes Nov 25, 2026
cau-git
cau-git previously approved these changes Nov 26, 2026
its-amann and others added 11 commits November 26, 2026 16:09
Inline groups are now concatenated without separators, so the backend is
responsible for the whitespace between runs.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
LaTeX still rendered an empty heading command when a title or section
header owned a leading inline group together with body children. Treat the
leading inline group as the heading content, as the other serializers do.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
Markdown, HTML, DocTags, LaTeX, the outline and the hierarchical chunker each
carried their own copy of the check for an item whose content lives in a
leading inline group. Move it into get_inline_content_group so the rule
cannot drift between them.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
The JSON and ITXT outline titles of a heading whose content lives in an
inline group were Markdown, so formatting and hyperlinks leaked into the
title field. Use the plain-text serializer, matching headings that carry
their text directly.
The outline labels select outline entries. Forwarding them to the Markdown
text serializer filtered out the runs of a rich heading and left it empty.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
Place the rich heading regression tests next to the serializer and chunker
tests they belong to instead of a dedicated file. Split the checks per
output format, add a test pinning that only the leading inline group of a
rich heading is its title, and give each new test a short docstring.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
Drop the redundant has_inline_repr flag in the HTML and Markdown text
serializers and branch on child_group directly. Move the heading content
lookup in HierarchicalChunker into a small helper that returns the leading
inline group or a sole formula/code child. No behavior change.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
Collapse newlines in the inline content of titles and section headers
into a space, as is already done for plain headings, instead of
emitting GFM hard line breaks that split the heading line.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
Return only the document from build_rich_heading_doc and assert the exact
outline output for the JSON, ITXT and Markdown formats.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
@ceberam
ceberam dismissed stale reviews from cau-git and themself via 8adb9db November 26, 2026 15:40
@ceberam
ceberam force-pushed the fix/serialize-heading-inline-content-5034 branch from 391bf76 to 8adb9db Compare November 26, 2026 15:40
ceberam
ceberam previously approved these changes Nov 26, 2026
Signed-off-by: Cesar Berrospi Ramis <[email protected]>
@github-actions github-actions Bot added the ai:ci-needs-care AI triage: check CI-safety findings before you approve CI label Nov 26, 2026
@ceberam
ceberam merged commit cb4c09d into docling-project:main Nov 26, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai:ci-needs-care AI triage: check CI-safety findings before you approve CI bug Something isn't working chunking Document chunking doctags DocTags / IDocTags token format serialization Output serializers: Markdown, HTML, LaTeX, JSON, plain-text, outline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants