summaryrefslogtreecommitdiffhomepage
path: root/util/latencyqueue/latencyqueue_test.go
blob: dcf4b38d596ca43dab9228993c7551952ed7f2bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause

package latencyqueue

import (
	"context"
	"sync"
	"sync/atomic"
	"testing"
	"testing/synctest"
	"time"
)

func TestBasicEnqueueDequeue(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		processed := make([]int, 0)
		var mu sync.Mutex
		q := New[int](context.Background(), 100*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {
			mu.Lock()
			processed = append(processed, val)
			mu.Unlock()
		})
		defer q.Close()

		q.Enqueue([]int{0, 1, 2, 3, 4})

		barrier := q.Barrier()
		<-barrier

		if err := context.Cause(q.Context()); err != nil {
			t.Errorf("expected no error after successful processing, got %v", err)
		}

		mu.Lock()
		defer mu.Unlock()
		if len(processed) != 5 {
			t.Errorf("expected 5 items processed, got %d", len(processed))
		}
		for i := range 5 {
			if processed[i] != i {
				t.Errorf("expected processed[%d] = %d, got %d", i, i, processed[i])
			}
		}
	})
}

func TestLagThresholdExceeded(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 50*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {
			time.Sleep(30 * time.Millisecond)
		})
		defer q.Close()

		batch := make([]int, 10)
		for i := range batch {
			batch[i] = i
		}
		q.Enqueue(batch)

		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrLagged {
			t.Errorf("expected ErrLagged, got %v", err)
		}
	})
}

func TestFastProcessingNoLag(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		processed := atomic.Int32{}
		q.Start(func(ctx context.Context, val int) {
			processed.Add(1)
		})
		defer q.Close()

		batch := make([]int, 100)
		for i := range batch {
			batch[i] = i
		}
		q.Enqueue(batch)

		barrier := q.Barrier()
		<-barrier

		if err := context.Cause(q.Context()); err != nil {
			t.Errorf("expected no error, got %v", err)
		}

		if processed.Load() != 100 {
			t.Errorf("expected 100 items processed, got %d", processed.Load())
		}
	})
}

func TestMultipleBarriers(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		processed := atomic.Int32{}
		q.Start(func(ctx context.Context, val int) {
			processed.Add(1)
			time.Sleep(5 * time.Millisecond)
		})
		defer q.Close()

		barrier1 := q.Barrier()
		<-barrier1
		count1 := processed.Load()
		if count1 > 0 {
			t.Errorf("barrier1: nothing enqueued before it, but got %d processed", count1)
		}

		q.Enqueue([]int{0, 1, 2, 3, 4})
		barrier2 := q.Barrier()
		<-barrier2
		count2 := processed.Load()
		if count2 < 5 {
			t.Errorf("barrier2: expected at least 5 processed, got %d", count2)
		}

		q.Enqueue([]int{5, 6, 7, 8, 9})
		barrier3 := q.Barrier()
		<-barrier3
		count3 := processed.Load()
		if count3 != 10 {
			t.Errorf("barrier3: expected exactly 10 processed (all items), got %d", count3)
		}
	})
}

func TestCloseStopsProcessing(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		processed := atomic.Int32{}
		q.Start(func(ctx context.Context, val int) {
			processed.Add(1)
			time.Sleep(10 * time.Millisecond)
		})

		batch := make([]int, 1000)
		for i := range batch {
			batch[i] = i
		}
		q.Enqueue(batch)

		time.Sleep(20 * time.Millisecond)
		q.Close()

		processedCount := processed.Load()
		if processedCount >= 1000 {
			t.Error("expected some items to be dropped after close")
		}

		if q.Enqueue([]int{9999}) {
			t.Error("enqueue after close should return false")
		}

		if err := context.Cause(q.Context()); err != ErrClosed {
			t.Errorf("expected ErrClosed, got %v", err)
		}
	})
}

func TestBatchesShareEnqueueTime(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 50*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {
			time.Sleep(10 * time.Millisecond)
		})
		defer q.Close()

		batch := make([]int, 10)
		for i := range batch {
			batch[i] = i
		}
		q.Enqueue(batch)

		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrLagged {
			t.Errorf("expected ErrLagged - batch items share enqueue time, got %v", err)
		}
	})
}

func TestAbortStopsProcessing(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 200*time.Millisecond)

		processed := atomic.Int32{}
		q.Start(func(ctx context.Context, val int) {
			processed.Add(1)
			if val == 3 {
				q.Abort()
			}
			time.Sleep(10 * time.Millisecond)
		})

		q.Enqueue([]int{1, 2, 3, 4, 5})

		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrAborted {
			t.Errorf("expected ErrAborted, got %v", err)
		}

		count := processed.Load()
		if count > 3 {
			t.Errorf("expected at most 3 items processed after abort, got %d", count)
		}
		if count == 0 {
			t.Error("expected at least one item to be processed")
		}
	})
}

