Skip to content

feat: honor the InlineGroup whitespace contract in the backends - #3891

Merged
vagenas merged 30 commits into
mainfrom
cau/serializer-whitespace-fixes
Nov 4, 2026
Merged

vagenas merged 30 commits into
mainfrom
cau/serializer-whitespace-fixes

Conversation

@cau-git

@cau-git cau-git commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Important

Paired with docling-project/docling-core#693, and it must merge after it. These backends emit inline runs that carry their own boundary whitespace, and only a docling-core that joins runs faithfully renders them correctly.

Update: merged main, new producers fixed

main (7b12671e) is merged into this branch in one merge commit (e493be97), pushed as a fast-forward. uv.lock pins docling-core#693 at c87ddd11, with doclang 0.9.

Producers that landed on main in the meantime and broke the contract are fixed here. Each would merge words as soon as the new core is released:

Groundtruth was regenerated rather than merged by hand, including the LaTeX .dclg and JATS goldens. The net test-data diff against main is 172 files. The LightOnOCR and dots tests moved to contract expectations. tests/test_backend_markdown.py was added to .github/max-lines-ignore.

Still to do before merge:

  • Regenerate the LibreOffice-dependent docx goldens (test_emf_docx.docx and others) on a machine with LibreOffice. They were not regenerated in this update, because these tests skip without LibreOffice. CI previously failed on textbox.docx.
  • After the docling-core release: drop the docling-core entry from [tool.uv.sources], raise the floor in the root, slim and meta-package pyproject.toml, and re-lock.

Summary

docling-core no longer joins InlineGroup runs with a hard " "; it concatenates them faithfully. Producers must therefore stop stripping run boundaries, because the serializer no longer adds a separator back.

Until now every backend relied on that join, which is why the committed groundtruth contained H 2 O, x 2 + y 3 and (strong) .. Once a backend strips the boundary, the real spacing can't be recovered downstream, so the fix has to happen where the runs are made.

today : ... Water is written as H 2 O using sub. ... x 2  + y 3  uses sup. ... CO 2 * .
fixed : ... Water is written as H2O using sub. ... x2 + y3 uses sup. ... CO2*.

today : ... we have a strong emphasis (strong) . Notice that ...
fixed : ... we have a strong emphasis (strong). Notice that ...

What changed

HTML. The whitespace was lost at extraction. " ".join(text.split()) collapses runs of whitespace, which is correct per the HTML spec, but it also strips the edges, which is the defect. Everything downstream therefore received runs that were already stripped. Extraction now collapses without trimming, and normalization happens once per block across the whole run list. Collapsing per node can't see that ["a ", " ", " b"] is a single boundary. simplify_text_elements merges neighbours with the same format without a separator, to_single_text_element concatenates as-is, and the emitters no longer strip individual runs.

