assignment-user-matcher 1.2.1 → 1.2.3

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.
Files changed (43) hide show
  1. package/README.md +609 -5
  2. package/dist/index.d.ts +7 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -1
  5. package/dist/learning/auto-weights.d.ts +31 -0
  6. package/dist/learning/auto-weights.d.ts.map +1 -0
  7. package/dist/learning/auto-weights.js +65 -0
  8. package/dist/learning/features.d.ts +19 -0
  9. package/dist/learning/features.d.ts.map +1 -0
  10. package/dist/learning/features.js +55 -0
  11. package/dist/lua/workflow-transition.lua +29 -0
  12. package/dist/managers/LearningManager.d.ts +129 -0
  13. package/dist/managers/LearningManager.d.ts.map +1 -0
  14. package/dist/managers/LearningManager.js +269 -0
  15. package/dist/managers/ReliabilityManager.d.ts +60 -2
  16. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  17. package/dist/managers/ReliabilityManager.js +190 -9
  18. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  19. package/dist/managers/WorkflowManager.d.ts +80 -6
  20. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  21. package/dist/managers/WorkflowManager.js +464 -81
  22. package/dist/matcher.class.d.ts +180 -13
  23. package/dist/matcher.class.d.ts.map +1 -1
  24. package/dist/matcher.class.js +632 -46
  25. package/dist/queries/pagination.d.ts.map +1 -1
  26. package/dist/queries/pagination.js +9 -6
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +1 -1
  29. package/dist/types/matcher.d.ts +258 -9
  30. package/dist/types/matcher.d.ts.map +1 -1
  31. package/dist/utils/geo.d.ts +26 -0
  32. package/dist/utils/geo.d.ts.map +1 -0
  33. package/dist/utils/geo.js +62 -0
  34. package/dist/utils/keys.d.ts +15 -0
  35. package/dist/utils/keys.d.ts.map +1 -1
  36. package/dist/utils/keys.js +17 -0
  37. package/dist/workflow-builder.d.ts +2 -4
  38. package/dist/workflow-builder.d.ts.map +1 -1
  39. package/dist/workflow-builder.js +4 -46
  40. package/dist/workflow-validation.d.ts +4 -0
  41. package/dist/workflow-validation.d.ts.map +1 -0
  42. package/dist/workflow-validation.js +85 -0
  43. package/package.json +4 -2
package/README.md CHANGED
@@ -51,11 +51,29 @@ Traditional matching systems can become bottlenecks, leading to delays, suboptim
51
51
  2. **Matching via Tag Intersection:**
52
52
  The core matching logic finds users whose tags have a common intersection with an assignment's tags.
53
53
 
54
- When using `routingWeights` with the built-in matcher:
55
- - Only **positive** weights (`> 0`) make assignments eligible.
56
- - Weight `0` is a **hard veto** (exact tag or suffix wildcard like `lang:*`).
57
- - Wildcards are **suffix-only** (`prefix*`). Patterns like `skill:*:node` are not treated as wildcards.
58
- - If a user has `routingWeights` but no positive entries, assignments stay queued.
54
+ When using `routingWeights` with the built-in matcher:
55
+
56
+ - Only **positive** weights (`> 0`) make assignments eligible.
57
+ - Weight `0` is a **hard veto** (exact tag or suffix wildcard like `lang:*`).
58
+ - Wildcards are **suffix-only** (`prefix*`). Patterns like `skill:*:node` are not treated as wildcards.
59
+ - If a user has `routingWeights` but no positive entries, assignments stay queued.
60
+
61
+ Hard veto configuration example:
62
+
63
+ ```ts
64
+ await assignmentMatcher.addUser({
65
+ id: 'agent_1',
66
+ tags: [],
67
+ routingWeights: {
68
+ 'support:*': 100, // eligible
69
+ 'lang:*': 0, // hard veto for all language-tagged assignments
70
+ default: 0, // hard veto for default matching fallback
71
+ },
72
+ });
73
+ ```
74
+
75
+ Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
76
+ Configure hard veto behavior only through `routingWeights` values.
59
77
 
60
78
  3. **Prioritization Engine:**
61
79
  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.
