assignment-user-matcher 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -12
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/learning/auto-weights.d.ts +18 -8
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +120 -18
- package/dist/learning/features.d.ts +2 -2
- package/dist/learning/features.d.ts.map +1 -1
- package/dist/learning/features.js +10 -2
- package/dist/managers/LearningManager.d.ts +7 -0
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +85 -11
- package/dist/managers/WorkflowManager.d.ts +2 -0
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +3 -2
- package/dist/matcher.class.d.ts +79 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +587 -14
- package/dist/scoring/match-score.d.ts +6 -0
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +17 -2
- package/dist/sla/policy.d.ts +49 -0
- package/dist/sla/policy.d.ts.map +1 -0
- package/dist/sla/policy.js +96 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -1
- package/dist/tracing/decision-trace.js +4 -2
- package/dist/types/matcher.d.ts +242 -1
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +7 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +13 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -385,15 +385,59 @@ The wait clock always survives an escalation: requeues go through `addAssignment
|
|
|
385
385
|
|
|
386
386
|
Subscribe via `onAssignmentLifecycle` for `escalated` (`{ fromWorkerId, level, blockedPreviousOwner }`) and `escalationExhausted` (`{ level, parked }`) events; `expired` is still emitted first, so existing consumers are unaffected. Parked assignments are reachable with `getParkedAssignments()`, returned to the queue with `unparkAssignment(id, { resetEscalation? })`, and report `_status: 'parked'` from `getAssignment()` — they never read as "not found". `getEscalationLevel(id)` reports how far an assignment has climbed.
|
|
387
387
|
|
|
388
|
+
### SLA policies (`Assignment.sla`)
|
|
389
|
+
|
|
390
|
+
Escalation owns the *response* side (how long a matched user has to accept). `SlaPolicy` owns everything after that: how long the accepting user has to finish, how many times the work may be refused before it is pulled from rotation, and an absolute freshness cutoff after which the work is moot.
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
await matcher.addAssignment({
|
|
394
|
+
id: 'order-42',
|
|
395
|
+
tags: ['fulfillment'],
|
|
396
|
+
sla: {
|
|
397
|
+
completeWithinMs: 30 * 60_000, // finish within 30 min of accepting
|
|
398
|
+
onCompletionBreach: 'requeue', // take it back if they don't
|
|
399
|
+
maxRejections: 3, // after 3 refusals, stop offering it
|
|
400
|
+
expireAfterMs: 24 * 3600_000, // moot after 24h no matter what
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
matcher.startMaintenance(); // SLA clocks are swept by the maintenance tick
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
| Field | Meaning | Default |
|
|
408
|
+
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- |
|
|
409
|
+
| `completeWithinMs` | Completion deadline, measured from `acceptAssignment()`. Swept by `processCompletionDeadlines()` | none |
|
|
410
|
+
| `expireAfterMs` | Absolute freshness cutoff from **first enqueue** — survives requeues and applies in every state (queued, pending, accepted). Swept by `processSlaExpiries()` | none |
|
|
411
|
+
| `maxRejections` | Refusal budget. Explicit `rejectAssignment()` calls **and** blocking no-response expiries (`escalation.onNoResponse: 'block'`) count; idle/operator releases don't | none |
|
|
412
|
+
| `onCompletionBreach` | `'notify'` (event only, worker keeps it) / `'requeue'` (take back, block breacher) / `'fail'` / `'park'` | `'notify'` |
|
|
413
|
+
| `onMaxRejections` | `'park'` / `'fail'` / `'keep'` (keep offering; budget becomes measurement-only) | `'park'` |
|
|
414
|
+
| `onExpire` | `'drop'` (remove entirely) / `'park'` (retain for inspection) | `'drop'` |
|
|
415
|
+
|
|
416
|
+
Semantics worth knowing:
|
|
417
|
+
|
|
418
|
+
- **Fire-once.** A breached completion deadline is removed from the deadline index before the action runs, so a `'notify'` breach doesn't re-fire every tick; a requeued-after-breach assignment gets a fresh completion clock only on its next accept.
|
|
419
|
+
- **The TTL never extends.** Rejection ping-pong re-adds the same JSON, whose `_enqueuedAt` keeps the original first-enqueue time — the freshness cutoff is a hard wall, not a sliding window.
|
|
420
|
+
- **Rejection budget outranks escalation.** Once `maxRejections` is exhausted the assignment is parked/failed instead of climbing further tiers.
|
|
421
|
+
- **Sweep granularity.** Like response deadlines, SLA clocks fire on the maintenance tick, not at the exact deadline.
|
|
422
|
+
- **Unparking.** `unparkAssignment(id, { resetSla: true })` clears the first-enqueue clock and rejection counter; without it an unparked TTL-expired item simply expires again on the next sweep.
|
|
423
|
+
|
|
424
|
+
Lifecycle events: `completionBreached` (`{ workerId, action }`), `slaExpired` (`{ ownerId, action }`), `rejectionBudgetExhausted` (`{ rejections, action }`).
|
|
425
|
+
|
|
426
|
+
**SLO measurement.** `getSlaStats(tag?)` returns aggregate attainment counters — global, or for one tag: `offers`, `acceptedInTime`, `acceptanceBreaches`, `completionBreaches`, `ttlExpiries`, `rejectionParked`, plus `meanAcceptLatencyMs` (matched→accepted) and `meanCompleteLatencyMs` (accepted→completed). Counters are best-effort `HINCRBY`s piggybacking paths that already touch Redis; only SLA-bearing assignments are measured.
|
|
427
|
+
|
|
428
|
+
**Learning integration.** Breach outcomes flow into the contextual bandit as ordinary rewards (TTL expiry and completion breach → `expire`; completion breach with `'fail'` → `fail`), so per-user/per-tag stats and the automatic routing-weight vetoes pick up chronic breachers with no extra configuration. The default feature extractor also emits `sla:hasDeadline` and `sla:tightness` (normalized against `learningSlaTightnessReferenceMs`, default 1h) for assignments with a completion deadline, letting the model learn that tight-deadline work needs fast finishers. Custom feature extractors are unaffected.
|
|
429
|
+
|
|
388
430
|
### `startMaintenance(options?)` / `stopMaintenance()` / `runMaintenanceOnce(options?)`
|
|
389
431
|
|
|
390
432
|
Deadlines are not self-firing — something has to sweep them. `startMaintenance()` runs every enabled sweep on one tick:
|
|
391
433
|
|
|
392
434
|
- `responseDeadlines` (default on) — expiry, escalation, parking.
|
|
435
|
+
- `completionDeadlines` (default on) — SLA completion deadlines (`sla.completeWithinMs`).
|
|
436
|
+
- `slaExpiries` (default on) — SLA freshness TTLs (`sla.expireAfterMs`).
|
|
393
437
|
- `workflowStepTimeouts` (default on when `enableWorkflows`) — the step-timeout index. **Note:** `startOrchestrator()` consumes the event stream but does not sweep step timeouts; without maintenance, `timeoutMs` on a workflow step never fires.
|
|
394
438
|
- `idleUsers` (default on when `idleUserTimeoutMs` is set).
|
|
395
439
|
|
|
396
|
-
`runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
|
|
440
|
+
`runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `completionBreaches`, `slaExpiries`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
|
|
397
441
|
|
|
398
442
|
### `getQueueStats(): Promise<QueueStats>`
|
|
399
443
|
|
|
@@ -585,6 +629,10 @@ type Options = {
|
|
|
585
629
|
// tag-overlap-ratio and embedding-similarity features.
|
|
586
630
|
learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
|
|
587
631
|
|
|
632
|
+
// Reference duration (ms) used to normalize the `sla:tightness` feature
|
|
633
|
+
// emitted by the default extractor for assignments with sla.completeWithinMs.
|
|
634
|
+
learningSlaTightnessReferenceMs?: number; // Default: 3600000 (1 hour)
|
|
635
|
+
|
|
588
636
|
// TTL for stored decision contexts in ms.
|
|
589
637
|
learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
|
|
590
638
|
|
|
@@ -658,6 +706,11 @@ What a trace contains:
|
|
|
658
706
|
`assignmentVeto` (the assignment's `vetoedUsers`), and `rejectedPreviously` —
|
|
659
707
|
are struck out in the trace even though the Redis-side prefilter kept them
|
|
660
708
|
out of the scoring pass entirely.
|
|
709
|
+
- Where a veto came from. For users carrying `learnedRoutingWeights`, each
|
|
710
|
+
`veto` reason also has `source: 'learned' | 'manual'`, separating a veto the
|
|
711
|
+
automatic routing-weight sync synthesized from one an operator configured.
|
|
712
|
+
The field is absent for users with no learned weights, so traces are
|
|
713
|
+
unchanged when the learning layer is off.
|
|
661
714
|
|
|
662
715
|
Honesty notes: in the default `'first-come'` mode users evaluate and claim in
|
|
663
716
|
parallel, so a candidate whose snapshot read happened after the winner's claim
|
|
@@ -809,26 +862,53 @@ Beyond re-ranking, the learning layer can fully automate `routingWeights`
|
|
|
809
862
|
authoring. With `enableAutoRoutingWeights: true` (requires `enableLearning`),
|
|
810
863
|
every reward observation also updates per-user, per-tag statistics in Redis
|
|
811
864
|
(atomic `HINCRBY`/`HINCRBYFLOAT` — O(tags) per outcome, no scans, no
|
|
812
|
-
read-modify-write), and weights are synthesized on demand with a
|
|
813
|
-
policy
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
-
|
|
818
|
-
|
|
819
|
-
-
|
|
820
|
-
the
|
|
865
|
+
read-modify-write), and weights are synthesized on demand with a configurable
|
|
866
|
+
bandit policy.
|
|
867
|
+
|
|
868
|
+
**Policies:**
|
|
869
|
+
|
|
870
|
+
- `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
|
|
871
|
+
bonus favors less-sampled tags, and bad tags are hard-vetoed at weight `0`.
|
|
872
|
+
- `policy: 'confidence'`: uses upper-confidence-bound for the weight and a
|
|
873
|
+
conservative lower-confidence-bound for the veto decision, so uncertainty
|
|
874
|
+
works against exclusion.
|
|
875
|
+
- `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
|
|
876
|
+
weight.
|
|
877
|
+
|
|
878
|
+
**Guardrails (all opt-in):**
|
|
879
|
+
|
|
880
|
+
- `minSamplesForVeto`: a learned weight-0 may only override a _manual_
|
|
881
|
+
(non-learned) weight after this many observations, preventing a few bad
|
|
882
|
+
rolls from silently starving a user. Defaults to `minSamples` (5) for
|
|
883
|
+
backward compatibility; 20 is a reasonable production floor.
|
|
884
|
+
- `maxDeltaPerSync`: clamps how far any single learned weight can move per
|
|
885
|
+
sync, avoiding oscillation.
|
|
886
|
+
- `minTotalSamples`: skip users whose total evidence is still too thin.
|
|
887
|
+
- `decayHalfLifeMs`: exponentially decay older observations on read so stale
|
|
888
|
+
history cannot veto a user's improving skills.
|
|
889
|
+
- `terminalOnlyTagStats`: when `true`, only terminal outcomes
|
|
890
|
+
(complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
|
|
891
|
+
the non-terminal `accept` update is skipped.
|
|
821
892
|
|
|
822
893
|
```typescript
|
|
823
894
|
const matcher = new AssignmentMatcher(redisClient, {
|
|
824
895
|
enableLearning: true,
|
|
825
896
|
enableAutoRoutingWeights: true,
|
|
897
|
+
// Optional: run the guarded sync automatically on one replica.
|
|
898
|
+
// A Redis lock prevents overlapping runs across replicas.
|
|
899
|
+
autoRoutingWeightsSyncIntervalMs: 60_000,
|
|
826
900
|
autoRoutingWeights: {
|
|
827
901
|
minSamples: 5, // observations before a tag's stats are trusted
|
|
828
902
|
vetoThreshold: -0.5, // mean reward at/below this → weight 0 (hard veto)
|
|
829
903
|
maxWeight: 100, // top of the synthesized weight scale
|
|
830
904
|
explorationBonus: 0.5, // UCB coefficient; higher → more exploration
|
|
831
905
|
priorWeight: 50, // optimistic weight for unexplored tags
|
|
906
|
+
policy: 'confidence', // or 'ucb1' (default) / 'thompson'
|
|
907
|
+
confidenceZ: 1.5, // z-score for the confidence policy
|
|
908
|
+
minSamplesForVeto: 20, // stricter bar for overriding manual weights
|
|
909
|
+
maxDeltaPerSync: 25, // max change per sync on a single weight
|
|
910
|
+
decayHalfLifeMs: 24 * 60 * 60 * 1000, // 24h half-life
|
|
911
|
+
terminalOnlyTagStats: false,
|
|
832
912
|
},
|
|
833
913
|
});
|
|
834
914
|
|
|
@@ -844,15 +924,28 @@ await matcher.syncLearnedRoutingWeights(); // all tracked users
|
|
|
844
924
|
|
|
845
925
|
// Include exploration priors for known tags the user has never seen:
|
|
846
926
|
await matcher.syncLearnedRoutingWeights('user-1', { includeUnexploredTags: true });
|
|
927
|
+
|
|
928
|
+
// Preview the would-be map without writing anything:
|
|
929
|
+
const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true });
|
|
930
|
+
|
|
931
|
+
// Undo the last sync if the result looks wrong:
|
|
932
|
+
await matcher.revertLearnedRoutingWeights('user-1');
|
|
847
933
|
```
|
|
848
934
|
|
|
849
935
|
Synthesis happens outside the matching hot path — matching itself reads the
|
|
850
936
|
user's stored `routingWeights` exactly as before, so the per-match cost is
|
|
851
937
|
unchanged. The last-applied learned map is stored on the user as
|
|
852
|
-
`learnedRoutingWeights` for observability,
|
|
853
|
-
|
|
938
|
+
`learnedRoutingWeights` for observability, the previous map is snapshotted as
|
|
939
|
+
`routingWeightsSnapshot` for rollback, and `resetLearningModel()` clears all
|
|
940
|
+
per-user tag statistics. The pure synthesis function is exported as
|
|
854
941
|
`synthesizeRoutingWeights` for offline pipelines.
|
|
855
942
|
|
|
943
|
+
Run the regression gate to validate a new policy before shipping it:
|
|
944
|
+
|
|
945
|
+
```bash
|
|
946
|
+
./node_modules/.bin/ts-node benchmark-weights.ts
|
|
947
|
+
```
|
|
948
|
+
|
|
856
949
|
### RL Scalability & Redis Constraints
|
|
857
950
|
|
|
858
951
|
The RL layer adds controlled overhead: decision recording, outcome archival,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import AssignmentMatcher from './matcher.class';
|
|
2
|
-
export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, MaintenanceOptions, MaintenanceReport, } from './matcher.class';
|
|
3
|
-
export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
|
|
2
|
+
export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, SlaPolicy, SlaStats, MaintenanceOptions, MaintenanceReport, } from './matcher.class';
|
|
3
|
+
export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, AutoRoutingWeightsPolicy, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
|
|
4
4
|
export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
|
|
5
5
|
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
6
6
|
export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
|
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,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GACpB,MAAM,iBAAiB,CAAC;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AAqB,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"}
|
|
@@ -1,26 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Automatic routing-weight synthesis from per-user tag reward statistics.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
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:
|
|
4
|
+
* Supports three policies:
|
|
7
5
|
*
|
|
8
|
-
* -
|
|
9
|
-
*
|
|
6
|
+
* - 'ucb1' (default): mean reward plus an exploration bonus that shrinks as
|
|
7
|
+
* the tag is sampled more.
|
|
8
|
+
* - 'confidence': upper-confidence-bound for the weight, lower-confidence-bound
|
|
9
|
+
* for the veto decision, so vetoes are conservative and weights reflect
|
|
10
|
+
* uncertainty.
|
|
11
|
+
* - 'thompson': sample from the per-tag posterior (Gaussian approximation)
|
|
12
|
+
* when mapping to a weight.
|
|
13
|
+
*
|
|
14
|
+
* Scores map onto the conventional 0-100 routing-weight scale:
|
|
15
|
+
*
|
|
16
|
+
* - tags with enough samples and a sufficiently bad mean/LCB get weight 0
|
|
17
|
+
* (the matcher's hard-veto semantics),
|
|
10
18
|
* - under-sampled or unobserved known tags get an optimistic `priorWeight`
|
|
11
19
|
* so the matcher keeps exploring them,
|
|
12
|
-
* - all other tags get a weight proportional to their
|
|
20
|
+
* - all other tags get a weight proportional to their score, clamped to
|
|
13
21
|
* [1, maxWeight] so eligible tags never collapse to an accidental veto.
|
|
14
22
|
*
|
|
15
23
|
* Pure module: no Redis access, O(number of tags) per call.
|
|
16
24
|
*/
|
|
17
25
|
import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
|
|
18
|
-
export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'
|
|
26
|
+
export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight' | 'maxDeltaPerSync' | 'decayHalfLifeMs' | 'rng'>> & {
|
|
27
|
+
priorWeight: number;
|
|
28
|
+
};
|
|
19
29
|
/**
|
|
20
30
|
* Synthesize a routingWeights map from per-tag reward statistics.
|
|
21
31
|
*
|
|
22
32
|
* @param stats per-user tag reward statistics (from learned outcomes)
|
|
23
|
-
* @param options
|
|
33
|
+
* @param options synthesis policy and tuning (merged with defaults)
|
|
24
34
|
* @param knownTags optional tags to include even without observations;
|
|
25
35
|
* unobserved known tags receive the optimistic prior weight
|
|
26
36
|
* @param existingWeights optional current routingWeights of the user;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAA4B,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE7G,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAC/C,IAAI,CAAC,yBAAyB,EAAE,aAAa,GAAG,iBAAiB,GAAG,iBAAiB,GAAG,KAAK,CAAC,CACjG,GAAG;IACA,WAAW,EAAE,MAAM,CAAC;CAYvB,CAAC;AA2IF;;;;;;;;;;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"}
|
|
@@ -6,12 +6,118 @@ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
|
|
|
6
6
|
vetoThreshold: -0.5,
|
|
7
7
|
maxWeight: 100,
|
|
8
8
|
explorationBonus: 0.5,
|
|
9
|
+
priorWeight: 50,
|
|
10
|
+
policy: 'ucb1',
|
|
11
|
+
confidenceZ: 1.96,
|
|
12
|
+
minTotalSamples: 0,
|
|
13
|
+
minSamplesForVeto: 5,
|
|
14
|
+
terminalOnlyTagStats: false,
|
|
9
15
|
};
|
|
16
|
+
function resolveOptions(options) {
|
|
17
|
+
const maxWeight = options?.maxWeight ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.maxWeight;
|
|
18
|
+
return {
|
|
19
|
+
minSamples: options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples,
|
|
20
|
+
vetoThreshold: options?.vetoThreshold ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.vetoThreshold,
|
|
21
|
+
maxWeight,
|
|
22
|
+
explorationBonus: options?.explorationBonus ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.explorationBonus,
|
|
23
|
+
policy: options?.policy ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.policy,
|
|
24
|
+
confidenceZ: options?.confidenceZ ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.confidenceZ,
|
|
25
|
+
minTotalSamples: options?.minTotalSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minTotalSamples,
|
|
26
|
+
minSamplesForVeto: options?.minSamplesForVeto ?? options?.minSamples ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.minSamples,
|
|
27
|
+
terminalOnlyTagStats: options?.terminalOnlyTagStats ?? exports.DEFAULT_AUTO_WEIGHTS_OPTIONS.terminalOnlyTagStats,
|
|
28
|
+
priorWeight: options?.priorWeight ?? Math.round(maxWeight / 2),
|
|
29
|
+
maxDeltaPerSync: options?.maxDeltaPerSync,
|
|
30
|
+
decayHalfLifeMs: options?.decayHalfLifeMs,
|
|
31
|
+
rng: options?.rng ?? Math.random,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function isManualTag(tag, existingWeights) {
|
|
35
|
+
return !!existingWeights && tag in existingWeights;
|
|
36
|
+
}
|
|
37
|
+
function canVeto(policy, stat, vetoScore, lcb, opts, existingWeights) {
|
|
38
|
+
const manual = isManualTag(stat.tag, existingWeights);
|
|
39
|
+
const effectiveMinSamples = manual ? opts.minSamplesForVeto : opts.minSamples;
|
|
40
|
+
if (stat.count < effectiveMinSamples)
|
|
41
|
+
return false;
|
|
42
|
+
if (policy === 'confidence') {
|
|
43
|
+
return lcb <= opts.vetoThreshold;
|
|
44
|
+
}
|
|
45
|
+
return vetoScore <= opts.vetoThreshold;
|
|
46
|
+
}
|
|
47
|
+
function tagScore(policy, stat, totalCount, opts) {
|
|
48
|
+
const mean = stat.meanReward;
|
|
49
|
+
const se = stat.standardError ?? 0;
|
|
50
|
+
if (policy === 'confidence') {
|
|
51
|
+
const z = opts.confidenceZ;
|
|
52
|
+
return { ucb: mean + z * se, lcb: mean - z * se, sample: mean };
|
|
53
|
+
}
|
|
54
|
+
if (policy === 'thompson') {
|
|
55
|
+
// Gaussian Thompson sample: mean + Z(rng) * se, where Z is the normal
|
|
56
|
+
// inverse CDF approximated by the Acklam/Bailey approximation.
|
|
57
|
+
const sample = se > 0 ? mean + acklamInverseNormal(opts.rng()) * se : mean;
|
|
58
|
+
return { ucb: sample, lcb: sample, sample };
|
|
59
|
+
}
|
|
60
|
+
// 'ucb1'
|
|
61
|
+
const ucb = mean + opts.explorationBonus * Math.sqrt(Math.log(totalCount + 1) / stat.count);
|
|
62
|
+
return { ucb, lcb: mean, sample: ucb };
|
|
63
|
+
}
|
|
64
|
+
function normalizedWeight(score, maxWeight) {
|
|
65
|
+
const normalized = (Math.min(Math.max(score, -1), 1) + 1) / 2;
|
|
66
|
+
return Math.max(1, Math.round(normalized * maxWeight));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Acklam/Bailey approximation of the standard-normal quantile function.
|
|
70
|
+
* Maps p in (0, 1) to a z-score. Used for Thompson sampling without pulling
|
|
71
|
+
* in a statistics dependency.
|
|
72
|
+
*/
|
|
73
|
+
function acklamInverseNormal(p) {
|
|
74
|
+
if (p <= 0)
|
|
75
|
+
return -6;
|
|
76
|
+
if (p >= 1)
|
|
77
|
+
return 6;
|
|
78
|
+
const a1 = -39.6968302866538;
|
|
79
|
+
const a2 = 220.946098424521;
|
|
80
|
+
const a3 = -275.928510446969;
|
|
81
|
+
const a4 = 138.357751867269;
|
|
82
|
+
const a5 = -30.6647980661472;
|
|
83
|
+
const a6 = 2.50662827745924;
|
|
84
|
+
const b1 = -54.4760987982241;
|
|
85
|
+
const b2 = 161.585836858041;
|
|
86
|
+
const b3 = -155.698979859887;
|
|
87
|
+
const b4 = 66.8013118877197;
|
|
88
|
+
const b5 = -13.2806815528857;
|
|
89
|
+
const c1 = -0.00778489400243029;
|
|
90
|
+
const c2 = -0.322396458441136;
|
|
91
|
+
const c3 = -2.40075827716184;
|
|
92
|
+
const c4 = -2.54973253934373;
|
|
93
|
+
const c5 = 4.37466414146497;
|
|
94
|
+
const c6 = 2.93816398269878;
|
|
95
|
+
const d1 = 0.00778469570904146;
|
|
96
|
+
const d2 = 0.32246712907004;
|
|
97
|
+
const d3 = 2.445134137143;
|
|
98
|
+
const d4 = 3.75440866190742;
|
|
99
|
+
const pLow = 0.02425;
|
|
100
|
+
const pHigh = 1 - pLow;
|
|
101
|
+
let q;
|
|
102
|
+
let r;
|
|
103
|
+
if (p < pLow) {
|
|
104
|
+
q = Math.sqrt(-2 * Math.log(p));
|
|
105
|
+
return (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
|
|
106
|
+
}
|
|
107
|
+
if (p <= pHigh) {
|
|
108
|
+
q = p - 0.5;
|
|
109
|
+
r = q * q;
|
|
110
|
+
return (((((((a1 * r + a2) * r + a3) * r + a4) * r + a5) * r + a6) * q) /
|
|
111
|
+
(((((b1 * r + b2) * r + b3) * r + b4) * r + b5) * r + 1));
|
|
112
|
+
}
|
|
113
|
+
q = Math.sqrt(-2 * Math.log(1 - p));
|
|
114
|
+
return -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
|
|
115
|
+
}
|
|
10
116
|
/**
|
|
11
117
|
* Synthesize a routingWeights map from per-tag reward statistics.
|
|
12
118
|
*
|
|
13
119
|
* @param stats per-user tag reward statistics (from learned outcomes)
|
|
14
|
-
* @param options
|
|
120
|
+
* @param options synthesis policy and tuning (merged with defaults)
|
|
15
121
|
* @param knownTags optional tags to include even without observations;
|
|
16
122
|
* unobserved known tags receive the optimistic prior weight
|
|
17
123
|
* @param existingWeights optional current routingWeights of the user;
|
|
@@ -19,37 +125,33 @@ exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = {
|
|
|
19
125
|
* tags instead of the flat `priorWeight` when provided
|
|
20
126
|
*/
|
|
21
127
|
function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
|
|
22
|
-
const
|
|
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 = {};
|
|
128
|
+
const opts = resolveOptions(options);
|
|
28
129
|
const totalCount = stats.reduce((sum, s) => sum + s.count, 0);
|
|
130
|
+
if (opts.minTotalSamples > 0 && totalCount < opts.minTotalSamples) {
|
|
131
|
+
return {};
|
|
132
|
+
}
|
|
133
|
+
const weights = {};
|
|
29
134
|
for (const stat of stats) {
|
|
30
|
-
if (stat.count < minSamples) {
|
|
135
|
+
if (stat.count < opts.minSamples) {
|
|
31
136
|
// Not enough evidence yet: use the existing weight as a warm
|
|
32
137
|
// prior if available, otherwise fall back to the flat prior.
|
|
33
|
-
weights[stat.tag] = existingWeights?.[stat.tag] ?? priorWeight;
|
|
138
|
+
weights[stat.tag] = existingWeights?.[stat.tag] ?? opts.priorWeight;
|
|
34
139
|
continue;
|
|
35
140
|
}
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
// weight 0 as exclusion). The veto uses the raw mean so the
|
|
41
|
-
// exploration bonus cannot keep a provably bad tag alive.
|
|
141
|
+
const { ucb, lcb, sample } = tagScore(opts.policy, stat, totalCount, opts);
|
|
142
|
+
const weightScore = opts.policy === 'thompson' ? sample : ucb;
|
|
143
|
+
const vetoScore = opts.policy === 'confidence' ? lcb : opts.policy === 'thompson' ? sample : stat.meanReward;
|
|
144
|
+
if (canVeto(opts.policy, stat, vetoScore, lcb, opts, existingWeights)) {
|
|
42
145
|
weights[stat.tag] = 0;
|
|
43
146
|
continue;
|
|
44
147
|
}
|
|
45
148
|
// Map score (clamped to [-1, 1]) onto [1, maxWeight].
|
|
46
|
-
|
|
47
|
-
weights[stat.tag] = Math.max(1, Math.round(normalized * maxWeight));
|
|
149
|
+
weights[stat.tag] = normalizedWeight(weightScore, opts.maxWeight);
|
|
48
150
|
}
|
|
49
151
|
if (knownTags) {
|
|
50
152
|
for (const tag of knownTags) {
|
|
51
153
|
if (!(tag in weights))
|
|
52
|
-
weights[tag] = existingWeights?.[tag] ?? priorWeight;
|
|
154
|
+
weights[tag] = existingWeights?.[tag] ?? opts.priorWeight;
|
|
53
155
|
}
|
|
54
156
|
}
|
|
55
157
|
// Tags the user already had weights for are treated as implicitly known:
|
|
@@ -13,7 +13,7 @@ import type { User, LearningFeatures, LearningAssignmentContext } from '../types
|
|
|
13
13
|
export declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
14
14
|
/**
|
|
15
15
|
* Default feature extractor: tag matches, normalized skill weights,
|
|
16
|
-
* tag-overlap ratio,
|
|
16
|
+
* tag-overlap ratio, optional embedding similarity, and SLA urgency.
|
|
17
17
|
*/
|
|
18
|
-
export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext): LearningFeatures;
|
|
18
|
+
export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext, slaTightnessReferenceMs?: number): LearningFeatures;
|
|
19
19
|
//# sourceMappingURL=features.d.ts.map
|
|
@@ -1 +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,
|
|
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,CAChC,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,yBAAyB,EACrC,uBAAuB,GAAE,MAAgB,GAC1C,gBAAgB,CAuClB"}
|
|
@@ -24,9 +24,9 @@ function cosineSimilarity(a, b) {
|
|
|
24
24
|
exports.cosineSimilarity = cosineSimilarity;
|
|
25
25
|
/**
|
|
26
26
|
* Default feature extractor: tag matches, normalized skill weights,
|
|
27
|
-
* tag-overlap ratio,
|
|
27
|
+
* tag-overlap ratio, optional embedding similarity, and SLA urgency.
|
|
28
28
|
*/
|
|
29
|
-
function extractMatchFeatures(user, assignment) {
|
|
29
|
+
function extractMatchFeatures(user, assignment, slaTightnessReferenceMs = 3600000) {
|
|
30
30
|
const features = { bias: 1 };
|
|
31
31
|
const userTags = new Set(user.tags || []);
|
|
32
32
|
const assignmentTags = assignment.tags || [];
|
|
@@ -50,6 +50,14 @@ function extractMatchFeatures(user, assignment) {
|
|
|
50
50
|
if (Array.isArray(user.embedding) && Array.isArray(assignment.embedding)) {
|
|
51
51
|
features['emb:sim'] = cosineSimilarity(user.embedding, assignment.embedding);
|
|
52
52
|
}
|
|
53
|
+
// SLA urgency: assignment-side only (user-invariant), so custom
|
|
54
|
+
// extractors and existing learned weights are unaffected.
|
|
55
|
+
const completeWithinMs = Number(assignment.sla?.completeWithinMs);
|
|
56
|
+
if (Number.isFinite(completeWithinMs) && completeWithinMs > 0) {
|
|
57
|
+
features['sla:hasDeadline'] = 1;
|
|
58
|
+
const reference = Number.isFinite(slaTightnessReferenceMs) && slaTightnessReferenceMs > 0 ? slaTightnessReferenceMs : 3600000;
|
|
59
|
+
features['sla:tightness'] = 1 - Math.min(1, completeWithinMs / reference);
|
|
60
|
+
}
|
|
53
61
|
return features;
|
|
54
62
|
}
|
|
55
63
|
exports.extractMatchFeatures = extractMatchFeatures;
|
|
@@ -99,6 +99,11 @@ export declare class LearningManager {
|
|
|
99
99
|
* Train the model directly with raw (features, reward) samples.
|
|
100
100
|
* Enables offline/batch imports from external pipelines (data warehouses,
|
|
101
101
|
* historical logs, post-processing jobs) without a live decision context.
|
|
102
|
+
*
|
|
103
|
+
* The model is loaded once and SGD is replayed locally, then the
|
|
104
|
+
* accumulated deltas are written in a single batched round trip —
|
|
105
|
+
* equivalent to per-sample updateModel calls when no concurrent writer
|
|
106
|
+
* interleaves, and orders of magnitude cheaper for bulk imports.
|
|
102
107
|
*/
|
|
103
108
|
trainSamples(samples: LearningSample[]): Promise<number>;
|
|
104
109
|
/**
|
|
@@ -107,6 +112,8 @@ export declare class LearningManager {
|
|
|
107
112
|
* so high-throughput outcome streams scale without contention.
|
|
108
113
|
*/
|
|
109
114
|
private updateTagStats;
|
|
115
|
+
/** True when the configured policy/decay needs reward variance/timestamps. */
|
|
116
|
+
private needsVarianceTracking;
|
|
110
117
|
/** Per-user, per-tag reward statistics aggregated from observed outcomes */
|
|
111
118
|
getUserTagStats(userId: string): Promise<LearningTagStat[]>;
|
|
112
119
|
/** Users that have accumulated tag reward statistics */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,eAAO,MAAM,wBAAwB,EAAE,eAMtC,CAAC;AAKF,MAAM,WAAW,sBAAsB;IACnC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,eAAe,CAAC,EAAE,M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