func TestConcurrentEnqueuers(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 5*time.Second)

		var processed []int
		var mu sync.Mutex
		q.Start(func(ctx context.Context, val int) {
			mu.Lock()
			processed = append(processed, val)
			mu.Unlock()
		})
		defer q.Close()

		var wg sync.WaitGroup
		wg.Add(2)

		go func() {
			defer wg.Done()
			q.Enqueue([]int{100, 101, 102})
		}()

		go func() {
			defer wg.Done()
			q.Enqueue([]int{200, 201, 202})
		}()

		wg.Wait()
		barrier := q.Barrier()
		<-barrier

		mu.Lock()
		defer mu.Unlock()

		if len(processed) != 6 {
			t.Errorf("expected 6 items, got %d", len(processed))
		}

		has100 := false
		has200 := false
		idx100, idx200 := -1, -1

		for i, v := range processed {
			if v == 100 {
				has100 = true
				idx100 = i
			}
			if v == 200 {
				has200 = true
				idx200 = i
			}
		}

		if !has100 || !has200 {
			t.Fatal("both batches should be processed")
		}

		if idx100+2 < len(processed) {
			if processed[idx100] != 100 || processed[idx100+1] != 101 || processed[idx100+2] != 102 {
				t.Errorf("batch [100,101,102] not in order at position %d", idx100)
			}
		}

		if idx200+2 < len(processed) {
			if processed[idx200] != 200 || processed[idx200+1] != 201 || processed[idx200+2] != 202 {
				t.Errorf("batch [200,201,202] not in order at position %d", idx200)
			}
		}
	})
}

func TestProcessorReceivesContextCancellation(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 50*time.Millisecond)

		processorStarted := make(chan struct{})
		contextCancelledDuringProcessing := atomic.Bool{}

		q.Start(func(ctx context.Context, val int) {
			close(processorStarted)
			for i := 0; i < 10; i++ {
				select {
				case <-ctx.Done():
					contextCancelledDuringProcessing.Store(true)
					return
				default:
					time.Sleep(20 * time.Millisecond)
				}
			}
		})
		defer q.Close()

		q.Enqueue([]int{1, 2, 3})

		<-processorStarted
		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrLagged {
			t.Errorf("expected ErrLagged, got %v", err)
		}

		if !contextCancelledDuringProcessing.Load() {
			t.Error("expected processor to observe context cancellation during processing")
		}
	})
}

func TestProcessorReceivesAbortCancellation(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 500*time.Millisecond)

		processorStarted := make(chan struct{})
		contextCancelledDuringProcessing := atomic.Bool{}

		q.Start(func(ctx context.Context, val int) {
			if val == 1 {
				close(processorStarted)
			}
			for i := 0; i < 10; i++ {
				select {
				case <-ctx.Done():
					contextCancelledDuringProcessing.Store(true)
					return
				default:
					time.Sleep(10 * time.Millisecond)
				}
			}
		})

		q.Enqueue([]int{1, 2, 3, 4, 5})

		<-processorStarted
		q.Abort()
		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrAborted {
			t.Errorf("expected ErrAborted, got %v", err)
		}

		if !contextCancelledDuringProcessing.Load() {
			t.Error("expected processor to observe context cancellation during processing")
		}
	})
}

func TestEnqueueFailsAfterLag(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 30*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {
			time.Sleep(20 * time.Millisecond)
		})
		defer q.Close()

		q.Enqueue([]int{1, 2, 3})

		<-q.Done()

		if q.Enqueue([]int{999}) {
			t.Error("enqueue after lag should return false")
		}

		if err := context.Cause(q.Context()); err != ErrLagged {
			t.Errorf("expected ErrLagged, got %v", err)
		}
	})
}

func TestContextCause(t *testing.T) {
	t.Parallel()
	tests := []struct {
		name      string
		setup     func(*Queue[int])
		expectErr error
	}{
		{
			name: "close",
			setup: func(q *Queue[int]) {
				q.Start(func(ctx context.Context, val int) {})
				q.Close()
			},
			expectErr: ErrClosed,
		},
		{
			name: "abort",
			setup: func(q *Queue[int]) {
				q.Start(func(ctx context.Context, val int) {})
				q.Abort()
				<-q.Done()
			},
			expectErr: ErrAborted,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			synctest.Test(t, func(t *testing.T) {
				q := New[int](context.Background(), 100*time.Millisecond)
				tt.setup(q)

				if err := context.Cause(q.Context()); err != tt.expectErr {
					t.Errorf("expected %v, got %v", tt.expectErr, err)
				}
			})
		})
	}
}

