assignment-user-matcher 1.3.0 → 1.7.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.
@@ -9,6 +9,7 @@ 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
11
  const fair_arbitration_1 = require("./scoring/fair-arbitration");
12
+ const policy_1 = require("./escalation/policy");
12
13
  const decision_trace_1 = require("./tracing/decision-trace");
13
14
  const features_1 = require("./learning/features");
14
15
  const DecisionTraceManager_1 = require("./managers/DecisionTraceManager");
@@ -37,6 +38,12 @@ class AssignmentMatcher {
37
38
  constructor(redisClient, options) {
38
39
  this.redisClient = redisClient;
39
40
  this.luaScriptSha = null;
41
+ // ============================================================================
42
+ // Maintenance — the periodic sweeps that make deadlines actually fire
43
+ // ============================================================================
44
+ this.maintenanceInterval = null;
45
+ this.maintenanceOptions = null;
46
+ this.maintenanceRunning = false;
40
47
  this.autoReleaseInterval = null;
41
48
  this.idleUserInterval = null;
42
49
  this.relevantBatchSize = options?.relevantBatchSize ?? 50;
@@ -124,16 +131,33 @@ class AssignmentMatcher {
124
131
  eventBatchSize: options?.workflowEventBatchSize,
125
132
  pollBlockMs: options?.workflowPollBlockMs,
126
133
  maxEventsPerSecond: options?.workflowMaxEventsPerSecond,
134
+ onWorkflowEvent: options?.onWorkflowEvent,
127
135
  });
136
+ this.onAssignmentLifecycle = options?.onAssignmentLifecycle;
128
137
  this.readyPromise = this.initRedis();
129
138
  }
130
- /** Keys for the three assignment stores (used by pagination queries) */
139
+ /**
140
+ * Fire the optional assignment lifecycle hook. Errors are swallowed so a
141
+ * slow/failing observer can never break a lifecycle transition.
142
+ */
143
+ emitAssignmentLifecycle(event) {
144
+ if (!this.onAssignmentLifecycle)
145
+ return;
146
+ try {
147
+ this.onAssignmentLifecycle(event);
148
+ }
149
+ catch (err) {
150
+ // Best-effort hook: do not propagate.
151
+ }
152
+ }
153
+ /** Keys for the assignment stores (used by pagination queries) */
131
154
  get assignmentStoreKeys() {
132
155
  return {
133
156
  queued: this.assignmentsRefKey,
134
157
  pending: this.pendingAssignmentsKey,
135
158
  accepted: this.acceptedAssignmentsKey,
136
159
  completed: this.completedAssignmentsKey,
160
+ parked: this.keys.parkedAssignments(),
137
161
  };
138
162
  }
