Repository navigation
Expand file tree
/
Copy pathtask_buffer_test.go
More file actions
419 lines (372 loc) · 12.5 KB
/
Copy pathtask_buffer_test.go
File metadata and controls
419 lines (372 loc) · 12.5 KB
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
// These white-box tests exercise chunkedTaskBuffer directly so its internal
// chunk boundaries, capacity limit, and locking behavior can be verified.
package agilepool
import (
"sync"
"sync/atomic"
"testing"
)
type bufferTestTask struct {
id int
}
// process is intentionally empty: the buffer stores and forwards tasks but
// never executes them. The id is the only state needed by these tests.
func (bufferTestTask) process() {}
// fillTaskBuffer constructs an exact FIFO state without exercising
// PushAndForward. pushTail requires its caller to hold taskMu.
func fillTaskBuffer(tb testing.TB, buffer *chunkedTaskBuffer, start, count int) {
tb.Helper()
buffer.taskMu.Lock()
defer buffer.taskMu.Unlock()
for i := 0; i < count; i++ {
buffer.pushTail(bufferTestTask{id: start + i})
}
}
// fillTaskBufferWithTask efficiently creates large states, such as a full
// buffer, when individual task identities are irrelevant.
func fillTaskBufferWithTask(tb testing.TB, buffer *chunkedTaskBuffer, task Task, count int) {
tb.Helper()
buffer.taskMu.Lock()
defer buffer.taskMu.Unlock()
for i := 0; i < count; i++ {
buffer.pushTail(task)
}
}
// drainTaskBuffer uses a deliberately non-chunk-sized batch so draining covers
// repeated PopBatch calls as well as chunk transitions.
func drainTaskBuffer(buffer *chunkedTaskBuffer) []Task {
const batchSize = 257
batch := make([]Task, batchSize)
var tasks []Task
for {
n := buffer.PopBatch(batch)
if n == 0 {
return tasks
}
tasks = append(tasks, batch[:n]...)
}
}
// bufferTaskID also verifies that the buffer returns the original concrete
// task type rather than replacing or wrapping it.
func bufferTaskID(tb testing.TB, task Task) int {
tb.Helper()
testTask, ok := task.(bufferTestTask)
if !ok {
tb.Fatalf("task has type %T, want bufferTestTask", task)
}
return testTask.id
}
// assertTaskIDs checks both task conservation and FIFO order.
func assertTaskIDs(tb testing.TB, tasks []Task, want []int) {
tb.Helper()
if len(tasks) != len(want) {
tb.Fatalf("got %d tasks, want %d", len(tasks), len(want))
}
for i, task := range tasks {
if got := bufferTaskID(tb, task); got != want[i] {
tb.Fatalf("task %d has id %d, want %d", i, got, want[i])
}
}
}
// TestChunkedTaskBufferPushAndForward covers the successful fast path and the
// failed-forward path, both with and without an existing backlog.
func TestChunkedTaskBufferPushAndForward(t *testing.T) {
t.Run("empty buffer forwards the submitted task", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
callbackCalls := 0
forwardedID := -1
result := buffer.PushAndForward(bufferTestTask{id: 1}, func(task Task) bool {
callbackCalls++
forwardedID = bufferTaskID(t, task)
return true
})
if result != taskBufferAccepted {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferAccepted)
}
if callbackCalls != 1 {
t.Fatalf("forward callback called %d times, want 1", callbackCalls)
}
if forwardedID != 1 {
t.Fatalf("forwarded task id = %d, want 1", forwardedID)
}
if got := buffer.Len(); got != 0 {
t.Fatalf("Len() = %d, want 0", got)
}
})
t.Run("failed forward requeues the task", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
callbackCalls := 0
result := buffer.PushAndForward(bufferTestTask{id: 2}, func(task Task) bool {
callbackCalls++
if got := bufferTaskID(t, task); got != 2 {
t.Fatalf("forwarded task id = %d, want 2", got)
}
return false
})
if result != taskBufferAccepted {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferAccepted)
}
if callbackCalls != 1 {
t.Fatalf("forward callback called %d times, want 1", callbackCalls)
}
if got := buffer.Len(); got != 1 {
t.Fatalf("Len() = %d, want 1", got)
}
batch := make([]Task, 1)
if n := buffer.PopBatch(batch); n != 1 {
t.Fatalf("PopBatch() = %d, want 1", n)
}
assertTaskIDs(t, batch, []int{2})
})
t.Run("backlog forward succeeds without losing tasks", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
fillTaskBuffer(t, buffer, 1, 2)
callbackCalls := 0
forwardedID := -1
result := buffer.PushAndForward(bufferTestTask{id: 3}, func(task Task) bool {
callbackCalls++
forwardedID = bufferTaskID(t, task)
return true
})
if result != taskBufferAccepted {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferAccepted)
}
if callbackCalls != 1 {
t.Fatalf("forward callback called %d times, want 1", callbackCalls)
}
if forwardedID != 1 {
t.Fatalf("forwarded task id = %d, want oldest task 1", forwardedID)
}
assertTaskIDs(t, drainTaskBuffer(buffer), []int{2, 3})
})
t.Run("backlog forward failure preserves FIFO order", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
fillTaskBuffer(t, buffer, 1, 2)
callbackCalls := 0
forwardedID := -1
result := buffer.PushAndForward(bufferTestTask{id: 3}, func(task Task) bool {
callbackCalls++
forwardedID = bufferTaskID(t, task)
return false
})
if result != taskBufferAccepted {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferAccepted)
}
if callbackCalls != 1 {
t.Fatalf("forward callback called %d times, want 1", callbackCalls)
}
if forwardedID != 1 {
t.Fatalf("forwarded task id = %d, want oldest task 1", forwardedID)
}
// taskQueue is still full, so the oldest task must stay at the head
// rather than being requeued behind newer tasks.
assertTaskIDs(t, drainTaskBuffer(buffer), []int{1, 2, 3})
})
}
// TestChunkedTaskBufferPopBatch verifies batch sizing, FIFO behavior across a
// chunk boundary, and reuse after all chunks have been consumed.
func TestChunkedTaskBufferPopBatch(t *testing.T) {
t.Run("empty and empty destination", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
if n := buffer.PopBatch(nil); n != 0 {
t.Fatalf("PopBatch(nil) = %d, want 0", n)
}
if n := buffer.PopBatch(make([]Task, 0)); n != 0 {
t.Fatalf("PopBatch(empty) = %d, want 0", n)
}
if n := buffer.PopBatch(make([]Task, 1)); n != 0 {
t.Fatalf("PopBatch() on empty buffer = %d, want 0", n)
}
})
for _, tc := range []struct {
name string
taskCount int
batchSize int
wantCount int
}{
{name: "batch smaller than buffer", taskCount: 3, batchSize: 2, wantCount: 2},
{name: "batch equals buffer", taskCount: 3, batchSize: 3, wantCount: 3},
{name: "batch larger than buffer", taskCount: 3, batchSize: 5, wantCount: 3},
} {
t.Run(tc.name, func(t *testing.T) {
buffer := newChunkedTaskBuffer()
fillTaskBuffer(t, buffer, 0, tc.taskCount)
batch := make([]Task, tc.batchSize)
n := buffer.PopBatch(batch)
if n != tc.wantCount {
t.Fatalf("PopBatch() = %d, want %d", n, tc.wantCount)
}
for i := 0; i < n; i++ {
if got := bufferTaskID(t, batch[i]); got != i {
t.Fatalf("task %d has id %d, want %d", i, got, i)
}
}
if got, want := buffer.Len(), int64(tc.taskCount-tc.wantCount); got != want {
t.Fatalf("Len() = %d, want %d", got, want)
}
})
}
t.Run("crosses a chunk boundary in FIFO order", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
// Read seven tasks from the second chunk and leave ten behind. This
// catches index-reset errors while advancing from one chunk to the next.
const tailCount = 17
const remaining = 10
taskCount := taskChunkSize + tailCount
batchSize := taskCount - remaining
fillTaskBuffer(t, buffer, 0, taskCount)
batch := make([]Task, batchSize)
n := buffer.PopBatch(batch)
if n != batchSize {
t.Fatalf("PopBatch() = %d, want %d", n, batchSize)
}
for i, task := range batch {
if got := bufferTaskID(t, task); got != i {
t.Fatalf("task %d has id %d, want %d", i, got, i)
}
}
if got := buffer.Len(); got != remaining {
t.Fatalf("Len() = %d, want %d", got, remaining)
}
})
t.Run("buffer is reusable after being drained", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
firstCount := taskChunkSize + 1
fillTaskBuffer(t, buffer, 0, firstCount)
// The extra destination slot makes PopBatch attempt one more pop after
// the last task, exercising the empty-buffer cleanup path.
firstBatch := make([]Task, firstCount+1)
if n := buffer.PopBatch(firstBatch); n != firstCount {
t.Fatalf("first PopBatch() = %d, want %d", n, firstCount)
}
if got := buffer.Len(); got != 0 {
t.Fatalf("Len() after drain = %d, want 0", got)
}
fillTaskBuffer(t, buffer, 100, 3)
secondBatch := make([]Task, 3)
if n := buffer.PopBatch(secondBatch); n != len(secondBatch) {
t.Fatalf("second PopBatch() = %d, want %d", n, len(secondBatch))
}
assertTaskIDs(t, secondBatch, []int{100, 101, 102})
})
}
// TestChunkedTaskBufferCloseAndFull verifies rejection precedence without
// discarding tasks that were accepted before Close.
func TestChunkedTaskBufferCloseAndFull(t *testing.T) {
t.Run("close is idempotent and accepted tasks remain drainable", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
fillTaskBuffer(t, buffer, 10, 2)
buffer.Close()
buffer.Close()
callbackCalls := 0
result := buffer.PushAndForward(bufferTestTask{id: 12}, func(Task) bool {
callbackCalls++
return true
})
if result != taskBufferClosed {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferClosed)
}
if callbackCalls != 0 {
t.Fatalf("forward callback called %d times, want 0", callbackCalls)
}
if got := buffer.Len(); got != 2 {
t.Fatalf("Len() = %d, want 2", got)
}
assertTaskIDs(t, drainTaskBuffer(buffer), []int{10, 11})
})
t.Run("full buffer rejects before forwarding", func(t *testing.T) {
buffer := newChunkedTaskBuffer()
fillTaskBufferWithTask(t, buffer, bufferTestTask{id: 1}, maxChunkLen)
callbackCalls := 0
forward := func(Task) bool {
callbackCalls++
return true
}
if result := buffer.PushAndForward(bufferTestTask{id: 2}, forward); result != taskBufferFull {
t.Fatalf("PushAndForward() = %v, want %v", result, taskBufferFull)
}
if callbackCalls != 0 {
t.Fatalf("forward callback called %d times, want 0", callbackCalls)
}
if got := buffer.Len(); got != maxChunkLen {
t.Fatalf("Len() = %d, want %d", got, maxChunkLen)
}
// Closed is checked before full in PushAndForward, so a buffer in both
// states must report taskBufferClosed.
buffer.Close()
if result := buffer.PushAndForward(bufferTestTask{id: 3}, forward); result != taskBufferClosed {
t.Fatalf("PushAndForward() on closed full buffer = %v, want %v", result, taskBufferClosed)
}
if callbackCalls != 0 {
t.Fatalf("forward callback called %d times, want 0", callbackCalls)
}
})
}
// TestChunkedTaskBufferConcurrentPush is a race-detector target. It checks
// conservation and uniqueness rather than ordering because producer lock
// acquisition order is intentionally nondeterministic.
func TestChunkedTaskBufferConcurrentPush(t *testing.T) {
const (
producerCount = 8
tasksPerProducer = 1000
totalTasks = producerCount * tasksPerProducer
)
buffer := newChunkedTaskBuffer()
var accepted atomic.Int64
var callbackCalls atomic.Int64
var unexpectedResults atomic.Int64
var producers sync.WaitGroup
for producer := 0; producer < producerCount; producer++ {
producers.Add(1)
go func(producer int) {
defer producers.Done()
start := producer * tasksPerProducer
for i := 0; i < tasksPerProducer; i++ {
// Reject forwarding so every accepted task remains in the buffer
// until the single-threaded verification phase below.
result := buffer.PushAndForward(bufferTestTask{id: start + i}, func(Task) bool {
callbackCalls.Add(1)
return false
})
if result == taskBufferAccepted {
accepted.Add(1)
} else {
unexpectedResults.Add(1)
}
}
}(producer)
}
producers.Wait()
if got := unexpectedResults.Load(); got != 0 {
t.Fatalf("got %d unexpected push results", got)
}
if got := accepted.Load(); got != totalTasks {
t.Fatalf("accepted %d tasks, want %d", got, totalTasks)
}
if got := callbackCalls.Load(); got != totalTasks {
t.Fatalf("forward callback called %d times, want %d", got, totalTasks)
}
tasks := drainTaskBuffer(buffer)
if len(tasks) != totalTasks {
t.Fatalf("drained %d tasks, want %d", len(tasks), totalTasks)
}
seen := make([]bool, totalTasks)
for _, task := range tasks {
id := bufferTaskID(t, task)
if id < 0 || id >= totalTasks {
t.Fatalf("task id %d is outside [0, %d)", id, totalTasks)
}
if seen[id] {
t.Fatalf("task id %d was drained more than once", id)
}
seen[id] = true
}
for id, wasSeen := range seen {
if !wasSeen {
t.Fatalf("task id %d was not drained", id)
}
}
if got := buffer.Len(); got != 0 {
t.Fatalf("Len() = %d after drain, want 0", got)
}
}