Two consequences worth calling out:

  • A boundary never lands inside a ` delimiter. The serializers hoist whitespace out of emphasis but not out of code, so the space goes to whichever neighbour is plain. When both sides are code, the space becomes an unformatted run of its own, because `a b` `` is corrupt either way. For the same reason the emitters keep whitespace-only runs: normalization has already trimmed the block edges, so any whitespace run that survives is significant.
  • Edge whitespace blocks two shortcuts.
    • The single-character compactor skips candidates that carry edge whitespace; otherwise it would glue words back together in rendered span soup.
    • _is_rich_table_cell uses the normalized list too. Otherwise the whitespace between tags in <td>\n<p>x</p>\n</td> counts as two extra runs and the cell is misclassified.

MS Word.

  • _get_paragraph_elements grouped runs by format and used strip() both to decide whether to emit a run and as the emitted value. It now groups without stripping and trims only the paragraph edges.
  • _add_inline_equations_to_parent builds its own InlineGroup outside that path. It stripped the text after the last equation, which merged the formula into the next word ($A= \pi r^{2}$is the area formula). It now trims only the group edges.

Markdown. The backend keeps the raw Marko RawText fragments instead of stripping them. It emits a space for a soft line break, which is how a soft-wrapped paragraph renders and what the join used to supply. A hard break before a code span emits a "\n" run.

JATS. _strip_segments became _trim_segment_edges. It drops empty segments, merges compatible neighbours, and trims only the first and last segment.

ODF was already the reference producer. Its tail-text recovery came from #3850. This PR only removes the hyperlink-boundary strip that #3949 added.

Temporary dependency source: remove before release

tool.uv.sources points at the docling-core branch, so the paired change can be installed and CI resolves the same core the goldens were generated against. uv.lock pins the exact commit.

Release checklist:

  1. Merge and release docling-core (a 2.x minor, not 3.0).
  2. Drop the docling-core entry from [tool.uv.sources].
  3. Raise the docling-core floor to the release that carries the faithful join, and re-lock.

Version skew

Both packages are on 2.x and a major bump isn't affordable, so the dangerous combination can be installed and is worth understanding:

docling-core docling backends result
old (" " join) old (runs without spaces) correct, the status quo
new ("" join) new (runs carry their whitespace) correct, the goal
new old merged words
old new (this PR) double spaces, cosmetic

Hence the merge order: docling-core first, then this.

Testing

Against docling-core#693 at c87ddd11: the backend, LaTeX, Chandra, dots, LightOnOCR and contract subset gives 2004 passed, 15 skipped, 1 failed (test_backend_webp, a local ImportError), and 10 other DocLang-dependent files give 194 passed. The full suite, the PDF end-to-end tests and the --large-scale LaTeX corpus were not run.

tests/test_inline_whitespace_contract.py covers the cases that need a source document built on the fly:

  • DOCX runs that carry their own whitespace;
  • DOCX inline-equation boundaries;
  • HTML boundaries around adjacent code spans (with and without spaces, and mixed with formatting);
  • <pre> interior whitespace;
  • JATS runs that rejoin to the source text.

Known limitations (all already on main, unchanged)

  • A loose Markdown list item - intro\n\n more **x** y exports as - intromore **x** y. This comes from the md backend's nesting.
  • A docx checkbox paragraph with several runs repeats the checkbox label on every run.
  • An HTML <br> inside <p> or <td> becomes a space. Words don't merge, but the line break is lost.

Out of scope

  • <pre> with inline markup still produces one code item per fragment. This PR only stops it from merging words (<pre>See <a>x</a> first</pre>) and keeps the interior whitespace. The fragment structure is a separate issue that already exists.
  • The synthetic trailing " " that get_text adds for p/li/th/td. It is a fake block separator at the character-extraction layer: a different concern, with other consumers.
  • Real CSS whitespace processing: the white-space property, computed display per element, &nbsp; and bidi. Collapsing at extraction plus normalizing across runs covers the normal-flow content tested here.

Checklist:

  • Documentation has been updated, if necessary.
  • Examples have been added, if necessary.
  • Tests have been added, if necessary.

@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

Thanks @cau-git, all your commits are properly signed off. 🎉

@mergify

mergify Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 2 protections blocking · waiting on 👀 reviews

Protection Waiting on
🔴 Require two reviewer for test updates 👀 reviews
🟢 Enforce conventional commit —

🔴 Require two reviewer for test updates

Waiting for

  • #approved-reviews-by >= 2
This rule is failing.

When test data is updated, we require two reviewers

  • #approved-reviews-by >= 2

Show 1 satisfied protection

🟢 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)(?:\(.+\))?(!)?:

@codecov

codecov Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

@cau-git cau-git changed the title Cau/serializer whitespace fixes feat: honor the InlineGroup whitespace contract in the backends Jul 27, 2026
Inline runs carry their own significant whitespace and the docling-core
serializers now concatenate them faithfully, so producers must stop stripping run
boundaries. Previously each backend relied on the serializer's hard `" "` join,
which invented spaces (`H 2 O`, `x 2 + y 3`, `(strong) .`) and made the real
boundary unrecoverable.

HTML: collapse whitespace without trimming at the extraction origin
(`" ".join(s.split())` did both), then normalize once per block across the whole
run list -- per-node collapsing cannot see that `["a ", " ", " b"]` is one
boundary. `simplify_text_elements` merges same-format neighbours without a
separator, `to_single_text_element` concatenates verbatim, and the emitters no
longer strip individual runs. The single-char compactor skips candidates carrying
edge whitespace, or it would glue words in rendered span soup.
`_is_rich_table_cell` consumes the normalized list too: inter-tag whitespace in
`<td>\n<p>x</p>\n</td>` otherwise counts as two extra runs and misclassifies the
cell.

A boundary never lands inside a `` ` `` delimiter, because the serializers hoist
whitespace out of emphasis but not out of code. It goes on whichever neighbour is
plain; when both sides are code it becomes an unformatted run of its own, since
`` `a`` b` `` is corrupt either way. The emitters therefore keep whitespace-only
runs: normalization has already trimmed the block edges, so one that survives is
significant.

