-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathBatchProcessingThreadSafetyTests.cs
More file actions
894 lines (769 loc) · 35.8 KB
/
BatchProcessingThreadSafetyTests.cs
File metadata and controls
894 lines (769 loc) · 35.8 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
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
using System.Collections.Concurrent;
using Amazon.Lambda.SQSEvents;
using AWS.Lambda.Powertools.BatchProcessing;
using AWS.Lambda.Powertools.BatchProcessing.Sqs;
using AWS.Lambda.Powertools.ConcurrencyTests.BatchProcessing.Helpers;
using Xunit;
namespace AWS.Lambda.Powertools.ConcurrencyTests.BatchProcessing;
/// <summary>
/// Tests for validating thread-safety in AWS Lambda Powertools Batch Processing utility
/// under concurrent execution scenarios.
///
/// These tests verify that when multiple Lambda invocations run concurrently (multi-instance mode),
/// the batch processing operations are thread-safe and don't cause exceptions or data corruption.
/// </summary>
[Collection("BatchProcessing Concurrency Tests")]
public class BatchProcessingThreadSafetyTests
{
#region Helper Classes
private class ThreadSafetyResult
{
public string InvocationId { get; set; } = string.Empty;
public int InvocationIndex { get; set; }
public int OperationsAttempted { get; set; }
public int OperationsCompleted { get; set; }
public bool ExceptionThrown { get; set; }
public string? ExceptionMessage { get; set; }
public string? ExceptionType { get; set; }
public ProcessingResult<SQSEvent.SQSMessage>? Result { get; set; }
}
private class DataIntegrityResult
{
public string InvocationId { get; set; } = string.Empty;
public int InvocationIndex { get; set; }
public int ExpectedRecordCount { get; set; }
public int ActualRecordCount { get; set; }
public int ExpectedSuccessCount { get; set; }
public int ActualSuccessCount { get; set; }
public int ExpectedFailureCount { get; set; }
public int ActualFailureCount { get; set; }
public bool ExceptionThrown { get; set; }
public string? ExceptionMessage { get; set; }
public HashSet<string> ExpectedRecordIds { get; set; } = new();
public HashSet<string> ActualRecordIds { get; set; } = new();
public bool HasCorrectRecords => ActualRecordIds.SetEquals(ExpectedRecordIds);
}
private class ParallelProcessingResult
{
public string InvocationId { get; set; } = string.Empty;
public int InvocationIndex { get; set; }
public int ExpectedRecordCount { get; set; }
public int ExpectedSuccessCount { get; set; }
public int ExpectedFailureCount { get; set; }
public ProcessingResult<SQSEvent.SQSMessage>? Result { get; set; }
public bool ExceptionThrown { get; set; }
public string? ExceptionMessage { get; set; }
public TimeSpan Duration { get; set; }
}
#endregion
#region Basic Thread-Safety Tests (Task 3.1)
/// <summary>
/// Verifies that concurrent access to the batch processor does not throw
/// thread-safety related exceptions.
/// Requirements: 2.1
/// </summary>
[Theory]
[InlineData(2, 10)]
[InlineData(5, 20)]
[InlineData(10, 10)]
public async Task ConcurrentAccess_ShouldNotThrowThreadSafetyExceptions(
int concurrencyLevel, int iterationsPerThread)
{
// Arrange
var results = new ConcurrentBag<ThreadSafetyResult>();
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = Enumerable.Range(0, concurrencyLevel).Select(threadIndex => Task.Run(async () =>
{
var result = new ThreadSafetyResult
{
InvocationIndex = threadIndex,
OperationsAttempted = iterationsPerThread
};
try
{
barrier.SignalAndWait();
for (int iteration = 0; iteration < iterationsPerThread; iteration++)
{
var invocationId = $"thread-{threadIndex}-iter-{iteration}-{Guid.NewGuid():N}";
result.InvocationId = invocationId;
var sqsEvent = TestEventFactory.CreateSqsEvent(3, invocationId);
var handler = new TestSqsRecordHandler();
var processor = new SqsBatchProcessor();
var processingResult = await processor.ProcessAsync(sqsEvent, handler);
// Verify basic correctness
Assert.Equal(3, processingResult.BatchRecords.Count);
result.OperationsCompleted++;
}
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
result.ExceptionType = ex.GetType().Name;
}
results.Add(result);
})).ToList();
await Task.WhenAll(tasks);
// Assert
Assert.Equal(concurrencyLevel, results.Count);
Assert.All(results, r => Assert.False(r.ExceptionThrown,
$"Thread {r.InvocationIndex} threw {r.ExceptionType}: {r.ExceptionMessage}"));
Assert.All(results, r => Assert.Equal(r.OperationsAttempted, r.OperationsCompleted));
}
/// <summary>
/// Verifies that data integrity is maintained when multiple invocations
/// simultaneously clear and populate ProcessingResult.
/// Requirements: 2.2
/// </summary>
[Theory]
[InlineData(2)]
[InlineData(5)]
[InlineData(10)]
public async Task ConcurrentProcessingResultClearing_ShouldMaintainDataIntegrity(int concurrencyLevel)
{
// Arrange
var results = new DataIntegrityResult[concurrencyLevel];
var barrier = new Barrier(concurrencyLevel);
var recordCounts = Enumerable.Range(0, concurrencyLevel)
.Select(i => 3 + i) // Different record counts: 3, 4, 5, etc.
.ToArray();
// Act
var tasks = new Task[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++)
{
int invocationIndex = i;
tasks[i] = Task.Run(async () =>
{
var invocationId = $"integrity-{invocationIndex}-{Guid.NewGuid():N}";
var recordCount = recordCounts[invocationIndex];
var sqsEvent = TestEventFactory.CreateSqsEvent(recordCount, invocationId);
var expectedRecordIds = TestEventFactory.GetSqsMessageIds(sqsEvent);
var failureCount = invocationIndex % recordCount; // Varying failure counts
var handler = new TestSqsRecordHandler
{
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new DataIntegrityResult
{
InvocationId = invocationId,
InvocationIndex = invocationIndex,
ExpectedRecordCount = recordCount,
ExpectedSuccessCount = recordCount - failureCount,
ExpectedFailureCount = failureCount,
ExpectedRecordIds = expectedRecordIds
};
try
{
// Synchronize to maximize race condition potential
barrier.SignalAndWait();
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions { ThrowOnFullBatchFailure = false };
var processingResult = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
result.ActualRecordCount = processingResult.BatchRecords.Count;
result.ActualSuccessCount = processingResult.SuccessRecords.Count;
result.ActualFailureCount = processingResult.FailureRecords.Count;
result.ActualRecordIds = processingResult.BatchRecords
.Select(r => r.MessageId)
.ToHashSet();
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
results[invocationIndex] = result;
});
}
await Task.WhenAll(tasks);
// Assert
foreach (var result in results)
{
Assert.False(result.ExceptionThrown, result.ExceptionMessage);
Assert.Equal(result.ExpectedRecordCount, result.ActualRecordCount);
Assert.Equal(result.ExpectedSuccessCount, result.ActualSuccessCount);
Assert.Equal(result.ExpectedFailureCount, result.ActualFailureCount);
Assert.True(result.HasCorrectRecords,
$"Invocation {result.InvocationId}: Expected records {string.Join(",", result.ExpectedRecordIds)} " +
$"but got {string.Join(",", result.ActualRecordIds)}");
}
}
/// <summary>
/// Verifies that parallel batch processing within an invocation works correctly
/// while other invocations are also processing.
/// Requirements: 2.3
/// </summary>
[Theory]
[InlineData(2, 5)]
[InlineData(3, 8)]
[InlineData(5, 6)]
public async Task ParallelProcessingWithConcurrentInvocations_ShouldTrackRecordsCorrectly(
int concurrencyLevel, int recordsPerInvocation)
{
// Arrange
var results = new ParallelProcessingResult[concurrencyLevel];
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = new Task[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++)
{
int invocationIndex = i;
tasks[i] = Task.Run(async () =>
{
var invocationId = $"parallel-{invocationIndex}-{Guid.NewGuid():N}";
var sqsEvent = TestEventFactory.CreateSqsEvent(recordsPerInvocation, invocationId);
var failureCount = invocationIndex % recordsPerInvocation;
var handler = new TestSqsRecordHandler
{
ProcessingDelay = TimeSpan.FromMilliseconds(10), // Add delay to increase overlap
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new ParallelProcessingResult
{
InvocationId = invocationId,
InvocationIndex = invocationIndex,
ExpectedRecordCount = recordsPerInvocation,
ExpectedSuccessCount = recordsPerInvocation - failureCount,
ExpectedFailureCount = failureCount
};
try
{
barrier.SignalAndWait();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions
{
BatchParallelProcessingEnabled = true,
MaxDegreeOfParallelism = 4,
ThrowOnFullBatchFailure = false
};
result.Result = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
stopwatch.Stop();
result.Duration = stopwatch.Elapsed;
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
results[invocationIndex] = result;
});
}
await Task.WhenAll(tasks);
// Assert
foreach (var result in results)
{
Assert.False(result.ExceptionThrown, result.ExceptionMessage);
Assert.NotNull(result.Result);
Assert.Equal(result.ExpectedRecordCount, result.Result.BatchRecords.Count);
Assert.Equal(result.ExpectedSuccessCount, result.Result.SuccessRecords.Count);
Assert.Equal(result.ExpectedFailureCount, result.Result.FailureRecords.Count);
// Verify all records belong to this invocation
foreach (var record in result.Result.BatchRecords)
{
Assert.True(record.MessageId.StartsWith(result.InvocationId),
$"Record {record.MessageId} does not belong to invocation {result.InvocationId}");
}
}
}
#endregion
#region Property 4: Exception-Free Concurrent Access
/// <summary>
/// **Feature: batch-processing-multi-instance-validation, Property 4: Exception-Free Concurrent Access**
///
/// Property: For any number of concurrent threads accessing the singleton batch processor,
/// all operations SHALL complete without throwing thread-safety related exceptions
/// (InvalidOperationException, ConcurrentModificationException, etc.).
///
/// **Validates: Requirements 2.1**
/// </summary>
[Theory]
[InlineData(2, 5, 3)]
[InlineData(3, 10, 5)]
[InlineData(5, 8, 4)]
[InlineData(10, 5, 3)]
public async Task Property4_ExceptionFreeConcurrentAccess_AllOperationsShouldComplete(
int concurrencyLevel, int iterationsPerThread, int recordsPerIteration)
{
// Arrange
var results = new ConcurrentBag<ThreadSafetyResult>();
var exceptions = new ConcurrentBag<Exception>();
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = Enumerable.Range(0, concurrencyLevel).Select(threadIndex => Task.Run(async () =>
{
var result = new ThreadSafetyResult
{
InvocationIndex = threadIndex,
OperationsAttempted = iterationsPerThread
};
try
{
barrier.SignalAndWait();
for (int iteration = 0; iteration < iterationsPerThread; iteration++)
{
var invocationId = $"prop4-t{threadIndex}-i{iteration}-{Guid.NewGuid():N}";
result.InvocationId = invocationId;
var sqsEvent = TestEventFactory.CreateSqsEvent(recordsPerIteration, invocationId);
var handler = new TestSqsRecordHandler();
var processor = new SqsBatchProcessor();
var processingResult = await processor.ProcessAsync(sqsEvent, handler);
// Property check: Result should have correct record count
Assert.Equal(recordsPerIteration, processingResult.BatchRecords.Count);
// Property check: All records should be successes (no failures configured)
Assert.Equal(recordsPerIteration, processingResult.SuccessRecords.Count);
Assert.Empty(processingResult.FailureRecords);
result.OperationsCompleted++;
}
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}";
result.ExceptionType = ex.GetType().Name;
exceptions.Add(ex);
}
results.Add(result);
})).ToList();
await Task.WhenAll(tasks);
// Assert - Property: No thread-safety exceptions should be thrown
Assert.Equal(concurrencyLevel, results.Count);
Assert.Empty(exceptions);
Assert.All(results, r => Assert.False(r.ExceptionThrown,
$"Property violation: Thread {r.InvocationIndex} threw {r.ExceptionType}: {r.ExceptionMessage}"));
Assert.All(results, r => Assert.Equal(r.OperationsAttempted, r.OperationsCompleted));
}
/// <summary>
/// Additional test for Property 4 with mixed operations (success and failure).
/// </summary>
[Theory]
[InlineData(3, 10)]
[InlineData(5, 15)]
[InlineData(8, 8)]
public async Task Property4_ExceptionFreeConcurrentAccess_MixedOperations_ShouldComplete(
int concurrencyLevel, int iterationsPerThread)
{
// Arrange
var results = new ConcurrentBag<ThreadSafetyResult>();
var exceptions = new ConcurrentBag<Exception>();
var barrier = new Barrier(concurrencyLevel);
var random = new Random();
// Act
var tasks = Enumerable.Range(0, concurrencyLevel).Select(threadIndex => Task.Run(async () =>
{
var result = new ThreadSafetyResult
{
InvocationIndex = threadIndex,
OperationsAttempted = iterationsPerThread
};
try
{
barrier.SignalAndWait();
for (int iteration = 0; iteration < iterationsPerThread; iteration++)
{
var invocationId = $"prop4mix-t{threadIndex}-i{iteration}-{Guid.NewGuid():N}";
var recordCount = random.Next(2, 8);
var failureCount = random.Next(0, recordCount);
var sqsEvent = TestEventFactory.CreateSqsEvent(recordCount, invocationId);
var handler = new TestSqsRecordHandler
{
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions { ThrowOnFullBatchFailure = false };
var processingResult = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
// Property check: Total records should match
Assert.Equal(recordCount, processingResult.BatchRecords.Count);
// Property check: Success + Failure should equal total
Assert.Equal(recordCount,
processingResult.SuccessRecords.Count + processingResult.FailureRecords.Count);
result.OperationsCompleted++;
}
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
result.ExceptionType = ex.GetType().Name;
exceptions.Add(ex);
}
results.Add(result);
})).ToList();
await Task.WhenAll(tasks);
// Assert
Assert.Equal(concurrencyLevel, results.Count);
Assert.Empty(exceptions);
Assert.All(results, r => Assert.False(r.ExceptionThrown, r.ExceptionMessage));
Assert.All(results, r => Assert.Equal(r.OperationsAttempted, r.OperationsCompleted));
}
#endregion
#region Property 5: Data Integrity Under Concurrent Clear
/// <summary>
/// **Feature: batch-processing-multi-instance-validation, Property 5: Data Integrity Under Concurrent Clear**
///
/// Property: For any set of invocations that simultaneously begin ProcessAsync
/// (triggering ProcessingResult clearing), each invocation SHALL maintain data integrity
/// in its final result.
///
/// **Validates: Requirements 2.2**
/// </summary>
[Theory]
[InlineData(2, 3, 7)]
[InlineData(3, 4, 8)]
[InlineData(5, 3, 6)]
[InlineData(10, 2, 5)]
public async Task Property5_DataIntegrityUnderConcurrentClear_EachInvocationMaintainsIntegrity(
int concurrencyLevel, int minRecords, int maxRecords)
{
// Arrange
var random = new Random();
var recordCounts = Enumerable.Range(0, concurrencyLevel)
.Select(_ => random.Next(minRecords, maxRecords + 1))
.ToArray();
var failureCounts = recordCounts
.Select(rc => random.Next(0, rc))
.ToArray();
var results = new DataIntegrityResult[concurrencyLevel];
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = new Task[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++)
{
int invocationIndex = i;
tasks[i] = Task.Run(async () =>
{
var invocationId = $"prop5-{invocationIndex}-{Guid.NewGuid():N}";
var recordCount = recordCounts[invocationIndex];
var failureCount = failureCounts[invocationIndex];
var sqsEvent = TestEventFactory.CreateSqsEvent(recordCount, invocationId);
var expectedRecordIds = TestEventFactory.GetSqsMessageIds(sqsEvent);
var handler = new TestSqsRecordHandler
{
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new DataIntegrityResult
{
InvocationId = invocationId,
InvocationIndex = invocationIndex,
ExpectedRecordCount = recordCount,
ExpectedSuccessCount = recordCount - failureCount,
ExpectedFailureCount = failureCount,
ExpectedRecordIds = expectedRecordIds
};
try
{
// Synchronize to maximize concurrent clearing
barrier.SignalAndWait();
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions { ThrowOnFullBatchFailure = false };
var processingResult = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
result.ActualRecordCount = processingResult.BatchRecords.Count;
result.ActualSuccessCount = processingResult.SuccessRecords.Count;
result.ActualFailureCount = processingResult.FailureRecords.Count;
result.ActualRecordIds = processingResult.BatchRecords
.Select(r => r.MessageId)
.ToHashSet();
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
results[invocationIndex] = result;
});
}
await Task.WhenAll(tasks);
// Assert - Property: Each invocation maintains data integrity
foreach (var result in results)
{
// Property check 1: No exceptions
Assert.False(result.ExceptionThrown,
$"Property violation: Invocation {result.InvocationId} threw: {result.ExceptionMessage}");
// Property check 2: Record count integrity
Assert.Equal(result.ExpectedRecordCount, result.ActualRecordCount);
// Property check 3: Success count integrity
Assert.Equal(result.ExpectedSuccessCount, result.ActualSuccessCount);
// Property check 4: Failure count integrity
Assert.Equal(result.ExpectedFailureCount, result.ActualFailureCount);
// Property check 5: Record identity integrity
Assert.True(result.HasCorrectRecords,
$"Property violation: Invocation {result.InvocationId} has incorrect records. " +
$"Expected: {string.Join(",", result.ExpectedRecordIds)}, " +
$"Actual: {string.Join(",", result.ActualRecordIds)}");
// Property check 6: No foreign records
var foreignRecords = result.ActualRecordIds.Except(result.ExpectedRecordIds).ToList();
Assert.Empty(foreignRecords);
}
}
/// <summary>
/// Additional test for Property 5 with rapid successive invocations.
/// </summary>
[Theory]
[InlineData(5, 20)]
[InlineData(10, 15)]
public async Task Property5_DataIntegrityUnderConcurrentClear_RapidSuccessiveInvocations(
int concurrencyLevel, int iterationsPerThread)
{
// Arrange
var allResults = new ConcurrentBag<DataIntegrityResult>();
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = Enumerable.Range(0, concurrencyLevel).Select(threadIndex => Task.Run(async () =>
{
barrier.SignalAndWait();
for (int iteration = 0; iteration < iterationsPerThread; iteration++)
{
var invocationId = $"prop5rapid-t{threadIndex}-i{iteration}-{Guid.NewGuid():N}";
var recordCount = 3 + (iteration % 5);
var failureCount = iteration % recordCount;
var sqsEvent = TestEventFactory.CreateSqsEvent(recordCount, invocationId);
var expectedRecordIds = TestEventFactory.GetSqsMessageIds(sqsEvent);
var handler = new TestSqsRecordHandler
{
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new DataIntegrityResult
{
InvocationId = invocationId,
InvocationIndex = threadIndex,
ExpectedRecordCount = recordCount,
ExpectedSuccessCount = recordCount - failureCount,
ExpectedFailureCount = failureCount,
ExpectedRecordIds = expectedRecordIds
};
try
{
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions { ThrowOnFullBatchFailure = false };
var processingResult = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
result.ActualRecordCount = processingResult.BatchRecords.Count;
result.ActualSuccessCount = processingResult.SuccessRecords.Count;
result.ActualFailureCount = processingResult.FailureRecords.Count;
result.ActualRecordIds = processingResult.BatchRecords
.Select(r => r.MessageId)
.ToHashSet();
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
allResults.Add(result);
}
})).ToList();
await Task.WhenAll(tasks);
// Assert
Assert.Equal(concurrencyLevel * iterationsPerThread, allResults.Count);
Assert.All(allResults, r =>
{
Assert.False(r.ExceptionThrown, r.ExceptionMessage);
Assert.Equal(r.ExpectedRecordCount, r.ActualRecordCount);
Assert.Equal(r.ExpectedSuccessCount, r.ActualSuccessCount);
Assert.Equal(r.ExpectedFailureCount, r.ActualFailureCount);
Assert.True(r.HasCorrectRecords);
});
}
#endregion
#region Property 6: Parallel Processing with Concurrent Invocations
/// <summary>
/// **Feature: batch-processing-multi-instance-validation, Property 6: Parallel Processing with Concurrent Invocations**
///
/// Property: For any invocation using BatchParallelProcessingEnabled=true while other invocations
/// are also processing, the parallel invocation SHALL correctly track all success and failure records.
///
/// **Validates: Requirements 2.3**
/// </summary>
[Theory]
[InlineData(2, 5, 2)]
[InlineData(3, 8, 3)]
[InlineData(5, 6, 4)]
[InlineData(8, 4, 2)]
public async Task Property6_ParallelProcessingWithConcurrentInvocations_CorrectlyTracksRecords(
int concurrencyLevel, int recordsPerInvocation, int maxDegreeOfParallelism)
{
// Arrange
var random = new Random();
var failureCounts = Enumerable.Range(0, concurrencyLevel)
.Select(_ => random.Next(0, recordsPerInvocation))
.ToArray();
var results = new ParallelProcessingResult[concurrencyLevel];
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = new Task[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++)
{
int invocationIndex = i;
tasks[i] = Task.Run(async () =>
{
var invocationId = $"prop6-{invocationIndex}-{Guid.NewGuid():N}";
var failureCount = failureCounts[invocationIndex];
var sqsEvent = TestEventFactory.CreateSqsEvent(recordsPerInvocation, invocationId);
var handler = new TestSqsRecordHandler
{
ProcessingDelay = TimeSpan.FromMilliseconds(5), // Add delay to increase parallel overlap
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new ParallelProcessingResult
{
InvocationId = invocationId,
InvocationIndex = invocationIndex,
ExpectedRecordCount = recordsPerInvocation,
ExpectedSuccessCount = recordsPerInvocation - failureCount,
ExpectedFailureCount = failureCount
};
try
{
barrier.SignalAndWait();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions
{
BatchParallelProcessingEnabled = true,
MaxDegreeOfParallelism = maxDegreeOfParallelism,
ThrowOnFullBatchFailure = false
};
result.Result = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
stopwatch.Stop();
result.Duration = stopwatch.Elapsed;
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
results[invocationIndex] = result;
});
}
await Task.WhenAll(tasks);
// Assert - Property: Each parallel invocation correctly tracks records
foreach (var result in results)
{
// Property check 1: No exceptions
Assert.False(result.ExceptionThrown,
$"Property violation: Invocation {result.InvocationId} threw: {result.ExceptionMessage}");
Assert.NotNull(result.Result);
// Property check 2: Total record count is correct
Assert.Equal(result.ExpectedRecordCount, result.Result.BatchRecords.Count);
// Property check 3: Success count is correct
Assert.Equal(result.ExpectedSuccessCount, result.Result.SuccessRecords.Count);
// Property check 4: Failure count is correct
Assert.Equal(result.ExpectedFailureCount, result.Result.FailureRecords.Count);
// Property check 5: BatchItemFailures count matches failure count
Assert.Equal(result.ExpectedFailureCount,
result.Result.BatchItemFailuresResponse.BatchItemFailures.Count);
// Property check 6: All records belong to this invocation
foreach (var record in result.Result.BatchRecords)
{
Assert.True(record.MessageId.StartsWith(result.InvocationId),
$"Property violation: Record {record.MessageId} does not belong to invocation {result.InvocationId}");
}
// Property check 7: All failure IDs belong to this invocation
foreach (var failure in result.Result.BatchItemFailuresResponse.BatchItemFailures)
{
Assert.True(failure.ItemIdentifier.StartsWith(result.InvocationId),
$"Property violation: Failure {failure.ItemIdentifier} does not belong to invocation {result.InvocationId}");
}
}
}
/// <summary>
/// Additional test for Property 6 with mixed parallel and sequential processing.
/// </summary>
[Theory]
[InlineData(4, 6)]
[InlineData(6, 8)]
public async Task Property6_MixedParallelAndSequentialProcessing_AllInvocationsCorrect(
int concurrencyLevel, int recordsPerInvocation)
{
// Arrange
var results = new ParallelProcessingResult[concurrencyLevel];
var barrier = new Barrier(concurrencyLevel);
// Act
var tasks = new Task[concurrencyLevel];
for (int i = 0; i < concurrencyLevel; i++)
{
int invocationIndex = i;
bool useParallel = invocationIndex % 2 == 0; // Alternate between parallel and sequential
tasks[i] = Task.Run(async () =>
{
var invocationId = $"prop6mix-{invocationIndex}-{Guid.NewGuid():N}";
var failureCount = invocationIndex % recordsPerInvocation;
var sqsEvent = TestEventFactory.CreateSqsEvent(recordsPerInvocation, invocationId);
var handler = new TestSqsRecordHandler
{
ProcessingDelay = TimeSpan.FromMilliseconds(3),
ShouldFail = msg =>
{
var msgIndex = int.Parse(msg.MessageId.Split("-msg-")[1]);
return msgIndex < failureCount;
}
};
var result = new ParallelProcessingResult
{
InvocationId = invocationId,
InvocationIndex = invocationIndex,
ExpectedRecordCount = recordsPerInvocation,
ExpectedSuccessCount = recordsPerInvocation - failureCount,
ExpectedFailureCount = failureCount
};
try
{
barrier.SignalAndWait();
var processor = new SqsBatchProcessor();
var processingOptions = new ProcessingOptions
{
BatchParallelProcessingEnabled = useParallel,
MaxDegreeOfParallelism = useParallel ? 4 : 1,
ThrowOnFullBatchFailure = false
};
result.Result = await processor.ProcessAsync(sqsEvent, handler, processingOptions);
}
catch (Exception ex)
{
result.ExceptionThrown = true;
result.ExceptionMessage = $"{ex.GetType().Name}: {ex.Message}";
}
results[invocationIndex] = result;
});
}
await Task.WhenAll(tasks);
// Assert
foreach (var result in results)
{
Assert.False(result.ExceptionThrown, result.ExceptionMessage);
Assert.NotNull(result.Result);
Assert.Equal(result.ExpectedRecordCount, result.Result.BatchRecords.Count);
Assert.Equal(result.ExpectedSuccessCount, result.Result.SuccessRecords.Count);
Assert.Equal(result.ExpectedFailureCount, result.Result.FailureRecords.Count);
// Verify record ownership
foreach (var record in result.Result.BatchRecords)
{
Assert.True(record.MessageId.StartsWith(result.InvocationId));
}
}
}
#endregion
}