assignment-user-matcher 1.10.0 → 1.11.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 +59 -10
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/learning/auto-weights.d.ts +7 -4
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +7 -6
- package/dist/lua/workflow-transition.lua +8 -2
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +47 -0
- package/dist/managers/WorkflowManager.d.ts +7 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +85 -12
- package/dist/matcher.class.d.ts +35 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +308 -76
- package/dist/queries/users.d.ts +34 -0
- package/dist/queries/users.d.ts.map +1 -0
- package/dist/queries/users.js +227 -0
- package/dist/scheduling/constraints/availability.d.ts +0 -1
- package/dist/scheduling/constraints/availability.d.ts.map +1 -1
- package/dist/scheduling/constraints/availability.js +27 -4
- package/dist/scheduling/constraints/contract.d.ts.map +1 -1
- package/dist/scheduling/constraints/contract.js +17 -3
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/daily-rest.js +7 -2
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -1
- package/dist/scheduling/constraints/hour-budget.js +7 -1
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -1
- package/dist/scheduling/constraints/in-shift-breaks.js +4 -2
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/min-rest.js +8 -19
- package/dist/scheduling/constraints/night-work.js +17 -1
- package/dist/scheduling/constraints/no-overlap.d.ts +5 -1
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -1
- package/dist/scheduling/constraints/no-overlap.js +11 -12
- package/dist/scheduling/constraints/weekly-rest.js +12 -1
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +7 -0
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +1 -0
- package/dist/scheduling/time.d.ts +6 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +20 -9
- package/dist/scheduling/types.d.ts +6 -0
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +71 -2
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +1 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/package.json +1 -1
package/dist/matcher.class.js
CHANGED
|
@@ -7,6 +7,7 @@ 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 users_1 = require("./queries/users");
|
|
10
11
|
const match_score_1 = require("./scoring/match-score");
|
|
11
12
|
const fair_arbitration_1 = require("./scoring/fair-arbitration");
|
|
12
13
|
const policy_1 = require("./escalation/policy");
|
|
@@ -297,7 +298,9 @@ class AssignmentMatcher {
|
|
|
297
298
|
async loadLuaScripts() {
|
|
298
299
|
try {
|
|
299
300
|
this.luaScriptSha = await this.redisClient.scriptLoad(WORKFLOW_TRANSITION_LUA);
|
|
300
|
-
|
|
301
|
+
// The source rides along so a NOSCRIPT after a Redis restart can
|
|
302
|
+
// be answered with a re-load instead of bricking every transition.
|
|
303
|
+
this.workflow.setLuaScriptSha(this.luaScriptSha, WORKFLOW_TRANSITION_LUA);
|
|
301
304
|
}
|
|
302
305
|
catch (err) {
|
|
303
306
|
console.error('Failed to load Lua scripts:', err);
|
|
@@ -1126,7 +1129,13 @@ class AssignmentMatcher {
|
|
|
1126
1129
|
const existingForSynthesis = user.routingWeights
|
|
1127
1130
|
? Object.fromEntries(Object.entries(user.routingWeights).filter(([tag]) => !(tag in previousLearned)))
|
|
1128
1131
|
: undefined;
|
|
1129
|
-
|
|
1132
|
+
// The user's own declared tags are always known: once the sync
|
|
1133
|
+
// installs a routingWeights map, only positive entries match, so a
|
|
1134
|
+
// declared tag the learner has no data for would silently stop
|
|
1135
|
+
// matching forever. Including it here gives it the exploration
|
|
1136
|
+
// prior instead.
|
|
1137
|
+
const userKnownTags = [...new Set([...(knownTags ?? []), ...(user.tags ?? [])])];
|
|
1138
|
+
const learned = await this.learning.getLearnedRoutingWeights(id, userKnownTags.length > 0 ? userKnownTags : undefined, existingForSynthesis);
|
|
1130
1139
|
if (Object.keys(learned).length === 0)
|
|
1131
1140
|
continue;
|
|
1132
1141
|
// Apply per-sync step clamp. Vetoes (weight 0) that passed the
|
|
@@ -1164,7 +1173,11 @@ class AssignmentMatcher {
|
|
|
1164
1173
|
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
1165
1174
|
...user,
|
|
1166
1175
|
routingWeights,
|
|
1167
|
-
|
|
1176
|
+
// `null` (not undefined) for a previously weightless user:
|
|
1177
|
+
// undefined is dropped by JSON, which made the sync
|
|
1178
|
+
// irreversible for exactly the tag-based users it affects
|
|
1179
|
+
// the most. Revert restores tag-based matching from null.
|
|
1180
|
+
routingWeightsSnapshot: user.routingWeights ?? null,
|
|
1168
1181
|
learnedRoutingWeights: clampedLearned,
|
|
1169
1182
|
learnedRoutingWeightsSyncedAt: Date.now(),
|
|
1170
1183
|
}));
|
|
@@ -1189,7 +1202,7 @@ class AssignmentMatcher {
|
|
|
1189
1202
|
for (const [id, json] of Object.entries(all)) {
|
|
1190
1203
|
try {
|
|
1191
1204
|
const u = JSON.parse(json);
|
|
1192
|
-
if (u.routingWeightsSnapshot)
|
|
1205
|
+
if (u.routingWeightsSnapshot !== undefined)
|
|
1193
1206
|
targets.push(id);
|
|
1194
1207
|
}
|
|
1195
1208
|
catch {
|
|
@@ -1203,11 +1216,13 @@ class AssignmentMatcher {
|
|
|
1203
1216
|
if (!userJson)
|
|
1204
1217
|
continue;
|
|
1205
1218
|
const user = JSON.parse(userJson);
|
|
1206
|
-
|
|
1219
|
+
// A `null` snapshot means "had no routingWeights before the sync"
|
|
1220
|
+
// — reverting restores tag-based matching by dropping the map.
|
|
1221
|
+
if (user.routingWeightsSnapshot === undefined)
|
|
1207
1222
|
continue;
|
|
1208
1223
|
await this.redisClient.hSet(this.usersKey, id, JSON.stringify({
|
|
1209
1224
|
...user,
|
|
1210
|
-
routingWeights: user.routingWeightsSnapshot,
|
|
1225
|
+
routingWeights: user.routingWeightsSnapshot ?? undefined,
|
|
1211
1226
|
routingWeightsSnapshot: undefined,
|
|
1212
1227
|
learnedRoutingWeights: undefined,
|
|
1213
1228
|
learnedRoutingWeightsSyncedAt: undefined,
|
|
@@ -1255,7 +1270,10 @@ class AssignmentMatcher {
|
|
|
1255
1270
|
}
|
|
1256
1271
|
/** All known tags except the internal 'default' tag (for exploration priors) */
|
|
1257
1272
|
async getKnownTagsForAutoWeights() {
|
|
1258
|
-
|
|
1273
|
+
// allTags is a ZSET (zAdd in enqueueAssignment, zRangeByLex in wildcard
|
|
1274
|
+
// expansion) — an SMEMBERS read threw WRONGTYPE on any deployment that
|
|
1275
|
+
// had ever enqueued an assignment.
|
|
1276
|
+
const tags = await this.redisClient.zRange(this.allTagsKey, 0, -1);
|
|
1259
1277
|
return tags.filter((t) => t !== 'default');
|
|
1260
1278
|
}
|
|
1261
1279
|
// ============================================================================
|
|
@@ -1398,12 +1416,26 @@ class AssignmentMatcher {
|
|
|
1398
1416
|
const assignmentPriorityKey = this.keys.assignmentPriority(id);
|
|
1399
1417
|
const assignmentTagsKey = this.keys.assignmentTags(id);
|
|
1400
1418
|
const assignmentGeoKey = this.keys.assignmentsGeo();
|
|
1401
|
-
// Fetch tags, owner (in case it's pending),
|
|
1402
|
-
|
|
1419
|
+
// Fetch tags, owner (in case it's pending), accepted JSON (for the
|
|
1420
|
+
// per-user accepted index), and vetoed users for index cleanup
|
|
1421
|
+
const [tagsCsv, owner, acceptedJson, vetoedUsers] = await Promise.all([
|
|
1403
1422
|
this.redisClient.hGet(assignmentTagsKey, 'tags'),
|
|
1404
1423
|
this.redisClient.hGet(this.assignmentOwnerKey, id),
|
|
1424
|
+
this.redisClient.hGet(this.acceptedAssignmentsKey, id),
|
|
1405
1425
|
this.redisClient.sMembers(this.keys.assignmentVetoed(id)),
|
|
1406
1426
|
]);
|
|
1427
|
+
// Best-effort owner of the accepted record: only SLA-bearing items
|
|
1428
|
+
// carry _acceptedBy, so a non-SLA accepted assignment leaves a stale
|
|
1429
|
+
// per-user index member here — reads filter it out and self-heal.
|
|
1430
|
+
let acceptedBy = null;
|
|
1431
|
+
if (acceptedJson && acceptedJson.indexOf('"sla"') !== -1) {
|
|
1432
|
+
try {
|
|
1433
|
+
acceptedBy = JSON.parse(acceptedJson)[policy_2.SLA_ACCEPTED_BY_FIELD] ?? null;
|
|
1434
|
+
}
|
|
1435
|
+
catch {
|
|
1436
|
+
// keep null on parse failure
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1407
1439
|
let tags = [];
|
|
1408
1440
|
if (tagsCsv && tagsCsv.length > 0) {
|
|
1409
1441
|
tags = tagsCsv.split(',');
|
|
@@ -1432,6 +1464,9 @@ class AssignmentMatcher {
|
|
|
1432
1464
|
}
|
|
1433
1465
|
// 3. Remove from Accepted state
|
|
1434
1466
|
multi.hDel(this.acceptedAssignmentsKey, id);
|
|
1467
|
+
if (acceptedBy) {
|
|
1468
|
+
multi.zRem(this.keys.userAcceptedAssignments(acceptedBy), id);
|
|
1469
|
+
}
|
|
1435
1470
|
// 4. Clear SLA indexes (no-ops for non-SLA assignments)
|
|
1436
1471
|
multi.zRem(this.acceptedAssignmentsExpiryKey, id);
|
|
1437
1472
|
multi.zRem(this.assignmentsSlaExpiryKey, id);
|
|
@@ -1449,6 +1484,7 @@ class AssignmentMatcher {
|
|
|
1449
1484
|
.del(this.keys.userAssignments(userId))
|
|
1450
1485
|
.del(this.keys.userRejected(userId))
|
|
1451
1486
|
.del(this.keys.userVetoed(userId))
|
|
1487
|
+
.del(this.keys.userAcceptedAssignments(userId))
|
|
1452
1488
|
.zRem(this.keys.userActivity(), userId)
|
|
1453
1489
|
.sRem(this.keys.pausedUsers(), userId)
|
|
1454
1490
|
.hDel(this.usersKey, userId);
|
|
@@ -1480,11 +1516,58 @@ class AssignmentMatcher {
|
|
|
1480
1516
|
let cursor = '0';
|
|
1481
1517
|
do {
|
|
1482
1518
|
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1483
|
-
|
|
1519
|
+
for (const entry of entries) {
|
|
1520
|
+
try {
|
|
1521
|
+
users.push(JSON.parse(entry.value));
|
|
1522
|
+
}
|
|
1523
|
+
catch {
|
|
1524
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1484
1527
|
cursor = nextCursor;
|
|
1485
1528
|
} while (cursor !== '0');
|
|
1486
1529
|
return users;
|
|
1487
1530
|
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Paginated user query with composable status/workload filters
|
|
1533
|
+
* (`status`, `idleForMs`, `hasBacklog`, `atCapacity`). All reads are
|
|
1534
|
+
* bounded: the users hash is paged with HSCAN and per-page metadata is
|
|
1535
|
+
* batched into one multi(). A scan page is never split, so a page may
|
|
1536
|
+
* exceed `limit` by less than one scan page, and filtered scans may
|
|
1537
|
+
* return short pages with `hasMore: true` — keep consuming until
|
|
1538
|
+
* `hasMore` is false. `status: 'idle'` without an explicit `idleForMs`
|
|
1539
|
+
* falls back to the matcher's `idleUserTimeoutMs` (matches nobody when
|
|
1540
|
+
* that is not configured either).
|
|
1541
|
+
*/
|
|
1542
|
+
async getUsersPaginated(options) {
|
|
1543
|
+
await this.readyPromise;
|
|
1544
|
+
const resolved = options ? { ...options } : undefined;
|
|
1545
|
+
if (resolved && resolved.idleForMs === undefined && resolved.status === 'idle' && this.idleUserTimeoutMs !== null) {
|
|
1546
|
+
resolved.idleForMs = this.idleUserTimeoutMs;
|
|
1547
|
+
}
|
|
1548
|
+
return (0, users_1.getUsersPaginatedFromStore)(this.redisClient, this.keys, resolved, (user) => this.backlogLimitFor(user));
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* Order-preserving workload summaries for a known set of user ids
|
|
1552
|
+
* (chunked pipelined reads). Missing or corrupt user records are omitted.
|
|
1553
|
+
*/
|
|
1554
|
+
async getUserSummaries(userIds) {
|
|
1555
|
+
await this.readyPromise;
|
|
1556
|
+
return (0, users_1.getUserSummariesBatch)(this.redisClient, this.keys, userIds, (user) => this.backlogLimitFor(user));
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* A user's accepted (in-progress) assignments, newest first, backed by
|
|
1560
|
+
* the per-user accepted index. Verified against the accepted store, so
|
|
1561
|
+
* stale index members (e.g. left by a `removeAssignment` on a non-SLA
|
|
1562
|
+
* assignment, or by an older library version) are dropped and self-healed.
|
|
1563
|
+
*
|
|
1564
|
+
* Note: the index is maintained from the version that introduced it —
|
|
1565
|
+
* accepted work that predates it appears only after it cycles.
|
|
1566
|
+
*/
|
|
1567
|
+
async getActiveAssignmentsForUser(userId) {
|
|
1568
|
+
await this.readyPromise;
|
|
1569
|
+
return (0, users_1.getActiveAssignmentsFromStore)(this.redisClient, this.keys, userId);
|
|
1570
|
+
}
|
|
1488
1571
|
// ============================================================================
|
|
1489
1572
|
// Worker Availability (pause/resume)
|
|
1490
1573
|
// ============================================================================
|
|
@@ -1601,15 +1684,35 @@ class AssignmentMatcher {
|
|
|
1601
1684
|
let cursor = '0';
|
|
1602
1685
|
do {
|
|
1603
1686
|
const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.usersKey, cursor, { COUNT: 500 });
|
|
1604
|
-
|
|
1687
|
+
for (const entry of entries) {
|
|
1688
|
+
try {
|
|
1689
|
+
users.push(JSON.parse(entry.value));
|
|
1690
|
+
}
|
|
1691
|
+
catch {
|
|
1692
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1605
1695
|
cursor = nextCursor;
|
|
1606
1696
|
} while (cursor !== '0');
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1697
|
+
// Chunked pipelined backlog reads — one multi() per 500 users keeps
|
|
1698
|
+
// pipelines bounded when the pool grows.
|
|
1699
|
+
const perUser = [];
|
|
1700
|
+
for (let start = 0; start < users.length; start += 500) {
|
|
1701
|
+
const chunk = users.slice(start, start + 500);
|
|
1702
|
+
const multi = this.redisClient.multi();
|
|
1703
|
+
for (const user of chunk) {
|
|
1704
|
+
multi.sCard(this.keys.userAssignments(user.id));
|
|
1705
|
+
}
|
|
1706
|
+
const backlogs = (await multi.exec());
|
|
1707
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1708
|
+
perUser.push({
|
|
1709
|
+
userId: chunk[i].id,
|
|
1710
|
+
backlog: Number(backlogs[i] ?? 0),
|
|
1711
|
+
maxBacklogSize: this.backlogLimitFor(chunk[i]),
|
|
1712
|
+
paused: paused.has(chunk[i].id),
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1613
1716
|
perUser.sort((a, b) => a.userId.localeCompare(b.userId));
|
|
1614
1717
|
return {
|
|
1615
1718
|
queued: counts.queued,
|
|
@@ -1621,43 +1724,79 @@ class AssignmentMatcher {
|
|
|
1621
1724
|
}
|
|
1622
1725
|
/**
|
|
1623
1726
|
* Get all pending assignments with owner and pending duration metadata.
|
|
1727
|
+
* Reads are bounded: the pending hash is paged with HSCAN and each page's
|
|
1728
|
+
* owner/expiry lookups are batched. Pass `{ limit }` (clamped to 1000) to
|
|
1729
|
+
* hydrate only the top-N longest-pending assignments instead of every one.
|
|
1624
1730
|
*/
|
|
1625
|
-
async getPendingAssignmentsWithAge() {
|
|
1731
|
+
async getPendingAssignmentsWithAge(options) {
|
|
1626
1732
|
await this.readyPromise;
|
|
1627
1733
|
const now = Date.now();
|
|
1628
|
-
const
|
|
1629
|
-
|
|
1630
|
-
|
|
1734
|
+
const metas = [];
|
|
1735
|
+
// HSCAN may repeat a field across pages under a concurrent rehash;
|
|
1736
|
+
// the listing must not repeat an assignment.
|
|
1737
|
+
const seen = new Set();
|
|
1738
|
+
let cursor = '0';
|
|
1739
|
+
do {
|
|
1740
|
+
const { cursor: nextCursor, entries: rawEntries } = await this.redisClient.hScan(this.pendingAssignmentsKey, cursor, { COUNT: 500 });
|
|
1741
|
+
cursor = nextCursor;
|
|
1742
|
+
const entries = rawEntries.filter((entry) => !seen.has(entry.field));
|
|
1743
|
+
if (entries.length === 0)
|
|
1744
|
+
continue;
|
|
1745
|
+
for (const entry of entries)
|
|
1746
|
+
seen.add(entry.field);
|
|
1747
|
+
const pageIds = entries.map((entry) => entry.field);
|
|
1748
|
+
const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, pageIds);
|
|
1749
|
+
const multi = this.redisClient.multi();
|
|
1750
|
+
for (const id of pageIds) {
|
|
1751
|
+
multi.zScore(this.pendingAssignmentsExpiryKey, id);
|
|
1752
|
+
}
|
|
1753
|
+
const expiryScores = (await multi.exec());
|
|
1754
|
+
for (let i = 0; i < entries.length; i++) {
|
|
1755
|
+
const json = entries[i].value;
|
|
1756
|
+
if (!json)
|
|
1757
|
+
continue;
|
|
1758
|
+
const score = expiryScores[i];
|
|
1759
|
+
const expiresAt = score === null || score === undefined ? null : Number(score);
|
|
1760
|
+
const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
|
|
1761
|
+
const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
|
|
1762
|
+
metas.push({ json, ownerId: owners[i] ?? null, pendingForMs, pendingSince, expiresAt });
|
|
1763
|
+
}
|
|
1764
|
+
} while (cursor !== '0');
|
|
1765
|
+
if (metas.length === 0) {
|
|
1631
1766
|
return [];
|
|
1632
1767
|
}
|
|
1633
|
-
const
|
|
1634
|
-
this.redisClient.hmGet(this.assignmentOwnerKey, assignmentIds),
|
|
1635
|
-
Promise.all(assignmentIds.map((id) => this.redisClient.zScore(this.pendingAssignmentsExpiryKey, id))),
|
|
1636
|
-
]);
|
|
1637
|
-
const results = [];
|
|
1638
|
-
for (let i = 0; i < assignmentIds.length; i++) {
|
|
1639
|
-
const id = assignmentIds[i];
|
|
1640
|
-
const json = pendingEntries[id];
|
|
1641
|
-
if (!json)
|
|
1642
|
-
continue;
|
|
1643
|
-
let assignment;
|
|
1768
|
+
const hydrate = (meta) => {
|
|
1644
1769
|
try {
|
|
1645
|
-
|
|
1770
|
+
return {
|
|
1771
|
+
assignment: JSON.parse(meta.json),
|
|
1772
|
+
ownerId: meta.ownerId,
|
|
1773
|
+
pendingForMs: meta.pendingForMs,
|
|
1774
|
+
pendingSince: meta.pendingSince,
|
|
1775
|
+
expiresAt: meta.expiresAt,
|
|
1776
|
+
};
|
|
1646
1777
|
}
|
|
1647
1778
|
catch {
|
|
1648
|
-
|
|
1779
|
+
return null;
|
|
1649
1780
|
}
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1781
|
+
};
|
|
1782
|
+
const limit = options?.limit;
|
|
1783
|
+
if (typeof limit === 'number' && Number.isFinite(limit)) {
|
|
1784
|
+
// Sort the (small) metadata first, then hydrate only the top N.
|
|
1785
|
+
const clamped = Math.max(1, Math.min(Math.floor(limit), 1000));
|
|
1786
|
+
const top = [...metas].sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1)).slice(0, clamped);
|
|
1787
|
+
const results = [];
|
|
1788
|
+
for (const meta of top) {
|
|
1789
|
+
const hydrated = hydrate(meta);
|
|
1790
|
+
if (hydrated)
|
|
1791
|
+
results.push(hydrated);
|
|
1792
|
+
}
|
|
1793
|
+
return results;
|
|
1794
|
+
}
|
|
1795
|
+
const results = [];
|
|
1796
|
+
for (const meta of metas) {
|
|
1797
|
+
const hydrated = hydrate(meta);
|
|
1798
|
+
if (hydrated)
|
|
1799
|
+
results.push(hydrated);
|
|
1661
1800
|
}
|
|
1662
1801
|
results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
|
|
1663
1802
|
return results;
|
|
@@ -1756,12 +1895,23 @@ class AssignmentMatcher {
|
|
|
1756
1895
|
return { id, priority };
|
|
1757
1896
|
}
|
|
1758
1897
|
async setAssignmentPriorityByTags(tags, priority) {
|
|
1759
|
-
// Update priorities for
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1898
|
+
// Update priorities for QUEUED assignments that include any of the
|
|
1899
|
+
// specified tags. Pending/accepted assignments left the matching
|
|
1900
|
+
// indexes at claim time — re-zAdding them here would resurrect
|
|
1901
|
+
// permanent ghost candidates that crowd real work out of the batch.
|
|
1902
|
+
const queued = await this.redisClient.hGetAll(this.assignmentsRefKey);
|
|
1903
|
+
const relevantAssignments = [];
|
|
1904
|
+
for (const json of Object.values(queued)) {
|
|
1905
|
+
try {
|
|
1906
|
+
const assignment = JSON.parse(json);
|
|
1907
|
+
const assignmentTagSet = new Set(assignment.tags);
|
|
1908
|
+
if (tags.some((tag) => assignmentTagSet.has(tag)))
|
|
1909
|
+
relevantAssignments.push(assignment);
|
|
1910
|
+
}
|
|
1911
|
+
catch {
|
|
1912
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1765
1915
|
if (relevantAssignments.length > 0) {
|
|
1766
1916
|
const multi = this.redisClient.multi();
|
|
1767
1917
|
for (const assignment of relevantAssignments) {
|
|
@@ -1778,6 +1928,23 @@ class AssignmentMatcher {
|
|
|
1778
1928
|
}
|
|
1779
1929
|
}
|
|
1780
1930
|
await multi.exec();
|
|
1931
|
+
// The snapshot read above races the atomic claim gate (same
|
|
1932
|
+
// pattern as setAssignmentPriority): undo any ghost the writes
|
|
1933
|
+
// resurrected for assignments claimed since the read.
|
|
1934
|
+
const ids = relevantAssignments.map((a) => a.id);
|
|
1935
|
+
const owners = await this.redisClient.hmGet(this.assignmentOwnerKey, ids);
|
|
1936
|
+
const ghosts = relevantAssignments.filter((_, i) => owners[i]);
|
|
1937
|
+
if (ghosts.length > 0) {
|
|
1938
|
+
const cleanup = this.redisClient.multi();
|
|
1939
|
+
for (const assignment of ghosts) {
|
|
1940
|
+
cleanup.zRem(this.assignmentsKey, assignment.id);
|
|
1941
|
+
const idxTags = [...assignment.tags, ...(this.enableDefaultMatching ? ['default'] : [])];
|
|
1942
|
+
for (const tag of idxTags) {
|
|
1943
|
+
cleanup.zRem(this.keys.tagAssignments(tag), assignment.id);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
await cleanup.exec();
|
|
1947
|
+
}
|
|
1781
1948
|
}
|
|
1782
1949
|
return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
|
|
1783
1950
|
}
|
|
@@ -1807,17 +1974,25 @@ class AssignmentMatcher {
|
|
|
1807
1974
|
const own = user.maxBacklogSize;
|
|
1808
1975
|
return typeof own === 'number' && Number.isFinite(own) && own >= 0 ? own : this.maxUserBacklogSize;
|
|
1809
1976
|
}
|
|
1810
|
-
async computeCandidatesForUser(user, capToBacklog = true, collector) {
|
|
1977
|
+
async computeCandidatesForUser(user, capToBacklog = true, collector, grantBudget) {
|
|
1811
1978
|
const userAssignments = [];
|
|
1812
1979
|
const routingWeights = user.routingWeights;
|
|
1813
1980
|
const hasRoutingWeights = Boolean(routingWeights && Object.keys(routingWeights).length > 0);
|
|
1981
|
+
// The cap bounds TOTAL backlog, not new grants per pass: callers that
|
|
1982
|
+
// know the user's current backlog pass the remaining headroom as
|
|
1983
|
+
// `grantBudget` (without it, a user holding work could be topped up to
|
|
1984
|
+
// 2×limit−1). capToBacklog=false (the fair path) keeps the full
|
|
1985
|
+
// candidate set for global arbitration.
|
|
1986
|
+
const effectiveCap = capToBacklog
|
|
1987
|
+
? Math.max(0, grantBudget ?? this.backlogLimitFor(user))
|
|
1988
|
+
: this.backlogLimitFor(user);
|
|
1814
1989
|
// Priority 1: Check for workflow-targeted assignments (deterministic matching)
|
|
1815
1990
|
if (this.enableWorkflows) {
|
|
1816
1991
|
const workflowAssignments = await this.getWorkflowTargetedAssignments(user.id);
|
|
1817
1992
|
if (workflowAssignments.length > 0) {
|
|
1818
1993
|
// Workflow assignments take precedence - add them first with highest priority
|
|
1819
1994
|
userAssignments.push(...workflowAssignments);
|
|
1820
|
-
if (userAssignments.length >=
|
|
1995
|
+
if (userAssignments.length >= effectiveCap) {
|
|
1821
1996
|
return { userAssignments, selected: [], workflowTargetedCount: userAssignments.length };
|
|
1822
1997
|
}
|
|
1823
1998
|
}
|
|
@@ -2012,7 +2187,7 @@ class AssignmentMatcher {
|
|
|
2012
2187
|
}
|
|
2013
2188
|
eligible.sort((a, b) => b.effectivePriority - a.effectivePriority);
|
|
2014
2189
|
for (const c of eligible) {
|
|
2015
|
-
if (capToBacklog && userAssignments.length >=
|
|
2190
|
+
if (capToBacklog && userAssignments.length >= effectiveCap)
|
|
2016
2191
|
break;
|
|
2017
2192
|
userAssignments.push({ id: c.detail.id, priority: c.effectivePriority });
|
|
2018
2193
|
selected.push({ id: c.detail.id, tags: c.detail.tags });
|
|
@@ -2021,7 +2196,7 @@ class AssignmentMatcher {
|
|
|
2021
2196
|
}
|
|
2022
2197
|
else {
|
|
2023
2198
|
for (const d of details) {
|
|
2024
|
-
if (capToBacklog && userAssignments.length >=
|
|
2199
|
+
if (capToBacklog && userAssignments.length >= effectiveCap)
|
|
2025
2200
|
break;
|
|
2026
2201
|
// Check CIDR restrictions: if assignment has allowedCidrs, user must have matching IP
|
|
2027
2202
|
if (!(0, cidr_1.checkCidrMatch)(user.ip, d.allowedCidrs)) {
|
|
@@ -2127,6 +2302,10 @@ class AssignmentMatcher {
|
|
|
2127
2302
|
for (const tag of tags) {
|
|
2128
2303
|
rm.zRem(this.keys.tagAssignments(tag), s.id);
|
|
2129
2304
|
}
|
|
2305
|
+
// Leaving the queued universe takes the geo index entry along
|
|
2306
|
+
// (a requeue re-adds it via enqueue's geoAdd); without this the
|
|
2307
|
+
// index grows monotonically with completed work.
|
|
2308
|
+
rm.zRem(this.keys.assignmentsGeo(), s.id);
|
|
2130
2309
|
// Add to pending structures. An assignment carrying an
|
|
2131
2310
|
// EscalationPolicy sets its own response deadline; everything
|
|
2132
2311
|
// else uses the matcher-wide one and never pays for a parse.
|
|
@@ -2175,11 +2354,26 @@ class AssignmentMatcher {
|
|
|
2175
2354
|
}
|
|
2176
2355
|
return claimedIds;
|
|
2177
2356
|
}
|
|
2178
|
-
async getUserRelatedAssignments(user, collector) {
|
|
2179
|
-
const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector);
|
|
2180
|
-
const claimedIds = await this.claimSelected(user, selected);
|
|
2357
|
+
async getUserRelatedAssignments(user, collector, grantBudget) {
|
|
2358
|
+
const { userAssignments, selected, workflowTargetedCount } = await this.computeCandidatesForUser(user, true, collector, grantBudget);
|
|
2181
2359
|
const workflowTargeted = userAssignments.slice(0, workflowTargetedCount);
|
|
2182
|
-
|
|
2360
|
+
// Targeted grants go through the SAME queued→pending claim gate as
|
|
2361
|
+
// organic matching — a grant that only lands in the backlog set while
|
|
2362
|
+
// the assignment stays queued would "accept" into nothing and be
|
|
2363
|
+
// re-granted forever. A targeted id the tag path also selected is
|
|
2364
|
+
// claimed once, under its targeted entry.
|
|
2365
|
+
const targetedIds = new Set(workflowTargeted.map((t) => t.id));
|
|
2366
|
+
const claimList = [
|
|
2367
|
+
...workflowTargeted.map((t) => ({ id: t.id, tags: t.tags ?? '' })),
|
|
2368
|
+
...selected.filter((s) => !targetedIds.has(s.id)),
|
|
2369
|
+
];
|
|
2370
|
+
const claimedIds = await this.claimSelected(user, claimList);
|
|
2371
|
+
const tagScored = userAssignments
|
|
2372
|
+
.slice(workflowTargetedCount)
|
|
2373
|
+
.filter((ua) => claimedIds.has(ua.id) && !targetedIds.has(ua.id));
|
|
2374
|
+
// A targeted assignment that lost the claim was already moved to
|
|
2375
|
+
// pending for this same user on an earlier pass — its backlog
|
|
2376
|
+
// membership below is an idempotent re-add, so it is never stripped.
|
|
2183
2377
|
return { assignments: [...workflowTargeted, ...tagScored], claimedIds, workflowTargeted };
|
|
2184
2378
|
}
|
|
2185
2379
|
/**
|
|
@@ -2279,7 +2473,8 @@ class AssignmentMatcher {
|
|
|
2279
2473
|
}));
|
|
2280
2474
|
// Workflow-targeted assignments are deterministically targeted at one
|
|
2281
2475
|
// user each - not contested across users - so claim them immediately,
|
|
2282
|
-
// exactly like the non-fair path does
|
|
2476
|
+
// exactly like the non-fair path does: through the claimSelected gate
|
|
2477
|
+
// (queued→pending with an owner), then the backlog membership.
|
|
2283
2478
|
await Promise.all(perUser.map(async ({ user, candidates }) => {
|
|
2284
2479
|
const workflowOnly = candidates.userAssignments.slice(0, candidates.workflowTargetedCount);
|
|
2285
2480
|
if (workflowOnly.length === 0)
|
|
@@ -2288,6 +2483,7 @@ class AssignmentMatcher {
|
|
|
2288
2483
|
// Membership must be read before the sAdd below
|
|
2289
2484
|
workflowGrants.push(...(await this.filterNewWorkflowGrants(user, workflowOnly)));
|
|
2290
2485
|
}
|
|
2486
|
+
await this.claimSelected(user, workflowOnly.map((a) => ({ id: a.id, tags: a.tags ?? '' })));
|
|
2291
2487
|
await this.redisClient.sAdd(this.keys.userAssignments(user.id), workflowOnly.map((a) => `assignment:${a.id}`));
|
|
2292
2488
|
}));
|
|
2293
2489
|
// Flatten every user's tag-scored candidates into one global list of
|
|
@@ -2406,7 +2602,7 @@ class AssignmentMatcher {
|
|
|
2406
2602
|
if (userMatchesCount >= this.backlogLimitFor(user))
|
|
2407
2603
|
return;
|
|
2408
2604
|
const collector = this.tracingActive ? new decision_trace_1.TraceCollector() : undefined;
|
|
2409
|
-
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
2605
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
|
|
2410
2606
|
// Membership must be read before the sAdd below
|
|
2411
2607
|
const newWorkflowGrants = collector ? await this.filterNewWorkflowGrants(user, workflowTargeted) : [];
|
|
2412
2608
|
const relevantAssignmentKeys = assignments
|
|
@@ -2447,7 +2643,7 @@ class AssignmentMatcher {
|
|
|
2447
2643
|
if (userMatchesCount >= this.backlogLimitFor(user)) {
|
|
2448
2644
|
return;
|
|
2449
2645
|
}
|
|
2450
|
-
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector);
|
|
2646
|
+
const { assignments, claimedIds, workflowTargeted } = await this.getUserRelatedAssignments(user, collector, this.backlogLimitFor(user) - userMatchesCount);
|
|
2451
2647
|
if (collector) {
|
|
2452
2648
|
for (const id of claimedIds)
|
|
2453
2649
|
winners.set(id, user.id);
|
|
@@ -2667,6 +2863,10 @@ class AssignmentMatcher {
|
|
|
2667
2863
|
}
|
|
2668
2864
|
}
|
|
2669
2865
|
multi.hSet(this.acceptedAssignmentsKey, assignmentId, acceptedJson);
|
|
2866
|
+
// Per-user accepted-work index (raw id, score = accept time).
|
|
2867
|
+
// Inside the guard: an accept whose pending JSON is missing stores
|
|
2868
|
+
// nothing, so it must index nothing.
|
|
2869
|
+
multi.zAdd(this.keys.userAcceptedAssignments(userId), { score: now, value: assignmentId });
|
|
2670
2870
|
}
|
|
2671
2871
|
await multi.exec();
|
|
2672
2872
|
// SLO accept stats piggyback the accept path (internally guarded:
|
|
@@ -2796,6 +2996,7 @@ class AssignmentMatcher {
|
|
|
2796
2996
|
// Move from accepted to completed
|
|
2797
2997
|
const multi = this.redisClient.multi();
|
|
2798
2998
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
2999
|
+
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
2799
3000
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2800
3001
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2801
3002
|
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
@@ -2851,6 +3052,7 @@ class AssignmentMatcher {
|
|
|
2851
3052
|
// Move from accepted to completed (with failed status)
|
|
2852
3053
|
const multi = this.redisClient.multi();
|
|
2853
3054
|
multi.hDel(this.acceptedAssignmentsKey, assignmentId);
|
|
3055
|
+
multi.zRem(this.keys.userAcceptedAssignments(userId), assignmentId);
|
|
2854
3056
|
// Clear SLA indexes (no-ops for non-SLA assignments)
|
|
2855
3057
|
multi.zRem(this.acceptedAssignmentsExpiryKey, assignmentId);
|
|
2856
3058
|
multi.zRem(this.assignmentsSlaExpiryKey, assignmentId);
|
|
@@ -3251,8 +3453,10 @@ class AssignmentMatcher {
|
|
|
3251
3453
|
}
|
|
3252
3454
|
if (action === 'requeue') {
|
|
3253
3455
|
const multi = this.redisClient.multi().hDel(this.acceptedAssignmentsKey, id);
|
|
3254
|
-
if (workerId)
|
|
3456
|
+
if (workerId) {
|
|
3255
3457
|
multi.sAdd(this.keys.userRejected(workerId), id);
|
|
3458
|
+
multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3459
|
+
}
|
|
3256
3460
|
await multi.exec();
|
|
3257
3461
|
// The JSON still carries _enqueuedAt, so the freshness TTL
|
|
3258
3462
|
// keeps ticking across the requeue. A requeue after a
|
|
@@ -3262,7 +3466,7 @@ class AssignmentMatcher {
|
|
|
3262
3466
|
continue;
|
|
3263
3467
|
}
|
|
3264
3468
|
if (action === 'fail') {
|
|
3265
|
-
|
|
3469
|
+
const multi = this.redisClient
|
|
3266
3470
|
.multi()
|
|
3267
3471
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3268
3472
|
.hSet(this.completedAssignmentsKey, id, JSON.stringify({
|
|
@@ -3272,17 +3476,21 @@ class AssignmentMatcher {
|
|
|
3272
3476
|
_failureReason: 'completion-sla-breach',
|
|
3273
3477
|
}))
|
|
3274
3478
|
// Terminal: the freshness TTL no longer applies.
|
|
3275
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3276
|
-
|
|
3479
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3480
|
+
if (workerId)
|
|
3481
|
+
multi.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3482
|
+
await multi.exec();
|
|
3277
3483
|
continue;
|
|
3278
3484
|
}
|
|
3279
3485
|
// 'park'
|
|
3280
|
-
|
|
3486
|
+
const parkMulti = this.redisClient
|
|
3281
3487
|
.multi()
|
|
3282
3488
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3283
3489
|
.hSet(this.keys.parkedAssignments(), id, JSON.stringify(assignment))
|
|
3284
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3285
|
-
|
|
3490
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3491
|
+
if (workerId)
|
|
3492
|
+
parkMulti.zRem(this.keys.userAcceptedAssignments(workerId), id);
|
|
3493
|
+
await parkMulti.exec();
|
|
3286
3494
|
}
|
|
3287
3495
|
return { breached };
|
|
3288
3496
|
}
|
|
@@ -3339,12 +3547,14 @@ class AssignmentMatcher {
|
|
|
3339
3547
|
await multi.exec();
|
|
3340
3548
|
}
|
|
3341
3549
|
else if (acceptedJson) {
|
|
3342
|
-
|
|
3550
|
+
const multi = this.redisClient
|
|
3343
3551
|
.multi()
|
|
3344
3552
|
.hDel(this.acceptedAssignmentsKey, id)
|
|
3345
3553
|
.zRem(this.acceptedAssignmentsExpiryKey, id)
|
|
3346
|
-
.zRem(this.assignmentsSlaExpiryKey, id)
|
|
3347
|
-
|
|
3554
|
+
.zRem(this.assignmentsSlaExpiryKey, id);
|
|
3555
|
+
if (ownerId)
|
|
3556
|
+
multi.zRem(this.keys.userAcceptedAssignments(ownerId), id);
|
|
3557
|
+
await multi.exec();
|
|
3348
3558
|
}
|
|
3349
3559
|
else {
|
|
3350
3560
|
// Queued: full index cleanup via removeAssignment (also zRems
|
|
@@ -3463,7 +3673,16 @@ class AssignmentMatcher {
|
|
|
3463
3673
|
// A due notBefore falls straight through addAssignment's hold
|
|
3464
3674
|
// guard into the normal enqueue, which also clears the scheduled
|
|
3465
3675
|
// hash atomically with the queued write.
|
|
3466
|
-
|
|
3676
|
+
try {
|
|
3677
|
+
await this.addAssignment(JSON.parse(json));
|
|
3678
|
+
}
|
|
3679
|
+
catch (err) {
|
|
3680
|
+
// The zRem claim already consumed the only trigger; without
|
|
3681
|
+
// restoring it, a failed enqueue strands the assignment in the
|
|
3682
|
+
// scheduled store forever (nothing re-examines it).
|
|
3683
|
+
await this.redisClient.zAdd(this.scheduledActivateAtKey, { score: now, value: id });
|
|
3684
|
+
throw err;
|
|
3685
|
+
}
|
|
3467
3686
|
activated++;
|
|
3468
3687
|
this.emitAssignmentLifecycle({ kind: 'scheduleActivated', taskId: id, at: now });
|
|
3469
3688
|
}
|
|
@@ -3519,8 +3738,12 @@ class AssignmentMatcher {
|
|
|
3519
3738
|
delete record[policy_2.SLA_ACCEPTED_AT_FIELD];
|
|
3520
3739
|
delete record[policy_2.SLA_ACCEPTED_BY_FIELD];
|
|
3521
3740
|
}
|
|
3522
|
-
|
|
3741
|
+
// Re-enqueue BEFORE dropping the parked copy: the parked hash holds
|
|
3742
|
+
// the only copy of the JSON, so the reverse order loses the assignment
|
|
3743
|
+
// outright if the enqueue fails mid-flight. A crash between these two
|
|
3744
|
+
// leaves a duplicate (queued + parked), which a repeat unpark heals.
|
|
3523
3745
|
await this.addAssignment(assignment);
|
|
3746
|
+
await this.redisClient.hDel(this.keys.parkedAssignments(), id);
|
|
3524
3747
|
return true;
|
|
3525
3748
|
}
|
|
3526
3749
|
/** Current escalation level of an assignment (0 = never escalated). */
|
|
@@ -3761,18 +3984,27 @@ class AssignmentMatcher {
|
|
|
3761
3984
|
async getWorkflowTargetedAssignments(userId) {
|
|
3762
3985
|
const targeted = [];
|
|
3763
3986
|
// Scan queued assignments for those with _targetUserId matching this user
|
|
3764
|
-
const queuedAssignments = await
|
|
3987
|
+
const [queuedAssignments, rejectedMembers] = await Promise.all([
|
|
3988
|
+
this.redisClient.hGetAll(this.assignmentsRefKey),
|
|
3989
|
+
this.redisClient.sMembers(this.keys.userRejected(userId)),
|
|
3990
|
+
]);
|
|
3991
|
+
const rejected = new Set(rejectedMembers);
|
|
3765
3992
|
for (const [assignmentId, json] of Object.entries(queuedAssignments)) {
|
|
3766
3993
|
try {
|
|
3767
3994
|
const assignment = JSON.parse(json);
|
|
3768
|
-
// Hard veto applies even to deterministic workflow targeting
|
|
3995
|
+
// Hard veto applies even to deterministic workflow targeting,
|
|
3996
|
+
// and so does the user's own prior rejection — re-granting a
|
|
3997
|
+
// rejected assignment forever violates the rejection contract.
|
|
3769
3998
|
if (assignment.vetoedUsers?.includes(userId))
|
|
3770
3999
|
continue;
|
|
4000
|
+
if (rejected.has(assignmentId))
|
|
4001
|
+
continue;
|
|
3771
4002
|
if (assignment._targetUserId === userId && assignment._workflowInstanceId) {
|
|
3772
4003
|
// This is a workflow assignment targeted at this user
|
|
3773
4004
|
targeted.push({
|
|
3774
4005
|
id: assignmentId,
|
|
3775
4006
|
priority: assignment.priority ?? 1000,
|
|
4007
|
+
tags: (assignment.tags ?? []).join(','),
|
|
3776
4008
|
});
|
|
3777
4009
|
}
|
|
3778
4010
|
}
|