assignment-user-matcher 1.2.1 → 1.2.2
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 +505 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/learning/features.d.ts +19 -0
- package/dist/learning/features.d.ts.map +1 -0
- package/dist/learning/features.js +55 -0
- package/dist/managers/LearningManager.d.ts +94 -0
- package/dist/managers/LearningManager.d.ts.map +1 -0
- package/dist/managers/LearningManager.js +194 -0
- package/dist/managers/WorkflowManager.d.ts +3 -6
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +15 -4
- package/dist/matcher.class.d.ts +78 -8
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +329 -13
- package/dist/types/matcher.d.ts +119 -9
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +5 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/dist/workflow-builder.d.ts +2 -4
- package/dist/workflow-builder.d.ts.map +1 -1
- package/dist/workflow-builder.js +4 -46
- package/dist/workflow-validation.d.ts +4 -0
- package/dist/workflow-validation.d.ts.map +1 -0
- package/dist/workflow-validation.js +85 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -57,6 +57,23 @@ Traditional matching systems can become bottlenecks, leading to delays, suboptim
|
|
|
57
57
|
- Wildcards are **suffix-only** (`prefix*`). Patterns like `skill:*:node` are not treated as wildcards.
|
|
58
58
|
- If a user has `routingWeights` but no positive entries, assignments stay queued.
|
|
59
59
|
|
|
60
|
+
Hard veto configuration example:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
await assignmentMatcher.addUser({
|
|
64
|
+
id: 'agent_1',
|
|
65
|
+
tags: [],
|
|
66
|
+
routingWeights: {
|
|
67
|
+
'support:*': 100, // eligible
|
|
68
|
+
'lang:*': 0, // hard veto for all language-tagged assignments
|
|
69
|
+
default: 0, // hard veto for default matching fallback
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
|
|
75
|
+
Configure hard veto behavior only through `routingWeights` values.
|
|
76
|
+
|
|
60
77
|
3. **Prioritization Engine:**
|
|
61
78
|
Assignments are typically processed in the order they are received or by a custom prioritization function you can provide. This ensures that older or more critical assignments get attention first. The library aims to match the highest priority assignments to available, suitable users.
|
|
62
79
|
|
|
@@ -149,6 +166,53 @@ async function runExample() {
|
|
|
149
166
|
runExample().catch(console.error);
|
|
150
167
|
```
|
|
151
168
|
|
|
169
|
+
### 3. Workflow Quick Start
|
|
170
|
+
|
|
171
|
+
Workflows are easiest to use with the builder helpers and the `executeWorkflow()` convenience method.
|
|
172
|
+
|
|
173
|
+
```typescript
|
|
174
|
+
import AssignmentMatcher, { workflow } from 'assignment-user-matcher';
|
|
175
|
+
|
|
176
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
177
|
+
enableWorkflows: true,
|
|
178
|
+
redisPrefix: 'exampleApp:',
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// Optional if your Redis client is already connected.
|
|
182
|
+
// Useful when the matcher is created with a closed client.
|
|
183
|
+
await matcher.waitUntilReady();
|
|
184
|
+
|
|
185
|
+
const onboardingWorkflow = workflow('onboarding', 'Onboarding')
|
|
186
|
+
.step('profile')
|
|
187
|
+
.name('Complete profile')
|
|
188
|
+
.assignment({ tags: ['profile'], title: 'Complete your profile' })
|
|
189
|
+
.targetUser('initiator')
|
|
190
|
+
.defaultNext('review')
|
|
191
|
+
.done()
|
|
192
|
+
.step('review')
|
|
193
|
+
.name('Manager review')
|
|
194
|
+
.assignment({ tags: ['review'], title: 'Review onboarding' })
|
|
195
|
+
.targetUser({ tag: 'managers' })
|
|
196
|
+
.defaultNext(null)
|
|
197
|
+
.done()
|
|
198
|
+
.build();
|
|
199
|
+
|
|
200
|
+
// Registers the definition if needed, then starts the workflow instance.
|
|
201
|
+
const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
|
|
202
|
+
source: 'signup',
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
console.log(instance.id, instance.currentStepId);
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
You can still call `registerWorkflow()` and `startWorkflow()` separately if you want explicit lifecycle control.
|
|
209
|
+
|
|
210
|
+
Plain object workflow definitions are also accepted. The library now fills in sensible defaults:
|
|
211
|
+
|
|
212
|
+
- `version` defaults to `1`
|
|
213
|
+
- `initialStepId` defaults to the first step ID
|
|
214
|
+
- invalid definitions fail early during registration with clear validation errors
|
|
215
|
+
|
|
152
216
|
## API Reference
|
|
153
217
|
|
|
154
218
|
The main class provided is `AssignmentMatcher`.
|
|
@@ -188,6 +252,16 @@ Retrieves the current list of assignments that a user is tentatively matched wit
|
|
|
188
252
|
|
|
189
253
|
- `userId: string`: The ID of the user.
|
|
190
254
|
|
|
255
|
+
### `getPendingAssignmentsWithAge(): Promise<PendingAssignmentInfo[]>`
|
|
256
|
+
|
|
257
|
+
Retrieves current pending assignments, including who owns each assignment and how long it has been pending.
|
|
258
|
+
|
|
259
|
+
- `assignment`: The assignment payload.
|
|
260
|
+
- `ownerId`: The current owner user ID, or `null` if missing.
|
|
261
|
+
- `pendingForMs`: Elapsed pending time in milliseconds.
|
|
262
|
+
- `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
|
|
263
|
+
- `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
|
|
264
|
+
|
|
191
265
|
### `removeUser(userId: string): Promise<void>`
|
|
192
266
|
|
|
193
267
|
Removes a user from the system and clears their assignment backlog.
|
|
@@ -200,6 +274,17 @@ Removes a specific assignment from the system. Requires tags to efficiently loca
|
|
|
200
274
|
|
|
201
275
|
Marks an assignment as completed by a user, removing it from their backlog and potentially making them available for new assignments.
|
|
202
276
|
|
|
277
|
+
### `waitUntilReady(): Promise<AssignmentMatcher>`
|
|
278
|
+
|
|
279
|
+
Waits for the matcher to finish connecting and initializing internal Redis and workflow resources.
|
|
280
|
+
|
|
281
|
+
### `executeWorkflow(workflowOrId, userId, initialContext?): Promise<WorkflowInstance>`
|
|
282
|
+
|
|
283
|
+
The simplest workflow entrypoint.
|
|
284
|
+
|
|
285
|
+
- Pass a workflow ID to start an already-registered workflow.
|
|
286
|
+
- Pass a workflow definition or builder-produced definition to register it and start it in one call.
|
|
287
|
+
|
|
203
288
|
## Options
|
|
204
289
|
|
|
205
290
|
You can pass an options object to the `AssignmentMatcher` constructor:
|
|
@@ -227,6 +312,16 @@ type Options = {
|
|
|
227
312
|
// If set to false, you should provide a custom `matchingFunction`.
|
|
228
313
|
enableDefaultMatching?: boolean; // Default: true
|
|
229
314
|
|
|
315
|
+
// Opt-in idle user auto-rejection. When set, users holding pending
|
|
316
|
+
// (not yet accepted/rejected) assignments with no activity for this many
|
|
317
|
+
// milliseconds are removed from the matching pool by `processIdleUsers()`,
|
|
318
|
+
// and their pending assignments are requeued for other users.
|
|
319
|
+
// Activity is recorded automatically on addUser/acceptAssignment/rejectAssignment,
|
|
320
|
+
// or explicitly via `touchUser(userId)` as a heartbeat.
|
|
321
|
+
// Use `startIdleUserInterval(intervalMs)` / `stopIdleUserInterval()` to run
|
|
322
|
+
// the check periodically. Disabled when undefined (default).
|
|
323
|
+
idleUserTimeoutMs?: number; // Default: undefined (disabled)
|
|
324
|
+
|
|
230
325
|
// A custom function to determine the priority of an assignment.
|
|
231
326
|
// The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
|
|
232
327
|
// and should return a numerical priority score. Higher scores mean higher priority.
|
|
@@ -250,9 +345,419 @@ type Options = {
|
|
|
250
345
|
assignmentPriority: number | string, // This is the score from prioritizationFunction or createdAt
|
|
251
346
|
assignmentId?: string,
|
|
252
347
|
) => Promise<[number, number]>;
|
|
348
|
+
|
|
349
|
+
// ========== Reinforcement Learning Options ==========
|
|
350
|
+
|
|
351
|
+
// Enable the adaptive learning layer (contextual bandit re-ranking).
|
|
352
|
+
enableLearning?: boolean; // Default: false
|
|
353
|
+
|
|
354
|
+
// SGD learning rate for online model updates.
|
|
355
|
+
learningRate?: number; // Default: 0.1
|
|
356
|
+
|
|
357
|
+
// Epsilon-greedy exploration rate in [0, 1]. With this probability, a random
|
|
358
|
+
// jitter is added to candidate scores so the model keeps gathering data on
|
|
359
|
+
// under-served candidates.
|
|
360
|
+
learningExplorationRate?: number; // Default: 0.05
|
|
361
|
+
|
|
362
|
+
// Shadow mode: record decisions and learn from outcomes, but never alter
|
|
363
|
+
// ranking. Useful for safely evaluating the model before going live.
|
|
364
|
+
learningShadowMode?: boolean; // Default: false
|
|
365
|
+
|
|
366
|
+
// Multiplier applied to the predicted reward when re-ranking candidates.
|
|
367
|
+
// Higher values let the learned model dominate over base priority.
|
|
368
|
+
learningBoostFactor?: number; // Default: 1
|
|
369
|
+
|
|
370
|
+
// Override rewards per lifecycle outcome (merged with defaults):
|
|
371
|
+
// { accept: 0.3, complete: 1, reject: -0.6, expire: -0.3, fail: -0.8 }
|
|
372
|
+
learningRewards?: Partial<Record<'accept' | 'complete' | 'reject' | 'expire' | 'fail', number>>;
|
|
373
|
+
|
|
374
|
+
// Custom feature extractor. Defaults to tag-match, normalized skill-weight,
|
|
375
|
+
// tag-overlap-ratio and embedding-similarity features.
|
|
376
|
+
learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
|
|
377
|
+
|
|
378
|
+
// TTL for stored decision contexts in ms.
|
|
379
|
+
learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
|
|
380
|
+
|
|
381
|
+
// Weights applied to named external feedback signals when computing rewards.
|
|
382
|
+
// Signals not listed here default to weight 1. Negative weights turn a
|
|
383
|
+
// signal into a penalty (e.g. { errorRate: -2 }).
|
|
384
|
+
learningSignalWeights?: Record<string, number>;
|
|
385
|
+
|
|
386
|
+
// TTL for archived episodes awaiting late external feedback in ms.
|
|
387
|
+
learningFeedbackTtlMs?: number; // Default: 604800000 (7 days)
|
|
253
388
|
};
|
|
254
389
|
```
|
|
255
390
|
|
|
391
|
+
## Adaptive Matching with Reinforcement Learning
|
|
392
|
+
|
|
393
|
+
The matcher includes an opt-in, Redis-backed contextual bandit that learns from
|
|
394
|
+
assignment outcomes and re-ranks candidates automatically. Hard matching rules
|
|
395
|
+
(tags, `routingWeights`, vetoes, CIDR, `skillThresholds`) always apply first —
|
|
396
|
+
the learned model only reorders assignments that are already eligible.
|
|
397
|
+
|
|
398
|
+
How it works:
|
|
399
|
+
|
|
400
|
+
1. When a user is matched, a sparse feature vector is extracted for each
|
|
401
|
+
eligible candidate (tag matches, normalized skill weights, tag overlap, and
|
|
402
|
+
optional `embedding` cosine similarity if both user and assignment carry an
|
|
403
|
+
`embedding: number[]` field).
|
|
404
|
+
2. Candidates are ranked by `combinedPriority + boostFactor * predictedReward`.
|
|
405
|
+
3. The decision context is stored, and lifecycle outcomes (`accept`,
|
|
406
|
+
`complete`, `reject`, `expire`, `fail`) feed rewards back into the model via
|
|
407
|
+
online SGD updates — fully automatic, no training pipeline needed.
|
|
408
|
+
|
|
409
|
+
```typescript
|
|
410
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
411
|
+
enableLearning: true,
|
|
412
|
+
// Start safe: observe without affecting ranking
|
|
413
|
+
learningShadowMode: true,
|
|
414
|
+
// Optional reward shaping
|
|
415
|
+
learningRewards: { complete: 2, reject: -1 },
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
// ... normal addUser / addAssignment / matchUsersAssignments usage ...
|
|
419
|
+
|
|
420
|
+
// Inspect what the model has learned
|
|
421
|
+
const model = await matcher.getLearningModel(); // { 'tag:english': '0.42', ... }
|
|
422
|
+
const stats = await matcher.getLearningStats(); // { decisions, rewards, totalReward, averageReward }
|
|
423
|
+
|
|
424
|
+
// Manual reward shaping for a matched assignment (e.g. CSAT score arrived later)
|
|
425
|
+
await matcher.recordLearningReward('assignment-123', 1.5);
|
|
426
|
+
|
|
427
|
+
// Start over
|
|
428
|
+
await matcher.resetLearningModel();
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
### Feeding External Data into the Model
|
|
432
|
+
|
|
433
|
+
Matchmaking quality signals often arrive after an assignment is closed — QA
|
|
434
|
+
audits, accuracy reviews, customer satisfaction scores, handle-time analysis.
|
|
435
|
+
The learning layer supports three external feed paths:
|
|
436
|
+
|
|
437
|
+
**1. Named feedback signals (post-processing per assignment).** When an
|
|
438
|
+
assignment reaches a terminal state, its feature context is archived as an
|
|
439
|
+
*episode* (kept for `learningFeedbackTtlMs`). External pipelines can attribute
|
|
440
|
+
late signals to it at any point within that window:
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
444
|
+
enableLearning: true,
|
|
445
|
+
// Reward = sum(signalValue * signalWeight); unlisted signals default to 1
|
|
446
|
+
learningSignalWeights: {
|
|
447
|
+
accuracy: 2, // accuracy audits matter most
|
|
448
|
+
csat: 1, // customer satisfaction
|
|
449
|
+
handleTimePenalty: -0.5, // longer handling reduces reward
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
// ...assignment is matched, accepted, completed...
|
|
454
|
+
|
|
455
|
+
// Hours/days later, the QA pipeline reports back:
|
|
456
|
+
await matcher.recordLearningFeedback('assignment-123', {
|
|
457
|
+
accuracy: 0.95,
|
|
458
|
+
csat: 0.8,
|
|
459
|
+
handleTimePenalty: 0.3,
|
|
460
|
+
});
|
|
461
|
+
// reward = 0.95*2 + 0.8*1 + 0.3*-0.5 = 2.55, applied to the episode's features
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
**2. Raw reward shaping.** `recordLearningReward(assignmentId, reward)` applies
|
|
465
|
+
an explicit numeric reward against an assignment's decision context when you
|
|
466
|
+
want full control over the value.
|
|
467
|
+
|
|
468
|
+
**3. Offline batch training.** `trainLearningSamples(samples)` updates the
|
|
469
|
+
model directly from raw `(features, reward)` pairs — no live decision context
|
|
470
|
+
needed. Use it to bootstrap the model from historical data or to run scheduled
|
|
471
|
+
imports from a data warehouse:
|
|
472
|
+
|
|
473
|
+
```typescript
|
|
474
|
+
await matcher.trainLearningSamples([
|
|
475
|
+
{ features: { bias: 1, 'tag:english': 1, 'skill:english': 0.8 }, reward: 1.2 },
|
|
476
|
+
{ features: { bias: 1, 'tag:billing': 1 }, reward: -0.4 },
|
|
477
|
+
]);
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
Feature names are arbitrary strings — as long as your
|
|
481
|
+
`learningFeatureExtractor` produces the same names at match time, externally
|
|
482
|
+
trained weights apply immediately to live ranking.
|
|
483
|
+
|
|
484
|
+
Rollout recommendation: enable with `learningShadowMode: true` first, watch
|
|
485
|
+
`getLearningStats()` and `getLearningModel()`, then flip shadow mode off and
|
|
486
|
+
tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
|
|
487
|
+
domain-specific setups (custom embeddings, business features), supply a
|
|
488
|
+
`learningFeatureExtractor`.
|
|
489
|
+
|
|
490
|
+
### RL Scalability & Redis Constraints
|
|
491
|
+
|
|
492
|
+
The RL layer adds controlled overhead: decision recording, outcome archival,
|
|
493
|
+
and weight updates. Because these operations are write-heavy and per-assignment,
|
|
494
|
+
scalability depends primarily on Redis memory, write throughput, and feature
|
|
495
|
+
cardinality — not on learning math itself.
|
|
496
|
+
|
|
497
|
+
#### Redis Workload Breakdown
|
|
498
|
+
|
|
499
|
+
Each matched assignment now costs:
|
|
500
|
+
1. **Decision record** (live): ~300 bytes for features + metadata; expires in 7 days (configurable).
|
|
501
|
+
2. **Episode archive** (terminal): ~400 bytes; kept until feedback arrives, expires in 7 days.
|
|
502
|
+
3. **Model updates**: One hash increment per feature per outcome (typically 5–15 features).
|
|
503
|
+
4. **Stats tracking**: Shared atomic increments.
|
|
504
|
+
|
|
505
|
+
Matching a single assignment typically involves:
|
|
506
|
+
- 1–2 Redis reads (model + candidate details).
|
|
507
|
+
- 3–5 Redis writes per matched assignment (decision, model updates, stats).
|
|
508
|
+
- Pipelined to reduce round trips.
|
|
509
|
+
|
|
510
|
+
#### Memory Estimation
|
|
511
|
+
|
|
512
|
+
Assume:
|
|
513
|
+
- **Small deployment**: 10 users, 1,000 live assignments, ~8 features per assignment.
|
|
514
|
+
- Model: ~8 KB (8 features × 1 KB per weight + overhead).
|
|
515
|
+
- Decisions: ~300 KB (1,000 × 300 bytes).
|
|
516
|
+
- Overhead: ~500 KB for indices and stats.
|
|
517
|
+
- **Total: ~1 MB**. No scaling issues with standard Redis (safe at anything).
|
|
518
|
+
|
|
519
|
+
- **Medium deployment**: 100 users, 100,000 live assignments, ~15 features.
|
|
520
|
+
- Model: ~15 KB.
|
|
521
|
+
- Decisions: ~30 MB (100,000 × 300 bytes).
|
|
522
|
+
- Episodes archived: ~10 MB (depends on feedback delay; typically 10% of live at any moment).
|
|
523
|
+
- Overhead: ~5 MB.
|
|
524
|
+
- **Total: ~50 MB**. Easily within Redis limits; watch growth over weeks.
|
|
525
|
+
|
|
526
|
+
- **High-throughput deployment**: 1,000 users, 1,000,000 live assignments, ~20 features, exploration enabled.
|
|
527
|
+
- Model: ~20 KB.
|
|
528
|
+
- Decisions: ~300 MB (1,000,000 × 300 bytes).
|
|
529
|
+
- Episodes: ~100 MB.
|
|
530
|
+
- Overhead: ~50 MB.
|
|
531
|
+
- **Total: ~450 MB**. Manageable with a 2–4 GB Redis instance; requires TTL discipline.
|
|
532
|
+
|
|
533
|
+
#### Configuration Guidelines
|
|
534
|
+
|
|
535
|
+
**Small (10–50 users, <10K assignments/day):**
|
|
536
|
+
|
|
537
|
+
```typescript
|
|
538
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
539
|
+
enableLearning: true,
|
|
540
|
+
learningShadowMode: true, // Observe first; no ranking impact
|
|
541
|
+
learningRate: 0.1,
|
|
542
|
+
learningExplorationRate: 0, // No exploration overhead
|
|
543
|
+
learningDecisionTtlMs: 604800000, // 7 days
|
|
544
|
+
learningFeedbackTtlMs: 604800000, // 7 days
|
|
545
|
+
});
|
|
546
|
+
// Safe: no performance issues. Monitor model size weekly.
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
**Medium (50–500 users, 10K–100K assignments/day):**
|
|
550
|
+
|
|
551
|
+
```typescript
|
|
552
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
553
|
+
enableLearning: true,
|
|
554
|
+
learningShadowMode: false,
|
|
555
|
+
learningRate: 0.05, // Slower learning for stability
|
|
556
|
+
learningExplorationRate: 0.02, // 2% of matches explore randomly
|
|
557
|
+
learningBoostFactor: 50, // Moderate impact on ranking
|
|
558
|
+
learningDecisionTtlMs: 259200000, // 3 days (balance TTL vs memory)
|
|
559
|
+
learningFeedbackTtlMs: 259200000,
|
|
560
|
+
learningSignalWeights: { accuracy: 1, csat: 0.5, errorRate: -1 },
|
|
561
|
+
});
|
|
562
|
+
// Recommended: batch external feedback imports off-peak.
|
|
563
|
+
// Monitor: Redis memory growth, write latency, decision key count.
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
**High-throughput (500+ users, 100K+ assignments/day):**
|
|
567
|
+
|
|
568
|
+
```typescript
|
|
569
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
570
|
+
enableLearning: true,
|
|
571
|
+
learningShadowMode: false,
|
|
572
|
+
learningRate: 0.02, // Conservative learning rate
|
|
573
|
+
learningExplorationRate: 0.01, // Minimal exploration (1%)
|
|
574
|
+
learningBoostFactor: 30, // Restrained boost to avoid instability
|
|
575
|
+
learningDecisionTtlMs: 86400000, // 1 day (shorter TTL for faster cleanup)
|
|
576
|
+
learningFeedbackTtlMs: 172800000, // 2 days (stagger feedback arrival)
|
|
577
|
+
learningSignalWeights: { accuracy: 1, csat: 0.3 }, // Fewer signals = less noise
|
|
578
|
+
// Consider sampling outcomes if traffic is extreme:
|
|
579
|
+
// Only learn from 10% of low-priority assignments.
|
|
580
|
+
});
|
|
581
|
+
// Monitoring critical: set up Redis memory alerts, track write amplification.
|
|
582
|
+
// Consider a separate Redis instance for RL state if main matcher instance is saturated.
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
#### Safety Guardrails
|
|
586
|
+
|
|
587
|
+
1. **Keep hard rules outside RL.** Eligibility, vetoes, backlog limits, and lifecycle state remain deterministic. RL only adjusts ranking of already-eligible candidates.
|
|
588
|
+
2. **Start shadow mode.** Always enable `learningShadowMode: true` for the first week, then migrate to live mode with guardrails in place.
|
|
589
|
+
3. **Cap exploration.** Set `learningExplorationRate ≤ 0.05` (5%). Exploration is important for learning but creates churn and can impact user experience.
|
|
590
|
+
4. **Aggressive TTL.** Never leave decision records for more than 7 days. Episodes (feedback-waiting) should expire in 3–7 days depending on your feedback SLA.
|
|
591
|
+
5. **Batch feedback imports.** Run external QA/accuracy signal imports as background jobs during low-traffic windows, not inline with matching.
|
|
592
|
+
6. **Monitor key counts.** Use `redis-cli info keyspace` or equivalent to watch key cardinality. If decision keys grow unbounded, TTL is broken or Redis is out of memory.
|
|
593
|
+
7. **Separate concerns.** If your matcher handles 1M+ assignments/day, use a dedicated Redis instance for RL state, separate from the main queue data.
|
|
594
|
+
|
|
595
|
+
#### Monitoring & Diagnostics
|
|
596
|
+
|
|
597
|
+
Key metrics to track:
|
|
598
|
+
|
|
599
|
+
- **Model size**: `(await matcher.getLearningModel()).length` — should be stable (5–50 features). If growing > 100, your feature extractor is leaking.
|
|
600
|
+
- **Decision cardinality**: `DBSIZE` and filter for `learning:decision:*` — should stay < 2× your `maxUserBacklogSize × numUsers`.
|
|
601
|
+
- **Learning stats**: `getLearningStats()` — watch `averageReward` drift and `decisions` growth rate. If `averageReward` is always zero or NaN, your reward signals are malformed.
|
|
602
|
+
- **Redis memory**: Keep below 70% of instance limit. Set memory alerts.
|
|
603
|
+
- **Write latency**: Track Redis command latencies (`latency latest`). Spikes indicate contention; consider sharding or a larger instance.
|
|
604
|
+
- **Model convergence**: Periodically log `getLearningModel()` weights and compare week-over-week. Sharp weight changes suggest concept drift or noisy rewards.
|
|
605
|
+
|
|
606
|
+
#### Recommended Production Workflow
|
|
607
|
+
|
|
608
|
+
1. Deploy with `learningShadowMode: true` and `learningExplorationRate: 0` for 1–2 weeks.
|
|
609
|
+
2. Validate that `getLearningStats()` shows growing reward without ranking instability.
|
|
610
|
+
3. Switch to live mode with low `learningExplorationRate` (0.01–0.02).
|
|
611
|
+
4. Set up external feedback pipeline (QA, CSAT, etc.) and test with a small sample.
|
|
612
|
+
5. Gradually increase `boostFactor` and `explorationRate` based on business metrics (completion rate, SLA, re-open rate).
|
|
613
|
+
6. Monitor weekly; roll back or reduce `boostFactor` if metrics degrade.
|
|
614
|
+
|
|
615
|
+
### Learning Benchmark Simulation
|
|
616
|
+
|
|
617
|
+
Use the built-in simulation benchmark to compare baseline routing vs learning shadow mode vs live learning mode on the same deterministic workload.
|
|
618
|
+
|
|
619
|
+
Run with defaults:
|
|
620
|
+
|
|
621
|
+
```bash
|
|
622
|
+
pnpm benchmark:learning
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
Run with custom scale:
|
|
626
|
+
|
|
627
|
+
```bash
|
|
628
|
+
pnpm benchmark:learning -- 300 8000 10 20260611
|
|
629
|
+
# arguments: <users> <assignmentsPerRound> <rounds> <seed>
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
Output includes:
|
|
633
|
+
|
|
634
|
+
1. Per-mode throughput and latency (`baseline`, `learning-shadow`, `learning-live`)
|
|
635
|
+
2. Acceptance/completion/rejection/failure rates
|
|
636
|
+
3. A normalized quality score for quick comparisons
|
|
637
|
+
4. Top learned model weights
|
|
638
|
+
5. Delta summary vs baseline (throughput, completion rate, quality)
|
|
639
|
+
|
|
640
|
+
### Configuration Playbook (How To Choose)
|
|
641
|
+
|
|
642
|
+
Use this quick guide based on your primary goal.
|
|
643
|
+
|
|
644
|
+
#### Throughput-first (minimal latency impact)
|
|
645
|
+
|
|
646
|
+
```typescript
|
|
647
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
648
|
+
enableLearning: true,
|
|
649
|
+
learningShadowMode: false,
|
|
650
|
+
learningExplorationRate: 0.005,
|
|
651
|
+
learningBoostFactor: 20,
|
|
652
|
+
learningRate: 0.02,
|
|
653
|
+
learningDecisionTtlMs: 86400000,
|
|
654
|
+
learningFeedbackTtlMs: 86400000,
|
|
655
|
+
relevantBatchSize: 50,
|
|
656
|
+
maxUserBacklogSize: 1,
|
|
657
|
+
});
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
When to use:
|
|
661
|
+
1. You have tight p95/p99 latency SLOs.
|
|
662
|
+
2. Even a 2-5% throughput drop is expensive.
|
|
663
|
+
|
|
664
|
+
#### Balanced (recommended starting point)
|
|
665
|
+
|
|
666
|
+
```typescript
|
|
667
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
668
|
+
enableLearning: true,
|
|
669
|
+
learningShadowMode: false,
|
|
670
|
+
learningExplorationRate: 0.01,
|
|
671
|
+
learningBoostFactor: 35,
|
|
672
|
+
learningRate: 0.05,
|
|
673
|
+
learningDecisionTtlMs: 259200000,
|
|
674
|
+
learningFeedbackTtlMs: 259200000,
|
|
675
|
+
relevantBatchSize: 100,
|
|
676
|
+
maxUserBacklogSize: 1,
|
|
677
|
+
});
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
When to use:
|
|
681
|
+
1. You want measurable quality lift with moderate performance cost.
|
|
682
|
+
2. You can tolerate small throughput swings while tuning.
|
|
683
|
+
|
|
684
|
+
#### Quality-first (maximize learning impact)
|
|
685
|
+
|
|
686
|
+
```typescript
|
|
687
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
688
|
+
enableLearning: true,
|
|
689
|
+
learningShadowMode: false,
|
|
690
|
+
learningExplorationRate: 0.02,
|
|
691
|
+
learningBoostFactor: 60,
|
|
692
|
+
learningRate: 0.08,
|
|
693
|
+
learningDecisionTtlMs: 604800000,
|
|
694
|
+
learningFeedbackTtlMs: 604800000,
|
|
695
|
+
relevantBatchSize: 200,
|
|
696
|
+
maxUserBacklogSize: 1,
|
|
697
|
+
});
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
When to use:
|
|
701
|
+
1. Completion/quality metrics matter more than raw throughput.
|
|
702
|
+
2. You have enough headroom in Redis and CPU.
|
|
703
|
+
|
|
704
|
+
### How To Tune It (Step by Step)
|
|
705
|
+
|
|
706
|
+
1. Start with **shadow mode** and exploration off:
|
|
707
|
+
|
|
708
|
+
```typescript
|
|
709
|
+
learningShadowMode: true,
|
|
710
|
+
learningExplorationRate: 0,
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
2. Run baseline benchmark and record metrics:
|
|
714
|
+
|
|
715
|
+
```bash
|
|
716
|
+
pnpm benchmark:learning -- 100 1000 10 42
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
3. Move to live mode with conservative values:
|
|
720
|
+
|
|
721
|
+
```typescript
|
|
722
|
+
learningShadowMode: false,
|
|
723
|
+
learningBoostFactor: 20,
|
|
724
|
+
learningExplorationRate: 0.005,
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
4. Compare deltas:
|
|
728
|
+
- `Throughput delta` should stay above your SLO floor (e.g. not below `-2%`).
|
|
729
|
+
- `Completion rate delta` should be positive.
|
|
730
|
+
- `Quality score delta` should be positive.
|
|
731
|
+
|
|
732
|
+
5. If throughput regresses too much:
|
|
733
|
+
- Reduce `learningBoostFactor`.
|
|
734
|
+
- Reduce `learningExplorationRate`.
|
|
735
|
+
- Reduce `relevantBatchSize`.
|
|
736
|
+
- Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
|
|
737
|
+
|
|
738
|
+
6. If quality lift is too small:
|
|
739
|
+
- Increase `learningBoostFactor` gradually (`+10` per step).
|
|
740
|
+
- Increase `learningExplorationRate` slightly (`+0.005`), capped at `0.05`.
|
|
741
|
+
- Improve signal quality in `learningSignalWeights`.
|
|
742
|
+
|
|
743
|
+
### Reading Benchmark Deltas Quickly
|
|
744
|
+
|
|
745
|
+
Example:
|
|
746
|
+
|
|
747
|
+
```text
|
|
748
|
+
Throughput delta: -5.11%
|
|
749
|
+
Completion rate delta: +4.80pp
|
|
750
|
+
Quality score delta: +0.0274
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
Interpretation:
|
|
754
|
+
1. You traded some speed (`-5.11%`) for better outcomes.
|
|
755
|
+
2. Completion improved by **4.80 percentage points** (`pp`, not percent).
|
|
756
|
+
3. Quality improved overall (`+0.0274`).
|
|
757
|
+
|
|
758
|
+
Choose the config where business utility is highest for your constraints.
|
|
759
|
+
If throughput is the hard constraint, keep throughput delta near zero and accept smaller quality gains.
|
|
760
|
+
|
|
256
761
|
## Detailed Example & Performance Insights
|
|
257
762
|
|
|
258
763
|
The following example demonstrates adding multiple users and assignments and then measures the performance of the matching process.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import AssignmentMatcher from './matcher.class';
|
|
2
2
|
export type { Assignment, options, Stats, User } from './matcher.class';
|
|
3
|
-
export type { WorkflowDefinition, WorkflowInstance, WorkflowStep, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, } from './matcher.class';
|
|
3
|
+
export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, WorkflowTargetUser, WorkflowMachineTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, PendingAssignmentInfo, } from './matcher.class';
|
|
4
|
+
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
4
5
|
export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow, } from './workflow-builder';
|
|
6
|
+
export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
|
|
5
7
|
export * from './utils/cidr';
|
|
6
8
|
export { createKeyBuilders, type KeyBuilders, type RedisKeyConfig } from './utils/keys';
|
|
7
9
|
export { AssignmentMatcher };
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAGxE,YAAY,EACR,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAGxE,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,qBAAqB,GACxB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG7E,OAAO,EACH,eAAe,EACf,mBAAmB,EACnB,QAAQ,EACR,cAAc,EACd,gBAAgB,GACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -17,9 +17,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
17
17
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
18
|
};
|
|
19
19
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
-
exports.AssignmentMatcher = exports.createKeyBuilders = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = void 0;
|
|
20
|
+
exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.cosineSimilarity = exports.extractMatchFeatures = void 0;
|
|
21
21
|
const matcher_class_1 = __importDefault(require("./matcher.class"));
|
|
22
22
|
exports.AssignmentMatcher = matcher_class_1.default;
|
|
23
|
+
// Learning feature helpers (for custom feature extractors)
|
|
24
|
+
var features_1 = require("./learning/features");
|
|
25
|
+
Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
|
|
26
|
+
Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: function () { return features_1.cosineSimilarity; } });
|
|
23
27
|
// Workflow builder DSL
|
|
24
28
|
var workflow_builder_1 = require("./workflow-builder");
|
|
25
29
|
Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
|
|
@@ -27,6 +31,9 @@ Object.defineProperty(exports, "WorkflowStepBuilder", { enumerable: true, get: f
|
|
|
27
31
|
Object.defineProperty(exports, "workflow", { enumerable: true, get: function () { return workflow_builder_1.workflow; } });
|
|
28
32
|
Object.defineProperty(exports, "linearWorkflow", { enumerable: true, get: function () { return workflow_builder_1.linearWorkflow; } });
|
|
29
33
|
Object.defineProperty(exports, "approvalWorkflow", { enumerable: true, get: function () { return workflow_builder_1.approvalWorkflow; } });
|
|
34
|
+
var workflow_validation_1 = require("./workflow-validation");
|
|
35
|
+
Object.defineProperty(exports, "normalizeWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.normalizeWorkflowDefinition; } });
|
|
36
|
+
Object.defineProperty(exports, "validateWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.validateWorkflowDefinition; } });
|
|
30
37
|
// Utility exports for advanced usage
|
|
31
38
|
__exportStar(require("./utils/cidr"), exports);
|
|
32
39
|
var keys_1 = require("./utils/keys");
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default feature extraction for the learning (contextual bandit) layer.
|
|
3
|
+
*
|
|
4
|
+
* Produces a sparse feature vector describing how well a user matches an
|
|
5
|
+
* assignment. All features are normalized to roughly [0, 1] so learned
|
|
6
|
+
* weights stay comparable across feature families.
|
|
7
|
+
*/
|
|
8
|
+
import type { User, LearningFeatures, LearningAssignmentContext } from '../types/matcher';
|
|
9
|
+
/**
|
|
10
|
+
* Cosine similarity between two numeric vectors.
|
|
11
|
+
* Returns 0 for mismatched lengths or zero-magnitude vectors.
|
|
12
|
+
*/
|
|
13
|
+
export declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
14
|
+
/**
|
|
15
|
+
* Default feature extractor: tag matches, normalized skill weights,
|
|
16
|
+
* tag-overlap ratio, and optional embedding similarity.
|
|
17
|
+
*/
|
|
18
|
+
export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext): LearningFeatures;
|
|
19
|
+
//# sourceMappingURL=features.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../../src/learning/features.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAG1F;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAYjE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,yBAAyB,GAAG,gBAAgB,CA6BxG"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.extractMatchFeatures = exports.cosineSimilarity = void 0;
|
|
4
|
+
const match_score_1 = require("../scoring/match-score");
|
|
5
|
+
/**
|
|
6
|
+
* Cosine similarity between two numeric vectors.
|
|
7
|
+
* Returns 0 for mismatched lengths or zero-magnitude vectors.
|
|
8
|
+
*/
|
|
9
|
+
function cosineSimilarity(a, b) {
|
|
10
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length)
|
|
11
|
+
return 0;
|
|
12
|
+
let dot = 0;
|
|
13
|
+
let normA = 0;
|
|
14
|
+
let normB = 0;
|
|
15
|
+
for (let i = 0; i < a.length; i++) {
|
|
16
|
+
dot += a[i] * b[i];
|
|
17
|
+
normA += a[i] * a[i];
|
|
18
|
+
normB += b[i] * b[i];
|
|
19
|
+
}
|
|
20
|
+
if (normA === 0 || normB === 0)
|
|
21
|
+
return 0;
|
|
22
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
23
|
+
}
|
|
24
|
+
exports.cosineSimilarity = cosineSimilarity;
|
|
25
|
+
/**
|
|
26
|
+
* Default feature extractor: tag matches, normalized skill weights,
|
|
27
|
+
* tag-overlap ratio, and optional embedding similarity.
|
|
28
|
+
*/
|
|
29
|
+
function extractMatchFeatures(user, assignment) {
|
|
30
|
+
const features = { bias: 1 };
|
|
31
|
+
const userTags = new Set(user.tags || []);
|
|
32
|
+
const assignmentTags = assignment.tags || [];
|
|
33
|
+
let overlapCount = 0;
|
|
34
|
+
for (const tag of assignmentTags) {
|
|
35
|
+
if (userTags.has(tag)) {
|
|
36
|
+
features[`tag:${tag}`] = 1;
|
|
37
|
+
overlapCount++;
|
|
38
|
+
}
|
|
39
|
+
if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
|
|
40
|
+
const weight = (0, match_score_1.getEffectiveWeight)(user.routingWeights, tag);
|
|
41
|
+
if (weight > 0) {
|
|
42
|
+
// Normalize assuming the conventional 0-100 weight scale, capped at 1.
|
|
43
|
+
features[`skill:${tag}`] = Math.min(weight / 100, 1);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (assignmentTags.length > 0) {
|
|
48
|
+
features.overlap = overlapCount / assignmentTags.length;
|
|
49
|
+
}
|
|
50
|
+
if (Array.isArray(user.embedding) && Array.isArray(assignment.embedding)) {
|
|
51
|
+
features['emb:sim'] = cosineSimilarity(user.embedding, assignment.embedding);
|
|
52
|
+
}
|
|
53
|
+
return features;
|
|
54
|
+
}
|
|
55
|
+
exports.extractMatchFeatures = extractMatchFeatures;
|