-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_multiprocess_integration_test.go
More file actions
378 lines (306 loc) · 9.67 KB
/
process_multiprocess_integration_test.go
File metadata and controls
378 lines (306 loc) · 9.67 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
//go:build integration
package comet
import (
"context"
"fmt"
"os"
"os/exec"
"strconv"
"sync"
"testing"
"time"
)
// TestProcessMultiProcessIntegration tests Process() with actual OS processes
func TestProcessMultiProcessIntegration(t *testing.T) {
if testing.Short() {
t.Skip("skipping multi-process integration test in short mode")
}
dir := t.TempDir()
totalMessages := 200
batchSize := 25
numWorkers := 3
stream := "multiproc:v1:shard:0000"
// Step 1: Write test data using main process
t.Logf("Writing %d messages to %s", totalMessages, stream)
config := DeprecatedMultiProcessConfig(0, 2)
client, err := NewClient(dir, config)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
var messages [][]byte
for i := 0; i < totalMessages; i++ {
messages = append(messages, []byte(fmt.Sprintf("multiproc-msg-%04d", i)))
}
_, err = client.Append(ctx, stream, messages)
if err != nil {
t.Fatal(err)
}
// Sync to ensure messages are durable
if err := client.Sync(ctx); err != nil {
t.Fatal(err)
}
client.Close()
// Verify data was written
client2, err := NewClient(dir, config)
if err != nil {
t.Fatal(err)
}
length, err := client2.Len(ctx, stream)
if err != nil {
t.Fatal(err)
}
client2.Close()
if length != int64(totalMessages) {
t.Fatalf("Expected %d messages written, got %d", totalMessages, length)
}
t.Logf("Verified %d messages written", length)
// Step 2: Launch multiple worker processes
t.Logf("Launching %d worker processes", numWorkers)
var wg sync.WaitGroup
results := make(chan workerResult, numWorkers)
for workerID := 0; workerID < numWorkers; workerID++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
// Launch worker process
cmd := exec.Command("go", "test", "-run", "TestMultiProcessWorker",
"-timeout", "30s", "-v")
cmd.Env = append(os.Environ(),
fmt.Sprintf("COMET_TEST_DATA_DIR=%s", dir),
fmt.Sprintf("COMET_TEST_WORKER_ID=%d", id),
fmt.Sprintf("COMET_TEST_BATCH_SIZE=%d", batchSize),
fmt.Sprintf("COMET_TEST_STREAM=%s", stream),
)
output, err := cmd.CombinedOutput()
results <- workerResult{
workerID: id,
output: string(output),
err: err,
}
}(workerID)
}
// Wait for all workers to complete (with timeout)
done := make(chan struct{})
go func() {
wg.Wait()
close(results)
close(done)
}()
select {
case <-done:
// All workers completed
case <-time.After(25 * time.Second):
t.Fatal("Workers timed out")
}
// Step 3: Collect and analyze results
var successfulWorkers int
for result := range results {
if result.err != nil {
t.Logf("Worker %d failed: %v", result.workerID, result.err)
t.Logf("Worker %d output:\n%s", result.workerID, result.output)
} else {
successfulWorkers++
// Parse processed count from output (workers will log it)
// This is a simple approach - in production you'd use structured logging
t.Logf("Worker %d completed successfully", result.workerID)
t.Logf("Worker %d output:\n%s", result.workerID, result.output)
}
}
// Step 4: Verify final state
t.Logf("Integration test completed: %d/%d workers successful", successfulWorkers, numWorkers)
if successfulWorkers == 0 {
t.Fatal("No workers completed successfully")
}
// Verify that data is still accessible and consistent
client3, err := NewClient(dir, config)
if err != nil {
t.Fatal(err)
}
defer client3.Close()
finalLength, err := client3.Len(ctx, stream)
if err != nil {
t.Fatal(err)
}
if finalLength != int64(totalMessages) {
t.Errorf("Data integrity check failed: expected %d messages, got %d", totalMessages, finalLength)
}
t.Logf("✅ Multi-process integration test passed with %d successful workers", successfulWorkers)
}
// TestMultiProcessWorker is the worker process entry point
// This runs in separate OS processes spawned by TestProcessMultiProcessIntegration
func TestMultiProcessWorker(t *testing.T) {
// Only run when called as a worker process
dataDir := os.Getenv("COMET_TEST_DATA_DIR")
if dataDir == "" {
t.Skip("Not running as multi-process worker")
}
workerIDStr := os.Getenv("COMET_TEST_WORKER_ID")
batchSizeStr := os.Getenv("COMET_TEST_BATCH_SIZE")
_ = os.Getenv("COMET_TEST_STREAM") // stream not used in worker test
workerID, _ := strconv.Atoi(workerIDStr)
batchSize, _ := strconv.Atoi(batchSizeStr)
t.Logf("Worker %d starting: dataDir=%s, batchSize=%d",
workerID, dataDir, batchSize)
// Initialize client in multi-process mode
config := DeprecatedMultiProcessConfig(0, 2)
client, err := NewClient(dataDir, config)
if err != nil {
t.Fatalf("Worker %d failed to create client: %v", workerID, err)
}
defer client.Close()
// Create consumer with unique group for this worker
consumer := NewConsumer(client, ConsumerOptions{
Group: fmt.Sprintf("worker-%d", workerID),
})
defer consumer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
processedCount := 0
batchCount := 0
processFunc := func(ctx context.Context, msgs []StreamMessage) error {
batchCount++
processedCount += len(msgs)
t.Logf("Worker %d: Batch %d processed %d messages (total: %d)",
workerID, batchCount, len(msgs), processedCount)
// Simulate some processing work
time.Sleep(10 * time.Millisecond)
// Stop after processing a reasonable amount or timeout
if processedCount >= 50 || batchCount >= 10 {
t.Logf("Worker %d: Stopping after processing %d messages in %d batches",
workerID, processedCount, batchCount)
cancel()
}
return nil
}
// Start processing
err = consumer.Process(ctx, processFunc,
WithStream("multiproc:v1:shard:*"),
WithBatchSize(batchSize),
WithAutoAck(true),
WithPollInterval(100*time.Millisecond),
)
t.Logf("Worker %d final results: processed %d messages in %d batches",
workerID, processedCount, batchCount)
// Success criteria: must process at least some messages
if processedCount == 0 {
t.Fatalf("Worker %d processed 0 messages - Process() may have failed", workerID)
}
if batchCount == 0 {
t.Fatalf("Worker %d had 0 batches - Process() may have failed", workerID)
}
t.Logf("✅ Worker %d completed successfully", workerID)
}
// TestProcessMultiProcessContention tests multiple processes competing for the same data
func TestProcessMultiProcessContention(t *testing.T) {
if testing.Short() {
t.Skip("skipping multi-process contention test in short mode")
}
dir := t.TempDir()
totalMessages := 100
stream := "contention:v1:shard:0042"
// Write test data
config := DeprecatedMultiProcessConfig(0, 2)
client, err := NewClient(dir, config)
if err != nil {
t.Fatal(err)
}
var messages [][]byte
for i := 0; i < totalMessages; i++ {
messages = append(messages, []byte(fmt.Sprintf("contention-msg-%04d", i)))
}
ctx := context.Background()
_, err = client.Append(ctx, stream, messages)
if err != nil {
t.Fatal(err)
}
client.Close()
// Launch 2 competing processes with the same consumer group
// This tests that multi-process coordination works correctly
var wg sync.WaitGroup
results := make(chan workerResult, 2)
for workerID := 0; workerID < 2; workerID++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
cmd := exec.Command("go", "test", "-run", "TestMultiProcessContentionWorker",
"-timeout", "20s", "-v")
cmd.Env = append(os.Environ(),
fmt.Sprintf("COMET_TEST_DATA_DIR=%s", dir),
fmt.Sprintf("COMET_TEST_WORKER_ID=%d", id),
fmt.Sprintf("COMET_TEST_STREAM=%s", stream),
)
output, err := cmd.CombinedOutput()
results <- workerResult{
workerID: id,
output: string(output),
err: err,
}
}(workerID)
}
go func() {
wg.Wait()
close(results)
}()
// Collect results
successCount := 0
for result := range results {
if result.err != nil {
t.Logf("Contention worker %d failed: %v", result.workerID, result.err)
t.Logf("Output:\n%s", result.output)
} else {
successCount++
t.Logf("Contention worker %d succeeded", result.workerID)
}
}
if successCount < 1 {
t.Fatal("No contention workers completed successfully")
}
t.Logf("✅ Multi-process contention test passed with %d successful workers", successCount)
}
// TestMultiProcessContentionWorker runs competing workers with same consumer group
func TestMultiProcessContentionWorker(t *testing.T) {
dataDir := os.Getenv("COMET_TEST_DATA_DIR")
if dataDir == "" {
t.Skip("Not running as contention worker")
}
workerIDStr := os.Getenv("COMET_TEST_WORKER_ID")
_ = os.Getenv("COMET_TEST_STREAM") // stream not used in contention worker
workerID, _ := strconv.Atoi(workerIDStr)
config := DeprecatedMultiProcessConfig(0, 2)
client, err := NewClient(dataDir, config)
if err != nil {
t.Fatalf("Contention worker %d failed to create client: %v", workerID, err)
}
defer client.Close()
// Use SAME consumer group to test contention/coordination
consumer := NewConsumer(client, ConsumerOptions{Group: "shared-group"})
defer consumer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
processedCount := 0
processFunc := func(ctx context.Context, msgs []StreamMessage) error {
processedCount += len(msgs)
t.Logf("Contention worker %d: processed %d messages (total: %d)",
workerID, len(msgs), processedCount)
// Stop after reasonable processing
if processedCount >= 30 {
cancel()
}
return nil
}
err = consumer.Process(ctx, processFunc,
WithStream("contention:v1:shard:*"),
WithBatchSize(10),
WithAutoAck(true),
)
t.Logf("Contention worker %d final: processed %d messages", workerID, processedCount)
// In contention scenario, it's ok if one worker gets most/all messages
// The key is that Process() doesn't hang or fail
t.Logf("✅ Contention worker %d completed", workerID)
}
type workerResult struct {
workerID int
output string
err error
}