Skip to content

perf: lookups run by the page instead of reading the whole document - #95

Merged
nathanfallet merged 17 commits into
mainfrom
perf/lookups-in-page
Nov 21, 2026
Merged

nathanfallet merged 17 commits into
mainfrom
perf/lookups-in-page

Conversation

@nathanfallet

@nathanfallet nathanfallet commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Why

On a remote browser (a DevTools endpoint reached through a proxy or a relay, browserUrl of #92), the cost of a lookup
is no longer the query but the transfer. select, selectAll, querySelector and querySelectorAll on the whole
document read the full tree first (DOM.getDocument(depth = -1, pierce = true)): on a large page that is megabytes of
JSON per lookup. #93 keeps that read while the page does not change, but a page that keeps changing (a timer, a live
list) still pays it on nearly every lookup.

This PR lets the page run the selector and describes only the matches, for everyone: there is no setting.

What changes

  • select, selectAll, querySelector and querySelectorAll without a node:
    • run document.querySelector(…) / document.querySelectorAll(…) in the page (Runtime.evaluate), the selector
      entering the script only as a JSON string literal;
    • describe each match with its subtree (DOM.describeNode, depth -1, pierce), the descriptions of
      querySelectorAll sent together, in document order;
    • put every object the lookup creates in an object group of its own, released in the same round trip as the
      descriptions (sent after them), on every path, cancellation included, waiting two seconds at most: a lookup leaves
      no object in the page, and a found element resolves its node at its first call, as before.
  • selectAll / querySelectorAll whose matches outweigh the document (nested matches, a selector matching most of
    the page): the page answers "document" and the lookup reads the document as before, the smaller transfer. The count
    stops as soon as it passes the document's.
  • Invalid selector: the same exception as before. The page's SyntaxError (a DOMException) is thrown as the
    CDPException the browser gives DOM.querySelector (select, querySelector) or DOM.querySelectorAll
    (selectAll, querySelectorAll): code -32000, originalMessage "DOM Error while querying", data null, same
    message, after disabling the DOM agent, as before. Checked on Chrome 157 against the protocol path itself, for
    li[, an empty selector and an unknown pseudo-class. Any other exception of the page stays an EvaluateException.
  • Node ids, tree, parent: filled on demand. A found element carries its node and subtree (tag, text, attributes,
    children, backendNodeId as before). Its node, tree, parentId and parent fill themselves on their first read
    from the document the tab keeps from an earlier read (find, xpath, a lookup under an element, update()…) while
    the page has not changed since, with no command; they are then exactly those of the document lookup (tested on
    Chrome). The document's node is taken only when it holds the same subtree as the one found, ids aside, so a read
    elsewhere never changes what the element shows; the document's nodes are indexed once per read. A lookup under such
    an element (element.querySelector, a NodeOrElement passed back to querySelector) binds it by itself first, a
    bare node included, and update() reads the document as before.
  • Waiting, polling and timeouts keep their behaviour. An object or execution context dropped by a navigation during
    the lookup counts as no match, so select tries again; when only some matches of querySelectorAll are gone, none is
    returned. Any other protocol error is thrown, "Inspected target navigated or closed" included (the document read
    threw it too).
  • selectAll(includeFrames = true) reads the document (searching inside the frames needs it), for the page's own
    matches too: one read for both.
  • Config.lookupsInPage, ConfigBuilder.lookupsInPage and Config.Defaults.LOOKUPS_IN_PAGE, added by the first
    commits of this branch, are removed: they were never released.
  • Lookups under a node or an element, find, findAll and xpath are unchanged.

Still different from reading the document

Written in the KDoc of Tab.querySelector ("How lookups work") and in a new quickstart section of the same name,
linked from the README:

Before Now
Data read the whole document the matches and their subtrees (the document when they outweigh it)
node.nodeId, parentId, tree, parent set filled on first read from a kept document; without one: nodeId may be 0, parentId / tree null, parent throws, until update()
A page that replaces document.querySelector not affected its override runs
Remote objects one per element used none kept: the lookup's object group is released in the same round trip; the first call resolves the node, as before
DOM.* mutation events, DOM agent flowing after the first lookup, agent enabled none until something reads the document: a busy page may count as idle sooner; a DOM.disable sent by hand fails

Why "on first read" cannot always fetch: node, tree, parentId and parent are plain properties of Element,
not suspend functions, and the library targets JavaScript too, where a getter cannot wait for a protocol reply; on the
JVM, blocking inside a getter would deadlock any caller whose scope also runs the connection (createBrowser(this)
inside runBlocking, runTest, a UI dispatcher). So the first read fills them when a current document is already
known, and otherwise leaves them for update(). Fetching on every first read would need suspend accessors, a breaking
change of the public API, left out of this PR.

Tests

  • LookupsInPageTest (scripted link): node ids, tree and parent filled on first read from a kept document with no
    command, not from a document the page changed since, nor from a node with another subtree; an evaluation cancelled
    in flight releases its group, a lookup that finds nothing sends no release; commands and parameters, no DOM.getDocument, the object group of each lookup
    and its release in the same round trip as the descriptions, the release bounded to two seconds, a found element
    without objects that resolves its node at its first call, polling then timeout, match gone then retried, JSON
    literal, querySelectorAll order, matches that outweigh the document read from it, object or context gone counts as
    no match, a closed target and any other protocol error thrown, cancellation, includeFrames from one document read,
    binding under an element, a bare node and another Element implementation; node ids, tree and parent after
    update() equal to the document lookup's; the invalid-selector exception (class, method, code, message, data, the
    DOM agent disabled) for both methods; a script's own SyntaxError stays an EvaluateException.
  • LookupsInPageBehaviourTest (real headless Chrome): every lookup compared with the document lookup on the same page
    (elements, text, attributes, children, order, no match, shadow root, frames), clicks, navigation, no tree until
    update() when no document was read, node ids / tree / parent filled on first read once it was, node ids / tree / parent after update() identical to the document lookup's, binding under an element,
    matches that outweigh the document, and the invalid-selector exception compared field by field with the one
    DOM.querySelector(All) raises.
  • DocumentReuseTest, SettledLookupTest, LookupBehaviourTest adapted to the single path.
  • Every added or changed line of core/src/commonMain is covered (Kover, codecov/patch).

