assignment-user-matcher 1.15.0 → 1.16.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 +378 -9
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/learning/atomic-ingestion.d.ts +11 -0
- package/dist/learning/atomic-ingestion.d.ts.map +1 -0
- package/dist/learning/atomic-ingestion.js +187 -0
- package/dist/learning/auto-weights.d.ts +13 -2
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +203 -35
- package/dist/learning/features.d.ts +5 -3
- package/dist/learning/features.d.ts.map +1 -1
- package/dist/learning/features.js +105 -4
- package/dist/learning/policy.d.ts +57 -0
- package/dist/learning/policy.d.ts.map +1 -0
- package/dist/learning/policy.js +71 -0
- package/dist/managers/LearningManager.d.ts +312 -35
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +1006 -168
- package/dist/matcher.class.d.ts +98 -11
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +247 -40
- package/dist/scheduling/constraints/cost.d.ts.map +1 -1
- package/dist/scheduling/constraints/cost.js +3 -2
- package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
- package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
- package/dist/scheduling/constraints/employee-scope.js +157 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -1
- package/dist/scheduling/constraints/notice.js +8 -5
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
- package/dist/scheduling/constraints/rest-days.js +6 -6
- package/dist/scheduling/cost.d.ts.map +1 -1
- package/dist/scheduling/cost.js +2 -1
- package/dist/scheduling/engine/construction.d.ts +11 -3
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +31 -6
- package/dist/scheduling/engine/objective.d.ts +4 -4
- package/dist/scheduling/engine/objective.d.ts.map +1 -1
- package/dist/scheduling/engine/objective.js +12 -4
- package/dist/scheduling/engine/propagation.js +2 -1
- package/dist/scheduling/engine/search.d.ts +1 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -1
- package/dist/scheduling/engine/search.js +1 -1
- package/dist/scheduling/engine/state.d.ts.map +1 -1
- package/dist/scheduling/engine/state.js +4 -0
- package/dist/scheduling/index.d.ts +1 -1
- package/dist/scheduling/index.d.ts.map +1 -1
- package/dist/scheduling/model.d.ts +1 -1
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +184 -42
- package/dist/scheduling/operations.d.ts +4 -0
- package/dist/scheduling/operations.d.ts.map +1 -1
- package/dist/scheduling/operations.js +36 -16
- package/dist/scheduling/provenance.d.ts +1 -1
- package/dist/scheduling/provenance.d.ts.map +1 -1
- package/dist/scheduling/provenance.js +16 -2
- package/dist/scheduling/scheduler.class.d.ts +1 -1
- package/dist/scheduling/scheduler.class.d.ts.map +1 -1
- package/dist/scheduling/scheduler.class.js +5 -3
- package/dist/scheduling/time.d.ts +2 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +26 -1
- package/dist/scheduling/types.d.ts +78 -3
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +309 -4
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +12 -2
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +35 -2
- package/package.json +2 -1
|
@@ -3,16 +3,31 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Maintains an online linear reward model: each feature has a learned weight
|
|
5
5
|
* stored in a Redis hash. Predictions are dot products of the feature vector
|
|
6
|
-
* with the learned weights; updates
|
|
7
|
-
* observed
|
|
6
|
+
* with the learned weights; updates are stochastic gradient steps on the
|
|
7
|
+
* observed outcome of each *committed attempt*.
|
|
8
8
|
*
|
|
9
9
|
* The model only re-ranks candidates that already passed the hard matching
|
|
10
10
|
* rules (tags/weights, CIDR, skill thresholds) - it never makes an ineligible
|
|
11
11
|
* assignment eligible.
|
|
12
|
+
*
|
|
13
|
+
* Three invariants shape the storage layout:
|
|
14
|
+
*
|
|
15
|
+
* 1. **One decision per committed attempt.** Contexts are keyed by a unique
|
|
16
|
+
* `decisionId`, not by assignment id, and are written only for the worker
|
|
17
|
+
* who actually won the claim. An assignment that is rejected and rematched
|
|
18
|
+
* opens a second, independent attempt; feedback for the first can never
|
|
19
|
+
* reach the second.
|
|
20
|
+
* 2. **Ingestion is idempotent.** The applied-event marker and all learning
|
|
21
|
+
* effects commit together after validation; failed preparations can retry
|
|
22
|
+
* without losing an event or counting its evidence twice.
|
|
23
|
+
* 3. **Missing means unknown.** Absent quality feedback trains nothing; it is
|
|
24
|
+
* never a zero label.
|
|
12
25
|
*/
|
|
13
|
-
import type { RedisClientType, LearningFeatures, LearningOutcome, LearningRewards, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions } from '../types/matcher';
|
|
26
|
+
import type { RedisClientType, LearningFeatures, LearningOutcome, LearningRewards, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, LearningRewardTarget, LearningTargetsOptions, LearningPrediction, LearningRewardAccounting, LearningUpdateMode, LearningExplorationPolicy, LearningWorkerPerformance, AutoRoutingWeightsOptions, AutoWeightExplanation } from '../types/matcher';
|
|
14
27
|
import type { KeyBuilders } from '../utils/keys';
|
|
15
28
|
export declare const DEFAULT_LEARNING_REWARDS: LearningRewards;
|
|
29
|
+
/** Contract version of the decision records this build writes. */
|
|
30
|
+
export declare const LEARNING_FEATURE_VERSION = 2;
|
|
16
31
|
export interface LearningManagerOptions {
|
|
17
32
|
/** SGD learning rate (default: 0.1) */
|
|
18
33
|
learningRate?: number;
|
|
@@ -34,6 +49,65 @@ export interface LearningManagerOptions {
|
|
|
34
49
|
trackTagStats?: boolean;
|
|
35
50
|
/** Tuning for automatic routing-weight synthesis */
|
|
36
51
|
autoWeights?: AutoRoutingWeightsOptions;
|
|
52
|
+
/** SGD update rule (default: 'normalized') */
|
|
53
|
+
updateMode?: LearningUpdateMode;
|
|
54
|
+
/** L2 regularization coefficient (default: 0) */
|
|
55
|
+
l2?: number;
|
|
56
|
+
/** Maximum L2 norm of a single update (default: 1) */
|
|
57
|
+
maxUpdateNorm?: number;
|
|
58
|
+
/** Absolute cap on a single learned weight (default: 100) */
|
|
59
|
+
maxWeightMagnitude?: number;
|
|
60
|
+
/** Per-tag evidence accounting (default: 'per-event') */
|
|
61
|
+
rewardAccounting?: LearningRewardAccounting;
|
|
62
|
+
/** Selection policy name recorded on decisions (default: 'jitter') */
|
|
63
|
+
explorationPolicy?: LearningExplorationPolicy;
|
|
64
|
+
/** Random source for exploration (default: Math.random) */
|
|
65
|
+
rng?: () => number;
|
|
66
|
+
/** Multi-target reward modelling (default: off) */
|
|
67
|
+
targets?: LearningTargetsOptions;
|
|
68
|
+
/** Maximum age of an event relative to its attempt in ms (default: feedbackTtlMs) */
|
|
69
|
+
maxFeedbackAgeMs?: number;
|
|
70
|
+
/** Reject a feedback signal whose magnitude exceeds this (default: 1e6) */
|
|
71
|
+
maxSignalMagnitude?: number;
|
|
72
|
+
/** Clamp computed rewards to this magnitude (default: 100) */
|
|
73
|
+
maxRewardMagnitude?: number;
|
|
74
|
+
/** Track per-worker performance aggregates for the richer feature set (default: false) */
|
|
75
|
+
trackPerformance?: boolean;
|
|
76
|
+
/** Shrinkage strength toward the team prior (default: 5) */
|
|
77
|
+
performancePriorStrength?: number;
|
|
78
|
+
}
|
|
79
|
+
/** One committed attempt awaiting persistence. */
|
|
80
|
+
export interface LearningDecisionInput {
|
|
81
|
+
decisionId: string;
|
|
82
|
+
userId: string;
|
|
83
|
+
assignmentId: string;
|
|
84
|
+
features: LearningFeatures;
|
|
85
|
+
predictedReward: number;
|
|
86
|
+
components?: Partial<Record<LearningRewardTarget, number>>;
|
|
87
|
+
tags?: string[];
|
|
88
|
+
propensity?: number;
|
|
89
|
+
policy?: LearningExplorationPolicy;
|
|
90
|
+
candidateCount?: number;
|
|
91
|
+
}
|
|
92
|
+
/** Model weights for every configured target, loaded once per pass. */
|
|
93
|
+
export interface LearningModelSnapshot {
|
|
94
|
+
generation: number;
|
|
95
|
+
legacy: Record<string, string>;
|
|
96
|
+
targets: Partial<Record<LearningRewardTarget, Record<string, string>>>;
|
|
97
|
+
}
|
|
98
|
+
/** Why an event was not applied. */
|
|
99
|
+
export type LearningRejectReason = 'orphan' | 'duplicate' | 'stale' | 'superseded' | 'ambiguous' | 'invalid' | 'ownerMismatch';
|
|
100
|
+
export interface LearningApplyOptions {
|
|
101
|
+
/** Explicit event id; when omitted the outcome name is the dedupe token */
|
|
102
|
+
eventId?: string;
|
|
103
|
+
/** Reject the event unless the attempt belongs to this worker */
|
|
104
|
+
expectedUserId?: string;
|
|
105
|
+
/**
|
|
106
|
+
* The failure/expiry was a system fault, not the worker's. Under
|
|
107
|
+
* multi-target modelling it produces no `successGivenAcceptance` label
|
|
108
|
+
* unless `targets.systemFaultCountsAsFailure` is set.
|
|
109
|
+
*/
|
|
110
|
+
systemFault?: boolean;
|
|
37
111
|
}
|
|
38
112
|
export declare class LearningManager {
|
|
39
113
|
private redisClient;
|
|
@@ -48,12 +122,48 @@ export declare class LearningManager {
|
|
|
48
122
|
readonly feedbackTtlMs: number;
|
|
49
123
|
readonly trackTagStats: boolean;
|
|
50
124
|
readonly autoWeights: AutoRoutingWeightsOptions;
|
|
125
|
+
readonly updateMode: LearningUpdateMode;
|
|
126
|
+
readonly l2: number;
|
|
127
|
+
readonly maxUpdateNorm: number;
|
|
128
|
+
readonly maxWeightMagnitude: number;
|
|
129
|
+
readonly rewardAccounting: LearningRewardAccounting;
|
|
130
|
+
readonly explorationPolicy: LearningExplorationPolicy;
|
|
131
|
+
readonly rng: () => number;
|
|
132
|
+
readonly targets?: LearningTargetsOptions;
|
|
133
|
+
readonly activeTargets: LearningRewardTarget[];
|
|
134
|
+
readonly maxFeedbackAgeMs: number;
|
|
135
|
+
readonly maxSignalMagnitude: number;
|
|
136
|
+
readonly maxRewardMagnitude: number;
|
|
137
|
+
readonly trackPerformance: boolean;
|
|
138
|
+
readonly performancePriorStrength: number;
|
|
139
|
+
/** Monotonic suffix making decision ids unique within a process-millisecond. */
|
|
140
|
+
private decisionSeq;
|
|
141
|
+
/** Short-lived cache of the model generation (a GET per outcome is wasteful). */
|
|
142
|
+
private generationCache?;
|
|
51
143
|
constructor(redisClient: RedisClientType, keys: KeyBuilders, options?: LearningManagerOptions);
|
|
52
|
-
/**
|
|
144
|
+
/** True when multi-target reward modelling is configured. */
|
|
145
|
+
get multiTarget(): boolean;
|
|
146
|
+
/** Load the full legacy model weights hash from Redis */
|
|
53
147
|
getModel(): Promise<Record<string, string>>;
|
|
148
|
+
/** Load one target's model weights hash */
|
|
149
|
+
getTargetModel(target: LearningRewardTarget): Promise<Record<string, string>>;
|
|
150
|
+
/**
|
|
151
|
+
* Load every model needed for one matching pass in one batch, plus the
|
|
152
|
+
* generation stamped onto the decisions this pass commits.
|
|
153
|
+
*/
|
|
154
|
+
loadModels(): Promise<LearningModelSnapshot>;
|
|
54
155
|
/** Predict expected reward for a feature vector against given model weights */
|
|
55
156
|
predict(features: LearningFeatures, weights: Record<string, string | number>): number;
|
|
56
|
-
/**
|
|
157
|
+
/**
|
|
158
|
+
* Score a candidate against a loaded snapshot.
|
|
159
|
+
*
|
|
160
|
+
* In multi-target mode the components are calibrated probabilities and
|
|
161
|
+
* the utility is their configured combination — never presented as a
|
|
162
|
+
* probability itself. In legacy mode the single model's raw prediction is
|
|
163
|
+
* both the utility and the only component.
|
|
164
|
+
*/
|
|
165
|
+
predictWith(snapshot: LearningModelSnapshot, features: LearningFeatures): LearningPrediction;
|
|
166
|
+
/** Epsilon-greedy exploration check (legacy 'jitter' policy) */
|
|
57
167
|
shouldExplore(): boolean;
|
|
58
168
|
/** Current shadow mode state (true: learn-only, false: affects ranking) */
|
|
59
169
|
get shadowMode(): boolean;
|
|
@@ -65,54 +175,176 @@ export declare class LearningManager {
|
|
|
65
175
|
*/
|
|
66
176
|
setShadowMode(enabled: boolean): void;
|
|
67
177
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
178
|
+
* Mint an id for one committed attempt. Unique per process-millisecond;
|
|
179
|
+
* the assignment id prefix keeps the key human-readable in Redis.
|
|
180
|
+
*/
|
|
181
|
+
newDecisionId(assignmentId: string): string;
|
|
182
|
+
/** Current model generation (cached for a second; a reset is rare) */
|
|
183
|
+
currentGeneration(): Promise<number>;
|
|
184
|
+
/**
|
|
185
|
+
* Persist the contexts of attempts that were actually committed.
|
|
186
|
+
*
|
|
187
|
+
* Called from the claim path with only the ids the worker won, so a
|
|
188
|
+
* candidate that lost the race — to another worker in the same pass or to
|
|
189
|
+
* another process — leaves no decision behind.
|
|
190
|
+
*/
|
|
191
|
+
recordDecisions(inputs: LearningDecisionInput[], generation?: number): Promise<void>;
|
|
192
|
+
/**
|
|
193
|
+
* Queue the same writes onto a caller-owned transaction.
|
|
194
|
+
*
|
|
195
|
+
* The claim path uses this to put the decision context in the *same*
|
|
196
|
+
* batch as the queued -> pending state change. A separate write after the
|
|
197
|
+
* claim leaves a crash gap in which the worker owns the assignment but no
|
|
198
|
+
* learning context exists for it, so its outcome would arrive orphaned.
|
|
199
|
+
*
|
|
200
|
+
* Takes an explicit generation (carried on the scoring snapshot) so it
|
|
201
|
+
* stays synchronous and can be composed into an existing multi.
|
|
202
|
+
*/
|
|
203
|
+
queueDecisionWrites(multi: ReturnType<RedisClientType['multi']>, inputs: LearningDecisionInput[], gen: number): void;
|
|
204
|
+
/**
|
|
205
|
+
* Persist one decision context.
|
|
206
|
+
*
|
|
207
|
+
* @deprecated Prefer {@link recordDecisions} from the claim path; this
|
|
208
|
+
* single-record form exists for direct/manual integrations.
|
|
70
209
|
*/
|
|
71
|
-
recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number, tags?: string[]): Promise<
|
|
72
|
-
/** Fetch
|
|
210
|
+
recordDecision(userId: string, assignmentId: string, features: LearningFeatures, predictedReward: number, tags?: string[]): Promise<string>;
|
|
211
|
+
/** Fetch the in-flight decision record for an assignment, or null */
|
|
73
212
|
getDecision(assignmentId: string): Promise<LearningDecisionRecord | null>;
|
|
213
|
+
/** Fetch a decision record by attempt id, or null when absent/expired */
|
|
214
|
+
getDecisionById(decisionId: string): Promise<LearningDecisionRecord | null>;
|
|
215
|
+
/** Fetch the most recently archived episode for an assignment, or null */
|
|
216
|
+
getEpisode(assignmentId: string): Promise<LearningEpisodeRecord | null>;
|
|
217
|
+
/** Fetch an archived episode by attempt id, or null when absent/expired */
|
|
218
|
+
getEpisodeById(decisionId: string): Promise<LearningEpisodeRecord | null>;
|
|
74
219
|
/**
|
|
75
|
-
* Apply a lifecycle outcome
|
|
76
|
-
*
|
|
220
|
+
* Apply a lifecycle outcome to the attempt currently in flight for an
|
|
221
|
+
* assignment. Idempotent: a redelivered event applies once.
|
|
222
|
+
*
|
|
223
|
+
* Terminal outcomes archive the attempt as an episode (with TTL) so late
|
|
77
224
|
* external feedback can still be attributed to the original features.
|
|
78
|
-
* Returns false
|
|
225
|
+
* Returns false when the event was not applied, for any reason.
|
|
79
226
|
*/
|
|
80
|
-
applyOutcome(assignmentId: string, outcome: LearningOutcome): Promise<boolean>;
|
|
227
|
+
applyOutcome(assignmentId: string, outcome: LearningOutcome, options?: LearningApplyOptions): Promise<boolean>;
|
|
81
228
|
/**
|
|
82
|
-
* Apply a manually chosen reward
|
|
83
|
-
*
|
|
229
|
+
* Apply a manually chosen reward to the in-flight attempt.
|
|
230
|
+
*
|
|
231
|
+
* Terminal by default (it closes the learning episode) — pass
|
|
232
|
+
* `terminal: false` to shape a reward without ending the attempt, which
|
|
233
|
+
* is what lets later lifecycle outcomes still produce their own labels.
|
|
84
234
|
*/
|
|
85
|
-
recordReward(assignmentId: string, reward: number
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
private updateModel;
|
|
89
|
-
/** Fetch an archived episode record, or null when absent/expired */
|
|
90
|
-
getEpisode(assignmentId: string): Promise<LearningEpisodeRecord | null>;
|
|
235
|
+
recordReward(assignmentId: string, reward: number, options?: LearningApplyOptions & {
|
|
236
|
+
terminal?: boolean;
|
|
237
|
+
}): Promise<boolean>;
|
|
91
238
|
/**
|
|
92
|
-
* Apply named external feedback signals (e.g. { accuracy: 0.95 })
|
|
93
|
-
* the
|
|
239
|
+
* Apply named external feedback signals (e.g. `{ accuracy: 0.95 }`) to an
|
|
240
|
+
* attempt — the one in flight, or the archived episode when the work has
|
|
241
|
+
* already closed.
|
|
242
|
+
*
|
|
94
243
|
* Reward = sum(signalValue * signalWeight), default weight 1 per signal.
|
|
95
|
-
*
|
|
244
|
+
* Validation happens before anything is written: an empty signal map, a
|
|
245
|
+
* non-numeric value, or a value beyond `maxSignalMagnitude` is rejected
|
|
246
|
+
* whole rather than becoming a partial or zero-reward observation.
|
|
247
|
+
*
|
|
248
|
+
* Addressing an assignment that has BOTH a live attempt and an archived
|
|
249
|
+
* one is ambiguous after a reassignment — it is rejected rather than
|
|
250
|
+
* guessed. Pass the `decisionId` to say which attempt is meant.
|
|
251
|
+
*/
|
|
252
|
+
recordFeedback(assignmentId: string, signals: LearningSignals, options?: {
|
|
253
|
+
decisionId?: string;
|
|
254
|
+
eventId?: string;
|
|
255
|
+
expectedUserId?: string;
|
|
256
|
+
}): Promise<boolean>;
|
|
257
|
+
/** Sum of weighted signals, or undefined when the map fails validation. */
|
|
258
|
+
private rewardFromSignals;
|
|
259
|
+
/**
|
|
260
|
+
* Normalized quality label in [0, 1] from a signal map, or undefined when
|
|
261
|
+
* the signals carry no quality reading — which trains nothing.
|
|
262
|
+
*/
|
|
263
|
+
private qualityFromSignals;
|
|
264
|
+
private signalFingerprint;
|
|
265
|
+
/**
|
|
266
|
+
* The single ingestion path. Everything that trains the model goes
|
|
267
|
+
* through here so attribution, deduplication, staleness and generation
|
|
268
|
+
* checks cannot drift between callers.
|
|
269
|
+
*/
|
|
270
|
+
private ingest;
|
|
271
|
+
private ingestPrepared;
|
|
272
|
+
/** Archive an in-flight attempt as an episode and retire its pointer. */
|
|
273
|
+
private archive;
|
|
274
|
+
/**
|
|
275
|
+
* `per-attempt` evidence: accumulate rewards on the live attempt and
|
|
276
|
+
* write ONE per-tag observation when it closes. Feedback arriving after
|
|
277
|
+
* that revises the existing observation instead of adding a second — a
|
|
278
|
+
* correction is not new evidence.
|
|
279
|
+
*/
|
|
280
|
+
private accountPerAttempt;
|
|
281
|
+
/** Derive and apply per-target labels for one lifecycle event. */
|
|
282
|
+
private trainTargets;
|
|
283
|
+
/**
|
|
284
|
+
* Active feature names, in a stable order, skipping zero-valued and
|
|
285
|
+
* non-finite entries — the only fields an update ever needs to read.
|
|
286
|
+
*/
|
|
287
|
+
private activeFeatures;
|
|
288
|
+
/**
|
|
289
|
+
* Read only the weights an update touches.
|
|
290
|
+
*
|
|
291
|
+
* The old code loaded the entire model hash for every observation, which
|
|
292
|
+
* grows without bound as the feature space does. HMGET over the active
|
|
293
|
+
* features is O(active features) regardless of model size.
|
|
294
|
+
*/
|
|
295
|
+
private readWeights;
|
|
296
|
+
/**
|
|
297
|
+
* Turn a prediction error into a bounded weight delta per feature.
|
|
298
|
+
*
|
|
299
|
+
* The raw rule `w += lr * error * x` is unstable: with `k` active unit
|
|
300
|
+
* features every step overshoots by a factor of `k`, so the error
|
|
301
|
+
* alternates sign and grows. Normalizing by the active vector's squared
|
|
302
|
+
* norm makes one step land exactly on the observation (the
|
|
303
|
+
* normalized-LMS / passive-aggressive rule) regardless of how many
|
|
304
|
+
* features fired; the norm clip and weight cap bound the rest.
|
|
305
|
+
*/
|
|
306
|
+
private computeDeltas;
|
|
307
|
+
/**
|
|
308
|
+
* Write deltas, clamping any weight that would leave the magnitude cap.
|
|
309
|
+
* Increments are used in the ordinary case so concurrent trainers compose;
|
|
310
|
+
* the clamp falls back to a set, which is the only way to bound a value.
|
|
96
311
|
*/
|
|
97
|
-
|
|
312
|
+
private writeDeltas;
|
|
313
|
+
/** Apply one bounded SGD step to the legacy scalar-reward model */
|
|
314
|
+
private updateModel;
|
|
315
|
+
/** Apply one bounded step to a target model (logistic for binary targets) */
|
|
316
|
+
private updateTargetModel;
|
|
98
317
|
/**
|
|
99
318
|
* Train the model directly with raw (features, reward) samples.
|
|
100
319
|
* Enables offline/batch imports from external pipelines (data warehouses,
|
|
101
320
|
* historical logs, post-processing jobs) without a live decision context.
|
|
102
321
|
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
* interleaves, and orders of magnitude cheaper for bulk imports.
|
|
322
|
+
* Samples are processed in bounded chunks and each chunk re-reads the
|
|
323
|
+
* weights it touches, so a long import cannot keep accumulating against a
|
|
324
|
+
* snapshot the live model has already moved away from.
|
|
107
325
|
*/
|
|
108
|
-
trainSamples(samples: LearningSample[]): Promise<number>;
|
|
326
|
+
trainSamples(samples: LearningSample[], chunkSize?: number): Promise<number>;
|
|
109
327
|
/**
|
|
110
|
-
* Update per-user, per-tag reward aggregates
|
|
111
|
-
*
|
|
112
|
-
*
|
|
328
|
+
* Update per-user, per-tag reward aggregates.
|
|
329
|
+
*
|
|
330
|
+
* Without decay these are plain atomic increments — O(tags), no
|
|
331
|
+
* read-modify-write, so high-throughput outcome streams scale without
|
|
332
|
+
* contention. With decay the sums must be rescaled to "as of now" before
|
|
333
|
+
* the observation lands, which the batched Lua script does for every tag
|
|
334
|
+
* of an observation in ONE call.
|
|
113
335
|
*/
|
|
114
336
|
private updateTagStats;
|
|
115
|
-
/**
|
|
337
|
+
/**
|
|
338
|
+
* Replace a tag observation's reward without changing its count — the
|
|
339
|
+
* exact correction a revised label calls for.
|
|
340
|
+
*/
|
|
341
|
+
private reviseTagStats;
|
|
342
|
+
/**
|
|
343
|
+
* True when the configured policy needs reward variance and per-tag
|
|
344
|
+
* write timestamps. A veto cooldown counts: without a last-observation
|
|
345
|
+
* timestamp there is no way to tell that a veto has gone stale, so the
|
|
346
|
+
* cooldown would silently never fire.
|
|
347
|
+
*/
|
|
116
348
|
private needsVarianceTracking;
|
|
117
349
|
/** Per-user, per-tag reward statistics aggregated from observed outcomes */
|
|
118
350
|
getUserTagStats(userId: string): Promise<LearningTagStat[]>;
|
|
@@ -128,9 +360,54 @@ export declare class LearningManager {
|
|
|
128
360
|
* instead of the flat `priorWeight`.
|
|
129
361
|
*/
|
|
130
362
|
getLearnedRoutingWeights(userId: string, knownTags?: string[], existingWeights?: Record<string, number>): Promise<Record<string, number>>;
|
|
363
|
+
/** Independent attempts observed for a worker, counted once per attempt. */
|
|
364
|
+
getUserAttemptTotal(userId: string): Promise<number | undefined>;
|
|
365
|
+
/**
|
|
366
|
+
* The same synthesis with its reasoning attached — estimate, uncertainty,
|
|
367
|
+
* evidence, last observation and next reassessment per tag.
|
|
368
|
+
*/
|
|
369
|
+
explainLearnedRoutingWeights(userId: string, knownTags?: string[], existingWeights?: Record<string, number>): Promise<AutoWeightExplanation[]>;
|
|
370
|
+
/**
|
|
371
|
+
* Fold one lifecycle outcome into the per-worker and team aggregates the
|
|
372
|
+
* performance features read. Pure counters — no per-candidate reads ever
|
|
373
|
+
* happen against these; a matching pass loads one hash per worker.
|
|
374
|
+
*/
|
|
375
|
+
private updatePerformance;
|
|
376
|
+
/** Record an observed handling time (accept -> complete) for a worker */
|
|
377
|
+
recordHandlingTime(userId: string, tags: string[] | undefined, durationMs: number): Promise<void>;
|
|
378
|
+
/** Team-wide priors the per-worker rates are shrunk toward */
|
|
379
|
+
loadTeamPriors(): Promise<{
|
|
380
|
+
acceptanceRate?: number;
|
|
381
|
+
successRate?: number;
|
|
382
|
+
handlingTimeMs?: number;
|
|
383
|
+
}>;
|
|
384
|
+
/**
|
|
385
|
+
* Load one worker's performance aggregates and shrink them toward the
|
|
386
|
+
* team priors. A worker with no history gets the prior, not zero — an
|
|
387
|
+
* unjustifiably pessimistic estimate is how a new worker starves.
|
|
388
|
+
*/
|
|
389
|
+
loadPerformance(userId: string, priors: {
|
|
390
|
+
acceptanceRate?: number;
|
|
391
|
+
successRate?: number;
|
|
392
|
+
handlingTimeMs?: number;
|
|
393
|
+
}): Promise<LearningWorkerPerformance>;
|
|
394
|
+
/** Pure shrinkage of a raw aggregate hash toward team priors. */
|
|
395
|
+
shrinkPerformance(raw: Record<string, string>, priors: {
|
|
396
|
+
acceptanceRate?: number;
|
|
397
|
+
successRate?: number;
|
|
398
|
+
handlingTimeMs?: number;
|
|
399
|
+
}): LearningWorkerPerformance;
|
|
400
|
+
private bumpStat;
|
|
131
401
|
/** Aggregate learning statistics */
|
|
132
402
|
getStats(): Promise<LearningStats>;
|
|
133
|
-
/**
|
|
403
|
+
/**
|
|
404
|
+
* Reset model weights, statistics, and per-user tag statistics.
|
|
405
|
+
*
|
|
406
|
+
* The generation counter is bumped rather than cleared: attempts that are
|
|
407
|
+
* still in flight were committed against the old model, and applying
|
|
408
|
+
* their outcomes to the fresh one would silently repopulate what was just
|
|
409
|
+
* reset. Those events are rejected and counted as `supersededEvents`.
|
|
410
|
+
*/
|
|
134
411
|
resetModel(): Promise<void>;
|
|
135
412
|
}
|
|
136
413
|
//# sourceMappingURL=LearningManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,OAAO,KAAK,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,oBAAoB,EACpB,sBAAsB,EACtB,kBAAkB,EAClB,wBAAwB,EACxB,kBAAkB,EAClB,yBAAyB,EACzB,yBAAyB,EACzB,yBAAy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