Skip to content

Cache XML from url: references as text, not markup (#179, item 1) - #188

Merged
caufieldjh merged 4 commits into
mainfrom
caufieldjh/url-source-xml-parsing
Nov 30, 2026
Merged

caufieldjh merged 4 commits into
mainfrom
caufieldjh/url-source-xml-parsing

Conversation

@caufieldjh

@caufieldjh caufieldjh commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Addresses item 1 of #179. Item 2 (several fields per JSON API source) and the third ask in the comments are not in this PR.

Problem

URLSource flattened only HTML. An XML response, such as one CFR section from the eCFR versioner API (text/xml), was cached with its tags, so a quote crossing an inline tag failed:

Identification. Zinc oxide-eugenol is a device composed of zinc oxide-eugenol (crosses </I>): invalid, 95% "very close match"

Change

  • XML is recognised by a media type of xml or *+xml, or by a leading XML declaration. HTML is still checked first, so XHTML (also when served as text/xml) stays on the HTML path. SVG and drawio are left as they were. A Word or Excel media type (…openxmlformats…) contains xml but is not treated as XML.
  • JATS goes through XMLExtractor first, as the issue suggests, but only when the root is <article> or <pmc-articleset> (with or without a namespace prefix). Other XML that happens to have <body>/<p> (DITA, TEI) would otherwise lose its headings and lists.
  • Any other XML is flattened by the new xml_to_text (etl/extract/xml.py):
    • Tags and attributes are dropped. All text is kept, in document order.
    • An element inside running text is removed in place and adds no space. Running text means mixed content (<I> in <P>), nested formatting (<B> in that <I>), or a lone element in P/HEAD/TITLE/LI.
    • Any other element starts a new line. That includes several sibling elements with no text between them, even inside a <li> or <p>, so <name>Resin</name><class>2</class> gives two lines, not Resin2. A break never stops a quote matching, because matching normalizes whitespace; welding two words together would.
    • True breaks start a line wherever they appear: P, PARA, LI, TR, ROW, BR, SECTION, SEC, DIV/DIV1–DIV9, H1–H6. TITLE/HEAD inside a sentence stay inline (TEI). Names are matched on the lowercased local name.
    • It uses the shared untrusted-XML parser, so external entities, DTDs and the network are never read. The lxml half of _parse is split out as _parse_root and reused.
  • Malformed XML is stored as fetched, not partly recovered. Recovery can drop text with no warning: in <a>one</a><b>two</b>, "two" is lost.
  • content_type stays url.
  • URL_SOURCE_CACHE_VERSION goes from 2 to 3, so url: entries cached with raw XML are refreshed. This refetches every url: entry once (HTML and PDF too), as the version 2 bump did.

Behaviour note

A JATS article fetched through url: is now narrowed to its body text, as from other article sources. A quote of its abstract or title that matched the raw XML will fail; the docs point to the article's PMID:/DOI: for those. This was a deliberate choice over flattening JATS whole.

Tests

  • tests/test_url_xml_to_text.py (new) tests against the real eCFR response for 21 CFR 872.3275 (tests/fixtures/xml/, fetched 2026-11-30). It covers:
    • both quotes from the issue
    • media-type and sniffing rules: XHTML, SVG, Office, plain text
    • JATS, and non-JATS XML with <body>
    • compact records, entities, CDATA, namespaces, comments and processing instructions
    • XXE, and malformed input
  • test_url_source_cache_version.py: a version 2 entry is stale.
  • test_url_html_sanitize.py::test_xml_is_left_alone checked the old raw-XML behaviour that Support XML responses for url: references, and several fields per JSON API source #179 changes. It is rewritten as test_xml_is_flattened_not_sanitized_as_html.
  • These pass locally: the URL/XML tests, all package doctests (just doctest), just mypy and just format.
  • The full just test run had 8 failures in unrelated suites: ClinicalTrials cache, PMID network, HTML acceptance, validation counts, and Wikipedia. Which ones failed varied between runs, and they pass on rerun, which points to network or timing flakiness. They were not compared against main.

Docs

  • docs/how-to/validate-urls.md: new "XML responses" section, with an eCFR example.
  • docs/troubleshooting.md: the version 3 cache refresh.

🤖 Generated with Claude Code

A url: response that is XML was cached with its tags, so a quote crossing
an inline tag (eCFR's <I>) failed. Now JATS articles (root <article> or
<pmc-articleset>) are read by XMLExtractor, and any other XML is flattened
by the new xml_to_text: tags and attributes dropped, a block element
starting a line, an element inside running text adding nothing. Malformed
XML is stored as fetched, since recovery can silently drop text.

XML is recognised by an xml or +xml media type or an XML declaration;
XHTML stays on the HTML path and SVG is left alone. URL_SOURCE_CACHE_VERSION
goes to 3 so url: entries cached with raw XML are refreshed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 1m 25s —— View job


Review of PR #188: cache XML from url: as text

  • Gather context / diff
  • Review source changes (xml.py, url.py, reference_fetcher.py)
  • Review tests and docs
  • Post review

The change is well scoped and well documented. HTML is still checked before XML, the Office media type is excluded, only <article>/<pmc-articleset> roots go to the JATS extractor, and malformed XML is kept as fetched rather than recovered. The XXE test and the real eCFR fixture are both good. I found one real bug in the inline/block rule and a few smaller points.

Note: uv and the project dependencies (lxml, bs4) are not installed in this runner, so I could not run the tests. I worked through the cases below by hand against the code. Please confirm them with a quick local run.


🐛 Nested inline elements are split onto separate lines

xml_to_text (src/linkml_reference_validator/etl/extract/xml.py, the iterwalk loop) treats a child as inline only when its direct parent has text of its own. An inline element with no text of its own, inside running text, therefore turns its children into blocks:

xml_to_text(b"<P>a <I><B>bold italic</B></I> d</P>")
# expected: 'a bold italic d'
# actual:   'a\nbold italic\nd'

Here <I> is inline because P is mixed, so mixed gets False for <I>. <B> then fails mixed[-1], becomes a block, and breaks the line. Nested formatting is common: <b><i>…</i></b> in XHTML-like XML, and eCFR's <E T=".."> and <SU> inside emphasis. A quote across that span would fail in the way #179 was meant to fix.

A related case: a block element whose children are all elements, with no text between them, splits every child:

xml_to_text(b"<P><I>(a)</I><B>Identification.</B></P>")  # '(a)\nIdentification.'

Suggested fix: carry an "inline context" down the stack. A child is inline when its parent is mixed or its parent is itself inline, and probably also when its parent is a named text block (p, para, head, title, li). Records like <rec><name>…</name><class>…</class></rec> still work, because rec is neither mixed, inline, nor a named block. Please add a test for each of the two cases above.

Fix this →


⚠️ Smaller points

  1. title, item and head always start a line, even inside running text. In TEI, <title> is often inline (<p>See <title>Hamlet</title> act 1</p> gives See\nHamlet\nact 1). item is also generic enough to show up inline. The XML_BLOCK_ELEMENTS list is a reasonable trade-off for eCFR. Consider applying the always-break rule only to names that are really breaks (br, p, para, li, tr, row, div*), and letting title/head/item use the mixed-content rule. Otherwise, document this as a known limit.
  2. _root_element is imported privately across modules (url.py imports it from acquire). It is now used by two modules, so consider making it public or adding a small public helper.
  3. Namespace-prefixed JATS roots (b"jats:article") don't match JATS_ROOTS, because _root_element returns the prefixed name. They fall back to flattening the whole document, which is safe, so this is just something to know about.
  4. Title for XML responses. _extract_title only looks at <title>/<meta>, so an eCFR entry's title will be the URL. The first non-empty line of the flattened text (§ 872.3275 Dental cement.) would be a better fallback. This is optional and could be a follow-up.
  5. Only a UTF-8 BOM is skipped in _markup_format's sniffing. A UTF-16 XML body without an XML media type won't be sniffed as XML. That is rare, and it matches _looks_like_html.

✅ Security

  • Parsing goes through the shared untrusted_xml_parser with recover=False. External entities, DTD loading and the network stay off, and there is a test for this.
  • iterwalk keeps the walk iterative, so deeply nested input won't overflow the recursion limit.
  • Malformed input returns None, and the raw body is kept. This matches the existing behaviour for unparseable content.

✅ Performance

  • _has_direct_text checks the children of each element once, so the walk is linear overall. Input size is already capped by ContentAcquirer.
  • The cache version bump to 3 refetches every url: entry once. The PR description and troubleshooting.md both say so.

✅ Tests and docs

  • The tests cover media-type sniffing, XHTML, SVG, Office, JATS vs. non-JATS <body>, entities, CDATA, namespaces, comments/PIs, XXE and malformed input.
  • The doctests on _parse_root, _markup_format, _is_named_block and xml_to_text are useful documentation.
  • The only gap is the nested-inline case above.
  • The new "XML responses" section and the note about JATS being narrowed to its body are clear.

Summary: I'd merge once the nested-inline bug is fixed and has tests. The other points are optional.

An element was inline only when its direct parent held text, so
<P>a <I><B>x</B></I> d</P> split into three lines. Inline context now
passes down: a child is inline when its parent holds text, is itself
inline, or is a text block (p, para, head, title, li). Only true breaks
(p, para, li, tr, row, br, section, sec, div*, h1-h6) break inside running
text, so TEI's inline <title> stays in its sentence. A JATS root is
matched on its local name, so <j:article> goes to XMLExtractor, and
acquire's root_element is public now that url.py uses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@caufieldjh

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed in 70a9a2b.

Nested inline elements (bug): fixed as you suggested. Inline context now passes down the tree. A child is inline when its parent has text of its own, is itself inline, or is a text block (p, para, head, title, li). Records still split. New tests cover:

  • <P>a <I><B>bold italic</B></I> d</P> → a bold italic d, and a deeper <I><B><SU> case
  • <P><I>(a)</I> <B>Identification.</B></P> → one line (with no space between the tags it gives (a)Identification., as written)
  • <results><rec><name>…</name><class>…</class></rec></results> still gives two lines

1. title/head/item: taken. Only true breaks always break now: p, para, li, tr, row, br, section, sec, div*, h1–h6. title, head and item follow the running-text rule, so <p>See <title>Hamlet</title> act 1</p> stays on one line. The test is parametrised over all three.

2. Private import: acquire._root_element is now the public root_element.

3. Prefixed JATS roots: fixed. The root is matched on its local name, so <j:article> goes to XMLExtractor, which already reads prefixed JATS correctly. A test covers it.

4. Title for XML responses: left for a follow-up. Today, title == url means no title was found, and the downstream eCFR case wants a title from the section heading. That fits better with the configurable-source ask in #179's comments.

5. UTF-16 sniffing: left as is. It is rare, and consistent with _looks_like_html.

Locally after the change: URL/XML/acquire tests 224 passed, just doctest 344 passed, just mypy and just format clean.

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 1m 5s —— View job


Re-review of PR #188 after 70a9a2b (nested inline / prefixed JATS)

  • Gather context: diff of the new commit against the previous review
  • Check the inline-context fix in xml_to_text
  • Check the break/text-block split, _is_jats and the root_element rename
  • Check the new tests and docs
  • Post review

Note: uv and lxml aren't installed in this runner, so I couldn't run the tests. Everything below comes from reading the code and working through cases by hand.

The main bug from my last review is fixed. Three of the smaller points are also dealt with: the inline title/head/item, the private _root_element import, and prefixed JATS roots. I'd merge this. What's left is small.


✅ The fix in xml_to_text (etl/extract/xml.py)

Each element now pushes a "running text" flag for its children (running_text). The flag is set when the element is inline itself, is named in XML_TEXT_BLOCK_ELEMENTS, or has text of its own. Working through the cases:

Input Result
<P>a <I><B>bold italic</B></I> d</P> a bold italic d ✅
<P><I>(a)</I><B>Identification.</B></P> (a)Identification., one line ✅
<p>See <title>Hamlet</title> act 1</p> See Hamlet act 1 ✅
<rec><name>Resin</name><class>2</class></rec> Resin / 2 ✅ (rec is not running text)
<doc>before<BR/>after</doc> breaks ✅ (_is_break wins over inline)
eCFR <DIV8><HEAD>…</HEAD><P>…</P></DIV8> HEAD is a block because DIV8 has no direct text ✅
eCFR <GPOTABLE><ROW><ENT>a</ENT><ENT>b</ENT></ROW> one cell per line ✅ (ROW is not a text block)

Splitting XML_BREAK_ELEMENTS from XML_TEXT_BLOCK_ELEMENTS is the right call. Narrowing _NUMBERED_BREAK to div\d*|h\d also stops a bare <h> from counting as a break.


⚠️ Remaining points (all minor)

  1. Inline context carries all the way down, so structured content inside a text block runs together. Everything under a <p>/<li>/<title> is inline unless it is a named break. Two examples:

    • <li><name>A</name><id>B</id></li> gives AB.
    • DITA allows <simpletable> inside <p>, so <p><simpletable><strow><stentry>a</stentry><stentry>b</stentry></strow></simpletable></p> gives ab.

    This doesn't affect eCFR, where tables are siblings of <P>, and it is the opposite trade-off to the bug just fixed. One cheap option: stop passing the flag down through an element that has no direct text and has more than one element child. That would keep <I><B> and still split cell-like siblings. Writing it down as a known limit in the xml_to_text docstring would also do.

  2. The PR description is out of date. It still says "P, HEAD, DIV/DIV1–DIV9, H1–H6, BR, LI, TR and a few others always start a line". HEAD (and title/item) no longer break inside running text. docs/how-to/validate-urls.md is already correct, so only the PR body needs editing.

  3. Test element-only-p-no-space (tests/test_url_xml_to_text.py) asserts (a)Identification.. That is right, since the source has no space, but it pins behaviour that is arguably surprising for something like <P><I>(a)</I><B>x</B></P>. Keep it if that's intended. A one-line comment ("no whitespace in source, so none added") would help the next reader.

  4. Prefixed JATS (url.py, _is_jats): this relies on BeautifulSoup's find_all("body")/find_all("p") also matching j:body/j:p. I believe BeautifulSoup does match on either name or prefix:name, and the new test_a_prefixed_jats_root_is_read_as_jats covers it. Please confirm that test passes locally, since I couldn't run it.

  5. Not addressed yet, and optional for this PR (both from the last review):

    • An XML entry's title still falls back to the URL. The first flattened line would be a better fallback.
    • Sniffing only skips a UTF-8 BOM, so a UTF-16 XML body without an XML media type isn't sniffed as XML.

✅ Security, performance and tests

  • Still parsed with recover=False through the shared untrusted parser. The walk is still iterative (iterwalk), and the extra _local_name per element keeps it linear.
  • root_element is now public. All call sites in acquire.py and url.py and its doctests were renamed. _is_jats has doctests for the plain, prefixed and non-JATS cases.
  • New tests cover nested and deeply nested inline elements, paragraphs that hold only elements, inline title/head/item, records that still split, and prefixed JATS. Together they cover both cases I asked for.

Summary: the blocking issue is fixed and tested, and I'd merge. Point 1 is worth a docstring note or a small follow-up. Point 2 is a quick edit to the PR description.

Running text passed down through any text block or inline element, so
<li><name>A</name><id>B</id></li> and a DITA <simpletable> in <p> read
as "AB". It now stops at an element that holds several elements and no
text of its own: those are fields or cells, and each gets a line. A break
costs a quote nothing, since matching normalizes whitespace; welding
costs the match. Formatting chains such as <I><B> stay inline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 57s —— View job


Re-review of PR #188 after d91a546 (sibling fields in running text)

  • Read the diff of d91a546 against the previous re-review
  • Check the new running_text rule in xml_to_text
  • Check the new tests and the docs change
  • Post review

Note: uv and lxml aren't installed in this runner, so I couldn't run the tests. I checked the cases below by reading the code.

This commit deals with point 1 from my last review, and it does it the way I suggested. I'd merge. The only thing left is one edit to the PR description. The rest is minor.


✅ The new rule (etl/extract/xml.py:687-690)

running_text.append(
    _has_direct_text(element)
    or ((inline or name in XML_TEXT_BLOCK_ELEMENTS) and len(element) <= 1)
)
Input Result
<P>a <I><B>bold italic</B></I> d</P> a bold italic d ✅ (I has one child)
<P>see <I><B>x</B></I></P> see x ✅
<li><name>A</name><id>B</id></li> A / B ✅
DITA <simpletable> inside <p> one cell per line ✅
<P><I>(a)</I> <B>Identification.</B> Zinc…</P> one line ✅ (P has text of its own, the tail Zinc…)
eCFR <P><I>(a) Identification.</I> Zinc oxide…</P> one line ✅. The real-fixture quotes are not affected
  • len(element) and comments: I first thought comments or PIs would count as children here. They don't, because etree.strip_tags(root, etree.Comment, etree.PI, etree.Entity) (line 662) runs before the walk. So <P><I>x</I></P> still has one child. ✅
  • Why breaking is safe: the reasoning in the docstring and comment holds up. A break only adds whitespace, which matching normalizes. Welding two words together breaks the match. test_a_quote_across_split_siblings_still_matches tests this through the real fetch path, which is a good choice.

⚠️ Remaining points (minor)

  1. The opposite case now adds a space between adjacent inline siblings. An inline element that holds two elements and no text of its own now splits them:

    • <P>see <I><B>Zinc</B><SU>1</SU></I> d</P> gives see / Zinc / 1 / d, so the text reads Zinc 1, where the source says Zinc1.
    • A quote written as Zinc1 (for example, a footnote marker copied from rendered text) would no longer match.

    This is the mirror of the problem just fixed, and the source gives no way to tell the two apart. I think erring toward a break is right. A doctest or a test that pins this case down would record the trade-off on purpose. Optional.

  2. The PR description is still out of date. It says "P, HEAD, … always start a line" and "Any other element starts a new line". Since 70a9a2b and this commit:

    • HEAD, TITLE and ITEM follow the running-text rule.
    • Several sibling elements with no text between them each get their own line, even inside <P>/<LI>.

    docs/how-to/validate-urls.md is already correct, so only the PR body needs updating.

  3. The docs wording is a little loose. validate-urls.md says "a single element alone in a <P>… counts as running text". The code means one child element, and that child can itself carry tail text. <P><I>a</I> b</P> takes the _has_direct_text path anyway, so the behaviour is right. Only the sentence could be tighter. Nit.

  4. Still deferred from earlier reviews, and fine as a follow-up:

    • An XML entry's title falls back to the URL.
    • Sniffing skips only a UTF-8 BOM, so UTF-16 XML without an XML media type is not detected.

✅ Security, performance and tests

  • Nothing changed on the security side: still recover=False through the shared untrusted parser, and still an iterative iterwalk.
  • len(element) costs O(1) per element, and _has_direct_text is still one pass over the children. The walk stays linear.
  • Tests:
    • The removed element-only-p / element-only-p-no-space cases were moved to the new test_sibling_elements_without_text_between_are_not_welded, which uses the new expectation ((a) / Identification.). This also settles point 3 from my last review.
    • single-child-chain checks that one child is still inline.
    • Together these cover both sides of the new rule.

Summary: the fix is correct, tested, and documented. I'd merge after updating the PR description. Point 1 is optional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 52s —— View job


Re-review of PR #188 after 35ca085 (adjacent inline siblings test)

  • Read the diff of 35ca085 against the previous re-review
  • Run the URL/XML tests and the doctests for the changed modules
  • Check the PR description against the code
  • Post review

This commit closes the last open points from my previous re-review. Nothing is blocking, and I'd merge.

This time I could run things. I installed the package with pip, since uv isn't on the runner:

  • tests/test_url_xml_to_text.py, tests/test_url_html_sanitize.py and tests/test_url_source_cache_version.py: 109 passed.
  • Doctests in etl/extract/xml.py, etl/sources/url.py and etl/acquire.py: 28 passed.
  • test_a_prefixed_jats_root_is_read_as_jats passes, so BeautifulSoup does match prefixed JATS tags. That settles point 4 from my earlier review.

✅ What changed

  • Trade-off test (tests/test_url_xml_to_text.py:231): test_adjacent_inline_siblings_with_no_text_between_are_split_on_purpose checks that <P>see <I><B>Zinc</B><SU>1</SU></I> d</P> gives see / Zinc / 1 / d. Its docstring explains why the code breaks the line here rather than joining the words. That was what I asked for, and the next person to change the rule will see it.
  • Docs wording (docs/how-to/validate-urls.md:121): it now says "the content of a <P>… holding just one child element", which matches len(element) <= 1. That fixes the nit.
  • PR description: it now covers the running-text rule, sibling fields getting their own lines, and the reduced list of break elements (TITLE/HEAD stay inline). It matches the code.

⚠️ Nits (optional)

  • docs/how-to/validate-urls.md:122: the edited line is longer than the lines around it, so the paragraph's wrapping is uneven. It makes no difference to the rendered page.
  • Two items are still deferred, as agreed, and fine for a follow-up:
    • An XML entry with no <title> still uses its URL as the title.
    • Sniffing only skips a UTF-8 BOM, so a UTF-16 XML body is not detected as XML unless the media type says XML.

✅ Security, performance and test coverage

Nothing changed here since my last review. XML is still parsed by the shared untrusted parser with recover=False, the walk is still an iterative iterwalk and stays linear, and the XXE and malformed-input tests are still in place. Both sides of the inline/break rule have tests.

Summary: ready to merge.

@caufieldjh

Copy link
Copy Markdown
Contributor Author

Re-review points, in 35ca085:

  1. Adjacent inline siblings: kept the break, as you suggested. test_adjacent_inline_siblings_with_no_text_between_are_split_on_purpose records the trade-off: <I><B>Zinc</B><SU>1</SU></I> reads Zinc 1.
  2. PR description: updated. The edit landed while your re-review was running.
  3. Docs wording: tightened to "holding just one child element".
  4. Title fallback and UTF-16 sniffing: left for follow-ups.

tests/test_url_xml_to_text.py: 55 passed. just format is clean. test_a_prefixed_jats_root_is_read_as_jats passes locally, so BeautifulSoup does match j:body/j:p.

@caufieldjh
caufieldjh merged commit 2dea92c into main Nov 30, 2026
5 checks passed
@caufieldjh
caufieldjh deleted the caufieldjh/url-source-xml-parsing branch November 30, 2026 22:17
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