[🐛 Bug]: BiDi: request.children lists every finished sub-request twice, is never trimmed and makes each response slower to handle
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
- Ambito
- backend, performance
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
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
- Lingua principale
- TypeScript
- Stelle
- 9.9k
- Fork
- 2.7k
- Merge medio
- 17h 37m
- PR unite (30g)
- 92
Preparare l'ambiente
Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di webdriverio/webdriverio
-
[🐛 Bug]: @wdio/reporter drops the function name of a string script in command outputForse già presa @dhananjay6561 l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 80/100
webdriverio/webdriverio#16507 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
@wdio/utils: monad.ts tells browser from element scope by function name, which breaks under minificationForse già presa @xixi-box l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 79/100
webdriverio/webdriverio#16504 ·
I maintainer di solito rispondono entro 1 giorno
-
[💡 Feature]: Allow to pass options to `tsx`Forse già presa @Mittalnew l’ha presa 21 giorni fa. Apertahelp wanted Idea 💡 wdio-cli
Difficoltà 2/5 1-3 ore Idoneità per principianti 66/100
webdriverio/webdriverio#16361 · 8 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
Bug 🐛 Needs Triaging ⏳
Difficoltà 3/5 Mezza giornata Idoneità per principianti 35/100
webdriverio/webdriverio#16500 · 2 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
[🐛 Bug]: Since Chrome 158, a mock that lets a response through strips all the response headersForse già presa @PloneMraz l’ha presa 2 giorni fa. ApertaBug 🐛 Needs Triaging ⏳
Difficoltà 4/5 3-5 giorni Idoneità per principianti 45/100
webdriverio/webdriverio#16498 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di webdriverio/webdriverio
Issue simili
-
Postgres upgrade golden leaves fixture URL query parameters in the expected output comparisonAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
garrytan/gbrain#10437 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Bedrock "Too many tokens" throttle is not auto-retried, unlike "Too many requests"Forse già presa @acmerfight l’ha presa oggi. Apertauntriaged
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
earendil-works/pi#12573 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 70/100
agentes-chat/agentes-chat#1506 ·
I maintainer di solito rispondono entro 1 giorno
-
comp/desktop desktop/files os/windows P2 type/perf
Difficoltà 2/5 1-3 ore Idoneità per principianti 80/100
NousResearch/hermes-agent#160359 ·
I maintainer di solito rispondono entro 1 giorno
-
Missing repro Platform: Android
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
software-mansion/react-native-reanimated#11554 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno