assignment-user-matcher 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENCE +21 -53
- package/README.md +184 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/managers/DecisionTraceManager.d.ts +34 -0
- package/dist/managers/DecisionTraceManager.d.ts.map +1 -0
- package/dist/managers/DecisionTraceManager.js +74 -0
- package/dist/managers/WorkflowManager.d.ts +6 -0
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +10 -0
- package/dist/matcher.class.d.ts +216 -2
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +1056 -77
- package/dist/scoring/fair-arbitration.d.ts +68 -0
- package/dist/scoring/fair-arbitration.d.ts.map +1 -0
- package/dist/scoring/fair-arbitration.js +151 -0
- package/dist/scoring/match-score.d.ts +17 -1
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +81 -1
- package/dist/tracing/decision-trace.d.ts +48 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -0
- package/dist/tracing/decision-trace.js +152 -0
- package/dist/types/matcher.d.ts +324 -0
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +6 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +10 -0
- package/package.json +58 -57
package/dist/matcher.class.js
CHANGED
|
@@ -8,7 +8,10 @@ const geo_1 = require("./utils/geo");
|
|
|
8
8
|
const keys_1 = require("./utils/keys");
|
|
9
9
|
const pagination_1 = require("./queries/pagination");
|
|
10
10
|
const match_score_1 = require("./scoring/match-score");
|
|
11
|
+
const fair_arbitration_1 = require("./scoring/fair-arbitration");
|
|
12
|
+
const decision_trace_1 = require("./tracing/decision-trace");
|
|
11
13
|
const features_1 = require("./learning/features");
|
|
14
|
+
const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
|
|
12
15
|
const LearningManager_1 = require("./managers/LearningManager");
|
|
13
16
|
const ReliabilityManager_1 = require("./managers/ReliabilityManager");
|
|
14
17
|
const TelemetryManager_1 = require("./managers/TelemetryManager");
|
|
@@ -60,6 +63,14 @@ class AssignmentMatcher {
|
|
|
60
63
|
this.geoDefaultMaxDistanceKm = options?.geoDefaultMaxDistanceKm;
|
|
61
64
|
this.geoScoreWeight = options?.geoScoreWeight ?? 0;
|
|
62
65
|
this.geoMatchingFunction = options?.geoMatchingFunction;
|
|
66
|
+
this.enableFairTiebreaker = options?.enableFairTiebreaker ?? false;
|
|
67
|
+
this.fairnessMode = options?.fairness;
|
|
68
|
+
if (this.fairnessMode)
|
|
69
|
+
this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
|
|
70
|
+
this.fairnessLoadPenalty = options?.fairnessLoadPenalty ?? 0;
|
|
71
|
+
this.fairnessTieBand = options?.fairnessTieBand ?? 0;
|
|
72
|
+
this.fairnessMaxPerWindow = options?.fairnessMaxPerWindow;
|
|
73
|
+
this.fairnessWindowMs = options?.fairnessWindowMs ?? 3600000;
|
|
63
74
|
// Workflow options
|
|
64
75
|
this.enableWorkflows = options?.enableWorkflows ?? false;
|
|
65
76
|
this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
|
|
@@ -95,6 +106,13 @@ class AssignmentMatcher {
|
|
|
95
106
|
trackTagStats: this.enableAutoRoutingWeights,
|
|
96
107
|
autoWeights: options?.autoRoutingWeights,
|
|
97
108
|
});
|
|
109
|
+
// Decision traces (opt-in explainability/audit records per routing decision)
|
|
110
|
+
this.enableDecisionTraces = options?.enableDecisionTraces ?? false;
|
|
111
|
+
this.decisionTraceMaxCandidates = options?.decisionTraceMaxCandidates ?? 25;
|
|
112
|
+
this.decisionTraces = new DecisionTraceManager_1.DecisionTraceManager(this.redisClient, this.keys, {
|
|
113
|
+
maxEntries: options?.decisionTraceMaxEntries ?? 1000,
|
|
114
|
+
onDecision: options?.onMatchDecision,
|
|
115
|
+
});
|
|
98
116
|
this.workflow = new WorkflowManager_1.WorkflowManager(this.redisClient, this.keys, this.reliability, this.telemetry, this, {
|
|
99
117
|
enableWorkflows: this.enableWorkflows,
|
|
100
118
|
streamConsumerGroup: this.streamConsumerGroup,
|
|
@@ -331,6 +349,348 @@ class AssignmentMatcher {
|
|
|
331
349
|
await this.readyPromise;
|
|
332
350
|
return this.learning.shadowMode;
|
|
333
351
|
}
|
|
352
|
+
/**
|
|
353
|
+
* Toggle fair-tiebreaker global best-match arbitration at runtime.
|
|
354
|
+
* See `MatcherOptions.enableFairTiebreaker` for what this changes.
|
|
355
|
+
*/
|
|
356
|
+
setFairTiebreaker(enabled) {
|
|
357
|
+
this.enableFairTiebreaker = !!enabled;
|
|
358
|
+
}
|
|
359
|
+
/** Current runtime fair-tiebreaker state. */
|
|
360
|
+
isFairTiebreakerEnabled() {
|
|
361
|
+
return this.enableFairTiebreaker;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Switch the bulk-matching fairness policy at runtime — shorthand for
|
|
365
|
+
* `setFairnessConfig({ fairness: mode })`. See `MatcherOptions.fairness`
|
|
366
|
+
* for what each mode does.
|
|
367
|
+
*/
|
|
368
|
+
setFairness(mode) {
|
|
369
|
+
this.setFairnessConfig({ fairness: mode });
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Retune any subset of the bulk-matching fairness knobs at runtime without
|
|
373
|
+
* reconstructing the matcher. Absent fields are left unchanged; the new
|
|
374
|
+
* values take effect on the next `matchUsersAssignments()` call (a match
|
|
375
|
+
* already in flight keeps the values it started with). Merge semantics
|
|
376
|
+
* mirror the constructor exactly — in particular, an explicit `fairness`
|
|
377
|
+
* overrides `enableFairTiebreaker`. See `MatcherOptions` for each field.
|
|
378
|
+
*/
|
|
379
|
+
setFairnessConfig(config) {
|
|
380
|
+
if ('enableFairTiebreaker' in config)
|
|
381
|
+
this.enableFairTiebreaker = !!config.enableFairTiebreaker;
|
|
382
|
+
if ('fairness' in config) {
|
|
383
|
+
this.fairnessMode = config.fairness;
|
|
384
|
+
if (this.fairnessMode)
|
|
385
|
+
this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
|
|
386
|
+
}
|
|
387
|
+
if ('fairnessLoadPenalty' in config)
|
|
388
|
+
this.fairnessLoadPenalty = config.fairnessLoadPenalty ?? 0;
|
|
389
|
+
if ('fairnessTieBand' in config)
|
|
390
|
+
this.fairnessTieBand = config.fairnessTieBand ?? 0;
|
|
391
|
+
if ('fairnessMaxPerWindow' in config)
|
|
392
|
+
this.fairnessMaxPerWindow = config.fairnessMaxPerWindow;
|
|
393
|
+
if ('fairnessWindowMs' in config)
|
|
394
|
+
this.fairnessWindowMs = config.fairnessWindowMs ?? 3600000;
|
|
395
|
+
}
|
|
396
|
+
/** Current runtime fairness policy. */
|
|
397
|
+
getFairness() {
|
|
398
|
+
if (!this.enableFairTiebreaker)
|
|
399
|
+
return 'first-come';
|
|
400
|
+
return this.fairnessMode ?? 'best-match';
|
|
401
|
+
}
|
|
402
|
+
/** Snapshot of the live fairness configuration. */
|
|
403
|
+
getFairnessConfig() {
|
|
404
|
+
return {
|
|
405
|
+
fairness: this.getFairness(),
|
|
406
|
+
enableFairTiebreaker: this.enableFairTiebreaker,
|
|
407
|
+
fairnessLoadPenalty: this.fairnessLoadPenalty,
|
|
408
|
+
fairnessTieBand: this.fairnessTieBand,
|
|
409
|
+
fairnessMaxPerWindow: this.fairnessMaxPerWindow,
|
|
410
|
+
fairnessWindowMs: this.fairnessWindowMs,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
// ============================================================================
|
|
414
|
+
// Decision Traces & Explainability
|
|
415
|
+
// ============================================================================
|
|
416
|
+
/** Whether trace capture should run this pass (persistence flag or real-time hook). */
|
|
417
|
+
get tracingActive() {
|
|
418
|
+
return this.enableDecisionTraces || this.decisionTraces.hasDecisionHook;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Toggle decision-trace persistence at runtime without reconstructing the
|
|
422
|
+
* matcher. Takes effect on the next matching pass (a pass already in
|
|
423
|
+
* flight keeps the value it started with).
|
|
424
|
+
*/
|
|
425
|
+
setDecisionTraces(enabled) {
|
|
426
|
+
this.enableDecisionTraces = !!enabled;
|
|
427
|
+
}
|
|
428
|
+
/** Current runtime decision-trace persistence state. */
|
|
429
|
+
isDecisionTracesEnabled() {
|
|
430
|
+
return this.enableDecisionTraces;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Query recorded decision traces, newest first. Only decisions made while
|
|
434
|
+
* `enableDecisionTraces` was active are stored — traces are captured as
|
|
435
|
+
* decisions happen, never reconstructed after the fact.
|
|
436
|
+
*/
|
|
437
|
+
async getDecisionTraces(query) {
|
|
438
|
+
await this.readyPromise;
|
|
439
|
+
return this.decisionTraces.getTraces(query);
|
|
440
|
+
}
|
|
441
|
+
/** Delete all recorded decision traces. */
|
|
442
|
+
async clearDecisionTraces() {
|
|
443
|
+
await this.readyPromise;
|
|
444
|
+
return this.decisionTraces.clear();
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Explain, from live state, which users could receive an assignment and
|
|
448
|
+
* why each one is or is not eligible: vetoes, prior rejections, skill
|
|
449
|
+
* thresholds, CIDR and geo constraints, backlog, the full score breakdown,
|
|
450
|
+
* and learning influence. Works for assignments in any lifecycle state;
|
|
451
|
+
* for matched assignments the current owner is flagged `chosen` (accepted
|
|
452
|
+
* assignments report `ownerId: null` because ownership metadata is
|
|
453
|
+
* released on acceptance — decision traces retain the full history).
|
|
454
|
+
*
|
|
455
|
+
* This is an on-demand recomputation against current state. For the
|
|
456
|
+
* auditable record of a decision as it actually happened, use
|
|
457
|
+
* `getDecisionTraces()`.
|
|
458
|
+
*/
|
|
459
|
+
async explainMatch(assignmentId, opts) {
|
|
460
|
+
await this.readyPromise;
|
|
461
|
+
const evaluatedAt = Date.now();
|
|
462
|
+
let found = await (0, pagination_1.getAssignmentById)(this.redisClient, this.assignmentStoreKeys, assignmentId);
|
|
463
|
+
let status;
|
|
464
|
+
if (found) {
|
|
465
|
+
status = (found._status ?? 'queued');
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
// getAssignmentById only covers queued/pending/accepted
|
|
469
|
+
const completedJson = await this.redisClient.hGet(this.completedAssignmentsKey, assignmentId);
|
|
470
|
+
if (!completedJson) {
|
|
471
|
+
return { assignmentId, status: 'not_found', ownerId: null, evaluatedAt, candidates: [] };
|
|
472
|
+
}
|
|
473
|
+
found = JSON.parse(completedJson);
|
|
474
|
+
status = 'completed';
|
|
475
|
+
}
|
|
476
|
+
const assignment = found;
|
|
477
|
+
let ownerId = null;
|
|
478
|
+
if (status === 'pending') {
|
|
479
|
+
ownerId = (await this.redisClient.hGet(this.assignmentOwnerKey, assignmentId)) ?? null;
|
|
480
|
+
}
|
|
481
|
+
else if (status === 'completed') {
|
|
482
|
+
ownerId = assignment._completedBy ?? assignment._failedBy ?? null;
|
|
483
|
+
}
|
|
484
|
+
// Queued assignments may have had their priority retuned since creation
|
|
485
|
+
let basePriority = Number(assignment.priority) || 0;
|
|
486
|
+
if (status === 'queued') {
|
|
487
|
+
const stored = await this.redisClient.hGet(this.keys.assignmentPriority(assignmentId), 'priority');
|
|
488
|
+
if (stored !== null && stored !== undefined)
|
|
489
|
+
basePriority = Number(stored) || 0;
|
|
490
|
+
}
|
|
491
|
+
// Mirror the tags CSV the scoring path sees (the stored tags hash appends 'default')
|
|
492
|
+
const tagsCsv = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
|
|
493
|
+
let userList;
|
|
494
|
+
if (opts?.userIds && opts.userIds.length > 0) {
|
|
495
|
+
const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
|
|
496
|
+
userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
|
|
497
|
+
}
|
|
498
|
+
else {
|
|
499
|
+
const all = await this.redisClient.hGetAll(this.usersKey);
|
|
500
|
+
userList = Object.values(all).map((json) => JSON.parse(json));
|
|
501
|
+
}
|
|
502
|
+
const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
|
|
503
|
+
const candidates = await Promise.all(userList.map((user) => this.explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights)));
|
|
504
|
+
(0, decision_trace_1.sortCandidates)(candidates);
|
|
505
|
+
return { assignmentId, status, ownerId, evaluatedAt, candidates };
|
|
506
|
+
}
|
|
507
|
+
/** One user's full eligibility/score evaluation for explainMatch(). */
|
|
508
|
+
async explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights) {
|
|
509
|
+
const reasons = [];
|
|
510
|
+
let eligible = true;
|
|
511
|
+
if (assignment.vetoedUsers?.includes(user.id)) {
|
|
512
|
+
reasons.push({ kind: 'assignmentVeto' });
|
|
513
|
+
eligible = false;
|
|
514
|
+
}
|
|
515
|
+
const [isRejected, backlog, isPaused] = await Promise.all([
|
|
516
|
+
this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId),
|
|
517
|
+
this.redisClient.sCard(this.keys.userAssignments(user.id)),
|
|
518
|
+
this.redisClient.sIsMember(this.keys.pausedUsers(), user.id),
|
|
519
|
+
]);
|
|
520
|
+
if (isRejected) {
|
|
521
|
+
reasons.push({ kind: 'rejectedPreviously' });
|
|
522
|
+
eligible = false;
|
|
523
|
+
}
|
|
524
|
+
if (isPaused) {
|
|
525
|
+
reasons.push({ kind: 'paused' });
|
|
526
|
+
eligible = false;
|
|
527
|
+
}
|
|
528
|
+
const backlogLimit = this.backlogLimitFor(user);
|
|
529
|
+
if (backlog >= backlogLimit) {
|
|
530
|
+
reasons.push({ kind: 'backlogFull', backlog, limit: backlogLimit });
|
|
531
|
+
eligible = false;
|
|
532
|
+
}
|
|
533
|
+
const routingWeights = user.routingWeights;
|
|
534
|
+
const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
|
|
535
|
+
if (hasRoutingWeights &&
|
|
536
|
+
this.usingDefaultMatchScore &&
|
|
537
|
+
!Object.values(routingWeights).some((w) => typeof w === 'number' && w > 0)) {
|
|
538
|
+
reasons.push({ kind: 'noPositiveWeights' });
|
|
539
|
+
eligible = false;
|
|
540
|
+
}
|
|
541
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, assignment.allowedCidrs)) {
|
|
542
|
+
reasons.push({ kind: 'cidrMismatch', ip: user.ip });
|
|
543
|
+
eligible = false;
|
|
544
|
+
}
|
|
545
|
+
const geoMatch = await this.evaluateGeoMatch(user, assignment);
|
|
546
|
+
let geoBoost = 0;
|
|
547
|
+
if (!geoMatch.eligible) {
|
|
548
|
+
reasons.push({
|
|
549
|
+
kind: 'geoDistance',
|
|
550
|
+
distanceKm: geoMatch.distanceKm,
|
|
551
|
+
maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
|
|
552
|
+
withinRange: false,
|
|
553
|
+
});
|
|
554
|
+
eligible = false;
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
geoBoost = this.calculateGeoBoost(geoMatch);
|
|
558
|
+
if (typeof geoMatch.distanceKm === 'number') {
|
|
559
|
+
reasons.push({
|
|
560
|
+
kind: 'geoDistance',
|
|
561
|
+
distanceKm: geoMatch.distanceKm,
|
|
562
|
+
maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
|
|
563
|
+
withinRange: true,
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
if (geoBoost > 0)
|
|
567
|
+
reasons.push({ kind: 'geoBoost', boost: geoBoost });
|
|
568
|
+
}
|
|
569
|
+
let score;
|
|
570
|
+
let combinedPriority;
|
|
571
|
+
if (this.usingDefaultMatchScore) {
|
|
572
|
+
const explained = (0, match_score_1.explainMatchScore)(user, tagsCsv, basePriority, this.enableDefaultMatching, assignment.skillThresholds);
|
|
573
|
+
score = explained.score;
|
|
574
|
+
combinedPriority = explained.combinedPriority;
|
|
575
|
+
reasons.push(...explained.reasons);
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
[score, combinedPriority] = await this.matchScore(user, tagsCsv, basePriority, assignmentId, assignment.skillThresholds);
|
|
579
|
+
reasons.push({ kind: 'customScore', score });
|
|
580
|
+
}
|
|
581
|
+
if (!score)
|
|
582
|
+
eligible = false;
|
|
583
|
+
let learningBoost = 0;
|
|
584
|
+
if (this.enableLearning && modelWeights) {
|
|
585
|
+
const context = { ...assignment, id: assignmentId, tags: assignment.tags };
|
|
586
|
+
const features = this.learningFeatureExtractor(user, context);
|
|
587
|
+
const predicted = this.learning.predict(features, modelWeights);
|
|
588
|
+
const shadowMode = this.learning.shadowMode;
|
|
589
|
+
learningBoost = shadowMode ? 0 : this.learning.boostFactor * predicted;
|
|
590
|
+
reasons.push({ kind: 'learningBoost', predicted, boost: learningBoost, shadowMode });
|
|
591
|
+
}
|
|
592
|
+
return {
|
|
593
|
+
userId: user.id,
|
|
594
|
+
eligible,
|
|
595
|
+
chosen: ownerId === user.id,
|
|
596
|
+
score,
|
|
597
|
+
effectivePriority: combinedPriority + geoBoost + learningBoost,
|
|
598
|
+
reasons,
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
/** Build and record this pass's decision traces; failures never break matching. */
|
|
602
|
+
async recordPassTraces(collector, winners, workflowGrants, mode, users) {
|
|
603
|
+
if (winners.size === 0 && workflowGrants.length === 0)
|
|
604
|
+
return;
|
|
605
|
+
try {
|
|
606
|
+
// A workflow-targeted assignment is also tag-indexed, so the
|
|
607
|
+
// tag-scored path can claim it in the same pass. One decision,
|
|
608
|
+
// one trace: the deterministic targeting is the authoritative
|
|
609
|
+
// story, so the 'workflow' record wins.
|
|
610
|
+
for (const grant of workflowGrants)
|
|
611
|
+
winners.delete(grant.assignmentId);
|
|
612
|
+
const matchedAt = Date.now();
|
|
613
|
+
const contexts = await this.getTraceUserContexts(users);
|
|
614
|
+
const traces = [
|
|
615
|
+
...(0, decision_trace_1.buildDecisionTraces)({
|
|
616
|
+
collector,
|
|
617
|
+
winners,
|
|
618
|
+
mode,
|
|
619
|
+
users: contexts,
|
|
620
|
+
maxCandidates: this.decisionTraceMaxCandidates,
|
|
621
|
+
matchedAt,
|
|
622
|
+
}),
|
|
623
|
+
...(0, decision_trace_1.buildWorkflowTraces)(workflowGrants, matchedAt),
|
|
624
|
+
];
|
|
625
|
+
await this.decisionTraces.record(traces, this.enableDecisionTraces);
|
|
626
|
+
}
|
|
627
|
+
catch (err) {
|
|
628
|
+
console.error('Failed to record decision traces:', err);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
/** Exclusion sets used to enrich traces with prefiltered (vetoed/rejected/paused) users. */
|
|
632
|
+
async getTraceUserContexts(users) {
|
|
633
|
+
const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
|
|
634
|
+
return Promise.all(users.map(async (user) => {
|
|
635
|
+
const [rejected, vetoed] = await Promise.all([
|
|
636
|
+
this.redisClient.sMembers(this.keys.userRejected(user.id)),
|
|
637
|
+
this.redisClient.sMembers(this.keys.userVetoed(user.id)),
|
|
638
|
+
]);
|
|
639
|
+
return {
|
|
640
|
+
user,
|
|
641
|
+
rejected: new Set(rejected),
|
|
642
|
+
vetoed: new Set(vetoed),
|
|
643
|
+
paused: paused.has(user.id),
|
|
644
|
+
};
|
|
645
|
+
}));
|
|
646
|
+
}
|
|
647
|
+
/** One sMembers per pass: the user list minus currently paused users. */
|
|
648
|
+
async filterPausedUsers(users) {
|
|
649
|
+
const paused = await this.redisClient.sMembers(this.keys.pausedUsers());
|
|
650
|
+
if (paused.length === 0)
|
|
651
|
+
return users;
|
|
652
|
+
const pausedSet = new Set(paused);
|
|
653
|
+
return users.filter((user) => !pausedSet.has(user.id));
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Workflow-targeted assignments are re-granted idempotently on every
|
|
657
|
+
* matching pass until actioned; only first-time grants deserve a decision
|
|
658
|
+
* trace. Reads membership before the sAdd that follows.
|
|
659
|
+
*/
|
|
660
|
+
async filterNewWorkflowGrants(user, workflowTargeted) {
|
|
661
|
+
if (workflowTargeted.length === 0)
|
|
662
|
+
return [];
|
|
663
|
+
const memberships = await this.redisClient.smIsMember(this.keys.userAssignments(user.id), workflowTargeted.map((w) => `assignment:${w.id}`));
|
|
664
|
+
return workflowTargeted
|
|
665
|
+
.filter((_, i) => !memberships[i])
|
|
666
|
+
.map((w) => ({ assignmentId: w.id, userId: user.id, priority: w.priority }));
|
|
667
|
+
}
|
|
668
|
+
/** Reasons for one scored candidate evaluation (trace capture only). */
|
|
669
|
+
traceScoreReasons(user, detail, score, geoMatch, geoBoost, learning) {
|
|
670
|
+
const reasons = this.usingDefaultMatchScore
|
|
671
|
+
? (0, match_score_1.explainMatchScore)(user, detail.tags, detail.basePriority, this.enableDefaultMatching, detail.skillThresholds)
|
|
672
|
+
.reasons
|
|
673
|
+
: [{ kind: 'customScore', score }];
|
|
674
|
+
if (typeof geoMatch.distanceKm === 'number') {
|
|
675
|
+
reasons.push({
|
|
676
|
+
kind: 'geoDistance',
|
|
677
|
+
distanceKm: geoMatch.distanceKm,
|
|
678
|
+
maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
|
|
679
|
+
withinRange: true,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
if (geoBoost > 0)
|
|
683
|
+
reasons.push({ kind: 'geoBoost', boost: geoBoost });
|
|
684
|
+
if (learning) {
|
|
685
|
+
reasons.push({
|
|
686
|
+
kind: 'learningBoost',
|
|
687
|
+
predicted: learning.predicted,
|
|
688
|
+
boost: learning.boost,
|
|
689
|
+
shadowMode: learning.shadowMode,
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
return reasons;
|
|
693
|
+
}
|
|
334
694
|
// ============================================================================
|
|
335
695
|
// Auto Routing Weights (RL-generated tags/weights)
|
|
336
696
|
// ============================================================================
|
|
@@ -460,6 +820,9 @@ class AssignmentMatcher {
|
|
|
460
820
|
const multi = this.redisClient
|
|
461
821
|
.multi()
|
|
462
822
|
.hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
|
|
823
|
+
// NX: a requeue (reject/expiry re-adds via this method) keeps the
|
|
824
|
+
// original first-enqueue wait clock.
|
|
825
|
+
.zAdd(this.keys.assignmentsQueuedAt(), { score: Date.now(), value: id }, { NX: true })
|
|
463
826
|
.hSet(assignmentPriorityKey, 'priority', priority)
|
|
464
827
|
// Ensure 'default' tag is persisted consistently when enabled
|
|
465
828
|
.hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
|
|
@@ -474,6 +837,14 @@ class AssignmentMatcher {
|
|
|
474
837
|
member: id,
|
|
475
838
|
});
|
|
476
839
|
}
|
|
840
|
+
// Index hard vetoes both ways: assignment -> users for cleanup,
|
|
841
|
+
// user -> assignments for exclusion via ZDIFFSTORE during matching.
|
|
842
|
+
if (assignment.vetoedUsers && assignment.vetoedUsers.length > 0) {
|
|
843
|
+
multi.sAdd(this.keys.assignmentVetoed(id), assignment.vetoedUsers);
|
|
844
|
+
for (const vetoedUserId of assignment.vetoedUsers) {
|
|
845
|
+
multi.sAdd(this.keys.userVetoed(vetoedUserId), id);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
477
848
|
// Also index assignment into per-tag sorted sets (by priority)
|
|
478
849
|
// This enables efficient weighted matching via ZUNIONSTORE.
|
|
479
850
|
const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
@@ -492,10 +863,11 @@ class AssignmentMatcher {
|
|
|
492
863
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
493
864
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
494
865
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
495
|
-
// Fetch tags
|
|
496
|
-
const [tagsCsv, owner] = await Promise.all([
|
|
866
|
+
// Fetch tags, owner (in case it's pending), and vetoed users for index cleanup
|
|
867
|
+
const [tagsCsv, owner, vetoedUsers] = await Promise.all([
|
|
497
868
|
this.redisClient.hGet(assignmentTagsKey, 'tags'),
|
|
498
869
|
this.redisClient.hGet(this.assignmentOwnerKey, id),
|
|
870
|
+
this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
|
|
499
871
|
]);
|
|
500
872
|
let tags = [];
|
|
501
873
|
if (tagsCsv && tagsCsv.length > 0) {
|
|
@@ -507,10 +879,15 @@ class AssignmentMatcher {
|
|
|
507
879
|
multi.del(assignmentPriorityKey);
|
|
508
880
|
multi.del(assignmentTagsKey);
|
|
509
881
|
multi.zRem(this.assignmentsKey, id.toString());
|
|
882
|
+
multi.zRem(this.keys.assignmentsQueuedAt(), id.toString());
|
|
510
883
|
for (const tag of tags) {
|
|
511
884
|
multi.zRem(this.keys.tagAssignments(tag), id.toString());
|
|
512
885
|
}
|
|
513
886
|
multi.zRem(assignmentGeoKey, id.toString());
|
|
887
|
+
multi.del(this.keys.assignmentVetoed(id));
|
|
888
|
+
for (const vetoedUserId of vetoedUsers) {
|
|
889
|
+
multi.sRem(this.keys.userVetoed(vetoedUserId), id);
|
|
890
|
+
}
|
|
514
891
|
// 2. Remove from Pending state
|
|
515
892
|
multi.hDel(this.pendingAssignmentsKey, id);
|
|
516
893
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
@@ -529,11 +906,78 @@ class AssignmentMatcher {
|
|
|
529
906
|
.multi()
|
|
530
907
|
.del(this.keys.userAssignments(userId))
|
|
531
908
|
.del(this.keys.userRejected(userId))
|
|
909
|
+
.del(this.keys.userVetoed(userId))
|
|
532
910
|
.zRem(this.keys.userActivity(), userId)
|
|
911
|
+
.sRem(this.keys.pausedUsers(), userId)
|
|
533
912
|
.hDel(this.usersKey, userId);
|
|
534
913
|
await multi.exec();
|
|
535
914
|
return userId;
|
|
536
915
|
}
|
|
916
|
+
/**
|
|
917
|
+
* Get one stored user as last written by addUser (including the injected
|
|
918
|
+
* 'default' tag when enableDefaultMatching is on), or null.
|
|
919
|
+
*/
|
|
920
|
+
async getUser(userId) {
|
|
921
|
+
await this.readyPromise;
|
|
922
|
+
const json = await this.redisClient.hGet(this.usersKey, userId);
|
|
923
|
+
return json ? JSON.parse(json) : null;
|
|
924
|
+
}
|
|
925
|
+
/** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
|
|
926
|
+
async getUsers() {
|
|
927
|
+
await this.readyPromise;
|
|
928
|
+
const users = [];
|
|
929
|
+
let cursor = '0';
|
|
930
|
+
do {
|
|
931
|
+
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
932
|
+
users.push(...entries.map((t) => JSON.parse(t.value)));
|
|
933
|
+
cursor = nextCursor;
|
|
934
|
+
} while (cursor !== '0');
|
|
935
|
+
return users;
|
|
936
|
+
}
|
|
937
|
+
// ============================================================================
|
|
938
|
+
// Worker Availability (pause/resume)
|
|
939
|
+
// ============================================================================
|
|
940
|
+
/**
|
|
941
|
+
* Pause a user: they stop receiving new assignments in every matching path
|
|
942
|
+
* until resumed, but keep their pending backlog and can still accept,
|
|
943
|
+
* complete, reject, or fail work they already hold. Paused users are also
|
|
944
|
+
* exempt from idle auto-removal (pausing is deliberate absence, not
|
|
945
|
+
* idleness). Idempotent.
|
|
946
|
+
*
|
|
947
|
+
* @returns false when the user is not in the pool (nothing is recorded)
|
|
948
|
+
*/
|
|
949
|
+
async pauseUser(userId) {
|
|
950
|
+
await this.readyPromise;
|
|
951
|
+
const exists = await this.redisClient.hExists(this.usersKey, userId);
|
|
952
|
+
if (!exists)
|
|
953
|
+
return false;
|
|
954
|
+
await this.redisClient.sAdd(this.keys.pausedUsers(), userId);
|
|
955
|
+
return true;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Resume a paused user so matching considers them again on the next pass.
|
|
959
|
+
* Also records activity (resets the idle clock).
|
|
960
|
+
*
|
|
961
|
+
* @returns false when the user was not paused
|
|
962
|
+
*/
|
|
963
|
+
async resumeUser(userId) {
|
|
964
|
+
await this.readyPromise;
|
|
965
|
+
const wasPaused = await this.redisClient.sRem(this.keys.pausedUsers(), userId);
|
|
966
|
+
if (wasPaused)
|
|
967
|
+
await this.touchUser(userId);
|
|
968
|
+
return wasPaused > 0;
|
|
969
|
+
}
|
|
970
|
+
/** Whether a user is currently paused. */
|
|
971
|
+
async isUserPaused(userId) {
|
|
972
|
+
await this.readyPromise;
|
|
973
|
+
return Boolean(await this.redisClient.sIsMember(this.keys.pausedUsers(), userId));
|
|
974
|
+
}
|
|
975
|
+
/** IDs of all currently paused users. */
|
|
976
|
+
async getPausedUsers() {
|
|
977
|
+
await this.readyPromise;
|
|
978
|
+
const members = await this.redisClient.sMembers(this.keys.pausedUsers());
|
|
979
|
+
return members.sort();
|
|
980
|
+
}
|
|
537
981
|
/**
|
|
538
982
|
* Get all assignments (queued, pending, and accepted).
|
|
539
983
|
* For large datasets, prefer using getAssignmentsPaginated() instead.
|
|
@@ -574,6 +1018,42 @@ class AssignmentMatcher {
|
|
|
574
1018
|
await this.readyPromise;
|
|
575
1019
|
return (0, pagination_1.getAssignmentsByIdsBatch)(this.redisClient, this.assignmentStoreKeys, ids);
|
|
576
1020
|
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Live operational snapshot for dashboards: queued/pending counts, the
|
|
1023
|
+
* age of the longest-waiting unaccepted assignment, and every user's
|
|
1024
|
+
* backlog depth, effective cap, and paused state. The wait clock starts
|
|
1025
|
+
* at first enqueue and survives reject/expiry requeues; it stops on
|
|
1026
|
+
* accept or removal.
|
|
1027
|
+
*/
|
|
1028
|
+
async getQueueStats() {
|
|
1029
|
+
await this.readyPromise;
|
|
1030
|
+
const [counts, oldestEntries, pausedMembers] = await Promise.all([
|
|
1031
|
+
(0, pagination_1.getAssignmentCountsFromStores)(this.redisClient, this.assignmentStoreKeys),
|
|
1032
|
+
this.redisClient.zRangeWithScores(this.keys.assignmentsQueuedAt(), 0, 0),
|
|
1033
|
+
this.redisClient.sMembers(this.keys.pausedUsers()),
|
|
1034
|
+
]);
|
|
1035
|
+
const paused = new Set(pausedMembers);
|
|
1036
|
+
const users = [];
|
|
1037
|
+
let cursor = '0';
|
|
1038
|
+
do {
|
|
1039
|
+
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1040
|
+
users.push(...entries.map((t) => JSON.parse(t.value)));
|
|
1041
|
+
cursor = nextCursor;
|
|
1042
|
+
} while (cursor !== '0');
|
|
1043
|
+
const perUser = await Promise.all(users.map(async (user) => ({
|
|
1044
|
+
userId: user.id,
|
|
1045
|
+
backlog: await this.redisClient.sCard(this.keys.userAssignments(user.id)),
|
|
1046
|
+
maxBacklogSize: this.backlogLimitFor(user),
|
|
1047
|
+
paused: paused.has(user.id),
|
|
1048
|
+
})));
|
|
1049
|
+
perUser.sort((a, b) => a.userId.localeCompare(b.userId));
|
|
1050
|
+
return {
|
|
1051
|
+
queued: counts.queued,
|
|
1052
|
+
pending: counts.pending,
|
|
1053
|
+
oldestWaitingMs: oldestEntries.length > 0 ? Date.now() - Number(oldestEntries[0].score) : null,
|
|
1054
|
+
perUser,
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
577
1057
|
/**
|
|
578
1058
|
* Get all pending assignments with owner and pending duration metadata.
|
|
579
1059
|
*/
|
|
@@ -677,22 +1157,37 @@ class AssignmentMatcher {
|
|
|
677
1157
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
678
1158
|
// Fetch tags to update per-tag indices
|
|
679
1159
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
680
|
-
const [
|
|
1160
|
+
const [refJson, tagsCsv] = (await this.redisClient
|
|
681
1161
|
.multi()
|
|
682
|
-
.
|
|
1162
|
+
.hGet(this.assignmentsRefKey, id)
|
|
683
1163
|
.hGet(assignmentTagsKey, 'tags')
|
|
684
1164
|
.exec());
|
|
685
1165
|
const tags = (tagsCsv && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
|
|
686
1166
|
const multi = this.redisClient.multi();
|
|
687
1167
|
multi.hSet(assignmentPriorityKey, 'priority', priority);
|
|
688
|
-
if (
|
|
689
|
-
// Update global zset score and per-tag zset scores only if assignment still exists
|
|
1168
|
+
if (refJson) {
|
|
1169
|
+
// Update global zset score and per-tag zset scores only if assignment still exists,
|
|
1170
|
+
// plus the stored record itself so reads see the new priority.
|
|
1171
|
+
multi.hSet(this.assignmentsRefKey, id, JSON.stringify({ ...JSON.parse(refJson), priority }));
|
|
690
1172
|
multi.zAdd(this.assignmentsKey, { score: Number(priority), value: id });
|
|
691
1173
|
for (const tag of tags) {
|
|
692
1174
|
multi.zAdd(this.keys.tagAssignments(tag), { score: Number(priority), value: id });
|
|
693
1175
|
}
|
|
694
1176
|
}
|
|
695
1177
|
await multi.exec();
|
|
1178
|
+
if (refJson) {
|
|
1179
|
+
// The snapshot read above races the atomic claim gate: if a claim
|
|
1180
|
+
// HDELed the record between our read and write, the writes above
|
|
1181
|
+
// resurrected a ghost queued entry. Detect and undo.
|
|
1182
|
+
const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
|
|
1183
|
+
if (owner) {
|
|
1184
|
+
const cleanup = this.redisClient.multi().hDel(this.assignmentsRefKey, id).zRem(this.assignmentsKey, id);
|
|
1185
|
+
for (const tag of tags) {
|
|
1186
|
+
cleanup.zRem(this.keys.tagAssignments(tag), id);
|
|
1187
|
+
}
|
|
1188
|
+
await cleanup.exec();
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
696
1191
|
return { id, priority };
|
|
697
1192
|
}
|
|
698
1193
|
async setAssignmentPriorityByTags(tags, priority) {
|
|
@@ -721,7 +1216,33 @@ class AssignmentMatcher {
|
|
|
721
1216
|
}
|
|
722
1217
|
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
723
1218
|
}
|
|
724
|
-
|
|
1219
|
+
/**
|
|
1220
|
+
* Read-only candidate discovery for one user: workflow-targeted lookups,
|
|
1221
|
+
* the weighted per-tag zset union/diff, and per-candidate scoring
|
|
1222
|
+
* (learning-influenced or plain, matching the existing behavior exactly).
|
|
1223
|
+
* Does NOT claim anything - see claimSelected() for that. Split out so
|
|
1224
|
+
* matchAllUsersFair() can evaluate every user's candidates before any of
|
|
1225
|
+
* them claim, enabling global (cross-user) score comparison.
|
|
1226
|
+
*
|
|
1227
|
+
* `capToBacklog` (default true, matching prior inline behavior): stop
|
|
1228
|
+
* scoring once this user's own maxUserBacklogSize worth of candidates has
|
|
1229
|
+
* been found. matchAllUsersFair() passes false - capping per-user during
|
|
1230
|
+
* discovery would silently drop a user's lower-priority candidates before
|
|
1231
|
+
* global arbitration ever runs, e.g. a user whose top picks all lose to a
|
|
1232
|
+
* higher scorer should still be considered for their next-best options,
|
|
1233
|
+
* not left with nothing because discovery stopped early.
|
|
1234
|
+
*/
|
|
1235
|
+
/**
|
|
1236
|
+
* Effective backlog cap for one user: `user.maxBacklogSize` when it is a
|
|
1237
|
+
* valid non-negative number, else the matcher-wide `maxUserBacklogSize`.
|
|
1238
|
+
* The fairness window auto-cap derivation (team-level) deliberately keeps
|
|
1239
|
+
* using the global value.
|
|
1240
|
+
*/
|
|
1241
|
+
backlogLimitFor(user) {
|
|
1242
|
+
const own = user.maxBacklogSize;
|
|
1243
|
+
return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
|
|
1244
|
+
}
|
|
1245
|
+
async computeCandidatesForUser(user, capToBacklog = true, collector) {
|
|
725
1246
|
const userAssignments = [];
|
|
726
1247
|
const routingWeights = user.routingWeights;
|
|
727
1248
|
const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
|
|
@@ -731,8 +1252,8 @@ class AssignmentMatcher {
|
|
|
731
1252
|
if (workflowAssignments.length > 0) {
|
|
732
1253
|
// Workflow assignments take precedence - add them first with highest priority
|
|
733
1254
|
userAssignments.push(...workflowAssignments);
|
|
734
|
-
if (userAssignments.length >= this.
|
|
735
|
-
return userAssignments;
|
|
1255
|
+
if (userAssignments.length >= this.backlogLimitFor(user)) {
|
|
1256
|
+
return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
|
|
736
1257
|
}
|
|
737
1258
|
}
|
|
738
1259
|
}
|
|
@@ -768,10 +1289,10 @@ class AssignmentMatcher {
|
|
|
768
1289
|
// In weighted default matching, users must define at least one positive weight.
|
|
769
1290
|
// If they don't, nothing should be assigned and queue remains intact.
|
|
770
1291
|
if (hasRoutingWeights && this.usingDefaultMatchScore && positiveWeights.length === 0) {
|
|
771
|
-
return userAssignments;
|
|
1292
|
+
return { userAssignments, selected: [], workflowTargetedCount };
|
|
772
1293
|
}
|
|
773
1294
|
if (positiveWeights.length === 0)
|
|
774
|
-
return userAssignments;
|
|
1295
|
+
return { userAssignments, selected: [], workflowTargetedCount };
|
|
775
1296
|
// Expand wildcards
|
|
776
1297
|
const expandedPositive = await this.expandTagWildcards(positiveWeights);
|
|
777
1298
|
const expandedZero = this.usingDefaultMatchScore
|
|
@@ -779,7 +1300,7 @@ class AssignmentMatcher {
|
|
|
779
1300
|
: [];
|
|
780
1301
|
const finalZeroTags = expandedZero.map((t) => t.tag);
|
|
781
1302
|
if (expandedPositive.length === 0)
|
|
782
|
-
return userAssignments;
|
|
1303
|
+
return { userAssignments, selected: [], workflowTargetedCount };
|
|
783
1304
|
const tempKey = this.keys.tempUserCandidates(user.id);
|
|
784
1305
|
const tempZeroKey = this.keys.tempUserExclude(user.id);
|
|
785
1306
|
const tempFinalKey = this.keys.tempUserFinal(user.id);
|
|
@@ -801,9 +1322,10 @@ class AssignmentMatcher {
|
|
|
801
1322
|
multi.expire(tempZeroKey, 5);
|
|
802
1323
|
excludeKeys.push(tempZeroKey);
|
|
803
1324
|
}
|
|
804
|
-
// Always exclude rejected assignments
|
|
1325
|
+
// Always exclude rejected and vetoed assignments
|
|
805
1326
|
excludeKeys.push(rejectedKey);
|
|
806
|
-
|
|
1327
|
+
excludeKeys.push(this.keys.userVetoed(user.id));
|
|
1328
|
+
// Final = candidates - exclude (zero weights + rejected + vetoed)
|
|
807
1329
|
multi.zDiffStore(tempFinalKey, [tempKey, ...excludeKeys]);
|
|
808
1330
|
// Set short TTLs to clean up
|
|
809
1331
|
multi.expire(tempKey, 5);
|
|
@@ -812,7 +1334,7 @@ class AssignmentMatcher {
|
|
|
812
1334
|
// Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
|
|
813
1335
|
const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
|
|
814
1336
|
if (top.length === 0)
|
|
815
|
-
return userAssignments;
|
|
1337
|
+
return { userAssignments, selected: [], workflowTargetedCount };
|
|
816
1338
|
// Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
|
|
817
1339
|
const batched = this.redisClient.multi();
|
|
818
1340
|
for (const entry of top) {
|
|
@@ -854,15 +1376,47 @@ class AssignmentMatcher {
|
|
|
854
1376
|
const modelWeights = await this.learning.getModel();
|
|
855
1377
|
const eligible = [];
|
|
856
1378
|
for (const d of details) {
|
|
857
|
-
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs))
|
|
1379
|
+
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
1380
|
+
collector?.record(d.id, d.tags, {
|
|
1381
|
+
userId: user.id,
|
|
1382
|
+
eligible: false,
|
|
1383
|
+
score: 0,
|
|
1384
|
+
effectivePriority: 0,
|
|
1385
|
+
reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
|
|
1386
|
+
});
|
|
858
1387
|
continue;
|
|
1388
|
+
}
|
|
859
1389
|
const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
|
|
860
|
-
if (!geoMatch.eligible)
|
|
1390
|
+
if (!geoMatch.eligible) {
|
|
1391
|
+
collector?.record(d.id, d.tags, {
|
|
1392
|
+
userId: user.id,
|
|
1393
|
+
eligible: false,
|
|
1394
|
+
score: 0,
|
|
1395
|
+
effectivePriority: 0,
|
|
1396
|
+
reasons: [
|
|
1397
|
+
{
|
|
1398
|
+
kind: 'geoDistance',
|
|
1399
|
+
distanceKm: geoMatch.distanceKm,
|
|
1400
|
+
maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
|
|
1401
|
+
withinRange: false,
|
|
1402
|
+
},
|
|
1403
|
+
],
|
|
1404
|
+
});
|
|
861
1405
|
continue;
|
|
1406
|
+
}
|
|
862
1407
|
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
863
|
-
if (!score || !combinedPriority)
|
|
1408
|
+
if (!score || !combinedPriority) {
|
|
1409
|
+
collector?.record(d.id, d.tags, {
|
|
1410
|
+
userId: user.id,
|
|
1411
|
+
eligible: false,
|
|
1412
|
+
score: 0,
|
|
1413
|
+
effectivePriority: Number(d.basePriority) || 0,
|
|
1414
|
+
reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
|
|
1415
|
+
});
|
|
864
1416
|
continue;
|
|
865
|
-
|
|
1417
|
+
}
|
|
1418
|
+
const traceGeoBoost = this.calculateGeoBoost(geoMatch);
|
|
1419
|
+
const geoAdjustedPriority = combinedPriority + traceGeoBoost;
|
|
866
1420
|
const context = {
|
|
867
1421
|
...(d.raw ?? {}),
|
|
868
1422
|
id: d.id,
|
|
@@ -879,10 +1433,21 @@ class AssignmentMatcher {
|
|
|
879
1433
|
? geoAdjustedPriority
|
|
880
1434
|
: geoAdjustedPriority + this.learning.boostFactor * predicted + exploration;
|
|
881
1435
|
eligible.push({ detail: d, combinedPriority, features, predicted, effectivePriority });
|
|
1436
|
+
collector?.record(d.id, d.tags, {
|
|
1437
|
+
userId: user.id,
|
|
1438
|
+
eligible: true,
|
|
1439
|
+
score,
|
|
1440
|
+
effectivePriority,
|
|
1441
|
+
reasons: this.traceScoreReasons(user, d, score, geoMatch, traceGeoBoost, {
|
|
1442
|
+
predicted,
|
|
1443
|
+
boost: effectivePriority - geoAdjustedPriority,
|
|
1444
|
+
shadowMode: this.learning.shadowMode,
|
|
1445
|
+
}),
|
|
1446
|
+
});
|
|
882
1447
|
}
|
|
883
1448
|
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
884
1449
|
for (const c of eligible) {
|
|
885
|
-
if (userAssignments.length >= this.
|
|
1450
|
+
if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
|
|
886
1451
|
break;
|
|
887
1452
|
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
888
1453
|
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
@@ -891,78 +1456,339 @@ class AssignmentMatcher {
|
|
|
891
1456
|
}
|
|
892
1457
|
else {
|
|
893
1458
|
for (const d of details) {
|
|
894
|
-
if (userAssignments.length >= this.
|
|
1459
|
+
if (capToBacklog && userAssignments.length >= this.backlogLimitFor(user))
|
|
895
1460
|
break;
|
|
896
1461
|
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
897
1462
|
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
1463
|
+
collector?.record(d.id, d.tags, {
|
|
1464
|
+
userId: user.id,
|
|
1465
|
+
eligible: false,
|
|
1466
|
+
score: 0,
|
|
1467
|
+
effectivePriority: 0,
|
|
1468
|
+
reasons: [{ kind: 'cidrMismatch', ip: user.ip }],
|
|
1469
|
+
});
|
|
898
1470
|
continue; // Skip this assignment - user IP doesn't match allowed CIDRs
|
|
899
1471
|
}
|
|
900
1472
|
const geoMatch = await this.evaluateGeoMatch(user, d.raw ?? { id: d.id, tags: [] });
|
|
901
1473
|
if (!geoMatch.eligible) {
|
|
1474
|
+
collector?.record(d.id, d.tags, {
|
|
1475
|
+
userId: user.id,
|
|
1476
|
+
eligible: false,
|
|
1477
|
+
score: 0,
|
|
1478
|
+
effectivePriority: 0,
|
|
1479
|
+
reasons: [
|
|
1480
|
+
{
|
|
1481
|
+
kind: 'geoDistance',
|
|
1482
|
+
distanceKm: geoMatch.distanceKm,
|
|
1483
|
+
maxDistanceKm: geoMatch.effectiveMaxDistanceKm,
|
|
1484
|
+
withinRange: false,
|
|
1485
|
+
},
|
|
1486
|
+
],
|
|
1487
|
+
});
|
|
902
1488
|
continue;
|
|
903
1489
|
}
|
|
904
1490
|
// Use custom matchScore (supports weights and thresholds) for a final check and tie-break
|
|
905
1491
|
const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id, d.skillThresholds);
|
|
906
1492
|
if (score && combinedPriority) {
|
|
907
|
-
|
|
1493
|
+
const geoBoost = this.calculateGeoBoost(geoMatch);
|
|
1494
|
+
userAssignments.push({ id: d.id, priority: combinedPriority + geoBoost });
|
|
908
1495
|
selected.push({ id: d.id, tags: d.tags });
|
|
1496
|
+
collector?.record(d.id, d.tags, {
|
|
1497
|
+
userId: user.id,
|
|
1498
|
+
eligible: true,
|
|
1499
|
+
score,
|
|
1500
|
+
effectivePriority: combinedPriority + geoBoost,
|
|
1501
|
+
reasons: this.traceScoreReasons(user, d, score, geoMatch, geoBoost),
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
else {
|
|
1505
|
+
collector?.record(d.id, d.tags, {
|
|
1506
|
+
userId: user.id,
|
|
1507
|
+
eligible: false,
|
|
1508
|
+
score: 0,
|
|
1509
|
+
effectivePriority: Number(d.basePriority) || 0,
|
|
1510
|
+
reasons: this.traceScoreReasons(user, d, score, geoMatch, 0),
|
|
1511
|
+
});
|
|
909
1512
|
}
|
|
910
1513
|
}
|
|
911
1514
|
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1515
|
+
return { userAssignments, selected, workflowTargetedCount };
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Atomically claims a set of tag-scored candidate assignments for one
|
|
1519
|
+
* user and returns which ones it actually won. The candidate read that
|
|
1520
|
+
* produces `selected` (zDiffStore/zRangeWithScores in
|
|
1521
|
+
* computeCandidatesForUser) is a snapshot taken before this point, and
|
|
1522
|
+
* candidate computation runs concurrently across users -
|
|
1523
|
+
* matchUsersAssignments() Promise.all's the bulk path, and a per-user
|
|
1524
|
+
* matchUsersAssignments(userId) call can race a bulk pass too. Without a
|
|
1525
|
+
* single atomic gate, two concurrent callers can both still see the same
|
|
1526
|
+
* assignment as available and both hand it to their user. HDEL on
|
|
1527
|
+
* assignmentsRefKey is atomic and idempotent (returns 1 only for
|
|
1528
|
+
* whichever caller actually deletes the field), so it's used here as
|
|
1529
|
+
* that gate: only assignments this call actually wins are kept - anything
|
|
1530
|
+
* already claimed by a concurrent caller since the snapshot read is
|
|
1531
|
+
* dropped instead of being double-assigned.
|
|
1532
|
+
*/
|
|
1533
|
+
async claimSelected(user, selected) {
|
|
923
1534
|
const claimedIds = new Set();
|
|
924
|
-
if (selected.length
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
1535
|
+
if (selected.length === 0)
|
|
1536
|
+
return claimedIds;
|
|
1537
|
+
const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
|
|
1538
|
+
const jsons = await Promise.all(jsonPromises);
|
|
1539
|
+
const now = Date.now();
|
|
1540
|
+
const claimMulti = this.redisClient.multi();
|
|
1541
|
+
for (const s of selected) {
|
|
1542
|
+
claimMulti.hDel(this.assignmentsRefKey, s.id);
|
|
1543
|
+
}
|
|
1544
|
+
const claimResults = (await claimMulti.exec());
|
|
1545
|
+
for (let i = 0; i < selected.length; i++) {
|
|
1546
|
+
if (Number(claimResults[i]) > 0)
|
|
1547
|
+
claimedIds.add(selected[i].id);
|
|
1548
|
+
}
|
|
1549
|
+
if (claimedIds.size > 0) {
|
|
1550
|
+
const rm = this.redisClient.multi();
|
|
933
1551
|
for (let i = 0; i < selected.length; i++) {
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
rm.
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
}
|
|
953
|
-
// Add to pending structures
|
|
954
|
-
if (json) {
|
|
955
|
-
rm.hSet(this.pendingAssignmentsKey, s.id, json);
|
|
956
|
-
rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
|
|
957
|
-
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
958
|
-
}
|
|
1552
|
+
const s = selected[i];
|
|
1553
|
+
if (!claimedIds.has(s.id))
|
|
1554
|
+
continue; // lost the race - already claimed elsewhere
|
|
1555
|
+
const json = jsons[i];
|
|
1556
|
+
rm.del(this.keys.assignmentPriority(s.id));
|
|
1557
|
+
rm.del(this.keys.assignmentTags(s.id));
|
|
1558
|
+
// Remove from global zset
|
|
1559
|
+
rm.zRem(this.assignmentsKey, s.id);
|
|
1560
|
+
// Remove from per-tag zsets
|
|
1561
|
+
const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
|
|
1562
|
+
for (const tag of tags) {
|
|
1563
|
+
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
1564
|
+
}
|
|
1565
|
+
// Add to pending structures
|
|
1566
|
+
if (json) {
|
|
1567
|
+
rm.hSet(this.pendingAssignmentsKey, s.id, json);
|
|
1568
|
+
rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
|
|
1569
|
+
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
959
1570
|
}
|
|
960
|
-
await rm.exec();
|
|
961
1571
|
}
|
|
1572
|
+
await rm.exec();
|
|
962
1573
|
}
|
|
1574
|
+
return claimedIds;
|
|
1575
|
+
}
|
|
1576
|
+
async getUserRelatedAssignments(user, collector) {
|
|
1577
|
+
const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
|
|
1578
|
+
const claimedIds = await this.claimSelected(user, selected);
|
|
963
1579
|
const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
|
|
964
1580
|
const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
|
|
965
|
-
return [...workflowTargeted, ...tagScored];
|
|
1581
|
+
return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
|
|
1582
|
+
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Opt-in alternative to the default parallel bulk path (see
|
|
1585
|
+
* MatcherOptions.enableFairTiebreaker): evaluates every user's eligible
|
|
1586
|
+
* candidates first (read-only, nobody claims yet), flattens them into one
|
|
1587
|
+
* global list sorted by score descending, then claims greedily in that
|
|
1588
|
+
* order. This guarantees the best-fit eligible candidate wins each
|
|
1589
|
+
* contested assignment, rather than whichever user's independent claim
|
|
1590
|
+
* happened to reach Redis first.
|
|
1591
|
+
*
|
|
1592
|
+
* Known limitation: when combined with enableLearning, computeCandidatesForUser
|
|
1593
|
+
* still records a bandit decision for every scored candidate at evaluation
|
|
1594
|
+
* time, including ones that lose the global tiebreak here - the learning
|
|
1595
|
+
* layer's per-user candidate ordering isn't itself part of the fairness
|
|
1596
|
+
* comparison in this mode. Fine for the common case (fairness without
|
|
1597
|
+
* learning), but a consumer combining both should be aware.
|
|
1598
|
+
*/
|
|
1599
|
+
async matchAllUsersFair() {
|
|
1600
|
+
let users = [];
|
|
1601
|
+
let cursor = '0';
|
|
1602
|
+
do {
|
|
1603
|
+
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1604
|
+
users.push(...entries.map((t) => JSON.parse(t.value)));
|
|
1605
|
+
cursor = nextCursor;
|
|
1606
|
+
} while (cursor !== '0');
|
|
1607
|
+
// Paused users sit out the pass entirely but stay in `users` so traces
|
|
1608
|
+
// can show them struck out.
|
|
1609
|
+
const activeUsers = await this.filterPausedUsers(users);
|
|
1610
|
+
const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
|
|
1611
|
+
const traceWinners = new Map();
|
|
1612
|
+
const workflowGrants = [];
|
|
1613
|
+
// Rolling-window grant cap: an explicit finite fairnessMaxPerWindow
|
|
1614
|
+
// always applies; the 'balanced' / 'spread-work' presets additionally
|
|
1615
|
+
// default a team-relative guardrail when no explicit cap is given
|
|
1616
|
+
// (fairnessMaxPerWindow: Infinity opts out of that too).
|
|
1617
|
+
const explicitCap = this.fairnessMaxPerWindow;
|
|
1618
|
+
const usesAutoCap = explicitCap === undefined && (this.fairnessMode === 'balanced' || this.fairnessMode === 'spread-work');
|
|
1619
|
+
const windowActive = usesAutoCap || (explicitCap !== undefined && Number.isFinite(explicitCap));
|
|
1620
|
+
const windowStart = Date.now() - this.fairnessWindowMs;
|
|
1621
|
+
// Phase 1: per-user backlog + window usage, one pipelined batch - the
|
|
1622
|
+
// rolling cap costs one extra command per user here, not a round trip.
|
|
1623
|
+
const usage = await Promise.all(activeUsers.map(async (user) => {
|
|
1624
|
+
const [backlog, grantsInWindow] = await Promise.all([
|
|
1625
|
+
this.redisClient.sCard(this.keys.userAssignments(user.id)),
|
|
1626
|
+
windowActive
|
|
1627
|
+
? this.redisClient.zCount(this.keys.userWindowGrants(user.id), windowStart, '+inf')
|
|
1628
|
+
: Promise.resolve(0),
|
|
1629
|
+
]);
|
|
1630
|
+
return { user, backlog, grantsInWindow };
|
|
1631
|
+
}));
|
|
1632
|
+
// The preset guardrail is scale-free on purpose: no fixed number fits
|
|
1633
|
+
// every deployment, but "nobody receives at more than double the
|
|
1634
|
+
// team's average rate" is safe anywhere. The maxUserBacklogSize floor
|
|
1635
|
+
// keeps a cold-started (empty-window) team from throttling itself.
|
|
1636
|
+
let windowCap = Infinity;
|
|
1637
|
+
if (explicitCap !== undefined && Number.isFinite(explicitCap)) {
|
|
1638
|
+
windowCap = explicitCap;
|
|
1639
|
+
}
|
|
1640
|
+
else if (usesAutoCap) {
|
|
1641
|
+
const totalGrants = usage.reduce((sum, u) => sum + u.grantsInWindow, 0);
|
|
1642
|
+
windowCap = Math.max(this.maxUserBacklogSize, Math.ceil((2 * totalGrants) / Math.max(1, usage.length)));
|
|
1643
|
+
}
|
|
1644
|
+
// Phase 2: read-only candidate discovery for users with headroom.
|
|
1645
|
+
const perUser = await Promise.all(usage.map(async ({ user, backlog, grantsInWindow }) => {
|
|
1646
|
+
const windowRemaining = windowActive ? Math.max(0, windowCap - grantsInWindow) : Infinity;
|
|
1647
|
+
if (backlog >= this.backlogLimitFor(user)) {
|
|
1648
|
+
return {
|
|
1649
|
+
user,
|
|
1650
|
+
backlog,
|
|
1651
|
+
windowRemaining,
|
|
1652
|
+
candidates: { userAssignments: [], selected: [], workflowTargetedCount: 0 },
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
if (windowRemaining <= 0) {
|
|
1656
|
+
// No tag-scored grant can land this pass, so skip candidate
|
|
1657
|
+
// scoring - but workflow-targeted assignments are direct
|
|
1658
|
+
// handoffs that bypass the window cap and must still flow.
|
|
1659
|
+
const workflowAssignments = this.enableWorkflows
|
|
1660
|
+
? await this.getWorkflowTargetedAssignments(user.id)
|
|
1661
|
+
: [];
|
|
1662
|
+
return {
|
|
1663
|
+
user,
|
|
1664
|
+
backlog,
|
|
1665
|
+
windowRemaining,
|
|
1666
|
+
candidates: {
|
|
1667
|
+
userAssignments: workflowAssignments,
|
|
1668
|
+
selected: [],
|
|
1669
|
+
workflowTargetedCount: workflowAssignments.length,
|
|
1670
|
+
},
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
// capToBacklog=false: this user's full candidate set is needed for
|
|
1674
|
+
// global arbitration below, not just as many as their own cap allows.
|
|
1675
|
+
const candidates = await this.computeCandidatesForUser(user, false, collector);
|
|
1676
|
+
return { user, backlog, windowRemaining, candidates };
|
|
1677
|
+
}));
|
|
1678
|
+
// Workflow-targeted assignments are deterministically targeted at one
|
|
1679
|
+
// user each - not contested across users - so claim them immediately,
|
|
1680
|
+
// exactly like the non-fair path does.
|
|
1681
|
+
await Promise.all(perUser.map(async ({ user, candidates }) => {
|
|
1682
|
+
const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
|
|
1683
|
+
if (workflowOnly.length === 0)
|
|
1684
|
+
return;
|
|
1685
|
+
if (collector) {
|
|
1686
|
+
// Membership must be read before the sAdd below
|
|
1687
|
+
workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
|
|
1688
|
+
}
|
|
1689
|
+
await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
|
|
1690
|
+
}));
|
|
1691
|
+
// Flatten every user's tag-scored candidates into one global list of
|
|
1692
|
+
// {user, assignment, score} pairs for cross-user arbitration.
|
|
1693
|
+
const globalPairs = [];
|
|
1694
|
+
for (const { user, candidates } of perUser) {
|
|
1695
|
+
const priorityById = new Map(candidates.userAssignments.map((ua) => [ua.id, ua.priority]));
|
|
1696
|
+
for (const s of candidates.selected) {
|
|
1697
|
+
globalPairs.push({
|
|
1698
|
+
user,
|
|
1699
|
+
userId: user.id,
|
|
1700
|
+
id: s.id,
|
|
1701
|
+
tags: s.tags,
|
|
1702
|
+
priority: priorityById.get(s.id) ?? 0,
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
const backlogUsed = new Map(perUser.map(({ user, backlog, candidates }) => [user.id, backlog + candidates.workflowTargetedCount]));
|
|
1707
|
+
// Fold the rolling-window cap into a per-user award ceiling: a user
|
|
1708
|
+
// may take at most min(backlog headroom, window headroom) more
|
|
1709
|
+
// tag-scored assignments this pass. Workflow-targeted grants above
|
|
1710
|
+
// are exempt from the window but still occupy backlog.
|
|
1711
|
+
// Always built (not only when the window is active) so per-user
|
|
1712
|
+
// backlog caps (user.maxBacklogSize) reach arbitration too;
|
|
1713
|
+
// windowRemaining is Infinity when the window is inactive.
|
|
1714
|
+
const maxByUser = new Map(perUser.map(({ user, backlog, windowRemaining, candidates }) => [
|
|
1715
|
+
user.id,
|
|
1716
|
+
backlog +
|
|
1717
|
+
candidates.workflowTargetedCount +
|
|
1718
|
+
Math.max(0, Math.min(this.backlogLimitFor(user) - backlog - candidates.workflowTargetedCount, windowRemaining)),
|
|
1719
|
+
]));
|
|
1720
|
+
// Arbitrate winners in memory (see arbitrateFair for the ordering:
|
|
1721
|
+
// best score wins, optionally load-penalized / tie-banded), then claim
|
|
1722
|
+
// in one batched claimSelected() call per user (all users in parallel)
|
|
1723
|
+
// rather than one claim round trip per pair - arbitration already
|
|
1724
|
+
// decides who wins every contested assignment within this process, so
|
|
1725
|
+
// per-pair claims would only re-discover that same answer at O(pairs)
|
|
1726
|
+
// sequential Redis round trips. The atomic HDEL gate inside
|
|
1727
|
+
// claimSelected() still protects against claims from OTHER processes:
|
|
1728
|
+
// a failed claim means the assignment is gone entirely (a concurrent
|
|
1729
|
+
// process won it), so the tentative winner's backlog slot is released
|
|
1730
|
+
// and the remaining pairs are re-arbitrated in another round. In the
|
|
1731
|
+
// common single-process case the first round claims everything and no
|
|
1732
|
+
// further rounds run.
|
|
1733
|
+
// A fairness preset ('balanced' / 'spread-work') derives its load
|
|
1734
|
+
// penalty from this pass's candidate scores; explicit expert knobs
|
|
1735
|
+
// always win over the preset.
|
|
1736
|
+
const knobs = (0, fair_arbitration_1.resolveFairnessKnobs)(this.fairnessMode, globalPairs.map((p) => p.priority), { loadPenalty: this.fairnessLoadPenalty, tieBand: this.fairnessTieBand });
|
|
1737
|
+
const settled = new Set();
|
|
1738
|
+
let remaining = globalPairs;
|
|
1739
|
+
while (remaining.length > 0) {
|
|
1740
|
+
const { winners, deferred } = (0, fair_arbitration_1.arbitrateFair)(remaining, backlogUsed, settled, {
|
|
1741
|
+
maxUserBacklogSize: this.maxUserBacklogSize,
|
|
1742
|
+
maxByUser,
|
|
1743
|
+
loadPenalty: knobs.loadPenalty,
|
|
1744
|
+
tieBand: knobs.tieBand,
|
|
1745
|
+
});
|
|
1746
|
+
const tentative = new Map();
|
|
1747
|
+
for (const w of winners) {
|
|
1748
|
+
const bucket = tentative.get(w.userId) ?? { user: w.user, pairs: [] };
|
|
1749
|
+
bucket.pairs.push({ id: w.id, tags: w.tags });
|
|
1750
|
+
tentative.set(w.userId, bucket);
|
|
1751
|
+
}
|
|
1752
|
+
if (tentative.size === 0)
|
|
1753
|
+
break;
|
|
1754
|
+
let anyLost = false;
|
|
1755
|
+
await Promise.all(Array.from(tentative.values()).map(async ({ user, pairs }) => {
|
|
1756
|
+
const claimedIds = await this.claimSelected(user, pairs);
|
|
1757
|
+
const won = pairs.filter((p) => claimedIds.has(p.id));
|
|
1758
|
+
if (collector) {
|
|
1759
|
+
for (const p of won)
|
|
1760
|
+
traceWinners.set(p.id, user.id);
|
|
1761
|
+
}
|
|
1762
|
+
if (won.length < pairs.length) {
|
|
1763
|
+
anyLost = true;
|
|
1764
|
+
backlogUsed.set(user.id, (backlogUsed.get(user.id) ?? 0) - (pairs.length - won.length));
|
|
1765
|
+
}
|
|
1766
|
+
// Won or lost, the assignment is no longer available to anyone.
|
|
1767
|
+
for (const p of pairs)
|
|
1768
|
+
settled.add(p.id);
|
|
1769
|
+
if (won.length > 0) {
|
|
1770
|
+
const grantMulti = this.redisClient.multi();
|
|
1771
|
+
grantMulti.sAdd(this.keys.userAssignments(user.id), won.map((p) => `assignment:${p.id}`));
|
|
1772
|
+
if (windowActive) {
|
|
1773
|
+
// Rolling-window bookkeeping: trim entries that
|
|
1774
|
+
// have aged out, record these grants, and let the
|
|
1775
|
+
// whole set expire if the user goes idle.
|
|
1776
|
+
const grantsKey = this.keys.userWindowGrants(user.id);
|
|
1777
|
+
const now = Date.now();
|
|
1778
|
+
grantMulti.zRemRangeByScore(grantsKey, '-inf', now - this.fairnessWindowMs);
|
|
1779
|
+
grantMulti.zAdd(grantsKey, won.map((p) => ({ score: now, value: `${now}:${p.id}` })));
|
|
1780
|
+
grantMulti.pExpire(grantsKey, this.fairnessWindowMs);
|
|
1781
|
+
}
|
|
1782
|
+
await grantMulti.exec();
|
|
1783
|
+
}
|
|
1784
|
+
}));
|
|
1785
|
+
if (!anyLost)
|
|
1786
|
+
break;
|
|
1787
|
+
remaining = deferred.filter((pair) => !settled.has(pair.id));
|
|
1788
|
+
}
|
|
1789
|
+
if (collector) {
|
|
1790
|
+
await this.recordPassTraces(collector, traceWinners, workflowGrants, this.getFairness(), users);
|
|
1791
|
+
}
|
|
966
1792
|
}
|
|
967
1793
|
async matchUsersAssignments(userId) {
|
|
968
1794
|
await this.readyPromise;
|
|
@@ -971,48 +1797,184 @@ class AssignmentMatcher {
|
|
|
971
1797
|
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
972
1798
|
if (!userJson)
|
|
973
1799
|
return;
|
|
1800
|
+
if (await this.redisClient.sIsMember(this.keys.pausedUsers(), userId))
|
|
1801
|
+
return;
|
|
974
1802
|
const user = JSON.parse(userJson);
|
|
975
1803
|
const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
|
|
976
|
-
if (userMatchesCount >= this.
|
|
1804
|
+
if (userMatchesCount >= this.backlogLimitFor(user))
|
|
977
1805
|
return;
|
|
978
|
-
const
|
|
979
|
-
const
|
|
1806
|
+
const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
|
|
1807
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
1808
|
+
// Membership must be read before the sAdd below
|
|
1809
|
+
const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
|
|
1810
|
+
const relevantAssignmentKeys = assignments
|
|
980
1811
|
.sort((a, b) => b.priority - a.priority)
|
|
981
1812
|
.map((a) => `assignment:${a.id}`);
|
|
982
1813
|
if (relevantAssignmentKeys.length > 0) {
|
|
983
1814
|
await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
|
|
984
1815
|
}
|
|
1816
|
+
if (collector) {
|
|
1817
|
+
const winners = new Map();
|
|
1818
|
+
for (const id of claimedIds)
|
|
1819
|
+
winners.set(id, user.id);
|
|
1820
|
+
await this.recordPassTraces(collector, winners, newWorkflowGrants, 'direct', [user]);
|
|
1821
|
+
}
|
|
985
1822
|
return;
|
|
986
1823
|
}
|
|
1824
|
+
if (this.enableFairTiebreaker) {
|
|
1825
|
+
return this.matchAllUsersFair();
|
|
1826
|
+
}
|
|
987
1827
|
// Otherwise, process all users in parallel as before.
|
|
988
1828
|
let users = [];
|
|
989
1829
|
let cursor = '0';
|
|
990
1830
|
// Fetch all users in a single loop
|
|
991
1831
|
do {
|
|
992
|
-
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor);
|
|
1832
|
+
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
993
1833
|
users.push(...entries.map((t) => JSON.parse(t.value)));
|
|
994
1834
|
cursor = nextCursor;
|
|
995
1835
|
} while (cursor !== '0');
|
|
1836
|
+
// Paused users sit out the pass entirely but stay in `users` so traces
|
|
1837
|
+
// can show them struck out.
|
|
1838
|
+
const activeUsers = await this.filterPausedUsers(users);
|
|
996
1839
|
// Process users in parallel
|
|
997
|
-
|
|
1840
|
+
const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
|
|
1841
|
+
const winners = new Map();
|
|
1842
|
+
const workflowGrants = [];
|
|
1843
|
+
await Promise.all(activeUsers.map(async (user) => {
|
|
998
1844
|
const userMatchesCount = await this.redisClient.sCard(this.keys.userAssignments(user.id));
|
|
999
|
-
if (userMatchesCount >= this.
|
|
1845
|
+
if (userMatchesCount >= this.backlogLimitFor(user)) {
|
|
1000
1846
|
return;
|
|
1001
1847
|
}
|
|
1002
|
-
const
|
|
1003
|
-
|
|
1848
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
1849
|
+
if (collector) {
|
|
1850
|
+
for (const id of claimedIds)
|
|
1851
|
+
winners.set(id, user.id);
|
|
1852
|
+
// Membership must be read before the sAdd below
|
|
1853
|
+
workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowTargeted)));
|
|
1854
|
+
}
|
|
1855
|
+
const relevantAssignmentKeys = assignments
|
|
1004
1856
|
.sort((a, b) => b.priority - a.priority)
|
|
1005
1857
|
.map((a) => `assignment:${a.id}`);
|
|
1006
1858
|
if (relevantAssignmentKeys.length > 0) {
|
|
1007
1859
|
await this.redisClient.sAdd(this.keys.userAssignments(user.id), relevantAssignmentKeys);
|
|
1008
1860
|
}
|
|
1009
1861
|
}));
|
|
1862
|
+
if (collector) {
|
|
1863
|
+
await this.recordPassTraces(collector, winners, workflowGrants, 'first-come', users);
|
|
1864
|
+
}
|
|
1010
1865
|
}
|
|
1011
1866
|
async getCurrentAssignmentsForUser(userId) {
|
|
1012
1867
|
await this.readyPromise;
|
|
1013
1868
|
const userAssignments = await this.redisClient.sMembers(this.keys.userAssignments(userId));
|
|
1014
1869
|
return userAssignments.map((el) => el.split(':')[1]);
|
|
1015
1870
|
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Operator override: hand an assignment directly to a user, bypassing
|
|
1873
|
+
* tag/weight selection. Works on queued assignments and on pending ones
|
|
1874
|
+
* held by another user (the previous owner's backlog slot is released).
|
|
1875
|
+
* Idempotent when the user already owns the assignment.
|
|
1876
|
+
*
|
|
1877
|
+
* Hard rules still apply unless `force`: the user must not be paused,
|
|
1878
|
+
* their backlog must have headroom, they must not be vetoed on the
|
|
1879
|
+
* assignment, and they must not have previously rejected it. `force`
|
|
1880
|
+
* bypasses those checks (the user must always exist). The learning layer
|
|
1881
|
+
* is never fed by manual assignments.
|
|
1882
|
+
*
|
|
1883
|
+
* When tracing is active the override is recorded as a decision trace
|
|
1884
|
+
* with mode `'manual'`, so supervisor actions show up in the same audit
|
|
1885
|
+
* trail as organic matches.
|
|
1886
|
+
*/
|
|
1887
|
+
async assignToUser(assignmentId, userId, options) {
|
|
1888
|
+
await this.readyPromise;
|
|
1889
|
+
const force = options?.force === true;
|
|
1890
|
+
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
1891
|
+
if (!userJson)
|
|
1892
|
+
throw new Error(`User not found: ${userId}`);
|
|
1893
|
+
const user = JSON.parse(userJson);
|
|
1894
|
+
const [queuedJson, previousOwnerId] = await Promise.all([
|
|
1895
|
+
this.redisClient.hGet(this.assignmentsRefKey, assignmentId),
|
|
1896
|
+
this.redisClient.hGet(this.assignmentOwnerKey, assignmentId),
|
|
1897
|
+
]);
|
|
1898
|
+
if (previousOwnerId === userId)
|
|
1899
|
+
return { previousOwnerId: userId };
|
|
1900
|
+
if (!queuedJson && !previousOwnerId) {
|
|
1901
|
+
throw new Error(`Assignment not found in queued or pending state: ${assignmentId}`);
|
|
1902
|
+
}
|
|
1903
|
+
if (!force) {
|
|
1904
|
+
const [isPaused, backlog, isVetoed, hasRejected] = await Promise.all([
|
|
1905
|
+
this.redisClient.sIsMember(this.keys.pausedUsers(), userId),
|
|
1906
|
+
this.redisClient.sCard(this.keys.userAssignments(userId)),
|
|
1907
|
+
this.redisClient.sIsMember(this.keys.assignmentVetoed(assignmentId), userId),
|
|
1908
|
+
this.redisClient.sIsMember(this.keys.userRejected(userId), assignmentId),
|
|
1909
|
+
]);
|
|
1910
|
+
if (isPaused)
|
|
1911
|
+
throw new Error(`User is paused: ${userId}`);
|
|
1912
|
+
if (backlog >= this.backlogLimitFor(user)) {
|
|
1913
|
+
throw new Error(`User backlog is full (${backlog}/${this.backlogLimitFor(user)}): ${userId}`);
|
|
1914
|
+
}
|
|
1915
|
+
if (isVetoed)
|
|
1916
|
+
throw new Error(`User is vetoed from this assignment: ${userId}`);
|
|
1917
|
+
if (hasRejected)
|
|
1918
|
+
throw new Error(`User previously rejected this assignment: ${userId}`);
|
|
1919
|
+
}
|
|
1920
|
+
if (queuedJson) {
|
|
1921
|
+
// Queued -> pending through the same atomic claim gate as organic
|
|
1922
|
+
// matching; losing it means a concurrent pass just took the
|
|
1923
|
+
// assignment.
|
|
1924
|
+
const tagsCsv = (await this.redisClient.hGet(this.keys.assignmentTags(assignmentId), 'tags')) ?? '';
|
|
1925
|
+
const claimed = await this.claimSelected(user, [{ id: assignmentId, tags: tagsCsv }]);
|
|
1926
|
+
if (!claimed.has(assignmentId)) {
|
|
1927
|
+
throw new Error(`Assignment is no longer available: ${assignmentId}`);
|
|
1928
|
+
}
|
|
1929
|
+
await this.redisClient.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
1930
|
+
}
|
|
1931
|
+
else {
|
|
1932
|
+
// Pending under another user: transfer ownership and restart the
|
|
1933
|
+
// expiry clock for the new owner.
|
|
1934
|
+
const transfer = this.redisClient
|
|
1935
|
+
.multi()
|
|
1936
|
+
.sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
|
|
1937
|
+
.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
|
|
1938
|
+
.hSet(this.assignmentOwnerKey, assignmentId, userId)
|
|
1939
|
+
.zAdd(this.pendingAssignmentsExpiryKey, {
|
|
1940
|
+
score: Date.now() + this.matchExpirationMs,
|
|
1941
|
+
value: assignmentId,
|
|
1942
|
+
});
|
|
1943
|
+
await transfer.exec();
|
|
1944
|
+
}
|
|
1945
|
+
await this.touchUser(userId);
|
|
1946
|
+
await this.recordManualAssignTrace(assignmentId, userId, force, previousOwnerId ?? null);
|
|
1947
|
+
return { previousOwnerId: previousOwnerId ?? null };
|
|
1948
|
+
}
|
|
1949
|
+
/** Audit record for an assignToUser() override; failures never break the assignment. */
|
|
1950
|
+
async recordManualAssignTrace(assignmentId, userId, force, previousOwnerId) {
|
|
1951
|
+
if (!this.tracingActive)
|
|
1952
|
+
return;
|
|
1953
|
+
try {
|
|
1954
|
+
await this.decisionTraces.record([
|
|
1955
|
+
{
|
|
1956
|
+
id: (0, crypto_1.randomUUID)(),
|
|
1957
|
+
assignmentId,
|
|
1958
|
+
chosenUserId: userId,
|
|
1959
|
+
matchedAt: Date.now(),
|
|
1960
|
+
mode: 'manual',
|
|
1961
|
+
candidates: [
|
|
1962
|
+
{
|
|
1963
|
+
userId,
|
|
1964
|
+
eligible: true,
|
|
1965
|
+
chosen: true,
|
|
1966
|
+
score: 0,
|
|
1967
|
+
effectivePriority: 0,
|
|
1968
|
+
reasons: [{ kind: 'manualAssignment', force, previousOwnerId }],
|
|
1969
|
+
},
|
|
1970
|
+
],
|
|
1971
|
+
},
|
|
1972
|
+
], this.enableDecisionTraces);
|
|
1973
|
+
}
|
|
1974
|
+
catch (err) {
|
|
1975
|
+
console.error('Failed to record manual assignment trace:', err);
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1016
1978
|
async acceptAssignment(userId, assignmentId) {
|
|
1017
1979
|
await this.readyPromise;
|
|
1018
1980
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
@@ -1025,6 +1987,8 @@ class AssignmentMatcher {
|
|
|
1025
1987
|
multi.hDel(this.pendingAssignmentsKey, assignmentId);
|
|
1026
1988
|
multi.zRem(this.pendingAssignmentsExpiryKey, assignmentId);
|
|
1027
1989
|
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
1990
|
+
// The wait clock stops when a user takes the work
|
|
1991
|
+
multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
|
|
1028
1992
|
// Store in accepted assignments
|
|
1029
1993
|
if (json) {
|
|
1030
1994
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
|
|
@@ -1176,6 +2140,14 @@ class AssignmentMatcher {
|
|
|
1176
2140
|
await this.readyPromise;
|
|
1177
2141
|
return this.workflow.listWorkflowDefinitions();
|
|
1178
2142
|
}
|
|
2143
|
+
/**
|
|
2144
|
+
* Delete a workflow definition by ID. Running instances are unaffected
|
|
2145
|
+
* (they carry their own snapshot). Returns `false` if it did not exist.
|
|
2146
|
+
*/
|
|
2147
|
+
async deleteWorkflowDefinition(id) {
|
|
2148
|
+
await this.readyPromise;
|
|
2149
|
+
return this.workflow.deleteWorkflowDefinition(id);
|
|
2150
|
+
}
|
|
1179
2151
|
/**
|
|
1180
2152
|
* Register and start a workflow in one call, or start an already-registered workflow by ID.
|
|
1181
2153
|
*/
|
|
@@ -1367,8 +2339,12 @@ class AssignmentMatcher {
|
|
|
1367
2339
|
return [];
|
|
1368
2340
|
const cutoff = Date.now() - this.idleUserTimeoutMs;
|
|
1369
2341
|
const idleCandidates = await this.redisClient.zRangeByScore(this.keys.userActivity(), '-inf', cutoff);
|
|
2342
|
+
// Paused users are deliberately absent, not idle - never auto-remove them.
|
|
2343
|
+
const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
|
|
1370
2344
|
const removed = [];
|
|
1371
2345
|
for (const userId of idleCandidates) {
|
|
2346
|
+
if (paused.has(userId))
|
|
2347
|
+
continue;
|
|
1372
2348
|
// Skip users no longer in the pool (clean up stale activity entry)
|
|
1373
2349
|
const exists = await this.redisClient.hExists(this.usersKey, userId);
|
|
1374
2350
|
if (!exists) {
|
|
@@ -1441,6 +2417,9 @@ class AssignmentMatcher {
|
|
|
1441
2417
|
for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
|
|
1442
2418
|
try {
|
|
1443
2419
|
const assignment = JSON.parse(json);
|
|
2420
|
+
// Hard veto applies even to deterministic workflow targeting
|
|
2421
|
+
if (assignment.vetoedUsers?.includes(userId))
|
|
2422
|
+
continue;
|
|
1444
2423
|
if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
|
|
1445
2424
|
// This is a workflow assignment targeted at this user
|
|
1446
2425
|
targeted.push({
|