@@ -149,6 +167,90 @@ async function runExample() {
149
167
  runExample().catch(console.error);
150
168
  ```
151
169
 
170
+ ### 3. Workflow Quick Start
171
+
172
+ Workflows are easiest to use with the builder helpers and the `executeWorkflow()` convenience method.
173
+
174
+ ```typescript
175
+ import AssignmentMatcher, { workflow } from 'assignment-user-matcher';
176
+
177
+ const matcher = new AssignmentMatcher(redisClient, {
178
+ enableWorkflows: true,
179
+ redisPrefix: 'exampleApp:',
180
+ });
181
+
182
+ // Optional if your Redis client is already connected.
183
+ // Useful when the matcher is created with a closed client.
184
+ await matcher.waitUntilReady();
185
+
186
+ const onboardingWorkflow = workflow('onboarding', 'Onboarding')
187
+ .step('profile')
188
+ .name('Complete profile')
189
+ .assignment({ tags: ['profile'], title: 'Complete your profile' })
190
+ .targetUser('initiator')
191
+ .defaultNext('review')
192
+ .done()
193
+ .step('review')
194
+ .name('Manager review')
195
+ .assignment({ tags: ['review'], title: 'Review onboarding' })
196
+ .targetUser({ tag: 'managers' })
197
+ .defaultNext(null)
198
+ .done()
199
+ .build();
200
+
201
+ // Registers the definition if needed, then starts the workflow instance.
202
+ const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
203
+ source: 'signup',
204
+ });
205
+
206
+ console.log(instance.id, instance.currentStepId);
207
+ ```
208
+
209
+ You can still call `registerWorkflow()` and `startWorkflow()` separately if you want explicit lifecycle control.
210
+
211
+ Plain object workflow definitions are also accepted. The library now fills in sensible defaults:
212
+
213
+ - `version` defaults to `1`
214
+ - `initialStepId` defaults to the first step ID
215
+ - invalid definitions fail early during registration with clear validation errors
216
+
217
+ ### 4. Scaling & Reliability for Workflows
218
+
219
+ The workflow engine is designed to run with many orchestrator replicas over large instance counts. The key building blocks:
220
+
221
+ - **Indexed step timeouts** — step expirations are tracked in a sorted set and claimed atomically, so `processExpiredWorkflowSteps()` is O(due steps) instead of scanning every instance, and an expiry fires on exactly one replica.
222
+ - **In-place conflict retries** — optimistic-lock (`VERSION_MISMATCH`) conflicts are retried immediately with a fresh read instead of waiting for the orphan-reclaim window.
223
+ - **Delayed retry queue** — failed events are scheduled for retry with exponential backoff (`workflowRetryBackoffMs`, default 1000ms initial delay) and drained automatically by the orchestrator; retries are claimed atomically across replicas.
224
+ - **Flow rate control** — tune orchestrator throughput per replica: `workflowEventBatchSize` (XREADGROUP COUNT, default 10), `workflowPollBlockMs` (blocking poll wait, default 5000ms), and `workflowMaxEventsPerSecond` to cap event processing (applies to both stream consumption and retry draining; unlimited when unset).
225
+ - **Per-event idempotency markers** — processed-event markers carry their own TTL (`workflowIdempotencyTtlMs`), and replayed step executions generate deterministic assignment IDs so crash-replays never create duplicate assignments.
226
+ - **Shared circuit breaker** — set `circuitBreakerShared: true` to converge breaker state across replicas through a shared Redis failure counter (recommended for multi-replica deployments).
227
+ - **Instance retention** — set `workflowInstanceRetentionMs` to expire terminal (completed/failed/cancelled) instances and clean their registry/index entries. Unset (the default) keeps them forever, matching previous behavior; a value in the range of days to weeks is recommended for high-volume deployments.
228
+
229
+ Operational helpers:
230
+
231
+ ```typescript
232
+ const matcher = new AssignmentMatcher(redisClient, {
233
+ enableWorkflows: true,
234
+ circuitBreakerShared: true,
235
+ workflowInstanceRetentionMs: 30 * 24 * 60 * 60 * 1000, // 30 days
236
+ });
237
+
238
+ // Machine steps can run through named handlers with timeout enforcement
239
+ // (step.timeoutMs / defaultTimeoutMs); falls back to executeMachineTask.
240
+ matcher.registerMachineHandler('score-lead', async ({ instance, step }) => {
241
+ return { score: 42 };
242
+ });
243
+
244
+ // One-time migration for deployments created before the indexes existed
245
+ await matcher.backfillWorkflowIndexes();
246
+
247
+ // Periodic maintenance for deployments without retention configured
248
+ await matcher.pruneWorkflowInstances(30 * 24 * 60 * 60 * 1000);
249
+
250
+ // Monitoring: active instances, retry queue depth, DLQ size, stream stats
251
+ const metrics = await matcher.getWorkflowMetrics();
252
+ ```
253
+
152
254
  ## API Reference
153
255
 
154
256
  The main class provided is `AssignmentMatcher`.
@@ -188,6 +290,16 @@ Retrieves the current list of assignments that a user is tentatively matched wit
188
290
 
189
291
  - `userId: string`: The ID of the user.
190
292
 
293
+ ### `getPendingAssignmentsWithAge(): Promise<PendingAssignmentInfo[]>`
294
+
295
+ Retrieves current pending assignments, including who owns each assignment and how long it has been pending.
296
+
297
+ - `assignment`: The assignment payload.
298
+ - `ownerId`: The current owner user ID, or `null` if missing.
299
+ - `pendingForMs`: Elapsed pending time in milliseconds.
300
+ - `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
301
+ - `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
302
+
191
303
  ### `removeUser(userId: string): Promise<void>`
192
304
 
193
305
  Removes a user from the system and clears their assignment backlog.
@@ -200,6 +312,17 @@ Removes a specific assignment from the system. Requires tags to efficiently loca
200
312
 
201
313
  Marks an assignment as completed by a user, removing it from their backlog and potentially making them available for new assignments.
202
314
 
315
+ ### `waitUntilReady(): Promise<AssignmentMatcher>`
316
+
317
+ Waits for the matcher to finish connecting and initializing internal Redis and workflow resources.
318
+
319
+ ### `executeWorkflow(workflowOrId, userId, initialContext?): Promise<WorkflowInstance>`
320
+
321
+ The simplest workflow entrypoint.
322
+
323
+ - Pass a workflow ID to start an already-registered workflow.
324
+ - Pass a workflow definition or builder-produced definition to register it and start it in one call.
325
+
203
326
  ## Options
204
327
 
205
328
  You can pass an options object to the `AssignmentMatcher` constructor:
@@ -227,6 +350,16 @@ type Options = {
227
350
  // If set to false, you should provide a custom `matchingFunction`.
228
351
  enableDefaultMatching?: boolean; // Default: true
229
352
 
353
+ // Opt-in idle user auto-rejection. When set, users holding pending
354
+ // (not yet accepted/rejected) assignments with no activity for this many
355
+ // milliseconds are removed from the matching pool by `processIdleUsers()`,
356
+ // and their pending assignments are requeued for other users.
357
+ // Activity is recorded automatically on addUser/acceptAssignment/rejectAssignment,
358
+ // or explicitly via `touchUser(userId)` as a heartbeat.
359
+ // Use `startIdleUserInterval(intervalMs)` / `stopIdleUserInterval()` to run
360
+ // the check periodically. Disabled when undefined (default).
361
+ idleUserTimeoutMs?: number; // Default: undefined (disabled)
362
+
230
363
  // A custom function to determine the priority of an assignment.
231
364
  // The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
232
365
  // and should return a numerical priority score. Higher scores mean higher priority.
@@ -250,9 +383,480 @@ type Options = {
250
383
  assignmentPriority: number | string, // This is the score from prioritizationFunction or createdAt
251
384
  assignmentId?: string,
252
385
  ) => Promise<[number, number]>;
386
+
387
+ // ========== Reinforcement Learning Options ==========
388
+
389
+ // Enable the adaptive learning layer (contextual bandit re-ranking).
390
+ enableLearning?: boolean; // Default: false
391
+
392
+ // SGD learning rate for online model updates.
393
+ learningRate?: number; // Default: 0.1
394
+
395
+ // Epsilon-greedy exploration rate in [0, 1]. With this probability, a random
396
+ // jitter is added to candidate scores so the model keeps gathering data on
397
+ // under-served candidates.
398
+ learningExplorationRate?: number; // Default: 0.05
399
+
400
+ // Shadow mode: record decisions and learn from outcomes, but never alter
401
+ // ranking. Useful for safely evaluating the model before going live.
402
+ learningShadowMode?: boolean; // Default: false
403
+
404
+ // Multiplier applied to the predicted reward when re-ranking candidates.
405
+ // Higher values let the learned model dominate over base priority.
406
+ learningBoostFactor?: number; // Default: 1
407
+
408
+ // Override rewards per lifecycle outcome (merged with defaults):
409
+ // { accept: 0.3, complete: 1, reject: -0.6, expire: -0.3, fail: -0.8 }
410
+ learningRewards?: Partial<Record<'accept' | 'complete' | 'reject' | 'expire' | 'fail', number>>;
411
+
412
+ // Custom feature extractor. Defaults to tag-match, normalized skill-weight,
413
+ // tag-overlap-ratio and embedding-similarity features.
414
+ learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
415
+
416
+ // TTL for stored decision contexts in ms.
417
+ learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
418
+
419
+ // Weights applied to named external feedback signals when computing rewards.
420
+ // Signals not listed here default to weight 1. Negative weights turn a
421
+ // signal into a penalty (e.g. { errorRate: -2 }).
422
+ learningSignalWeights?: Record<string, number>;
423
+
424
+ // TTL for archived episodes awaiting late external feedback in ms.
425
+ learningFeedbackTtlMs?: number; // Default: 604800000 (7 days)
253
426
  };
254
427
  ```