139
163
  async initRedis() {
@@ -506,17 +530,35 @@ class AssignmentMatcher {
506
530
  }
507
531
  /** One user's full eligibility/score evaluation for explainMatch(). */
508
532
  async explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights) {
533
+ const [isRejected, backlog, isPaused] = await Promise.all([
534
+ this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId),
535
+ this.redisClient.sCard(this.keys.userAssignments(user.id)),
536
+ this.redisClient.sIsMember(this.keys.pausedUsers(), user.id),
537
+ ]);
538
+ return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
539
+ assignmentId,
540
+ ownerId,
541
+ isRejected: Boolean(isRejected),
542
+ backlog,
543
+ isPaused: Boolean(isPaused),
544
+ });
545
+ }
546
+ /**
547
+ * Shared eligibility/scoring evaluation used by explainMatch() and
548
+ * previewMatch(). Read-only: never claims, writes, or records decisions.
549
+ */
550
+ async evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, opts) {
509
551
  const reasons = [];
510
552
  let eligible = true;
553
+ const assignmentId = opts.assignmentId ?? '';
554
+ const ownerId = opts.ownerId ?? null;
555
+ const isRejected = opts.isRejected ?? false;
556
+ const isPaused = opts.isPaused ?? false;
557
+ const backlog = opts.backlog ?? 0;
511
558
  if (assignment.vetoedUsers?.includes(user.id)) {
512
559
  reasons.push({ kind: 'assignmentVeto' });
513
560
  eligible = false;
514
561
  }
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
562
  if (isRejected) {
521
563
  reasons.push({ kind: 'rejectedPreviously' });
522
564
  eligible = false;
@@ -575,7 +617,7 @@ class AssignmentMatcher {
575
617
  reasons.push(...explained.reasons);
576
618
  }
577
619
  else {
578
- [score, combinedPriority] = await this.matchScore(user, tagsCsv, basePriority, assignmentId, assignment.skillThresholds);
620
+ [score, combinedPriority] = await this.matchScore(user, tagsCsv, basePriority, assignmentId || undefined, assignment.skillThresholds);
579
621
  reasons.push({ kind: 'customScore', score });
580
622
  }
581
623
  if (!score)
@@ -598,6 +640,52 @@ class AssignmentMatcher {
598
640
  reasons,
599
641
  };
600
642
  }
643
+ /**
644
+ * Preview which users would be candidates for a hypothetical assignment
645
+ * without creating it or claiming anything. Uses the same scoring, hard
646
+ * rules, and learning re-ranking as real matching, so the ranked result
647
+ * matches what `explainMatch()` would report if the assignment were added.
648
+ */
649
+ async previewMatch(input, opts) {
650
+ await this.readyPromise;
651
+ const evaluatedAt = Date.now();
652
+ const assignment = {
653
+ id: '',
654
+ tags: input.tags,
655
+ priority: input.priority ?? 0,
656
+ skillThresholds: input.skillThresholds,
657
+ allowedCidrs: input.allowedCidrs,
658
+ vetoedUsers: input.vetoedUsers,
659
+ latitude: input.latitude,
660
+ longitude: input.longitude,
661
+ maxDistanceKm: input.maxDistanceKm,
662
+ requireGeo: input.requireGeo,
663
+ };
664
+ const tagsCsv = [...input.tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
665
+ const basePriority = Number(assignment.priority) || 0;
666
+ let userList;
667
+ if (opts?.userIds && opts.userIds.length > 0) {
668
+ const jsons = await this.redisClient.hmGet(this.usersKey, opts.userIds);
669
+ userList = jsons.filter((json) => Boolean(json)).map((json) => JSON.parse(json));
670
+ }
671
+ else {
672
+ const all = await this.redisClient.hGetAll(this.usersKey);
673
+ userList = Object.values(all).map((json) => JSON.parse(json));
674
+ }
675
+ const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
676
+ const modelWeights = this.enableLearning ? await this.learning.getModel() : undefined;
677
+ const candidates = await Promise.all(userList.map(async (user) => {
678
+ const backlog = await this.redisClient.sCard(this.keys.userAssignments(user.id));
679
+ return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
680
+ ownerId: null,
681
+ isRejected: false,
682
+ backlog,
683
+ isPaused: paused.has(user.id),
684
+ });
685
+ }));
686
+ (0, decision_trace_1.sortCandidates)(candidates);
687
+ return { tags: input.tags, priority: basePriority, evaluatedAt, candidates };
688
+ }
601
689
  /** Build and record this pass's decision traces; failures never break matching. */
602
690
  async recordPassTraces(collector, winners, workflowGrants, mode, users) {
603
691
  if (winners.size === 0 && workflowGrants.length === 0)
@@ -922,6 +1010,15 @@ class AssignmentMatcher {
922
1010
  const json = await this.redisClient.hGet(this.usersKey, userId);
923
1011
  return json ? JSON.parse(json) : null;
924
1012
  }
1013
+ /**
1014
+ * Whether a user is registered in the pool. Used by the workflow engine
1015
+ * (via the WorkflowHost interface) to validate an initiator before
1016
+ * starting a run that targets 'initiator'.
1017
+ */
1018
+ async userExists(userId) {
1019
+ await this.readyPromise;
1020
+ return Boolean(await this.redisClient.hExists(this.usersKey, userId));
1021
+ }
925
1022
  /** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
926
1023
  async getUsers() {
927
1024
  await this.readyPromise;
@@ -967,6 +1064,19 @@ class AssignmentMatcher {
967
1064
  await this.touchUser(userId);
968
1065
  return wasPaused > 0;
969
1066
  }
1067
+ /**
1068
+ * Requeue every pending (matched but not yet accepted) assignment the user
1069
+ * holds so other users can pick them up — the operator's "this person is
1070
+ * gone, redistribute their work" move, typically paired with `pauseUser`
1071
+ * (which alone deliberately preserves the backlog). Accepted assignments
1072
+ * (work in progress) are never touched. Requeued assignments keep their
1073
+ * original wait clock, and a still-paused user won't win them back until
1074
+ * resumed. Returns the released assignment ids ([] when nothing was held).
1075
+ */
1076
+ async releaseUserAssignments(userId) {
1077
+ await this.readyPromise;
1078
+ return this.releaseUserPendingAssignments(userId);
1079
+ }
970
1080
  /** Whether a user is currently paused. */
971
1081
  async isUserPaused(userId) {
972
1082
  await this.readyPromise;
@@ -1562,14 +1672,31 @@ class AssignmentMatcher {
1562
1672
  for (const tag of tags) {
1563
1673
  rm.zRem(this.keys.tagAssignments(tag), s.id);
1564
1674
  }
1565
- // Add to pending structures
1675
+ // Add to pending structures. An assignment carrying an
1676
+ // EscalationPolicy sets its own response deadline; everything
1677
+ // else uses the matcher-wide one and never pays for a parse.
1566
1678
  if (json) {
1567
1679
  rm.hSet(this.pendingAssignmentsKey, s.id, json);
1568
- rm.zAdd(this.pendingAssignmentsExpiryKey, { score: now + this.matchExpirationMs, value: s.id });
1680
+ rm.zAdd(this.pendingAssignmentsExpiryKey, {
1681
+ score: now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs),
1682
+ value: s.id,
1683
+ });
1569
1684
  rm.hSet(this.assignmentOwnerKey, s.id, user.id);
1570
1685
  }
1571
1686
  }
1572
1687
  await rm.exec();
1688
+ for (let i = 0; i < selected.length; i++) {
1689
+ const s = selected[i];
1690
+ if (!claimedIds.has(s.id))
1691
+ continue;
1692
+ this.emitAssignmentLifecycle({
1693
+ kind: 'pending',
1694
+ taskId: s.id,
1695
+ workerId: user.id,
1696
+ matchedAt: now,
1697
+ expiresAt: now + (0, policy_1.responseDeadlineFromJson)(jsons[i], this.matchExpirationMs),
1698
+ });
1699
+ }
1573
1700
  }
1574
1701
  return claimedIds;
1575
1702
  }
@@ -1930,17 +2057,28 @@ class AssignmentMatcher {
1930
2057
  }
1931
2058
  else {
1932
2059
  // Pending under another user: transfer ownership and restart the
1933
- // expiry clock for the new owner.
2060
+ // expiry clock for the new owner (honouring the assignment's own
2061
+ // response deadline when it declares one).
2062
+ const pendingJson = await this.redisClient.hGet(this.pendingAssignmentsKey, assignmentId);
2063
+ const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
1934
2064
  const transfer = this.redisClient
1935
2065
  .multi()
1936
2066
  .sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`)
1937
2067
  .sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
1938
2068
  .hSet(this.assignmentOwnerKey, assignmentId, userId)
1939
2069
  .zAdd(this.pendingAssignmentsExpiryKey, {
1940
- score: Date.now() + this.matchExpirationMs,
2070
+ score: Date.now() + deadlineMs,
1941
2071
  value: assignmentId,
1942
2072
  });
1943
2073
  await transfer.exec();
2074
+ const reassignedAt = Date.now();
2075
+ this.emitAssignmentLifecycle({
2076
+ kind: 'pending',
2077
+ taskId: assignmentId,
2078
+ workerId: userId,
2079
+ matchedAt: reassignedAt,
2080
+ expiresAt: reassignedAt + deadlineMs,
2081
+ });
1944
2082
  }
1945
2083
  await this.touchUser(userId);
1946
2084
  await this.recordManualAssignTrace(assignmentId, userId, force, previousOwnerId ?? null);
@@ -1997,6 +2135,12 @@ class AssignmentMatcher {
1997
2135
  if (this.enableLearning) {
1998
2136
  await this.learning.applyOutcome(assignmentId, 'accept');
1999
2137
  }
2138
+ this.emitAssignmentLifecycle({
2139
+ kind: 'accepted',
2140
+ taskId: assignmentId,
2141
+ workerId: userId,
2142
+ acceptedAt: Date.now(),
2143
+ });
2000
2144
  await this.touchUser(userId);
2001
2145
  return true;
2002
2146
  }
@@ -2017,6 +2161,12 @@ class AssignmentMatcher {
2017
2161
  if (this.enableLearning) {
2018
2162
  await this.learning.applyOutcome(assignmentId, 'reject');
2019
2163
  }
2164
+ this.emitAssignmentLifecycle({
2165
+ kind: 'rejected',
2166
+ taskId: assignmentId,
2167
+ workerId: userId,
2168
+ rejectedAt: Date.now(),
2169
+ });
2020
2170
  await this.touchUser(userId);
2021
2171
  if (json) {
2022
2172
  await this.addAssignment(JSON.parse(json));
@@ -2067,6 +2217,12 @@ class AssignmentMatcher {
2067
2217
  payload: result?.data,
2068
2218
  });
2069
2219
  }
2220
+ this.emitAssignmentLifecycle({
2221
+ kind: 'completed',
2222
+ taskId: assignmentId,
2223
+ workerId: userId,
2224
+ completedAt: now,
2225
+ });
2070
2226
  return true;
2071
2227
  }
2072
2228
  /**
@@ -2187,6 +2343,15 @@ class AssignmentMatcher {
2187
2343
  await this.readyPromise;
2188
2344
  return this.workflow.getActiveWorkflowsForUser(userId);
2189
2345
  }
2346
+ /**
2347
+ * List workflow instances (runs), newest-created first, optionally
2348
+ * filtered by status and/or workflow definition. Paginated via an opaque
2349
+ * cursor from the previous page's `nextCursor`.
2350
+ */
2351
+ async listWorkflowInstances(query) {
2352
+ await this.readyPromise;
2353
+ return this.workflow.listWorkflowInstances(query);
2354
+ }
2190
2355
  /**
2191
2356
  * Cancel a workflow instance.
2192
2357
  */
@@ -2194,6 +2359,16 @@ class AssignmentMatcher {
2194
2359
  await this.readyPromise;
2195
2360
  return this.workflow.cancelWorkflow(instanceId);
2196
2361
  }
2362
+ /**
2363
+ * Complete (or fail, via `outcome.success: false`) an external step from
2364
+ * outside this process — the counterpart to the `step.ready` transition
2365
+ * delivered via `onWorkflowEvent`. Throws if the step isn't the run's
2366
+ * current step (or a pending parallel branch) or isn't an external step.
2367
+ */
2368
+ async completeWorkflowStep(instanceId, stepId, outcome) {
2369
+ await this.readyPromise;
2370
+ return this.workflow.completeWorkflowStep(instanceId, stepId, outcome);
2371
+ }
2197
2372
  /**
2198
2373
  * Check and process expired workflow steps.
2199
2374
  * Should be called periodically.
@@ -2202,6 +2377,15 @@ class AssignmentMatcher {
2202
2377
  await this.readyPromise;
2203
2378
  return this.workflow.processExpiredWorkflowSteps();
2204
2379
  }
2380
+ /**
2381
+ * Non-blocking drain of up to `maxEvents` due workflow events. Intended
2382
+ * for hosts that sweep many matcher instances periodically rather than
2383
+ * running `startOrchestrator()`'s dedicated blocking loop per instance.
2384
+ */
2385
+ async processWorkflowEvents(maxEvents) {
2386
+ await this.readyPromise;
2387
+ return this.workflow.processWorkflowEvents(maxEvents);
2388
+ }
2205
2389
  /**
2206
2390
  * Publish a workflow event to the Redis Stream.
2207
2391
  */
@@ -2264,21 +2448,52 @@ class AssignmentMatcher {
2264
2448
  await this.readyPromise;
2265
2449
  return this.workflow.getWorkflowMetrics();
2266
2450
  }
2267
- async processExpiredMatches() {
2451
+ /**
2452
+ * Requeue pending assignments whose response deadline elapsed, applying
2453
+ * each assignment's `EscalationPolicy` when it has one.
2454
+ *
2455
+ * Assignments without a policy take exactly the path they always did: the
2456
+ * owner loses the assignment, it returns to the open pool, and they may
2457
+ * win it again. With a policy the non-responder can be blocked, the
2458
+ * priority can climb, the tier tags can advance, and an exhausted ladder
2459
+ * can park the assignment instead of recirculating it forever.
2460
+ *
2461
+ * The wait clock (`assignmentsQueuedAt`) always survives: the requeue goes
2462
+ * through `addAssignment()`, whose `NX` keeps the original first-enqueue
2463
+ * time, so `oldestWaitingMs` measures the work item and not the tier.
2464
+ */
2465
+ async processResponseDeadlines() {
2268
2466
  await this.readyPromise;
2269
2467
  const now = Date.now();
2270
2468
  const expiredIds = await this.redisClient.zRangeByScore(this.pendingAssignmentsExpiryKey, '-inf', now);
2469
+ let escalations = 0;
2470
+ let parked = 0;
2271
2471
  for (const id of expiredIds) {
2272
2472
  const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
2273
2473
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
2474
+ const assignment = json ? JSON.parse(json) : null;
2475
+ const policy = assignment ? (0, policy_1.normalizeEscalationPolicy)(assignment.escalation) : null;
2476
+ const decision = assignment && policy ? (0, policy_1.escalateAssignment)(assignment, policy) : null;
2274
2477
  const multi = this.redisClient.multi();
2275
2478
  if (owner) {
2276
2479
  multi.sRem(this.keys.userAssignments(owner), `assignment:${id}`);
2480
+ // A blocking policy treats "never answered" as a soft rejection,
2481
+ // reusing the same rejected set an explicit reject writes to —
2482
+ // so the requeue cannot land back on the non-responder, and
2483
+ // decision traces already explain it as `rejectedPreviously`.
2484
+ if (decision?.blockPreviousOwner)
2485
+ multi.sAdd(this.keys.userRejected(owner), id);
2277
2486
  }
2278
2487
  multi.hDel(this.pendingAssignmentsKey, id);
2279
2488
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
2280
2489
  multi.hDel(this.assignmentOwnerKey, id);
2281
2490
  await multi.exec();
2491
+ this.emitAssignmentLifecycle({
2492
+ kind: 'expired',
2493
+ taskId: id,
2494
+ workerId: owner ?? null,
2495
+ expiredAt: now,
2496
+ });
2282
2497
  if (this.enableLearning) {
2283
2498
  await this.learning.applyOutcome(id, 'expire');
2284
2499
  }
@@ -2292,12 +2507,173 @@ class AssignmentMatcher {
2292
2507
  timestamp: now,
2293
2508
  });
2294
2509
  }
2295
- if (json) {
2296
- await this.addAssignment(JSON.parse(json));
2510
+ if (!assignment)
2511
+ continue;
2512
+ if (decision && decision.exhausted) {
2513
+ this.emitAssignmentLifecycle({
2514
+ kind: 'escalationExhausted',
2515
+ taskId: id,
2516
+ level: decision.level,
2517
+ parked: decision.onExhausted === 'park',
2518
+ at: now,
2519
+ });
2520
+ if (decision.onExhausted === 'park') {
2521
+ // Held out of matching entirely: no requeue, and the wait
2522
+ // clock is cleared so a parked item stops inflating
2523
+ // oldestWaitingMs for work that is still winnable.
2524
+ await this.redisClient
2525
+ .multi()
2526
+ .hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
2527
+ .zRem(this.keys.assignmentsQueuedAt(), id)
2528
+ .exec();
2529
+ parked++;
2530
+ continue;
2531
+ }
2532
+ await this.addAssignment(assignment);
2533
+ continue;
2534
+ }
2535
+ if (decision) {
2536
+ await this.addAssignment(decision.assignment);
2537
+ escalations++;
2538
+ this.emitAssignmentLifecycle({
2539
+ kind: 'escalated',
2540
+ taskId: id,
2541
+ fromWorkerId: owner ?? null,
2542
+ level: decision.level,
2543
+ blockedPreviousOwner: decision.blockPreviousOwner && Boolean(owner),
2544
+ reason: 'no-response',
2545
+ escalatedAt: now,
2546
+ });
2547
+ continue;
2297
2548
  }
2549
+ await this.addAssignment(assignment);
2298
2550
  }
2299
- return expiredIds.length;
2551
+ return { expired: expiredIds.length, escalations, parked };
2552
+ }
2553
+ /**
2554
+ * Backwards-compatible alias of `processResponseDeadlines()` returning
2555
+ * only the number of expired assignments.
2556
+ */
2557
+ async processExpiredMatches() {
2558
+ const { expired } = await this.processResponseDeadlines();
2559
+ return expired;
2300
2560
  }
2561
+ /**
2562
+ * Assignments held out of matching because their escalation ladder was
2563
+ * exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
2564
+ */
2565
+ async getParkedAssignments() {
2566
+ await this.readyPromise;
2567
+ const all = await this.redisClient.hGetAll(this.keys.parkedAssignments());
2568
+ return Object.values(all).map((json) => JSON.parse(json));
2569
+ }
2570
+ /**
2571
+ * Return a parked assignment to the queue, optionally resetting its
2572
+ * escalation level so the ladder can run again from the top.
2573
+ *
2574
+ * @returns false when the id was not parked
2575
+ */
2576
+ async unparkAssignment(id, opts) {
2577
+ await this.readyPromise;
2578
+ const json = await this.redisClient.hGet(this.keys.parkedAssignments(), id);
2579
+ if (!json)
2580
+ return false;
2581
+ const assignment = JSON.parse(json);
2582
+ if (opts?.resetEscalation)
2583
+ delete assignment._escalationLevel;
2584
+ await this.redisClient.hDel(this.keys.parkedAssignments(), id);
2585
+ await this.addAssignment(assignment);
2586
+ return true;
2587
+ }
2588
+ /** Current escalation level of an assignment (0 = never escalated). */
2589
+ async getEscalationLevel(id) {
2590
+ await this.readyPromise;
2591
+ const assignment = await this.getAssignment(id);
2592
+ return assignment ? (0, policy_1.escalationLevelOf)(assignment) : 0;
2593
+ }
2594
+ /**
2595
+ * Run every enabled maintenance sweep once: response deadlines and
2596
+ * escalations, workflow step timeouts, and idle-user release.
2597
+ *
2598
+ * Deadlines are not self-firing — something has to sweep them. Hosts that
2599
+ * already own a tick (a multi-tenant worker, a serverless schedule) should
2600
+ * call this instead of holding a timer per matcher; everyone else should
2601
+ * call `startMaintenance()` once and forget about it.
2602
+ */
2603
+ async runMaintenanceOnce(options) {
2604
+ await this.readyPromise;
2605
+ const startedAt = Date.now();
2606
+ const opts = this.resolveMaintenanceOptions(options);
2607
+ let expiredMatches = 0;
2608
+ let escalations = 0;
2609
+ let parked = 0;
2610
+ let expiredSteps = 0;
2611
+ let releasedIdleUsers = 0;
2612
+ if (opts.responseDeadlines) {
2613
+ const result = await this.processResponseDeadlines();
2614
+ expiredMatches = result.expired;
2615
+ escalations = result.escalations;
2616
+ parked = result.parked;
2617
+ }
2618
+ if (opts.workflowStepTimeouts && this.enableWorkflows) {
2619
+ expiredSteps = await this.processExpiredWorkflowSteps();
2620
+ }
2621
+ if (opts.idleUsers && this.idleUserTimeoutMs !== null) {
2622
+ releasedIdleUsers = (await this.processIdleUsers()).length;
2623
+ }
2624
+ return {
2625
+ expiredMatches,
2626
+ escalations,
2627
+ parked,
2628
+ expiredSteps,
2629
+ releasedIdleUsers,
2630
+ tookMs: Date.now() - startedAt,
2631
+ };
2632
+ }
2633
+ /**
2634
+ * Start the periodic maintenance tick. Idempotent; a second call with
2635
+ * different options replaces the first.
2636
+ *
2637
+ * @param options.intervalMs how often to sweep (default 5000)
2638
+ */
2639
+ startMaintenance(options) {
2640
+ this.stopMaintenance();
2641
+ this.maintenanceOptions = this.resolveMaintenanceOptions(options);
2642
+ const intervalMs = options?.intervalMs ?? 5000;
2643
+ this.maintenanceInterval = setInterval(() => {
2644
+ // Skip a tick rather than pile up overlapping sweeps when a pass
2645
+ // takes longer than the interval.
2646
+ if (this.maintenanceRunning)
2647
+ return;
2648
+ this.maintenanceRunning = true;
2649
+ this.runMaintenanceOnce(this.maintenanceOptions ?? undefined)
2650
+ .catch((err) => console.error('Maintenance tick failed:', err))
2651
+ .finally(() => {
2652
+ this.maintenanceRunning = false;
2653
+ });
2654
+ }, intervalMs);
2655
+ this.maintenanceInterval.unref?.();
2656
+ }
2657
+ /** Stop the periodic maintenance tick. Safe to call when not started. */
2658
+ stopMaintenance() {
2659
+ if (this.maintenanceInterval) {
2660
+ clearInterval(this.maintenanceInterval);
2661
+ this.maintenanceInterval = null;
2662
+ }
2663
+ this.maintenanceOptions = null;
2664
+ }
2665
+ /** Whether the maintenance tick is currently running. */
2666
+ isMaintenanceRunning() {
2667
+ return this.maintenanceInterval !== null;
2668
+ }
2669
+ resolveMaintenanceOptions(options) {
2670
+ return {
2671
+ responseDeadlines: options?.responseDeadlines ?? true,
2672
+ workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
2673
+ idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
2674
+ };
2675
+ }
2676
+ /** @deprecated Use `startMaintenance()`, which also sweeps workflow step timeouts. */
2301
2677
  startAutoReleaseInterval(intervalMs = 10000) {
2302
2678
  if (this.autoReleaseInterval)
2303
2679
  return;
@@ -2355,7 +2731,7 @@ class AssignmentMatcher {
2355
2731
  const pendingCount = await this.redisClient.sCard(this.keys.userAssignments(userId));
2356
2732
  if (pendingCount === 0)
2357
2733
  continue;
2358
- await this.releaseUserPendingAssignments(userId);
2734
+ await this.releaseUserPendingAssignments(userId, 'idle');
2359
2735
  await this.removeUser(userId);
2360
2736
  removed.push(userId);
2361
2737
  }
@@ -2364,9 +2740,10 @@ class AssignmentMatcher {
2364
2740
  /**
2365
2741
  * Requeue all pending assignments currently held by a user.
2366
2742
  */
2367
- async releaseUserPendingAssignments(userId) {
2743
+ async releaseUserPendingAssignments(userId, reason = 'operator') {
2368
2744
  const members = await this.redisClient.sMembers(this.keys.userAssignments(userId));
2369
2745
  const now = Date.now();
2746
+ const released = [];
2370
2747
  for (const member of members) {
2371
2748
  const id = member.split(':')[1];
2372
2749
  const json = await this.redisClient.hGet(this.pendingAssignmentsKey, id);
@@ -2376,6 +2753,13 @@ class AssignmentMatcher {
2376
2753
  multi.zRem(this.pendingAssignmentsExpiryKey, id);
2377
2754
  multi.hDel(this.assignmentOwnerKey, id);
2378
2755
  await multi.exec();
2756
+ this.emitAssignmentLifecycle({
2757
+ kind: 'released',
2758
+ taskId: id,
2759
+ workerId: userId,
2760
+ reason,
2761
+ releasedAt: now,
2762
+ });
2379
2763
  if (this.enableLearning) {
2380
2764
  await this.learning.applyOutcome(id, 'expire');
2381
2765
  }
@@ -2391,7 +2775,9 @@ class AssignmentMatcher {
2391
2775
  if (json) {
2392
2776
  await this.addAssignment(JSON.parse(json));
2393
2777
  }
2778
+ released.push(id);
2394
2779
  }
2780
+ return released;
2395
2781
  }
2396
2782
  startIdleUserInterval(intervalMs = 10000) {
2397
2783
  if (this.idleUserInterval)
@@ -19,12 +19,17 @@ export interface AssignmentCounts {
19
19
  queued: number;
20
20
  pending: number;
21
21
  accepted: number;
22
+ /** Assignments held out of matching by an exhausted escalation ladder */
23
+ parked: number;
24
+ /** queued + pending + accepted — parked items are counted separately */
22
25
  total: number;
23
26
  }
24
27
  export interface AssignmentKeys {
25
28
  queued: string;
26
29
  pending: string;
27
30
  accepted: string;
31
+ /** Optional parked store; omitted by callers that predate escalation policies */
32
+ parked?: string;
28
33
  }
29
34
  /**
30
35
  * Get all assignments from all stores (queued, pending, accepted)
@@ -1 +1 @@
1
- {"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../src/queries/pagination.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAEjE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,gBAAgB,GAAG,KAAK,CAAC;IAClC,YAAY,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC7B,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,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AM,CAAA;CAAE,CAAC,GAAG,IAAI,CAAC,CAmCrD;AAED;;GAEG;AACH,wBAAsB,wBAAwB,CAC1C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,GAAG,EAAE,MAAM,EAAE,GACd,OAAO,CAAC,UAAU,EAAE,CAAC,CA+BvB;AAED;;GAEG;AACH,wBAAsB,iCAAiC,CACnD,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC5B,OAAO,CAAC,gBAAgB,CAAC,CA2H3B"}
@@ -18,15 +18,17 @@ exports.getAllAssignmentsFromStores = getAllAssignmentsFromStores;
18
18
  * Get assignment counts by status
19
19
  */
20
20
  async function getAssignmentCountsFromStores(redisClient, keys) {
21
- const [queued, pending, accepted] = await Promise.all([
21
+ const [queued, pending, accepted, parked] = await Promise.all([
22
22
  redisClient.hLen(keys.queued),
23
23
  redisClient.hLen(keys.pending),
24
24
  redisClient.hLen(keys.accepted),
25
+ keys.parked ? redisClient.hLen(keys.parked) : Promise.resolve(0),
25
26
  ]);
26
27
  return {
27
28
  queued,
28
29
  pending,
29
30
  accepted,
31
+ parked,
30
32
  total: queued + pending + accepted,
31
33
  };
32
34
  }
@@ -55,6 +57,16 @@ async function getAssignmentById(redisClient, keys, id) {
55
57
  assignment._status = 'accepted';
56
58
  return assignment;
57
59
  }
60
+ // Parked items are out of the matching universe but must never read as
61
+ // "not found" — that would make an exhausted escalation look like data loss.
62
+ if (keys.parked) {
63
+ const parked = await redisClient.hGet(keys.parked, id);
64
+ if (parked) {
65
+ const assignment = JSON.parse(parked);
66
+ assignment._status = 'parked';
67
+ return assignment;
68
+ }
69
+ }
58
70
  return null;
59
71
  }
60
72
  exports.getAssignmentById = getAssignmentById;