Skip to content

Studio: cheaper per-token work in web page Markdown extraction - #16286

Merged
danielhanchen merged 5 commits into
mainfrom
perf/r16-web-extract
Nov 1, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
perf/r16-web-extract

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

What changes

web_fetch turns each fetched HTML page into Markdown with html_to_markdown(main_content=True). Most pages get a single tokenizer pass, and the per-token Python work in the renderer and in the title-button scan that runs alongside it is the main cost after the stdlib tokenizer. This PR cuts that work and leaves the output alone:

  • The title-button scan and the renderer now share one dict(attrs) and one hidden / ARIA-heading check per start tag. Before, each of them built its own dict and ran its own checks.
  • _is_hidden_element and _is_aria_heading skip their string work when the attribute is missing.
  • Implicit-close recovery returns straight away for a start tag outside every _IMPLICIT_CLOSERS set (_ANY_IMPLICIT_CLOSER). Before, it walked the open-tag stack for every span, a, img and so on.
  • The innermost open element of a name (scan endtag, renderer _exit_tag) is found by _innermost_index: the top of the stack first, then a backward C-level search (operator.indexOf(reversed(stack), name)) that never copies the stack, where it used to be a Python loop.
  • _prepare_foreign_html_start, _prepare_heading_start, _prepare_table_start, _close_header_frames and the scan's _close_headings are only called when their own early-return test would let them do something.
  • _emit takes a direct route when no header frame, heading or heading-link is open, and it now calls SiteLinks.clean only when a header frame measures the text.
  • Recorded start tags keep the parser's fresh attrs list without copying it (replay already copies it), and they read lineno / offset directly.

Results

The corpus is 39 real pages fetched once through _fetch_url_raw: Wikipedia articles and big tables, Python / Django / MDN / Kubernetes / Docker / GitHub REST docs, PyPI, GitHub README, issues and PR lists, BBC, Guardian, CNN, Ars Technica, HN, Lobsters, LWN, Discourse, the Bootstrap accordion docs and the WHATWG tables spec, from 13 KiB to 3.8 MiB. Base and head ran interleaved in one process over 11 rounds, comparing the sum of per-page minimums:

base head change
Whole corpus (sum of per-page min) 2830 ms 2377 ms -16.0%
Mean per page 72.6 ms 61.0 ms -11.6 ms
Largest single pages 189 ms (WHATWG tables) 152 ms -19.5%
Range across pages -10% to -22%

An A/A run (base against itself) moved 0.5%. Three more runs on a loaded host gave -15.0% to -16.1%.

The title-button scan's own cost over the recorded tokens of the corpus fell from 285 ms to 199 ms. That was measured before the shared-attribute change, which removes more from it.

Deep nesting

The lookup touches only the slots above the match, so closing deep or misnested pages stays linear (main_content=True, one process, busy host):

page base head
20,000 nested div 0.41 s 0.25 s
20,000 div + 20,000 misnested <section><span>t</section> 1.25 s 0.82 s
20,000 div + 20,000 stray </span> 35.1 s 8.9 s

Re-check

A second corpus of 20 live pages (Wikipedia, Python / MDN / Django / Docker / Kubernetes / GitHub REST docs, PyPI, GitHub, HN, Lobsters, LWN, BBC, Guardian, Ars Technica, WHATWG tables, Bootstrap), interleaved base / head / base over 7 rounds: -15.9% on the sum of per-page minimums (per-page median -13.5%), A/A within 2.4%. html_to_markdown in both modes and the SiteLinks.strip output are byte identical on all pages, and 3,000 to 4,000 fuzz documents per run show 0 mismatches on Python 3.11.17, 3.12.3, 3.13.12 and 3.14.3.

Tests

  • Byte identity: html_to_markdown output and SiteLinks.strip output are identical on all 39 pages. The full _fetch_page_text result (network stubbed, max_chars=16000) is identical too (same SHA-1 over all pages).
  • Fuzz: 30,000 base-vs-head cases (generated tag soup with headings, buttons, ARIA roles, hidden variants, tables, svg/math integration points, skipped subtrees and unclosed tags, plus real-page splices), across 4 modes and 4 span limits. 0 mismatches. Three deliberate one-line mutations of the head (dropping the ARIA-heading flag in the scan, dropping the heading-link guard in _emit, >= to > in the header-frame guard) were each caught.
  • Across Python versions (3.10.22, 3.11.14, 3.12.3, 3.13.12, 3.13.17, 3.14.3): 21,072 adversarial cases each (unclosed and stray tags, SVG / MathML breakouts, custom and uppercase elements, nested hidden and aria-hidden, headings inside buttons, details / summary, tables in headers, 300-deep nesting, malformed and duplicate attributes, a 200 KB attribute value, entity edge cases, unterminated script / style / comments, CDATA) plus 1,500 generated fuzz cases: 0 differ on every version.
  • New tests/test_html_to_md_fast_paths.py: golden outputs produced by the pre-change converter (ARIA-heading title buttons, hidden variants, implicit closers, header frames, foreign content, skipped subtrees), the attribute-check formulas compared with the old ones, the closer union, and the innermost-tag lookup (no stack copy, deep and misnested pages). The goldens pass on base as well.
  • Neighbour tests (48 files: every test touching _html_to_md / _fetch_page_text, plus web / html / fetch / markdown / search): base and head fail the same IDs, all pre-existing and outside this change: test_diffusion_offload_prefetch::test_resident_onload_skips_the_copy_stream_wait_when_fenced, test_diffusion_small_host_prefetch::test_group_offload_installs_prefetch_only_on_small_host_pipes, an import error in test_h3_stream_prefetch.py, and test_web_search_fallback::test_primary_eight_parallel_successes_all_use_provider. That last one is flaky under xdist and fails on both arms when run alone.

Not covered

  • Python patch releases after 3.12.3 and 3.14.3 were not run. The change depends only on handler call order and lineno / offset, which the existing token replay already relies on.
  • A second timing pass on a busier host gave -15.5% to -16.1% over three interleaved runs (A/A 0.1%); absolute times are host dependent.
  • Pages that block automated fetches (Reuters, AP, NYT, Stack Overflow, Reddit) are not in the corpus.
  • The time saved is CPU on the fetch thread. The network time of a fetch is unchanged.

The title-button scan and the renderer now share one attribute dict and
one hidden / ARIA-heading check per start tag, skip implicit-close
recovery for tags that close nothing, find the innermost open element
with a C-speed list lookup, call guarded helpers only when their own
early-return test would pass, keep recorded attrs uncopied, and run
SiteLinks.clean only where a header frame measures text. Output is
unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen danielhanchen self-assigned this Nov 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-01T11:02:09.081704Z
We couldn’t complete this review. Comment @codex review to try again.
af37f31 Draft marked ready
ℹ️ 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 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: 2463a3803b

ℹ️ 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".

break
open_tags = self._open_tags
if tag not in _VOID_TAGS and tag in open_tags:
i = len(open_tags) - 1 - open_tags[::-1].index(tag)

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 Avoid copying the entire open-tag stack on each closing tag

For deeply nested HTML, open_tags[::-1] copies the entire remaining stack even when the closing tag matches its last element. Closing N nested elements therefore becomes quadratic instead of linear; the identical change in _TitleButtonScan.endtag adds another full-stack copy per close. Testing '<div>' * 20000 + 'text' + '</div>' * 20000 (220 KB) with main_content=True took approximately 2.00 seconds after this change versus 0.46 seconds before it, while 10,000 levels took 0.55 versus 0.24 seconds. Preserve a last-element fast path or use a reverse lookup that does not copy the stack in both locations so fetched pages with deep nesting do not incur this regression.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 84d4a3c: one non-copying lookup (top of stack first, then a reverse walk only for misnested tags) serves both end-tag paths; 20,000 nested div/span pairs now render in 0.53s vs 0.79s on base and 8.05s before the fix, with a no-slice regression test.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 84d4a3cc04

ℹ️ 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".

Comment on lines +165 to +168
if tag not in stack:
return -1
while stack[i] != tag:
i -= 1

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 Search backward without a forward membership scan

For deeply nested HTML with shallow misnesting, tag not in stack scans the entire enclosing prefix even when the matching tag is only one slot below the top, making repeated closes quadratic. The previous copying issue is fixed; fresh evidence is '<div>' * n + '<section><span>text</section>' * n + '</div>' * n, where each </section> now scans all enclosing divs in both end-tag paths. With main_content=True, 10,000 levels took 3.43 seconds versus 0.82 seconds on the parent, and 20,000 took 12.97 versus 1.69 seconds. Use a bounded backward search that also handles absent tags, avoiding the forward membership pass so malformed fetched pages retain linear lookup work.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Nov 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 91478e4: the lookup now searches backward with operator.indexOf(reversed(stack), tag), no forward membership pass and no copy; the misnested case at 20,000 levels takes 0.82s vs 1.25s on base (7.31s on the previous head), with a test for it.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 91478e449d

ℹ️ 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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant