[🐛 Bug]: BiDi: request.children lists every finished sub-request twice, is never trimmed and makes each response slower to handle

Aperta
#16,416 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
node.js, typescript, web-dev

Direzione di ricerca

Start with packages/webdriverio/src/session/networkManager.ts, especially the #responseCompleted and request tracking code cited in the report. Reproduce with the provided stub BiDi script using node --expose-gc repro.mjs, then inspect how navigation and context lifecycle events affect retained requests. Done means each sub-request appears once, response matching avoids scanning the full children list, and finished navigation data can be released when it is no longer readable.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Bug 🐛 good first pick help wanted Performance Protocol Related
Have you read the Contributing Guidelines on issues?
WebdriverIO Version

10.2.0 (the code is the same on main at 8989d91)

Node.js Version

24.22.2

Mode

Standalone Mode

Which capabilities are you using?
{
  browserName: 'chrome'
}
// any WebDriver BiDi session
What happened?

In a BiDi session the NetworkManager collects the sub-requests of a navigation in request.children (the request of the context that browser.url() returns). Three things go wrong there:

  1. Every finished sub-request is in the list twice. #responseCompleted finds the child with children.find(...), sets its response, and then pushes the same object again: webdriverio/src/session/networkManager.ts#L231-L241. (await browser.url(url)).request.children shows each one twice.
  2. Nothing is ever removed. #requests and #lastNavigationByContext only get entries (webdriverio/src/session/networkManager.ts#L141-L150), and there is no delete or clear in the file. Sub-requests without a navigation id go to the last navigation of their context, so a page that keeps polling without navigating (an SPA, a dashboard) adds two entries per request for as long as the session lives.
  3. Handling a response is linear in that list. children.find at line 231 (and at webdriverio/src/session/networkManager.ts#L159) scans the whole list for every network.responseCompleted, so the total work is quadratic.

Every BiDi session subscribes to these events at start, whether or not the test reads request.

What is your expected behavior?
  • request.children has one entry per sub-request.
  • Finished navigations (and their children) are dropped when nothing can read them any more, for example when the context navigates again or is closed.
  • A response is matched to its request by id in constant time.
How to reproduce the bug.

The script starts a stub BiDi endpoint (HTTP for POST /session and a WebSocket server), so it needs no browser. It answers browsingContext.navigate with a page that loads 3 sub-resources, then sends 40,000 more request/response event pairs without a navigation, as a polling page would.

npm i [email protected] ws
node --expose-gc repro.mjs
repro.mjs
/**
 * the BiDi NetworkManager stores every sub-request of a page forever,
 * stores each finished one twice, and scans the whole list on every response.
 *
 * Run: node --expose-gc b3-network-manager.mjs
 */
import { remote } from 'webdriverio'
import http from 'node:http'
import { WebSocketServer } from 'ws'

// ---- stub server, no browser or device involved ----
const CONTEXT = 'ctx-1'

/**
 * @param {(msg: {id: number, method: string, params: any}, emit: (method: string, params: any) => void) => any} onCommand
 *        return the `result` of the command, or undefined for `{}`
 */
async function startFakeBidi (onCommand = () => undefined) {
    const commands = []
    const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' })
    await new Promise((r) => wss.on('listening', r))
    const wsPort = wss.address().port
    let socket
    const emit = (method, params) => socket.send(JSON.stringify({ type: 'event', method, params }))
    const sendRaw = (text) => socket.send(text)

    wss.on('connection', (ws) => {
        socket = ws
        ws.on('message', async (data) => {
            const msg = JSON.parse(data.toString())
            commands.push(msg.method)
            let result
            if (msg.method === 'browsingContext.getTree') {
                result = { contexts: [{ context: CONTEXT, url: 'about:blank', children: [], parent: null, userContext: 'default', originalOpener: null, clientWindow: 'w1' }] }
            } else if (msg.method === 'script.addPreloadScript') {
                result = { script: 'preload-' + msg.id }
            } else if (msg.method === 'session.subscribe') {
                result = { subscription: 'sub-' + msg.id }
            } else if (msg.method === 'script.callFunction' || msg.method === 'script.evaluate') {
                result = { type: 'success', realm: 'r1', result: { type: 'undefined' } }
            }
            const custom = await onCommand(msg, emit, sendRaw)
            if (custom !== undefined) {
                result = custom
            }
            ws.send(JSON.stringify({ type: 'success', id: msg.id, result: result ?? {} }))
        })
    })

    const server = http.createServer((req, res) => {
        let raw = ''
        req.on('data', (c) => { raw += c })
        req.on('end', () => {
            let value = null
            if (req.method === 'POST' && req.url === '/session') {
                value = {
                    sessionId: 'fake-session',
                    capabilities: { browserName: 'chrome', browserVersion: '142.0', platformName: 'mac', webSocketUrl: `ws://127.0.0.1:${wsPort}` }
                }
            } else if (req.url.endsWith('/window')) {
                value = CONTEXT
            }
            const payload = JSON.stringify({ value })
            res.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) })
            res.end(payload)
        })
    })
    await new Promise((r) => server.listen(0, '127.0.0.1', r))

    return {
        port: server.address().port,
        commands,
        emit,
        sendRaw,
        close: async () => {
            for (const client of wss.clients) { client.terminate() }
            await new Promise((r) => wss.close(r))
            await new Promise((r) => server.close(r))
        }
    }
}
// ---- reproduction ----

