From ca733e731fdf83d065bc67d00dc40fbb9a0ad8a1 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Tue, 17 Nov 2026 12:06:59 +0100 Subject: [PATCH] fix(search): run the debounced work once when both timers fire Every pending space has a debounce timer and a timeout timer, and both call the same work function. The function checked for a run in progress before taking the mutex, so when both timers were due together, both calls passed the check and the space was indexed twice at the same time. Take the mutex first and return when the work item is no longer the pending one. This is also what made "fires at the timeout even when continuously debounced" flaky: its two timers are due about 50ms apart, which is close enough on a busy CI runner. --- services/search/pkg/service/event/debouncer.go | 12 +++++++----- .../search/pkg/service/event/debouncer_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/services/search/pkg/service/event/debouncer.go b/services/search/pkg/service/event/debouncer.go index 9d2a10b08c..a815c5d80d 100644 --- a/services/search/pkg/service/event/debouncer.go +++ b/services/search/pkg/service/event/debouncer.go @@ -61,17 +61,19 @@ func (d *SpaceDebouncer) Debounce(id *provider.StorageSpaceId, ack AckFunc, forc wi := &workItem{force: force} wi.work = func() { + d.mutex.Lock() + if d.pending[id.OpaqueId] != wi { + // the debounce timer and the timeout can both fire for the same item + d.mutex.Unlock() + return + } if _, ok := d.inProgress.Load(id.OpaqueId); ok { // Reschedule this run for when the previous run has finished - d.mutex.Lock() - if wi := d.pending[id.OpaqueId]; wi != nil { - wi.t.Reset(d.after) - } + wi.t.Reset(d.after) d.mutex.Unlock() return } - d.mutex.Lock() wi.timeout.Stop() // stop the timeout timer if it is running delete(d.pending, id.OpaqueId) force := wi.force diff --git a/services/search/pkg/service/event/debouncer_test.go b/services/search/pkg/service/event/debouncer_test.go index 1f3d0a19db..eed4111e52 100644 --- a/services/search/pkg/service/event/debouncer_test.go +++ b/services/search/pkg/service/event/debouncer_test.go @@ -115,6 +115,21 @@ var _ = Describe("SpaceDebouncer", func() { }, "300ms").Should(Equal(1)) }) + It("runs once when the debounce timer and the timeout are due together", func() { + debouncer = event.NewSpaceDebouncer(20*time.Millisecond, 20*time.Millisecond, func(id *sprovider.StorageSpaceId, _ bool) { + if id.OpaqueId == "spaceid" { + callCount.Add(1) + } + }, log.NewLogger()) + + for i := 0; i < 10; i++ { + callCount.Store(0) + debouncer.Debounce(spaceid, nil, false) + time.Sleep(60 * time.Millisecond) + Expect(int(callCount.Load())).To(Equal(1), "iteration %d", i) + } + }) + It("doesn't run the timeout function if the work function has been called", func() { debouncer = event.NewSpaceDebouncer(100*time.Millisecond, 250*time.Millisecond, func(id *sprovider.StorageSpaceId, _ bool) { if id.OpaqueId == "spaceid" {