-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance_test.go
More file actions
816 lines (689 loc) Β· 23.1 KB
/
performance_test.go
File metadata and controls
816 lines (689 loc) Β· 23.1 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
package matcher
import (
"context"
"fmt"
"math/rand"
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"testing"
"time"
)
// BenchmarkConfig holds configuration for performance tests
type BenchmarkConfig struct {
NumRules int
NumDimensions int
NumQueries int
Concurrency int
}
// PerformanceMetrics holds detailed performance metrics
type PerformanceMetrics struct {
TotalTime time.Duration
AverageResponseTime time.Duration
ThroughputQPS float64
MemoryUsedMB float64
MemoryAllocatedMB float64
CPUUsagePercent float64
GCCount uint32
GCPauseTime time.Duration
}
// TestLargeScalePerformance tests with 50k rules and up to 20 dimensions
func TestLargeScalePerformance(t *testing.T) {
configs := []BenchmarkConfig{
{NumRules: 10000, NumDimensions: 5, NumQueries: 1000, Concurrency: 1},
{NumRules: 25000, NumDimensions: 10, NumQueries: 2000, Concurrency: 2},
{NumRules: 50000, NumDimensions: 15, NumQueries: 5000, Concurrency: 4},
{NumRules: 50000, NumDimensions: 20, NumQueries: 10000, Concurrency: 8},
}
for _, config := range configs {
t.Run(fmt.Sprintf("Rules_%d_Dims_%d_Queries_%d_Concurrency_%d",
config.NumRules, config.NumDimensions, config.NumQueries, config.Concurrency), func(t *testing.T) {
metrics := runPerformanceTest(t, config)
logPerformanceMetrics(t, config, metrics)
// Performance assertions
if metrics.AverageResponseTime > 50*time.Millisecond {
t.Errorf("Average response time too high: %v (expected < 50ms)", metrics.AverageResponseTime)
}
if metrics.ThroughputQPS < 100 {
t.Errorf("Throughput too low: %.2f QPS (expected > 100)", metrics.ThroughputQPS)
}
if metrics.MemoryUsedMB > 4000 { // 4GB limit
t.Errorf("Memory usage too high: %.2f MB (expected < 4000MB)", metrics.MemoryUsedMB)
}
})
}
}
// runPerformanceTest executes a performance test with the given configuration
func runPerformanceTest(t *testing.T, config BenchmarkConfig) PerformanceMetrics {
// Force garbage collection before test
runtime.GC()
debug.FreeOSMemory()
// Create matcher with optimized settings
engine, err := NewMatcherEngine(context.Background(), NewJSONPersistence("./test_perf_data"), nil, "perf-test", nil, 0)
if err != nil {
t.Fatalf("Failed to create matcher: %v", err)
}
defer engine.Close()
// Allow duplicate weights for performance testing to avoid weight conflicts with similar rules
engine.SetAllowDuplicateWeights(true)
// Configure dimensions
dimensions := generateDimensions(config.NumDimensions)
for _, dim := range dimensions {
if err := engine.AddDimension(dim); err != nil {
t.Fatalf("Failed to add dimension: %v", err)
}
}
// Record memory before adding rules
var memBefore runtime.MemStats
runtime.ReadMemStats(&memBefore)
// Generate and add rules
rules := generateRules(config.NumRules, dimensions)
start := time.Now()
for i, rule := range rules {
if err := engine.AddRule(rule); err != nil {
t.Fatalf("Failed to add rule %d: %v", i, err)
}
// Progress logging for large datasets
if i > 0 && i%10000 == 0 {
t.Logf("Added %d/%d rules", i, config.NumRules)
}
}
ruleAddTime := time.Since(start)
t.Logf("Added %d rules in %v", config.NumRules, ruleAddTime)
// Record memory after adding rules
var memAfter runtime.MemStats
runtime.ReadMemStats(&memAfter)
// Generate queries
queries := generateQueries(config.NumQueries, dimensions)
// Warm up
for i := 0; i < 100; i++ {
query := queries[i%len(queries)]
_, _ = engine.FindBestMatch(query)
}
// Force GC before measurement
runtime.GC()
// Record initial GC stats
var gcBefore debug.GCStats
debug.ReadGCStats(&gcBefore)
// Performance measurement with concurrency
var wg sync.WaitGroup
queryStart := time.Now()
queriesPerWorker := config.NumQueries / config.Concurrency
successCount := int64(0)
var successMutex sync.Mutex
for worker := 0; worker < config.Concurrency; worker++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
localSuccess := 0
startIdx := workerID * queriesPerWorker
endIdx := startIdx + queriesPerWorker
if workerID == config.Concurrency-1 {
endIdx = config.NumQueries // Handle remainder
}
for i := startIdx; i < endIdx; i++ {
query := queries[i%len(queries)]
result, err := engine.FindBestMatch(query)
if err == nil && result != nil {
localSuccess++
}
}
successMutex.Lock()
successCount += int64(localSuccess)
successMutex.Unlock()
}(worker)
}
wg.Wait()
totalQueryTime := time.Since(queryStart)
// Record final GC stats
var gcAfter debug.GCStats
debug.ReadGCStats(&gcAfter)
// Record final memory stats
var memFinal runtime.MemStats
runtime.ReadMemStats(&memFinal)
// Calculate metrics
return PerformanceMetrics{
TotalTime: totalQueryTime,
AverageResponseTime: time.Duration(int64(totalQueryTime) / int64(config.NumQueries)),
ThroughputQPS: float64(config.NumQueries) / totalQueryTime.Seconds(),
MemoryUsedMB: float64(memFinal.Sys) / 1024 / 1024,
MemoryAllocatedMB: float64(memFinal.Alloc) / 1024 / 1024,
CPUUsagePercent: calculateCPUUsage(totalQueryTime, config.Concurrency),
GCCount: uint32(gcAfter.NumGC - gcBefore.NumGC),
GCPauseTime: time.Duration(gcAfter.PauseTotal - gcBefore.PauseTotal),
}
}
// generateDimensions creates dimension configurations for testing
func generateDimensions(count int) []*DimensionConfig {
dimensionNames := []string{
"product", "environment", "region", "tier", "service", "version",
"team", "project", "component", "stage", "cluster", "namespace",
"deployment", "branch", "feature", "customer", "tenant", "zone",
"category", "priority",
}
dimensions := make([]*DimensionConfig, count)
for i := 0; i < count; i++ {
dimensions[i] = NewDimensionConfig(
dimensionNames[i%len(dimensionNames)]+fmt.Sprintf("_%d", i/len(dimensionNames)),
i,
i < 3, // First 3 dimensions are required
)
}
return dimensions
}
// generateRules creates test rules with realistic distribution
func generateRules(count int, dimensions []*DimensionConfig) []*Rule {
rules := make([]*Rule, count)
// Value pools for realistic data
valuePools := map[string][]string{
"product": {"ProductA", "ProductB", "ProductC", "ProductD", "ProductE"},
"environment": {"production", "staging", "development", "testing"},
"region": {"us-west", "us-east", "eu-west", "eu-central", "ap-southeast"},
"tier": {"premium", "standard", "basic"},
"service": {"api", "web", "worker", "scheduler", "database"},
"version": {"v1.0", "v1.1", "v2.0", "v2.1", "v3.0"},
}
for i := 0; i < count; i++ {
ruleBuilder := NewRule(fmt.Sprintf("rule_%d", i))
// Add dimensions with varying probability
for _, dim := range dimensions {
// Required dimensions always added, optional ones with 70% probability
if dim.Required || rand.Float64() < 0.7 {
var value string
var matchType MatchType
// Get base name without suffix
baseName := dim.Name
if idx := len(baseName) - 2; idx > 0 && baseName[idx] == '_' {
baseName = baseName[:idx]
}
if pool, exists := valuePools[baseName]; exists {
value = pool[rand.Intn(len(pool))]
} else {
value = fmt.Sprintf("value_%d_%d", i, rand.Intn(100))
}
// Distribute match types realistically
switch rand.Intn(10) {
case 0, 1: // 20% MatchTypeAny
matchType = MatchTypeAny
value = ""
case 2: // 10% MatchTypePrefix
matchType = MatchTypePrefix
if len(value) > 3 {
value = value[:3]
}
case 3: // 10% MatchTypeSuffix
matchType = MatchTypeSuffix
if len(value) > 3 {
value = value[len(value)-3:]
}
default: // 60% MatchTypeEqual
matchType = MatchTypeEqual
}
ruleBuilder.Dimension(dim.Name, value, matchType)
}
}
rules[i] = ruleBuilder.Build()
}
return rules
}
// generateQueries creates test queries with realistic patterns
func generateQueries(count int, dimensions []*DimensionConfig) []*QueryRule {
queries := make([]*QueryRule, count)
// Value pools matching rule generation
valuePools := map[string][]string{
"product": {"ProductA", "ProductB", "ProductC", "ProductD", "ProductE"},
"environment": {"production", "staging", "development", "testing"},
"region": {"us-west", "us-east", "eu-west", "eu-central", "ap-southeast"},
"tier": {"premium", "standard", "basic"},
"service": {"api", "web", "worker", "scheduler", "database"},
"version": {"v1.0", "v1.1", "v2.0", "v2.1", "v3.0"},
}
for i := 0; i < count; i++ {
values := make(map[string]string)
// Add required dimensions (always specified in queries)
for _, dim := range dimensions {
if dim.Required {
baseName := dim.Name
if idx := len(baseName) - 2; idx > 0 && baseName[idx] == '_' {
baseName = baseName[:idx]
}
if pool, exists := valuePools[baseName]; exists {
values[dim.Name] = pool[rand.Intn(len(pool))]
} else {
values[dim.Name] = fmt.Sprintf("query_value_%d", rand.Intn(50))
}
}
}
// Optionally add some optional dimensions (partial query testing)
for _, dim := range dimensions {
if !dim.Required && rand.Float64() < 0.4 { // 40% chance for optional dims
baseName := dim.Name
if idx := len(baseName) - 2; idx > 0 && baseName[idx] == '_' {
baseName = baseName[:idx]
}
if pool, exists := valuePools[baseName]; exists {
values[dim.Name] = pool[rand.Intn(len(pool))]
} else {
values[dim.Name] = fmt.Sprintf("query_value_%d", rand.Intn(50))
}
}
}
queries[i] = CreateQuery(values)
}
return queries
}
// calculateCPUUsage estimates CPU usage based on execution time and concurrency
func calculateCPUUsage(duration time.Duration, concurrency int) float64 {
// Simplified CPU usage calculation
// In a real test, you'd measure actual CPU time
totalCPUTime := duration * time.Duration(concurrency)
return float64(totalCPUTime) / float64(duration) * 100.0 / float64(runtime.NumCPU())
}
// logPerformanceMetrics logs detailed performance metrics
func logPerformanceMetrics(t *testing.T, config BenchmarkConfig, metrics PerformanceMetrics) {
t.Logf("\n"+
"=== PERFORMANCE METRICS ===\n"+
"Configuration:\n"+
" Rules: %d\n"+
" Dimensions: %d\n"+
" Queries: %d\n"+
" Concurrency: %d\n"+
"Performance:\n"+
" Total Time: %v\n"+
" Avg Response Time: %v\n"+
" Throughput: %.2f QPS\n"+
"Memory:\n"+
" System Memory: %.2f MB\n"+
" Allocated Memory: %.2f MB\n"+
"Garbage Collection:\n"+
" GC Count: %d\n"+
" GC Pause Time: %v\n"+
"CPU (estimated):\n"+
" CPU Usage: %.2f%%\n"+
"===========================",
config.NumRules, config.NumDimensions, config.NumQueries, config.Concurrency,
metrics.TotalTime, metrics.AverageResponseTime, metrics.ThroughputQPS,
metrics.MemoryUsedMB, metrics.MemoryAllocatedMB,
metrics.GCCount, metrics.GCPauseTime,
metrics.CPUUsagePercent)
}
// BenchmarkQueryPerformance provides Go benchmark results
func BenchmarkQueryPerformance(b *testing.B) {
// Create test engine
engine, err := NewMatcherEngine(context.Background(), NewJSONPersistence("./bench_data"), nil, "bench-test", nil, 0)
if err != nil {
b.Fatalf("Failed to create matcher: %v", err)
}
defer engine.Close()
engine.SetAllowDuplicateWeights(true)
// Add dimensions
dimensions := generateDimensions(10)
for _, dim := range dimensions {
if err := engine.AddDimension(dim); err != nil {
b.Fatalf("Failed to add dimension: %v", err)
}
}
// Add rules
rules := generateRules(10000, dimensions)
for _, rule := range rules {
if err := engine.AddRule(rule); err != nil {
b.Fatalf("Failed to add rule: %v", err)
}
}
// Generate test queries
queries := generateQueries(1000, dimensions)
// Reset timer before benchmark
b.ResetTimer()
// Run benchmark
b.RunParallel(func(pb *testing.PB) {
queryIndex := 0
for pb.Next() {
query := queries[queryIndex%len(queries)]
_, _ = engine.FindBestMatch(query)
queryIndex++
}
})
}
// BenchmarkMemoryEfficiency measures memory usage under different loads
func BenchmarkMemoryEfficiency(b *testing.B) {
testCases := []struct {
name string
numRules int
numDims int
}{
{"Small_1K_5D", 1000, 5},
{"Medium_10K_10D", 10000, 10},
{"Large_50K_15D", 50000, 15},
}
for _, tc := range testCases {
b.Run(tc.name, func(b *testing.B) {
var memBefore, memAfter runtime.MemStats
// Measure memory before
runtime.GC()
runtime.ReadMemStats(&memBefore)
// Create and populate engine
engine, err := NewMatcherEngine(context.Background(), NewJSONPersistence("./mem_bench_data"), nil, "mem-test", nil, 0)
if err != nil {
b.Fatalf("Failed to create matcher: %v", err)
}
engine.SetAllowDuplicateWeights(true)
dimensions := generateDimensions(tc.numDims)
for _, dim := range dimensions {
if err := engine.AddDimension(dim); err != nil {
b.Fatalf("Failed to add dimension: %v", err)
}
}
rules := generateRules(tc.numRules, dimensions)
for _, rule := range rules {
if err := engine.AddRule(rule); err != nil {
b.Fatalf("Failed to add rule: %v", err)
}
}
// Measure memory after
runtime.GC()
runtime.ReadMemStats(&memAfter)
engine.Close()
// Calculate memory usage
memUsed := memAfter.Alloc - memBefore.Alloc
memUsedMB := float64(memUsed) / 1024 / 1024
bytesPerRule := float64(memUsed) / float64(tc.numRules)
b.Logf("Memory usage for %d rules with %d dimensions:", tc.numRules, tc.numDims)
b.Logf(" Total memory: %.2f MB", memUsedMB)
b.Logf(" Memory per rule: %.2f bytes", bytesPerRule)
b.Logf(" Memory efficiency: %.2f MB/1K rules", memUsedMB*1000/float64(tc.numRules))
})
}
}
// TestRebuildStarvationFix verifies that FindBestMatch doesn't get starved by frequent rebuilds
func TestRebuildStarvationFix(t *testing.T) {
// Create persistence and engine
persistence := NewJSONPersistence(t.TempDir())
engine, err := NewMatcherEngine(context.Background(), persistence, nil, "test-starvation", nil, 0)
if err != nil {
t.Fatalf("Failed to create engine: %v", err)
}
defer engine.Close()
// Add dimension config
regionConfig := NewDimensionConfig("region", 0, false).SetWeight(MatchTypeEqual, 10.0)
envConfig := NewDimensionConfig("env", 1, false).SetWeight(MatchTypeEqual, 20.0)
err = engine.AddDimension(regionConfig)
if err != nil {
t.Fatalf("Failed to add dimension: %v", err)
}
err = engine.AddDimension(envConfig)
if err != nil {
t.Fatalf("Failed to add dimension: %v", err)
}
// Add a rule
rule := NewRule("starvation-test-rule-1").
Dimension("region", "us-east", MatchTypeEqual).
Dimension("env", "staging", MatchTypeAny).
Build()
err = engine.AddRule(rule)
if err != nil {
t.Fatalf("Failed to add rule: %v", err)
}
// Add a rule
rule = NewRule("starvation-test-rule-2").
Dimension("region", "us-west", MatchTypeEqual).
Dimension("env", "prod", MatchTypeAny).
Build()
err = engine.AddRule(rule)
if err != nil {
t.Fatalf("Failed to add rule: %v", err)
}
// Save to persistence
err = engine.SaveToPersistence()
if err != nil {
t.Fatalf("Failed to save: %v", err)
}
query := CreateQuery(map[string]string{
"region": "us-east",
})
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
var wg sync.WaitGroup
var rebuildCount int64
var queryCount int64
var queryErrors int64
// Start aggressive rebuilders
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
err := engine.Rebuild()
if err != nil {
t.Errorf("Rebuild failed: %v", err)
} else {
atomic.AddInt64(&rebuildCount, 1)
}
}
}
}()
}
// Start query workers
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
result, err := engine.FindBestMatch(query)
if err != nil {
atomic.AddInt64(&queryErrors, 1)
} else if result != nil {
atomic.AddInt64(&queryCount, 1)
}
}
}
}()
}
// Wait for completion
<-ctx.Done()
wg.Wait()
finalRebuildCount := atomic.LoadInt64(&rebuildCount)
finalQueryCount := atomic.LoadInt64(&queryCount)
finalQueryErrors := atomic.LoadInt64(&queryErrors)
t.Logf("Starvation test results:")
t.Logf(" Total rebuilds: %d", finalRebuildCount)
t.Logf(" Total successful queries: %d", finalQueryCount)
t.Logf(" Total query errors: %d", finalQueryErrors)
// Calculate rates
rebuildRate := float64(finalRebuildCount) / 3.0
queryRate := float64(finalQueryCount) / 3.0
t.Logf(" Rebuild rate: %.1f/sec", rebuildRate)
t.Logf(" Query rate: %.1f/sec", queryRate)
// Verify there were no query errors
if finalQueryErrors > 0 {
t.Errorf("Expected no query errors, got %d", finalQueryErrors)
}
// Verify that queries were not starved
// With the fix, we should get a reasonable query rate even with aggressive rebuilds
minExpectedQueryRate := 5000.0 // queries per second
if queryRate < minExpectedQueryRate {
t.Errorf("Query rate too low: %.1f/sec, expected at least %.1f/sec - possible starvation",
queryRate, minExpectedQueryRate)
}
// Verify that rebuilds were happening (ensuring the test is valid)
minExpectedRebuildRate := 1000.0 // rebuilds per second
if rebuildRate < minExpectedRebuildRate {
t.Errorf("Rebuild rate too low: %.1f/sec, expected at least %.1f/sec - test may not be valid",
rebuildRate, minExpectedRebuildRate)
}
t.Logf("β Starvation fix verified: query rate %.1f/sec with rebuild rate %.1f/sec",
queryRate, rebuildRate)
}
// TestHighConcurrencyNoPartialRules - More intensive concurrency test
func TestHighConcurrencyNoPartialRules(t *testing.T) {
tempDir := t.TempDir()
engine, err := NewMatcherEngineWithDefaults(tempDir)
if err != nil {
t.Fatalf("Failed to create engine: %v", err)
}
defer engine.Close()
// Allow duplicate weights for this test
engine.SetAllowDuplicateWeights(true)
// Add dimension configurations
for i, dimName := range []string{"region", "env", "service", "version", "tier"} {
config := NewDimensionConfig(dimName, i, false)
config.SetWeight(MatchTypeEqual, float64(10+i*2))
err = engine.AddDimension(config)
if err != nil {
t.Fatalf("Failed to add dimension %s: %v", dimName, err)
}
}
var issuesMu sync.Mutex
var issues []string
addIssue := func(issue string) {
issuesMu.Lock()
issues = append(issues, issue)
issuesMu.Unlock()
}
var wg sync.WaitGroup
// Higher concurrency numbers
numRuleWorkers := 20
numQueryWorkers := 20
rulesPerWorker := 10
// Start aggressive query workers
for i := 0; i < numQueryWorkers; i++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
queries := []*QueryRule{
{Values: map[string]string{"region": "us-west", "env": "prod"}},
{Values: map[string]string{"service": "api", "tier": "web"}},
{Values: map[string]string{"region": "us-east", "version": "v1.0"}},
{Values: map[string]string{"env": "staging", "service": "worker"}},
}
startTime := time.Now()
queryCount := 0
for time.Since(startTime) < 3*time.Second {
query := queries[queryCount%len(queries)]
matches, err := engine.FindAllMatches(query)
if err != nil {
addIssue(fmt.Sprintf("High-concurrency query worker %d: FindAllMatches error: %v", workerID, err))
return
}
queryCount++
// Aggressive validation of each match
for matchIdx, match := range matches {
rule := match.Rule
// Basic completeness checks
if rule.ID == "" {
addIssue(fmt.Sprintf("Query worker %d match %d: Empty rule ID", workerID, matchIdx))
}
if rule.Dimensions == nil {
addIssue(fmt.Sprintf("Query worker %d match %d: Nil dimensions for rule %s", workerID, matchIdx, rule.ID))
continue
}
// Deep validation of dimensions
for dimIdx, dim := range rule.Dimensions {
if dim == nil {
addIssue(fmt.Sprintf("Query worker %d match %d: Nil dimension %s in rule %s", workerID, matchIdx, dimIdx, rule.ID))
continue
}
if dim.DimensionName == "" {
addIssue(fmt.Sprintf("Query worker %d match %d: Empty dimension name at index %s in rule %s", workerID, matchIdx, dimIdx, rule.ID))
}
}
// Validate rule actually matches the query
matchesQuery := false
for _, dim := range rule.Dimensions {
if queryValue, exists := query.Values[dim.DimensionName]; exists {
switch dim.MatchType {
case MatchTypeEqual:
if dim.Value == queryValue {
matchesQuery = true
}
case MatchTypeAny:
matchesQuery = true
case MatchTypePrefix:
if len(queryValue) >= len(dim.Value) && queryValue[:len(dim.Value)] == dim.Value {
matchesQuery = true
}
case MatchTypeSuffix:
if len(queryValue) >= len(dim.Value) && queryValue[len(queryValue)-len(dim.Value):] == dim.Value {
matchesQuery = true
}
}
if matchesQuery {
break
}
}
}
// For rules with dimensions, at least one should match
if len(rule.Dimensions) > 0 && !matchesQuery {
addIssue(fmt.Sprintf("Query worker %d match %d: Rule %s doesn't actually match query", workerID, matchIdx, rule.ID))
}
}
// No delay - maximum pressure
}
t.Logf("High-concurrency query worker %d completed %d queries", workerID, queryCount)
}(i)
}
// Start aggressive rule manipulation workers
for i := 0; i < numRuleWorkers; i++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
values := []string{"us-west", "us-east", "eu-west", "prod", "staging", "dev", "api", "web", "worker", "v1.0", "v2.0", "v3.0"}
for j := 0; j < rulesPerWorker; j++ {
ruleID := fmt.Sprintf("high-conc-rule-%d-%d", workerID, j)
// Add rule
rule := NewRule(ruleID).
Dimension("region", values[j%len(values)], MatchTypeEqual).
Dimension("env", values[(j+1)%len(values)], MatchTypeEqual).
Dimension("service", values[(j+2)%len(values)], MatchTypeEqual).
Build()
weight := float64(1000 + workerID*100 + j)
rule.ManualWeight = &weight
if err := engine.AddRule(rule); err != nil {
addIssue(fmt.Sprintf("Rule worker %d: Failed to add rule %s: %v", workerID, ruleID, err))
continue
}
// Immediately try to update it
rule.Status = RuleStatusDraft
rule.Metadata = map[string]string{
"worker": fmt.Sprintf("worker-%d", workerID),
"iteration": fmt.Sprintf("%d", j),
}
if err := engine.UpdateRule(rule); err != nil {
addIssue(fmt.Sprintf("Rule worker %d: Failed to update rule %s: %v", workerID, ruleID, err))
}
// Maybe delete it
if j%3 == 0 {
if err := engine.DeleteRule(ruleID); err != nil {
addIssue(fmt.Sprintf("Rule worker %d: Failed to delete rule %s: %v", workerID, ruleID, err))
}
}
// No delay - maximum pressure
}
}(i)
}
wg.Wait()
// Check for issues
issuesMu.Lock()
defer issuesMu.Unlock()
if len(issues) > 0 {
t.Errorf("Found %d issues under high concurrency:", len(issues))
for i, issue := range issues {
if i < 20 { // Limit output to first 20 issues
t.Errorf("Issue %d: %s", i+1, issue)
}
}
if len(issues) > 20 {
t.Errorf("... and %d more issues", len(issues)-20)
}
} else {
t.Logf("SUCCESS: No partial rules found under high concurrency stress test")
}
}