assignment-user-matcher 1.2.3 → 1.2.5

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.
@@ -8,6 +8,7 @@ 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");
11
12
  const features_1 = require("./learning/features");
12
13
  const LearningManager_1 = require("./managers/LearningManager");
13
14
  const ReliabilityManager_1 = require("./managers/ReliabilityManager");
@@ -60,6 +61,14 @@ class AssignmentMatcher {
60
61
  this.geoDefaultMaxDistanceKm = options?.geoDefaultMaxDistanceKm;
61
62
  this.geoScoreWeight = options?.geoScoreWeight ?? 0;
62
63
  this.geoMatchingFunction = options?.geoMatchingFunction;
64
+ this.enableFairTiebreaker = options?.enableFairTiebreaker ?? false;
65
+ this.fairnessMode = options?.fairness;
66
+ if (this.fairnessMode)
67
+ this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
68
+ this.fairnessLoadPenalty = options?.fairnessLoadPenalty ?? 0;
69
+ this.fairnessTieBand = options?.fairnessTieBand ?? 0;
70
+ this.fairnessMaxPerWindow = options?.fairnessMaxPerWindow;
71
+ this.fairnessWindowMs = options?.fairnessWindowMs ?? 3600000;
63
72
  // Workflow options
64
73
  this.enableWorkflows = options?.enableWorkflows ?? false;
65
74
  this.streamConsumerGroup = options?.streamConsumerGroup ?? 'orchestrator';
@@ -331,6 +340,67 @@ class AssignmentMatcher {
331
340
  await this.readyPromise;
332
341
  return this.learning.shadowMode;
333
342
  }
343
+ /**
344
+ * Toggle fair-tiebreaker global best-match arbitration at runtime.
345
+ * See `MatcherOptions.enableFairTiebreaker` for what this changes.
346
+ */
347
+ setFairTiebreaker(enabled) {
348
+ this.enableFairTiebreaker = !!enabled;
349
+ }
350
+ /** Current runtime fair-tiebreaker state. */
351
+ isFairTiebreakerEnabled() {
352
+ return this.enableFairTiebreaker;
353
+ }
354
+ /**
355
+ * Switch the bulk-matching fairness policy at runtime — shorthand for
356
+ * `setFairnessConfig({ fairness: mode })`. See `MatcherOptions.fairness`
357
+ * for what each mode does.
358
+ */
359
+ setFairness(mode) {
360
+ this.setFairnessConfig({ fairness: mode });
361
+ }
362
+ /**
363
+ * Retune any subset of the bulk-matching fairness knobs at runtime without
364
+ * reconstructing the matcher. Absent fields are left unchanged; the new
365
+ * values take effect on the next `matchUsersAssignments()` call (a match
366
+ * already in flight keeps the values it started with). Merge semantics
367
+ * mirror the constructor exactly — in particular, an explicit `fairness`
368
+ * overrides `enableFairTiebreaker`. See `MatcherOptions` for each field.
369
+ */
370
+ setFairnessConfig(config) {
371
+ if ('enableFairTiebreaker' in config)
372
+ this.enableFairTiebreaker = !!config.enableFairTiebreaker;
373
+ if ('fairness' in config) {
374
+ this.fairnessMode = config.fairness;
375
+ if (this.fairnessMode)
376
+ this.enableFairTiebreaker = this.fairnessMode !== 'first-come';
377
+ }
378
+ if ('fairnessLoadPenalty' in config)
379
+ this.fairnessLoadPenalty = config.fairnessLoadPenalty ?? 0;
380
+ if ('fairnessTieBand' in config)
381
+ this.fairnessTieBand = config.fairnessTieBand ?? 0;
382
+ if ('fairnessMaxPerWindow' in config)
383
+ this.fairnessMaxPerWindow = config.fairnessMaxPerWindow;
384
+ if ('fairnessWindowMs' in config)
385
+ this.fairnessWindowMs = config.fairnessWindowMs ?? 3600000;
386
+ }
387
+ /** Current runtime fairness policy. */
388
+ getFairness() {
389
+ if (!this.enableFairTiebreaker)
390
+ return 'first-come';
391
+ return this.fairnessMode ?? 'best-match';
392
+ }
393
+ /** Snapshot of the live fairness configuration. */
394
+ getFairnessConfig() {
395
+ return {
396
+ fairness: this.getFairness(),
397
+ enableFairTiebreaker: this.enableFairTiebreaker,
398
+ fairnessLoadPenalty: this.fairnessLoadPenalty,
399
+ fairnessTieBand: this.fairnessTieBand,
400
+ fairnessMaxPerWindow: this.fairnessMaxPerWindow,
401
+ fairnessWindowMs: this.fairnessWindowMs,
402
+ };
403
+ }
334
404
  // ============================================================================
335
405
  // Auto Routing Weights (RL-generated tags/weights)
336
406
  // ============================================================================
@@ -474,6 +544,14 @@ class AssignmentMatcher {
474
544
  member: id,
475
545
  });
476
546
  }
547
+ // Index hard vetoes both ways: assignment -> users for cleanup,
548
+ // user -> assignments for exclusion via ZDIFFSTORE during matching.
549
+ if (assignment.vetoedUsers && assignment.vetoedUsers.length > 0) {
550
+ multi.sAdd(this.keys.assignmentVetoed(id), assignment.vetoedUsers);
551
+ for (const vetoedUserId of assignment.vetoedUsers) {
552
+ multi.sAdd(this.keys.userVetoed(vetoedUserId), id);
553
+ }
554
+ }
477
555
  // Also index assignment into per-tag sorted sets (by priority)
478
556
  // This enables efficient weighted matching via ZUNIONSTORE.
479
557
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
@@ -492,10 +570,11 @@ class AssignmentMatcher {
492
570
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
493
571
  const assignmentTagsKey = this.keys.assignmentTags(id);
494
572
  const assignmentGeoKey = this.keys.assignmentsGeo();
495
- // Fetch tags and owner in case it's pending
496
- const [tagsCsv, owner] = await Promise.all([
573
+ // Fetch tags, owner (in case it's pending), and vetoed users for index cleanup
574
+ const [tagsCsv, owner, vetoedUsers] = await Promise.all([
497
575
  this.redisClient.hGet(assignmentTagsKey, 'tags'),
498
576
  this.redisClient.hGet(this.assignmentOwnerKey, id),
577
+ this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
499
578
  ]);
500
579
  let tags = [];
501
580
  if (tagsCsv && tagsCsv.length > 0) {
@@ -511,6 +590,10 @@ class AssignmentMatcher {
511
590
  multi.zRem(this.keys.tagAssignments(tag), id.toString());
512
591
  }
513
592
  multi.zRem(assignmentGeoKey, id.toString());
593
+ multi.del(this.keys.assignmentVetoed(id));
594
+ for (const vetoedUserId of vetoedUsers) {
595
+ multi.sRem(this.keys.userVetoed(vetoedUserId), id);
596
+ }
514
597
  // 2. Remove from Pending state
515
598
  multi.hDel(this.pendingAssignmentsKey, id);
516
599
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
@@ -529,6 +612,7 @@ class AssignmentMatcher {
529
612
  .multi()
530
613
  .del(this.keys.userAssignments(userId))
531
614
  .del(this.keys.userRejected(userId))
615
+ .del(this.keys.userVetoed(userId))
532
616
  .zRem(this.keys.userActivity(), userId)
533
617
  .hDel(this.usersKey, userId);
534
618
  await multi.exec();
@@ -721,7 +805,23 @@ class AssignmentMatcher {
721
805
  }
722
806
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
723
807
  }
724
- async getUserRelatedAssignments(user) {
808
+ /**
809
+ * Read-only candidate discovery for one user: workflow-targeted lookups,
810
+ * the weighted per-tag zset union/diff, and per-candidate scoring
811
+ * (learning-influenced or plain, matching the existing behavior exactly).
812
+ * Does NOT claim anything - see claimSelected() for that. Split out so
813
+ * matchAllUsersFair() can evaluate every user's candidates before any of
814
+ * them claim, enabling global (cross-user) score comparison.
815
+ *
816
+ * `capToBacklog` (default true, matching prior inline behavior): stop
817
+ * scoring once this user's own maxUserBacklogSize worth of candidates has
818
+ * been found. matchAllUsersFair() passes false - capping per-user during
819
+ * discovery would silently drop a user's lower-priority candidates before
820
+ * global arbitration ever runs, e.g. a user whose top picks all lose to a
821
+ * higher scorer should still be considered for their next-best options,
822
+ * not left with nothing because discovery stopped early.
823
+ */
824
+ async computeCandidatesForUser(user, capToBacklog = true) {
725
825
  const userAssignments = [];
726
826
  const routingWeights = user.routingWeights;
727
827
  const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
@@ -732,7 +832,7 @@ class AssignmentMatcher {
732
832
  // Workflow assignments take precedence - add them first with highest priority
733
833
  userAssignments.push(...workflowAssignments);
734
834
  if (userAssignments.length >= this.maxUserBacklogSize) {
735
- return userAssignments;
835
+ return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
736
836
  }
737
837
  }
738
838
  }
@@ -768,10 +868,10 @@ class AssignmentMatcher {
768
868
  // In weighted default matching, users must define at least one positive weight.
769
869
  // If they don't, nothing should be assigned and queue remains intact.
770
870
  if (hasRoutingWeights && this.usingDefaultMatchScore && positiveWeights.length === 0) {
771
- return userAssignments;
871
+ return { userAssignments, selected: [], workflowTargetedCount };
772
872
  }
773
873
  if (positiveWeights.length === 0)
774
- return userAssignments;
874
+ return { userAssignments, selected: [], workflowTargetedCount };
775
875
  // Expand wildcards
776
876
  const expandedPositive = await this.expandTagWildcards(positiveWeights);
777
877
  const expandedZero = this.usingDefaultMatchScore
@@ -779,7 +879,7 @@ class AssignmentMatcher {
779
879
  : [];
780
880
  const finalZeroTags = expandedZero.map((t) => t.tag);
781
881
  if (expandedPositive.length === 0)
782
- return userAssignments;
882
+ return { userAssignments, selected: [], workflowTargetedCount };
783
883
  const tempKey = this.keys.tempUserCandidates(user.id);
784
884
  const tempZeroKey = this.keys.tempUserExclude(user.id);
785
885
  const tempFinalKey = this.keys.tempUserFinal(user.id);
@@ -801,9 +901,10 @@ class AssignmentMatcher {
801
901
  multi.expire(tempZeroKey, 5);
802
902
  excludeKeys.push(tempZeroKey);
803
903
  }
804
- // Always exclude rejected assignments
904
+ // Always exclude rejected and vetoed assignments
805
905
  excludeKeys.push(rejectedKey);
806
- // Final = candidates - exclude (zero weights + rejected)
906
+ excludeKeys.push(this.keys.userVetoed(user.id));
907
+ // Final = candidates - exclude (zero weights + rejected + vetoed)
807
908
  multi.zDiffStore(tempFinalKey, [tempKey, ...excludeKeys]);
808
909
  // Set short TTLs to clean up
809
910
  multi.expire(tempKey, 5);
@@ -812,7 +913,7 @@ class AssignmentMatcher {
812
913
  // Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
813
914
  const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
814
915
  if (top.length === 0)
815
- return userAssignments;
916
+ return { userAssignments, selected: [], workflowTargetedCount };
816
917
  // Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
817
918
  const batched = this.redisClient.multi();
818
919
  for (const entry of top) {
@@ -882,7 +983,7 @@ class AssignmentMatcher {
882
983
  }
883
984
  eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
884
985
  for (const c of eligible) {
885
- if (userAssignments.length >= this.maxUserBacklogSize)
986
+ if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
886
987
  break;
887
988
  userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
888
989
  selected.push({ id: c.detail.id, tags: c.detail.tags });
@@ -891,7 +992,7 @@ class AssignmentMatcher {
891
992
  }
892
993
  else {
893
994
  for (const d of details) {
894
- if (userAssignments.length >= this.maxUserBacklogSize)
995
+ if (capToBacklog && userAssignments.length >= this.maxUserBacklogSize)
895
996
  break;
896
997
  // Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
897
998
  if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
@@ -909,61 +1010,267 @@ class AssignmentMatcher {
909
1010
  }
910
1011
  }
911
1012
  }
912
- // Claim, then clean up. The candidate read above (zDiffStore/zRangeWithScores)
913
- // is a snapshot taken before this point, and getUserRelatedAssignments runs
914
- // concurrently across users - matchUsersAssignments() Promise.all's the bulk
915
- // path, and a per-user matchUsersAssignments(userId) call can race a bulk
916
- // pass too. Without a single atomic gate, two concurrent callers can both
917
- // still see the same assignment as available and both hand it to their user.
918
- // HDEL on assignmentsRefKey is atomic and idempotent (returns 1 only for
919
- // whichever caller actually deletes the field), so it's used here as that
920
- // gate: only assignments this call actually wins are kept: anything already
921
- // claimed by a concurrent caller since the snapshot read is dropped instead
922
- // of being double-assigned.
1013
+ return { userAssignments, selected, workflowTargetedCount };
1014
+ }
1015
+ /**
1016
+ * Atomically claims a set of tag-scored candidate assignments for one
1017
+ * user and returns which ones it actually won. The candidate read that
1018
+ * produces `selected` (zDiffStore/zRangeWithScores in
1019
+ * computeCandidatesForUser) is a snapshot taken before this point, and
1020
+ * candidate computation runs concurrently across users -
1021
+ * matchUsersAssignments() Promise.all's the bulk path, and a per-user
1022
+ * matchUsersAssignments(userId) call can race a bulk pass too. Without a
1023
+ * single atomic gate, two concurrent callers can both still see the same
1024
+ * assignment as available and both hand it to their user. HDEL on
1025
+ * assignmentsRefKey is atomic and idempotent (returns 1 only for
1026
+ * whichever caller actually deletes the field), so it's used here as
1027
+ * that gate: only assignments this call actually wins are kept - anything
1028
+ * already claimed by a concurrent caller since the snapshot read is
1029
+ * dropped instead of being double-assigned.
1030
+ */
1031
+ async claimSelected(user, selected) {
923
1032
  const claimedIds = new Set();
924
- if (selected.length > 0) {
925
- const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
926
- const jsons = await Promise.all(jsonPromises);
927
- const now = Date.now();
928
- const claimMulti = this.redisClient.multi();
929
- for (const s of selected) {
930
- claimMulti.hDel(this.assignmentsRefKey, s.id);
931
- }
932
- const claimResults = (await claimMulti.exec());
1033
+ if (selected.length === 0)
1034
+ return claimedIds;
1035
+ const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
1036
+ const jsons = await Promise.all(jsonPromises);
1037
+ const now = Date.now();
1038
+ const claimMulti = this.redisClient.multi();
1039
+ for (const s of selected) {
1040
+ claimMulti.hDel(this.assignmentsRefKey, s.id);
1041
+ }
1042
+ const claimResults = (await claimMulti.exec());
1043
+ for (let i = 0; i < selected.length; i++) {
1044
+ if (Number(claimResults[i]) > 0)
1045
+ claimedIds.add(selected[i].id);
1046
+ }
1047
+ if (claimedIds.size > 0) {
1048
+ const rm = this.redisClient.multi();
933
1049
  for (let i = 0; i < selected.length; i++) {
934
- if (Number(claimResults[i]) > 0)
935
- claimedIds.add(selected[i].id);
936
- }
937
- if (claimedIds.size > 0) {
938
- const rm = this.redisClient.multi();
939
- for (let i = 0; i < selected.length; i++) {
940
- const s = selected[i];
941
- if (!claimedIds.has(s.id))
942
- continue; // lost the race - already claimed elsewhere
943
- const json = jsons[i];
944
- rm.del(this.keys.assignmentPriority(s.id));
945
- rm.del(this.keys.assignmentTags(s.id));
946
- // Remove from global zset
947
- rm.zRem(this.assignmentsKey, s.id);
948
- // Remove from per-tag zsets
949
- const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
950
- for (const tag of tags) {
951
- rm.zRem(this.keys.tagAssignments(tag), s.id);
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
- }
1050
+ const s = selected[i];
1051
+ if (!claimedIds.has(s.id))
1052
+ continue; // lost the race - already claimed elsewhere
1053
+ const json = jsons[i];
1054
+ rm.del(this.keys.assignmentPriority(s.id));
1055
+ rm.del(this.keys.assignmentTags(s.id));
1056
+ // Remove from global zset
1057
+ rm.zRem(this.assignmentsKey, s.id);
1058
+ // Remove from per-tag zsets
1059
+ const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
1060
+ for (const tag of tags) {
1061
+ rm.zRem(this.keys.tagAssignments(tag), s.id);
1062
+ }
1063
+ // Add to pending structures
1064
+ if (json) {
1065
+ rm.hSet(this.pendingAssignmentsKey, s.id, json);
1066
+ rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
1067
+ rm.hSet(this.assignmentOwnerKey, s.id, user.id);
959
1068
  }
960
- await rm.exec();
961
1069
  }
1070
+ await rm.exec();
962
1071
  }
1072
+ return claimedIds;
1073
+ }
1074
+ async getUserRelatedAssignments(user) {
1075
+ const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user);
1076
+ const claimedIds = await this.claimSelected(user, selected);
963
1077
  const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
964
1078
  const tagScored = userAssignments.slice(workflowTargetedCount).filter((ua) => claimedIds.has(ua.id));
965
1079
  return [...workflowTargeted, ...tagScored];
966
1080
  }
1081
+ /**
1082
+ * Opt-in alternative to the default parallel bulk path (see
1083
+ * MatcherOptions.enableFairTiebreaker): evaluates every user's eligible
1084
+ * candidates first (read-only, nobody claims yet), flattens them into one
1085
+ * global list sorted by score descending, then claims greedily in that
1086
+ * order. This guarantees the best-fit eligible candidate wins each
1087
+ * contested assignment, rather than whichever user's independent claim
1088
+ * happened to reach Redis first.
1089
+ *
1090
+ * Known limitation: when combined with enableLearning, computeCandidatesForUser
1091
+ * still records a bandit decision for every scored candidate at evaluation
1092
+ * time, including ones that lose the global tiebreak here - the learning
1093
+ * layer's per-user candidate ordering isn't itself part of the fairness
1094
+ * comparison in this mode. Fine for the common case (fairness without
1095
+ * learning), but a consumer combining both should be aware.
1096
+ */
1097
+ async matchAllUsersFair() {
1098
+ let users = [];
1099
+ let cursor = '0';
1100
+ do {
1101
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
1102
+ users.push(...entries.map((t) => JSON.parse(t.value)));
1103
+ cursor = nextCursor;
1104
+ } while (cursor !== '0');
1105
+ // Rolling-window grant cap: an explicit finite fairnessMaxPerWindow
1106
+ // always applies; the 'balanced' / 'spread-work' presets additionally
1107
+ // default a team-relative guardrail when no explicit cap is given
1108
+ // (fairnessMaxPerWindow: Infinity opts out of that too).
1109
+ const explicitCap = this.fairnessMaxPerWindow;
1110
+ const usesAutoCap = explicitCap === undefined && (this.fairnessMode === 'balanced' || this.fairnessMode === 'spread-work');
1111
+ const windowActive = usesAutoCap || (explicitCap !== undefined && Number.isFinite(explicitCap));
1112
+ const windowStart = Date.now() - this.fairnessWindowMs;
1113
+ // Phase 1: per-user backlog + window usage, one pipelined batch - the
1114
+ // rolling cap costs one extra command per user here, not a round trip.
1115
+ const usage = await Promise.all(users.map(async (user) => {
1116
+ const [backlog, grantsInWindow] = await Promise.all([
1117
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
1118
+ windowActive
1119
+ ? this.redisClient.zCount(this.keys.userWindowGrants(user.id), windowStart, '+inf')
1120
+ : Promise.resolve(0),
1121
+ ]);
1122
+ return { user, backlog, grantsInWindow };
1123
+ }));
1124
+ // The preset guardrail is scale-free on purpose: no fixed number fits
1125
+ // every deployment, but "nobody receives at more than double the
1126
+ // team's average rate" is safe anywhere. The maxUserBacklogSize floor
1127
+ // keeps a cold-started (empty-window) team from throttling itself.
1128
+ let windowCap = Infinity;
1129
+ if (explicitCap !== undefined && Number.isFinite(explicitCap)) {
1130
+ windowCap = explicitCap;
1131
+ }
1132
+ else if (usesAutoCap) {
1133
+ const totalGrants = usage.reduce((sum, u) => sum + u.grantsInWindow, 0);
1134
+ windowCap = Math.max(this.maxUserBacklogSize, Math.ceil((2 * totalGrants) / Math.max(1, usage.length)));
1135
+ }
1136
+ // Phase 2: read-only candidate discovery for users with headroom.
1137
+ const perUser = await Promise.all(usage.map(async ({ user, backlog, grantsInWindow }) => {
1138
+ const windowRemaining = windowActive ? Math.max(0, windowCap - grantsInWindow) : Infinity;
1139
+ if (backlog >= this.maxUserBacklogSize) {
1140
+ return {
1141
+ user,
1142
+ backlog,
1143
+ windowRemaining,
1144
+ candidates: { userAssignments: [], selected: [], workflowTargetedCount: 0 },
1145
+ };
1146
+ }
1147
+ if (windowRemaining <= 0) {
1148
+ // No tag-scored grant can land this pass, so skip candidate
1149
+ // scoring - but workflow-targeted assignments are direct
1150
+ // handoffs that bypass the window cap and must still flow.
1151
+ const workflowAssignments = this.enableWorkflows
1152
+ ? await this.getWorkflowTargetedAssignments(user.id)
1153
+ : [];
1154
+ return {
1155
+ user,
1156
+ backlog,
1157
+ windowRemaining,
1158
+ candidates: {
1159
+ userAssignments: workflowAssignments,
1160
+ selected: [],
1161
+ workflowTargetedCount: workflowAssignments.length,
1162
+ },
1163
+ };
1164
+ }
1165
+ // capToBacklog=false: this user's full candidate set is needed for
1166
+ // global arbitration below, not just as many as their own cap allows.
1167
+ const candidates = await this.computeCandidatesForUser(user, false);
1168
+ return { user, backlog, windowRemaining, candidates };
1169
+ }));
1170
+ // Workflow-targeted assignments are deterministically targeted at one
1171
+ // user each - not contested across users - so claim them immediately,
1172
+ // exactly like the non-fair path does.
1173
+ await Promise.all(perUser.map(({ user, candidates }) => {
1174
+ const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
1175
+ if (workflowOnly.length === 0)
1176
+ return Promise.resolve(0);
1177
+ return this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
1178
+ }));
1179
+ // Flatten every user's tag-scored candidates into one global list of
1180
+ // {user, assignment, score} pairs for cross-user arbitration.
1181
+ const globalPairs = [];
1182
+ for (const { user, candidates } of perUser) {
1183
+ const priorityById = new Map(candidates.userAssignments.map((ua) => [ua.id, ua.priority]));
1184
+ for (const s of candidates.selected) {
1185
+ globalPairs.push({
1186
+ user,
1187
+ userId: user.id,
1188
+ id: s.id,
1189
+ tags: s.tags,
1190
+ priority: priorityById.get(s.id) ?? 0,
1191
+ });
1192
+ }
1193
+ }
1194
+ const backlogUsed = new Map(perUser.map(({ user, backlog, candidates }) => [user.id, backlog + candidates.workflowTargetedCount]));
1195
+ // Fold the rolling-window cap into a per-user award ceiling: a user
1196
+ // may take at most min(backlog headroom, window headroom) more
1197
+ // tag-scored assignments this pass. Workflow-targeted grants above
1198
+ // are exempt from the window but still occupy backlog.
1199
+ let maxByUser;
1200
+ if (windowActive) {
1201
+ maxByUser = new Map(perUser.map(({ user, backlog, windowRemaining, candidates }) => [
1202
+ user.id,
1203
+ backlog +
1204
+ candidates.workflowTargetedCount +
1205
+ Math.max(0, Math.min(this.maxUserBacklogSize - backlog - candidates.workflowTargetedCount, windowRemaining)),
1206
+ ]));
1207
+ }
1208
+ // Arbitrate winners in memory (see arbitrateFair for the ordering:
1209
+ // best score wins, optionally load-penalized / tie-banded), then claim
1210
+ // in one batched claimSelected() call per user (all users in parallel)
1211
+ // rather than one claim round trip per pair - arbitration already
1212
+ // decides who wins every contested assignment within this process, so
1213
+ // per-pair claims would only re-discover that same answer at O(pairs)
1214
+ // sequential Redis round trips. The atomic HDEL gate inside
1215
+ // claimSelected() still protects against claims from OTHER processes:
1216
+ // a failed claim means the assignment is gone entirely (a concurrent
1217
+ // process won it), so the tentative winner's backlog slot is released
1218
+ // and the remaining pairs are re-arbitrated in another round. In the
1219
+ // common single-process case the first round claims everything and no
1220
+ // further rounds run.
1221
+ // A fairness preset ('balanced' / 'spread-work') derives its load
1222
+ // penalty from this pass's candidate scores; explicit expert knobs
1223
+ // always win over the preset.
1224
+ const knobs = (0, fair_arbitration_1.resolveFairnessKnobs)(this.fairnessMode, globalPairs.map((p) => p.priority), { loadPenalty: this.fairnessLoadPenalty, tieBand: this.fairnessTieBand });
1225
+ const settled = new Set();
1226
+ let remaining = globalPairs;
1227
+ while (remaining.length > 0) {
1228
+ const { winners, deferred } = (0, fair_arbitration_1.arbitrateFair)(remaining, backlogUsed, settled, {
1229
+ maxUserBacklogSize: this.maxUserBacklogSize,
1230
+ maxByUser,
1231
+ loadPenalty: knobs.loadPenalty,
1232
+ tieBand: knobs.tieBand,
1233
+ });
1234
+ const tentative = new Map();
1235
+ for (const w of winners) {
1236
+ const bucket = tentative.get(w.userId) ?? { user: w.user, pairs: [] };
1237
+ bucket.pairs.push({ id: w.id, tags: w.tags });
1238
+ tentative.set(w.userId, bucket);
1239
+ }
1240
+ if (tentative.size === 0)
1241
+ break;
1242
+ let anyLost = false;
1243
+ await Promise.all(Array.from(tentative.values()).map(async ({ user, pairs }) => {
1244
+ const claimedIds = await this.claimSelected(user, pairs);
1245
+ const won = pairs.filter((p) => claimedIds.has(p.id));
1246
+ if (won.length < pairs.length) {
1247
+ anyLost = true;
1248
+ backlogUsed.set(user.id, (backlogUsed.get(user.id) ?? 0) - (pairs.length - won.length));
1249
+ }
1250
+ // Won or lost, the assignment is no longer available to anyone.
1251
+ for (const p of pairs)
1252
+ settled.add(p.id);
1253
+ if (won.length > 0) {
1254
+ const grantMulti = this.redisClient.multi();
1255
+ grantMulti.sAdd(this.keys.userAssignments(user.id), won.map((p) => `assignment:${p.id}`));
1256
+ if (windowActive) {
1257
+ // Rolling-window bookkeeping: trim entries that
1258
+ // have aged out, record these grants, and let the
1259
+ // whole set expire if the user goes idle.
1260
+ const grantsKey = this.keys.userWindowGrants(user.id);
1261
+ const now = Date.now();
1262
+ grantMulti.zRemRangeByScore(grantsKey, '-inf', now - this.fairnessWindowMs);
1263
+ grantMulti.zAdd(grantsKey, won.map((p) => ({ score: now, value: `${now}:${p.id}` })));
1264
+ grantMulti.pExpire(grantsKey, this.fairnessWindowMs);
1265
+ }
1266
+ await grantMulti.exec();
1267
+ }
1268
+ }));
1269
+ if (!anyLost)
1270
+ break;
1271
+ remaining = deferred.filter((pair) => !settled.has(pair.id));
1272
+ }
1273
+ }
967
1274
  async matchUsersAssignments(userId) {
968
1275
  await this.readyPromise;
969
1276
  // If a specific userId is provided, process only that user for precise per-user matching.
@@ -984,12 +1291,15 @@ class AssignmentMatcher {
984
1291
  }
985
1292
  return;
986
1293
  }
1294
+ if (this.enableFairTiebreaker) {
1295
+ return this.matchAllUsersFair();
1296
+ }
987
1297
  // Otherwise, process all users in parallel as before.
988
1298
  let users = [];
989
1299
  let cursor = '0';
990
1300
  // Fetch all users in a single loop
991
1301
  do {
992
- const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor);
1302
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
993
1303
  users.push(...entries.map((t) => JSON.parse(t.value)));
994
1304
  cursor = nextCursor;
995
1305
  } while (cursor !== '0');
@@ -1441,6 +1751,9 @@ class AssignmentMatcher {
1441
1751
  for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
1442
1752
  try {
1443
1753
  const assignment = JSON.parse(json);
1754
+ // Hard veto applies even to deterministic workflow targeting
1755
+ if (assignment.vetoedUsers?.includes(userId))
1756
+ continue;
1444
1757
  if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
1445
1758
  // This is a workflow assignment targeted at this user
1446
1759
  targeted.push({
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Global arbitration for fair-tiebreaker bulk matching: decides which user
3
+ * tentatively wins each contested candidate assignment. Pure logic - no Redis.
4
+ * See MatcherOptions.enableFairTiebreaker / fairnessLoadPenalty /
5
+ * fairnessTieBand for the behavior each knob selects.
6
+ */
7
+ import type { FairnessMode } from '../types/matcher';
8
+ /**
9
+ * Turns a fairness preset into concrete arbitration knobs, scaled to the
10
+ * median candidate score of the current matching pass so consumers never
11
+ * have to know their own score scale. Explicitly-set expert knobs
12
+ * (fairnessLoadPenalty / fairnessTieBand > 0) always win over the preset.
13
+ */
14
+ export declare function resolveFairnessKnobs(mode: FairnessMode | undefined, pairPriorities: number[], explicit: {
15
+ loadPenalty: number;
16
+ tieBand: number;
17
+ }): {
18
+ loadPenalty: number;
19
+ tieBand: number;
20
+ };
21
+ export interface FairArbitrationOptions {
22
+ maxUserBacklogSize: number;
23
+ /**
24
+ * Per-user override of the award ceiling (compared against the same
25
+ * `backlogUsed` counter as `maxUserBacklogSize`). Used to fold in
26
+ * additional limits like the rolling-window grant cap, which can leave a
27
+ * user with less headroom than their backlog alone would allow.
28
+ */
29
+ maxByUser?: Map<string, number>;
30
+ /**
31
+ * Score subtracted per assignment already on (or won this pass into) a
32
+ * user's backlog. 0 disables load-penalized scoring.
33
+ */
34
+ loadPenalty?: number;
35
+ /**
36
+ * Width of the score bucket within which candidates count as tied; ties
37
+ * go to the less-loaded user. 0 disables tie-band arbitration.
38
+ */
39
+ tieBand?: number;
40
+ }
41
+ interface ArbitrablePair {
42
+ userId: string;
43
+ id: string;
44
+ priority: number;
45
+ }
46
+ /**
47
+ * Walks the candidate pairs in best-first order and awards each assignment to
48
+ * exactly one user, honoring per-user backlog caps. Mutates `backlogUsed`
49
+ * (one increment per awarded pair). `settled` marks assignments no longer
50
+ * available at all (already claimed, or lost to a concurrent process).
51
+ *
52
+ * Returns `winners` in award order and `deferred`: pairs skipped only because
53
+ * their user was at cap - a cap that the caller may roll back if the user
54
+ * loses a claim to a concurrent process, so these stay eligible for another
55
+ * arbitration round.
56
+ *
57
+ * With neither knob set the order is a plain stable sort by score descending,
58
+ * matching the pre-fairness-knob behavior exactly. With a knob set, ordering
59
+ * is load-aware and therefore dynamic - each award changes the winner's load,
60
+ * which can demote their remaining candidates - so a lazy max-heap re-ranks
61
+ * entries whose user's load has grown since they were pushed.
62
+ */
63
+ export declare function arbitrateFair<P extends ArbitrablePair>(pairs: P[], backlogUsed: Map<string, number>, settled: Set<string>, options: FairArbitrationOptions): {
64
+ winners: P[];
65
+ deferred: P[];
66
+ };
67
+ export {};
68
+ //# sourceMappingURL=fair-arbitration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fair-arbitration.d.ts","sourceRoot":"","sources":["../../src/scoring/fair-arbitration.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAarD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,cAAc,EAAE,MAAM,EAAE,EACxB,QAAQ,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAU1C;AAED,MAAM,WAAW,sBAAsB;IACnC,kBAAkB,EAAE,MAAM,CAAC;IAC3B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,cAAc;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,cAAc,EAClD,KAAK,EAAE,CAAC,EAAE,EACV,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAChC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EACpB,OAAO,EAAE,sBAAsB,GAChC;IAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IAAC,QAAQ,EAAE,CAAC,EAAE,CAAA;CAAE,CA6FjC"}