assignment-user-matcher 1.16.1 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +290 -8
- package/dist/escalation/policy.d.ts +11 -0
- package/dist/escalation/policy.d.ts.map +1 -1
- package/dist/escalation/policy.js +22 -1
- package/dist/forecasting/backtest.d.ts +52 -0
- package/dist/forecasting/backtest.d.ts.map +1 -0
- package/dist/forecasting/backtest.js +195 -0
- package/dist/forecasting/calendar.d.ts +44 -0
- package/dist/forecasting/calendar.d.ts.map +1 -0
- package/dist/forecasting/calendar.js +85 -0
- package/dist/forecasting/cover.d.ts +69 -0
- package/dist/forecasting/cover.d.ts.map +1 -0
- package/dist/forecasting/cover.js +103 -0
- package/dist/forecasting/days.d.ts +17 -0
- package/dist/forecasting/days.d.ts.map +1 -0
- package/dist/forecasting/days.js +35 -0
- package/dist/forecasting/distributions.d.ts +31 -0
- package/dist/forecasting/distributions.d.ts.map +1 -0
- package/dist/forecasting/distributions.js +154 -0
- package/dist/forecasting/effects.d.ts +88 -0
- package/dist/forecasting/effects.d.ts.map +1 -0
- package/dist/forecasting/effects.js +303 -0
- package/dist/forecasting/erlang.d.ts +31 -0
- package/dist/forecasting/erlang.d.ts.map +1 -0
- package/dist/forecasting/erlang.js +86 -0
- package/dist/forecasting/forecast.d.ts +7 -0
- package/dist/forecasting/forecast.d.ts.map +1 -0
- package/dist/forecasting/forecast.js +221 -0
- package/dist/forecasting/index.d.ts +18 -0
- package/dist/forecasting/index.d.ts.map +1 -0
- package/dist/forecasting/index.js +54 -0
- package/dist/forecasting/model.d.ts +145 -0
- package/dist/forecasting/model.d.ts.map +1 -0
- package/dist/forecasting/model.js +583 -0
- package/dist/forecasting/nowcast.d.ts +26 -0
- package/dist/forecasting/nowcast.d.ts.map +1 -0
- package/dist/forecasting/nowcast.js +92 -0
- package/dist/forecasting/simulation.d.ts +91 -0
- package/dist/forecasting/simulation.d.ts.map +1 -0
- package/dist/forecasting/simulation.js +478 -0
- package/dist/forecasting/spikes.d.ts +6 -0
- package/dist/forecasting/spikes.d.ts.map +1 -0
- package/dist/forecasting/spikes.js +73 -0
- package/dist/forecasting/staffing.d.ts +64 -0
- package/dist/forecasting/staffing.d.ts.map +1 -0
- package/dist/forecasting/staffing.js +765 -0
- package/dist/forecasting/stats.d.ts +11 -0
- package/dist/forecasting/stats.d.ts.map +1 -0
- package/dist/forecasting/stats.js +45 -0
- package/dist/forecasting/types.d.ts +299 -0
- package/dist/forecasting/types.d.ts.map +1 -0
- package/dist/forecasting/types.js +8 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/learning/auto-weights.d.ts +1 -5
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +0 -3
- package/dist/lua/book-slot.lua +84 -0
- package/dist/lua/claim-queued.lua +47 -0
- package/dist/managers/DecisionTraceManager.d.ts +15 -0
- package/dist/managers/DecisionTraceManager.d.ts.map +1 -1
- package/dist/managers/DecisionTraceManager.js +117 -11
- package/dist/managers/LearningManager.d.ts +12 -0
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +21 -7
- package/dist/managers/ReliabilityManager.d.ts +1 -2
- package/dist/managers/ReliabilityManager.d.ts.map +1 -1
- package/dist/managers/ReliabilityManager.js +1 -1
- package/dist/managers/TelemetryManager.d.ts.map +1 -1
- package/dist/managers/TelemetryManager.js +9 -3
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +3 -4
- package/dist/matcher.class.d.ts +319 -4
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +1428 -102
- package/dist/queries/lane-stats.d.ts +51 -0
- package/dist/queries/lane-stats.d.ts.map +1 -0
- package/dist/queries/lane-stats.js +78 -0
- package/dist/schedule/recurrence.d.ts +11 -0
- package/dist/schedule/recurrence.d.ts.map +1 -1
- package/dist/schedule/recurrence.js +19 -2
- package/dist/schedule/slot.d.ts +60 -0
- package/dist/schedule/slot.d.ts.map +1 -0
- package/dist/schedule/slot.js +86 -0
- package/dist/scheduling/constraints/availability.d.ts +2 -14
- package/dist/scheduling/constraints/availability.d.ts.map +1 -1
- package/dist/scheduling/constraints/availability.js +14 -15
- package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -1
- package/dist/scheduling/constraints/employee-scope.js +10 -2
- package/dist/scheduling/constraints/support.d.ts +4 -8
- package/dist/scheduling/constraints/support.d.ts.map +1 -1
- package/dist/scheduling/constraints/support.js +23 -2
- package/dist/scheduling/constraints/weekly-rest.d.ts +28 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/weekly-rest.js +108 -21
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +33 -4
- package/dist/scheduling/engine/objective.d.ts +0 -1
- package/dist/scheduling/engine/objective.d.ts.map +1 -1
- package/dist/scheduling/engine/objective.js +45 -3
- package/dist/scheduling/engine/search.d.ts +4 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -1
- package/dist/scheduling/engine/search.js +2 -1
- package/dist/scheduling/engine/state.d.ts +14 -0
- package/dist/scheduling/engine/state.d.ts.map +1 -1
- package/dist/scheduling/engine/state.js +7 -0
- package/dist/scheduling/engine/timeline.d.ts +9 -1
- package/dist/scheduling/engine/timeline.d.ts.map +1 -1
- package/dist/scheduling/engine/timeline.js +52 -27
- package/dist/scheduling/engine/verdicts.d.ts +40 -1
- package/dist/scheduling/engine/verdicts.d.ts.map +1 -1
- package/dist/scheduling/engine/verdicts.js +177 -17
- package/dist/scheduling/index.d.ts +3 -2
- package/dist/scheduling/index.d.ts.map +1 -1
- package/dist/scheduling/index.js +7 -1
- package/dist/scheduling/model.d.ts +2 -3
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +30 -12
- package/dist/scheduling/operations.d.ts +174 -2
- package/dist/scheduling/operations.d.ts.map +1 -1
- package/dist/scheduling/operations.js +513 -15
- package/dist/scheduling/preference-report.d.ts +15 -0
- package/dist/scheduling/preference-report.d.ts.map +1 -0
- package/dist/scheduling/preference-report.js +111 -0
- package/dist/scheduling/preferences.d.ts +30 -0
- package/dist/scheduling/preferences.d.ts.map +1 -0
- package/dist/scheduling/preferences.js +85 -0
- package/dist/scheduling/resilience.d.ts +46 -0
- package/dist/scheduling/resilience.d.ts.map +1 -0
- package/dist/scheduling/resilience.js +45 -0
- package/dist/scheduling/scheduler.class.d.ts +12 -1
- package/dist/scheduling/scheduler.class.d.ts.map +1 -1
- package/dist/scheduling/scheduler.class.js +28 -4
- package/dist/scheduling/time.d.ts +28 -6
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +59 -17
- package/dist/scheduling/types.d.ts +107 -1
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/scoring/fair-arbitration.d.ts.map +1 -1
- package/dist/scoring/fair-arbitration.js +2 -1
- package/dist/tracing/decision-trace.d.ts +5 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -1
- package/dist/tracing/decision-trace.js +3 -0
- package/dist/types/matcher.d.ts +369 -2
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/updates/assignment-update.d.ts +93 -0
- package/dist/updates/assignment-update.d.ts.map +1 -0
- package/dist/updates/assignment-update.js +91 -0
- package/dist/utils/keys.d.ts +10 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +43 -0
- package/package.json +15 -2
package/dist/matcher.class.js
CHANGED
|
@@ -7,12 +7,15 @@ const cidr_1 = require("./utils/cidr");
|
|
|
7
7
|
const geo_1 = require("./utils/geo");
|
|
8
8
|
const keys_1 = require("./utils/keys");
|
|
9
9
|
const pagination_1 = require("./queries/pagination");
|
|
10
|
+
const lane_stats_1 = require("./queries/lane-stats");
|
|
10
11
|
const users_1 = require("./queries/users");
|
|
12
|
+
const assignment_update_1 = require("./updates/assignment-update");
|
|
11
13
|
const match_score_1 = require("./scoring/match-score");
|
|
12
14
|
const fair_arbitration_1 = require("./scoring/fair-arbitration");
|
|
13
15
|
const policy_1 = require("./escalation/policy");
|
|
14
16
|
const policy_2 = require("./sla/policy");
|
|
15
17
|
const policy_3 = require("./schedule/policy");
|
|
18
|
+
const slot_1 = require("./schedule/slot");
|
|
16
19
|
const recurrence_1 = require("./schedule/recurrence");
|
|
17
20
|
const assignment_lint_1 = require("./validation/assignment-lint");
|
|
18
21
|
const decision_trace_1 = require("./tracing/decision-trace");
|
|
@@ -40,6 +43,20 @@ function loadLuaScript(filename) {
|
|
|
40
43
|
}
|
|
41
44
|
// Lua script for atomic workflow transitions
|
|
42
45
|
const WORKFLOW_TRANSITION_LUA = loadLuaScript('workflow-transition.lua');
|
|
46
|
+
// Lua script for the atomic slot reservation: the clash probe and the write
|
|
47
|
+
// are one decision, or two sweeps both book somebody's 14:00.
|
|
48
|
+
const BOOK_SLOT_LUA = loadLuaScript('book-slot.lua');
|
|
49
|
+
// Lua script for the claim: the queued -> pending move, its deadline, its owner
|
|
50
|
+
// and its learning context, in the one step that decides who won the work.
|
|
51
|
+
const CLAIM_QUEUED_LUA = loadLuaScript('claim-queued.lua');
|
|
52
|
+
/**
|
|
53
|
+
* The longest appointment allowed by default, and therefore how far back the
|
|
54
|
+
* overlap probe reaches. A booking that started more than this before the one
|
|
55
|
+
* being placed cannot still be running.
|
|
56
|
+
*/
|
|
57
|
+
const DEFAULT_MAX_SLOT_SPAN_MS = 24 * 60 * 60 * 1000;
|
|
58
|
+
/** How long the booking sweep waits before re-examining a slot it could not fill. */
|
|
59
|
+
const DEFAULT_SLOT_BOOKING_RETRY_MS = 15 * 60 * 1000;
|
|
43
60
|
// Retention purges are capped per maintenance pass so enabling retention on a
|
|
44
61
|
// deployment with a large historical completed store drains it across ticks
|
|
45
62
|
// instead of one deletion storm.
|
|
@@ -48,6 +65,8 @@ class AssignmentMatcher {
|
|
|
48
65
|
constructor(redisClient, options) {
|
|
49
66
|
this.redisClient = redisClient;
|
|
50
67
|
this.luaScriptSha = null;
|
|
68
|
+
this.bookSlotSha = null;
|
|
69
|
+
this.slotAvailability = null;
|
|
51
70
|
this.autoRoutingWeightsSyncInterval = null;
|
|
52
71
|
// ============================================================================
|
|
53
72
|
// Maintenance — the periodic sweeps that make deadlines actually fire
|
|
@@ -67,7 +86,14 @@ class AssignmentMatcher {
|
|
|
67
86
|
this.assignmentsRefKey = this.keys.assignmentsRef();
|
|
68
87
|
this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
|
|
69
88
|
this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
|
|
89
|
+
this.offerCooldownMs =
|
|
90
|
+
Number.isFinite(Number(options?.offerCooldownMs)) && Number(options?.offerCooldownMs) > 0
|
|
91
|
+
? Number(options?.offerCooldownMs)
|
|
92
|
+
: 0;
|
|
70
93
|
this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
|
|
94
|
+
this.slotAvailability = options?.slotAvailability ?? null;
|
|
95
|
+
this.maxSlotSpanMs = options?.maxSlotSpanMs ?? DEFAULT_MAX_SLOT_SPAN_MS;
|
|
96
|
+
this.slotBookingRetryMs = options?.slotBookingRetryMs ?? DEFAULT_SLOT_BOOKING_RETRY_MS;
|
|
71
97
|
const completedRetentionMs = options?.completedAssignmentsRetentionMs;
|
|
72
98
|
this.completedAssignmentsRetentionMs =
|
|
73
99
|
completedRetentionMs !== undefined && Number.isFinite(completedRetentionMs) && completedRetentionMs > 0
|
|
@@ -83,6 +109,9 @@ class AssignmentMatcher {
|
|
|
83
109
|
this.scheduledAssignmentsKey = this.keys.scheduledAssignments();
|
|
84
110
|
this.scheduledActivateAtKey = this.keys.scheduledActivateAt();
|
|
85
111
|
this.scheduleNotAfterKey = this.keys.scheduleNotAfter();
|
|
112
|
+
this.slotBookingsKey = this.keys.slotBookings();
|
|
113
|
+
this.bookingSpansKey = this.keys.bookingSpans();
|
|
114
|
+
this.slotBookingDueAtKey = this.keys.slotBookingDueAt();
|
|
86
115
|
this.recurringAssignmentsKey = this.keys.recurringAssignments();
|
|
87
116
|
this.recurringDueAtKey = this.keys.recurringDueAt();
|
|
88
117
|
this.completedAssignmentsKey = this.keys.completedAssignments();
|
|
@@ -201,7 +230,7 @@ class AssignmentMatcher {
|
|
|
201
230
|
try {
|
|
202
231
|
this.onAssignmentLifecycle(event);
|
|
203
232
|
}
|
|
204
|
-
catch
|
|
233
|
+
catch {
|
|
205
234
|
// Best-effort hook: do not propagate.
|
|
206
235
|
}
|
|
207
236
|
}
|
|
@@ -332,6 +361,7 @@ class AssignmentMatcher {
|
|
|
332
361
|
// The source rides along so a NOSCRIPT after a Redis restart can
|
|
333
362
|
// be answered with a re-load instead of bricking every transition.
|
|
334
363
|
this.workflow.setLuaScriptSha(this.luaScriptSha, WORKFLOW_TRANSITION_LUA);
|
|
364
|
+
this.bookSlotSha = await this.redisClient.scriptLoad(BOOK_SLOT_LUA);
|
|
335
365
|
}
|
|
336
366
|
catch (err) {
|
|
337
367
|
console.error('Failed to load Lua scripts:', err);
|
|
@@ -693,15 +723,17 @@ class AssignmentMatcher {
|
|
|
693
723
|
}
|
|
694
724
|
/** One user's full eligibility/score evaluation for explainMatch(). */
|
|
695
725
|
async explainCandidate(user, assignment, assignmentId, tagsCsv, basePriority, ownerId, modelWeights) {
|
|
696
|
-
const [isRejected, backlog, isPaused] = await Promise.all([
|
|
726
|
+
const [isRejected, backlog, isPaused, cooldownUntil] = await Promise.all([
|
|
697
727
|
this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId),
|
|
698
728
|
this.redisClient.sCard(this.keys.userAssignments(user.id)),
|
|
699
729
|
this.redisClient.sIsMember(this.keys.pausedUsers(), user.id),
|
|
730
|
+
this.redisClient.zScore(this.keys.userOfferCooldown(user.id), assignmentId),
|
|
700
731
|
]);
|
|
701
732
|
return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
|
|
702
733
|
assignmentId,
|
|
703
734
|
ownerId,
|
|
704
735
|
isRejected: Boolean(isRejected),
|
|
736
|
+
cooldownUntil: cooldownUntil === null ? null : Number(cooldownUntil),
|
|
705
737
|
backlog,
|
|
706
738
|
isPaused: Boolean(isPaused),
|
|
707
739
|
});
|
|
@@ -726,6 +758,11 @@ class AssignmentMatcher {
|
|
|
726
758
|
reasons.push({ kind: 'rejectedPreviously' });
|
|
727
759
|
eligible = false;
|
|
728
760
|
}
|
|
761
|
+
const cooldownUntil = opts.cooldownUntil ?? null;
|
|
762
|
+
if (cooldownUntil !== null && cooldownUntil > Date.now()) {
|
|
763
|
+
reasons.push({ kind: 'offerCooldown', until: cooldownUntil });
|
|
764
|
+
eligible = false;
|
|
765
|
+
}
|
|
729
766
|
if (isPaused) {
|
|
730
767
|
reasons.push({ kind: 'paused' });
|
|
731
768
|
eligible = false;
|
|
@@ -972,11 +1009,15 @@ class AssignmentMatcher {
|
|
|
972
1009
|
const basePriority = Number(storedPriority ?? assignment.priority) || 0;
|
|
973
1010
|
const tagsCsv = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])].join(',');
|
|
974
1011
|
const evaluations = await Promise.all(users.map(async (user) => {
|
|
975
|
-
const isRejected = await
|
|
1012
|
+
const [isRejected, cooldownUntil] = await Promise.all([
|
|
1013
|
+
this.redisClient.sIsMember(this.keys.userRejected(user.id), id),
|
|
1014
|
+
this.redisClient.zScore(this.keys.userOfferCooldown(user.id), id),
|
|
1015
|
+
]);
|
|
976
1016
|
return this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
|
|
977
1017
|
assignmentId: id,
|
|
978
1018
|
ownerId: null,
|
|
979
1019
|
isRejected: Boolean(isRejected),
|
|
1020
|
+
cooldownUntil: cooldownUntil === null ? null : Number(cooldownUntil),
|
|
980
1021
|
backlog: backlogs.get(user.id) ?? 0,
|
|
981
1022
|
isPaused: paused.has(user.id),
|
|
982
1023
|
});
|
|
@@ -1057,14 +1098,20 @@ class AssignmentMatcher {
|
|
|
1057
1098
|
async getTraceUserContexts(users) {
|
|
1058
1099
|
const paused = new Set(await this.redisClient.sMembers(this.keys.pausedUsers()));
|
|
1059
1100
|
return Promise.all(users.map(async (user) => {
|
|
1060
|
-
const [rejected, vetoed] = await Promise.all([
|
|
1101
|
+
const [rejected, vetoed, resting] = await Promise.all([
|
|
1061
1102
|
this.redisClient.sMembers(this.keys.userRejected(user.id)),
|
|
1062
1103
|
this.redisClient.sMembers(this.keys.userVetoed(user.id)),
|
|
1104
|
+
// Only the entries still in force: an elapsed rest is not a
|
|
1105
|
+
// reason anybody was struck out of this pass. Exclusive at
|
|
1106
|
+
// `now`, the mirror of the prune in discovery, which drops
|
|
1107
|
+
// everything up to and including it.
|
|
1108
|
+
this.redisClient.zRangeByScoreWithScores(this.keys.userOfferCooldown(user.id), `(${Date.now()}`, '+inf'),
|
|
1063
1109
|
]);
|
|
1064
1110
|
return {
|
|
1065
1111
|
user,
|
|
1066
1112
|
rejected: new Set(rejected),
|
|
1067
1113
|
vetoed: new Set(vetoed),
|
|
1114
|
+
cooldown: new Map(resting.map((e) => [e.value, Number(e.score)])),
|
|
1068
1115
|
paused: paused.has(user.id),
|
|
1069
1116
|
};
|
|
1070
1117
|
}));
|
|
@@ -1388,21 +1435,48 @@ class AssignmentMatcher {
|
|
|
1388
1435
|
// The wait clock and SLA freshness TTL therefore anchor at
|
|
1389
1436
|
// activation, not creation.
|
|
1390
1437
|
const schedulePolicy = (0, policy_3.normalizeSchedulePolicy)(assignment.schedule);
|
|
1391
|
-
|
|
1438
|
+
const slot = (0, slot_1.normalizeSlot)(assignment.slot);
|
|
1439
|
+
if (slot && slot.durationMs > this.maxSlotSpanMs) {
|
|
1440
|
+
// The overlap probe only reaches back `maxSlotSpanMs`; a longer
|
|
1441
|
+
// appointment would silently slip past it, so it is refused here
|
|
1442
|
+
// rather than booked and then double-booked.
|
|
1443
|
+
throw new Error(`Assignment slot is longer than maxSlotSpanMs (${slot.durationMs} > ${this.maxSlotSpanMs}): ${assignment.id}`);
|
|
1444
|
+
}
|
|
1445
|
+
const now = Date.now();
|
|
1446
|
+
// A slot is a hold in its own right: the work happens at `startAt`, so
|
|
1447
|
+
// it has no business in the queue before then. When the assignment
|
|
1448
|
+
// also declares an offer window, the later of the two wins — an
|
|
1449
|
+
// explicit `notBefore` can delay an appointment, never bring it
|
|
1450
|
+
// forward.
|
|
1451
|
+
const scheduleHold = schedulePolicy && (0, policy_3.isHeld)(schedulePolicy, now) ? schedulePolicy.notBefore : null;
|
|
1452
|
+
const slotHold = slot && slot.startAt > now ? slot.startAt : null;
|
|
1453
|
+
const activateAt = scheduleHold !== null || slotHold !== null ? Math.max(scheduleHold ?? 0, slotHold ?? 0) : null;
|
|
1454
|
+
if (activateAt !== null) {
|
|
1392
1455
|
const multi = this.redisClient
|
|
1393
1456
|
.multi()
|
|
1394
1457
|
.hSet(this.scheduledAssignmentsKey, assignment.id, JSON.stringify(assignment))
|
|
1395
|
-
.zAdd(this.scheduledActivateAtKey, { score:
|
|
1396
|
-
if (schedulePolicy
|
|
1458
|
+
.zAdd(this.scheduledActivateAtKey, { score: activateAt, value: assignment.id });
|
|
1459
|
+
if (schedulePolicy?.notAfter !== undefined) {
|
|
1397
1460
|
multi.zAdd(this.scheduleNotAfterKey, { score: schedulePolicy.notAfter, value: assignment.id });
|
|
1398
1461
|
}
|
|
1462
|
+
if (slot) {
|
|
1463
|
+
// The sweep may reserve somebody from here on. Clamped to
|
|
1464
|
+
// `now` so a slot created inside its own book-ahead window is
|
|
1465
|
+
// picked up by the very next pass instead of waiting for a
|
|
1466
|
+
// moment that is already behind us.
|
|
1467
|
+
multi.zAdd(this.slotBookingDueAtKey, {
|
|
1468
|
+
score: Math.max(now, (0, slot_1.bookingOpensAt)(slot)),
|
|
1469
|
+
value: assignment.id,
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1399
1472
|
await multi.exec();
|
|
1400
1473
|
return assignment;
|
|
1401
1474
|
}
|
|
1402
1475
|
return this.enqueueAssignment(assignment, schedulePolicy);
|
|
1403
1476
|
}
|
|
1404
1477
|
async enqueueAssignment(assignment, schedulePolicy) {
|
|
1405
|
-
|
|
1478
|
+
const { id, tags, latitude, longitude } = assignment;
|
|
1479
|
+
let { priority } = assignment;
|
|
1406
1480
|
if (!priority)
|
|
1407
1481
|
priority = await this.calculatePriority(assignment);
|
|
1408
1482
|
// First-enqueue clock for the freshness TTL: NX semantics via the
|
|
@@ -1438,18 +1512,19 @@ class AssignmentMatcher {
|
|
|
1438
1512
|
if (slaExpiry !== null) {
|
|
1439
1513
|
multi.zAdd(this.assignmentsSlaExpiryKey, { score: slaExpiry, value: id });
|
|
1440
1514
|
}
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1515
|
+
// The offer deadline is absolute, so requeues re-add the same score —
|
|
1516
|
+
// the notAfter clock is never extended.
|
|
1517
|
+
if (schedulePolicy?.notAfter !== undefined) {
|
|
1518
|
+
multi.zAdd(this.scheduleNotAfterKey, { score: schedulePolicy.notAfter, value: id });
|
|
1519
|
+
}
|
|
1520
|
+
// Atomic hand-off out of the scheduled store (no-ops when the
|
|
1521
|
+
// assignment was never held); also self-heals an activation that
|
|
1522
|
+
// crashed between the sweep's claim and this enqueue. Unconditional:
|
|
1523
|
+
// a `slot` holds an assignment on its own, with no schedule policy
|
|
1524
|
+
// anywhere, and gating this on one leaves such a task queued *and*
|
|
1525
|
+
// still sitting in the scheduled store.
|
|
1526
|
+
multi.hDel(this.scheduledAssignmentsKey, id);
|
|
1527
|
+
multi.zRem(this.scheduledActivateAtKey, id);
|
|
1453
1528
|
if ((0, geo_1.isValidLatitude)(latitude) && (0, geo_1.isValidLongitude)(longitude)) {
|
|
1454
1529
|
multi.geoAdd(assignmentGeoKey, {
|
|
1455
1530
|
longitude,
|
|
@@ -1485,24 +1560,18 @@ class AssignmentMatcher {
|
|
|
1485
1560
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
1486
1561
|
// Fetch tags, owner (in case it's pending), accepted JSON (for the
|
|
1487
1562
|
// per-user accepted index), and vetoed users for index cleanup
|
|
1488
|
-
const [tagsCsv, owner, acceptedJson, vetoedUsers] = await Promise.all([
|
|
1563
|
+
const [tagsCsv, owner, acceptedJson, vetoedUsers, bookingJson] = await Promise.all([
|
|
1489
1564
|
this.redisClient.hGet(assignmentTagsKey, 'tags'),
|
|
1490
1565
|
this.redisClient.hGet(this.assignmentOwnerKey, id),
|
|
1491
1566
|
this.redisClient.hGet(this.acceptedAssignmentsKey, id),
|
|
1492
1567
|
this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
|
|
1568
|
+
this.redisClient.hGet(this.slotBookingsKey, id),
|
|
1493
1569
|
]);
|
|
1494
|
-
//
|
|
1495
|
-
//
|
|
1496
|
-
//
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
try {
|
|
1500
|
-
acceptedBy = JSON.parse(acceptedJson)[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
|
|
1501
|
-
}
|
|
1502
|
-
catch {
|
|
1503
|
-
// keep null on parse failure
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1570
|
+
// Who accepted it, from the index written in the accept transaction.
|
|
1571
|
+
// Reading the record's `_acceptedBy` instead would find nothing for an
|
|
1572
|
+
// ordinary assignment and leave that person's per-user index pointing
|
|
1573
|
+
// at work that no longer exists.
|
|
1574
|
+
const acceptedBy = acceptedJson ? await this.ownerOf(id, 'accepted', acceptedJson) : null;
|
|
1506
1575
|
let tags = [];
|
|
1507
1576
|
if (tagsCsv && tagsCsv.length > 0) {
|
|
1508
1577
|
tags = tagsCsv.split(',');
|
|
@@ -1531,6 +1600,7 @@ class AssignmentMatcher {
|
|
|
1531
1600
|
}
|
|
1532
1601
|
// 3. Remove from Accepted state
|
|
1533
1602
|
multi.hDel(this.acceptedAssignmentsKey, id);
|
|
1603
|
+
multi.hDel(this.keys.acceptedAssignmentOwner(), id);
|
|
1534
1604
|
if (acceptedBy) {
|
|
1535
1605
|
multi.zRem(this.keys.userAcceptedAssignments(acceptedBy), id);
|
|
1536
1606
|
}
|
|
@@ -1541,16 +1611,46 @@ class AssignmentMatcher {
|
|
|
1541
1611
|
multi.hDel(this.scheduledAssignmentsKey, id);
|
|
1542
1612
|
multi.zRem(this.scheduledActivateAtKey, id);
|
|
1543
1613
|
multi.zRem(this.scheduleNotAfterKey, id);
|
|
1614
|
+
// 6. Clear the booking (no-op for unslotted assignments). Same rule the
|
|
1615
|
+
// wait clock and the SLA indexes carry: a reservation nobody clears
|
|
1616
|
+
// goes on blocking that worker's afternoon forever.
|
|
1617
|
+
multi.hDel(this.slotBookingsKey, id);
|
|
1618
|
+
multi.hDel(this.bookingSpansKey, id);
|
|
1619
|
+
multi.zRem(this.slotBookingDueAtKey, id);
|
|
1620
|
+
const releasedBooking = AssignmentMatcher.parseBooking(bookingJson);
|
|
1621
|
+
if (releasedBooking)
|
|
1622
|
+
multi.zRem(this.keys.userBookings(releasedBooking.userId), id);
|
|
1544
1623
|
await multi.exec();
|
|
1624
|
+
if (releasedBooking) {
|
|
1625
|
+
this.emitAssignmentLifecycle({
|
|
1626
|
+
kind: 'slotBookingReleased',
|
|
1627
|
+
taskId: id,
|
|
1628
|
+
workerId: releasedBooking.userId,
|
|
1629
|
+
reason: 'terminal',
|
|
1630
|
+
at: Date.now(),
|
|
1631
|
+
});
|
|
1632
|
+
}
|
|
1545
1633
|
return id;
|
|
1546
1634
|
}
|
|
1635
|
+
/**
|
|
1636
|
+
* Remove a user from the pool, handing back everything they held.
|
|
1637
|
+
*
|
|
1638
|
+
* Pending offers and accepted work go back to the queue (`released` with
|
|
1639
|
+
* `reason: 'removed'`), and slot bookings are dropped back onto the booking
|
|
1640
|
+
* sweep. Deleting only the user's own indexes used to strand all of it:
|
|
1641
|
+
* their offers sat under a person who no longer existed until a response
|
|
1642
|
+
* deadline (if any) ran out, and accepted work never came back at all —
|
|
1643
|
+
* nobody else could complete it, and the one person who could was gone.
|
|
1644
|
+
*/
|
|
1547
1645
|
async removeUser(userId) {
|
|
1548
1646
|
await this.readyPromise;
|
|
1647
|
+
await this.handBackHeldWork(userId);
|
|
1549
1648
|
const multi = this.redisClient
|
|
1550
1649
|
.multi()
|
|
1551
1650
|
.del(this.keys.userAssignments(userId))
|
|
1552
1651
|
.del(this.keys.userRejected(userId))
|
|
1553
1652
|
.del(this.keys.userVetoed(userId))
|
|
1653
|
+
.del(this.keys.userOfferCooldown(userId))
|
|
1554
1654
|
.del(this.keys.userAcceptedAssignments(userId))
|
|
1555
1655
|
.zRem(this.keys.userActivity(), userId)
|
|
1556
1656
|
.sRem(this.keys.pausedUsers(), userId)
|
|
@@ -1558,6 +1658,55 @@ class AssignmentMatcher {
|
|
|
1558
1658
|
await multi.exec();
|
|
1559
1659
|
return userId;
|
|
1560
1660
|
}
|
|
1661
|
+
/**
|
|
1662
|
+
* What a user holds right now: unanswered offers, accepted work and slot
|
|
1663
|
+
* bookings, as assignment ids. The read an offboarding preview shows
|
|
1664
|
+
* before `removeUser` hands all of it back.
|
|
1665
|
+
*/
|
|
1666
|
+
async getUserHeldWork(userId) {
|
|
1667
|
+
await this.readyPromise;
|
|
1668
|
+
const [pendingMembers, accepted, booked] = await Promise.all([
|
|
1669
|
+
this.redisClient.sMembers(this.keys.userAssignments(userId)),
|
|
1670
|
+
this.redisClient.zRange(this.keys.userAcceptedAssignments(userId), 0, -1),
|
|
1671
|
+
this.redisClient.zRange(this.keys.userBookings(userId), 0, -1),
|
|
1672
|
+
]);
|
|
1673
|
+
return { pending: pendingMembers.map((member) => member.split(':')[1]).sort(), accepted, booked };
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Requeue every pending and accepted assignment a departing user holds and
|
|
1677
|
+
* drop their slot bookings. Goes through `reclaimForRematch`, so the store
|
|
1678
|
+
* HDEL is the claim gate (a task completed between the read and the write
|
|
1679
|
+
* is left alone), the acceptance stamps and completion clock are cleared,
|
|
1680
|
+
* and the learning attempt is closed as a system fault — leaving is not
|
|
1681
|
+
* the worker failing the work.
|
|
1682
|
+
*/
|
|
1683
|
+
async handBackHeldWork(userId) {
|
|
1684
|
+
const [pendingMembers, acceptedIds, bookedIds] = await Promise.all([
|
|
1685
|
+
this.redisClient.sMembers(this.keys.userAssignments(userId)),
|
|
1686
|
+
this.redisClient.zRange(this.keys.userAcceptedAssignments(userId), 0, -1),
|
|
1687
|
+
this.redisClient.zRange(this.keys.userBookings(userId), 0, -1),
|
|
1688
|
+
]);
|
|
1689
|
+
const held = [
|
|
1690
|
+
...pendingMembers.map((member) => ({ id: member.split(':')[1], from: 'pending' })),
|
|
1691
|
+
...acceptedIds.map((id) => ({ id, from: 'accepted' })),
|
|
1692
|
+
];
|
|
1693
|
+
for (const { id, from } of held) {
|
|
1694
|
+
const store = from === 'pending' ? this.pendingAssignmentsKey : this.acceptedAssignmentsKey;
|
|
1695
|
+
const json = await this.redisClient.hGet(store, id);
|
|
1696
|
+
if (!json)
|
|
1697
|
+
continue;
|
|
1698
|
+
let record;
|
|
1699
|
+
try {
|
|
1700
|
+
record = JSON.parse(json);
|
|
1701
|
+
}
|
|
1702
|
+
catch {
|
|
1703
|
+
continue;
|
|
1704
|
+
}
|
|
1705
|
+
await this.reclaimForRematch(id, record, userId, from, 'removed');
|
|
1706
|
+
}
|
|
1707
|
+
for (const id of bookedIds)
|
|
1708
|
+
await this.releaseSlotBooking(id, 'operator', 'worker removed');
|
|
1709
|
+
}
|
|
1561
1710
|
/**
|
|
1562
1711
|
* Get one stored user as last written by addUser (including the injected
|
|
1563
1712
|
* 'default' tag when enableDefaultMatching is on), or null.
|
|
@@ -1789,6 +1938,123 @@ class AssignmentMatcher {
|
|
|
1789
1938
|
perUser,
|
|
1790
1939
|
};
|
|
1791
1940
|
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Per-tag queue depth and age, plus the wait-clock distribution — the
|
|
1943
|
+
* "which skill is backing up" view a floor with hundreds of thousands of
|
|
1944
|
+
* waiting tasks needs, where listing tasks tells nobody anything.
|
|
1945
|
+
*
|
|
1946
|
+
* Cost is O(tags) `ZCARD`s plus one tag read per sampled assignment, all
|
|
1947
|
+
* pipelined; nothing scales with queue depth. A lane's oldest age is exact
|
|
1948
|
+
* when its work appears among the `oldestSampleSize` oldest waiting
|
|
1949
|
+
* assignments, and an upper bound otherwise (`oldestExact: false`).
|
|
1950
|
+
*/
|
|
1951
|
+
async getLaneStats(options = {}) {
|
|
1952
|
+
await this.readyPromise;
|
|
1953
|
+
const sampleSize = Math.min(20000, Math.max(1, Math.floor(options.oldestSampleSize ?? 2000)));
|
|
1954
|
+
const clockKey = this.keys.assignmentsQueuedAt();
|
|
1955
|
+
const [tags, waiting, sample] = await Promise.all([
|
|
1956
|
+
this.redisClient.zRange(this.keys.allTags(), 0, -1),
|
|
1957
|
+
this.redisClient.zCard(clockKey),
|
|
1958
|
+
this.redisClient.zRangeWithScores(clockKey, 0, sampleSize - 1),
|
|
1959
|
+
]);
|
|
1960
|
+
const now = Date.now();
|
|
1961
|
+
const counts = [];
|
|
1962
|
+
for (let start = 0; start < tags.length; start += 500) {
|
|
1963
|
+
const chunk = tags.slice(start, start + 500);
|
|
1964
|
+
const multi = this.redisClient.multi();
|
|
1965
|
+
for (const tag of chunk)
|
|
1966
|
+
multi.zCard(this.keys.tagAssignments(tag));
|
|
1967
|
+
const cards = (await multi.exec());
|
|
1968
|
+
chunk.forEach((tag, i) => counts.push({ tag, queued: Number(cards[i] ?? 0) }));
|
|
1969
|
+
}
|
|
1970
|
+
const entries = [];
|
|
1971
|
+
for (let start = 0; start < sample.length; start += 500) {
|
|
1972
|
+
const chunk = sample.slice(start, start + 500);
|
|
1973
|
+
const multi = this.redisClient.multi();
|
|
1974
|
+
for (const item of chunk)
|
|
1975
|
+
multi.hGet(this.keys.assignmentTags(item.value), 'tags');
|
|
1976
|
+
const csvs = (await multi.exec());
|
|
1977
|
+
chunk.forEach((item, i) => entries.push({ tagsCsv: csvs[i] ?? null, queuedAt: Number(item.score) }));
|
|
1978
|
+
}
|
|
1979
|
+
// A lane the oldest-first sample never reached still needs to say what
|
|
1980
|
+
// its work travels with; a few of its own members answer that.
|
|
1981
|
+
const sampled = new Set();
|
|
1982
|
+
for (const entry of entries)
|
|
1983
|
+
for (const tag of (entry.tagsCsv ?? '').split(','))
|
|
1984
|
+
if (tag)
|
|
1985
|
+
sampled.add(tag);
|
|
1986
|
+
const unseen = counts.filter((c) => c.queued > 0 && !sampled.has(c.tag)).map((c) => c.tag);
|
|
1987
|
+
const extraTagSets = [];
|
|
1988
|
+
for (let start = 0; start < unseen.length; start += 200) {
|
|
1989
|
+
const chunk = unseen.slice(start, start + 200);
|
|
1990
|
+
const multi = this.redisClient.multi();
|
|
1991
|
+
for (const tag of chunk)
|
|
1992
|
+
multi.zRange(this.keys.tagAssignments(tag), 0, 2);
|
|
1993
|
+
const members = (await multi.exec());
|
|
1994
|
+
const ids = [...new Set(members.flat())];
|
|
1995
|
+
if (ids.length === 0)
|
|
1996
|
+
continue;
|
|
1997
|
+
const read = this.redisClient.multi();
|
|
1998
|
+
for (const id of ids)
|
|
1999
|
+
read.hGet(this.keys.assignmentTags(id), 'tags');
|
|
2000
|
+
for (const csv of (await read.exec()))
|
|
2001
|
+
if (csv)
|
|
2002
|
+
extraTagSets.push(csv);
|
|
2003
|
+
}
|
|
2004
|
+
const scoreAt = async (rank) => {
|
|
2005
|
+
if (waiting === 0)
|
|
2006
|
+
return null;
|
|
2007
|
+
if (rank < sample.length)
|
|
2008
|
+
return Number(sample[rank].score);
|
|
2009
|
+
const hit = await this.redisClient.zRangeWithScores(clockKey, rank, rank);
|
|
2010
|
+
return hit.length > 0 ? Number(hit[0].score) : null;
|
|
2011
|
+
};
|
|
2012
|
+
const [p50, p95] = await Promise.all([scoreAt((0, lane_stats_1.waitRank)(waiting, 0.5)), scoreAt((0, lane_stats_1.waitRank)(waiting, 0.05))]);
|
|
2013
|
+
return {
|
|
2014
|
+
lanes: (0, lane_stats_1.summarizeLanes)({
|
|
2015
|
+
counts,
|
|
2016
|
+
sample: entries,
|
|
2017
|
+
sampleComplete: sample.length >= waiting,
|
|
2018
|
+
now,
|
|
2019
|
+
ignore: this.enableDefaultMatching ? new Set(['default']) : undefined,
|
|
2020
|
+
extraTagSets,
|
|
2021
|
+
}),
|
|
2022
|
+
waits: (0, lane_stats_1.waitDistribution)(waiting, { p50, p95, oldest: sample.length > 0 ? Number(sample[0].score) : null }, now),
|
|
2023
|
+
sampleComplete: sample.length >= waiting,
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
/**
|
|
2027
|
+
* The oldest queued assignments in one lane (tag), oldest first — what a
|
|
2028
|
+
* lane view lists under "waiting longest". Walks the wait-clock index from
|
|
2029
|
+
* the oldest end and keeps assignments still queued under `tag`, reading
|
|
2030
|
+
* at most `scanLimit` entries so a deep, mixed queue stays bounded; a lane
|
|
2031
|
+
* whose work is all younger than that returns fewer (possibly none).
|
|
2032
|
+
*/
|
|
2033
|
+
async getOldestQueuedInLane(tag, options = {}) {
|
|
2034
|
+
await this.readyPromise;
|
|
2035
|
+
const limit = Math.min(100, Math.max(1, Math.floor(options.limit ?? 10)));
|
|
2036
|
+
const scanLimit = Math.min(50000, Math.max(limit, Math.floor(options.scanLimit ?? 5000)));
|
|
2037
|
+
const clockKey = this.keys.assignmentsQueuedAt();
|
|
2038
|
+
const now = Date.now();
|
|
2039
|
+
const found = [];
|
|
2040
|
+
for (let start = 0; start < scanLimit && found.length < limit; start += 500) {
|
|
2041
|
+
const page = await this.redisClient.zRangeWithScores(clockKey, start, Math.min(start + 500, scanLimit) - 1);
|
|
2042
|
+
if (page.length === 0)
|
|
2043
|
+
break;
|
|
2044
|
+
const multi = this.redisClient.multi();
|
|
2045
|
+
for (const item of page)
|
|
2046
|
+
multi.hGet(this.keys.assignmentTags(item.value), 'tags');
|
|
2047
|
+
const csvs = (await multi.exec());
|
|
2048
|
+
for (let i = 0; i < page.length && found.length < limit; i++) {
|
|
2049
|
+
if (csvs[i] && csvs[i].split(',').includes(tag)) {
|
|
2050
|
+
found.push({ id: page[i].value, waitingMs: Math.max(0, now - Number(page[i].score)) });
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
if (page.length < 500)
|
|
2054
|
+
break;
|
|
2055
|
+
}
|
|
2056
|
+
return found;
|
|
2057
|
+
}
|
|
1792
2058
|
/**
|
|
1793
2059
|
* Get all pending assignments with owner and pending duration metadata.
|
|
1794
2060
|
* Reads are bounded: the pending hash is paged with HSCAN and each page's
|
|
@@ -2070,6 +2336,311 @@ class AssignmentMatcher {
|
|
|
2070
2336
|
}
|
|
2071
2337
|
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
2072
2338
|
}
|
|
2339
|
+
/**
|
|
2340
|
+
* Edit a task that already exists — including one somebody is holding.
|
|
2341
|
+
*
|
|
2342
|
+
* Creation is not the last moment a task's facts are known: a title is
|
|
2343
|
+
* wrong, a description gains the detail that was missing, and — the one
|
|
2344
|
+
* that matters here — the routing tags turn out to describe the wrong kind
|
|
2345
|
+
* of work. `tags` and `priority` decide who should have the task, so
|
|
2346
|
+
* changing them is not a metadata write; it is a re-statement of who this
|
|
2347
|
+
* work is for.
|
|
2348
|
+
*
|
|
2349
|
+
* The rule, applied in every state: **retag always, then re-check the
|
|
2350
|
+
* holder.** The new tags are written wherever the task lives, and if the
|
|
2351
|
+
* task is out with somebody, that person is scored against the new tag set
|
|
2352
|
+
* exactly as organic matching would score them. Still eligible and they
|
|
2353
|
+
* keep it — including work they have already accepted, because nothing
|
|
2354
|
+
* about the job changed for them. No longer eligible and the task is taken
|
|
2355
|
+
* back and returned to the queue (`requeued: true`), where the next pass
|
|
2356
|
+
* offers it to somebody the new tags actually reach. That is the whole of
|
|
2357
|
+
* the redistribution: this method never picks the replacement, it only
|
|
2358
|
+
* puts the work back where matching can find it.
|
|
2359
|
+
*
|
|
2360
|
+
* An edit that does not touch the tags never moves anything, whoever holds
|
|
2361
|
+
* the task and however they came by it — a typo fixed in a title is not a
|
|
2362
|
+
* reason to pull a job off the person doing it. `updateAssignment` is also
|
|
2363
|
+
* the only path that re-checks eligibility mid-flight; `assignToUser`
|
|
2364
|
+
* remains the operator's deliberate override and is unaffected.
|
|
2365
|
+
*
|
|
2366
|
+
* Terminal work cannot be edited: a completed or failed task is a record
|
|
2367
|
+
* of what happened. Returns `null` when no live record exists.
|
|
2368
|
+
*
|
|
2369
|
+
* @example
|
|
2370
|
+
* ```typescript
|
|
2371
|
+
* const result = await matcher.updateAssignment('job-12', {
|
|
2372
|
+
* title: 'Leaking kitchen tap',
|
|
2373
|
+
* tags: ['plumbing', 'urgent'],
|
|
2374
|
+
* });
|
|
2375
|
+
* if (result?.requeued) {
|
|
2376
|
+
* // the previous holder no longer matches — it is back in the queue
|
|
2377
|
+
* }
|
|
2378
|
+
* ```
|
|
2379
|
+
*/
|
|
2380
|
+
async updateAssignment(id, patch) {
|
|
2381
|
+
await this.readyPromise;
|
|
2382
|
+
const normalizedTags = patch.tags !== undefined ? (0, assignment_update_1.normalizeUpdateTags)(patch.tags) : undefined;
|
|
2383
|
+
if (normalizedTags !== undefined && normalizedTags.length === 0) {
|
|
2384
|
+
throw new Error(`An assignment must carry at least one tag: ${id}`);
|
|
2385
|
+
}
|
|
2386
|
+
// Where the task lives now. Read in lifecycle order and take the first
|
|
2387
|
+
// hit: the stores are disjoint in steady state, but a claim racing this
|
|
2388
|
+
// read can briefly show two, and the earlier state is the one whose
|
|
2389
|
+
// indexes still need moving.
|
|
2390
|
+
const [queuedJson, pendingJson, acceptedJson, parkedJson, scheduledJson, indexedPriority] = (await this.redisClient
|
|
2391
|
+
.multi()
|
|
2392
|
+
.hGet(this.assignmentsRefKey, id)
|
|
2393
|
+
.hGet(this.pendingAssignmentsKey, id)
|
|
2394
|
+
.hGet(this.acceptedAssignmentsKey, id)
|
|
2395
|
+
.hGet(this.keys.parkedAssignments(), id)
|
|
2396
|
+
.hGet(this.scheduledAssignmentsKey, id)
|
|
2397
|
+
// Read for free in the same round trip: a task created without
|
|
2398
|
+
// an explicit priority has one only here (see `priority` below).
|
|
2399
|
+
.hGet(this.keys.assignmentPriority(id), 'priority')
|
|
2400
|
+
.exec());
|
|
2401
|
+
const located = queuedJson
|
|
2402
|
+
? { status: 'queued', json: queuedJson }
|
|
2403
|
+
: pendingJson
|
|
2404
|
+
? { status: 'pending', json: pendingJson }
|
|
2405
|
+
: acceptedJson
|
|
2406
|
+
? { status: 'accepted', json: acceptedJson }
|
|
2407
|
+
: parkedJson
|
|
2408
|
+
? { status: 'parked', json: parkedJson }
|
|
2409
|
+
: scheduledJson
|
|
2410
|
+
? { status: 'scheduled', json: scheduledJson }
|
|
2411
|
+
: null;
|
|
2412
|
+
if (!located)
|
|
2413
|
+
return null;
|
|
2414
|
+
const current = JSON.parse(located.json);
|
|
2415
|
+
const updated = (0, assignment_update_1.applyUpdate)(current, patch, normalizedTags);
|
|
2416
|
+
const diff = (0, assignment_update_1.diffTagIndexes)(current.tags ?? [], updated.tags ?? [], this.enableDefaultMatching);
|
|
2417
|
+
// `enqueueAssignment` derives a priority for a task created without one
|
|
2418
|
+
// (queue age by default, or the caller's `prioritizationFunction`) and
|
|
2419
|
+
// writes it to the indexes but never into the stored record. Reading
|
|
2420
|
+
// the priority back off the JSON therefore finds nothing, and taking
|
|
2421
|
+
// that for zero would send an edited task to the back of the queue for
|
|
2422
|
+
// a title fix — so the index is the fallback, not `0`.
|
|
2423
|
+
const storedPriority = indexedPriority !== null && indexedPriority !== undefined && indexedPriority !== ''
|
|
2424
|
+
? Number(indexedPriority)
|
|
2425
|
+
: undefined;
|
|
2426
|
+
const priority = updated.priority ?? (Number.isFinite(storedPriority) ? storedPriority : current.priority);
|
|
2427
|
+
switch (located.status) {
|
|
2428
|
+
case 'scheduled':
|
|
2429
|
+
// Held out of matching entirely: raw JSON is the only storage a
|
|
2430
|
+
// pre-activation task has, so there are no indexes to move. The
|
|
2431
|
+
// activation sweep enqueues whatever is written here.
|
|
2432
|
+
await this.redisClient.hSet(this.scheduledAssignmentsKey, id, JSON.stringify(updated));
|
|
2433
|
+
break;
|
|
2434
|
+
case 'parked':
|
|
2435
|
+
// Same shape as scheduled — the parked hash holds the only copy,
|
|
2436
|
+
// and `unparkAssignment` re-enqueues it through `addAssignment`,
|
|
2437
|
+
// which builds every index from these tags.
|
|
2438
|
+
await this.redisClient.hSet(this.keys.parkedAssignments(), id, JSON.stringify(updated));
|
|
2439
|
+
break;
|
|
2440
|
+
case 'queued':
|
|
2441
|
+
await this.rewriteQueuedAssignment(id, updated, diff, priority);
|
|
2442
|
+
break;
|
|
2443
|
+
case 'pending':
|
|
2444
|
+
case 'accepted':
|
|
2445
|
+
// The record's own JSON is the whole edit for held work. The
|
|
2446
|
+
// `assignment:<id>:tags` hash belongs to the queued universe —
|
|
2447
|
+
// `claimSelected` deletes it on the way out and nothing reads
|
|
2448
|
+
// it again — so re-creating it here would leak one key per
|
|
2449
|
+
// edited task past completion.
|
|
2450
|
+
await this.redisClient.hSet(located.status === 'pending' ? this.pendingAssignmentsKey : this.acceptedAssignmentsKey, id, JSON.stringify(updated));
|
|
2451
|
+
break;
|
|
2452
|
+
}
|
|
2453
|
+
const result = {
|
|
2454
|
+
id,
|
|
2455
|
+
status: located.status,
|
|
2456
|
+
tags: updated.tags ?? [],
|
|
2457
|
+
priority,
|
|
2458
|
+
requeued: false,
|
|
2459
|
+
previousOwnerId: null,
|
|
2460
|
+
};
|
|
2461
|
+
// Only a genuine routing change can cost somebody their work.
|
|
2462
|
+
if (!diff.changed || (located.status !== 'pending' && located.status !== 'accepted'))
|
|
2463
|
+
return result;
|
|
2464
|
+
const ownerId = await this.ownerOf(id, located.status, located.json);
|
|
2465
|
+
result.previousOwnerId = ownerId;
|
|
2466
|
+
if (!ownerId)
|
|
2467
|
+
return result;
|
|
2468
|
+
// A workflow-targeted task is routed by name, not by tags: the targeted
|
|
2469
|
+
// lookup grants it to its target without reading a tag at all. Evicting
|
|
2470
|
+
// the holder on a retag would therefore be a round trip to nowhere —
|
|
2471
|
+
// the very next pass hands it straight back — so tags do not un-route
|
|
2472
|
+
// what tags never routed.
|
|
2473
|
+
if (updated._workflowInstanceId &&
|
|
2474
|
+
updated._targetUserId === ownerId) {
|
|
2475
|
+
return result;
|
|
2476
|
+
}
|
|
2477
|
+
const [userJson, vetoed] = await Promise.all([
|
|
2478
|
+
this.redisClient.hGet(this.usersKey, ownerId),
|
|
2479
|
+
this.redisClient.sIsMember(this.keys.assignmentVetoed(id), ownerId),
|
|
2480
|
+
]);
|
|
2481
|
+
const user = userJson ? JSON.parse(userJson) : null;
|
|
2482
|
+
if (!user) {
|
|
2483
|
+
await this.reclaimIfStillHeld(id, updated, ownerId, located.status, result);
|
|
2484
|
+
return result;
|
|
2485
|
+
}
|
|
2486
|
+
// The same judgement the matching pass makes — the caller's own
|
|
2487
|
+
// `matchingFunction` when there is one, plus the CIDR and geo rules —
|
|
2488
|
+
// rather than a second, smaller copy of it that could keep somebody
|
|
2489
|
+
// `explainMatch` calls ineligible, or confiscate work a custom scorer
|
|
2490
|
+
// would still award.
|
|
2491
|
+
//
|
|
2492
|
+
// What is deliberately neutralised: backlog depth, pause state and
|
|
2493
|
+
// prior rejections. Those are reasons not to *newly* offer work; none
|
|
2494
|
+
// of them is a reason to take back work somebody already holds.
|
|
2495
|
+
const evaluated = await this.evaluateCandidateForAssignment(user, updated, diff.tagsCsv, priority ?? 0, undefined, {
|
|
2496
|
+
assignmentId: id,
|
|
2497
|
+
ownerId,
|
|
2498
|
+
isRejected: false,
|
|
2499
|
+
isPaused: false,
|
|
2500
|
+
backlog: 0,
|
|
2501
|
+
});
|
|
2502
|
+
if (evaluated.eligible && !vetoed)
|
|
2503
|
+
return result;
|
|
2504
|
+
await this.reclaimIfStillHeld(id, updated, ownerId, located.status, result);
|
|
2505
|
+
return result;
|
|
2506
|
+
}
|
|
2507
|
+
/** Requeue a retagged task and record it on the result, unless it moved on first. */
|
|
2508
|
+
async reclaimIfStillHeld(id, updated, ownerId, from, result) {
|
|
2509
|
+
if (!(await this.reclaimForRematch(id, updated, ownerId, from)))
|
|
2510
|
+
return;
|
|
2511
|
+
result.status = 'queued';
|
|
2512
|
+
result.requeued = true;
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* Move a queued task between per-tag indexes.
|
|
2516
|
+
*
|
|
2517
|
+
* Carries the same claim-race guard as `setAssignmentPriority`: the read
|
|
2518
|
+
* that found this task queued can be overtaken by an atomic claim, in which
|
|
2519
|
+
* case the writes below resurrect a ghost queued entry for work somebody
|
|
2520
|
+
* already holds. Detect it by the owner appearing, and undo — under the new
|
|
2521
|
+
* tags, which are the ones just written.
|
|
2522
|
+
*/
|
|
2523
|
+
async rewriteQueuedAssignment(id, updated, diff, priority) {
|
|
2524
|
+
const score = Number(priority ?? 0);
|
|
2525
|
+
const multi = this.redisClient
|
|
2526
|
+
.multi()
|
|
2527
|
+
.hSet(this.assignmentsRefKey, id, JSON.stringify(updated))
|
|
2528
|
+
.hSet(this.keys.assignmentTags(id), 'tags', diff.tagsCsv)
|
|
2529
|
+
.hSet(this.keys.assignmentPriority(id), 'priority', score)
|
|
2530
|
+
.zAdd(this.assignmentsKey, { score, value: id });
|
|
2531
|
+
for (const tag of diff.removed)
|
|
2532
|
+
multi.zRem(this.keys.tagAssignments(tag), id);
|
|
2533
|
+
// Every surviving tag is rescored, not just the new ones: a patch may
|
|
2534
|
+
// change the priority as well, and a half-rescored index would order
|
|
2535
|
+
// this task differently depending on which tag the union came through.
|
|
2536
|
+
for (const tag of diff.indexTags) {
|
|
2537
|
+
multi.zAdd(this.keys.tagAssignments(tag), { score, value: id });
|
|
2538
|
+
multi.zAdd(this.allTagsKey, { score: 0, value: tag });
|
|
2539
|
+
}
|
|
2540
|
+
await multi.exec();
|
|
2541
|
+
const owner = await this.redisClient.hGet(this.assignmentOwnerKey, id);
|
|
2542
|
+
if (!owner)
|
|
2543
|
+
return;
|
|
2544
|
+
const cleanup = this.redisClient.multi().hDel(this.assignmentsRefKey, id).zRem(this.assignmentsKey, id);
|
|
2545
|
+
for (const tag of diff.indexTags)
|
|
2546
|
+
cleanup.zRem(this.keys.tagAssignments(tag), id);
|
|
2547
|
+
await cleanup.exec();
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Who holds a pending or accepted task.
|
|
2551
|
+
*
|
|
2552
|
+
* Each state has its own owner hash, so this is one HGET either way. The
|
|
2553
|
+
* `_acceptedBy` fallback is there for records accepted before the accepted
|
|
2554
|
+
* owner index existed; ordinary records never carried that stamp, which is
|
|
2555
|
+
* why the index had to exist.
|
|
2556
|
+
*/
|
|
2557
|
+
async ownerOf(id, status, json) {
|
|
2558
|
+
if (status === 'pending')
|
|
2559
|
+
return (await this.redisClient.hGet(this.assignmentOwnerKey, id)) ?? null;
|
|
2560
|
+
if (status !== 'accepted')
|
|
2561
|
+
return null;
|
|
2562
|
+
const indexed = await this.redisClient.hGet(this.keys.acceptedAssignmentOwner(), id);
|
|
2563
|
+
if (indexed)
|
|
2564
|
+
return indexed;
|
|
2565
|
+
// Records accepted before the owner index existed still carry the
|
|
2566
|
+
// stamp when they declare an SLA.
|
|
2567
|
+
try {
|
|
2568
|
+
const stamped = JSON.parse(json)[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
2569
|
+
if (typeof stamped === 'string')
|
|
2570
|
+
return stamped;
|
|
2571
|
+
}
|
|
2572
|
+
catch {
|
|
2573
|
+
// an unparseable record has no owner to report
|
|
2574
|
+
}
|
|
2575
|
+
return null;
|
|
2576
|
+
}
|
|
2577
|
+
/**
|
|
2578
|
+
* Take a task back off its holder and return it to the open pool.
|
|
2579
|
+
*
|
|
2580
|
+
* Deliberately not `releaseUserPendingAssignments`: that one walks a whole
|
|
2581
|
+
* backlog. This is one task. What it does share with that path is closing
|
|
2582
|
+
* the worker's learning attempt, as a system fault: the reason the work
|
|
2583
|
+
* moved is that an operator changed what it *is*, which says nothing about
|
|
2584
|
+
* how the worker was doing it, and `systemFault` is exactly how the layer
|
|
2585
|
+
* is told to record an attempt without scoring it as a failure. Leaving
|
|
2586
|
+
* the attempt open instead would leave it the *live* attempt for this
|
|
2587
|
+
* assignment, so quality feedback arriving afterwards would train the
|
|
2588
|
+
* worker who no longer holds the work.
|
|
2589
|
+
*
|
|
2590
|
+
* The HDEL out of the holder's store is the claim gate, exactly as it is
|
|
2591
|
+
* for an organic claim: the read that found this task pending can be
|
|
2592
|
+
* overtaken by the holder accepting it, and a task that is no longer where
|
|
2593
|
+
* we found it must not be requeued — that would put one task in the open
|
|
2594
|
+
* pool and in the accepted store at once. Returns whether the reclaim
|
|
2595
|
+
* actually happened.
|
|
2596
|
+
*/
|
|
2597
|
+
async reclaimForRematch(id, updated, ownerId, from, reason = 'retagged') {
|
|
2598
|
+
const now = Date.now();
|
|
2599
|
+
const multi = this.redisClient.multi();
|
|
2600
|
+
multi.sRem(this.keys.userAssignments(ownerId), `assignment:${id}`);
|
|
2601
|
+
if (from === 'pending') {
|
|
2602
|
+
multi.hDel(this.pendingAssignmentsKey, id);
|
|
2603
|
+
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
2604
|
+
multi.hDel(this.assignmentOwnerKey, id);
|
|
2605
|
+
}
|
|
2606
|
+
else {
|
|
2607
|
+
multi.hDel(this.acceptedAssignmentsKey, id);
|
|
2608
|
+
multi.zRem(this.keys.userAcceptedAssignments(ownerId), id);
|
|
2609
|
+
multi.hDel(this.keys.acceptedAssignmentOwner(), id);
|
|
2610
|
+
// The completion clock started when this person accepted; they no
|
|
2611
|
+
// longer have the work, so it must not keep ticking against them.
|
|
2612
|
+
multi.zRem(this.acceptedAssignmentsExpiryKey, id);
|
|
2613
|
+
}
|
|
2614
|
+
// The store HDEL is the second command in either branch; a zero means
|
|
2615
|
+
// the task left that store between the locate read and this write.
|
|
2616
|
+
const results = (await multi.exec());
|
|
2617
|
+
if (Number(results?.[1] ?? 0) === 0)
|
|
2618
|
+
return false;
|
|
2619
|
+
// The acceptance stamps describe a hand-over that has been undone.
|
|
2620
|
+
// Left in place they would make the requeued record look accepted to
|
|
2621
|
+
// `removeAssignment`'s owner lookup and to the completion sweep.
|
|
2622
|
+
const record = updated;
|
|
2623
|
+
delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
|
|
2624
|
+
delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
2625
|
+
delete record[policy_2.SLA_MATCHED_AT_FIELD];
|
|
2626
|
+
if (from === 'accepted')
|
|
2627
|
+
(0, assignment_update_1.consumeOfferWindow)(record);
|
|
2628
|
+
this.emitAssignmentLifecycle({
|
|
2629
|
+
kind: 'released',
|
|
2630
|
+
taskId: id,
|
|
2631
|
+
workerId: ownerId,
|
|
2632
|
+
reason,
|
|
2633
|
+
releasedAt: now,
|
|
2634
|
+
});
|
|
2635
|
+
if (this.enableLearning) {
|
|
2636
|
+
// Closes the attempt without scoring it against the worker, and —
|
|
2637
|
+
// the point of the call — retires it as the live attempt for this
|
|
2638
|
+
// assignment so later feedback cannot be attributed to them.
|
|
2639
|
+
await this.learning.applyOutcome(id, 'expire', { expectedUserId: ownerId, systemFault: true });
|
|
2640
|
+
}
|
|
2641
|
+
await this.addAssignment(updated);
|
|
2642
|
+
return true;
|
|
2643
|
+
}
|
|
2073
2644
|
/**
|
|
2074
2645
|
* Read-only candidate discovery for one user: workflow-targeted lookups,
|
|
2075
2646
|
* the weighted per-tag zset union/diff, and per-candidate scoring
|
|
@@ -2240,7 +2811,15 @@ class AssignmentMatcher {
|
|
|
2240
2811
|
// Always exclude rejected and vetoed assignments
|
|
2241
2812
|
excludeKeys.push(rejectedKey);
|
|
2242
2813
|
excludeKeys.push(this.keys.userVetoed(user.id));
|
|
2243
|
-
//
|
|
2814
|
+
// Offers this user let lapse and has not finished resting from. Elapsed
|
|
2815
|
+
// entries are dropped first, so the zset is its own expiry clock and
|
|
2816
|
+
// the diff below needs no scores. One extra command in a pipeline that
|
|
2817
|
+
// was already going to Redis — no additional round trip, and a key that
|
|
2818
|
+
// never gets written costs a no-op prune.
|
|
2819
|
+
const cooldownKey = this.keys.userOfferCooldown(user.id);
|
|
2820
|
+
multi.zRemRangeByScore(cooldownKey, '-inf', Date.now());
|
|
2821
|
+
excludeKeys.push(cooldownKey);
|
|
2822
|
+
// Final = candidates - exclude (zero weights + rejected + vetoed + resting)
|
|
2244
2823
|
multi.zDiffStore(tempFinalKey, [tempKey, ...excludeKeys]);
|
|
2245
2824
|
// Set short TTLs to clean up
|
|
2246
2825
|
multi.expire(tempKey, 5);
|
|
@@ -2500,14 +3079,83 @@ class AssignmentMatcher {
|
|
|
2500
3079
|
const jsonPromises = selected.map((s) => this.redisClient.hGet(this.assignmentsRefKey, s.id));
|
|
2501
3080
|
const jsons = await Promise.all(jsonPromises);
|
|
2502
3081
|
const now = Date.now();
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
3082
|
+
// What each assignment becomes once it is won, worked out before the
|
|
3083
|
+
// claim so the claim itself can write it. SLA-bearing assignments get a
|
|
3084
|
+
// match timestamp for accept-latency SLO stats; everyone else's JSON
|
|
3085
|
+
// stays byte-identical (guarded by the same cheap indexOf).
|
|
3086
|
+
const pendingJsons = jsons.map((json) => {
|
|
3087
|
+
if (!json || json.indexOf('"sla"') === -1)
|
|
3088
|
+
return json;
|
|
3089
|
+
try {
|
|
3090
|
+
const parsed = JSON.parse(json);
|
|
3091
|
+
parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
|
|
3092
|
+
return JSON.stringify(parsed);
|
|
3093
|
+
}
|
|
3094
|
+
catch {
|
|
3095
|
+
return json; // keep original JSON on parse failure
|
|
3096
|
+
}
|
|
3097
|
+
});
|
|
3098
|
+
// The claim and the queued -> pending move are ONE atomic step. The
|
|
3099
|
+
// HDEL on the queued hash is still the gate (only one caller ever gets
|
|
3100
|
+
// 1 back), but the pending record, its response deadline and its owner
|
|
3101
|
+
// are written in the same script: between two round trips the
|
|
3102
|
+
// assignment was in no store at all, so a concurrent read (cancel,
|
|
3103
|
+
// GET, explain) answered "not found" for live work, and a crash in that
|
|
3104
|
+
// gap lost the assignment outright. An id with no JSON at the snapshot
|
|
3105
|
+
// read is not claimed — it has nothing to move.
|
|
3106
|
+
//
|
|
3107
|
+
// The learning context of a won attempt is committed in the same step,
|
|
3108
|
+
// and only for the attempts this worker actually wins: a separate write
|
|
3109
|
+
// afterwards would leave a crash gap in which the worker owns the
|
|
3110
|
+
// assignment but no learning context exists for it, and its outcome
|
|
3111
|
+
// would then arrive orphaned. A candidate that loses the gate writes
|
|
3112
|
+
// nothing, so no decision is ever left behind for work never received.
|
|
3113
|
+
const decisionFor = new Map();
|
|
3114
|
+
if (this.enableLearning) {
|
|
3115
|
+
const inputs = selected
|
|
3116
|
+
.filter((s) => s.learning)
|
|
3117
|
+
.map((s) => ({
|
|
3118
|
+
decisionId: this.learning.newDecisionId(s.id),
|
|
3119
|
+
userId: user.id,
|
|
3120
|
+
assignmentId: s.id,
|
|
3121
|
+
features: s.learning.features,
|
|
3122
|
+
predictedReward: s.learning.predictedReward,
|
|
3123
|
+
components: s.learning.components,
|
|
3124
|
+
tags: s.learning.tags,
|
|
3125
|
+
propensity: s.learning.propensity,
|
|
3126
|
+
policy: s.learning.policy,
|
|
3127
|
+
candidateCount: s.learning.candidateCount,
|
|
3128
|
+
}));
|
|
3129
|
+
const generation = selected.find((s) => s.learning)?.learning?.generation ?? 0;
|
|
3130
|
+
for (const write of this.learning.decisionWrites(inputs, generation)) {
|
|
3131
|
+
decisionFor.set(write.assignmentId, write);
|
|
3132
|
+
}
|
|
2506
3133
|
}
|
|
2507
|
-
const
|
|
3134
|
+
const claimArgs = [user.id, String(this.learning?.decisionTtlMs ?? 0)];
|
|
3135
|
+
const claimIndex = [];
|
|
2508
3136
|
for (let i = 0; i < selected.length; i++) {
|
|
2509
|
-
|
|
2510
|
-
|
|
3137
|
+
const json = jsons[i];
|
|
3138
|
+
if (!json)
|
|
3139
|
+
continue;
|
|
3140
|
+
claimIndex.push(i);
|
|
3141
|
+
const decision = decisionFor.get(selected[i].id);
|
|
3142
|
+
claimArgs.push(selected[i].id, pendingJsons[i], String(now + (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs)), decision?.decisionKey ?? '', decision?.json ?? '', decision?.pointerKey ?? '', decision?.decisionId ?? '');
|
|
3143
|
+
}
|
|
3144
|
+
if (claimIndex.length > 0) {
|
|
3145
|
+
const won = (await this.redisClient.eval(CLAIM_QUEUED_LUA, {
|
|
3146
|
+
keys: [
|
|
3147
|
+
this.assignmentsRefKey,
|
|
3148
|
+
this.pendingAssignmentsKey,
|
|
3149
|
+
this.pendingAssignmentsExpiryKey,
|
|
3150
|
+
this.assignmentOwnerKey,
|
|
3151
|
+
this.keys.learningStats(),
|
|
3152
|
+
],
|
|
3153
|
+
arguments: claimArgs,
|
|
3154
|
+
}));
|
|
3155
|
+
claimIndex.forEach((selectedIndex, k) => {
|
|
3156
|
+
if (Number(won[k]) > 0)
|
|
3157
|
+
claimedIds.add(selected[selectedIndex].id);
|
|
3158
|
+
});
|
|
2511
3159
|
}
|
|
2512
3160
|
if (claimedIds.size > 0) {
|
|
2513
3161
|
const rm = this.redisClient.multi();
|
|
@@ -2529,63 +3177,21 @@ class AssignmentMatcher {
|
|
|
2529
3177
|
// (a requeue re-adds it via enqueue's geoAdd); without this the
|
|
2530
3178
|
// index grows monotonically with completed work.
|
|
2531
3179
|
rm.zRem(this.keys.assignmentsGeo(), s.id);
|
|
2532
|
-
//
|
|
2533
|
-
//
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
const parsed = JSON.parse(json);
|
|
2543
|
-
parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
|
|
2544
|
-
pendingJson = JSON.stringify(parsed);
|
|
2545
|
-
// Count the offer (global + per-tag) in the same batch.
|
|
2546
|
-
rm.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
|
|
2547
|
-
for (const tag of (parsed.tags ?? [])) {
|
|
2548
|
-
if (tag)
|
|
2549
|
-
rm.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
|
|
2550
|
-
}
|
|
2551
|
-
}
|
|
2552
|
-
catch {
|
|
2553
|
-
// keep original JSON on parse failure
|
|
3180
|
+
// The pending record, its deadline and its owner were written
|
|
3181
|
+
// by the claim itself; what is left is the SLA offer count.
|
|
3182
|
+
if (json && json.indexOf('"sla"') !== -1) {
|
|
3183
|
+
try {
|
|
3184
|
+
const parsed = JSON.parse(json);
|
|
3185
|
+
// Count the offer (global + per-tag) in the same batch.
|
|
3186
|
+
rm.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
|
|
3187
|
+
for (const tag of (parsed.tags ?? [])) {
|
|
3188
|
+
if (tag)
|
|
3189
|
+
rm.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
|
|
2554
3190
|
}
|
|
2555
3191
|
}
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
value: s.id,
|
|
2560
|
-
});
|
|
2561
|
-
rm.hSet(this.assignmentOwnerKey, s.id, user.id);
|
|
2562
|
-
}
|
|
2563
|
-
}
|
|
2564
|
-
// Commit the learning context for the attempts this worker
|
|
2565
|
-
// actually won — and only those. The HDEL above is the atomic gate
|
|
2566
|
-
// that decides ownership, so this is the first point at which "who
|
|
2567
|
-
// got this assignment" is a settled fact. The writes go into the
|
|
2568
|
-
// SAME transaction as the queued -> pending move: a separate write
|
|
2569
|
-
// afterwards would leave a crash gap in which the worker owns the
|
|
2570
|
-
// assignment but no learning context exists for it, and its
|
|
2571
|
-
// outcome would then arrive orphaned.
|
|
2572
|
-
if (this.enableLearning) {
|
|
2573
|
-
const decisions = selected
|
|
2574
|
-
.filter((s) => claimedIds.has(s.id) && s.learning)
|
|
2575
|
-
.map((s) => ({
|
|
2576
|
-
decisionId: this.learning.newDecisionId(s.id),
|
|
2577
|
-
userId: user.id,
|
|
2578
|
-
assignmentId: s.id,
|
|
2579
|
-
features: s.learning.features,
|
|
2580
|
-
predictedReward: s.learning.predictedReward,
|
|
2581
|
-
components: s.learning.components,
|
|
2582
|
-
tags: s.learning.tags,
|
|
2583
|
-
propensity: s.learning.propensity,
|
|
2584
|
-
policy: s.learning.policy,
|
|
2585
|
-
candidateCount: s.learning.candidateCount,
|
|
2586
|
-
}));
|
|
2587
|
-
if (decisions.length > 0) {
|
|
2588
|
-
this.learning.queueDecisionWrites(rm, decisions, selected.find((s) => s.learning)?.learning?.generation ?? 0);
|
|
3192
|
+
catch {
|
|
3193
|
+
// an unparseable record counts no offer, as before
|
|
3194
|
+
}
|
|
2589
3195
|
}
|
|
2590
3196
|
}
|
|
2591
3197
|
await rm.exec();
|
|
@@ -2645,7 +3251,7 @@ class AssignmentMatcher {
|
|
|
2645
3251
|
* outcomes to workers who never received the work.
|
|
2646
3252
|
*/
|
|
2647
3253
|
async matchAllUsersFair() {
|
|
2648
|
-
|
|
3254
|
+
const users = [];
|
|
2649
3255
|
let cursor = '0';
|
|
2650
3256
|
do {
|
|
2651
3257
|
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
@@ -2876,7 +3482,7 @@ class AssignmentMatcher {
|
|
|
2876
3482
|
return this.matchAllUsersFair();
|
|
2877
3483
|
}
|
|
2878
3484
|
// Otherwise, process all users in parallel as before.
|
|
2879
|
-
|
|
3485
|
+
const users = [];
|
|
2880
3486
|
let cursor = '0';
|
|
2881
3487
|
// Fetch all users in a single loop
|
|
2882
3488
|
do {
|
|
@@ -2948,12 +3554,27 @@ class AssignmentMatcher {
|
|
|
2948
3554
|
]);
|
|
2949
3555
|
if (previousOwnerId === userId)
|
|
2950
3556
|
return { previousOwnerId: userId };
|
|
3557
|
+
// Already accepted? Reassigning work somebody took on is the "during
|
|
3558
|
+
// execution" case: a supervisor moving a job that has started. It comes
|
|
3559
|
+
// back as a fresh *offer* rather than transferring the acceptance,
|
|
3560
|
+
// because the new worker has not agreed to anything yet and a task
|
|
3561
|
+
// sitting in the accepted store under somebody who never said yes is a
|
|
3562
|
+
// completion clock running against a promise nobody made.
|
|
3563
|
+
let acceptedJson = null;
|
|
2951
3564
|
if (!queuedJson && !previousOwnerId) {
|
|
3565
|
+
acceptedJson = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
3566
|
+
if (acceptedJson) {
|
|
3567
|
+
previousOwnerId = await this.ownerOf(assignmentId, 'accepted', acceptedJson);
|
|
3568
|
+
if (previousOwnerId === userId)
|
|
3569
|
+
return { previousOwnerId: userId };
|
|
3570
|
+
}
|
|
3571
|
+
}
|
|
3572
|
+
if (!queuedJson && !previousOwnerId && !acceptedJson) {
|
|
2952
3573
|
// Held by schedule.notBefore? Operators may early-activate with
|
|
2953
3574
|
// force; without it the hold is honored like any other rule.
|
|
2954
3575
|
const scheduledJson = await this.redisClient.hGet(this.scheduledAssignmentsKey, assignmentId);
|
|
2955
3576
|
if (!scheduledJson) {
|
|
2956
|
-
throw new Error(`Assignment not found in queued or
|
|
3577
|
+
throw new Error(`Assignment not found in queued, pending or accepted state: ${assignmentId}`);
|
|
2957
3578
|
}
|
|
2958
3579
|
const held = JSON.parse(scheduledJson);
|
|
2959
3580
|
const heldPolicy = (0, policy_3.normalizeSchedulePolicy)(held.schedule);
|
|
@@ -2991,7 +3612,15 @@ class AssignmentMatcher {
|
|
|
2991
3612
|
if (hasRejected)
|
|
2992
3613
|
throw new Error(`User previously rejected this assignment: ${userId}`);
|
|
2993
3614
|
}
|
|
2994
|
-
|
|
3615
|
+
// An operator override is a human decision about this one task, so a
|
|
3616
|
+
// rest period is not a reason to refuse it — the claim below never
|
|
3617
|
+
// reads the cooldown anyway. Clearing it stops a bar that is now moot
|
|
3618
|
+
// from surviving into the next organic pass.
|
|
3619
|
+
await this.redisClient.zRem(this.keys.userOfferCooldown(userId), assignmentId);
|
|
3620
|
+
if (acceptedJson) {
|
|
3621
|
+
await this.offerAcceptedToUser(assignmentId, acceptedJson, previousOwnerId, userId);
|
|
3622
|
+
}
|
|
3623
|
+
else if (queuedJson) {
|
|
2995
3624
|
// Queued -> pending through the same atomic claim gate as organic
|
|
2996
3625
|
// matching; losing it means a concurrent pass just took the
|
|
2997
3626
|
// assignment.
|
|
@@ -3044,6 +3673,105 @@ class AssignmentMatcher {
|
|
|
3044
3673
|
await this.recordManualAssignTrace(assignmentId, userId, force, previousOwnerId ?? null);
|
|
3045
3674
|
return { previousOwnerId: previousOwnerId ?? null };
|
|
3046
3675
|
}
|
|
3676
|
+
/**
|
|
3677
|
+
* Hand accepted work to a different person as a pending offer.
|
|
3678
|
+
*
|
|
3679
|
+
* Everything the acceptance established is undone: the record leaves the
|
|
3680
|
+
* accepted store and the previous owner's accepted index, the completion
|
|
3681
|
+
* deadline they were working to is dropped, and the `_acceptedAt` /
|
|
3682
|
+
* `_acceptedBy` stamps go with it — a record that still claimed to be
|
|
3683
|
+
* accepted would be read as such by the completion sweep and by
|
|
3684
|
+
* `removeAssignment`'s owner lookup.
|
|
3685
|
+
*
|
|
3686
|
+
* The wait clock is restarted rather than left cleared. `acceptAssignment`
|
|
3687
|
+
* stops it because somebody took the work; this puts the task back among
|
|
3688
|
+
* the unaccepted, and a queue-age dashboard that could not see it would be
|
|
3689
|
+
* under-reporting real waiting work. It anchors at the hand-over, which is
|
|
3690
|
+
* when this particular wait began.
|
|
3691
|
+
*/
|
|
3692
|
+
async offerAcceptedToUser(assignmentId, acceptedJson, previousOwnerId, userId) {
|
|
3693
|
+
// The accepted hash is the only copy, so the HDEL is the claim gate:
|
|
3694
|
+
// losing it means a completion, failure or sweep got there first.
|
|
3695
|
+
const claimed = await this.redisClient.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
3696
|
+
if (!claimed)
|
|
3697
|
+
throw new Error(`Assignment is no longer available: ${assignmentId}`);
|
|
3698
|
+
const now = Date.now();
|
|
3699
|
+
let pendingJson = acceptedJson;
|
|
3700
|
+
// Only records that were stamped need rewriting, and only SLA-bearing
|
|
3701
|
+
// ones get a fresh match timestamp — the same cheap guards the organic
|
|
3702
|
+
// claim and the pending-to-pending transfer use, so an assignment
|
|
3703
|
+
// without an SLA keeps byte-identical stored JSON through a hand-over.
|
|
3704
|
+
const isSla = acceptedJson.indexOf('"sla"') !== -1;
|
|
3705
|
+
let tags = [];
|
|
3706
|
+
if (isSla ||
|
|
3707
|
+
acceptedJson.indexOf('"' + policy_2.SLA_ACCEPTED_AT_FIELD + '"') !== -1 ||
|
|
3708
|
+
acceptedJson.indexOf('"notAfter"') !== -1) {
|
|
3709
|
+
try {
|
|
3710
|
+
const parsed = JSON.parse(acceptedJson);
|
|
3711
|
+
delete parsed[policy_2.SLA_ACCEPTED_AT_FIELD];
|
|
3712
|
+
delete parsed[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
3713
|
+
if (isSla)
|
|
3714
|
+
parsed[policy_2.SLA_MATCHED_AT_FIELD] = now;
|
|
3715
|
+
// The first acceptance answered the offer window; this
|
|
3716
|
+
// hand-over is not a second chance to miss it.
|
|
3717
|
+
(0, assignment_update_1.consumeOfferWindow)(parsed);
|
|
3718
|
+
tags = (parsed.tags ?? []);
|
|
3719
|
+
pendingJson = JSON.stringify(parsed);
|
|
3720
|
+
}
|
|
3721
|
+
catch {
|
|
3722
|
+
// keep the original JSON on parse failure
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
const deadlineMs = (0, policy_1.responseDeadlineFromJson)(pendingJson, this.matchExpirationMs);
|
|
3726
|
+
const multi = this.redisClient
|
|
3727
|
+
.multi()
|
|
3728
|
+
.hSet(this.pendingAssignmentsKey, assignmentId, pendingJson)
|
|
3729
|
+
.hSet(this.assignmentOwnerKey, assignmentId, userId)
|
|
3730
|
+
.zAdd(this.pendingAssignmentsExpiryKey, { score: now + deadlineMs, value: assignmentId })
|
|
3731
|
+
.sAdd(this.keys.userAssignments(userId), `assignment:${assignmentId}`)
|
|
3732
|
+
.zAdd(this.keys.assignmentsQueuedAt(), { score: now, value: assignmentId }, { NX: true })
|
|
3733
|
+
.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
3734
|
+
if (previousOwnerId) {
|
|
3735
|
+
multi.zRem(this.keys.userAcceptedAssignments(previousOwnerId), assignmentId);
|
|
3736
|
+
// Not when the owner is getting it back (`returnAcceptedToPending`):
|
|
3737
|
+
// the add above is the point.
|
|
3738
|
+
if (previousOwnerId !== userId) {
|
|
3739
|
+
multi.sRem(this.keys.userAssignments(previousOwnerId), `assignment:${assignmentId}`);
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3742
|
+
multi.hDel(this.keys.acceptedAssignmentOwner(), assignmentId);
|
|
3743
|
+
// A re-offer is an offer. Without counting it, the new worker's accept
|
|
3744
|
+
// lands against the original offer and the acceptance rate reads above
|
|
3745
|
+
// 100%.
|
|
3746
|
+
if (isSla) {
|
|
3747
|
+
multi.hIncrByFloat(this.keys.slaStats(), 'offers', 1);
|
|
3748
|
+
for (const tag of tags) {
|
|
3749
|
+
if (tag)
|
|
3750
|
+
multi.hIncrByFloat(this.keys.slaTagStats(tag), 'offers', 1);
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
await multi.exec();
|
|
3754
|
+
if (previousOwnerId) {
|
|
3755
|
+
// Nothing else names them: the `pending` event below is about the
|
|
3756
|
+
// new worker. Without this the person who was actually doing the
|
|
3757
|
+
// job is never told it moved, and anything mirroring their accepted
|
|
3758
|
+
// work goes on showing it.
|
|
3759
|
+
this.emitAssignmentLifecycle({
|
|
3760
|
+
kind: 'released',
|
|
3761
|
+
taskId: assignmentId,
|
|
3762
|
+
workerId: previousOwnerId,
|
|
3763
|
+
reason: 'reassigned',
|
|
3764
|
+
releasedAt: now,
|
|
3765
|
+
});
|
|
3766
|
+
}
|
|
3767
|
+
this.emitAssignmentLifecycle({
|
|
3768
|
+
kind: 'pending',
|
|
3769
|
+
taskId: assignmentId,
|
|
3770
|
+
workerId: userId,
|
|
3771
|
+
matchedAt: now,
|
|
3772
|
+
expiresAt: now + deadlineMs,
|
|
3773
|
+
});
|
|
3774
|
+
}
|
|
3047
3775
|
/** Audit record for an assignToUser() override; failures never break the assignment. */
|
|
3048
3776
|
async recordManualAssignTrace(assignmentId, userId, force, previousOwnerId) {
|
|
3049
3777
|
if (!this.tracingActive)
|
|
@@ -3088,6 +3816,8 @@ class AssignmentMatcher {
|
|
|
3088
3816
|
multi.hDel(this.assignmentOwnerKey, assignmentId);
|
|
3089
3817
|
// The wait clock stops when a user takes the work
|
|
3090
3818
|
multi.zRem(this.keys.assignmentsQueuedAt(), assignmentId);
|
|
3819
|
+
// Taking the work settles any earlier unanswered offer of it.
|
|
3820
|
+
multi.zRem(this.keys.userOfferCooldown(userId), assignmentId);
|
|
3091
3821
|
// Acceptance ends the offer window: the notAfter clock dies here, so
|
|
3092
3822
|
// no post-accept path ever needs to clear it. One indexOf keeps
|
|
3093
3823
|
// schedule-less assignments free of any extra cost.
|
|
@@ -3126,6 +3856,10 @@ class AssignmentMatcher {
|
|
|
3126
3856
|
// Inside the guard: an accept whose pending JSON is missing stores
|
|
3127
3857
|
// nothing, so it must index nothing.
|
|
3128
3858
|
multi.zAdd(this.keys.userAcceptedAssignments(userId), { score: now, value: assignmentId });
|
|
3859
|
+
// Acceptance deletes the pending owner hash, and the byte-identical
|
|
3860
|
+
// rule keeps `_acceptedBy` off ordinary records — so without this
|
|
3861
|
+
// there is no index saying who holds accepted work.
|
|
3862
|
+
multi.hSet(this.keys.acceptedAssignmentOwner(), assignmentId, userId);
|
|
3129
3863
|
}
|
|
3130
3864
|
await multi.exec();
|
|
3131
3865
|
// SLO accept stats piggyback the accept path (internally guarded:
|
|
@@ -3145,6 +3879,26 @@ class AssignmentMatcher {
|
|
|
3145
3879
|
await this.touchUser(userId);
|
|
3146
3880
|
return true;
|
|
3147
3881
|
}
|
|
3882
|
+
/**
|
|
3883
|
+
* Undo an acceptance: the worker who accepted the task gets it back as a
|
|
3884
|
+
* pending offer of their own. Nothing is refused or requeued for others, so
|
|
3885
|
+
* unlike `rejectAssignment` it works on accepted work, and the worker is not
|
|
3886
|
+
* barred from taking it again. Emits `released` (`reassigned`) for the
|
|
3887
|
+
* worker, then `pending` — the same events and storage changes as handing
|
|
3888
|
+
* accepted work to somebody else, with the owner on both ends.
|
|
3889
|
+
*
|
|
3890
|
+
* Only the accepting worker may do this; anyone else throws.
|
|
3891
|
+
*/
|
|
3892
|
+
async returnAcceptedToPending(userId, assignmentId) {
|
|
3893
|
+
await this.readyPromise;
|
|
3894
|
+
const acceptedJson = await this.redisClient.hGet(this.acceptedAssignmentsKey, assignmentId);
|
|
3895
|
+
const owner = acceptedJson ? await this.ownerOf(assignmentId, 'accepted', acceptedJson) : null;
|
|
3896
|
+
if (!acceptedJson || owner !== userId)
|
|
3897
|
+
throw new Error('Assignment not accepted by user');
|
|
3898
|
+
await this.offerAcceptedToUser(assignmentId, acceptedJson, userId, userId);
|
|
3899
|
+
await this.touchUser(userId);
|
|
3900
|
+
return true;
|
|
3901
|
+
}
|
|
3148
3902
|
async rejectAssignment(userId, assignmentId) {
|
|
3149
3903
|
await this.readyPromise;
|
|
3150
3904
|
const isAssigned = await this.redisClient.sIsMember(this.keys.userAssignments(userId), `assignment:${assignmentId}`);
|
|
@@ -3251,11 +4005,23 @@ class AssignmentMatcher {
|
|
|
3251
4005
|
if (!json) {
|
|
3252
4006
|
throw new Error('Assignment not found in accepted state');
|
|
3253
4007
|
}
|
|
4008
|
+
// Work can change hands after acceptance (`assignToUser` on accepted
|
|
4009
|
+
// work, or a retag that takes it back), and the person who used to
|
|
4010
|
+
// hold it may still have it on screen. Finishing somebody else's task
|
|
4011
|
+
// would delete their record, clear the wrong per-user index and
|
|
4012
|
+
// attribute the outcome to the wrong worker, so the holder is checked
|
|
4013
|
+
// rather than assumed. An entry is absent only for work accepted
|
|
4014
|
+
// before the owner index existed, which is left alone.
|
|
4015
|
+
const holderId = await this.ownerOf(assignmentId, 'accepted', json);
|
|
4016
|
+
if (holderId && holderId !== userId) {
|
|
4017
|
+
throw new Error(`Assignment is not held by this user: ${assignmentId}`);
|
|
4018
|
+
}
|
|
3254
4019
|
const assignment = JSON.parse(json);
|
|
3255
4020
|
const now = Date.now();
|
|
3256
4021
|
// Move from accepted to completed
|
|
3257
4022
|
const multi = this.redisClient.multi();
|
|
3258
4023
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
4024
|
+
multi.hDel(this.keys.acceptedAssignmentOwner(), assignmentId);
|
|
3259
4025
|
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
3260
4026
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
3261
4027
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
@@ -3289,6 +4055,7 @@ class AssignmentMatcher {
|
|
|
3289
4055
|
payload: result?.data,
|
|
3290
4056
|
});
|
|
3291
4057
|
}
|
|
4058
|
+
await this.clearBookingOnTerminal(assignmentId);
|
|
3292
4059
|
this.emitAssignmentLifecycle({
|
|
3293
4060
|
kind: 'completed',
|
|
3294
4061
|
taskId: assignmentId,
|
|
@@ -3310,11 +4077,23 @@ class AssignmentMatcher {
|
|
|
3310
4077
|
if (!json) {
|
|
3311
4078
|
throw new Error('Assignment not found in accepted state');
|
|
3312
4079
|
}
|
|
4080
|
+
// Work can change hands after acceptance (`assignToUser` on accepted
|
|
4081
|
+
// work, or a retag that takes it back), and the person who used to
|
|
4082
|
+
// hold it may still have it on screen. Finishing somebody else's task
|
|
4083
|
+
// would delete their record, clear the wrong per-user index and
|
|
4084
|
+
// attribute the outcome to the wrong worker, so the holder is checked
|
|
4085
|
+
// rather than assumed. An entry is absent only for work accepted
|
|
4086
|
+
// before the owner index existed, which is left alone.
|
|
4087
|
+
const holderId = await this.ownerOf(assignmentId, 'accepted', json);
|
|
4088
|
+
if (holderId && holderId !== userId) {
|
|
4089
|
+
throw new Error(`Assignment is not held by this user: ${assignmentId}`);
|
|
4090
|
+
}
|
|
3313
4091
|
const assignment = JSON.parse(json);
|
|
3314
4092
|
const now = Date.now();
|
|
3315
4093
|
// Move from accepted to completed (with failed status)
|
|
3316
4094
|
const multi = this.redisClient.multi();
|
|
3317
4095
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
4096
|
+
multi.hDel(this.keys.acceptedAssignmentOwner(), assignmentId);
|
|
3318
4097
|
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
3319
4098
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
3320
4099
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
@@ -3349,6 +4128,7 @@ class AssignmentMatcher {
|
|
|
3349
4128
|
// worker-reported failure was invisible to lifecycle observers (and
|
|
3350
4129
|
// therefore to the platform's webhooks, sockets and push) even though
|
|
3351
4130
|
// the workflow stream above heard about it.
|
|
4131
|
+
await this.clearBookingOnTerminal(assignmentId);
|
|
3352
4132
|
this.emitAssignmentLifecycle({
|
|
3353
4133
|
kind: 'failed',
|
|
3354
4134
|
taskId: assignmentId,
|
|
@@ -3594,6 +4374,31 @@ class AssignmentMatcher {
|
|
|
3594
4374
|
// decision traces already explain it as `rejectedPreviously`.
|
|
3595
4375
|
if (decision?.blockPreviousOwner)
|
|
3596
4376
|
multi.sAdd(this.keys.userRejected(owner), id);
|
|
4377
|
+
else if (assignment) {
|
|
4378
|
+
// Not blocked, but not asked again immediately either: the
|
|
4379
|
+
// offer rests. Without this the requeue below lands back on
|
|
4380
|
+
// the same person on the very next pass, which for work
|
|
4381
|
+
// with a single eligible worker is an endless re-offer loop
|
|
4382
|
+
// — one decision trace, and one "offered" row in any host
|
|
4383
|
+
// UI, every deadline for as long as the task lives.
|
|
4384
|
+
//
|
|
4385
|
+
// Guarded on `assignment`: a null here means the record was
|
|
4386
|
+
// removed or accepted between the index read and ours, and
|
|
4387
|
+
// there is nothing left to rest from.
|
|
4388
|
+
const cooldownMs = (0, policy_1.offerCooldownMs)(assignment, this.offerCooldownMs);
|
|
4389
|
+
if (cooldownMs > 0) {
|
|
4390
|
+
const cooldownKey = this.keys.userOfferCooldown(owner);
|
|
4391
|
+
// Elapsed entries go first so the set never grows past
|
|
4392
|
+
// what is still in force. No key TTL, deliberately: a
|
|
4393
|
+
// per-key expiry set from *this* cooldown would cut short
|
|
4394
|
+
// any longer one the same user is already serving, and
|
|
4395
|
+
// per-entry expiry is exactly what the score is. An
|
|
4396
|
+
// empty zset deletes itself, and removeUser drops the
|
|
4397
|
+
// key — the same lifetime the rejected set has.
|
|
4398
|
+
multi.zRemRangeByScore(cooldownKey, '-inf', now);
|
|
4399
|
+
multi.zAdd(cooldownKey, { score: now + cooldownMs, value: id });
|
|
4400
|
+
}
|
|
4401
|
+
}
|
|
3597
4402
|
}
|
|
3598
4403
|
multi.hDel(this.pendingAssignmentsKey, id);
|
|
3599
4404
|
multi.zRem(this.pendingAssignmentsExpiryKey, id);
|
|
@@ -3963,6 +4768,8 @@ class AssignmentMatcher {
|
|
|
3963
4768
|
// A due notBefore falls straight through addAssignment's hold
|
|
3964
4769
|
// guard into the normal enqueue, which also clears the scheduled
|
|
3965
4770
|
// hash atomically with the queued write.
|
|
4771
|
+
const slot = (0, slot_1.slotFromJson)(json);
|
|
4772
|
+
const booking = slot ? await this.getSlotBooking(id) : null;
|
|
3966
4773
|
try {
|
|
3967
4774
|
await this.addAssignment(JSON.parse(json));
|
|
3968
4775
|
}
|
|
@@ -3975,9 +4782,514 @@ class AssignmentMatcher {
|
|
|
3975
4782
|
}
|
|
3976
4783
|
activated++;
|
|
3977
4784
|
this.emitAssignmentLifecycle({ kind: 'scheduleActivated', taskId: id, at: now });
|
|
4785
|
+
if (slot) {
|
|
4786
|
+
// The appointment has arrived. A booked one goes to the person
|
|
4787
|
+
// it was booked to, as a pending offer — never as an
|
|
4788
|
+
// acceptance, because they have not said yes to anything yet.
|
|
4789
|
+
// `force` is right here: the booking cleared every guardrail
|
|
4790
|
+
// when it was made, and refusing now on a backlog count would
|
|
4791
|
+
// strand an appointment somebody is expecting.
|
|
4792
|
+
if (booking) {
|
|
4793
|
+
try {
|
|
4794
|
+
await this.assignToUser(id, booking.userId, { force: true });
|
|
4795
|
+
}
|
|
4796
|
+
catch (err) {
|
|
4797
|
+
// The holder vanished (removed, or the task was taken
|
|
4798
|
+
// by something else between the enqueue and here).
|
|
4799
|
+
// The work is queued and matchable, which is the
|
|
4800
|
+
// honest fallback; the stale reservation is not.
|
|
4801
|
+
await this.releaseSlotBooking(id, 'operator', err?.message);
|
|
4802
|
+
}
|
|
4803
|
+
}
|
|
4804
|
+
else {
|
|
4805
|
+
// Nobody booked it in time. `'queue'` leaves it in the open
|
|
4806
|
+
// pool it was just enqueued into — the appointment is
|
|
4807
|
+
// simply being staffed late — while park and drop mirror
|
|
4808
|
+
// `schedule.onMiss`.
|
|
4809
|
+
const unbooked = slot.onUnbooked;
|
|
4810
|
+
if (unbooked === 'park') {
|
|
4811
|
+
await this.redisClient.hSet(this.keys.parkedAssignments(), id, json);
|
|
4812
|
+
await this.removeAssignment(id);
|
|
4813
|
+
}
|
|
4814
|
+
else if (unbooked === 'drop') {
|
|
4815
|
+
await this.removeAssignment(id);
|
|
4816
|
+
}
|
|
4817
|
+
await this.redisClient.zRem(this.slotBookingDueAtKey, id);
|
|
4818
|
+
}
|
|
4819
|
+
}
|
|
3978
4820
|
}
|
|
3979
4821
|
return { activated, missed };
|
|
3980
4822
|
}
|
|
4823
|
+
// ============================================================================
|
|
4824
|
+
// Slots and bookings — reserving a worker's time ahead of the work
|
|
4825
|
+
// ============================================================================
|
|
4826
|
+
/**
|
|
4827
|
+
* Run the booking script, reloading it if Redis has forgotten it.
|
|
4828
|
+
*
|
|
4829
|
+
* The script is the only place a reservation is written, so a NOSCRIPT
|
|
4830
|
+
* after a Redis restart must be answered with a reload rather than a
|
|
4831
|
+
* fallback: a non-atomic path here would be a second claim gate, and two
|
|
4832
|
+
* gates on one resource is how the same hour gets booked twice.
|
|
4833
|
+
*/
|
|
4834
|
+
async runBookSlot(keys, args) {
|
|
4835
|
+
if (!this.bookSlotSha)
|
|
4836
|
+
this.bookSlotSha = await this.redisClient.scriptLoad(BOOK_SLOT_LUA);
|
|
4837
|
+
try {
|
|
4838
|
+
return (await this.redisClient.evalSha(this.bookSlotSha, { keys, arguments: args }));
|
|
4839
|
+
}
|
|
4840
|
+
catch (err) {
|
|
4841
|
+
if (!String(err.message).includes('NOSCRIPT'))
|
|
4842
|
+
throw err;
|
|
4843
|
+
this.bookSlotSha = await this.redisClient.scriptLoad(BOOK_SLOT_LUA);
|
|
4844
|
+
return (await this.redisClient.evalSha(this.bookSlotSha, { keys, arguments: args }));
|
|
4845
|
+
}
|
|
4846
|
+
}
|
|
4847
|
+
/** The slot of an assignment currently held in the scheduled store. */
|
|
4848
|
+
async loadSlottedAssignment(assignmentId) {
|
|
4849
|
+
const json = await this.redisClient.hGet(this.scheduledAssignmentsKey, assignmentId);
|
|
4850
|
+
if (!json)
|
|
4851
|
+
return null;
|
|
4852
|
+
const slot = (0, slot_1.slotFromJson)(json);
|
|
4853
|
+
if (!slot)
|
|
4854
|
+
return null;
|
|
4855
|
+
return { assignment: JSON.parse(json), slot };
|
|
4856
|
+
}
|
|
4857
|
+
/**
|
|
4858
|
+
* Reserve a worker for a slotted assignment.
|
|
4859
|
+
*
|
|
4860
|
+
* A reservation is not an offer and not an acceptance: it holds the hour
|
|
4861
|
+
* against anything else landing on it and it puts the job on the worker's
|
|
4862
|
+
* calendar, but it occupies no backlog place and starts no clock. That is
|
|
4863
|
+
* what keeps `accepted` meaning "I am working on this" — a fortnight of
|
|
4864
|
+
* booked appointments must not fill somebody's backlog cap, and a
|
|
4865
|
+
* completion deadline must not run against work that has not started.
|
|
4866
|
+
*
|
|
4867
|
+
* The clash probe and the write happen inside one Lua script, because
|
|
4868
|
+
* checking and then writing lets two callers both book the same hour.
|
|
4869
|
+
*
|
|
4870
|
+
* `force` skips the caller's `blocked` availability — a planner overriding
|
|
4871
|
+
* an absence is a human decision about one job. It never skips the overlap
|
|
4872
|
+
* rule: double-booking one person at 14:00 is a data error, not a
|
|
4873
|
+
* judgement call.
|
|
4874
|
+
*/
|
|
4875
|
+
async bookSlot(assignmentId, userId, options) {
|
|
4876
|
+
await this.readyPromise;
|
|
4877
|
+
const userJson = await this.redisClient.hGet(this.usersKey, userId);
|
|
4878
|
+
if (!userJson)
|
|
4879
|
+
throw new Error(`User not found: ${userId}`);
|
|
4880
|
+
const held = await this.loadSlottedAssignment(assignmentId);
|
|
4881
|
+
if (!held)
|
|
4882
|
+
throw new Error(`Assignment is not a slotted assignment awaiting its slot: ${assignmentId}`);
|
|
4883
|
+
const { slot } = held;
|
|
4884
|
+
const availability = (await this.loadSlotAvailability([userId], slot.startAt, (0, slot_1.slotEndsAt)(slot))).get(userId);
|
|
4885
|
+
return this.reserveSlot(assignmentId, userId, slot, availability, options);
|
|
4886
|
+
}
|
|
4887
|
+
/**
|
|
4888
|
+
* The reservation itself, given availability already in hand.
|
|
4889
|
+
*
|
|
4890
|
+
* Split from `bookSlot` so the sweep can book from the one availability
|
|
4891
|
+
* read it made for the whole pass, rather than asking the host again per
|
|
4892
|
+
* candidate — the per-candidate round trip every other sweep in this
|
|
4893
|
+
* class is careful not to make.
|
|
4894
|
+
*/
|
|
4895
|
+
async reserveSlot(assignmentId, userId, slot, availability, options) {
|
|
4896
|
+
const startAt = slot.startAt;
|
|
4897
|
+
const endAt = (0, slot_1.slotEndsAt)(slot);
|
|
4898
|
+
const source = options?.source ?? 'manual';
|
|
4899
|
+
const blocking = AssignmentMatcher.coversSlot(availability?.blocked, startAt, endAt);
|
|
4900
|
+
if (!options?.force && blocking.length > 0) {
|
|
4901
|
+
return { booked: false, refusal: { reason: 'unavailable', detail: blocking[0].reason } };
|
|
4902
|
+
}
|
|
4903
|
+
const soft = AssignmentMatcher.coversSlot(availability?.warnings, startAt, endAt);
|
|
4904
|
+
const warnings = soft.length > 0 ? soft : undefined;
|
|
4905
|
+
const booking = {
|
|
4906
|
+
assignmentId,
|
|
4907
|
+
userId,
|
|
4908
|
+
startAt,
|
|
4909
|
+
endAt,
|
|
4910
|
+
bookedAt: Date.now(),
|
|
4911
|
+
source,
|
|
4912
|
+
...(warnings ? { warnings } : {}),
|
|
4913
|
+
};
|
|
4914
|
+
const result = await this.runBookSlot([this.slotBookingsKey, this.bookingSpansKey, this.keys.userBookings(userId)], [assignmentId, String(startAt), String(endAt), String(this.maxSlotSpanMs), JSON.stringify(booking)]);
|
|
4915
|
+
if (result[0] === 'already-booked') {
|
|
4916
|
+
return { booked: false, refusal: { reason: 'already-booked', holderId: result[1] } };
|
|
4917
|
+
}
|
|
4918
|
+
if (result[0] === 'clash') {
|
|
4919
|
+
return { booked: false, refusal: { reason: 'clash', clashingAssignmentId: result[1] } };
|
|
4920
|
+
}
|
|
4921
|
+
// The slot is spoken for; it no longer needs re-examining by the sweep.
|
|
4922
|
+
await this.redisClient.zRem(this.slotBookingDueAtKey, assignmentId);
|
|
4923
|
+
this.emitAssignmentLifecycle({
|
|
4924
|
+
kind: 'slotBooked',
|
|
4925
|
+
taskId: assignmentId,
|
|
4926
|
+
workerId: userId,
|
|
4927
|
+
startAt,
|
|
4928
|
+
endAt,
|
|
4929
|
+
source,
|
|
4930
|
+
...(warnings ? { warnings } : {}),
|
|
4931
|
+
at: booking.bookedAt,
|
|
4932
|
+
});
|
|
4933
|
+
return { booked: true, booking };
|
|
4934
|
+
}
|
|
4935
|
+
/** The booking held against an assignment, if any. */
|
|
4936
|
+
async getSlotBooking(assignmentId) {
|
|
4937
|
+
await this.readyPromise;
|
|
4938
|
+
const json = await this.redisClient.hGet(this.slotBookingsKey, assignmentId);
|
|
4939
|
+
if (!json)
|
|
4940
|
+
return null;
|
|
4941
|
+
try {
|
|
4942
|
+
return JSON.parse(json);
|
|
4943
|
+
}
|
|
4944
|
+
catch {
|
|
4945
|
+
return null;
|
|
4946
|
+
}
|
|
4947
|
+
}
|
|
4948
|
+
/**
|
|
4949
|
+
* Drop a reservation, leaving the assignment slotted but unbooked.
|
|
4950
|
+
*
|
|
4951
|
+
* Every terminal path calls this with `'terminal'` — the same rule the
|
|
4952
|
+
* wait clock and the SLA indexes carry, and for the same reason: a booking
|
|
4953
|
+
* row nobody clears goes on blocking that worker's 14:00 forever.
|
|
4954
|
+
*/
|
|
4955
|
+
async releaseSlotBooking(assignmentId, reason = 'operator', detail) {
|
|
4956
|
+
await this.readyPromise;
|
|
4957
|
+
const booking = await this.getSlotBooking(assignmentId);
|
|
4958
|
+
if (!booking)
|
|
4959
|
+
return null;
|
|
4960
|
+
const multi = this.redisClient
|
|
4961
|
+
.multi()
|
|
4962
|
+
.hDel(this.slotBookingsKey, assignmentId)
|
|
4963
|
+
.hDel(this.bookingSpansKey, assignmentId)
|
|
4964
|
+
.zRem(this.keys.userBookings(booking.userId), assignmentId);
|
|
4965
|
+
// A released booking goes back to the sweep, unless the task is over.
|
|
4966
|
+
if (reason !== 'terminal') {
|
|
4967
|
+
multi.zAdd(this.slotBookingDueAtKey, { score: Date.now(), value: assignmentId });
|
|
4968
|
+
}
|
|
4969
|
+
else {
|
|
4970
|
+
multi.zRem(this.slotBookingDueAtKey, assignmentId);
|
|
4971
|
+
}
|
|
4972
|
+
await multi.exec();
|
|
4973
|
+
this.emitAssignmentLifecycle({
|
|
4974
|
+
kind: 'slotBookingReleased',
|
|
4975
|
+
taskId: assignmentId,
|
|
4976
|
+
workerId: booking.userId,
|
|
4977
|
+
reason,
|
|
4978
|
+
...(detail ? { detail } : {}),
|
|
4979
|
+
at: Date.now(),
|
|
4980
|
+
});
|
|
4981
|
+
return booking;
|
|
4982
|
+
}
|
|
4983
|
+
/**
|
|
4984
|
+
* The worker raising a problem with an appointment booked onto them.
|
|
4985
|
+
*
|
|
4986
|
+
* They cannot *decline* it — the planner's decision stands, which is what
|
|
4987
|
+
* makes a published calendar worth trusting — but saying "not me" is not
|
|
4988
|
+
* declining, and a booking nobody will honour is worse than an unbooked
|
|
4989
|
+
* slot. The reservation is dropped and the worker is added to the
|
|
4990
|
+
* assignment's rejected set, so the next sweep cannot hand it straight
|
|
4991
|
+
* back to them.
|
|
4992
|
+
*/
|
|
4993
|
+
async handBackBooking(assignmentId, userId, reason) {
|
|
4994
|
+
await this.readyPromise;
|
|
4995
|
+
const booking = await this.getSlotBooking(assignmentId);
|
|
4996
|
+
if (!booking)
|
|
4997
|
+
return null;
|
|
4998
|
+
if (booking.userId !== userId) {
|
|
4999
|
+
throw new Error(`Assignment ${assignmentId} is not booked to ${userId}`);
|
|
5000
|
+
}
|
|
5001
|
+
await this.redisClient.sAdd(this.keys.userRejected(userId), assignmentId);
|
|
5002
|
+
return this.releaseSlotBooking(assignmentId, 'hand-back', reason);
|
|
5003
|
+
}
|
|
5004
|
+
/**
|
|
5005
|
+
* Bookings overlapping a window — the calendar read.
|
|
5006
|
+
*
|
|
5007
|
+
* Half-open on both sides: a booking that ends exactly at `from` or starts
|
|
5008
|
+
* exactly at `to` is outside the window, matching the overlap rule so a
|
|
5009
|
+
* day view and the clash probe cannot disagree about what "that day"
|
|
5010
|
+
* contains.
|
|
5011
|
+
*/
|
|
5012
|
+
async getBookings(query) {
|
|
5013
|
+
await this.readyPromise;
|
|
5014
|
+
const { from, to, userId } = query;
|
|
5015
|
+
let ids;
|
|
5016
|
+
if (userId) {
|
|
5017
|
+
// Reach back a full slot span: a booking that started before the
|
|
5018
|
+
// window can still be running inside it.
|
|
5019
|
+
ids = await this.redisClient.zRangeByScore(this.keys.userBookings(userId), Math.max(0, from - this.maxSlotSpanMs), `(${to}`);
|
|
5020
|
+
}
|
|
5021
|
+
else {
|
|
5022
|
+
ids = await this.redisClient.hKeys(this.slotBookingsKey);
|
|
5023
|
+
}
|
|
5024
|
+
if (ids.length === 0)
|
|
5025
|
+
return [];
|
|
5026
|
+
const records = await this.redisClient.hmGet(this.slotBookingsKey, ids);
|
|
5027
|
+
const bookings = [];
|
|
5028
|
+
for (const json of records) {
|
|
5029
|
+
if (!json)
|
|
5030
|
+
continue;
|
|
5031
|
+
try {
|
|
5032
|
+
const booking = JSON.parse(json);
|
|
5033
|
+
if (booking.startAt < to && booking.endAt > from)
|
|
5034
|
+
bookings.push(booking);
|
|
5035
|
+
}
|
|
5036
|
+
catch {
|
|
5037
|
+
// A corrupt row is not worth failing a calendar read over.
|
|
5038
|
+
}
|
|
5039
|
+
}
|
|
5040
|
+
bookings.sort((a, b) => a.startAt - b.startAt);
|
|
5041
|
+
return bookings;
|
|
5042
|
+
}
|
|
5043
|
+
/** Availability for a set of workers, as one batched call into the host. */
|
|
5044
|
+
async loadSlotAvailability(userIds, from, to) {
|
|
5045
|
+
const byUser = new Map();
|
|
5046
|
+
if (!this.slotAvailability || userIds.length === 0)
|
|
5047
|
+
return byUser;
|
|
5048
|
+
// The host's availability source being down is not a reason to book
|
|
5049
|
+
// over somebody's leave: an error here propagates, the sweep restores
|
|
5050
|
+
// its index entry and books nobody this pass.
|
|
5051
|
+
for (const row of await this.slotAvailability(userIds, from, to))
|
|
5052
|
+
byUser.set(row.userId, row);
|
|
5053
|
+
return byUser;
|
|
5054
|
+
}
|
|
5055
|
+
/**
|
|
5056
|
+
* Drop any reservation a task still carries as it reaches a terminal
|
|
5057
|
+
* state. Complete and fail do not go through `removeAssignment`, so
|
|
5058
|
+
* without this the worker's calendar keeps an appointment for work that
|
|
5059
|
+
* is over, and the hour stays blocked against anything else.
|
|
5060
|
+
*/
|
|
5061
|
+
async clearBookingOnTerminal(assignmentId) {
|
|
5062
|
+
const booking = AssignmentMatcher.parseBooking(await this.redisClient.hGet(this.slotBookingsKey, assignmentId));
|
|
5063
|
+
if (!booking)
|
|
5064
|
+
return;
|
|
5065
|
+
await this.redisClient
|
|
5066
|
+
.multi()
|
|
5067
|
+
.hDel(this.slotBookingsKey, assignmentId)
|
|
5068
|
+
.hDel(this.bookingSpansKey, assignmentId)
|
|
5069
|
+
.zRem(this.slotBookingDueAtKey, assignmentId)
|
|
5070
|
+
.zRem(this.keys.userBookings(booking.userId), assignmentId)
|
|
5071
|
+
.exec();
|
|
5072
|
+
this.emitAssignmentLifecycle({
|
|
5073
|
+
kind: 'slotBookingReleased',
|
|
5074
|
+
taskId: assignmentId,
|
|
5075
|
+
workerId: booking.userId,
|
|
5076
|
+
reason: 'terminal',
|
|
5077
|
+
at: Date.now(),
|
|
5078
|
+
});
|
|
5079
|
+
}
|
|
5080
|
+
static parseBooking(json) {
|
|
5081
|
+
if (!json)
|
|
5082
|
+
return null;
|
|
5083
|
+
try {
|
|
5084
|
+
return JSON.parse(json);
|
|
5085
|
+
}
|
|
5086
|
+
catch {
|
|
5087
|
+
return null;
|
|
5088
|
+
}
|
|
5089
|
+
}
|
|
5090
|
+
static coversSlot(intervals, startAt, endAt) {
|
|
5091
|
+
if (!intervals)
|
|
5092
|
+
return [];
|
|
5093
|
+
return intervals.filter((interval) => interval.from < endAt && interval.to > startAt);
|
|
5094
|
+
}
|
|
5095
|
+
/**
|
|
5096
|
+
* Who could take this appointment, best first.
|
|
5097
|
+
*
|
|
5098
|
+
* Ranking goes through the same `evaluateCandidateForAssignment` that
|
|
5099
|
+
* `explainMatch` uses, so routing weights, wildcards, zero-weight vetoes,
|
|
5100
|
+
* skill thresholds, CIDR and geo all apply. A second, smaller copy of the
|
|
5101
|
+
* judgement is how a booking and an explain start disagreeing.
|
|
5102
|
+
*
|
|
5103
|
+
* Two deliberate departures from live matching: backlog is not counted,
|
|
5104
|
+
* because a reservation takes no backlog place and somebody swamped today
|
|
5105
|
+
* may be the right person for next Thursday; and a pause is not counted
|
|
5106
|
+
* either, for the same reason — being away from the queue now says nothing
|
|
5107
|
+
* about a fortnight out.
|
|
5108
|
+
*/
|
|
5109
|
+
async rankSlotCandidates(assignmentId) {
|
|
5110
|
+
await this.readyPromise;
|
|
5111
|
+
const held = await this.loadSlottedAssignment(assignmentId);
|
|
5112
|
+
if (!held)
|
|
5113
|
+
throw new Error(`Assignment is not a slotted assignment awaiting its slot: ${assignmentId}`);
|
|
5114
|
+
const { assignment, slot } = held;
|
|
5115
|
+
const users = await this.loadUsers();
|
|
5116
|
+
if (users.length === 0)
|
|
5117
|
+
return [];
|
|
5118
|
+
const pass = await this.loadBookingPass(users, slot.startAt, (0, slot_1.slotEndsAt)(slot));
|
|
5119
|
+
return this.rankForSlot(assignment, slot, users, pass);
|
|
5120
|
+
}
|
|
5121
|
+
/** Every user, parsed once. */
|
|
5122
|
+
async loadUsers() {
|
|
5123
|
+
const all = await this.redisClient.hGetAll(this.usersKey);
|
|
5124
|
+
return Object.values(all).map((json) => JSON.parse(json));
|
|
5125
|
+
}
|
|
5126
|
+
/**
|
|
5127
|
+
* What one booking pass reads once and every slot in it shares: the
|
|
5128
|
+
* host's availability over the whole window, and the learning model.
|
|
5129
|
+
*/
|
|
5130
|
+
async loadBookingPass(users, from, to) {
|
|
5131
|
+
const [availability, modelWeights] = await Promise.all([
|
|
5132
|
+
this.loadSlotAvailability(users.map((user) => user.id), from, to),
|
|
5133
|
+
this.enableLearning ? this.learning.getModel() : Promise.resolve(undefined),
|
|
5134
|
+
]);
|
|
5135
|
+
return { availability, modelWeights };
|
|
5136
|
+
}
|
|
5137
|
+
async rankForSlot(assignment, slot, users, pass) {
|
|
5138
|
+
const assignmentId = assignment.id;
|
|
5139
|
+
const startAt = slot.startAt;
|
|
5140
|
+
const endAt = (0, slot_1.slotEndsAt)(slot);
|
|
5141
|
+
const { availability, modelWeights } = pass;
|
|
5142
|
+
const tagsCsv = assignment.tags.join(',');
|
|
5143
|
+
const basePriority = assignment.priority ?? 0;
|
|
5144
|
+
const rejected = await Promise.all(users.map((user) => this.redisClient.sIsMember(this.keys.userRejected(user.id), assignmentId)));
|
|
5145
|
+
const busy = await Promise.all(users.map((user) => this.findSlotClash(user.id, assignmentId, startAt, endAt)));
|
|
5146
|
+
const candidates = [];
|
|
5147
|
+
for (const [index, user] of users.entries()) {
|
|
5148
|
+
const trace = await this.evaluateCandidateForAssignment(user, assignment, tagsCsv, basePriority, modelWeights, {
|
|
5149
|
+
assignmentId,
|
|
5150
|
+
isRejected: Boolean(rejected[index]),
|
|
5151
|
+
backlog: 0,
|
|
5152
|
+
isPaused: false,
|
|
5153
|
+
});
|
|
5154
|
+
const blocked = AssignmentMatcher.coversSlot(availability.get(user.id)?.blocked, startAt, endAt);
|
|
5155
|
+
const warnings = AssignmentMatcher.coversSlot(availability.get(user.id)?.warnings, startAt, endAt);
|
|
5156
|
+
const clashingAssignmentId = busy[index];
|
|
5157
|
+
candidates.push({
|
|
5158
|
+
userId: user.id,
|
|
5159
|
+
score: trace.score,
|
|
5160
|
+
effectivePriority: trace.effectivePriority,
|
|
5161
|
+
bookable: trace.eligible && blocked.length === 0 && clashingAssignmentId === null,
|
|
5162
|
+
reasons: trace.reasons,
|
|
5163
|
+
...(clashingAssignmentId ? { clashingAssignmentId } : {}),
|
|
5164
|
+
...(blocked.length > 0 ? { blocked } : {}),
|
|
5165
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
5166
|
+
});
|
|
5167
|
+
}
|
|
5168
|
+
candidates.sort((a, b) => Number(b.bookable) - Number(a.bookable) ||
|
|
5169
|
+
b.effectivePriority - a.effectivePriority ||
|
|
5170
|
+
b.score - a.score ||
|
|
5171
|
+
a.userId.localeCompare(b.userId));
|
|
5172
|
+
return candidates;
|
|
5173
|
+
}
|
|
5174
|
+
/**
|
|
5175
|
+
* The id of a booking already on this worker that overlaps the window, or
|
|
5176
|
+
* null. Read-only: the authoritative answer is the Lua script's, this one
|
|
5177
|
+
* exists so the planner sees the clash before trying.
|
|
5178
|
+
*/
|
|
5179
|
+
async findSlotClash(userId, assignmentId, startAt, endAt) {
|
|
5180
|
+
const ids = await this.redisClient.zRangeByScore(this.keys.userBookings(userId), Math.max(0, startAt - this.maxSlotSpanMs), `(${endAt}`);
|
|
5181
|
+
const others = ids.filter((id) => id !== assignmentId);
|
|
5182
|
+
if (others.length === 0)
|
|
5183
|
+
return null;
|
|
5184
|
+
const spans = await this.redisClient.hmGet(this.bookingSpansKey, others);
|
|
5185
|
+
for (const [index, span] of spans.entries()) {
|
|
5186
|
+
if (!span)
|
|
5187
|
+
continue;
|
|
5188
|
+
const separator = span.indexOf(':');
|
|
5189
|
+
if (separator === -1)
|
|
5190
|
+
continue;
|
|
5191
|
+
const otherEnd = Number(span.slice(separator + 1));
|
|
5192
|
+
if (Number.isFinite(otherEnd) && otherEnd > startAt)
|
|
5193
|
+
return others[index];
|
|
5194
|
+
}
|
|
5195
|
+
return null;
|
|
5196
|
+
}
|
|
5197
|
+
/**
|
|
5198
|
+
* Sweep the booking clocks: reserve a worker for every slotted assignment
|
|
5199
|
+
* whose book-ahead window has opened.
|
|
5200
|
+
*
|
|
5201
|
+
* Runs before `processScheduledAssignments()` so a slot booked in this
|
|
5202
|
+
* pass is activated onto its holder in the same pass when its start has
|
|
5203
|
+
* already arrived. Each zset entry fires once — the `zRem` claim makes
|
|
5204
|
+
* concurrent replicas skip entries another sweep already took — and a slot
|
|
5205
|
+
* nobody can take is re-indexed `slotBookingRetryMs` out, so it books
|
|
5206
|
+
* itself once a clashing job moves or an absence is cancelled.
|
|
5207
|
+
*
|
|
5208
|
+
* The sweep commits no learning decision and consumes no learned
|
|
5209
|
+
* re-ranking, for the same reason `assignToUser` does not: nobody was
|
|
5210
|
+
* offered anything and nobody chose.
|
|
5211
|
+
*/
|
|
5212
|
+
async processSlotBookings() {
|
|
5213
|
+
await this.readyPromise;
|
|
5214
|
+
const now = Date.now();
|
|
5215
|
+
let booked = 0;
|
|
5216
|
+
let unfillable = 0;
|
|
5217
|
+
const dueIds = await this.redisClient.zRangeByScore(this.slotBookingDueAtKey, '-inf', now);
|
|
5218
|
+
if (dueIds.length === 0)
|
|
5219
|
+
return { booked, unfillable };
|
|
5220
|
+
// Claim first, then read once for the whole pass: the host is asked
|
|
5221
|
+
// for availability one time over the union of every due slot, not once
|
|
5222
|
+
// per slot and again per candidate. Claims that turn out to be stale
|
|
5223
|
+
// (activated, removed, already booked) are simply dropped.
|
|
5224
|
+
const due = [];
|
|
5225
|
+
for (const id of dueIds) {
|
|
5226
|
+
const claimed = await this.redisClient.zRem(this.slotBookingDueAtKey, id);
|
|
5227
|
+
if (!claimed)
|
|
5228
|
+
continue;
|
|
5229
|
+
const held = await this.loadSlottedAssignment(id);
|
|
5230
|
+
if (!held)
|
|
5231
|
+
continue;
|
|
5232
|
+
if (await this.redisClient.hExists(this.slotBookingsKey, id))
|
|
5233
|
+
continue;
|
|
5234
|
+
due.push({ id, ...held });
|
|
5235
|
+
}
|
|
5236
|
+
if (due.length === 0)
|
|
5237
|
+
return { booked, unfillable };
|
|
5238
|
+
const restore = async () => {
|
|
5239
|
+
// Without restoring the index entries a failed pass strands every
|
|
5240
|
+
// slot in it unbooked forever — nothing else re-examines them.
|
|
5241
|
+
for (const entry of due) {
|
|
5242
|
+
await this.redisClient.zAdd(this.slotBookingDueAtKey, { score: now, value: entry.id });
|
|
5243
|
+
}
|
|
5244
|
+
};
|
|
5245
|
+
let users;
|
|
5246
|
+
let pass;
|
|
5247
|
+
try {
|
|
5248
|
+
users = await this.loadUsers();
|
|
5249
|
+
pass = await this.loadBookingPass(users, Math.min(...due.map((entry) => entry.slot.startAt)), Math.max(...due.map((entry) => (0, slot_1.slotEndsAt)(entry.slot))));
|
|
5250
|
+
}
|
|
5251
|
+
catch (err) {
|
|
5252
|
+
await restore();
|
|
5253
|
+
throw err;
|
|
5254
|
+
}
|
|
5255
|
+
for (const { id, assignment, slot } of due) {
|
|
5256
|
+
const candidates = users.length === 0 ? [] : await this.rankForSlot(assignment, slot, users, pass);
|
|
5257
|
+
let placed = false;
|
|
5258
|
+
for (const candidate of candidates) {
|
|
5259
|
+
if (!candidate.bookable)
|
|
5260
|
+
break;
|
|
5261
|
+
const result = await this.reserveSlot(id, candidate.userId, slot, pass.availability.get(candidate.userId), {
|
|
5262
|
+
source: 'sweep',
|
|
5263
|
+
});
|
|
5264
|
+
if (result.booked) {
|
|
5265
|
+
booked++;
|
|
5266
|
+
placed = true;
|
|
5267
|
+
break;
|
|
5268
|
+
}
|
|
5269
|
+
// Lost the race to a concurrent sweep, or this worker was
|
|
5270
|
+
// booked for something else between the rank and the write.
|
|
5271
|
+
if (result.refusal.reason === 'already-booked') {
|
|
5272
|
+
placed = true;
|
|
5273
|
+
break;
|
|
5274
|
+
}
|
|
5275
|
+
}
|
|
5276
|
+
if (!placed) {
|
|
5277
|
+
unfillable++;
|
|
5278
|
+
await this.redisClient.zAdd(this.slotBookingDueAtKey, {
|
|
5279
|
+
score: now + this.slotBookingRetryMs,
|
|
5280
|
+
value: id,
|
|
5281
|
+
});
|
|
5282
|
+
this.emitAssignmentLifecycle({
|
|
5283
|
+
kind: 'slotUnfillable',
|
|
5284
|
+
taskId: id,
|
|
5285
|
+
startAt: slot.startAt,
|
|
5286
|
+
endAt: (0, slot_1.slotEndsAt)(slot),
|
|
5287
|
+
at: now,
|
|
5288
|
+
});
|
|
5289
|
+
}
|
|
5290
|
+
}
|
|
5291
|
+
return { booked, unfillable };
|
|
5292
|
+
}
|
|
3981
5293
|
/**
|
|
3982
5294
|
* Assignments held out of matching because their escalation ladder was
|
|
3983
5295
|
* exhausted under `onExhausted: 'park'` — nobody answered, all the way up.
|
|
@@ -4012,14 +5324,15 @@ class AssignmentMatcher {
|
|
|
4012
5324
|
* Occurrences fire with sweep granularity: `startMaintenance()` /
|
|
4013
5325
|
* `runMaintenanceOnce()` / `processRecurringAssignments()`.
|
|
4014
5326
|
*
|
|
4015
|
-
* @throws when `recurrence` is unusable (`everyMs` missing
|
|
4016
|
-
* or `until` before
|
|
5327
|
+
* @throws when `recurrence` is unusable (`everyMs` missing, the gap between
|
|
5328
|
+
* occurrences — `everyMs / times` — under 1000, or `until` before
|
|
5329
|
+
* `startAt`)
|
|
4017
5330
|
*/
|
|
4018
5331
|
async addRecurringAssignment(template) {
|
|
4019
5332
|
await this.readyPromise;
|
|
4020
5333
|
const policy = (0, recurrence_1.normalizeRecurrencePolicy)(template.recurrence);
|
|
4021
5334
|
if (!policy) {
|
|
4022
|
-
throw new Error(`addRecurringAssignment: recurrence needs everyMs >= ${recurrence_1.MIN_EVERY_MS} and a satisfiable until/startAt`);
|
|
5335
|
+
throw new Error(`addRecurringAssignment: recurrence needs everyMs / times >= ${recurrence_1.MIN_EVERY_MS} and a satisfiable until/startAt`);
|
|
4023
5336
|
}
|
|
4024
5337
|
const existingJson = await this.redisClient.hGet(this.recurringAssignmentsKey, template.id);
|
|
4025
5338
|
const existing = existingJson ? JSON.parse(existingJson) : null;
|
|
@@ -4309,6 +5622,8 @@ class AssignmentMatcher {
|
|
|
4309
5622
|
let recurrenceMaterializations = 0;
|
|
4310
5623
|
let recurrenceRetirements = 0;
|
|
4311
5624
|
let retentionPurged = 0;
|
|
5625
|
+
let slotsBooked = 0;
|
|
5626
|
+
let slotsUnfillable = 0;
|
|
4312
5627
|
// Recurrence before schedule: an occurrence materialized due-now is
|
|
4313
5628
|
// then activated by the schedule sweep in this same tick.
|
|
4314
5629
|
if (opts.recurrence) {
|
|
@@ -4316,6 +5631,14 @@ class AssignmentMatcher {
|
|
|
4316
5631
|
recurrenceMaterializations = result.materialized;
|
|
4317
5632
|
recurrenceRetirements = result.retired;
|
|
4318
5633
|
}
|
|
5634
|
+
// Bookings before schedule: a slot booked in this pass is handed to
|
|
5635
|
+
// its holder by the activation below in the same tick, rather than
|
|
5636
|
+
// spending one tick in the open pool first.
|
|
5637
|
+
if (opts.slotBookings) {
|
|
5638
|
+
const result = await this.processSlotBookings();
|
|
5639
|
+
slotsBooked = result.booked;
|
|
5640
|
+
slotsUnfillable = result.unfillable;
|
|
5641
|
+
}
|
|
4319
5642
|
// Schedule first: a just-activated assignment's response/SLA clocks
|
|
4320
5643
|
// then start from this same tick's state.
|
|
4321
5644
|
if (opts.scheduled) {
|
|
@@ -4357,6 +5680,8 @@ class AssignmentMatcher {
|
|
|
4357
5680
|
recurrenceMaterializations,
|
|
4358
5681
|
recurrenceRetirements,
|
|
4359
5682
|
retentionPurged,
|
|
5683
|
+
slotsBooked,
|
|
5684
|
+
slotsUnfillable,
|
|
4360
5685
|
tookMs: Date.now() - startedAt,
|
|
4361
5686
|
};
|
|
4362
5687
|
}
|
|
@@ -4402,6 +5727,7 @@ class AssignmentMatcher {
|
|
|
4402
5727
|
completionDeadlines: options?.completionDeadlines ?? true,
|
|
4403
5728
|
slaExpiries: options?.slaExpiries ?? true,
|
|
4404
5729
|
scheduled: options?.scheduled ?? true,
|
|
5730
|
+
slotBookings: options?.slotBookings ?? true,
|
|
4405
5731
|
recurrence: options?.recurrence ?? true,
|
|
4406
5732
|
workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
|
|
4407
5733
|
idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
|