func TestBarrierWithContextDistinction(t *testing.T) {
	t.Parallel()
	tests := []struct {
		name        string
		setup       func(*Queue[int]) <-chan struct{}
		expectErr   error
		description string
	}{
		{
			name: "normal completion",
			setup: func(q *Queue[int]) <-chan struct{} {
				q.Start(func(ctx context.Context, val int) {})
				q.Enqueue([]int{1, 2, 3})
				return q.Barrier()
			},
			expectErr:   nil,
			description: "barrier completes normally when items are processed",
		},
		{
			name: "close",
			setup: func(q *Queue[int]) <-chan struct{} {
				q.Start(func(ctx context.Context, val int) {
					time.Sleep(100 * time.Millisecond)
				})
				q.Enqueue([]int{1, 2, 3, 4, 5})
				b := q.Barrier()
				time.Sleep(10 * time.Millisecond)
				q.Close()
				return b
			},
			expectErr:   ErrClosed,
			description: "barrier released when queue is closed",
		},
		{
			name: "abort",
			setup: func(q *Queue[int]) <-chan struct{} {
				q.Start(func(ctx context.Context, val int) {
					time.Sleep(100 * time.Millisecond)
				})
				q.Enqueue([]int{1, 2, 3, 4, 5})
				b := q.Barrier()
				time.Sleep(10 * time.Millisecond)
				q.Abort()
				return b
			},
			expectErr:   ErrAborted,
			description: "barrier released when queue is aborted",
		},
		{
			name: "lag",
			setup: func(q *Queue[int]) <-chan struct{} {
				q.Start(func(ctx context.Context, val int) {
					time.Sleep(30 * time.Millisecond)
				})
				q.Enqueue([]int{1, 2, 3, 4, 5})
				return q.Barrier()
			},
			expectErr:   ErrLagged,
			description: "barrier released when lag threshold is exceeded",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			synctest.Test(t, func(t *testing.T) {
				var q *Queue[int]
				if tt.name == "lag" {
					q = New[int](context.Background(), 50*time.Millisecond)
				} else {
					q = New[int](context.Background(), 5*time.Second)
				}
				defer q.Close()

				barrier := tt.setup(q)
				<-barrier

				if err := context.Cause(q.Context()); err != tt.expectErr {
					t.Errorf("%s: expected %v, got %v", tt.description, tt.expectErr, err)
				}
			})
		})
	}
}

func TestFirstStopWins(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {})

		q.Abort()
		q.Close()

		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrAborted {
			t.Errorf("expected ErrAborted (first error wins), got %v", err)
		}
	})
}

func TestMultipleCloseCallsSafe(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {})

		q.Close()
		q.Close()

		if err := context.Cause(q.Context()); err != ErrClosed {
			t.Errorf("expected ErrClosed, got %v", err)
		}
	})
}

func TestMultipleAbortCallsSafe(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 100*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {})

		q.Abort()
		q.Abort()
		q.Abort()

		<-q.Done()

		if err := context.Cause(q.Context()); err != ErrAborted {
			t.Errorf("expected ErrAborted, got %v", err)
		}
	})
}

func TestCounters(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 500*time.Millisecond)

		processed := make(chan struct{}, 10)
		q.Start(func(ctx context.Context, val int) {
			time.Sleep(5 * time.Millisecond)
			processed <- struct{}{}
		})
		defer q.Close()

		q.Enqueue([]int{1, 2, 3})

		counters := q.Counters()
		if counters.Enqueued != 3 {
			t.Errorf("expected 3 enqueued, got %d", counters.Enqueued)
		}

		q.Enqueue([]int{4, 5})

		counters = q.Counters()
		if counters.Enqueued != 5 {
			t.Errorf("expected 5 enqueued total, got %d", counters.Enqueued)
		}

		<-processed
		<-processed

		counters = q.Counters()
		if counters.Processed < 2 {
			t.Errorf("expected at least 2 processed, got %d", counters.Processed)
		}
		if counters.Processed > counters.Enqueued {
			t.Errorf("processed (%d) cannot exceed enqueued (%d)", counters.Processed, counters.Enqueued)
		}

		barrier := q.Barrier()
		<-barrier

		counters = q.Counters()
		if counters.Enqueued != 5 {
			t.Errorf("expected 5 enqueued total, got %d", counters.Enqueued)
		}
		if counters.Processed != 5 {
			t.Errorf("expected 5 processed, got %d", counters.Processed)
		}
	})
}