`<pre>` is preformatted, so it is taken verbatim and only its block edges are
trimmed. Stripping each fragment merged `<pre>See <a>x</a> first</pre>` into one
word once the join stopped compensating. The one-code-item-per-fragment shape of
`<pre>` with inline markup is a separate pre-existing issue and is left alone.

MS Word: group runs by format without stripping, then trim only the paragraph
edges. `_add_inline_equations_to_parent` builds its own InlineGroup outside that
path and stripped the fragment after the last equation, merging the formula into
the next word (`$A= \pi r^{2}$is the area formula`); it now trims group edges
only. JATS: `_strip_segments` becomes `_trim_segment_edges`. Markdown: keep the
raw Marko `RawText` fragments and emit a space for a soft line break, which is
how a soft-wrapped paragraph renders and which the join used to supply.

Goldens are re-baselined. `textbox.docx` is left untouched: its output varies
between identical runs, and its test is already `xfail(strict=False)`, so
regenerating it would only bless nondeterministic data.

Ships as a minor, not a major: `feat!:` would make python-semantic-release
(7.34.6) bump to 3.0, and a 3.0 is not affordable here. Needs a docling-core
floor bump to the release that carries the faithful join, once that number exists
-- an older docling-core with these backends produces double spaces (cosmetic),
but a newer docling-core under older backends merges words.
These backends emit inline runs that own their boundary whitespace, which only a
faithful-join docling-core renders correctly. Point `tool.uv.sources` at the
branch carrying that change so the lock-step pair is installable and CI resolves
the same core the goldens were baselined against.

`uv.lock` pins the exact commit (66040cb7). Temporary: drop the source and raise
the `docling-core` floor in `dependencies` once the release carrying the faithful
join exists on PyPI.

The lock diff is larger than the one entry because moving docling-core from a
registry wheel to a git checkout re-narrows environment markers across the graph.
The resolved package set is unchanged at 382, and no dependency is added or
removed.
I, Christoph Auer <[email protected]>, hereby add my Signed-off-by to this commit: ec6163c
I, Christoph Auer <[email protected]>, hereby add my Signed-off-by to this commit: 8a7b4fe
I, Christoph Auer <[email protected]>, hereby add my Signed-off-by to this commit: 31a4a73

Signed-off-by: Christoph Auer <[email protected]>
Rebase integration. Upstream #3949 (ODF anchor hyperlinks) stripped whitespace
at hyperlink boundaries in _normalize_odf_text_runs, correct under the old ''
join which re-inserted a separator, but a word-merge under the faithful join
(Watch[the talk]for context). The boundary space now stays in the plain run
and the serializer places it outside the link markup, per the contract.

- drop the hyperlink-boundary strip; update #3949's two tests to the
  contract-correct whitespace-bearing item texts (markdown was already right)
