Closed ankur22 closed 1 month ago
So, my understanding is Event.data is any and the queue.read slice was holding onto the Event that was read. Since any can be of any pointer that points to any value, it can clearly leak.
Yeah, that's correct. I'm wondering if the other parts of the queue/handler in the emitter need to be looked at too for similar issues.
When we read off the read queue, we alias the slice. What has been forgotten though is to remove the reference to the entry in the slice after it has been read. This fixes that by overwriting the entry with a new Event. This now allows the GC to pick up the buffered data that the event was holding onto.
What?
This is removing the reference to the data that is no longer needed once the Event has been sent and read off the queue,. but before the read queue is aliased.
Why?
I remember having this complicated write/read slice in the emitter queue. The reason we needed this to keep the incoming CDP messages in order, otherwise they would go out of order (PR). The issue is that once the event is read off the read queue, the read slice is aliased, but the event is still held in memory in the underlying array!
By overwriting the entry before the alias the data that was being held onto is now free to be picked up by the GC.
How to Test
Testing this change requires the following to be performed:
main
, so checkoutmain
;mem-test.js
```js import { browser } from "k6/browser"; export const options = { scenarios: { ui: { iterations: 1, executor: "shared-iterations", maxDuration: '120m', options: { browser: { type: "chromium", }, }, }, } }; export default async function () { const page = await browser.newPage(); for (var i = 0; i < 10; i++) { await page.goto("http://2022wfh.ddns.net/test", { waitUntil: "networkidle" }); } await page.close(); } ```./mem_bench.sh on_main.csv mem-test.js
:Bash script to run and keep track of memory usage
```bash #!/bin/bash # Usage: ./mem_bench.shgo tool pprof -http=":8002" pprof-heap-1
inuse_space
already selected in the graph view, go tohttp://localhost:8002/ui/flamegraph
;fix/memory-leak-in-event-queue
;io.ReadAll
hasn't grown:Checklist
Related PR(s)/Issue(s)
Updates: https://github.com/grafana/xk6-browser/issues/1480