func TestPanicRecovery(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 500*time.Millisecond)

		q.Start(func(ctx context.Context, val int) {
			if val == 2 {
				panic("test panic")
			}
		})

		q.Enqueue([]int{1, 2, 3})

		<-q.Done()

		err := context.Cause(q.Context())
		if err == nil {
			t.Fatal("expected panic error, got nil")
		}

		panicErr, ok := err.(*ErrPanic)
		if !ok {
			t.Fatalf("expected *ErrPanic, got %T: %v", err, err)
		}

		if panicErr.Panic != "test panic" {
			t.Errorf("expected panic value 'test panic', got %v", panicErr.Panic)
		}
	})
}

func TestContextPropagation(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		parentCtx, parentCancel := context.WithCancel(context.Background())
		defer parentCancel()

		q := New[int](parentCtx, 500*time.Millisecond)

		var receivedCtx context.Context
		var mu sync.Mutex
		q.Start(func(ctx context.Context, val int) {
			mu.Lock()
			receivedCtx = ctx
			mu.Unlock()
			time.Sleep(10 * time.Millisecond)
		})
		defer q.Close()

		q.Enqueue([]int{1})
		time.Sleep(5 * time.Millisecond)

		mu.Lock()
		ctx := receivedCtx
		mu.Unlock()

		if ctx == nil {
			t.Fatal("expected context to be passed to processor")
		}

		parentCancel()
		<-q.Done()

		if err := q.Context().Err(); err != context.Canceled {
			t.Errorf("expected context.Canceled when parent cancelled, got %v", err)
		}
	})
}

func TestZeroMaxLag(t *testing.T) {
	t.Parallel()
	synctest.Test(t, func(t *testing.T) {
		q := New[int](context.Background(), 0)

		processed := atomic.Int32{}
		q.Start(func(ctx context.Context, val int) {
			processed.Add(1)
			time.Sleep(10 * time.Millisecond)
		})
		defer q.Close()

		q.Enqueue([]int{1, 2, 3})
		barrier := q.Barrier()
		<-barrier

		if processed.Load() != 3 {
			t.Errorf("expected 3 items processed with zero maxLag, got %d", processed.Load())
		}

		if err := context.Cause(q.Context()); err != nil {
			t.Errorf("expected no error with zero maxLag, got %v", err)
		}
	})
}

// BenchmarkVariableLoad tests memory efficiency under variable load patterns.
// The ringbuffer-based implementation should efficiently handle:
// - Bursts of enqueues followed by processing
// - Growing and shrinking queue sizes
// - Memory compaction during idle periods
func BenchmarkVariableLoad(b *testing.B) {
	q := New[int](context.Background(), 10*time.Second)

	processed := atomic.Int64{}
	q.Start(func(ctx context.Context, val int) {
		processed.Add(1)
		// Simulate some processing time
		time.Sleep(10 * time.Microsecond)
	})
	defer q.Close()

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		// Simulate bursty traffic - enqueue in batches
		batchSize := 10 + (i % 50) // Variable batch sizes from 10-59
		batch := make([]int, batchSize)
		for j := range batch {
			batch[j] = i*100 + j
		}
		q.Enqueue(batch)

		// Occasionally wait for processing to catch up
		if i%100 == 99 {
			barrier := q.Barrier()
			<-barrier
		}
	}

	// Final barrier to ensure all items are processed
	barrier := q.Barrier()
	<-barrier

	b.ReportMetric(float64(processed.Load()), "items")
}

// BenchmarkSteadyState tests performance under steady-state conditions.
func BenchmarkSteadyState(b *testing.B) {
	q := New[int](context.Background(), 10*time.Second)

	q.Start(func(ctx context.Context, val int) {
		// Fast processing
	})
	defer q.Close()

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		q.Enqueue([]int{i})
	}

	barrier := q.Barrier()
	<-barrier
}

// BenchmarkBurstThenDrain tests memory efficiency in burst-then-drain scenarios.
// This pattern exposes inefficiencies in slice-based implementations where
// the underlying array never shrinks. The ringbuffer should compact efficiently.
func BenchmarkBurstThenDrain(b *testing.B) {
	q := New[int](context.Background(), 10*time.Second)

	processDelay := atomic.Bool{}
	q.Start(func(ctx context.Context, val int) {
		if processDelay.Load() {
			time.Sleep(100 * time.Microsecond)
		}
	})
	defer q.Close()

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		// Burst phase: enqueue many items with slow processing
		processDelay.Store(true)
		largeBatch := make([]int, 1000)
		for j := range largeBatch {
			largeBatch[j] = i*1000 + j
		}
		q.Enqueue(largeBatch)

		// Let queue fill up a bit
		time.Sleep(500 * time.Microsecond)

		// Drain phase: speed up processing
		processDelay.Store(false)
		barrier := q.Barrier()
		<-barrier

		// Allow time for compaction to potentially occur
		time.Sleep(100 * time.Microsecond)
	}
}