Repository navigation
perf: lookups run by the page instead of reading the whole document - #95
Merged
Merged
Conversation
…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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…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.
Member
Author
|
End-to-end comparison, 5 alternating pairs (this branch vs
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
marked this pull request as ready for review
November 20, 2026 19:21
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
On a remote browser (a DevTools endpoint reached through a proxy or a relay,
browserUrlof #92), the cost of a lookupis no longer the query but the transfer.
select,selectAll,querySelectorandquerySelectorAllon the wholedocument read the full tree first (
DOM.getDocument(depth = -1, pierce = true)): on a large page that is megabytes ofJSON 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,querySelectorandquerySelectorAllwithout a node:document.querySelector(…)/document.querySelectorAll(…)in the page (Runtime.evaluate), the selectorentering the script only as a JSON string literal;
DOM.describeNode, depth -1, pierce), the descriptions ofquerySelectorAllsent together, in document order;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/querySelectorAllwhose matches outweigh the document (nested matches, a selector matching most ofthe page): the page answers
"document"and the lookup reads the document as before, the smaller transfer. The countstops as soon as it passes the document's.
SyntaxError(aDOMException) is thrown as theCDPExceptionthe browser givesDOM.querySelector(select,querySelector) orDOM.querySelectorAll(
selectAll,querySelectorAll): code -32000,originalMessage"DOM Error while querying",datanull, samemessage, after disabling the DOM agent, as before. Checked on Chrome 157 against the protocol path itself, forli[, an empty selector and an unknown pseudo-class. Any other exception of the page stays anEvaluateException.children,
backendNodeIdas before). Itsnode,tree,parentIdandparentfill themselves on their first readfrom the document the tab keeps from an earlier read (
find,xpath, a lookup under an element,update()…) whilethe 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, aNodeOrElementpassed back toquerySelector) binds it by itself first, abare node included, and
update()reads the document as before.the lookup counts as no match, so
selecttries again; when only some matches ofquerySelectorAllare gone, none isreturned. 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 ownmatches too: one read for both.
Config.lookupsInPage,ConfigBuilder.lookupsInPageandConfig.Defaults.LOOKUPS_IN_PAGE, added by the firstcommits of this branch, are removed: they were never released.
find,findAllandxpathare 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:
node.nodeId,parentId,tree,parentnodeIdmay be 0,parentId/treenull,parentthrows, untilupdate()document.querySelectorDOM.*mutation events, DOM agentDOM.disablesent by hand failsWhy "on first read" cannot always fetch:
node,tree,parentIdandparentare plain properties ofElement,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 alreadyknown, and otherwise leaves them for
update(). Fetching on every first read would need suspend accessors, a breakingchange 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 nocommand, 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 lookupand 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,
querySelectorAllorder, matches that outweigh the document read from it, object or context gone counts asno match, a closed target and any other protocol error thrown, cancellation,
includeFramesfrom one document read,binding under an element, a bare node and another
Elementimplementation; node ids, tree and parent afterupdate()equal to the document lookup's; the invalid-selector exception (class, method, code, message, data, theDOM agent disabled) for both methods; a script's own
SyntaxErrorstays anEvaluateException.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 afterupdate()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,LookupBehaviourTestadapted to the single path.core/src/commonMainis 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;
mainat 9d0a01b, this branch at 80e26dd (the commitsafter it change docs and tests only):
mainselect+ firstapply: commandsselect+ firstapply: data receivedselect+ firstapply: timeselectAll(2 matches) + firstapply: commandsselectAll(2 matches) + firstapply: data receivedselectAll(2 matches) + firstapply: timeselectthentree/parent(page changing, soupdate()): commandsselectthentree/parent: data receivedselectthentree/parent: timeDOM.*events received per lookupA 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 ofmegabytes. 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
mainbefore 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:
the differences that remain are listed above.
(
DOM.getDocument) threw for the same race before, and Chrome also sends it for a closed tab, which must fail ratherthan poll until the timeout.
command's entry when its reply arrives, awaited or not, and a closed connection clears them all.
as holding objects from the moment the evaluation is sent; a lookup that finds nothing still sends no release.
div,*) pay one evaluation before falling back to the document read: accepted, the fallback isthe smaller transfer, and the extra round trip is small next to the document read it precedes.
DOM.*events until the document is read, so a busy page may look idle sooner: documented (KDoc, quickstart).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.
update(): same outcome as before,where the stale node id failed the same way.
selectAll(includeFrames = true)reads the document on every poll: unchanged from before (its frames need thedocument); the comment that claimed "one read" is corrected.
dom.disable()test now enables the agent first: the difference it hides is documented; a test that assertsthe failure would lock in a quirk rather than a behaviour.