assignment-user-matcher 1.2.2 → 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.
- package/README.md +188 -89
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/learning/auto-weights.d.ts +31 -0
- package/dist/learning/auto-weights.d.ts.map +1 -0
- package/dist/learning/auto-weights.js +65 -0
- package/dist/lua/workflow-transition.lua +29 -0
- package/dist/managers/LearningManager.d.ts +39 -4
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +78 -3
- package/dist/managers/ReliabilityManager.d.ts +60 -2
- package/dist/managers/ReliabilityManager.d.ts.map +1 -1
- package/dist/managers/ReliabilityManager.js +190 -9
- package/dist/managers/TelemetryManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.d.ts +78 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +449 -77
- package/dist/matcher.class.d.ts +105 -8
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +307 -37
- package/dist/queries/pagination.d.ts.map +1 -1
- package/dist/queries/pagination.js +9 -6
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +1 -1
- package/dist/types/matcher.d.ts +139 -0
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/geo.d.ts +26 -0
- package/dist/utils/geo.d.ts.map +1 -0
- package/dist/utils/geo.js +62 -0
- package/dist/utils/keys.d.ts +10 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +11 -0
- package/dist/workflow-validation.d.ts.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -51,28 +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
|
-
|
|
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:
|
|
59
55
|
|
|
60
|
-
|
|
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.
|
|
61
60
|
|
|
62
|
-
|
|
63
|
-
|
|
61
|
+
Hard veto configuration example:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
await assignmentMatcher.addUser({
|
|
64
65
|
id: 'agent_1',
|
|
65
66
|
tags: [],
|
|
66
67
|
routingWeights: {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
'support:*': 100, // eligible
|
|
69
|
+
'lang:*': 0, // hard veto for all language-tagged assignments
|
|
70
|
+
default: 0, // hard veto for default matching fallback
|
|
70
71
|
},
|
|
71
|
-
|
|
72
|
-
|
|
72
|
+
});
|
|
73
|
+
```
|
|
73
74
|
|
|
74
|
-
|
|
75
|
-
|
|
75
|
+
Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
|
|
76
|
+
Configure hard veto behavior only through `routingWeights` values.
|
|
76
77
|
|
|
77
78
|
3. **Prioritization Engine:**
|
|
78
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.
|
|
@@ -174,8 +175,8 @@ Workflows are easiest to use with the builder helpers and the `executeWorkflow()
|
|
|
174
175
|
import AssignmentMatcher, { workflow } from 'assignment-user-matcher';
|
|
175
176
|
|
|
176
177
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
177
|
-
|
|
178
|
-
|
|
178
|
+
enableWorkflows: true,
|
|
179
|
+
redisPrefix: 'exampleApp:',
|
|
179
180
|
});
|
|
180
181
|
|
|
181
182
|
// Optional if your Redis client is already connected.
|
|
@@ -183,23 +184,23 @@ const matcher = new AssignmentMatcher(redisClient, {
|
|
|
183
184
|
await matcher.waitUntilReady();
|
|
184
185
|
|
|
185
186
|
const onboardingWorkflow = workflow('onboarding', 'Onboarding')
|
|
186
|
-
|
|
187
|
+
.step('profile')
|
|
187
188
|
.name('Complete profile')
|
|
188
189
|
.assignment({ tags: ['profile'], title: 'Complete your profile' })
|
|
189
190
|
.targetUser('initiator')
|
|
190
191
|
.defaultNext('review')
|
|
191
192
|
.done()
|
|
192
|
-
|
|
193
|
+
.step('review')
|
|
193
194
|
.name('Manager review')
|
|
194
195
|
.assignment({ tags: ['review'], title: 'Review onboarding' })
|
|
195
196
|
.targetUser({ tag: 'managers' })
|
|
196
197
|
.defaultNext(null)
|
|
197
198
|
.done()
|
|
198
|
-
|
|
199
|
+
.build();
|
|
199
200
|
|
|
200
201
|
// Registers the definition if needed, then starts the workflow instance.
|
|
201
202
|
const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
|
|
202
|
-
|
|
203
|
+
source: 'signup',
|
|
203
204
|
});
|
|
204
205
|
|
|
205
206
|
console.log(instance.id, instance.currentStepId);
|
|
@@ -213,6 +214,43 @@ Plain object workflow definitions are also accepted. The library now fills in se
|
|
|
213
214
|
- `initialStepId` defaults to the first step ID
|
|
214
215
|
- invalid definitions fail early during registration with clear validation errors
|
|
215
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
|
+
|
|
216
254
|
## API Reference
|
|
217
255
|
|
|
218
256
|
The main class provided is `AssignmentMatcher`.
|
|
@@ -436,7 +474,7 @@ The learning layer supports three external feed paths:
|
|
|
436
474
|
|
|
437
475
|
**1. Named feedback signals (post-processing per assignment).** When an
|
|
438
476
|
assignment reaches a terminal state, its feature context is archived as an
|
|
439
|
-
|
|
477
|
+
_episode_ (kept for `learningFeedbackTtlMs`). External pipelines can attribute
|
|
440
478
|
late signals to it at any point within that window:
|
|
441
479
|
|
|
442
480
|
```typescript
|
|
@@ -444,8 +482,8 @@ const matcher = new AssignmentMatcher(redisClient, {
|
|
|
444
482
|
enableLearning: true,
|
|
445
483
|
// Reward = sum(signalValue * signalWeight); unlisted signals default to 1
|
|
446
484
|
learningSignalWeights: {
|
|
447
|
-
accuracy: 2,
|
|
448
|
-
csat: 1,
|
|
485
|
+
accuracy: 2, // accuracy audits matter most
|
|
486
|
+
csat: 1, // customer satisfaction
|
|
449
487
|
handleTimePenalty: -0.5, // longer handling reduces reward
|
|
450
488
|
},
|
|
451
489
|
});
|
|
@@ -487,6 +525,56 @@ tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
|
|
|
487
525
|
domain-specific setups (custom embeddings, business features), supply a
|
|
488
526
|
`learningFeatureExtractor`.
|
|
489
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
|
+
|
|
490
578
|
### RL Scalability & Redis Constraints
|
|
491
579
|
|
|
492
580
|
The RL layer adds controlled overhead: decision recording, outcome archival,
|
|
@@ -497,12 +585,14 @@ cardinality — not on learning math itself.
|
|
|
497
585
|
#### Redis Workload Breakdown
|
|
498
586
|
|
|
499
587
|
Each matched assignment now costs:
|
|
588
|
+
|
|
500
589
|
1. **Decision record** (live): ~300 bytes for features + metadata; expires in 7 days (configurable).
|
|
501
590
|
2. **Episode archive** (terminal): ~400 bytes; kept until feedback arrives, expires in 7 days.
|
|
502
591
|
3. **Model updates**: One hash increment per feature per outcome (typically 5–15 features).
|
|
503
592
|
4. **Stats tracking**: Shared atomic increments.
|
|
504
593
|
|
|
505
594
|
Matching a single assignment typically involves:
|
|
595
|
+
|
|
506
596
|
- 1–2 Redis reads (model + candidate details).
|
|
507
597
|
- 3–5 Redis writes per matched assignment (decision, model updates, stats).
|
|
508
598
|
- Pipelined to reduce round trips.
|
|
@@ -510,25 +600,28 @@ Matching a single assignment typically involves:
|
|
|
510
600
|
#### Memory Estimation
|
|
511
601
|
|
|
512
602
|
Assume:
|
|
603
|
+
|
|
513
604
|
- **Small deployment**: 10 users, 1,000 live assignments, ~8 features per assignment.
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
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).
|
|
518
610
|
|
|
519
611
|
- **Medium deployment**: 100 users, 100,000 live assignments, ~15 features.
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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.
|
|
525
618
|
|
|
526
619
|
- **High-throughput deployment**: 1,000 users, 1,000,000 live assignments, ~20 features, exploration enabled.
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
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.
|
|
532
625
|
|
|
533
626
|
#### Configuration Guidelines
|
|
534
627
|
|
|
@@ -537,11 +630,11 @@ Assume:
|
|
|
537
630
|
```typescript
|
|
538
631
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
539
632
|
enableLearning: true,
|
|
540
|
-
learningShadowMode: true,
|
|
633
|
+
learningShadowMode: true, // Observe first; no ranking impact
|
|
541
634
|
learningRate: 0.1,
|
|
542
|
-
learningExplorationRate: 0,
|
|
543
|
-
learningDecisionTtlMs: 604800000,
|
|
544
|
-
learningFeedbackTtlMs: 604800000,
|
|
635
|
+
learningExplorationRate: 0, // No exploration overhead
|
|
636
|
+
learningDecisionTtlMs: 604800000, // 7 days
|
|
637
|
+
learningFeedbackTtlMs: 604800000, // 7 days
|
|
545
638
|
});
|
|
546
639
|
// Safe: no performance issues. Monitor model size weekly.
|
|
547
640
|
```
|
|
@@ -552,10 +645,10 @@ const matcher = new AssignmentMatcher(redisClient, {
|
|
|
552
645
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
553
646
|
enableLearning: true,
|
|
554
647
|
learningShadowMode: false,
|
|
555
|
-
learningRate: 0.05,
|
|
556
|
-
learningExplorationRate: 0.02,
|
|
557
|
-
learningBoostFactor: 50,
|
|
558
|
-
learningDecisionTtlMs: 259200000,
|
|
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)
|
|
559
652
|
learningFeedbackTtlMs: 259200000,
|
|
560
653
|
learningSignalWeights: { accuracy: 1, csat: 0.5, errorRate: -1 },
|
|
561
654
|
});
|
|
@@ -569,12 +662,12 @@ const matcher = new AssignmentMatcher(redisClient, {
|
|
|
569
662
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
570
663
|
enableLearning: true,
|
|
571
664
|
learningShadowMode: false,
|
|
572
|
-
learningRate: 0.02,
|
|
573
|
-
learningExplorationRate: 0.01,
|
|
574
|
-
learningBoostFactor: 30,
|
|
575
|
-
learningDecisionTtlMs: 86400000,
|
|
576
|
-
learningFeedbackTtlMs: 172800000,
|
|
577
|
-
learningSignalWeights: { accuracy: 1, csat: 0.3 },
|
|
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
|
|
578
671
|
// Consider sampling outcomes if traffic is extreme:
|
|
579
672
|
// Only learn from 10% of low-priority assignments.
|
|
580
673
|
});
|
|
@@ -645,19 +738,20 @@ Use this quick guide based on your primary goal.
|
|
|
645
738
|
|
|
646
739
|
```typescript
|
|
647
740
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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,
|
|
657
750
|
});
|
|
658
751
|
```
|
|
659
752
|
|
|
660
753
|
When to use:
|
|
754
|
+
|
|
661
755
|
1. You have tight p95/p99 latency SLOs.
|
|
662
756
|
2. Even a 2-5% throughput drop is expensive.
|
|
663
757
|
|
|
@@ -665,19 +759,20 @@ When to use:
|
|
|
665
759
|
|
|
666
760
|
```typescript
|
|
667
761
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
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,
|
|
677
771
|
});
|
|
678
772
|
```
|
|
679
773
|
|
|
680
774
|
When to use:
|
|
775
|
+
|
|
681
776
|
1. You want measurable quality lift with moderate performance cost.
|
|
682
777
|
2. You can tolerate small throughput swings while tuning.
|
|
683
778
|
|
|
@@ -685,19 +780,20 @@ When to use:
|
|
|
685
780
|
|
|
686
781
|
```typescript
|
|
687
782
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
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,
|
|
697
792
|
});
|
|
698
793
|
```
|
|
699
794
|
|
|
700
795
|
When to use:
|
|
796
|
+
|
|
701
797
|
1. Completion/quality metrics matter more than raw throughput.
|
|
702
798
|
2. You have enough headroom in Redis and CPU.
|
|
703
799
|
|
|
@@ -725,20 +821,22 @@ learningExplorationRate: 0.005,
|
|
|
725
821
|
```
|
|
726
822
|
|
|
727
823
|
4. Compare deltas:
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
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.
|
|
731
828
|
|
|
732
829
|
5. If throughput regresses too much:
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
830
|
+
|
|
831
|
+
- Reduce `learningBoostFactor`.
|
|
832
|
+
- Reduce `learningExplorationRate`.
|
|
833
|
+
- Reduce `relevantBatchSize`.
|
|
834
|
+
- Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
|
|
737
835
|
|
|
738
836
|
6. If quality lift is too small:
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
837
|
+
- Increase `learningBoostFactor` gradually (`+10` per step).
|
|
838
|
+
- Increase `learningExplorationRate` slightly (`+0.005`), capped at `0.05`.
|
|
839
|
+
- Improve signal quality in `learningSignalWeights`.
|
|
742
840
|
|
|
743
841
|
### Reading Benchmark Deltas Quickly
|
|
744
842
|
|
|
@@ -751,6 +849,7 @@ Quality score delta: +0.0274
|
|
|
751
849
|
```
|
|
752
850
|
|
|
753
851
|
Interpretation:
|
|
852
|
+
|
|
754
853
|
1. You traded some speed (`-5.11%`) for better outcomes.
|
|
755
854
|
2. Completion improved by **4.80 percentage points** (`pp`, not percent).
|
|
756
855
|
3. Quality improved overall (`+0.0274`).
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import AssignmentMatcher from './matcher.class';
|
|
2
|
-
export type { Assignment, options, Stats, User } 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';
|
|
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
4
|
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
5
|
-
export {
|
|
5
|
+
export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
|
|
6
|
+
export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
|
|
6
7
|
export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
|
|
7
8
|
export * from './utils/cidr';
|
|
9
|
+
export * from './utils/geo';
|
|
8
10
|
export { createKeyBuilders, type KeyBuilders, type RedisKeyConfig } from './utils/keys';
|
|
9
11
|
export { AssignmentMatcher };
|
|
10
12
|
export default 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,
|
|
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"}
|
package/dist/index.js
CHANGED
|
@@ -17,13 +17,17 @@ 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.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.cosineSimilarity = exports.extractMatchFeatures = void 0;
|
|
20
|
+
exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = 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
23
|
// Learning feature helpers (for custom feature extractors)
|
|
24
24
|
var features_1 = require("./learning/features");
|
|
25
25
|
Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
|
|
26
26
|
Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: function () { return features_1.cosineSimilarity; } });
|
|
27
|
+
// Automatic routing-weight synthesis (UCB1 policy over learned tag stats)
|
|
28
|
+
var auto_weights_1 = require("./learning/auto-weights");
|
|
29
|
+
Object.defineProperty(exports, "synthesizeRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.synthesizeRoutingWeights; } });
|
|
30
|
+
Object.defineProperty(exports, "DEFAULT_AUTO_WEIGHTS_OPTIONS", { enumerable: true, get: function () { return auto_weights_1.DEFAULT_AUTO_WEIGHTS_OPTIONS; } });
|
|
27
31
|
// Workflow builder DSL
|
|
28
32
|
var workflow_builder_1 = require("./workflow-builder");
|
|
29
33
|
Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
|
|
@@ -36,6 +40,7 @@ Object.defineProperty(exports, "normalizeWorkflowDefinition", { enumerable: true
|
|
|
36
40
|
Object.defineProperty(exports, "validateWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.validateWorkflowDefinition; } });
|
|
37
41
|
// Utility exports for advanced usage
|
|
38
42
|
__exportStar(require("./utils/cidr"), exports);
|
|
43
|
+
__exportStar(require("./utils/geo"), exports);
|
|
39
44
|
var keys_1 = require("./utils/keys");
|
|
40
45
|
Object.defineProperty(exports, "createKeyBuilders", { enumerable: true, get: function () { return keys_1.createKeyBuilders; } });
|
|
41
46
|
exports.default = matcher_class_1.default;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Automatic routing-weight synthesis from per-user tag reward statistics.
|
|
3
|
+
*
|
|
4
|
+
* Implements a UCB1-style bandit policy over tags: each tag's score is its
|
|
5
|
+
* mean observed reward plus an exploration bonus that shrinks as the tag is
|
|
6
|
+
* sampled more. Scores map onto the conventional 0-100 routing-weight scale:
|
|
7
|
+
*
|
|
8
|
+
* - tags with enough samples and a mean reward at/below `vetoThreshold` get
|
|
9
|
+
* weight 0 (the matcher's hard-veto semantics),
|
|
10
|
+
* - under-sampled or unobserved known tags get an optimistic `priorWeight`
|
|
11
|
+
* so the matcher keeps exploring them,
|
|
12
|
+
* - all other tags get a weight proportional to their UCB score, clamped to
|
|
13
|
+
* [1, maxWeight] so eligible tags never collapse to an accidental veto.
|
|
14
|
+
*
|
|
15
|
+
* Pure module: no Redis access, O(number of tags) per call.
|
|
16
|
+
*/
|
|
17
|
+
import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
|
|
18
|
+
export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'>>;
|
|
19
|
+
/**
|
|
20
|
+
* Synthesize a routingWeights map from per-tag reward statistics.
|
|
21
|
+
*
|
|
22
|
+
* @param stats per-user tag reward statistics (from learned outcomes)
|
|
23
|
+
* @param options UCB policy tuning (merged with defaults)
|
|
24
|
+
* @param knownTags optional tags to include even without observations;
|
|
25
|
+
* unobserved known tags receive the optimistic prior weight
|
|
26
|
+
* @param existingWeights optional current routingWeights of the user;
|
|
27
|
+
* used as the per-tag prior for under-sampled or unobserved
|
|
28
|
+
* tags instead of the flat `priorWeight` when provided
|
|
29
|
+
*/
|
|
30
|
+
export declare function synthesizeRoutingWeights(stats: LearningTagStat[], options?: AutoRoutingWeightsOptions, knownTags?: string[], existingWeights?: Record<string, number>): Record<string, number>;
|
|
31
|
+
//# sourceMappingURL=auto-weights.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnF,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,aAAa,CAAC,CAKjG,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACpC,KAAK,EAAE,eAAe,EAAE,EACxB,OAAO,CAAC,EAAE,yBAAyB,EACnC,SAAS,CAAC,EAAE,MAAM,EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA8CxB"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.synthesizeRoutingWeights = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = void 0;
|
|
4
|
+
exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
|
|
5
|
+
minSamples: 5,
|
|
6
|
+
vetoThreshold: -0.5,
|
|
7
|
+
maxWeight: 100,
|
|
8
|
+
explorationBonus: 0.5,
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Synthesize a routingWeights map from per-tag reward statistics.
|
|
12
|
+
*
|
|
13
|
+
* @param stats per-user tag reward statistics (from learned outcomes)
|
|
14
|
+
* @param options UCB policy tuning (merged with defaults)
|
|
15
|
+
* @param knownTags optional tags to include even without observations;
|
|
16
|
+
* unobserved known tags receive the optimistic prior weight
|
|
17
|
+
* @param existingWeights optional current routingWeights of the user;
|
|
18
|
+
* used as the per-tag prior for under-sampled or unobserved
|
|
19
|
+
* tags instead of the flat `priorWeight` when provided
|
|
20
|
+
*/
|
|
21
|
+
function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
|
|
22
|
+
const minSamples = options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples;
|
|
23
|
+
const vetoThreshold = options?.vetoThreshold ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.vetoThreshold;
|
|
24
|
+
const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
|
|
25
|
+
const explorationBonus = options?.explorationBonus ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.explorationBonus;
|
|
26
|
+
const priorWeight = options?.priorWeight ?? Math.round(maxWeight / 2);
|
|
27
|
+
const weights = {};
|
|
28
|
+
const totalCount = stats.reduce((sum, s) => sum + s.count, 0);
|
|
29
|
+
for (const stat of stats) {
|
|
30
|
+
if (stat.count < minSamples) {
|
|
31
|
+
// Not enough evidence yet: use the existing weight as a warm
|
|
32
|
+
// prior if available, otherwise fall back to the flat prior.
|
|
33
|
+
weights[stat.tag] = existingWeights?.[stat.tag] ?? priorWeight;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
// UCB1 score: mean reward + exploration bonus for under-sampled tags.
|
|
37
|
+
const ucb = stat.meanReward + explorationBonus * Math.sqrt(Math.log(totalCount + 1) / stat.count);
|
|
38
|
+
if (stat.meanReward <= vetoThreshold) {
|
|
39
|
+
// Consistently bad on the evidence: hard veto (matcher treats
|
|
40
|
+
// weight 0 as exclusion). The veto uses the raw mean so the
|
|
41
|
+
// exploration bonus cannot keep a provably bad tag alive.
|
|
42
|
+
weights[stat.tag] = 0;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
// Map score (clamped to [-1, 1]) onto [1, maxWeight].
|
|
46
|
+
const normalized = (Math.min(Math.max(ucb, -1), 1) + 1) / 2;
|
|
47
|
+
weights[stat.tag] = Math.max(1, Math.round(normalized * maxWeight));
|
|
48
|
+
}
|
|
49
|
+
if (knownTags) {
|
|
50
|
+
for (const tag of knownTags) {
|
|
51
|
+
if (!(tag in weights))
|
|
52
|
+
weights[tag] = existingWeights?.[tag] ?? priorWeight;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Tags the user already had weights for are treated as implicitly known:
|
|
56
|
+
// keep the existing value until sufficient evidence overrides it.
|
|
57
|
+
if (existingWeights) {
|
|
58
|
+
for (const [tag, existing] of Object.entries(existingWeights)) {
|
|
59
|
+
if (!(tag in weights))
|
|
60
|
+
weights[tag] = existing;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return weights;
|
|
64
|
+
}
|
|
65
|
+
exports.synthesizeRoutingWeights = synthesizeRoutingWeights;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
-- workflow-transition.lua
|
|
2
|
+
-- Atomic workflow state transition with optimistic locking (CAS)
|
|
3
|
+
--
|
|
4
|
+
-- KEYS[1] = workflow instance key
|
|
5
|
+
-- ARGV[1] = expected version
|
|
6
|
+
-- ARGV[2] = new data (JSON string)
|
|
7
|
+
--
|
|
8
|
+
-- Returns:
|
|
9
|
+
-- {ok = true} on success
|
|
10
|
+
-- {err = 'NOT_FOUND'} if instance doesn't exist
|
|
11
|
+
-- {err = 'VERSION_MISMATCH', current_version = N} if version doesn't match
|
|
12
|
+
|
|
13
|
+
local key = KEYS[1]
|
|
14
|
+
local expected_version = tonumber(ARGV[1])
|
|
15
|
+
local new_data = ARGV[2]
|
|
16
|
+
|
|
17
|
+
local current = redis.call('HGET', key, 'data')
|
|
18
|
+
if not current then
|
|
19
|
+
return cjson.encode({err = 'NOT_FOUND'})
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
local parsed = cjson.decode(current)
|
|
23
|
+
if parsed.version ~= expected_version then
|
|
24
|
+
return cjson.encode({err = 'VERSION_MISMATCH', current_version = parsed.version})
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
redis.call('HSET', key, 'data', new_data)
|
|
28
|
+
return cjson.encode({ok = true})
|
|
29
|
+
|