-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathfairQueueSelectionStrategy.test.ts
More file actions
1261 lines (1094 loc) · 39 KB
/
fairQueueSelectionStrategy.test.ts
File metadata and controls
1261 lines (1094 loc) · 39 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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { redisTest } from "@internal/testcontainers";
import { describe, expect, vi } from "vitest";
import { RUN_QUEUE_RESUME_PRIORITY_TIMESTAMP_OFFSET } from "../constants.js";
import { FairQueueSelectionStrategy } from "../fairQueueSelectionStrategy.js";
import { RunQueueFullKeyProducer } from "../keyProducer.js";
import { EnvQueues, RunQueueKeyProducer } from "../types.js";
import { createRedisClient, RedisOptions } from "@internal/redis";
vi.setConfig({ testTimeout: 60_000 }); // 30 seconds timeout
describe("FairDequeuingStrategy", () => {
redisTest(
"should distribute a single queue from a single env",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "test-seed-1", // for deterministic shuffling
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: Date.now() - 1000, // 1 second ago
queueId: "queue-1",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
const result = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
envId: "env-1",
queues: [keyProducer.queueKey("org-1", "proj-1", "env-1", "queue-1")],
});
}
);
redisTest("should respect env concurrency limits", async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 2,
parentQueueLimit: 100,
seed: "test-seed-3",
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: Date.now() - 1000,
queueId: "queue-1",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
await setupConcurrency({
redis,
keyProducer,
env: { envId: "env-1", projectId: "proj-1", orgId: "org-1", currentConcurrency: 2, limit: 2 },
});
const result = await strategy.distributeFairQueuesFromParentQueue("parent-queue", "consumer-1");
expect(result).toHaveLength(0);
});
redisTest("should respect parentQueueLimit", async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 2, // Only take 2 queues
seed: "test-seed-6",
});
const now = Date.now();
// Setup 3 queues but parentQueueLimit is 2
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 3000,
queueId: "queue-1",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 2000,
queueId: "queue-2",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 1000,
queueId: "queue-3",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
const result = await strategy.distributeFairQueuesFromParentQueue("parent-queue", "consumer-1");
expect(result).toHaveLength(1);
const queue1 = keyProducer.queueKey("org-1", "proj-1", "env-1", "queue-1");
const queue2 = keyProducer.queueKey("org-1", "proj-1", "env-1", "queue-2");
expect(result[0]).toEqual({
envId: "env-1",
queues: [queue1, queue2],
});
});
redisTest(
"should reuse snapshots across calls for the same consumer",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 10,
seed: "test-seed-reuse-1",
reuseSnapshotCount: 1,
});
const now = Date.now();
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 3000,
queueId: "queue-1",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 2000,
queueId: "queue-2",
orgId: "org-2",
projectId: "proj-2",
envId: "env-2",
});
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 1000,
queueId: "queue-3",
orgId: "org-3",
projectId: "proj-3",
envId: "env-3",
});
const startDistribute1 = performance.now();
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
const result = flattenResults(envResult);
const distribute1Duration = performance.now() - startDistribute1;
console.log("First distribution took", distribute1Duration, "ms");
expect(result).toHaveLength(3);
// Should only get the two oldest queues
const queue1 = keyProducer.queueKey("org-1", "proj-1", "env-1", "queue-1");
const queue2 = keyProducer.queueKey("org-2", "proj-2", "env-2", "queue-2");
const queue3 = keyProducer.queueKey("org-3", "proj-3", "env-3", "queue-3");
expect(result).toEqual([queue2, queue1, queue3]);
const startDistribute2 = performance.now();
const result2 = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
const distribute2Duration = performance.now() - startDistribute2;
console.log("Second distribution took", distribute2Duration, "ms");
// Make sure the second call is more than 2 times faster than the first
expect(distribute2Duration).toBeLessThan(distribute1Duration / 2);
const startDistribute3 = performance.now();
const result3 = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
const distribute3Duration = performance.now() - startDistribute3;
console.log("Third distribution took", distribute3Duration, "ms");
// Make sure the third call is more than 4 times the second
expect(distribute3Duration).toBeGreaterThan(distribute2Duration * 2);
}
);
redisTest(
"should fairly distribute queues across environments over time",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "test-seed-5",
});
const now = Date.now();
// Test configuration
const orgs = ["org-1", "org-2", "org-3"];
const envsPerOrg = 3; // Each org has 3 environments
const queuesPerEnv = 5; // Each env has 5 queues
const iterations = 1000;
// Setup queues
for (const orgId of orgs) {
for (let envNum = 1; envNum <= envsPerOrg; envNum++) {
const envId = `env-${orgId}-${envNum}`;
const projectId = `proj-${orgId}-${envNum}`;
for (let queueNum = 1; queueNum <= queuesPerEnv; queueNum++) {
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
// Vary the ages slightly
score: now - Math.random() * 10000,
queueId: `queue-${orgId}-${envId}-${queueNum}`,
orgId,
projectId,
envId,
});
}
// Setup reasonable concurrency limits
await setupConcurrency({
redis,
keyProducer,
env: { envId, projectId, orgId, currentConcurrency: 1, limit: 5 },
});
}
}
// Track distribution statistics
type PositionStats = {
firstPosition: number; // Count of times this env/org was first
positionSums: number; // Sum of positions (for averaging)
appearances: number; // Total number of appearances
};
const envStats: Record<string, PositionStats> = {};
const orgStats: Record<string, PositionStats> = {};
// Initialize stats objects
for (const orgId of orgs) {
orgStats[orgId] = { firstPosition: 0, positionSums: 0, appearances: 0 };
for (let envNum = 1; envNum <= envsPerOrg; envNum++) {
const envId = `env-${orgId}-${envNum}`;
envStats[envId] = { firstPosition: 0, positionSums: 0, appearances: 0 };
}
}
// Run multiple iterations
for (let i = 0; i < iterations; i++) {
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
`consumer-${i % 3}` // Simulate 3 different consumers
);
const result = flattenResults(envResult);
// Track positions of queues
result.forEach((queueId, position) => {
const orgId = keyProducer.orgIdFromQueue(queueId);
const envId = keyProducer.envIdFromQueue(queueId);
// Update org stats
orgStats[orgId].appearances++;
orgStats[orgId].positionSums += position;
if (position === 0) orgStats[orgId].firstPosition++;
// Update env stats
envStats[envId].appearances++;
envStats[envId].positionSums += position;
if (position === 0) envStats[envId].firstPosition++;
});
}
// Calculate and log statistics
console.log("\nOrganization Statistics:");
for (const [orgId, stats] of Object.entries(orgStats)) {
const avgPosition = stats.positionSums / stats.appearances;
const firstPositionPercentage = (stats.firstPosition / iterations) * 100;
console.log(`${orgId}:
First Position: ${firstPositionPercentage.toFixed(2)}%
Average Position: ${avgPosition.toFixed(2)}
Total Appearances: ${stats.appearances}`);
}
console.log("\nEnvironment Statistics:");
for (const [envId, stats] of Object.entries(envStats)) {
const avgPosition = stats.positionSums / stats.appearances;
const firstPositionPercentage = (stats.firstPosition / iterations) * 100;
console.log(`${envId}:
First Position: ${firstPositionPercentage.toFixed(2)}%
Average Position: ${avgPosition.toFixed(2)}
Total Appearances: ${stats.appearances}`);
}
// Verify fairness of first position distribution
const expectedFirstPositionPercentage = 100 / orgs.length;
const firstPositionStdDevOrgs = calculateStandardDeviation(
Object.values(orgStats).map((stats) => (stats.firstPosition / iterations) * 100)
);
const expectedEnvFirstPositionPercentage = 100 / (orgs.length * envsPerOrg);
const firstPositionStdDevEnvs = calculateStandardDeviation(
Object.values(envStats).map((stats) => (stats.firstPosition / iterations) * 100)
);
// Assert reasonable fairness for first position
expect(firstPositionStdDevOrgs).toBeLessThan(5); // Allow 5% standard deviation for orgs
expect(firstPositionStdDevEnvs).toBeLessThan(5); // Allow 5% standard deviation for envs
// Verify that each org and env gets a fair chance at first position
for (const [orgId, stats] of Object.entries(orgStats)) {
const firstPositionPercentage = (stats.firstPosition / iterations) * 100;
expect(firstPositionPercentage).toBeGreaterThan(expectedFirstPositionPercentage * 0.7); // Within 30% of expected
expect(firstPositionPercentage).toBeLessThan(expectedFirstPositionPercentage * 1.3);
}
for (const [envId, stats] of Object.entries(envStats)) {
const firstPositionPercentage = (stats.firstPosition / iterations) * 100;
expect(firstPositionPercentage).toBeGreaterThan(expectedEnvFirstPositionPercentage * 0.7); // Within 30% of expected
expect(firstPositionPercentage).toBeLessThan(expectedEnvFirstPositionPercentage * 1.3);
}
// Verify average positions are reasonably distributed
const avgPositionsOrgs = Object.values(orgStats).map(
(stats) => stats.positionSums / stats.appearances
);
const avgPositionsEnvs = Object.values(envStats).map(
(stats) => stats.positionSums / stats.appearances
);
const avgPositionStdDevOrgs = calculateStandardDeviation(avgPositionsOrgs);
const avgPositionStdDevEnvs = calculateStandardDeviation(avgPositionsEnvs);
expect(avgPositionStdDevOrgs).toBeLessThan(1); // Average positions should be fairly consistent
expect(avgPositionStdDevEnvs).toBeLessThan(1);
}
);
redisTest(
"should shuffle environments while maintaining age order within environments",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "fixed-seed",
});
const now = Date.now();
// Setup three environments, each with two queues of different ages
await Promise.all([
// env-1: one old queue (3000ms old) and one new queue (1000ms old)
setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 3000,
queueId: "queue-1-old",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
}),
setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 1000,
queueId: "queue-1-new",
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
}),
// env-2: same pattern
setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 3000,
queueId: "queue-2-old",
orgId: "org-1",
projectId: "proj-1",
envId: "env-2",
}),
setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 1000,
queueId: "queue-2-new",
orgId: "org-1",
projectId: "proj-1",
envId: "env-2",
}),
]);
// Setup basic concurrency settings
await setupConcurrency({
redis,
keyProducer,
env: {
envId: "env-1",
projectId: "proj-1",
orgId: "org-1",
currentConcurrency: 0,
limit: 5,
},
});
await setupConcurrency({
redis,
keyProducer,
env: {
envId: "env-2",
projectId: "proj-1",
orgId: "org-1",
currentConcurrency: 0,
limit: 5,
},
});
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
const result = flattenResults(envResult);
// Group queues by environment
const queuesByEnv = result.reduce(
(acc, queueId) => {
const envId = keyProducer.envIdFromQueue(queueId);
if (!acc[envId]) {
acc[envId] = [];
}
acc[envId].push(queueId);
return acc;
},
{} as Record<string, string[]>
);
// Verify that:
// 1. We got all queues
expect(result).toHaveLength(4);
// 2. Queues are grouped by environment
for (const envQueues of Object.values(queuesByEnv)) {
expect(envQueues).toHaveLength(2);
// 3. Within each environment, older queue comes before newer queue
const [firstQueue, secondQueue] = envQueues;
expect(firstQueue).toContain("old");
expect(secondQueue).toContain("new");
}
}
);
redisTest(
"should bias shuffling based on concurrency limits and available capacity",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const now = Date.now();
// Setup three environments with different concurrency settings
const envSetups = [
{
envId: "env-1",
orgId: "org-1",
projectId: "proj-1",
limit: 100,
current: 20, // Lots of available capacity
queueCount: 3,
},
{
envId: "env-2",
orgId: "org-1",
projectId: "proj-1",
limit: 50,
current: 40, // Less available capacity
queueCount: 3,
},
{
envId: "env-3",
orgId: "org-1",
projectId: "proj-1",
limit: 10,
current: 5, // Some available capacity
queueCount: 3,
},
];
// Setup queues and concurrency for each environment
for (const setup of envSetups) {
await setupConcurrency({
redis,
keyProducer,
env: {
envId: setup.envId,
projectId: setup.projectId,
orgId: setup.orgId,
currentConcurrency: setup.current,
limit: setup.limit,
},
});
for (let i = 0; i < setup.queueCount; i++) {
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - 1000 * (i + 1),
queueId: `queue-${i}`,
orgId: "org-1",
projectId: "proj-1",
envId: setup.envId,
});
}
}
// Create multiple strategies with different seeds
const numStrategies = 5;
const strategies = Array.from(
{ length: numStrategies },
(_, i) =>
new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: `test-seed-${i}`,
biases: {
concurrencyLimitBias: 0.8,
availableCapacityBias: 0.5,
queueAgeRandomization: 0.0,
},
})
);
// Run iterations across all strategies
const iterationsPerStrategy = 100;
const allResults: Record<string, number>[] = [];
for (const strategy of strategies) {
const firstPositionCounts: Record<string, number> = {};
for (let i = 0; i < iterationsPerStrategy; i++) {
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
`consumer-${i % 3}`
);
const result = flattenResults(envResult);
expect(result.length).toBeGreaterThan(0);
const firstEnv = keyProducer.envIdFromQueue(result[0]);
firstPositionCounts[firstEnv] = (firstPositionCounts[firstEnv] || 0) + 1;
}
allResults.push(firstPositionCounts);
}
// Calculate average distributions across all strategies
const avgDistribution: Record<string, number> = {};
const envIds = ["env-1", "env-2", "env-3"];
for (const envId of envIds) {
const sum = allResults.reduce((acc, result) => acc + (result[envId] || 0), 0);
avgDistribution[envId] = sum / numStrategies;
}
// Log individual strategy results and the average
console.log("\nResults by strategy:");
allResults.forEach((result, i) => {
console.log(`Strategy ${i + 1}:`, result);
});
console.log("\nAverage distribution:", avgDistribution);
// Calculate percentages from average distribution
const totalCount = Object.values(avgDistribution).reduce((sum, count) => sum + count, 0);
const highLimitPercentage = (avgDistribution["env-1"] / totalCount) * 100;
const lowLimitPercentage = (avgDistribution["env-3"] / totalCount) * 100;
console.log("\nPercentages:");
console.log("High limit percentage:", highLimitPercentage);
console.log("Low limit percentage:", lowLimitPercentage);
// Verify distribution across all strategies
expect(highLimitPercentage).toBeLessThan(60);
expect(lowLimitPercentage).toBeGreaterThan(10);
expect(highLimitPercentage).toBeGreaterThan(lowLimitPercentage);
}
);
redisTest(
"should respect ageInfluence parameter for queue ordering",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const now = Date.now();
// Setup queues with different ages in the same environment
const queueAges = [
{ id: "queue-1", age: 5000 }, // oldest
{ id: "queue-2", age: 3000 },
{ id: "queue-3", age: 1000 }, // newest
];
// Helper function to run iterations with a specific age influence
async function runWithQueueAgeRandomization(queueAgeRandomization: number) {
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "fixed-seed",
biases: {
concurrencyLimitBias: 0,
availableCapacityBias: 0,
queueAgeRandomization,
},
});
const positionCounts: Record<string, number[]> = {
"queue-1": [0, 0, 0],
"queue-2": [0, 0, 0],
"queue-3": [0, 0, 0],
};
const iterations = 1000;
for (let i = 0; i < iterations; i++) {
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
"consumer-1"
);
const result = flattenResults(envResult);
result.forEach((queueId, position) => {
const baseQueueId = queueId.split(":").pop()!;
positionCounts[baseQueueId][position]++;
});
}
return positionCounts;
}
// Setup test data
for (const { id, age } of queueAges) {
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - age,
queueId: id,
orgId: "org-1",
projectId: "proj-1",
envId: "env-1",
});
}
await setupConcurrency({
redis,
keyProducer,
env: {
envId: "env-1",
projectId: "proj-1",
orgId: "org-1",
currentConcurrency: 0,
limit: 5,
},
});
// Test with different age influence values
const strictAge = await runWithQueueAgeRandomization(0); // Strict age-based ordering
const mixed = await runWithQueueAgeRandomization(0.5); // Mix of age and random
const fullyRandom = await runWithQueueAgeRandomization(1); // Completely random
console.log("Distribution with strict age ordering (0.0):", strictAge);
console.log("Distribution with mixed ordering (0.5):", mixed);
console.log("Distribution with random ordering (1.0):", fullyRandom);
// With strict age ordering (0.0), oldest should always be first
expect(strictAge["queue-1"][0]).toBe(1000); // Always in first position
expect(strictAge["queue-3"][0]).toBe(0); // Never in first position
// With fully random (1.0), positions should still allow for some age bias
const randomFirstPositionSpread = Math.abs(
fullyRandom["queue-1"][0] - fullyRandom["queue-3"][0]
);
expect(randomFirstPositionSpread).toBeLessThan(200); // Allow for larger spread in distribution
// With mixed (0.5), should show preference for age but not absolute
expect(mixed["queue-1"][0]).toBeGreaterThan(mixed["queue-3"][0]); // Older preferred
expect(mixed["queue-3"][0]).toBeGreaterThan(0); // But newer still gets chances
}
);
redisTest(
"should respect maximumEnvCount and select envs based on queue ages",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "test-seed-max-orgs",
maximumEnvCount: 2, // Only select top 2 orgs
});
const now = Date.now();
// Setup 4 envs with different queue age profiles
const envSetups = [
{
envId: "env-1",
orgId: "org-1",
projectId: "proj-1",
queues: [
{ age: 1000 }, // Average age: 1000
],
},
{
envId: "env-2",
orgId: "org-1",
projectId: "proj-1",
queues: [
{ age: 5000 }, // Average age: 5000
{ age: 5000 },
],
},
{
envId: "env-3",
orgId: "org-1",
projectId: "proj-1",
queues: [
{ age: 2000 }, // Average age: 2000
{ age: 2000 },
],
},
{
envId: "env-4",
orgId: "org-1",
projectId: "proj-1",
queues: [
{ age: 500 }, // Average age: 500
{ age: 500 },
],
},
];
// Setup queues and concurrency for each org
for (const setup of envSetups) {
await setupConcurrency({
redis,
keyProducer,
env: {
envId: setup.envId,
projectId: setup.projectId,
orgId: setup.orgId,
currentConcurrency: 0,
limit: 5,
},
});
for (let i = 0; i < setup.queues.length; i++) {
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - setup.queues[i].age,
queueId: `queue-${setup.envId}-${i}`,
orgId: `org-${setup.envId}`,
projectId: `proj-${setup.envId}`,
envId: setup.envId,
});
}
}
// Run multiple iterations to verify consistent behavior
const iterations = 100;
const selectedEnvCounts: Record<string, number> = {};
for (let i = 0; i < iterations; i++) {
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
`consumer-${i}`
);
const result = flattenResults(envResult);
// Track which orgs were included in the result
const selectedEnvs = new Set(result.map((queueId) => keyProducer.envIdFromQueue(queueId)));
// Verify we never get more than maximumOrgCount orgs
expect(selectedEnvs.size).toBeLessThanOrEqual(2);
for (const envId of selectedEnvs) {
selectedEnvCounts[envId] = (selectedEnvCounts[envId] || 0) + 1;
}
}
console.log("Environment selection counts:", selectedEnvCounts);
// org-2 should be selected most often (highest average age)
expect(selectedEnvCounts["env-2"]).toBeGreaterThan(selectedEnvCounts["env-4"] || 0);
// org-4 should be selected least often (lowest average age)
const env4Count = selectedEnvCounts["env-4"] || 0;
expect(env4Count).toBeLessThan(selectedEnvCounts["env-2"]);
// Verify that envs with higher average queue age are selected more frequently
const sortedEnvs = Object.entries(selectedEnvCounts).sort((a, b) => b[1] - a[1]);
console.log("Sorted environment frequencies:", sortedEnvs);
// The top 2 most frequently selected orgs should be env-2 and env-3
// as they have the highest average queue ages
const topTwoEnvs = new Set([sortedEnvs[0][0], sortedEnvs[1][0]]);
expect(topTwoEnvs).toContain("env-2"); // Highest average age
expect(topTwoEnvs).toContain("env-3"); // Second highest average age
// Calculate selection percentages
const totalSelections = Object.values(selectedEnvCounts).reduce((a, b) => a + b, 0);
const selectionPercentages = Object.entries(selectedEnvCounts).reduce(
(acc, [orgId, count]) => {
acc[orgId] = (count / totalSelections) * 100;
return acc;
},
{} as Record<string, number>
);
console.log("Environment selection percentages:", selectionPercentages);
// Verify that env-2 (highest average age) gets selected in at least 40% of iterations
expect(selectionPercentages["env-2"]).toBeGreaterThan(40);
// Verify that env-4 (lowest average age) gets selected in less than 20% of iterations
expect(selectionPercentages["env-4"] || 0).toBeLessThan(20);
}
);
redisTest(
"should not overly bias picking environments when queue have priority offset ages",
async ({ redisOptions: redis }) => {
const keyProducer = new RunQueueFullKeyProducer();
const strategy = new FairQueueSelectionStrategy({
redis,
keys: keyProducer,
defaultEnvConcurrencyLimit: 5,
parentQueueLimit: 100,
seed: "test-seed-max-orgs",
maximumEnvCount: 2, // Only select top 2 orgs
});
const now = Date.now();
// Setup 4 envs with different queue age profiles
const envSetups = [
{
envId: "env-1",
queues: [
{ age: 1000 }, // Average age: 1000
],
},
{
envId: "env-2",
queues: [
{ age: 5000 + RUN_QUEUE_RESUME_PRIORITY_TIMESTAMP_OFFSET }, // Average age: 5000 + 1 year
{ age: 5000 + RUN_QUEUE_RESUME_PRIORITY_TIMESTAMP_OFFSET },
],
},
{
envId: "env-3",
queues: [
{ age: 2000 }, // Average age: 2000
{ age: 2000 },
],
},
{
envId: "env-4",
queues: [
{ age: 500 }, // Average age: 500
{ age: 500 },
],
},
];
// Setup queues and concurrency for each org
for (const setup of envSetups) {
await setupConcurrency({
redis,
keyProducer,
env: {
envId: setup.envId,
projectId: "proj-1",
orgId: "org-1",
currentConcurrency: 0,
limit: 5,
},
});
for (let i = 0; i < setup.queues.length; i++) {
await setupQueue({
redis,
keyProducer,
parentQueue: "parent-queue",
score: now - setup.queues[i].age,
queueId: `queue-${setup.envId}-${i}`,
orgId: `org-${setup.envId}`,
projectId: `proj-${setup.envId}`,
envId: setup.envId,
});
}
}
// Run multiple iterations to verify consistent behavior
const iterations = 100;
const selectedEnvCounts: Record<string, number> = {};
for (let i = 0; i < iterations; i++) {
const envResult = await strategy.distributeFairQueuesFromParentQueue(
"parent-queue",
`consumer-${i}`
);
const result = flattenResults(envResult);
// Track which orgs were included in the result
const selectedEnvs = new Set(result.map((queueId) => keyProducer.envIdFromQueue(queueId)));
// Verify we never get more than maximumOrgCount orgs
expect(selectedEnvs.size).toBeLessThanOrEqual(2);
for (const envId of selectedEnvs) {
selectedEnvCounts[envId] = (selectedEnvCounts[envId] || 0) + 1;
}
}
console.log("Environment selection counts:", selectedEnvCounts);
// org-2 should be selected most often (highest average age)
expect(selectedEnvCounts["env-2"]).toBeGreaterThan(selectedEnvCounts["env-4"] || 0);
// org-4 should be selected least often (lowest average age)
const env4Count = selectedEnvCounts["env-4"] || 0;
expect(env4Count).toBeLessThan(selectedEnvCounts["env-2"]);
// Verify that envs with higher average queue age are selected more frequently
const sortedEnvs = Object.entries(selectedEnvCounts).sort((a, b) => b[1] - a[1]);
console.log("Sorted environment frequencies:", sortedEnvs);