- regenerate ODF goldens (double-space / space-before-punct artifacts gone,
  upstream #3850 inter-span text renders tight)
- bump three upstream-added docx goldens to schema 1.11.0

Signed-off-by: Christoph Auer <[email protected]>
Re-resolve the docling-core git source to the rebased branch tip
(e4e745a, v2.91.0) after both PRs were rebased onto main; the lock
previously pinned the pre-rebase commit 66040cb7.

Signed-off-by: Christoph Auer <[email protected]>
@cau-git
cau-git force-pushed the cau/serializer-whitespace-fixes branch from 33c43dc to 93e3049 Compare August 18, 2026 13:26
@cau-git
cau-git marked this pull request as ready for review August 19, 2026 08:15
@el-belgounetos

Copy link
Copy Markdown

Hi,

Thanks for this work. One extra case that may be worth a test: a word split mid-word by a style change in DOCX, with no space at the run boundary.

Source Crédit Débit with a bold C and a bold D (runs C(bold) rédit D(bold) ébit). On docling 2.135.0 (before this PR) the Markdown is **C** rédit **D** ébit: _get_paragraph_elements strips the group edges, then MarkdownInlineSerializer joins with " ", so the original absence of a space is lost.

A control paragraph Plain + bo(bold) + ld middle and end (a real space before the bold run, none after) must give Plain **bo**ld middle and end.

The test descriptions mention DOCX runs owning their whitespace and unspaced HTML code spans, but I could not tell from the PR page whether an unspaced bold run inside a word is asserted for DOCX. Expected with the faithful join: **C**rédit **D**ébit and Plain **bo**ld middle and end. I have not run this against the PR branch. The generator script and fixture are attached (min_split_word.docx).

min_split_word.docx

@github-actions github-actions Bot added ai:ci-needs-care AI triage: check CI-safety findings before you approve CI and removed ai:ci-needs-care AI triage: check CI-safety findings before you approve CI labels Nov 4, 2026
Reduce comments and docstrings that describe what the code used to do,
or why an earlier version was wrong, to the rule the code follows now.
Remove the docling#3891 references from test docstrings. Rewrite the
AnnotatedTextList.normalize_whitespace docstring in Google style.
No behavior change.

Signed-off-by: Cesar Berrospi Ramis <[email protected]>
@github-actions github-actions Bot added ai:ci-needs-care AI triage: check CI-safety findings before you approve CI and removed ai:ci-needs-care AI triage: check CI-safety findings before you approve CI labels Nov 4, 2026
@github-actions github-actions Bot added ai:ci-needs-care AI triage: check CI-safety findings before you approve CI and removed ai:ci-needs-care AI triage: check CI-safety findings before you approve CI labels Nov 4, 2026
@github-actions github-actions Bot removed the ai:ci-needs-care AI triage: check CI-safety findings before you approve CI label Nov 4, 2026
@github-actions github-actions Bot added the ai:ci-needs-care AI triage: check CI-safety findings before you approve CI label Nov 4, 2026
@vagenas
vagenas merged commit ed7df11 into main Nov 4, 2026
54 checks passed
@vagenas
vagenas deleted the cau/serializer-whitespace-fixes branch November 4, 2026 14:11
ska2704 added a commit to ska2704/docling that referenced this pull request Nov 4, 2026
Regenerated the JATS reference data on top of the merged code to resolve
the .itxt conflicts with docling-project#3891.

Signed-off-by: SK Arin <[email protected]>
vagenas pushed a commit that referenced this pull request Nov 5, 2026
)

Runs carry their own whitespace since the inline group contract in #3891, so the test added in #5175 fails on main. Also exempt the test file from the line limit, which it exceeds on main.

Signed-off-by: Yashika Malhotra <[email protected]>
avanish-garg added a commit to avanish-garg/docling that referenced this pull request Nov 11, 2026
Since the InlineGroup whitespace contract (docling-project#3891) the serializers join the
runs of a group verbatim, so each run has to keep its own source whitespace.

Paragraph runs now go through `trim_run_edges`, like the equation fragments
already did. A whitespace-only run between two other runs is kept, and only
the outer edges of a paragraph that has several runs are trimmed; a paragraph
with a single run is left as it was. This applies to plain paragraphs and to
list items alike.

Signed-off-by: Avanish Garg <[email protected]>
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 asciidoc issue related to asciidoc backend docx issue related to docx backend enhancement New feature or request html issue related to html backend markdown issue related to markdown backend pptx issue related to pptx backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants