Skip to content

Page sources: cite an HTML or XML page by id from a URL template (#179) - #191

Merged
caufieldjh merged 7 commits into
mainfrom
caufieldjh/url-template-page-sources
Dec 3, 2026
Merged

caufieldjh merged 7 commits into
mainfrom
caufieldjh/url-template-page-sources

Conversation

@caufieldjh

@caufieldjh caufieldjh commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Addresses the third ask in #179 (from the issue comments): a sources: entry that builds a URL from {id} and reads the response the way url: does. Items 1 and 2 landed in #188 and #189. With this, #179 can be closed, unless entry-point discovery (the alternative raised in the issue) is still wanted.

Change

A sources: entry may now set format: html or format: xml:

sources:
  CFR:
    url_template: "https://www.ecfr.gov/api/renderer/v1/content/enhanced/current/title-21?section={id}"
    format: html
    title: "21 CFR {id}"

CFR:872.3275 is then fetched from that URL. HTML is sanitized and XML flattened exactly as for url: pages, and the cached entry keeps the id CFR:872.3275.

  • format: json (the default, unchanged), html or xml, in any case. The declared format only settles a tie. If the response's content type or first bytes say what it is, the response wins. SVG and drawio are never read as XML.
  • Only {id} is filled in, and url_template must use it. The issue's sample used {part}, but eCFR doesn't need it: ?section=872.3275 redirects to the full path. A template with any other placeholder is skipped with a warning. The template must be http(s) with a fixed host, and the id is URL-encoded (keeping / and :).
  • title: an optional literal template with {id}. Without it, the page's <title> is used, or failing that the URL, as for url:.
  • JSON-only keys (fields, headers, store_raw_response, content_type) are refused on a page entry with a warning. A bad PageSourceConfig built in Python raises ValueError, as JSONAPISourceConfig does since Let a JSON API source quote several fields (#179, item 2) #189.
  • Page entries are cached with content type url and the page URL as full_text_url. They share the url_source_version stamp, so they are refreshed along with url: pages.

Commits

Split for review:

  1. URLSource.read_url split out of fetch, with a declared format as tie-break. url: output is unchanged.
  2. PageSourceConfig and the template checks (models.py).
  3. The cache stamp and staleness check extended to any entry with content type url.
  4. PageSource, loader wiring, exports, tests and fixture.
  5. Docs.
  6. Review fixes: id encoding, fixed host, any-case format, and more tests.
  7. Re-review fixes: dot-segment ids refused, no {id} in the fragment, format case normalised in the config too.

Behaviour changes (for release notes)

  1. A sources: entry with an unrecognised format (e.g. pdf) used to load quietly as a JSON source. Now it is skipped with a warning.
  2. A cached entry with content type url, no url_source_version stamp, and an id not starting url: is refetched once. This likely includes CFR: entries made by a downstream URLSource subclass.
  3. If a page source's URL answers with a PDF, the entry is cached as full_text_pdf without the stamp, as url: does. The docs say so.

Not in this PR

  • Entry-point discovery of source plugins.
  • Request headers for page sources.

Tests

  • tests/test_page_sources.py (new) uses a real eCFR renderer response for 21 CFR 872.3275 (tests/fixtures/page_sources/, fetched 2026-12-03). It covers:
    • loading from YAML, with JSON entries unchanged
    • malformed entries
    • the fetched URL, id, title, content type and full_text_url
    • a quote across <em>
    • the format tie-break
    • bot-challenge and failed downloads
    • id_patterns
    • precedence between config files
    • a fetcher round trip served from cache
    • staleness of an unstamped entry
  • Locally, the new and related url, JSON API, precedence and bot-challenge tests pass (235), as do just doctest (358), just mypy and just format. The full suite was not run locally: test_url_fragment_cache.py and test_wikipedia_source.py time out on and off on my machine connecting to their own 127.0.0.1 test servers. Leaving that to CI.
  • Live CLI check against ecfr.gov with CFR:872.3275:
    • A quote spanning <em> is valid.
    • "(2) Classification. Class II." is valid.
    • "Class III device" is invalid.
    • The cached entry has the title, stamp and URL.

Docs

docs/how-to/add-reference-source.md has a new "Page sources (HTML or XML)" section, and its config table lists format and title.

🤖 Generated with Claude Code

caufieldjh and others added 5 commits December 3, 2026 14:20
…break (#179)

read_url(url, reference_id, config, *, declared_format=None) holds the
download, PDF, bot-challenge, title and flatten steps, so a configured page
source can read a page under its own reference id. _markup_format uses the
declared format only when the response itself says nothing; never for SVG
or drawio. url: output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A sources: entry with format html or xml. url_template must use {id} and
nothing else; title is an optional template with the same rule. Problems
raise ValueError in __post_init__, as for JSONAPISourceConfig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#179)

Page sources cache under their own prefix (e.g. CFR:) with content type
url, so they share the url: stamp and are refreshed with url: pages. An
unstamped non-url: entry with content type url is refetched once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PageSource builds the URL from {id}, reads it with URLSource.read_url,
applies the title template and records the page URL as full_text_url.
The loader sends non-JSON formats to PageSourceConfig, refuses JSON-only
keys, and skips an unknown format or bad template with a warning (an
unknown format used to load as JSON). Tests use a real eCFR renderer page
for 21 CFR 872.3275.

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

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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


PR review: page sources (#179)

  • Read the diff (git diff origin/main...HEAD)
  • Review the loader, models, the URLSource.read_url split, PageSource and the cache stamp
  • Review the tests
  • Run tests and ruff. Not done: uv isn't installed in this runner, so I couldn't run anything. CI will have to cover it.

Summary

The design holds up. read_url only adds a reference_id and a declared_format that settles ties. The url: path comes out the same, because declared=None gives the old return None. Validating templates in __post_init__ matches what #189 did for JSONAPISourceConfig. Refusing JSON-only keys (so a headers: entry with credentials isn't silently dropped) is a good call. The tests use a real eCFR response and cover the important paths. I found no blocking issues; the points below are small.

Issues

1. Formatting: three blank lines before _parse_page_source_config (src/linkml_reference_validator/etl/sources/loader.py:273)
There are three blank lines after _parse_source_config where there should be two. ruff format --check will probably fail on this in CI, even though just format passed locally. Check whether this commit was formatted.
Fix this →

2. The identifier goes into the URL without URL-encoding (etl/sources/page.py:71)
url_template.format(id=identifier) inserts the raw id. So CFR:872.3275&foo=bar or CFR:872.3275#x changes the request. An id with a space produces a URL that requests will re-encode in its own way. JSONAPISource (json_api.py:181) does the same, so this is consistent, and the risk is low because the host comes from the template. Two follow-ups are worth considering:

  • urllib.parse.quote(identifier, safe=":/."), or a doc note that ids are inserted verbatim.
  • url_template: "{id}" passes template_problem. That turns the source into a general URL fetcher under a short prefix. It may be fine, but it's probably not intended.

3. Confusing error for format: JSON (models.py, loader.py:233)
The loader compares format to "json" exactly, so format: JSON or format: HTML goes to the page path. It then fails with "format 'JSON' is not one of json, html, xml", which looks like it contradicts itself. Lower-casing it (str(data.get("format", "json")).lower()) would avoid this.

4. Literal braces in title
A title such as "Section {id} {draft}" is rejected correctly. But someone who wants a literal { has to write {{. One sentence in the docs table entry for title would cover it.

Performance

DynamicPageSource.can_handle builds a new PageSource on every call, and that recompiles the id_patterns each time. JSONAPISource works the same way, and re's internal cache makes the cost small. You could cache one PageSource on the class (_instance = PageSource(source_config)) if registry lookups ever become a hot path.

Cache stamp change

Extending the stamp check to content_type == "url" in both places (reference_fetcher.py:737 and :2380) is consistent. In this repo only URLSource produces content type url, so the only built-in entries refetched once are url: ones, and those were already covered. Behaviour change 2 in the PR body (downstream URLSource subclasses get refetched once) is the right thing to put in the release notes.

Test coverage

The tests are good. Two gaps you might fill:

  • PDF response from a page source. Behaviour change 3 (cached as full_text_pdf with no stamp, and title taken from the template rather than the recovered PDF title) has no test. One mocked test would pin it down.
  • Bare id plus prefix with a space. can_handle accepts CFR 872.3275 ([:\s]). A round-trip test that the fetcher strips the prefix and caches under CFR:872.3275 would protect that path.

Security

There's no new attack surface beyond item 2. Downloads still go through ContentAcquirer, so the size cap, rate limit and User-Agent all apply. HTML is sanitised through the existing html_to_text, and the YAML is loaded with typ="safe".

Verdict

Ready to merge once item 1 is checked. Items 2–4 and the test gaps are optional improvements.

- PageSource.url_for URL-encodes the id (keeping / and :), so an id can't
  add a query parameter or fragment.
- url_template must be http(s) with a fixed host; {id} only in the path
  or query.
- format is read without regard to case, so format: JSON stays JSON.
- Docs: literal braces in title, the host rule, id encoding.
- Tests: the above, a PDF answer (full_text_pdf, template title, no url
  stamp), and 'CFR 872.3275' cached as CFR:872.3275.
- Drop an extra blank line in loader.py; ruff format the two new files.

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

Copy link
Copy Markdown
Contributor Author

Thanks. Addressed in 1d4057f:

  1. Blank line: fixed. (The repo's just format runs ruff check, not ruff format --check; I also ran ruff format on the two new files.)
  2. Encoding: url_for now URL-encodes the id, keeping / and :, so 872.3275&part=1 becomes 872.3275%26part%3D1. url_template must also start with http:// or https:// and keep {id} out of the host, so "{id}" and "https://{id}/…" are refused. JSONAPISource is unchanged; that could follow separately.
  3. format: JSON: the format is now lower-cased before dispatch.
  4. Literal braces: the docs now say to double them.

Tests added for each, plus the two gaps: a PDF answer (cached as full_text_pdf with the template title and no url stamp), and CFR 872.3275 cached as CFR:872.3275.

Not changed: caching a PageSource on the dynamic class. It matches JSONAPISource, and re caches the compiled patterns.

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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


PR review: follow-up commit 1d4057f (#191 review)

  • Read the new commit and the full diff against origin/main
  • Check the id encoding, the host rule, case handling and the new tests
  • Run tests and ruff. Not done: uv and ruff aren't installed in this runner, so I couldn't run anything. CI will have to cover it.

Summary

The new commit covers every point from the earlier review, and I found nothing that blocks merging.

  • Formatting: the extra blank line in loader.py is gone, and both new files have been through ruff format.
  • Id encoding: url_for now runs quote(identifier, safe="/:"). A doctest and a parametrised test show that &, # and spaces can no longer add a query parameter or a fragment.
  • Host rule: _page_url_problem refuses templates that are not http(s) or that put {id} in the host. That rules out the url_template: "{id}" general-fetcher case.
  • Format case: format: JSON now stays a JSON source.
  • Docs: they now cover {{/}}, the host rule and the id encoding.
  • Tests: two gaps are filled: a PDF response (full_text_pdf, title from the template, no stamp) and CFR 872.3275 cached as CFR:872.3275.

Minor points (optional)

  1. .. in a path id (page.py:84). Because / is kept, an id like ../../other in a path template such as https://x/{id} becomes https://x/../../other. urllib3 removes dot segments, so the request reaches other paths on the same host. The host can't change, so the risk is low. If you want to rule it out, refuse ids with a .. segment, or say in the docs that path ids are inserted with / intact.
  2. {id} in a fragment. _page_url_problem only checks the host. A template like https://x/page#{id} passes, although the docs say {id} may only appear in the path or the query. The fragment is never sent to the server, so every id would fetch the same page. You could reject a { after #, or leave it as is.
  3. Case handling is in the loader only. The YAML path lower-cases format, but PageSourceConfig(format="HTML") built in Python still raises. If you want the two to behave the same, normalise self.format = self.format.lower() in __post_init__ (when it is a string) and drop the step in the loader.
  4. Import order (models.py:6). import re comes after from pathlib import Path. ruff's default rules (no I) won't flag it, so this is cosmetic.

Performance and security

Nothing new on performance; the earlier can_handle note still applies and is minor. On security, encoding plus the fixed host closes the main gap from the last review. Downloads still go through ContentAcquirer, so the size cap, rate limit and User-Agent all apply.

Verdict

Ready to merge once CI passes. The points above are optional.

…se in config (#191 re-review)

- PageSource.fetch refuses an id with a '.' or '..' path segment, since
  '/' is kept and the request could reach another path on the host.
- url_template may not put {id} in the #fragment, which is never sent.
- PageSourceConfig lower-cases format itself, so code-built configs take
  any case as YAML does.
- Import order in models.py.

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

Copy link
Copy Markdown
Contributor Author

Re-review points addressed in d2e8d58:

  1. Dot segments: an id with a . or .. path segment is refused with a warning and not fetched. (872.3275 is unaffected.)
  2. Fragment: {id} after # in url_template is now refused.
  3. Format case: PageSourceConfig.__post_init__ lower-cases format too. The loader keeps its own lower-casing, because it decides JSON vs page before any config exists.
  4. Import order: fixed.

Each has a test, and the docs mention 1 and 2.

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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


PR review: follow-up commit d2e8d58 (#191 re-review)

  • Read the new commit (git show d2e8d58) against the earlier review points
  • Check the dot-segment guard, the fragment rule, format normalisation and the new tests
  • Run tests and ruff. Not done: uv and ruff aren't installed in this runner, so I couldn't run anything. CI will have to cover it.

Summary

All four points from the last review are handled, each with a test. I found nothing that blocks merging.

  • Dot segments (page.py:97): fetch checks the raw id before url_for encodes it, so .., ./x and 872/../x are never requested. The parametrised test also asserts the acquirer is not called, which is the property that matters. Encoded variants can't get round the check, because quote turns % into %25, so %2e%2e reaches the server as %252e%252e. 872.3275 still passes, since it is never a whole segment.
  • Fragment (models.py:1079): { after # is refused, with a doctest and a loader test.
  • Format case (models.py:1121): __post_init__ lower-cases a string format. A non-string value from YAML still fails the membership check with a ValueError. Keeping the lower-casing in the loader too makes sense, since it picks JSON or page before any config exists.
  • Import order: fixed.

Minor notes (no action needed)

  1. The dot check also applies to query templates. For ?section={id}, an id of .. can't climb anywhere, but it is still refused. No real CFR id looks like that, and one simple rule is easier to explain than a per-template one, so I'd leave it.
  2. Literal braces in a fragment. A template like https://x/page#{{anchor}} is now refused, because the check looks for any { after #. That's very unlikely in practice, so it isn't worth handling.
  3. url_for is public. The dot-segment guard lives in fetch, so code that calls PageSource.url_for("../x") directly still gets an unguarded URL. Today only fetch calls it in src/. If you want the guard to hold for every caller, move the check into url_for (have it raise or return None), or say in its docstring that it doesn't check ids.

Performance, security, tests

  • Performance: nothing new.
  • Security: with the id encoded, the host fixed, dot segments refused and fragments refused, the template can no longer be used to reach anything but the intended paths on the configured host. Downloads still go through ContentAcquirer, so the size cap, rate limit and User-Agent all apply.
  • Tests: coverage of the new rules is good.

Verdict

Ready to merge once CI passes.

@caufieldjh
caufieldjh merged commit 434b1fb into main Dec 3, 2026
7 checks passed
@caufieldjh
caufieldjh deleted the caufieldjh/url-template-page-sources branch December 3, 2026 20:13
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