255
428
 
429
+ ## Adaptive Matching with Reinforcement Learning
430
+
431
+ The matcher includes an opt-in, Redis-backed contextual bandit that learns from
432
+ assignment outcomes and re-ranks candidates automatically. Hard matching rules
433
+ (tags, `routingWeights`, vetoes, CIDR, `skillThresholds`) always apply first —
434
+ the learned model only reorders assignments that are already eligible.
435
+
436
+ How it works:
437
+
438
+ 1. When a user is matched, a sparse feature vector is extracted for each
439
+ eligible candidate (tag matches, normalized skill weights, tag overlap, and
440
+ optional `embedding` cosine similarity if both user and assignment carry an
441
+ `embedding: number[]` field).
442
+ 2. Candidates are ranked by `combinedPriority + boostFactor * predictedReward`.
443
+ 3. The decision context is stored, and lifecycle outcomes (`accept`,
444
+ `complete`, `reject`, `expire`, `fail`) feed rewards back into the model via
445
+ online SGD updates — fully automatic, no training pipeline needed.
446
+
447
+ ```typescript
448
+ const matcher = new AssignmentMatcher(redisClient, {
449
+ enableLearning: true,
450
+ // Start safe: observe without affecting ranking
451
+ learningShadowMode: true,
452
+ // Optional reward shaping
453
+ learningRewards: { complete: 2, reject: -1 },
454
+ });
455
+
456
+ // ... normal addUser / addAssignment / matchUsersAssignments usage ...
457
+
458
+ // Inspect what the model has learned
459
+ const model = await matcher.getLearningModel(); // { 'tag:english': '0.42', ... }
460
+ const stats = await matcher.getLearningStats(); // { decisions, rewards, totalReward, averageReward }
461
+
462
+ // Manual reward shaping for a matched assignment (e.g. CSAT score arrived later)
463
+ await matcher.recordLearningReward('assignment-123', 1.5);
464
+
465
+ // Start over
466
+ await matcher.resetLearningModel();
467
+ ```
468
+
469
+ ### Feeding External Data into the Model
470
+
471
+ Matchmaking quality signals often arrive after an assignment is closed — QA
472
+ audits, accuracy reviews, customer satisfaction scores, handle-time analysis.
473
+ The learning layer supports three external feed paths:
474
+
475
+ **1. Named feedback signals (post-processing per assignment).** When an
476
+ assignment reaches a terminal state, its feature context is archived as an
477
+ _episode_ (kept for `learningFeedbackTtlMs`). External pipelines can attribute
478
+ late signals to it at any point within that window:
479
+
480
+ ```typescript
481
+ const matcher = new AssignmentMatcher(redisClient, {
482
+ enableLearning: true,
483
+ // Reward = sum(signalValue * signalWeight); unlisted signals default to 1
484
+ learningSignalWeights: {
485
+ accuracy: 2, // accuracy audits matter most
486
+ csat: 1, // customer satisfaction
487
+ handleTimePenalty: -0.5, // longer handling reduces reward
488
+ },
489
+ });
490
+
491
+ // ...assignment is matched, accepted, completed...
492
+
493
+ // Hours/days later, the QA pipeline reports back:
494
+ await matcher.recordLearningFeedback('assignment-123', {
495
+ accuracy: 0.95,
496
+ csat: 0.8,
497
+ handleTimePenalty: 0.3,
498
+ });
499
+ // reward = 0.95*2 + 0.8*1 + 0.3*-0.5 = 2.55, applied to the episode's features
500
+ ```
501
+
502
+ **2. Raw reward shaping.** `recordLearningReward(assignmentId, reward)` applies
503
+ an explicit numeric reward against an assignment's decision context when you
504
+ want full control over the value.
505
+
506
+ **3. Offline batch training.** `trainLearningSamples(samples)` updates the
507
+ model directly from raw `(features, reward)` pairs — no live decision context
508
+ needed. Use it to bootstrap the model from historical data or to run scheduled
509
+ imports from a data warehouse:
510
+
511
+ ```typescript
512
+ await matcher.trainLearningSamples([
513
+ { features: { bias: 1, 'tag:english': 1, 'skill:english': 0.8 }, reward: 1.2 },
514
+ { features: { bias: 1, 'tag:billing': 1 }, reward: -0.4 },
515
+ ]);
516
+ ```
517
+
518
+ Feature names are arbitrary strings — as long as your
519
+ `learningFeatureExtractor` produces the same names at match time, externally
520
+ trained weights apply immediately to live ranking.
521
+
522
+ Rollout recommendation: enable with `learningShadowMode: true` first, watch
523
+ `getLearningStats()` and `getLearningModel()`, then flip shadow mode off and
524
+ tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
525
+ domain-specific setups (custom embeddings, business features), supply a
526
+ `learningFeatureExtractor`.
527
+
528
+ ### Automatic Routing Weights (RL-Generated Tags/Weights)
529
+
530
+ Beyond re-ranking, the learning layer can fully automate `routingWeights`
531
+ authoring. With `enableAutoRoutingWeights: true` (requires `enableLearning`),
532
+ every reward observation also updates per-user, per-tag statistics in Redis
533
+ (atomic `HINCRBY`/`HINCRBYFLOAT` — O(tags) per outcome, no scans, no
534
+ read-modify-write), and weights are synthesized on demand with a UCB1 bandit
535
+ policy:
536
+
537
+ - tags with a high mean reward get proportionally high weights (UCB
538
+ exploration bonus favors less-sampled tags),
539
+ - tags with a mean reward at/below `vetoThreshold` (after `minSamples`
540
+ observations) get weight `0` — the matcher's hard-veto semantics,
541
+ - under-sampled or unobserved known tags get an optimistic `priorWeight` so
542
+ the system keeps exploring them.
543
+
544
+ ```typescript
545
+ const matcher = new AssignmentMatcher(redisClient, {
546
+ enableLearning: true,
547
+ enableAutoRoutingWeights: true,
548
+ autoRoutingWeights: {
549
+ minSamples: 5, // observations before a tag's stats are trusted
550
+ vetoThreshold: -0.5, // mean reward at/below this → weight 0 (hard veto)
551
+ maxWeight: 100, // top of the synthesized weight scale
552
+ explorationBonus: 0.5, // UCB coefficient; higher → more exploration
553
+ priorWeight: 50, // optimistic weight for unexplored tags
554
+ },
555
+ });
556
+
557
+ // Inspect what the system has learned for a user
558
+ const stats = await matcher.getLearnedTagStats('user-1');
559
+ const preview = await matcher.getLearnedRoutingWeights('user-1');
560
+
561
+ // Apply learned weights to one user, or to all tracked users (e.g. on a
562
+ // periodic job). Manual routingWeights entries for tags the learner has no
563
+ // data on are preserved; pass { overrideManual: true } to replace them.
564
+ await matcher.syncLearnedRoutingWeights('user-1');
565
+ await matcher.syncLearnedRoutingWeights(); // all tracked users
566
+
567
+ // Include exploration priors for known tags the user has never seen:
568
+ await matcher.syncLearnedRoutingWeights('user-1', { includeUnexploredTags: true });
569
+ ```
570
+
571
+ Synthesis happens outside the matching hot path — matching itself reads the
572
+ user's stored `routingWeights` exactly as before, so the per-match cost is
573
+ unchanged. The last-applied learned map is stored on the user as
574
+ `learnedRoutingWeights` for observability, and `resetLearningModel()` clears
575
+ all per-user tag statistics. The pure synthesis function is exported as
576
+ `synthesizeRoutingWeights` for offline pipelines.
577
+
578
+ ### RL Scalability & Redis Constraints
579
+
580
+ The RL layer adds controlled overhead: decision recording, outcome archival,
581
+ and weight updates. Because these operations are write-heavy and per-assignment,
582
+ scalability depends primarily on Redis memory, write throughput, and feature
583
+ cardinality — not on learning math itself.
584
+
585
+ #### Redis Workload Breakdown
586
+
587
+ Each matched assignment now costs:
588
+
589
+ 1. **Decision record** (live): ~300 bytes for features + metadata; expires in 7 days (configurable).
590
+ 2. **Episode archive** (terminal): ~400 bytes; kept until feedback arrives, expires in 7 days.
591
+ 3. **Model updates**: One hash increment per feature per outcome (typically 5–15 features).
592
+ 4. **Stats tracking**: Shared atomic increments.
593
+
594
+ Matching a single assignment typically involves:
595
+
596
+ - 1–2 Redis reads (model + candidate details).
597
+ - 3–5 Redis writes per matched assignment (decision, model updates, stats).
598
+ - Pipelined to reduce round trips.
599
+
600
+ #### Memory Estimation
601
+
602
+ Assume:
603
+
604
+ - **Small deployment**: 10 users, 1,000 live assignments, ~8 features per assignment.
605
+
606
+ - Model: ~8 KB (8 features × 1 KB per weight + overhead).
607
+ - Decisions: ~300 KB (1,000 × 300 bytes).
608
+ - Overhead: ~500 KB for indices and stats.
609
+ - **Total: ~1 MB**. No scaling issues with standard Redis (safe at anything).
610
+
611
+ - **Medium deployment**: 100 users, 100,000 live assignments, ~15 features.
612
+
613
+ - Model: ~15 KB.
614
+ - Decisions: ~30 MB (100,000 × 300 bytes).
615
+ - Episodes archived: ~10 MB (depends on feedback delay; typically 10% of live at any moment).
616
+ - Overhead: ~5 MB.
617
+ - **Total: ~50 MB**. Easily within Redis limits; watch growth over weeks.
618
+
619
+ - **High-throughput deployment**: 1,000 users, 1,000,000 live assignments, ~20 features, exploration enabled.
620
+ - Model: ~20 KB.
621
+ - Decisions: ~300 MB (1,000,000 × 300 bytes).
622
+ - Episodes: ~100 MB.
623
+ - Overhead: ~50 MB.
624
+ - **Total: ~450 MB**. Manageable with a 2–4 GB Redis instance; requires TTL discipline.
625
+
626
+ #### Configuration Guidelines
627
+
628
+ **Small (10–50 users, <10K assignments/day):**
629
+
630
+ ```typescript
631
+ const matcher = new AssignmentMatcher(redisClient, {
632
+ enableLearning: true,
633
+ learningShadowMode: true, // Observe first; no ranking impact
634
+ learningRate: 0.1,
635
+ learningExplorationRate: 0, // No exploration overhead
636
+ learningDecisionTtlMs: 604800000, // 7 days
637
+ learningFeedbackTtlMs: 604800000, // 7 days
638
+ });
639
+ // Safe: no performance issues. Monitor model size weekly.
640
+ ```
641
+
642
+ **Medium (50–500 users, 10K–100K assignments/day):**
643
+
644
+ ```typescript
645
+ const matcher = new AssignmentMatcher(redisClient, {
646
+ enableLearning: true,
647
+ learningShadowMode: false,
648
+ learningRate: 0.05, // Slower learning for stability
649
+ learningExplorationRate: 0.02, // 2% of matches explore randomly
650
+ learningBoostFactor: 50, // Moderate impact on ranking
651
+ learningDecisionTtlMs: 259200000, // 3 days (balance TTL vs memory)
652
+ learningFeedbackTtlMs: 259200000,
653
+ learningSignalWeights: { accuracy: 1, csat: 0.5, errorRate: -1 },
654
+ });
655
+ // Recommended: batch external feedback imports off-peak.
656
+ // Monitor: Redis memory growth, write latency, decision key count.
657
+ ```
658
+
659
+ **High-throughput (500+ users, 100K+ assignments/day):**
660
+
661
+ ```typescript
662
+ const matcher = new AssignmentMatcher(redisClient, {
663
+ enableLearning: true,
664
+ learningShadowMode: false,
665
+ learningRate: 0.02, // Conservative learning rate
666
+ learningExplorationRate: 0.01, // Minimal exploration (1%)
667
+ learningBoostFactor: 30, // Restrained boost to avoid instability
668
+ learningDecisionTtlMs: 86400000, // 1 day (shorter TTL for faster cleanup)
669
+ learningFeedbackTtlMs: 172800000, // 2 days (stagger feedback arrival)
670
+ learningSignalWeights: { accuracy: 1, csat: 0.3 }, // Fewer signals = less noise
671
+ // Consider sampling outcomes if traffic is extreme:
672
+ // Only learn from 10% of low-priority assignments.
673
+ });
674
+ // Monitoring critical: set up Redis memory alerts, track write amplification.
675
+ // Consider a separate Redis instance for RL state if main matcher instance is saturated.
676
+ ```
677
+
678
+ #### Safety Guardrails
679
+
680
+ 1. **Keep hard rules outside RL.** Eligibility, vetoes, backlog limits, and lifecycle state remain deterministic. RL only adjusts ranking of already-eligible candidates.
681
+ 2. **Start shadow mode.** Always enable `learningShadowMode: true` for the first week, then migrate to live mode with guardrails in place.
682
+ 3. **Cap exploration.** Set `learningExplorationRate ≤ 0.05` (5%). Exploration is important for learning but creates churn and can impact user experience.
683
+ 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.
684
+ 5. **Batch feedback imports.** Run external QA/accuracy signal imports as background jobs during low-traffic windows, not inline with matching.
685
+ 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.
686
+ 7. **Separate concerns.** If your matcher handles 1M+ assignments/day, use a dedicated Redis instance for RL state, separate from the main queue data.
687
+
688
+ #### Monitoring & Diagnostics
689
+
690
+ Key metrics to track:
691
+
692
+ - **Model size**: `(await matcher.getLearningModel()).length` — should be stable (5–50 features). If growing > 100, your feature extractor is leaking.
693
+ - **Decision cardinality**: `DBSIZE` and filter for `learning:decision:*` — should stay < 2× your `maxUserBacklogSize × numUsers`.
694
+ - **Learning stats**: `getLearningStats()` — watch `averageReward` drift and `decisions` growth rate. If `averageReward` is always zero or NaN, your reward signals are malformed.
695
+ - **Redis memory**: Keep below 70% of instance limit. Set memory alerts.
696
+ - **Write latency**: Track Redis command latencies (`latency latest`). Spikes indicate contention; consider sharding or a larger instance.
697
+ - **Model convergence**: Periodically log `getLearningModel()` weights and compare week-over-week. Sharp weight changes suggest concept drift or noisy rewards.
698
+
699
+ #### Recommended Production Workflow
700
+
701
+ 1. Deploy with `learningShadowMode: true` and `learningExplorationRate: 0` for 1–2 weeks.
702
+ 2. Validate that `getLearningStats()` shows growing reward without ranking instability.
703
+ 3. Switch to live mode with low `learningExplorationRate` (0.01–0.02).
704
+ 4. Set up external feedback pipeline (QA, CSAT, etc.) and test with a small sample.
705
+ 5. Gradually increase `boostFactor` and `explorationRate` based on business metrics (completion rate, SLA, re-open rate).
706
+ 6. Monitor weekly; roll back or reduce `boostFactor` if metrics degrade.
707
+
708
+ ### Learning Benchmark Simulation
709
+
710
+ Use the built-in simulation benchmark to compare baseline routing vs learning shadow mode vs live learning mode on the same deterministic workload.
711
+
712
+ Run with defaults:
713
+
714
+ ```bash
715
+ pnpm benchmark:learning
716
+ ```
717
+
718
+ Run with custom scale:
719
+
720
+ ```bash
721
+ pnpm benchmark:learning -- 300 8000 10 20260611
722
+ # arguments: <users> <assignmentsPerRound> <rounds> <seed>
723
+ ```
724
+
725
+ Output includes:
726
+
727
+ 1. Per-mode throughput and latency (`baseline`, `learning-shadow`, `learning-live`)
728
+ 2. Acceptance/completion/rejection/failure rates
729
+ 3. A normalized quality score for quick comparisons
730
+ 4. Top learned model weights
731
+ 5. Delta summary vs baseline (throughput, completion rate, quality)
732
+
733
+ ### Configuration Playbook (How To Choose)
734
+
735
+ Use this quick guide based on your primary goal.
736
+
737
+ #### Throughput-first (minimal latency impact)
738
+
739
+ ```typescript
740
+ const matcher = new AssignmentMatcher(redisClient, {
741
+ enableLearning: true,
742
+ learningShadowMode: false,
743
+ learningExplorationRate: 0.005,
744
+ learningBoostFactor: 20,
745
+ learningRate: 0.02,
746
+ learningDecisionTtlMs: 86400000,
747
+ learningFeedbackTtlMs: 86400000,
748
+ relevantBatchSize: 50,
749
+ maxUserBacklogSize: 1,
750
+ });
751
+ ```
752
+
753
+ When to use:
754
+
755
+ 1. You have tight p95/p99 latency SLOs.
756
+ 2. Even a 2-5% throughput drop is expensive.
757
+
758
+ #### Balanced (recommended starting point)
759
+
760
+ ```typescript
761
+ const matcher = new AssignmentMatcher(redisClient, {
762
+ enableLearning: true,
763
+ learningShadowMode: false,
764
+ learningExplorationRate: 0.01,
765
+ learningBoostFactor: 35,
766
+ learningRate: 0.05,
767
+ learningDecisionTtlMs: 259200000,
768
+ learningFeedbackTtlMs: 259200000,
769
+ relevantBatchSize: 100,
770
+ maxUserBacklogSize: 1,
771
+ });
772
+ ```
773
+
774
+ When to use:
775
+
776
+ 1. You want measurable quality lift with moderate performance cost.
777
+ 2. You can tolerate small throughput swings while tuning.
778
+
779
+ #### Quality-first (maximize learning impact)
780
+
781
+ ```typescript
782
+ const matcher = new AssignmentMatcher(redisClient, {
783
+ enableLearning: true,
784
+ learningShadowMode: false,
785
+ learningExplorationRate: 0.02,
786
+ learningBoostFactor: 60,
787
+ learningRate: 0.08,
788
+ learningDecisionTtlMs: 604800000,
789
+ learningFeedbackTtlMs: 604800000,
790
+ relevantBatchSize: 200,
791
+ maxUserBacklogSize: 1,
792
+ });
793
+ ```
794
+
795
+ When to use:
796
+
797
+ 1. Completion/quality metrics matter more than raw throughput.
798
+ 2. You have enough headroom in Redis and CPU.
799
+
800
+ ### How To Tune It (Step by Step)
801
+
802
+ 1. Start with **shadow mode** and exploration off:
803
+
804
+ ```typescript
805
+ learningShadowMode: true,
806
+ learningExplorationRate: 0,
807
+ ```
808
+
809
+ 2. Run baseline benchmark and record metrics:
810
+
811
+ ```bash
812
+ pnpm benchmark:learning -- 100 1000 10 42
813
+ ```
814
+
815
+ 3. Move to live mode with conservative values:
816
+
817
+ ```typescript
818
+ learningShadowMode: false,
819
+ learningBoostFactor: 20,
820
+ learningExplorationRate: 0.005,
821
+ ```
822
+
823
+ 4. Compare deltas:
824
+
825
+ - `Throughput delta` should stay above your SLO floor (e.g. not below `-2%`).
826
+ - `Completion rate delta` should be positive.
827
+ - `Quality score delta` should be positive.
828
+
829
+ 5. If throughput regresses too much:
830
+
831
+ - Reduce `learningBoostFactor`.
832
+ - Reduce `learningExplorationRate`.
833
+ - Reduce `relevantBatchSize`.
834
+ - Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
835
+
836
+ 6. If quality lift is too small:
837
+ - Increase `learningBoostFactor` gradually (`+10` per step).
838
+ - Increase `learningExplorationRate` slightly (`+0.005`), capped at `0.05`.
839
+ - Improve signal quality in `learningSignalWeights`.
840
+
841
+ ### Reading Benchmark Deltas Quickly
842
+
843
+ Example:
844
+
845
+ ```text
846
+ Throughput delta: -5.11%
847
+ Completion rate delta: +4.80pp
848
+ Quality score delta: +0.0274
849
+ ```
850
+
851
+ Interpretation:
852
+
853
+ 1. You traded some speed (`-5.11%`) for better outcomes.
854
+ 2. Completion improved by **4.80 percentage points** (`pp`, not percent).
855
+ 3. Quality improved overall (`+0.0274`).
856
+
857
+ Choose the config where business utility is highest for your constraints.
858
+ If throughput is the hard constraint, keep throughput delta near zero and accept smaller quality gains.
859
+
256
860
  ## Detailed Example & Performance Insights
257
861
 
258
862
  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,8 +1,12 @@
1
1
  import AssignmentMatcher from './matcher.class';
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';
4
- export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow, } from './workflow-builder';
2
+ export type { Assignment, MatcherOptions, options, Stats, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, } from './matcher.class';
3
+ export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
4
+ export { extractMatchFeatures, cosineSimilarity } from './learning/features';
5
+ export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
6
+ export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
7
+ export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
5
8
  export * from './utils/cidr';
9
+ export * from './utils/geo';
6
10
  export { createKeyBuilders, type KeyBuilders, type RedisKeyConfig } from './utils/keys';
7
11
  export { AssignmentMatcher };
8
12
  export default AssignmentMatcher;
@@ -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,GAC/B,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACH,eAAe,EACf,mBAAmB,EACnB,QAAQ,EACR,cAAc,EACd,gBAAgB,GACnB,MAAM,oBAAoB,CAAC;AAG5B,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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,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,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}