Skip to content

[CS146S Stanford] Studio web fetch: a bare & stays as written, and escaped code stays in its code block - #17200

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
mrityu75:fix/web-fetch-character-references
Nov 10, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
mrityu75:fix/web-fetch-character-references

Conversation

@mrityu75

@mrityu75 mrityu75 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Fixes #17199.

Problem

When the model fetches a page, Studio's HTML-to-Markdown converter:

  • appends a ; to a bare & followed by a letter, and decodes names that are references only with their ;. For example, AT&T. becomes AT&T.; and ?key=abc&format=json&lang=en becomes ?key=abc&format;=json⟨=en.
  • moves escaped characters out of a <pre> in a table cell. That is the layout of line-numbered code from Pygments' table formatter, Rouge and Chroma, so if a < b and c > 0: reads if a b and c 0: inside the fence. Inside a link in a <pre>, it moves the escaped characters into the link text and drops a &nbsp;.
  • can pass the rest of the page through as raw HTML:
    • on Python 3.13 and 3.14, after a decimal reference that has no ; and runs into a letter a–f (&#169Copyright);
    • on 3.11 and 3.12, after a &# with no digits when no ; follows it.

The issue lists live pages where this happens, such as Alpha Vantage's API samples, Google's Maps URLs docs and RFC 6749.

Root cause

The renderer ran HTMLParser with convert_charrefs=False and decoded references itself in handle_entityref and handle_charref:

  • HTMLParser reports &name whether or not a ; follows, and the handler always decoded &name;.
  • The decoded text went through _emit(), which picks an open link or table cell before an open <pre>, while the text around it went to the <pre>.
  • With convert_charrefs=False, HTMLParser's handling of a malformed &# depends on the Python version, and on each version some form of it ends the parse early.

Changes

  • HTMLParser(convert_charrefs=True), the stdlib default.
    • References decode inside their text run with html.unescape, as a browser decodes text, and the decoded run reaches handle_data, so it is routed with the text around it.
    • HTMLParser then never calls handle_entityref or handle_charref. They, their two replay branches and the html import are removed.
    • The _TokenLog docstring now names the three handlers its replay contract covers.
  • U+00A0 is not collapsed.
    • &nbsp; used to bypass the whitespace collapse in handle_data. Decoded inside the text run, it would be collapsed, and code indented with &nbsp; (W3Schools writes its examples that way) would lose its indentation.
    • Emitted text now collapses whitespace other than U+00A0 (_COLLAPSIBLE_RUN), as a browser does.
    • The header link-density tally still counts the text with U+00A0 collapsed, so a link header padded with &nbsp; is stripped as before.
  • Decimal references longer than 640 digits are shortened before parsing.
    • html.unescape raises ValueError once a decimal reference has more digits than int()'s limit. Python never sets that limit below 640, and leading zeros count toward it.
    • html_to_markdown drops the leading zeros of such a reference. If 8 or more digits remain, it writes &#65533, which is the U+FFFD that html.unescape gives past U+10FFFF.
    • On every version, main raised for such a reference ended by ; or a space, or inside an attribute. On 3.13 and 3.14 it also raised for one followed by a hex letter or cut off at the end of the page. With convert_charrefs=True alone, 3.11 and 3.12 would raise for those two as well.

Other behavior changes

  • Literal U+00A0: a literal U+00A0 in flowing text is now kept, as &nbsp; already was, instead of becoming a space.
  • Other whitespace references: &ensp;, &emsp;, &thinsp;, &#8239;, &#9;, &#10; and &#13; in flowing text now collapse like the characters they decode to, as those literal characters already did. Main emitted them as is, including a raw tab and carriage return.
  • U+00A0-only text between table elements: this is now dropped like other whitespace there.
    • Main put it in front of the next Markdown row (\xa0| c | d |).
    • It also drops Javadoc 8's method-summary tab separators, which sit inside a <caption>: All Methods\xa0Static Methods becomes All MethodsStatic Methods.
  • List markers: a list item whose first text is a reference after source indentation now gets the two spaces after its marker that literal text already gets (* "Quoted" title).
  • Legacy reference names in query parameters: a parameter that starts with a legacy reference name still decodes, as in a browser, but without the stray ;. &param=x was ¶m;=x and is now ¶m=x.

Testing

All runs were on macOS 26 (arm64).

  • New tests: 12 cases in test_web_fetch_extraction.py, which make 28 tests with the main_content variants.
    • Against origin/main's converter, 22 fail on Python 3.11.16 and 3.12.7, and 18 fail on 3.13.11 and 3.14.7, where CPython already parses a &# without digits as text.
    • The 6 that pass on main are guards: references still decode, &nbsp;-indented text keeps its indentation, and a &nbsp;-padded link header is still stripped.
    • All 28 pass on this branch on 3.11.16, 3.12.7, 3.13.11 and 3.14.7.
  • Converter test files (test_html_to_md_*.py and test_web_fetch_extraction.py): 1567 passed on main and 1595 (1567 + 28) on this branch, on each of 3.11.16, 3.12.7, 3.13.11 and 3.14.7.
  • Related backend tests: 47 backend test files around web fetch and the tool loop, on Python 3.12.7 with the backend CI dependencies.
    • This branch: 8232 passed, 9 failed, 3 skipped. origin/main: 8204 passed, 9 failed, 3 skipped. The 28 extra passes are the new tests.
    • The same 9 deferred workspace-deletion tests in test_sandbox_files_and_storage_roots.py fail on both on this machine.
    • The same 3 tests skip on both, because unsloth_zoo is not installed and a tokenizer file was not fetched.
  • Live pages: 155 saved responses (153 distinct URLs) from documentation, code-heavy, prose and data sites. They are 133 pages (7 of which give empty Markdown with both converters), 17 Cloudflare challenge pages, 4 "Access Denied" pages and 1 empty file. Converted with main_content=True:
    • 112 are identical, including all 29 non-pages and empty conversions.
    • 25 differ only in whitespace. 24 come from a literal U+00A0 that is now kept. The other is legislation.gov.uk, where &#xD; no longer emits a raw carriage return.
    • 18 differ in content. A script sorted the differing hunks on those pages:
      • 619 drop a stray ; or keep a bare & that main decoded.
      • 53 put characters back in their <pre>.
      • 12 keep a U+00A0 from &nbsp; inside a link in a <pre>, which main dropped (RFC section links, Cloudflare-protected email addresses in code samples).
      • 1 is the Javadoc caption change above.
    • Across these outputs, U+00A0 goes from 2,822 to 12,253 characters, 0.15% of the branch's 8.26M.
  • Robustness and speed:
    • 3,000 generated documents in both modes, on each of 3.11.16, 3.12.7, 3.13.11 and 3.14.7: 0 exceptions on this branch, 18 on main.
    • CPU time over the 155 responses (49 MB) on 3.13.11, as the sum of per-page minimums over 5 interleaved runs: 4.52 s on main and 4.44 s on this branch. The pre-pass costs 14 ms over the whole 49 MB.
  • Lint: python scripts/run_ruff_format.py (ruff-unsloth 0.6.9.post1), ruff check (0.17.3) and git diff --check pass.

Not covered

  • <caption> rendering: <caption> has no rendering rule. On both main and this branch, a caption runs into its table's header row.
  • _HTMLBodyLocator in tools.py: it also runs HTMLParser with convert_charrefs=False. It only finds where <body> starts, so the download can stop a window after it, and it produces no text, so it is left as is.

This contribution is part of Stanford's CS146S: The Modern Software Developer.

…n its code block

The HTML-to-Markdown converter ran HTMLParser with convert_charrefs=False
and decoded each reference itself. HTMLParser reports "&name" whether or
not a ";" follows, and the handler always decoded "&name;", so "AT&T."
became "AT&T.;" and "?key=abc&format=json&lang=en" became
"?key=abc&format;=json⟨=en". The decoded text also went through _emit(),
which picks an open link or table cell before an open <pre>, so the
escaped characters of a line-numbered code block (a <pre> in a table
cell) landed outside the code. And depending on the Python version, a
malformed "&#" (&#169Copyright, or a "&#" without digits) ended the parse
and left the rest of the page as raw HTML.

Let HTMLParser decode references inside their text run, and drop the
handlers and replay branches it no longer calls. Keep U+00A0 out of the
whitespace collapse of emitted text, as browsers do, so text indented
with &nbsp; keeps its indent, while the header link-density tally still
counts it collapsed. Shorten decimal references longer than 640 digits
before parsing, since html.unescape raises past int()'s digit limit.
@NilayYadav NilayYadav self-assigned this Nov 9, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T11:32:42.134840Z 7c6139f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 3ebd8cc297

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f4954306ff

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

)
if site_links is not None:
scored = site_links.clean(scored)
scored = _fold_kept_spaces(scored)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-clean folded spacer lines before ranking scopes

For two sibling <article> elements without a <main>, NBSP-only block spacers still inflate scope ranking. The added fold runs after _cleanup, so those lines are never cleaned up after becoming ASCII whitespace. A 240-character teaser followed by 400 <p>\xa0</p> spacers and <p>More information</p> scores 1,457 and displaces a 999-character real article; the parent selects the real article instead. Unlike the fixed contiguous-run case, this leaves hundreds of blank lines in len(scored). Re-clean the folded scoring view before ranking it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not changing this: it needs hundreds of empty spacer paragraphs, and the merge base already ranks the same page this way when the spacers are written as  .

# Collapse all whitespace (including newlines) per HTML rules.
text = _WHITESPACE_RUN.sub(" ", data)
# Collapse whitespace (including newlines) per HTML rules, which keep U+00A0 and other Unicode spaces.
text = _COLLAPSIBLE_RUN.sub(" ", data)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fold kept whitespace before the boilerplate length check

When a boilerplate notice is padded with literal U+00A0, preserving those characters can now push its raw line length past the 300-character check in _strip_boilerplate_lines before _line_is_boilerplate gets to normalize it. For example, a <main> containing <p>This website uses cookies followed by 17,000 NBSPs, .</p>, and a body paragraph previously returned just the body, but now retains the notice and padding. tools._render_page consequently truncates at its 16,000-character cap before reaching any body text. Apply the folded whitespace view to the boilerplate length check as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not changing this: 17,000 no-break spaces inside a cookie notice is not a real page, and the merge base already keeps that notice when the padding is  .

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 1e629f4843

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 84d415a57. 9 findings, fixed in bf15a2b, 1956506, 591d826, eb3f396, 57460d6, 3ebd8cc, f495430, 1e629f4; no open findings.

I reproduced a chat model fetching the Google Maps URLs docs with the web search tool on the merge base 3329d6d (Linux, T4, Qwen3-4B-Instruct-2507 Q4_K_M, Chromium 1400x1000):

  • Before: the tool result the model reads has https://www.google.com/maps/@?api=1↦_action=map&*parameters* and ?api=1&query;=lumen+field.
  • PR head: https://www.google.com/maps/@?api=1&map_action=map&*parameters* and ?api=1&query=lumen+field.

PR 17200 before/after

  • 26 live pages converted with both versions on Python 3.11, 3.12 and 3.13: 15 identical, 2 differ only in a kept no-break space, 10 differ in content and all of it is intended (Alpha Vantage &symbol;= 396 to 0, Google Maps ↦_action 13 to 0, RFC 6749 Section2 to Section 2, line-numbered MkDocs and Jekyll code keeps > in its fence). The Javadoc 8 String page is identical to the merge base.
  • Web fetch and HTML converter suites on 3.11, 3.12 and 3.13: 2029 passed on head; the new tests fail 28 cases on the merge base. The one failure (test_web_search_fallback::test_primary_eight_parallel_successes_all_use_provider) fails on both sides.
  • Converter CPU over those pages is within about 2% of the merge base, inside the noise of repeated base runs.

Conclusion: the bug is real and fixed on this branch, with no regression on the pages checked. Ready once CI on the current head is green.

@NilayYadav NilayYadav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for the PR! The goal of this PR is to make Studio's web fetch give the model the text a browser shows, so a bare & keeps its meaning and escaped characters stay inside their code block. As a summary, this PR lets HTMLParser decode character references inside each text run instead of in separate handlers, keeps no-break and other Unicode spaces when collapsing whitespace, and shortens very long decimal references so html.unescape cannot raise.

Reviewers Severity Finding
- - No open findings on the current head. The issues found during review (caption separators, &emsp; indentation, and no-break space padding changing which part of a page is kept) are fixed in the commits I pushed to this branch.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 7c6139f3e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Studio web fetch: a bare & gains a stray ;, escaped code leaves its code block, and a malformed &# can leave the rest of the page as raw HTML

3 participants