-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathengine_gas_test.go
More file actions
256 lines (217 loc) · 7.95 KB
/
engine_gas_test.go
File metadata and controls
256 lines (217 loc) · 7.95 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
package scheduler_test
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"github.com/storacha/piri/pkg/pdp/scheduler"
"github.com/storacha/piri/pkg/pdp/service/models"
)
// TestTaskEngineGasTooHighDoesNotIncrementRetries tests AC2: when a task returns
// ErrGasTooHigh, the handler requeues the task WITHOUT incrementing the retry counter.
//
// Scenario: MaxFailures=2, task returns ErrGasTooHigh 3 times then succeeds.
// If gas deferrals counted as failures, the task would be killed after 2 failures.
// Since they don't count, the task should survive and eventually succeed.
func TestTaskEngineGasTooHighDoesNotIncrementRetries(t *testing.T) {
db := setupTestDB(t)
gasFailures := 3 // Number of times to return ErrGasTooHigh before succeeding
var mu sync.Mutex
attempts := make(map[scheduler.TaskID]int)
mockTask := NewMockTask("test_task", false)
mockTask.typeDetails.MaxFailures = 2 // Less than gasFailures — would kill if counted
mockTask.doFunc = func(taskID scheduler.TaskID) (bool, error) {
mu.Lock()
attempt := attempts[taskID]
attempts[taskID] = attempt + 1
mu.Unlock()
if attempt < gasFailures {
return false, scheduler.ErrGasTooHigh
}
// Succeed on the 4th attempt
return true, nil
}
engine, err := scheduler.NewEngine(db, []scheduler.TaskInterface{mockTask})
require.NoError(t, err)
err = engine.Start(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
if err := engine.Stop(context.Background()); err != nil {
t.Logf("failed to stop engine: %v", err)
}
})
mockTask.WaitForReady()
// Add one task
mockTask.AddTask(func(tID scheduler.TaskID, tx *gorm.DB) (bool, error) {
return true, nil
})
// Wait for the task to eventually succeed (should take gasFailures+1 attempts)
assert.Eventually(t, func() bool {
mu.Lock()
defer mu.Unlock()
for _, count := range attempts {
if count >= gasFailures+1 {
return true
}
}
return false
}, 30*time.Second, 100*time.Millisecond,
fmt.Sprintf("Task should be attempted at least %d times", gasFailures+1))
// Small delay to ensure final database updates are complete
time.Sleep(500 * time.Millisecond)
// Task should be deleted (completed successfully)
var taskCount int64
db.Model(&models.Task{}).Where("name = ?", "test_task").Count(&taskCount)
assert.Equal(t, int64(0), taskCount, "Task should be deleted after successful completion")
// The task should have a successful completion in history
var histories []models.TaskHistory
require.NoError(t, db.Where("name = ?", "test_task").Order("work_start ASC").Find(&histories).Error)
// We expect gasFailures+1 history entries total
require.Len(t, histories, gasFailures+1,
"should have %d history entries (3 gas deferrals + 1 success)", gasFailures+1)
// The last entry should be successful
lastHistory := histories[len(histories)-1]
assert.True(t, lastHistory.Result, "last attempt should succeed")
assert.Empty(t, lastHistory.Err, "last attempt should have no error")
}
// TestTaskEngineGasTooHighRetryCounterNotIncremented tests AC2 more directly:
// verify that the retry counter in the task table is NOT incremented when
// ErrGasTooHigh is returned.
func TestTaskEngineGasTooHighRetryCounterNotIncremented(t *testing.T) {
db := setupTestDB(t)
var mu sync.Mutex
attempts := make(map[scheduler.TaskID]int)
// Use a channel to control when we check the DB state
gasReturned := make(chan struct{}, 10)
mockTask := NewMockTask("test_task", false)
mockTask.typeDetails.MaxFailures = 5
mockTask.doFunc = func(taskID scheduler.TaskID) (bool, error) {
mu.Lock()
attempt := attempts[taskID]
attempts[taskID] = attempt + 1
mu.Unlock()
if attempt < 3 {
gasReturned <- struct{}{}
return false, scheduler.ErrGasTooHigh
}
return true, nil
}
engine, err := scheduler.NewEngine(db, []scheduler.TaskInterface{mockTask})
require.NoError(t, err)
err = engine.Start(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
if err := engine.Stop(context.Background()); err != nil {
t.Logf("failed to stop engine: %v", err)
}
})
mockTask.WaitForReady()
mockTask.AddTask(func(tID scheduler.TaskID, tx *gorm.DB) (bool, error) {
return true, nil
})
// Wait for at least one gas deferral to happen
select {
case <-gasReturned:
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for gas deferral")
}
// Give the handler time to process
time.Sleep(200 * time.Millisecond)
// Check that retry counter was NOT incremented
var task models.Task
result := db.Where("name = ?", "test_task").First(&task)
if result.Error == nil {
// Task still exists (hasn't completed yet)
assert.Equal(t, uint(0), task.Retries,
"retry counter should NOT be incremented for ErrGasTooHigh")
}
// If the task already completed, that's also fine - it wasn't killed by MaxFailures
}
// TestTaskEngineGasTooHighVsRealFailure tests that ErrGasTooHigh and real failures
// are handled differently. Real failures increment retries; gas deferrals do not.
//
// MaxFailures=1 means the task is killed after 1 real-failure retry. The handler
// checks `retries >= MaxFailures` BEFORE incrementing, so the sequence is:
//
// attempt 0: gas -> retries stays 0
// attempt 1: gas -> retries stays 0
// attempt 2: real -> retries 0->1 (check 0>=1 false, requeue)
// attempt 3: real -> check 1>=1 true, killed
//
// Total: 4 attempts, all non-successful.
func TestTaskEngineGasTooHighVsRealFailure(t *testing.T) {
db := setupTestDB(t)
var mu sync.Mutex
attempts := make(map[scheduler.TaskID]int)
mockTask := NewMockTask("test_task", false)
mockTask.typeDetails.MaxFailures = 1
mockTask.doFunc = func(taskID scheduler.TaskID) (bool, error) {
mu.Lock()
attempt := attempts[taskID]
attempts[taskID] = attempt + 1
mu.Unlock()
switch attempt {
case 0:
// First: gas too high (should NOT count as failure)
return false, scheduler.ErrGasTooHigh
case 1:
// Second: gas too high again (should NOT count as failure)
return false, scheduler.ErrGasTooHigh
case 2:
// Third: real failure (SHOULD count as failure, retry #1)
return false, fmt.Errorf("real error")
case 3:
// Fourth: real failure — but killed before requeue since retries(1) >= MaxFailures(1)
return false, fmt.Errorf("real error again")
default:
// Should not reach here — MaxFailures=1 kills the task after attempt 3
return true, nil
}
}
engine, err := scheduler.NewEngine(db, []scheduler.TaskInterface{mockTask})
require.NoError(t, err)
err = engine.Start(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
if err := engine.Stop(context.Background()); err != nil {
t.Logf("failed to stop engine: %v", err)
}
})
mockTask.WaitForReady()
mockTask.AddTask(func(tID scheduler.TaskID, tx *gorm.DB) (bool, error) {
return true, nil
})
// Wait for enough attempts
assert.Eventually(t, func() bool {
mu.Lock()
defer mu.Unlock()
for _, count := range attempts {
// We expect at least 4 attempts:
// 2 gas deferrals (no retry increment) + 2 real failures (retries incremented)
// After retry #1 with MaxFailures=1, task should be killed
if count >= 4 {
return true
}
}
return false
}, 30*time.Second, 100*time.Millisecond)
// Wait for handler to finish processing
time.Sleep(500 * time.Millisecond)
// Task should be deleted (killed after MaxFailures real failures)
var taskCount int64
db.Model(&models.Task{}).Where("name = ?", "test_task").Count(&taskCount)
assert.Equal(t, int64(0), taskCount,
"Task should be deleted after exceeding real failure max")
// Verify history: should have 4 entries (2 gas + 2 real failures)
var histories []models.TaskHistory
require.NoError(t, db.Where("name = ?", "test_task").Order("work_start ASC").Find(&histories).Error)
require.Len(t, histories, 4, "should have 4 history entries total")
// None of the history entries should show as "done" (all were failures/deferrals)
for _, h := range histories {
assert.False(t, h.Result, "no attempt should have succeeded")
}
}