[🐛 Bug]: BiDi: request.children lists every finished sub-request twice, is never trimmed and makes each response slower to handle
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 48/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- node.js, typescript, web-dev
- Área
- backend, performance
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Have you read the Contributing Guidelines on issues?
- I have 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:
- Every finished sub-request is in the list twice.
#responseCompletedfinds the child withchildren.find(...), sets its response, and then pushes the same object again:webdriverio/src/session/networkManager.ts#L231-L241.(await browser.url(url)).request.childrenshows each one twice. - Nothing is ever removed.
#requestsand#lastNavigationByContextonly get entries (webdriverio/src/session/networkManager.ts#L141-L150), and there is nodeleteorclearin 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. - Handling a response is linear in that list.
children.findat line 231 (and atwebdriverio/src/session/networkManager.ts#L159) scans the whole list for everynetwork.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.childrenhas 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
- Lenguaje dominante
- TypeScript
- Estrellas
- 9.9k
- Forks
- 2.7k
- Merge medio
- 17 h 37 min
- PR fusionados (30 d)
- 92
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de webdriverio/webdriverio
-
[🐛 Bug]: @wdio/reporter drops the function name of a string script in command outputPosiblemente ocupada @dhananjay6561 la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
webdriverio/webdriverio#16507 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
@wdio/utils: monad.ts tells browser from element scope by function name, which breaks under minificationPosiblemente ocupada @xixi-box la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
webdriverio/webdriverio#16504 ·
Los mantenedores suelen responder en 1 día
-
[💡 Feature]: Allow to pass options to `tsx`Posiblemente ocupada @Mittalnew la tomó hace 21 días. Abiertohelp wanted Idea 💡 wdio-cli
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
webdriverio/webdriverio#16361 · 8 comentarios ·
Los mantenedores suelen responder en 1 día
-
Bug 🐛 Needs Triaging ⏳
Dificultad 3/5 Medio día Aptitud para principiantes 35/100
webdriverio/webdriverio#16500 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
[🐛 Bug]: Since Chrome 158, a mock that lets a response through strips all the response headersPosiblemente ocupada @PloneMraz la tomó hace 2 días. AbiertoBug 🐛 Needs Triaging ⏳
Dificultad 4/5 3-5 días Aptitud para principiantes 45/100
webdriverio/webdriverio#16498 · 3 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de webdriverio/webdriverio
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Los mantenedores suelen responder en 1 día
-
rel: fix
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Deltares/fews-web-oc#2400 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
ardia-browser/ardia#4426 ·
Los mantenedores suelen responder en 1 día
-
Bug report: isValidISODateDashOnly accepts text before or after the date-timePosiblemente ocupada @bardrop la tomó hoy. Abierto
Dificultad 1/5 1-3 horas Aptitud para principiantes 88/100
pnp/cli-microsoft365#7713 ·
Los mantenedores suelen responder en 1 día
-
Diagram: Journey Type: Bug / Error
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
mermaid-js/mermaid-v13#1293 ·
Los mantenedores suelen responder en 1 día