From bfd8959d2c98414470ea7882ff2d13eeea8eba98 Mon Sep 17 00:00:00 2001 From: ankur22 Date: Fri, 17 Jan 2025 10:48:32 +0000 Subject: [PATCH] Fix underlying slice by providing a new one When we read off the queue.read slice, it essentially pops the first available element by doing this: case eh.ch <- eh.queue.read[0]: eh.queue.read[0] = Event{} eh.queue.read = eh.queue.read[1:] So the entry where the event used to exist has been overwritten with a fresh instance of Event which will avoid a memory leak. However the issue is that the underlying slice keeps growing. During a long running test the slice could grow to an unnecessarily length. To avoid this issue, when queue.read is empty and is swapped with queue.write, just before swapping them around the existing queue.read is overwritten with a new slice, freeing up the old potentially long slice. This should help avoid memory leaks. --- js/modules/k6/browser/common/event_emitter.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/js/modules/k6/browser/common/event_emitter.go b/js/modules/k6/browser/common/event_emitter.go index 627baecb45a..6c4114383e2 100644 --- a/js/modules/k6/browser/common/event_emitter.go +++ b/js/modules/k6/browser/common/event_emitter.go @@ -136,6 +136,8 @@ func (e *BaseEventEmitter) emit(event string, data any) { // the read queue until that is again depleted. if len(eh.queue.read) == 0 { eh.queue.writeMutex.Lock() + // Clear the read slice before swapping to prevent keeping references + eh.queue.read = make([]Event, 0) eh.queue.read, eh.queue.write = eh.queue.write, eh.queue.read eh.queue.writeMutex.Unlock() }