Bench

Headless Chrome 157 behind a local proxy adding 30 ms each way (60 ms round trip), page of 1.16 MB of HTML with a
shadow host, an iframe and a timer that changes the DOM every 250 ms. Page loaded first; then 10 rounds of each
scenario, medians, commands and bytes counted at the proxy; main at 9d0a01b, this branch at 80e26dd (the commits
after it change docs and tests only):

main This PR
select + first apply: commands 5 6 (describe and release go together)
select + first apply: data received 9.18 MB 1.0 kB
select + first apply: time 835 ms 278 ms
selectAll (2 matches) + first apply: commands 4 7 (describes and release go together)
selectAll (2 matches) + first apply: data received 9.17 MB 1.9 kB
selectAll (2 matches) + first apply: time 758 ms 349 ms
select then tree / parent (page changing, so update()): commands 3 6
select then tree / parent: data received 9.18 MB 9.18 MB
select then tree / parent: time 626 ms 781 ms
DOM.* events received per lookup 6 to 10 0

A caller that needs the tree of an element on a page that keeps changing pays one more round trip than before (the
document is read by update() after the lookup instead of by it); everything else reads kilobytes instead of
megabytes. On a page that does not change between reads, the tree comes from the kept document with no command.

A downstream end-to-end suite (122 browser tests, real headless Chrome) ran 5 alternating passes against this branch
and main before the setting was removed: 10/10 green, wall-clock within run-to-run spread (comment below).

Review

An automated high-effort correctness review ran on 4207cc1; its ten findings and what became of them:

  1. Title and description still said "opt-in": both rewritten (this text). The change is unconditional by design;
    the differences that remain are listed above.
  2. "Inspected target navigated or closed" is thrown rather than counted as no match: kept, it is what the document read
    (DOM.getDocument) threw for the same race before, and Chrome also sends it for a closed tab, which must fail rather
    than poll until the timeout.
  3. Descriptions not awaited when a later send fails or the lookup is cancelled: no leak, the receive loop removes a
    command's entry when its reply arrives, awaited or not, and a closed connection clears them all.
  4. An evaluation cut in flight (cancelled, timed out) left its objects in the page: fixed in 80e26dd, the group counts
    as holding objects from the moment the evaluation is sent; a lookup that finds nothing still sends no release.
  5. Nested matches (div, *) pay one evaluation before falling back to the document read: accepted, the fallback is
    the smaller transfer, and the extra round trip is small next to the document read it precedes.
  6. No DOM.* events until the document is read, so a busy page may look idle sooner: documented (KDoc, quickstart).
  7. The getters swapped the found node for the document's node, even when the page had changed in between, and scanned
    the whole document per element: fixed in 80e26dd, the document's node is taken only when it holds the same subtree
    (ids aside), from an index built once per read; the bind also runs when the description already carries node ids.
  8. A lookup under an element the page removed queries node id 0, then fails in update(): same outcome as before,
    where the stale node id failed the same way.
  9. selectAll(includeFrames = true) reads the document on every poll: unchanged from before (its frames need the
    document); the comment that claimed "one read" is corrected.
  10. The dom.disable() test now enables the agent first: the difference it hides is documented; a test that asserts
    the failure would lock in a quirk rather than a behaviour.

…ument

With Config.lookupsInPage (off by default), select, selectAll,
querySelector and querySelectorAll without a node ask the page to run
document.querySelector / querySelectorAll (Runtime.evaluate) and describe
only the matches (DOM.describeNode, depth -1, pierce), instead of reading
the whole document (DOM.getDocument, depth -1, pierce) and querying it.

- The selector enters the script only as a JSON string literal.
- The element keeps the remote object of the lookup, so its first call
  needs no DOM.resolveNode; it carries no node id nor tree until update().
- Waiting, timeouts and errors keep their behaviour: an invalid selector
  throws the page's SyntaxError as an EvaluateException.
- Lookups under a node or an element, find and findAll are unchanged.
- KDoc of the setting, README and quickstart list every difference
  between on and off.
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

…nger need

- An object or execution context dropped by a navigation during an in-page
  lookup counts as no match (select tries again); any other protocol error
  is thrown instead of being read as no match.
- querySelectorAll releases the array of matches while they are described.
- selectAll(includeFrames = true) finds the iframes through the document,
  which the search inside each one reads anyway.
- A lookup under an element found in the page updates it from the document
  first, as it has no node id yet.
…ugh the document

- A match gone before it is described means the page navigated:
  querySelectorAll in the page returns no match rather than part of the old
  page's matches.
- Releasing the array is a cleanup: its failure never fails the lookup, and
  the array is also released when reading its properties fails.
- "Inspected target navigated or closed" counts as gone; "could not find" is
  narrowed to objects and nodes.
- selectAll(includeFrames = true) reads the document for the page's own
  matches too, so frames and page come from one read in both modes.
…path

- "Inspected target navigated or closed" no longer counts as gone: Chrome
  also sends it for a closed tab, which must fail rather than poll.
- The descriptions run in a supervisorScope, so one that fails no longer
  cancels the release of the array; the release swallows any error but a
  cancellation.
- selectAll(includeFrames = true) shares one helper for its document
  lookups; its KDoc says the document is read as without the setting.
- The release runs under NonCancellable, in parallel with the descriptions,
  and in a finally block on every other path (a failed or cancelled read of
  the array included); a failing description cancels the others again.
- The release never fails the lookup, its own timeout included.
- KDoc: what includeFrames reads with the setting on, and that a command cut
  with "Inspected target navigated or closed" is thrown, as off.
@nathanfallet

Copy link
Copy Markdown
Member Author

End-to-end comparison, 5 alternating pairs (this branch vs main), same machine, full browser suite each pass:

Run Branch Duration (s) Tests Failures
1 PR 2888 122 0
1 main 2929 122 0
2 PR 2943 122 0
2 main 2923 122 0
3 PR 2922 122 0
3 main 2945 122 0
4 PR 2923 122 0
4 main 2921 122 0
5 PR 2745 122 0
5 main 2616 122 0

Mean: PR 2884 s, main 2867 s (+0.6 %, within run-to-run spread). 10/10 passes green, no flaky test on either side. The suite is dominated by page loads, so wall-clock is not where the round-trip saving shows; it shows in the per-call counts from the local bench in the description.

Config.lookupsInPage, ConfigBuilder.lookupsInPage and Config.Defaults.LOOKUPS_IN_PAGE
are removed (never released): select, selectAll, querySelector and querySelectorAll
without a node always run the selector in the page and describe only the matches.

- An invalid selector throws the same CDPException as the document lookup did
  (DOM.querySelector or DOM.querySelectorAll, code -32000, "DOM Error while
  querying"), after disabling the DOM agent as before; any other exception of the
  page stays an EvaluateException.
- A lookup under an element or a bare node found in the page binds it to the
  document first (node ids, tree), without resolving its object again.
- The KDoc of Tab.querySelector and the quickstart describe how lookups work.
…the DOM agent before disabling it

A lookup run by the page does not enable the DOM agent, so a DOM.disable sent by hand
right after one fails as on any tab where it was never enabled. Also keeps the lines
added by this branch within the 120 columns of detekt.
…en its matches outweigh it

- The array and the matches of an in-page querySelectorAll live in an object group of
  their own, released in the same round trip as the descriptions (sent after them), on
  every path: a polled lookup no longer leaves one object per match in the page. Its
  elements resolve their node at their first call, as elements read from the document.
- When the matches' subtrees hold more elements than the whole document (nested matches,
  a selector matching most of the page), the page answers "document" and the lookup
  reads the document, the smaller transfer, as before.
- Only a DOMException SyntaxError is an invalid selector; a SyntaxError thrown by a
  script of the page stays an EvaluateException.
…anup

- select and querySelector put the match in an object group of the lookup, released in
  the same round trip as its description, like selectAll: a found element keeps no
  object of the page and resolves its node at its first call, as before, so a polled
  lookup no longer pins one object per call.
- The release waits two seconds at most, so a cancelled or timed-out lookup is not held
  by a slow connection for a whole command timeout.
- The selectAll script uses no global of the page but querySelectorAll and
  getElementsByTagName, and stops counting the matches' elements as soon as they pass
  the document's.
… on first read

The node and tree of an element found by a lookup the page ran are filled on
their first read from the document the tab keeps from an earlier read, while
the page has not changed since, with no command: node ids, tree, parentId and
parent are then those a lookup on the document gave. Without such a document
the element stays as found until update() or a lookup under it.
…ease an evaluation cut in flight

- A found element takes the kept document's node on its first read only when
  that node holds the same subtree, ids aside, so a read elsewhere never
  changes what the element shows; it binds even when the description already
  carries node ids (the browser gives them once the document was read). The
  document's nodes are indexed once per read.
- The object group of a lookup counts as holding objects from the moment the
  evaluation is sent: one cancelled or timed out in flight is released too;
  a lookup that finds nothing still sends no release.
@nathanfallet nathanfallet changed the title perf: opt-in lookups run by the page instead of reading the whole document perf: lookups run by the page instead of reading the whole document Nov 20, 2026
@nathanfallet
nathanfallet marked this pull request as ready for review November 20, 2026 19:21
nathanfallet and others added 2 commits November 21, 2026 16:01
Move the binding of an element to the kept document into ElementBinding, the
stable coordinates script into its own file, the cleanup of a lookup group into
a function of its own, and split the lookups in the page tests in two classes
sharing their fixtures. No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@nathanfallet
nathanfallet merged commit cfa4244 into main Nov 21, 2026
5 checks passed
@nathanfallet
nathanfallet deleted the perf/lookups-in-page branch November 21, 2026 16:03
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