const NAV = 'nav-1'
const URL = 'https://example.com/'
const requestData = (id, url) => ({
    request: id, url, method: 'GET', headers: [{ name: 'accept', value: { type: 'string', value: '*/*' } }],
    cookies: [], headersSize: 10, bodySize: 0, timings: {}
})
const base = (navigation) => ({ context: CONTEXT, navigation, isBlocked: false, redirectCount: 0, timestamp: Date.now() })

function emitRequest (emit, id, navigation = null) {
    const request = requestData(id, navigation ? URL : `${URL}api/poll?${id}`)
    emit('network.beforeRequestSent', { ...base(navigation), request, initiator: { type: 'other' } })
    emit('network.responseCompleted', {
        ...base(navigation), request,
        response: { url: request.url, protocol: 'h2', status: 200, statusText: 'OK', fromCache: false, headers: [], mimeType: 'application/json', bytesReceived: 10, headersSize: 10, bodySize: 0, content: { size: 0 } }
    })
}

const bidi = await startFakeBidi((msg, emit) => {
    if (msg.method === 'browsingContext.navigate') {
        emit('browsingContext.navigationStarted', { context: CONTEXT, navigation: NAV, timestamp: Date.now(), url: URL })
        emitRequest(emit, 'main', NAV)
        // the page loads 3 sub-resources
        for (let i = 0; i < 3; i++) { emitRequest(emit, `res-${i}`) }
        emit('browsingContext.load', { context: CONTEXT, navigation: NAV, timestamp: Date.now(), url: URL })
        return { navigation: NAV, url: URL }
    }
})

const browser = await remote({ hostname: '127.0.0.1', port: bidi.port, logLevel: 'silent', capabilities: { browserName: 'chrome' } })
// `request` is the object the NetworkManager keeps for this navigation
const { request } = await browser.url(URL)
await new Promise((r) => setTimeout(r, 100))
console.log(`page made 3 sub-requests -> request.children.length = ${request.children.length}`)
console.log('ids:', request.children.map((c) => c.id).join(', '))

// the page keeps polling an API without navigating (an SPA, a dashboard, a chat)
const heap = () => { global.gc(); return (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(1) }
console.log(`\nheap: ${heap()} MB`)
let sent = 0
for (let round = 1; round <= 4; round++) {
    const start = performance.now()
    for (let i = 0; i < 10000; i++) { emitRequest(bidi.emit, `poll-${sent++}`) }
    // wait until the client handled all of them
    while (request.children.length < (sent + 3) * 2) { await new Promise((r) => setTimeout(r, 20)) }
    console.log(`${sent} polled requests: children = ${request.children.length}, heap ${heap()} MB, handling this batch took ${Math.round(performance.now() - start)}ms`)
}

await browser.deleteSession().catch(() => {})
await bidi.close()
process.exit(0)

The 3 sub-requests are 6 children. Each batch of 10,000 polled requests takes longer to handle than the one before, from 1s to 8s.

Relevant log output
page made 3 sub-requests -> request.children.length = 6
ids: res-0, res-0, res-1, res-1, res-2, res-2

heap: 21.8 MB
10000 polled requests: children = 20006, heap 26.4 MB, handling this batch took 971ms
20000 polled requests: children = 40006, heap 30.8 MB, handling this batch took 1304ms
30000 polled requests: children = 60006, heap 35.2 MB, handling this batch took 3249ms
40000 polled requests: children = 80006, heap 39.7 MB, handling this batch took 8036ms
Code of Conduct
  • I agree to follow this project's Code of Conduct
Is there an existing issue for this?
  • I have searched the existing issues
Lingua principale
TypeScript
Stelle
9.9k
Fork
2.7k
Merge medio
17h 37m
PR unite (30g)
92

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di webdriverio/webdriverio

Tutte le issue di webdriverio/webdriverio

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.