assignment-user-matcher 1.7.0 → 1.8.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.
@@ -10,6 +10,7 @@ const pagination_1 = require("./queries/pagination");
10
10
  const match_score_1 = require("./scoring/match-score");
11
11
  const fair_arbitration_1 = require("./scoring/fair-arbitration");
12
12
  const policy_1 = require("./escalation/policy");
13
+ const policy_2 = require("./sla/policy");
13
14
  const decision_trace_1 = require("./tracing/decision-trace");
14
15
  const features_1 = require("./learning/features");
15
16
  const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
@@ -38,6 +39,7 @@ class AssignmentMatcher {
38
39
  constructor(redisClient, options) {
39
40
  this.redisClient = redisClient;
40
41
  this.luaScriptSha = null;
42
+ this.autoRoutingWeightsSyncInterval = null;
41
43
  // ============================================================================
42
44
  // Maintenance — the periodic sweeps that make deadlines actually fire
43
45
  // ============================================================================
@@ -62,6 +64,8 @@ class AssignmentMatcher {
62
64
  this.assignmentOwnerKey = this.keys.assignmentOwner();
63
65
  this.allTagsKey = this.keys.allTags();
64
66
  this.acceptedAssignmentsKey = this.keys.acceptedAssignments();
67
+ this.acceptedAssignmentsExpiryKey = this.keys.acceptedAssignmentsExpiry();
68
+ this.assignmentsSlaExpiryKey = this.keys.assignmentsSlaExpiry();
65
69
  this.completedAssignmentsKey = this.keys.completedAssignments();
66
70
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
67
71
  this.usingDefaultMatchScore = !options?.matchingFunction;
@@ -100,7 +104,12 @@ class AssignmentMatcher {
100
104
  // Learning layer (opt-in contextual bandit re-ranking)
101
105
  this.enableLearning = options?.enableLearning ?? false;
102
106
  this.enableAutoRoutingWeights = options?.enableAutoRoutingWeights ?? false;
103
- this.learningFeatureExtractor = options?.learningFeatureExtractor ?? features_1.extractMatchFeatures;
107
+ this.learningSlaTightnessReferenceMs = options?.learningSlaTightnessReferenceMs ?? 3600000;
108
+ // The default extractor closes over the configured SLA tightness
109
+ // reference; custom extractors keep their exact signature.
110
+ this.learningFeatureExtractor =
111
+ options?.learningFeatureExtractor ??
112
+ ((user, assignment) => (0, features_1.extractMatchFeatures)(user, assignment, this.learningSlaTightnessReferenceMs));
104
113
  this.learning = new LearningManager_1.LearningManager(this.redisClient, this.keys, {
105
114
  learningRate: options?.learningRate,
106
115
  explorationRate: options?.learningExplorationRate,
@@ -134,7 +143,16 @@ class AssignmentMatcher {
134
143
  onWorkflowEvent: options?.onWorkflowEvent,
135
144
  });
136
145
  this.onAssignmentLifecycle = options?.onAssignmentLifecycle;
137
- this.readyPromise = this.initRedis();
146
+ this.autoRoutingWeightsSyncIntervalMs = options?.autoRoutingWeightsSyncIntervalMs;
147
+ if (this.enableAutoRoutingWeights && this.autoRoutingWeightsSyncIntervalMs) {
148
+ this.readyPromise = this.initRedis().then((self) => {
149
+ this.startAutoRoutingWeightsSync(this.autoRoutingWeightsSyncIntervalMs);
150
+ return self;
151
+ });
152
+ }
153
+ else {
154
+ this.readyPromise = this.initRedis();
155
+ }
138
156
  }
139
157
  /**
140
158
  * Fire the optional assignment lifecycle hook. Errors are swallowed so a
@@ -150,6 +168,91 @@ class AssignmentMatcher {
150
168
  // Best-effort hook: do not propagate.
151
169
  }
152
170
  }
171
+ // ============================================================================
172
+ // SLO stats — minimal aggregate counters (global + per-tag hashes)
173
+ // ============================================================================
174
+ /** Increment SLO counters globally and per assignment tag. Best-effort. */
175
+ async bumpSlaStats(tags, deltas) {
176
+ try {
177
+ const multi = this.redisClient.multi();
178
+ const apply = (key) => {
179
+ for (const [field, delta] of Object.entries(deltas)) {
180
+ multi.hIncrByFloat(key, field, delta);
181
+ }
182
+ };
183
+ apply(this.keys.slaStats());
184
+ for (const tag of tags ?? []) {
185
+ if (tag)
186
+ apply(this.keys.slaTagStats(tag));
187
+ }
188
+ await multi.exec();
189
+ }
190
+ catch {
191
+ // Best-effort: stats never break the lifecycle.
192
+ }
193
+ }
194
+ /**
195
+ * Accept-path stats: offers were counted at claim time; here we record
196
+ * the accept, its latency (acceptedAt - matchedAt), and whether it beat
197
+ * the response deadline that was in effect.
198
+ */
199
+ async recordSlaAccept(pendingJson, acceptedAt) {
200
+ try {
201
+ const parsed = JSON.parse(pendingJson);
202
+ const matchedAt = Number(parsed[policy_2.SLA_MATCHED_AT_FIELD]);
203
+ if (!Number.isFinite(matchedAt) || matchedAt <= 0)
204
+ return;
205
+ const latency = Math.max(0, acceptedAt - matchedAt);
206
+ const respondWithin = (0, policy_1.responseDeadlineMs)(parsed, this.matchExpirationMs);
207
+ const deltas = {
208
+ accepts: 1,
209
+ acceptLatencyMsSum: latency,
210
+ };
211
+ if (matchedAt + respondWithin >= acceptedAt)
212
+ deltas.acceptedInTime = 1;
213
+ await this.bumpSlaStats(parsed.tags, deltas);
214
+ }
215
+ catch {
216
+ // best-effort: stats never break the lifecycle
217
+ }
218
+ }
219
+ /** Completion-path stats: completion latency (completedAt - acceptedAt). */
220
+ async recordSlaComplete(acceptedJson, completedAt) {
221
+ try {
222
+ const parsed = JSON.parse(acceptedJson);
223
+ const acceptedAt = Number(parsed[policy_2.SLA_ACCEPTED_AT_FIELD]);
224
+ if (!Number.isFinite(acceptedAt) || acceptedAt <= 0)
225
+ return;
226
+ await this.bumpSlaStats(parsed.tags, {
227
+ completes: 1,
228
+ completeLatencyMsSum: Math.max(0, completedAt - acceptedAt),
229
+ });
230
+ }
231
+ catch {
232
+ // best-effort
233
+ }
234
+ }
235
+ /**
236
+ * Aggregate SLO attainment counters, globally or for a single tag.
237
+ * Means are computed from sum/count pairs; 0 when no data.
238
+ */
239
+ async getSlaStats(tag) {
240
+ await this.readyPromise;
241
+ const raw = await this.redisClient.hGetAll(tag ? this.keys.slaTagStats(tag) : this.keys.slaStats());
242
+ const num = (field) => Number(raw[field]) || 0;
243
+ const accepts = num('accepts');
244
+ const completes = num('completes');
245
+ return {
246
+ offers: num('offers'),
247
+ acceptedInTime: num('acceptedInTime'),
248
+ acceptanceBreaches: num('acceptanceBreaches'),
249
+ completionBreaches: num('completionBreaches'),
250
+ ttlExpiries: num('ttlExpiries'),
251
+ rejectionParked: num('rejectionParked'),
252
+ meanAcceptLatencyMs: accepts > 0 ? num('acceptLatencyMsSum') / accepts : 0,
253
+ meanCompleteLatencyMs: completes > 0 ? num('completeLatencyMsSum') / completes : 0,
254
+ };
255
+ }
153
256
  /** Keys for the assignment stores (used by pagination queries) */
154
257
  get assignmentStoreKeys() {
155
258
  return {
@@ -816,6 +919,11 @@ class AssignmentMatcher {
816
919
  * The applied learned map is stored on the user as `learnedRoutingWeights`
817
920
  * for observability.
818
921
  *
922
+ * Guardrails: evidence floor (`minTotalSamples`), strict veto gate for
923
+ * manual tags (`minSamplesForVeto`), and per-sync step clamp
924
+ * (`maxDeltaPerSync`) are applied automatically. Set `dryRun: true` to
925
+ * compute the would-be map without writing anything.
926
+ *
819
927
  * Returns the applied weights per user id.
820
928
  */
821
929
  async syncLearnedRoutingWeights(userId, opts) {
@@ -823,6 +931,8 @@ class AssignmentMatcher {
823
931
  const targets = userId ? [userId] : await this.learning.listTrackedUsers();
824
932
  const knownTags = opts?.includeUnexploredTags ? await this.getKnownTagsForAutoWeights() : undefined;
825
933
  const applied = {};
934
+ const maxDelta = this.learning.autoWeights.maxDeltaPerSync;
935
+ const maxWeight = this.learning.autoWeights.maxWeight ?? 100;
826
936
  for (const id of targets) {
827
937
  const userJson = await this.redisClient.hGet(this.usersKey, id);
828
938
  if (!userJson)
@@ -838,23 +948,130 @@ class AssignmentMatcher {
838
948
  const learned = await this.learning.getLearnedRoutingWeights(id, knownTags, existingForSynthesis);
839
949
  if (Object.keys(learned).length === 0)
840
950
  continue;
951
+ // Apply per-sync step clamp. Vetoes (weight 0) that passed the
952
+ // strict veto gate are allowed to jump despite the clamp.
953
+ const clampedLearned = {};
954
+ for (const [tag, weight] of Object.entries(learned)) {
955
+ if (weight === 0 || maxDelta === undefined) {
956
+ clampedLearned[tag] = weight;
957
+ continue;
958
+ }
959
+ const previous = previousLearned[tag] ?? user.routingWeights?.[tag];
960
+ if (previous === undefined) {
961
+ clampedLearned[tag] = Math.min(weight, maxWeight);
962
+ continue;
963
+ }
964
+ const lower = previous - maxDelta;
965
+ const upper = previous + maxDelta;
966
+ clampedLearned[tag] = Math.min(Math.max(weight, lower, 1), upper, maxWeight);
967
+ }
841
968
  let routingWeights;
842
969
  if (opts?.overrideManual) {
843
- routingWeights = learned;
970
+ routingWeights = { ...clampedLearned };
844
971
  }
845
972
  else {
846
973
  const manualEntries = {};
847
974
  for (const [tag, weight] of Object.entries(user.routingWeights ?? {})) {
848
- if (!(tag in previousLearned) && !(tag in learned))
975
+ if (!(tag in previousLearned) && !(tag in clampedLearned))
849
976
  manualEntries[tag] = weight;
850
977
  }
851
- routingWeights = { ...manualEntries, ...learned };
978
+ routingWeights = { ...manualEntries, ...clampedLearned };
852
979
  }
853
- await this.redisClient.hSet(this.usersKey, id, JSON.stringify({ ...user, routingWeights, learnedRoutingWeights: learned }));
854
980
  applied[id] = routingWeights;
981
+ if (opts?.dryRun)
982
+ continue;
983
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
984
+ ...user,
985
+ routingWeights,
986
+ routingWeightsSnapshot: user.routingWeights,
987
+ learnedRoutingWeights: clampedLearned,
988
+ learnedRoutingWeightsSyncedAt: Date.now(),
989
+ }));
855
990
  }
856
991
  return applied;
857
992
  }
993
+ /**
994
+ * Revert learned routing weights for one user (or all users with a
995
+ * snapshot) to the map saved before the last sync. No-op when no snapshot
996
+ * exists.
997
+ *
998
+ * Returns reverted user ids.
999
+ */
1000
+ async revertLearnedRoutingWeights(userId) {
1001
+ await this.readyPromise;
1002
+ const targets = [];
1003
+ if (userId) {
1004
+ targets.push(userId);
1005
+ }
1006
+ else {
1007
+ const all = await this.redisClient.hGetAll(this.usersKey);
1008
+ for (const [id, json] of Object.entries(all)) {
1009
+ try {
1010
+ const u = JSON.parse(json);
1011
+ if (u.routingWeightsSnapshot)
1012
+ targets.push(id);
1013
+ }
1014
+ catch {
1015
+ // ignore malformed user entries
1016
+ }
1017
+ }
1018
+ }
1019
+ const reverted = [];
1020
+ for (const id of targets) {
1021
+ const userJson = await this.redisClient.hGet(this.usersKey, id);
1022
+ if (!userJson)
1023
+ continue;
1024
+ const user = JSON.parse(userJson);
1025
+ if (!user.routingWeightsSnapshot)
1026
+ continue;
1027
+ await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
1028
+ ...user,
1029
+ routingWeights: user.routingWeightsSnapshot,
1030
+ routingWeightsSnapshot: undefined,
1031
+ learnedRoutingWeights: undefined,
1032
+ learnedRoutingWeightsSyncedAt: undefined,
1033
+ }));
1034
+ reverted.push(id);
1035
+ }
1036
+ return reverted;
1037
+ }
1038
+ /** Start the automatic learned-weights sync tick. Idempotent. */
1039
+ startAutoRoutingWeightsSync(intervalMs) {
1040
+ this.stopAutoRoutingWeightsSync();
1041
+ if (intervalMs)
1042
+ this.autoRoutingWeightsSyncIntervalMs = intervalMs;
1043
+ const ms = this.autoRoutingWeightsSyncIntervalMs;
1044
+ if (!ms || !this.enableAutoRoutingWeights)
1045
+ return;
1046
+ this.autoRoutingWeightsSyncInterval = setInterval(() => {
1047
+ this.runAutoRoutingWeightsSyncTick().catch((err) => console.error('Auto routing-weights sync tick failed:', err));
1048
+ }, ms);
1049
+ this.autoRoutingWeightsSyncInterval.unref?.();
1050
+ }
1051
+ /** Stop the automatic learned-weights sync tick. Safe when not started. */
1052
+ stopAutoRoutingWeightsSync() {
1053
+ if (this.autoRoutingWeightsSyncInterval) {
1054
+ clearInterval(this.autoRoutingWeightsSyncInterval);
1055
+ this.autoRoutingWeightsSyncInterval = null;
1056
+ }
1057
+ }
1058
+ /** Whether the automatic learned-weights sync tick is running. */
1059
+ isAutoRoutingWeightsSyncRunning() {
1060
+ return this.autoRoutingWeightsSyncInterval !== null;
1061
+ }
1062
+ async runAutoRoutingWeightsSyncTick() {
1063
+ const ms = this.autoRoutingWeightsSyncIntervalMs;
1064
+ if (!ms)
1065
+ return;
1066
+ const lockTtl = Math.max(1000, ms - 1000);
1067
+ const acquired = await this.redisClient.set(this.keys.autoWeightsSyncLock(), this.streamConsumerName, {
1068
+ NX: true,
1069
+ PX: lockTtl,
1070
+ });
1071
+ if (!acquired)
1072
+ return;
1073
+ await this.syncLearnedRoutingWeights();
1074
+ }
858
1075
  /** All known tags except the internal 'default' tag (for exploration priors) */
859
1076
  async getKnownTagsForAutoWeights() {
860
1077
  const tags = await this.redisClient.sMembers(this.allTagsKey);
@@ -902,6 +1119,20 @@ class AssignmentMatcher {
902
1119
  let { id, tags, priority, latitude, longitude } = assignment;
903
1120
  if (!priority)
904
1121
  priority = await this.calculatePriority(assignment);
1122
+ // First-enqueue clock for the freshness TTL: NX semantics via the
1123
+ // object itself — a requeue re-adds the same JSON (with the original
1124
+ // _enqueuedAt), so the TTL is never extended by rejection ping-pong.
1125
+ // Only stamped when the assignment actually declares a TTL, so
1126
+ // non-SLA assignments keep byte-identical stored JSON.
1127
+ const slaPolicy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
1128
+ let slaExpiry = null;
1129
+ if (slaPolicy?.expireAfterMs !== undefined) {
1130
+ const record = assignment;
1131
+ if (record[policy_2.SLA_ENQUEUED_AT_FIELD] === undefined) {
1132
+ record[policy_2.SLA_ENQUEUED_AT_FIELD] = Date.now();
1133
+ }
1134
+ slaExpiry = (0, policy_2.slaExpiryScore)(record[policy_2.SLA_ENQUEUED_AT_FIELD], slaPolicy);
1135
+ }
905
1136
  const assignmentPriorityKey = this.keys.assignmentPriority(id);
906
1137
  const assignmentTagsKey = this.keys.assignmentTags(id);
907
1138
  const assignmentGeoKey = this.keys.assignmentsGeo();
@@ -918,6 +1149,9 @@ class AssignmentMatcher {
918
1149
  score: priority,
919
1150
  value: id,
920
1151
  });
1152
+ if (slaExpiry !== null) {
1153
+ multi.zAdd(this.assignmentsSlaExpiryKey, { score: slaExpiry, value: id });
1154
+ }
921
1155
  if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
922
1156
  multi.geoAdd(assignmentGeoKey, {
923
1157
  longitude,
@@ -985,6 +1219,9 @@ class AssignmentMatcher {
985
1219
  }
986
1220
  // 3. Remove from Accepted state
987
1221
  multi.hDel(this.acceptedAssignmentsKey, id);
1222
+ // 4. Clear SLA indexes (no-ops for non-SLA assignments)
1223
+ multi.zRem(this.acceptedAssignmentsExpiryKey, id);
1224
+ multi.zRem(this.assignmentsSlaExpiryKey, id);
988
1225
  await multi.exec();
989
1226
  return id;
990
1227
  }
@@ -1676,7 +1913,27 @@ class AssignmentMatcher {
1676
1913
  // EscalationPolicy sets its own response deadline; everything
1677
1914
  // else uses the matcher-wide one and never pays for a parse.
1678
1915
  if (json) {
1679
- rm.hSet(this.pendingAssignmentsKey, s.id, json);
1916
+ // SLA-bearing assignments get a match timestamp for
1917
+ // accept-latency SLO stats; everyone else's JSON stays
1918
+ // byte-identical (guarded by the same cheap indexOf).
1919
+ let pendingJson = json;
1920
+ if (json.indexOf('"sla"') !== -1) {
1921
+ try {
1922
+ const parsed = JSON.parse(json);
1923
+ parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
1924
+ pendingJson = JSON.stringify(parsed);
1925
+ // Count the offer (global + per-tag) in the same batch.
1926
+ rm.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
1927
+ for (const tag of (parsed.tags ?? [])) {
1928
+ if (tag)
1929
+ rm.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
1930
+ }
1931
+ }
1932
+ catch {
1933
+ // keep original JSON on parse failure
1934
+ }
1935
+ }
1936
+ rm.hSet(this.pendingAssignmentsKey, s.id, pendingJson);
1680
1937
  rm.zAdd(this.pendingAssignmentsExpiryKey, {
1681
1938
  score: now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs),
1682
1939
  value: s.id,
@@ -2061,17 +2318,30 @@ class AssignmentMatcher {
2061
2318
  // response deadline when it declares one).
2062
2319
  const pendingJson = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
2063
2320
  const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
2321
+ const now = Date.now();
2064
2322
  const transfer = this.redisClient
2065
2323
  .multi()
2066
2324
  .sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
2067
2325
  .sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
2068
2326
  .hSet(this.assignmentOwnerKey, assignmentId, userId)
2069
2327
  .zAdd(this.pendingAssignmentsExpiryKey, {
2070
- score: Date.now() + deadlineMs,
2328
+ score: now + deadlineMs,
2071
2329
  value: assignmentId,
2072
2330
  });
2331
+ // Refresh the SLA match timestamp for the new owner so accept
2332
+ // latency is measured against the transfer, not the original claim.
2333
+ if (pendingJson && pendingJson.indexOf('"sla"') !== -1) {
2334
+ try {
2335
+ const parsed = JSON.parse(pendingJson);
2336
+ parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
2337
+ transfer.hSet(this.pendingAssignmentsKey, assignmentId, JSON.stringify(parsed));
2338
+ }
2339
+ catch {
2340
+ // keep original JSON on parse failure
2341
+ }
2342
+ }
2073
2343
  await transfer.exec();
2074
- const reassignedAt = Date.now();
2344
+ const reassignedAt = now;
2075
2345
  this.emitAssignmentLifecycle({
2076
2346
  kind: 'pending',
2077
2347
  taskId: assignmentId,
@@ -2120,6 +2390,7 @@ class AssignmentMatcher {
2120
2390
  throw new Error('Assignment not found for user');
2121
2391
  // Get the assignment JSON before removing from pending
2122
2392
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
2393
+ const now = Date.now();
2123
2394
  const multi = this.redisClient.multi();
2124
2395
  multi.sRem(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
2125
2396
  multi.hDel(this.pendingAssignmentsKey, assignmentId);
@@ -2127,11 +2398,35 @@ class AssignmentMatcher {
2127
2398
  multi.hDel(this.assignmentOwnerKey, assignmentId);
2128
2399
  // The wait clock stops when a user takes the work
2129
2400
  multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
2130
- // Store in accepted assignments
2401
+ // Store in accepted assignments. SLA-bearing assignments are stamped
2402
+ // with the accept timestamp/owner and registered on the completion-
2403
+ // deadline index when they declare completeWithinMs.
2131
2404
  if (json) {
2132
- multi.hSet(this.acceptedAssignmentsKey, assignmentId, json);
2405
+ const slaPolicy = (0, policy_2.slaFromJson)(json);
2406
+ let acceptedJson = json;
2407
+ if (slaPolicy) {
2408
+ try {
2409
+ const parsed = JSON.parse(json);
2410
+ parsed[policy_2.SLA_ACCEPTED_AT_FIELD] = now;
2411
+ parsed[policy_2.SLA_ACCEPTED_BY_FIELD] = userId;
2412
+ acceptedJson = JSON.stringify(parsed);
2413
+ const deadline = (0, policy_2.completionDeadlineScore)(now, slaPolicy);
2414
+ if (deadline !== null) {
2415
+ multi.zAdd(this.acceptedAssignmentsExpiryKey, { score: deadline, value: assignmentId });
2416
+ }
2417
+ }
2418
+ catch {
2419
+ // keep original JSON on parse failure
2420
+ }
2421
+ }
2422
+ multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
2133
2423
  }
2134
2424
  await multi.exec();
2425
+ // SLO accept stats piggyback the accept path (internally guarded:
2426
+ // stats errors never break the lifecycle).
2427
+ if (json && json.indexOf('"sla"') !== -1) {
2428
+ await this.recordSlaAccept(json, now);
2429
+ }
2135
2430
  if (this.enableLearning) {
2136
2431
  await this.learning.applyOutcome(assignmentId, 'accept');
2137
2432
  }
@@ -2139,7 +2434,7 @@ class AssignmentMatcher {
2139
2434
  kind: 'accepted',
2140
2435
  taskId: assignmentId,
2141
2436
  workerId: userId,
2142
- acceptedAt: Date.now(),
2437
+ acceptedAt: now,
2143
2438
  });
2144
2439
  await this.touchUser(userId);
2145
2440
  return true;
@@ -2169,10 +2464,69 @@ class AssignmentMatcher {
2169
2464
  });
2170
2465
  await this.touchUser(userId);
2171
2466
  if (json) {
2172
- await this.addAssignment(JSON.parse(json));
2467
+ await this.requeueAfterRefusal(JSON.parse(json), 'reject');
2173
2468
  }
2174
2469
  return true;
2175
2470
  }
2471
+ /**
2472
+ * Shared requeue path for refusals (explicit rejects and blocking
2473
+ * no-response expiries): increments the SLA rejection counter and, when
2474
+ * the budget is exhausted, applies `onMaxRejections` instead of
2475
+ * requeueing. Non-SLA assignments take the untouched legacy path.
2476
+ */
2477
+ async requeueAfterRefusal(assignment, cause) {
2478
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
2479
+ if (!policy) {
2480
+ await this.addAssignment(assignment);
2481
+ return;
2482
+ }
2483
+ const record = assignment;
2484
+ const rejections = (0, policy_2.rejectionCountOf)(assignment) + 1;
2485
+ record[policy_2.SLA_REJECTION_COUNT_FIELD] = rejections;
2486
+ // 'keep' makes the budget measurement-only: the counter keeps
2487
+ // accumulating so stats stay honest, but the assignment is requeued.
2488
+ if (!(0, policy_2.rejectionBudgetExhausted)(assignment, policy) || policy.onMaxRejections === 'keep') {
2489
+ await this.addAssignment(assignment);
2490
+ return;
2491
+ }
2492
+ await this.applyRejectionExhaustion(assignment, policy, rejections, cause);
2493
+ }
2494
+ /**
2495
+ * Terminal step for an assignment whose rejection budget is exhausted:
2496
+ * parked or failed per `onMaxRejections`. The caller must already have
2497
+ * removed it from the pending structures.
2498
+ */
2499
+ async applyRejectionExhaustion(assignment, policy, rejections, cause) {
2500
+ const action = policy.onMaxRejections === 'fail' ? 'fail' : 'park';
2501
+ const now = Date.now();
2502
+ // The assignment leaves the queued/pending universe: stop both clocks.
2503
+ const multi = this.redisClient
2504
+ .multi()
2505
+ .zRem(this.keys.assignmentsQueuedAt(), assignment.id)
2506
+ .zRem(this.assignmentsSlaExpiryKey, assignment.id);
2507
+ if (action === 'park') {
2508
+ multi.hSet(this.keys.parkedAssignments(), assignment.id, JSON.stringify(assignment));
2509
+ }
2510
+ else {
2511
+ multi.hSet(this.completedAssignmentsKey, assignment.id, JSON.stringify({
2512
+ ...assignment,
2513
+ _failedAt: now,
2514
+ _failureReason: `rejection-budget-exhausted:${cause}`,
2515
+ }));
2516
+ }
2517
+ await multi.exec();
2518
+ this.emitAssignmentLifecycle({
2519
+ kind: 'rejectionBudgetExhausted',
2520
+ taskId: assignment.id,
2521
+ rejections,
2522
+ action,
2523
+ assignment,
2524
+ at: now,
2525
+ });
2526
+ if (action === 'park') {
2527
+ await this.bumpSlaStats(assignment.tags, { rejectionParked: 1 });
2528
+ }
2529
+ }
2176
2530
  /**
2177
2531
  * Complete an assignment with a result payload.
2178
2532
  * Moves the assignment from 'accepted' to 'completed' state and publishes an event
@@ -2194,6 +2548,9 @@ class AssignmentMatcher {
2194
2548
  // Move from accepted to completed
2195
2549
  const multi = this.redisClient.multi();
2196
2550
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
2551
+ // Clear SLA indexes (no-ops for non-SLA assignments)
2552
+ multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2553
+ multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
2197
2554
  // Store in completed with result metadata
2198
2555
  const completedData = {
2199
2556
  ...assignment,
@@ -2203,6 +2560,9 @@ class AssignmentMatcher {
2203
2560
  };
2204
2561
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
2205
2562
  await multi.exec();
2563
+ if (json.indexOf('"sla"') !== -1) {
2564
+ await this.recordSlaComplete(json, now);
2565
+ }
2206
2566
  if (this.enableLearning) {
2207
2567
  await this.learning.applyOutcome(assignmentId, 'complete');
2208
2568
  }
@@ -2243,6 +2603,9 @@ class AssignmentMatcher {
2243
2603
  // Move from accepted to completed (with failed status)
2244
2604
  const multi = this.redisClient.multi();
2245
2605
  multi.hDel(this.acceptedAssignmentsKey, assignmentId);
2606
+ // Clear SLA indexes (no-ops for non-SLA assignments)
2607
+ multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
2608
+ multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
2246
2609
  const failedData = {
2247
2610
  ...assignment,
2248
2611
  _failedBy: userId,
@@ -2473,6 +2836,15 @@ class AssignmentMatcher {
2473
2836
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
2474
2837
  const assignment = json ? JSON.parse(json) : null;
2475
2838
  const policy = assignment ? (0, policy_1.normalizeEscalationPolicy)(assignment.escalation) : null;
2839
+ const slaPolicy = assignment ? (0, policy_2.normalizeSlaPolicy)(assignment.sla) : null;
2840
+ // A blocking no-response expiry counts as a refusal against the
2841
+ // SLA rejection budget (same as an explicit reject). Increment
2842
+ // before escalateAssignment() spreads the object so the decision
2843
+ // carries the bumped count.
2844
+ const countsAsRefusal = Boolean(policy && policy.onNoResponse === 'block' && owner);
2845
+ if (assignment && slaPolicy && countsAsRefusal) {
2846
+ assignment[policy_2.SLA_REJECTION_COUNT_FIELD] = (0, policy_2.rejectionCountOf)(assignment) + 1;
2847
+ }
2476
2848
  const decision = assignment && policy ? (0, policy_1.escalateAssignment)(assignment, policy) : null;
2477
2849
  const multi = this.redisClient.multi();
2478
2850
  if (owner) {
@@ -2494,6 +2866,9 @@ class AssignmentMatcher {
2494
2866
  workerId: owner ?? null,
2495
2867
  expiredAt: now,
2496
2868
  });
2869
+ if (assignment && slaPolicy) {
2870
+ await this.bumpSlaStats(assignment.tags, { acceptanceBreaches: 1 });
2871
+ }
2497
2872
  if (this.enableLearning) {
2498
2873
  await this.learning.applyOutcome(id, 'expire');
2499
2874
  }
@@ -2509,6 +2884,15 @@ class AssignmentMatcher {
2509
2884
  }
2510
2885
  if (!assignment)
2511
2886
  continue;
2887
+ // The SLA rejection budget outranks the escalation ladder: once
2888
+ // nobody will take the work, tier hops are moot.
2889
+ if (slaPolicy &&
2890
+ countsAsRefusal &&
2891
+ (0, policy_2.rejectionBudgetExhausted)(assignment, slaPolicy) &&
2892
+ slaPolicy.onMaxRejections !== 'keep') {
2893
+ await this.applyRejectionExhaustion(assignment, slaPolicy, (0, policy_2.rejectionCountOf)(assignment), 'blocking-expiry');
2894
+ continue;
2895
+ }
2512
2896
  if (decision && decision.exhausted) {
2513
2897
  this.emitAssignmentLifecycle({
2514
2898
  kind: 'escalationExhausted',
@@ -2558,6 +2942,171 @@ class AssignmentMatcher {
2558
2942
  const { expired } = await this.processResponseDeadlines();
2559
2943
  return expired;
2560
2944
  }
2945
+ /**
2946
+ * Sweep accepted assignments whose completion deadline
2947
+ * (`sla.completeWithinMs`, measured from accept) has elapsed.
2948
+ *
2949
+ * Each breached entry is removed from the deadline index before the
2950
+ * action runs, so a breach fires exactly once: a `'notify'` breach does
2951
+ * not re-fire every tick, and a `'requeue'`d assignment only gets a
2952
+ * fresh completion clock on its next accept.
2953
+ */
2954
+ async processCompletionDeadlines() {
2955
+ await this.readyPromise;
2956
+ const now = Date.now();
2957
+ const breachedIds = await this.redisClient.zRangeByScore(this.acceptedAssignmentsExpiryKey, '-inf', now);
2958
+ let breached = 0;
2959
+ for (const id of breachedIds) {
2960
+ const json = await this.redisClient.hGet(this.acceptedAssignmentsKey, id);
2961
+ // Fire-once: drop the index entry first. If the assignment is
2962
+ // gone (completed/failed/removed between the zRange and now)
2963
+ // there is nothing to do.
2964
+ await this.redisClient.zRem(this.acceptedAssignmentsExpiryKey, id);
2965
+ if (!json)
2966
+ continue;
2967
+ const assignment = JSON.parse(json);
2968
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
2969
+ if (!policy)
2970
+ continue;
2971
+ breached++;
2972
+ const record = assignment;
2973
+ const workerId = record[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
2974
+ const action = policy.onCompletionBreach;
2975
+ this.emitAssignmentLifecycle({
2976
+ kind: 'completionBreached',
2977
+ taskId: id,
2978
+ workerId,
2979
+ action,
2980
+ assignment,
2981
+ at: now,
2982
+ });
2983
+ await this.bumpSlaStats(assignment.tags, { completionBreaches: 1 });
2984
+ if (this.enableLearning) {
2985
+ await this.learning.applyOutcome(id, action === 'fail' ? 'fail' : 'expire');
2986
+ }
2987
+ if (action === 'notify') {
2988
+ // Worker keeps the assignment; the event + learning outcome
2989
+ // above are the whole breach response.
2990
+ continue;
2991
+ }
2992
+ if (action === 'requeue') {
2993
+ const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
2994
+ if (workerId)
2995
+ multi.sAdd(this.keys.userRejected(workerId), id);
2996
+ await multi.exec();
2997
+ // The JSON still carries _enqueuedAt, so the freshness TTL
2998
+ // keeps ticking across the requeue. A requeue after a
2999
+ // completion breach is not a refusal: _rejectionCount is
3000
+ // untouched.
3001
+ await this.addAssignment(assignment);
3002
+ continue;
3003
+ }
3004
+ if (action === 'fail') {
3005
+ await this.redisClient
3006
+ .multi()
3007
+ .hDel(this.acceptedAssignmentsKey, id)
3008
+ .hSet(this.completedAssignmentsKey, id, JSON.stringify({
3009
+ ...assignment,
3010
+ _failedBy: workerId,
3011
+ _failedAt: now,
3012
+ _failureReason: 'completion-sla-breach',
3013
+ }))
3014
+ // Terminal: the freshness TTL no longer applies.
3015
+ .zRem(this.assignmentsSlaExpiryKey, id)
3016
+ .exec();
3017
+ continue;
3018
+ }
3019
+ // 'park'
3020
+ await this.redisClient
3021
+ .multi()
3022
+ .hDel(this.acceptedAssignmentsKey, id)
3023
+ .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
3024
+ .zRem(this.assignmentsSlaExpiryKey, id)
3025
+ .exec();
3026
+ }
3027
+ return { breached };
3028
+ }
3029
+ /**
3030
+ * Sweep assignments whose freshness TTL (`sla.expireAfterMs`, measured
3031
+ * from first enqueue) has elapsed. Applies in every state — queued,
3032
+ * pending, accepted — because stale work is stale regardless of who
3033
+ * holds it.
3034
+ */
3035
+ async processSlaExpiries() {
3036
+ await this.readyPromise;
3037
+ const now = Date.now();
3038
+ const expiredIds = await this.redisClient.zRangeByScore(this.assignmentsSlaExpiryKey, '-inf', now);
3039
+ let expired = 0;
3040
+ for (const id of expiredIds) {
3041
+ // Locate the current store: pending (with owner), accepted, or queued.
3042
+ const [pendingJson, acceptedJson, queuedJson] = await Promise.all([
3043
+ this.redisClient.hGet(this.pendingAssignmentsKey, id),
3044
+ this.redisClient.hGet(this.acceptedAssignmentsKey, id),
3045
+ this.redisClient.hGet(this.assignmentsRefKey, id),
3046
+ ]);
3047
+ const json = pendingJson ?? acceptedJson ?? queuedJson;
3048
+ // Stale index entry (already completed/failed/removed): just clean it.
3049
+ if (!json) {
3050
+ await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
3051
+ continue;
3052
+ }
3053
+ const assignment = JSON.parse(json);
3054
+ const policy = (0, policy_2.normalizeSlaPolicy)(assignment.sla);
3055
+ if (!policy || policy.expireAfterMs === undefined) {
3056
+ await this.redisClient.zRem(this.assignmentsSlaExpiryKey, id);
3057
+ continue;
3058
+ }
3059
+ const ownerId = pendingJson
3060
+ ? await this.redisClient.hGet(this.assignmentOwnerKey, id)
3061
+ : (assignment[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null);
3062
+ const action = policy.onExpire;
3063
+ expired++;
3064
+ if (action === 'park') {
3065
+ await this.redisClient.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment));
3066
+ }
3067
+ // Remove from whichever store it occupies, with full index cleanup.
3068
+ if (pendingJson) {
3069
+ const multi = this.redisClient.multi();
3070
+ if (ownerId)
3071
+ multi.sRem(this.keys.userAssignments(ownerId), `assignment:${id}`);
3072
+ multi.hDel(this.pendingAssignmentsKey, id);
3073
+ multi.zRem(this.pendingAssignmentsExpiryKey, id);
3074
+ multi.hDel(this.assignmentOwnerKey, id);
3075
+ multi.zRem(this.assignmentsSlaExpiryKey, id);
3076
+ // Leaving the queued/pending universe: the wait clock stops.
3077
+ multi.zRem(this.keys.assignmentsQueuedAt(), id);
3078
+ await multi.exec();
3079
+ }
3080
+ else if (acceptedJson) {
3081
+ await this.redisClient
3082
+ .multi()
3083
+ .hDel(this.acceptedAssignmentsKey, id)
3084
+ .zRem(this.acceptedAssignmentsExpiryKey, id)
3085
+ .zRem(this.assignmentsSlaExpiryKey, id)
3086
+ .exec();
3087
+ }
3088
+ else {
3089
+ // Queued: full index cleanup via removeAssignment (also zRems
3090
+ // the SLA expiry index).
3091
+ await this.removeAssignment(id);
3092
+ }
3093
+ this.emitAssignmentLifecycle({
3094
+ kind: 'slaExpired',
3095
+ taskId: id,
3096
+ ownerId,
3097
+ action,
3098
+ // Emitted after the removal above, so this snapshot is the only
3099
+ // remaining copy on the 'drop' path.
3100
+ assignment,
3101
+ at: now,
3102
+ });
3103
+ await this.bumpSlaStats(assignment.tags, { ttlExpiries: 1 });
3104
+ if (this.enableLearning) {
3105
+ await this.learning.applyOutcome(id, 'expire');
3106
+ }
3107
+ }
3108
+ return { expired };
3109
+ }
2561
3110
  /**
2562
3111
  * Assignments held out of matching because their escalation ladder was
2563
3112
  * exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
@@ -2571,6 +3120,10 @@ class AssignmentMatcher {
2571
3120
  * Return a parked assignment to the queue, optionally resetting its
2572
3121
  * escalation level so the ladder can run again from the top.
2573
3122
  *
3123
+ * `resetSla` clears the first-enqueue clock and rejection counter.
3124
+ * Without it an unparked assignment whose freshness TTL already elapsed
3125
+ * will simply expire again on the next TTL sweep.
3126
+ *
2574
3127
  * @returns false when the id was not parked
2575
3128
  */
2576
3129
  async unparkAssignment(id, opts) {
@@ -2579,8 +3132,16 @@ class AssignmentMatcher {
2579
3132
  if (!json)
2580
3133
  return false;
2581
3134
  const assignment = JSON.parse(json);
3135
+ const record = assignment;
2582
3136
  if (opts?.resetEscalation)
2583
- delete assignment._escalationLevel;
3137
+ delete record._escalationLevel;
3138
+ if (opts?.resetSla) {
3139
+ delete record[policy_2.SLA_ENQUEUED_AT_FIELD];
3140
+ delete record[policy_2.SLA_REJECTION_COUNT_FIELD];
3141
+ delete record[policy_2.SLA_MATCHED_AT_FIELD];
3142
+ delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
3143
+ delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
3144
+ }
2584
3145
  await this.redisClient.hDel(this.keys.parkedAssignments(), id);
2585
3146
  await this.addAssignment(assignment);
2586
3147
  return true;
@@ -2609,12 +3170,20 @@ class AssignmentMatcher {
2609
3170
  let parked = 0;
2610
3171
  let expiredSteps = 0;
2611
3172
  let releasedIdleUsers = 0;
3173
+ let completionBreaches = 0;
3174
+ let slaExpiries = 0;
2612
3175
  if (opts.responseDeadlines) {
2613
3176
  const result = await this.processResponseDeadlines();
2614
3177
  expiredMatches = result.expired;
2615
3178
  escalations = result.escalations;
2616
3179
  parked = result.parked;
2617
3180
  }
3181
+ if (opts.completionDeadlines) {
3182
+ completionBreaches = (await this.processCompletionDeadlines()).breached;
3183
+ }
3184
+ if (opts.slaExpiries) {
3185
+ slaExpiries = (await this.processSlaExpiries()).expired;
3186
+ }
2618
3187
  if (opts.workflowStepTimeouts && this.enableWorkflows) {
2619
3188
  expiredSteps = await this.processExpiredWorkflowSteps();
2620
3189
  }
@@ -2627,6 +3196,8 @@ class AssignmentMatcher {
2627
3196
  parked,
2628
3197
  expiredSteps,
2629
3198
  releasedIdleUsers,
3199
+ completionBreaches,
3200
+ slaExpiries,
2630
3201
  tookMs: Date.now() - startedAt,
2631
3202
  };
2632
3203
  }
@@ -2669,6 +3240,8 @@ class AssignmentMatcher {
2669
3240
  resolveMaintenanceOptions(options) {
2670
3241
  return {
2671
3242
  responseDeadlines: options?.responseDeadlines ?? true,
3243
+ completionDeadlines: options?.completionDeadlines ?? true,
3244
+ slaExpiries: options?.slaExpiries ?? true,
2672
3245
  workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
2673
3246
  idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
2674
3247
  };