assignment-user-matcher 1.15.1 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +372 -8
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/atomic-ingestion.d.ts +11 -0
  6. package/dist/learning/atomic-ingestion.d.ts.map +1 -0
  7. package/dist/learning/atomic-ingestion.js +187 -0
  8. package/dist/learning/auto-weights.d.ts +13 -2
  9. package/dist/learning/auto-weights.d.ts.map +1 -1
  10. package/dist/learning/auto-weights.js +203 -35
  11. package/dist/learning/features.d.ts +5 -3
  12. package/dist/learning/features.d.ts.map +1 -1
  13. package/dist/learning/features.js +105 -4
  14. package/dist/learning/policy.d.ts +57 -0
  15. package/dist/learning/policy.d.ts.map +1 -0
  16. package/dist/learning/policy.js +71 -0
  17. package/dist/managers/LearningManager.d.ts +312 -35
  18. package/dist/managers/LearningManager.d.ts.map +1 -1
  19. package/dist/managers/LearningManager.js +1006 -168
  20. package/dist/matcher.class.d.ts +98 -11
  21. package/dist/matcher.class.d.ts.map +1 -1
  22. package/dist/matcher.class.js +247 -40
  23. package/dist/scheduling/constraints/consecutive.d.ts +10 -0
  24. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -1
  25. package/dist/scheduling/constraints/consecutive.js +64 -1
  26. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  27. package/dist/scheduling/constraints/contract.js +12 -3
  28. package/dist/scheduling/constraints/cost.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/cost.js +3 -2
  30. package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
  31. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
  32. package/dist/scheduling/constraints/employee-scope.js +157 -0
  33. package/dist/scheduling/constraints/group-composition.js +2 -2
  34. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -1
  35. package/dist/scheduling/constraints/min-staffing.js +51 -8
  36. package/dist/scheduling/constraints/notice.d.ts.map +1 -1
  37. package/dist/scheduling/constraints/notice.js +8 -5
  38. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
  39. package/dist/scheduling/constraints/rest-days.js +6 -6
  40. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -1
  41. package/dist/scheduling/constraints/rolling-hours.js +29 -4
  42. package/dist/scheduling/cost.d.ts.map +1 -1
  43. package/dist/scheduling/cost.js +2 -1
  44. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  45. package/dist/scheduling/engine/construction.js +23 -3
  46. package/dist/scheduling/engine/objective.d.ts +4 -4
  47. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  48. package/dist/scheduling/engine/objective.js +32 -7
  49. package/dist/scheduling/engine/propagation.js +2 -1
  50. package/dist/scheduling/engine/search.d.ts +1 -0
  51. package/dist/scheduling/engine/search.d.ts.map +1 -1
  52. package/dist/scheduling/engine/search.js +1 -1
  53. package/dist/scheduling/engine/state.d.ts.map +1 -1
  54. package/dist/scheduling/engine/state.js +4 -0
  55. package/dist/scheduling/engine/timeline.d.ts +14 -0
  56. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  57. package/dist/scheduling/engine/timeline.js +33 -0
  58. package/dist/scheduling/index.d.ts +1 -1
  59. package/dist/scheduling/index.d.ts.map +1 -1
  60. package/dist/scheduling/model.d.ts +7 -2
  61. package/dist/scheduling/model.d.ts.map +1 -1
  62. package/dist/scheduling/model.js +254 -42
  63. package/dist/scheduling/operations.d.ts +4 -0
  64. package/dist/scheduling/operations.d.ts.map +1 -1
  65. package/dist/scheduling/operations.js +81 -22
  66. package/dist/scheduling/provenance.d.ts +1 -1
  67. package/dist/scheduling/provenance.d.ts.map +1 -1
  68. package/dist/scheduling/provenance.js +16 -2
  69. package/dist/scheduling/scheduler.class.d.ts +1 -1
  70. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  71. package/dist/scheduling/scheduler.class.js +5 -3
  72. package/dist/scheduling/sites.d.ts +1 -1
  73. package/dist/scheduling/sites.d.ts.map +1 -1
  74. package/dist/scheduling/sites.js +34 -1
  75. package/dist/scheduling/time.d.ts +2 -0
  76. package/dist/scheduling/time.d.ts.map +1 -1
  77. package/dist/scheduling/time.js +26 -1
  78. package/dist/scheduling/types.d.ts +152 -9
  79. package/dist/scheduling/types.d.ts.map +1 -1
  80. package/dist/types/matcher.d.ts +309 -4
  81. package/dist/types/matcher.d.ts.map +1 -1
  82. package/dist/utils/keys.d.ts +12 -2
  83. package/dist/utils/keys.d.ts.map +1 -1
  84. package/dist/utils/keys.js +35 -2
  85. package/package.json +12 -2
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LearningManager = exports.DEFAULT_LEARNING_REWARDS = void 0;
3
+ exports.LearningManager = exports.LEARNING_FEATURE_VERSION = exports.DEFAULT_LEARNING_REWARDS = void 0;
4
4
  const auto_weights_1 = require("../learning/auto-weights");
5
+ const atomic_ingestion_1 = require("../learning/atomic-ingestion");
5
6
  exports.DEFAULT_LEARNING_REWARDS = {
6
7
  accept: 0.3,
7
8
  complete: 1,
@@ -9,36 +10,91 @@ exports.DEFAULT_LEARNING_REWARDS = {
9
10
  expire: -0.3,
10
11
  fail: -0.8,
11
12
  };
13
+ /** Contract version of the decision records this build writes. */
14
+ exports.LEARNING_FEATURE_VERSION = 2;
12
15
  /** Outcomes that end an assignment's learning episode (decision record is removed) */
13
16
  const TERMINAL_OUTCOMES = new Set(['complete', 'reject', 'expire', 'fail']);
17
+ const DEFAULT_TARGETS = ['acceptance', 'successGivenAcceptance'];
14
18
  /**
15
- * Atomic decayed tag-outcome update: rescale the stored count/reward/rewardSq
16
- * sums by the elapsed half-life factor since the tag's last write, add the new
17
- * outcome at full weight, and stamp the write time — an exponentially-weighted
18
- * aggregate, exact per observation. KEYS: counts, rewards, rewardSq, ts
19
- * hashes. ARGV: tag, now (ms), halfLife (ms), reward.
19
+ * Batched decayed tag-outcome update. For each tag in ARGV (from index 4 on):
20
+ * rescale the stored weight/reward/rewardSq/weightSq sums by the elapsed
21
+ * half-life factor since that tag's last write, add the new observation at
22
+ * full weight, and stamp the write time — an exponentially-weighted
23
+ * aggregate, exact per observation.
24
+ *
25
+ * `weightSq` decays by f^2, not f: it is a sum of SQUARED weights, and
26
+ * carrying it is what makes the Kish effective sample size
27
+ * `sum(w)^2 / sum(w^2)` computable. Decaying it by f would leave the ratio
28
+ * indistinguishable from the raw count.
29
+ *
30
+ * KEYS: counts, rewards, rewardSq, ts, weightSq, attempts.
31
+ * ARGV: now (ms), halfLife (ms), reward, countAttempt, then the tags.
20
32
  */
21
33
  const DECAYED_TAG_OUTCOME_LUA = `
22
- local tag = ARGV[1]
23
- local now = tonumber(ARGV[2])
24
- local halfLife = tonumber(ARGV[3])
25
- local reward = tonumber(ARGV[4])
26
- local ts = tonumber(redis.call('HGET', KEYS[4], tag))
27
- local f = 1
28
- if ts and halfLife > 0 and now > ts then f = 2 ^ (-(now - ts) / halfLife) end
29
- local count = (tonumber(redis.call('HGET', KEYS[1], tag)) or 0) * f + 1
30
- local sum = (tonumber(redis.call('HGET', KEYS[2], tag)) or 0) * f + reward
31
- local sq = (tonumber(redis.call('HGET', KEYS[3], tag)) or 0) * f + reward * reward
32
- redis.call('HSET', KEYS[1], tag, count)
33
- redis.call('HSET', KEYS[2], tag, sum)
34
- redis.call('HSET', KEYS[3], tag, sq)
35
- redis.call('HSET', KEYS[4], tag, now)
34
+ local now = tonumber(ARGV[1])
35
+ local halfLife = tonumber(ARGV[2])
36
+ local reward = tonumber(ARGV[3])
37
+ local countAttempt = tonumber(ARGV[4])
38
+ for i = 5, #ARGV do
39
+ local tag = ARGV[i]
40
+ local ts = tonumber(redis.call('HGET', KEYS[4], tag))
41
+ local f = 1
42
+ if ts and halfLife > 0 and now > ts then f = 2 ^ (-(now - ts) / halfLife) end
43
+ local count = (tonumber(redis.call('HGET', KEYS[1], tag)) or 0) * f + 1
44
+ local sum = (tonumber(redis.call('HGET', KEYS[2], tag)) or 0) * f + reward
45
+ local sq = (tonumber(redis.call('HGET', KEYS[3], tag)) or 0) * f + reward * reward
46
+ local w2 = (tonumber(redis.call('HGET', KEYS[5], tag)) or 0) * f * f + 1
47
+ redis.call('HSET', KEYS[1], tag, count)
48
+ redis.call('HSET', KEYS[2], tag, sum)
49
+ redis.call('HSET', KEYS[3], tag, sq)
50
+ redis.call('HSET', KEYS[4], tag, now)
51
+ redis.call('HSET', KEYS[5], tag, w2)
52
+ if countAttempt == 1 then redis.call('HINCRBY', KEYS[6], tag, 1) end
53
+ end
36
54
  return 1
37
55
  `;
56
+ /**
57
+ * Revise a per-tag contribution that was already written, without adding a
58
+ * second observation: the count stays put and only the reward moments move.
59
+ * Under decay the old contribution has itself faded since it was written, so
60
+ * it is re-weighted by its own age (ARGV[3] = when it was written) before
61
+ * being swapped out — subtracting it at full weight would over-correct.
62
+ *
63
+ * KEYS: counts, rewards, rewardSq, ts. ARGV: now, halfLife, writtenAt,
64
+ * oldReward, newReward, then the tags.
65
+ */
66
+ const DECAYED_TAG_REVISION_LUA = `
67
+ local now = tonumber(ARGV[1])
68
+ local halfLife = tonumber(ARGV[2])
69
+ local writtenAt = tonumber(ARGV[3])
70
+ local oldR = tonumber(ARGV[4])
71
+ local newR = tonumber(ARGV[5])
72
+ local w = 1
73
+ if halfLife > 0 and now > writtenAt then w = 2 ^ (-(now - writtenAt) / halfLife) end
74
+ for i = 6, #ARGV do
75
+ local tag = ARGV[i]
76
+ local ts = tonumber(redis.call('HGET', KEYS[4], tag))
77
+ local f = 1
78
+ if ts and halfLife > 0 and now > ts then f = 2 ^ (-(now - ts) / halfLife) end
79
+ local count = (tonumber(redis.call('HGET', KEYS[1], tag)) or 0) * f
80
+ local sum = (tonumber(redis.call('HGET', KEYS[2], tag)) or 0) * f + w * (newR - oldR)
81
+ local sq = (tonumber(redis.call('HGET', KEYS[3], tag)) or 0) * f + w * (newR * newR - oldR * oldR)
82
+ if sq < 0 then sq = 0 end
83
+ redis.call('HSET', KEYS[1], tag, count)
84
+ redis.call('HSET', KEYS[2], tag, sum)
85
+ redis.call('HSET', KEYS[3], tag, sq)
86
+ redis.call('HSET', KEYS[4], tag, now)
87
+ end
88
+ return 1
89
+ `;
90
+ const clampFinite = (value, limit) => Math.max(-limit, Math.min(limit, value));
91
+ const sigmoid = (z) => 1 / (1 + Math.exp(-Math.max(-40, Math.min(40, z))));
38
92
  class LearningManager {
39
93
  constructor(redisClient, keys, options) {
40
94
  this.redisClient = redisClient;
41
95
  this.keys = keys;
96
+ /** Monotonic suffix making decision ids unique within a process-millisecond. */
97
+ this.decisionSeq = 0;
42
98
  this.learningRate = options?.learningRate ?? 0.1;
43
99
  this.explorationRate = options?.explorationRate ?? 0.05;
44
100
  this._shadowMode = options?.shadowMode ?? false;
@@ -49,11 +105,53 @@ class LearningManager {
49
105
  this.feedbackTtlMs = options?.feedbackTtlMs ?? 604800000;
50
106
  this.trackTagStats = options?.trackTagStats ?? false;
51
107
  this.autoWeights = options?.autoWeights ?? {};
108
+ this.updateMode = options?.updateMode ?? 'normalized';
109
+ this.l2 = options?.l2 ?? 0;
110
+ this.maxUpdateNorm = options?.maxUpdateNorm ?? 1;
111
+ this.maxWeightMagnitude = options?.maxWeightMagnitude ?? 100;
112
+ this.rewardAccounting = options?.rewardAccounting ?? 'per-event';
113
+ this.explorationPolicy = options?.explorationPolicy ?? 'jitter';
114
+ this.rng = options?.rng ?? Math.random;
115
+ this.targets = options?.targets;
116
+ this.activeTargets = options?.targets ? (options.targets.targets ?? DEFAULT_TARGETS) : [];
117
+ this.maxFeedbackAgeMs = options?.maxFeedbackAgeMs ?? this.feedbackTtlMs;
118
+ this.maxSignalMagnitude = options?.maxSignalMagnitude ?? 1e6;
119
+ this.maxRewardMagnitude = options?.maxRewardMagnitude ?? 100;
120
+ this.trackPerformance = options?.trackPerformance ?? false;
121
+ this.performancePriorStrength = options?.performancePriorStrength ?? 5;
52
122
  }
53
- /** Load the full model weights hash from Redis */
123
+ /** True when multi-target reward modelling is configured. */
124
+ get multiTarget() {
125
+ return this.activeTargets.length > 0;
126
+ }
127
+ // ------------------------------------------------------------------
128
+ // Model access
129
+ // ------------------------------------------------------------------
130
+ /** Load the full legacy model weights hash from Redis */
54
131
  async getModel() {
55
132
  return this.redisClient.hGetAll(this.keys.learningModel());
56
133
  }
134
+ /** Load one target's model weights hash */
135
+ async getTargetModel(target) {
136
+ return this.redisClient.hGetAll(this.keys.learningTargetModel(target));
137
+ }
138
+ /**
139
+ * Load every model needed for one matching pass in one batch, plus the
140
+ * generation stamped onto the decisions this pass commits.
141
+ */
142
+ async loadModels() {
143
+ const targetKeys = this.activeTargets;
144
+ const [legacy, generation, ...targetHashes] = await Promise.all([
145
+ this.getModel(),
146
+ this.currentGeneration(),
147
+ ...targetKeys.map((t) => this.getTargetModel(t)),
148
+ ]);
149
+ const targets = {};
150
+ targetKeys.forEach((t, i) => {
151
+ targets[t] = targetHashes[i];
152
+ });
153
+ return { generation: generation, legacy: legacy, targets };
154
+ }
57
155
  /** Predict expected reward for a feature vector against given model weights */
58
156
  predict(features, weights) {
59
157
  let sum = 0;
@@ -62,11 +160,42 @@ class LearningManager {
62
160
  if (!Number.isNaN(w) && w !== 0)
63
161
  sum += w * value;
64
162
  }
65
- return sum;
163
+ return Number.isFinite(sum) ? sum : 0;
66
164
  }
67
- /** Epsilon-greedy exploration check */
165
+ /**
166
+ * Score a candidate against a loaded snapshot.
167
+ *
168
+ * In multi-target mode the components are calibrated probabilities and
169
+ * the utility is their configured combination — never presented as a
170
+ * probability itself. In legacy mode the single model's raw prediction is
171
+ * both the utility and the only component.
172
+ */
173
+ predictWith(snapshot, features) {
174
+ if (!this.multiTarget) {
175
+ return { utility: this.predict(features, snapshot.legacy), components: {} };
176
+ }
177
+ const components = {};
178
+ for (const target of this.activeTargets) {
179
+ const weights = snapshot.targets[target] ?? {};
180
+ const raw = this.predict(features, weights);
181
+ components[target] = target === 'quality' ? Math.max(0, Math.min(1, raw)) : sigmoid(raw);
182
+ }
183
+ const hasAcceptance = this.activeTargets.includes('acceptance');
184
+ const pAccept = hasAcceptance ? (components.acceptance ?? 0) : 1;
185
+ const successWeight = this.targets?.successWeight ?? (this.activeTargets.includes('successGivenAcceptance') ? 1 : 0);
186
+ const qualityWeight = this.targets?.qualityWeight ??
187
+ (this.activeTargets.includes('quality') && !this.activeTargets.includes('successGivenAcceptance') ? 1 : 0);
188
+ // With no conditional target configured, acceptance IS the objective —
189
+ // defaulting its weight to 0 there would make the utility identically
190
+ // zero and leave ranking with no learned signal at all.
191
+ const acceptanceWeight = this.targets?.acceptanceWeight ?? (successWeight === 0 && qualityWeight === 0 ? 1 : 0);
192
+ const conditional = successWeight * (components.successGivenAcceptance ?? 0) + qualityWeight * (components.quality ?? 0);
193
+ const utility = acceptanceWeight * pAccept + pAccept * conditional;
194
+ return { utility: Number.isFinite(utility) ? utility : 0, components };
195
+ }
196
+ /** Epsilon-greedy exploration check (legacy 'jitter' policy) */
68
197
  shouldExplore() {
69
- return this.explorationRate > 0 && Math.random() < this.explorationRate;
198
+ return this.explorationRate > 0 && this.rng() < this.explorationRate;
70
199
  }
71
200
  /** Current shadow mode state (true: learn-only, false: affects ranking) */
72
201
  get shadowMode() {
@@ -81,29 +210,122 @@ class LearningManager {
81
210
  setShadowMode(enabled) {
82
211
  this._shadowMode = enabled;
83
212
  }
213
+ // ------------------------------------------------------------------
214
+ // Decisions (committed attempts)
215
+ // ------------------------------------------------------------------
84
216
  /**
85
- * Persist the decision context for an assignment so the eventual outcome
86
- * can be attributed back to the features that drove the match.
217
+ * Mint an id for one committed attempt. Unique per process-millisecond;
218
+ * the assignment id prefix keeps the key human-readable in Redis.
87
219
  */
88
- async recordDecision(userId, assignmentId, features, predictedReward, tags) {
89
- const record = {
90
- userId,
91
- assignmentId,
92
- features,
93
- predictedReward,
94
- tags,
95
- timestamp: Date.now(),
96
- };
220
+ newDecisionId(assignmentId) {
221
+ this.decisionSeq = (this.decisionSeq + 1) % 0xffffff;
222
+ return `${assignmentId}#${Date.now().toString(36)}${this.decisionSeq.toString(36)}${Math.floor(this.rng() * 0xffff).toString(36)}`;
223
+ }
224
+ /** Current model generation (cached for a second; a reset is rare) */
225
+ async currentGeneration() {
226
+ const cached = this.generationCache;
227
+ const now = Date.now();
228
+ if (cached && now - cached.readAt < 1000)
229
+ return cached.value;
230
+ const raw = await this.redisClient.get(this.keys.learningGeneration());
231
+ const value = Number(raw) || 0;
232
+ this.generationCache = { value, readAt: now };
233
+ return value;
234
+ }
235
+ /**
236
+ * Persist the contexts of attempts that were actually committed.
237
+ *
238
+ * Called from the claim path with only the ids the worker won, so a
239
+ * candidate that lost the race — to another worker in the same pass or to
240
+ * another process — leaves no decision behind.
241
+ */
242
+ async recordDecisions(inputs, generation) {
243
+ if (inputs.length === 0)
244
+ return;
245
+ const gen = generation ?? (await this.currentGeneration());
97
246
  const multi = this.redisClient.multi();
98
- multi.set(this.keys.learningDecision(assignmentId), JSON.stringify(record), {
99
- PX: this.decisionTtlMs,
100
- });
101
- multi.hIncrBy(this.keys.learningStats(), 'decisions', 1);
247
+ this.queueDecisionWrites(multi, inputs, gen);
102
248
  await multi.exec();
103
249
  }
104
- /** Fetch a stored decision record, or null when absent/expired */
250
+ /**
251
+ * Queue the same writes onto a caller-owned transaction.
252
+ *
253
+ * The claim path uses this to put the decision context in the *same*
254
+ * batch as the queued -> pending state change. A separate write after the
255
+ * claim leaves a crash gap in which the worker owns the assignment but no
256
+ * learning context exists for it, so its outcome would arrive orphaned.
257
+ *
258
+ * Takes an explicit generation (carried on the scoring snapshot) so it
259
+ * stays synchronous and can be composed into an existing multi.
260
+ */
261
+ queueDecisionWrites(multi, inputs, gen) {
262
+ if (inputs.length === 0)
263
+ return;
264
+ const now = Date.now();
265
+ for (const input of inputs) {
266
+ const record = {
267
+ decisionId: input.decisionId,
268
+ userId: input.userId,
269
+ assignmentId: input.assignmentId,
270
+ features: input.features,
271
+ predictedReward: input.predictedReward,
272
+ components: input.components,
273
+ tags: input.tags,
274
+ propensity: input.propensity,
275
+ policy: input.policy,
276
+ candidateCount: input.candidateCount,
277
+ featureVersion: exports.LEARNING_FEATURE_VERSION,
278
+ generation: gen,
279
+ accruedReward: 0,
280
+ timestamp: now,
281
+ };
282
+ multi.set(this.keys.learningDecision(input.decisionId), JSON.stringify(record), { PX: this.decisionTtlMs });
283
+ multi.set(this.keys.learningDecisionPointer(input.assignmentId), input.decisionId, {
284
+ PX: this.decisionTtlMs,
285
+ });
286
+ }
287
+ multi.hIncrBy(this.keys.learningStats(), 'decisions', inputs.length);
288
+ }
289
+ /**
290
+ * Persist one decision context.
291
+ *
292
+ * @deprecated Prefer {@link recordDecisions} from the claim path; this
293
+ * single-record form exists for direct/manual integrations.
294
+ */
295
+ async recordDecision(userId, assignmentId, features, predictedReward, tags) {
296
+ const decisionId = this.newDecisionId(assignmentId);
297
+ await this.recordDecisions([{ decisionId, userId, assignmentId, features, predictedReward, tags }]);
298
+ return decisionId;
299
+ }
300
+ /** Fetch the in-flight decision record for an assignment, or null */
105
301
  async getDecision(assignmentId) {
106
- const json = await this.redisClient.get(this.keys.learningDecision(assignmentId));
302
+ const decisionId = await this.redisClient.get(this.keys.learningDecisionPointer(assignmentId));
303
+ if (!decisionId)
304
+ return null;
305
+ return this.getDecisionById(decisionId);
306
+ }
307
+ /** Fetch a decision record by attempt id, or null when absent/expired */
308
+ async getDecisionById(decisionId) {
309
+ const json = await this.redisClient.get(this.keys.learningDecision(decisionId));
310
+ if (!json)
311
+ return null;
312
+ try {
313
+ return JSON.parse(json);
314
+ }
315
+ catch {
316
+ return null;
317
+ }
318
+ }
319
+ /** Fetch the most recently archived episode for an assignment, or null */
320
+ async getEpisode(assignmentId) {
321
+ const decisionId = await this.redisClient.get(this.keys.learningEpisodePointer(assignmentId));
322
+ if (!decisionId)
323
+ return null;
324
+ return this.getEpisodeById(decisionId);
325
+ }
326
+ /** Fetch an archived episode by attempt id, or null when absent/expired */
327
+ async getEpisodeById(decisionId) {
328
+ const json = await this.redisClient.get(this.keys.learningEpisode(decisionId));
107
329
  if (!json)
108
330
  return null;
109
331
  try {
@@ -113,197 +335,628 @@ class LearningManager {
113
335
  return null;
114
336
  }
115
337
  }
338
+ // ------------------------------------------------------------------
339
+ // Outcome ingestion
340
+ // ------------------------------------------------------------------
116
341
  /**
117
- * Apply a lifecycle outcome as a reward update.
118
- * Terminal outcomes archive the decision as an episode (with TTL) so late
342
+ * Apply a lifecycle outcome to the attempt currently in flight for an
343
+ * assignment. Idempotent: a redelivered event applies once.
344
+ *
345
+ * Terminal outcomes archive the attempt as an episode (with TTL) so late
119
346
  * external feedback can still be attributed to the original features.
120
- * Returns false if no decision context exists for the assignment.
347
+ * Returns false when the event was not applied, for any reason.
348
+ */
349
+ async applyOutcome(assignmentId, outcome, options) {
350
+ const eventKey = options?.eventId ? `event:${options.eventId}` : `outcome:${outcome}`;
351
+ return this.ingest(assignmentId, {
352
+ eventKey,
353
+ reward: this.rewards[outcome],
354
+ terminal: TERMINAL_OUTCOMES.has(outcome),
355
+ outcome,
356
+ expectedUserId: options?.expectedUserId,
357
+ systemFault: options?.systemFault,
358
+ });
359
+ }
360
+ /**
361
+ * Apply a manually chosen reward to the in-flight attempt.
362
+ *
363
+ * Terminal by default (it closes the learning episode) — pass
364
+ * `terminal: false` to shape a reward without ending the attempt, which
365
+ * is what lets later lifecycle outcomes still produce their own labels.
121
366
  */
122
- async applyOutcome(assignmentId, outcome) {
123
- return this.applyReward(assignmentId, this.rewards[outcome], TERMINAL_OUTCOMES.has(outcome), outcome);
367
+ async recordReward(assignmentId, reward, options) {
368
+ if (!Number.isFinite(reward)) {
369
+ await this.bumpStat('invalidFeedback');
370
+ return false;
371
+ }
372
+ return this.ingest(assignmentId, {
373
+ eventKey: options?.eventId ? `event:${options.eventId}` : `reward:${Date.now()}:${this.decisionSeq++}`,
374
+ reward,
375
+ terminal: options?.terminal ?? true,
376
+ expectedUserId: options?.expectedUserId,
377
+ });
124
378
  }
125
379
  /**
126
- * Apply a manually chosen reward (terminal: removes the decision record).
127
- * Enables external reward shaping beyond the built-in lifecycle outcomes.
380
+ * Apply named external feedback signals (e.g. `{ accuracy: 0.95 }`) to an
381
+ * attempt — the one in flight, or the archived episode when the work has
382
+ * already closed.
383
+ *
384
+ * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
385
+ * Validation happens before anything is written: an empty signal map, a
386
+ * non-numeric value, or a value beyond `maxSignalMagnitude` is rejected
387
+ * whole rather than becoming a partial or zero-reward observation.
388
+ *
389
+ * Addressing an assignment that has BOTH a live attempt and an archived
390
+ * one is ambiguous after a reassignment — it is rejected rather than
391
+ * guessed. Pass the `decisionId` to say which attempt is meant.
128
392
  */
129
- async recordReward(assignmentId, reward) {
130
- return this.applyReward(assignmentId, reward, true);
393
+ async recordFeedback(assignmentId, signals, options) {
394
+ const reward = this.rewardFromSignals(signals);
395
+ if (reward === undefined) {
396
+ await this.bumpStat('invalidFeedback');
397
+ return false;
398
+ }
399
+ let decisionId = options?.decisionId;
400
+ if (!decisionId) {
401
+ const [live, archived] = await Promise.all([
402
+ this.redisClient.get(this.keys.learningDecisionPointer(assignmentId)),
403
+ this.redisClient.get(this.keys.learningEpisodePointer(assignmentId)),
404
+ ]);
405
+ if (live && archived && live !== archived) {
406
+ // The assignment has been rematched: the archived attempt and
407
+ // the live one are different workers' work. Guessing here is
408
+ // exactly the mis-attribution this layer exists to avoid.
409
+ await this.bumpStat('ambiguousFeedback');
410
+ return false;
411
+ }
412
+ decisionId = (live ?? archived);
413
+ }
414
+ if (!decisionId) {
415
+ await this.bumpStat('orphanEvents');
416
+ return false;
417
+ }
418
+ return this.ingest(assignmentId, {
419
+ eventKey: options?.eventId ? `event:${options.eventId}` : `feedback:${this.signalFingerprint(signals)}`,
420
+ reward,
421
+ terminal: true,
422
+ decisionId,
423
+ expectedUserId: options?.expectedUserId,
424
+ quality: this.qualityFromSignals(signals),
425
+ });
131
426
  }
132
- async applyReward(assignmentId, reward, terminal, outcome) {
133
- const decision = await this.getDecision(assignmentId);
134
- if (!decision)
427
+ /** Sum of weighted signals, or undefined when the map fails validation. */
428
+ rewardFromSignals(signals) {
429
+ if (!signals || typeof signals !== 'object')
430
+ return undefined;
431
+ const entries = Object.entries(signals);
432
+ if (entries.length === 0)
433
+ return undefined;
434
+ let reward = 0;
435
+ for (const [signal, value] of entries) {
436
+ if (typeof value !== 'number' || !Number.isFinite(value))
437
+ return undefined;
438
+ if (Math.abs(value) > this.maxSignalMagnitude)
439
+ return undefined;
440
+ const weight = this.signalWeights[signal] ?? 1;
441
+ if (!Number.isFinite(weight))
442
+ return undefined;
443
+ reward += value * weight;
444
+ }
445
+ return Number.isFinite(reward) ? reward : undefined;
446
+ }
447
+ /**
448
+ * Normalized quality label in [0, 1] from a signal map, or undefined when
449
+ * the signals carry no quality reading — which trains nothing.
450
+ */
451
+ qualityFromSignals(signals) {
452
+ if (!this.activeTargets.includes('quality'))
453
+ return undefined;
454
+ const raw = signals.quality;
455
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
456
+ return undefined;
457
+ return Math.max(0, Math.min(1, raw));
458
+ }
459
+ signalFingerprint(signals) {
460
+ return Object.keys(signals)
461
+ .sort()
462
+ .map((k) => `${k}=${signals[k]}`)
463
+ .join('|');
464
+ }
465
+ /**
466
+ * The single ingestion path. Everything that trains the model goes
467
+ * through here so attribution, deduplication, staleness and generation
468
+ * checks cannot drift between callers.
469
+ */
470
+ async ingest(assignmentId, event) {
471
+ // A private view isolates the staged client and generation cache from
472
+ // other callers using this manager concurrently.
473
+ for (let attempt = 0; attempt < 32; attempt++) {
474
+ const work = (0, atomic_ingestion_1.prepareIngestion)(this.redisClient, [DECAYED_TAG_OUTCOME_LUA, DECAYED_TAG_REVISION_LUA]);
475
+ const view = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
476
+ view.redisClient = work.client;
477
+ view.generationCache = undefined;
478
+ const result = await view.ingestPrepared(assignmentId, event);
479
+ if (await work.commit())
480
+ return result;
481
+ }
482
+ throw new Error('Learning ingestion contention: retry the event with the same event ID');
483
+ }
484
+ async ingestPrepared(assignmentId, event) {
485
+ let decisionId = event.decisionId;
486
+ if (!decisionId) {
487
+ decisionId = (await this.redisClient.get(this.keys.learningDecisionPointer(assignmentId)));
488
+ }
489
+ if (!decisionId) {
490
+ await this.bumpStat('orphanEvents');
135
491
  return false;
136
- await this.updateModel(decision.features, reward);
137
- await this.updateTagStats(decision.userId, decision.tags, reward, terminal);
138
- if (terminal) {
139
- // Archive as episode so external post-processing feedback can
140
- // still reach the model after the assignment is closed.
141
- const episode = {
142
- userId: decision.userId,
143
- assignmentId,
144
- features: decision.features,
145
- outcome,
146
- tags: decision.tags,
147
- timestamp: Date.now(),
148
- };
149
- const multi = this.redisClient.multi();
150
- multi.set(this.keys.learningEpisode(assignmentId), JSON.stringify(episode), {
151
- PX: this.feedbackTtlMs,
152
- });
153
- multi.del(this.keys.learningDecision(assignmentId));
154
- await multi.exec();
492
+ }
493
+ const appliedKey = this.keys.learningApplied(decisionId);
494
+ const [decision, episode, appliedEvents] = await Promise.all([
495
+ this.getDecisionById(decisionId),
496
+ event.terminal || !event.outcome ? this.getEpisodeById(decisionId) : Promise.resolve(null),
497
+ this.redisClient.sMembers(appliedKey),
498
+ ]);
499
+ if (appliedEvents.includes(event.eventKey)) {
500
+ await this.bumpStat('duplicateEvents');
501
+ return false;
502
+ }
503
+ const context = decision ?? episode;
504
+ if (!context) {
505
+ await this.bumpStat('staleEvents');
506
+ return false;
507
+ }
508
+ if (event.expectedUserId && context.userId !== event.expectedUserId) {
509
+ await this.bumpStat('orphanEvents');
510
+ return false;
511
+ }
512
+ const generation = await this.currentGeneration();
513
+ if ((context.generation ?? 0) !== generation) {
514
+ await this.bumpStat('supersededEvents');
515
+ return false;
516
+ }
517
+ const age = Date.now() - context.timestamp;
518
+ if (age > this.maxFeedbackAgeMs) {
519
+ await this.bumpStat('staleEvents');
520
+ return false;
521
+ }
522
+ // Staged writes become visible only with every model/evidence update.
523
+ await this.redisClient.sAdd(appliedKey, event.eventKey);
524
+ await this.redisClient.pExpire(appliedKey, this.decisionTtlMs + this.feedbackTtlMs);
525
+ appliedEvents.push(event.eventKey);
526
+ const reward = clampFinite(event.reward, this.maxRewardMagnitude);
527
+ // ---- model updates -------------------------------------------------
528
+ if (this.multiTarget) {
529
+ await this.trainTargets(context.features, event, appliedEvents);
530
+ }
531
+ await this.updateModel(context.features, reward);
532
+ // ---- per-tag evidence ---------------------------------------------
533
+ if (this.rewardAccounting === 'per-attempt') {
534
+ await this.accountPerAttempt(decisionId, decision, episode, reward, event);
535
+ }
536
+ else {
537
+ await this.updateTagStats(context.userId, context.tags, reward, event.terminal, true);
538
+ }
539
+ // ---- performance aggregates ---------------------------------------
540
+ if (this.trackPerformance && event.outcome) {
541
+ await this.updatePerformance(context.userId, context.tags, event.outcome, appliedEvents);
542
+ }
543
+ // ---- lifecycle -----------------------------------------------------
544
+ if (event.terminal && decision) {
545
+ await this.archive(decision, event.outcome, reward);
155
546
  }
156
547
  return true;
157
548
  }
158
- /** Apply an SGD update for a single (features, reward) observation */
159
- async updateModel(features, reward) {
160
- const weights = await this.getModel();
161
- const prediction = this.predict(features, weights);
162
- const error = reward - prediction;
549
+ /** Archive an in-flight attempt as an episode and retire its pointer. */
550
+ async archive(decision, outcome, finalReward) {
551
+ const perAttempt = this.rewardAccounting === 'per-attempt';
552
+ const episode = {
553
+ decisionId: decision.decisionId,
554
+ userId: decision.userId,
555
+ assignmentId: decision.assignmentId,
556
+ features: decision.features,
557
+ outcome,
558
+ tags: decision.tags,
559
+ generation: decision.generation,
560
+ appliedTagReward: perAttempt ? (decision.accruedReward ?? 0) + finalReward : undefined,
561
+ tagStatsAt: perAttempt ? Date.now() : undefined,
562
+ timestamp: decision.timestamp,
563
+ };
163
564
  const multi = this.redisClient.multi();
565
+ multi.set(this.keys.learningEpisode(decision.decisionId), JSON.stringify(episode), { PX: this.feedbackTtlMs });
566
+ multi.set(this.keys.learningEpisodePointer(decision.assignmentId), decision.decisionId, {
567
+ PX: this.feedbackTtlMs,
568
+ });
569
+ multi.del(this.keys.learningDecision(decision.decisionId));
570
+ multi.del(this.keys.learningDecisionPointer(decision.assignmentId));
571
+ await multi.exec();
572
+ }
573
+ /**
574
+ * `per-attempt` evidence: accumulate rewards on the live attempt and
575
+ * write ONE per-tag observation when it closes. Feedback arriving after
576
+ * that revises the existing observation instead of adding a second — a
577
+ * correction is not new evidence.
578
+ */
579
+ async accountPerAttempt(decisionId, decision, episode, reward, event) {
580
+ if (decision && !event.terminal) {
581
+ decision.accruedReward = (decision.accruedReward ?? 0) + reward;
582
+ await this.redisClient.set(this.keys.learningDecision(decisionId), JSON.stringify(decision), {
583
+ PX: this.decisionTtlMs,
584
+ XX: true,
585
+ });
586
+ return;
587
+ }
588
+ if (decision && event.terminal) {
589
+ const total = clampFinite((decision.accruedReward ?? 0) + reward, this.maxRewardMagnitude);
590
+ await this.updateTagStats(decision.userId, decision.tags, total, true, true);
591
+ return;
592
+ }
593
+ if (episode) {
594
+ const previous = episode.appliedTagReward;
595
+ if (previous === undefined) {
596
+ await this.updateTagStats(episode.userId, episode.tags, reward, true, true);
597
+ return;
598
+ }
599
+ const revised = clampFinite(previous + reward, this.maxRewardMagnitude);
600
+ await this.reviseTagStats(episode, previous, revised);
601
+ episode.appliedTagReward = revised;
602
+ await this.redisClient.set(this.keys.learningEpisode(episode.decisionId), JSON.stringify(episode), {
603
+ PX: this.feedbackTtlMs,
604
+ XX: true,
605
+ });
606
+ }
607
+ }
608
+ /** Derive and apply per-target labels for one lifecycle event. */
609
+ async trainTargets(features, event, appliedEvents) {
610
+ const updates = [];
611
+ const accepted = appliedEvents.includes('outcome:accept');
612
+ const systemFaultCounts = this.targets?.systemFaultCountsAsFailure ?? false;
613
+ switch (event.outcome) {
614
+ case 'accept':
615
+ updates.push(['acceptance', 1]);
616
+ break;
617
+ case 'reject':
618
+ updates.push(['acceptance', 0]);
619
+ break;
620
+ case 'expire':
621
+ // Before acceptance the expiry is a non-response — an
622
+ // acceptance label. After acceptance it is a completion
623
+ // failure, and only counts against the worker when the caller
624
+ // has not flagged it as a system fault.
625
+ if (!accepted)
626
+ updates.push(['acceptance', 0]);
627
+ else if (!event.systemFault || systemFaultCounts)
628
+ updates.push(['successGivenAcceptance', 0]);
629
+ break;
630
+ case 'complete':
631
+ updates.push(['successGivenAcceptance', 1]);
632
+ break;
633
+ case 'fail':
634
+ if (!event.systemFault || systemFaultCounts)
635
+ updates.push(['successGivenAcceptance', 0]);
636
+ break;
637
+ default:
638
+ break;
639
+ }
640
+ if (event.quality !== undefined)
641
+ updates.push(['quality', event.quality]);
642
+ for (const [target, label] of updates) {
643
+ if (!this.activeTargets.includes(target))
644
+ continue;
645
+ await this.updateTargetModel(target, features, label);
646
+ }
647
+ }
648
+ // ------------------------------------------------------------------
649
+ // Model training
650
+ // ------------------------------------------------------------------
651
+ /**
652
+ * Active feature names, in a stable order, skipping zero-valued and
653
+ * non-finite entries — the only fields an update ever needs to read.
654
+ */
655
+ activeFeatures(features) {
656
+ const active = [];
164
657
  for (const [feature, value] of Object.entries(features)) {
165
- if (value === 0)
658
+ if (typeof value !== 'number' || !Number.isFinite(value) || value === 0)
166
659
  continue;
167
- multi.hIncrByFloat(this.keys.learningModel(), feature, this.learningRate * error * value);
660
+ active.push([feature, value]);
168
661
  }
169
- multi.hIncrBy(this.keys.learningStats(), 'rewards', 1);
170
- multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', reward);
171
- await multi.exec();
662
+ return active;
172
663
  }
173
- /** Fetch an archived episode record, or null when absent/expired */
174
- async getEpisode(assignmentId) {
175
- const json = await this.redisClient.get(this.keys.learningEpisode(assignmentId));
176
- if (!json)
177
- return null;
178
- try {
179
- return JSON.parse(json);
664
+ /**
665
+ * Read only the weights an update touches.
666
+ *
667
+ * The old code loaded the entire model hash for every observation, which
668
+ * grows without bound as the feature space does. HMGET over the active
669
+ * features is O(active features) regardless of model size.
670
+ */
671
+ async readWeights(key, names) {
672
+ const out = {};
673
+ if (names.length === 0)
674
+ return out;
675
+ const raw = (await this.redisClient.hmGet(key, names));
676
+ names.forEach((name, i) => {
677
+ out[name] = Number(raw[i]) || 0;
678
+ });
679
+ return out;
680
+ }
681
+ /**
682
+ * Turn a prediction error into a bounded weight delta per feature.
683
+ *
684
+ * The raw rule `w += lr * error * x` is unstable: with `k` active unit
685
+ * features every step overshoots by a factor of `k`, so the error
686
+ * alternates sign and grows. Normalizing by the active vector's squared
687
+ * norm makes one step land exactly on the observation (the
688
+ * normalized-LMS / passive-aggressive rule) regardless of how many
689
+ * features fired; the norm clip and weight cap bound the rest.
690
+ */
691
+ computeDeltas(active, weights, error, rate = this.learningRate) {
692
+ const deltas = {};
693
+ if (active.length === 0 || !Number.isFinite(error))
694
+ return deltas;
695
+ let denominator = 1;
696
+ if (this.updateMode === 'normalized') {
697
+ let sq = 0;
698
+ for (const [, value] of active)
699
+ sq += value * value;
700
+ // Floor of 1 keeps a sparse vector of tiny values from turning a
701
+ // normalized step into a division blow-up.
702
+ denominator = Math.max(1, sq);
180
703
  }
181
- catch {
182
- return null;
704
+ const scale = (rate * error) / denominator;
705
+ let normSq = 0;
706
+ for (const [feature, value] of active) {
707
+ const delta = scale * value - rate * this.l2 * (weights[feature] ?? 0);
708
+ if (!Number.isFinite(delta))
709
+ continue;
710
+ deltas[feature] = delta;
711
+ normSq += delta * delta;
183
712
  }
713
+ const norm = Math.sqrt(normSq);
714
+ if (this.maxUpdateNorm > 0 && norm > this.maxUpdateNorm) {
715
+ const shrink = this.maxUpdateNorm / norm;
716
+ for (const feature of Object.keys(deltas))
717
+ deltas[feature] *= shrink;
718
+ }
719
+ return deltas;
184
720
  }
185
721
  /**
186
- * Apply named external feedback signals (e.g. { accuracy: 0.95 }) against
187
- * the live decision or the archived episode of an assignment.
188
- * Reward = sum(signalValue * signalWeight), default weight 1 per signal.
189
- * Returns false when no learning context exists for the assignment.
722
+ * Write deltas, clamping any weight that would leave the magnitude cap.
723
+ * Increments are used in the ordinary case so concurrent trainers compose;
724
+ * the clamp falls back to a set, which is the only way to bound a value.
190
725
  */
191
- async recordFeedback(assignmentId, signals) {
192
- const context = (await this.getDecision(assignmentId)) ?? (await this.getEpisode(assignmentId));
193
- if (!context)
194
- return false;
195
- let reward = 0;
196
- for (const [signal, value] of Object.entries(signals)) {
197
- const weight = this.signalWeights[signal] ?? 1;
198
- reward += value * weight;
726
+ writeDeltas(multi, key, deltas, weights) {
727
+ for (const [feature, delta] of Object.entries(deltas)) {
728
+ const next = (weights[feature] ?? 0) + delta;
729
+ if (Math.abs(next) > this.maxWeightMagnitude) {
730
+ multi.hSet(key, feature, String(Math.sign(next) * this.maxWeightMagnitude));
731
+ }
732
+ else {
733
+ multi.hIncrByFloat(key, feature, delta);
734
+ }
199
735
  }
200
- await this.updateModel(context.features, reward);
201
- await this.updateTagStats(context.userId, context.tags, reward, true);
202
- return true;
736
+ }
737
+ /** Apply one bounded SGD step to the legacy scalar-reward model */
738
+ async updateModel(features, reward) {
739
+ const active = this.activeFeatures(features);
740
+ const names = active.map(([name]) => name);
741
+ const weights = await this.readWeights(this.keys.learningModel(), names);
742
+ let prediction = 0;
743
+ for (const [feature, value] of active)
744
+ prediction += (weights[feature] ?? 0) * value;
745
+ const deltas = this.computeDeltas(active, weights, reward - prediction);
746
+ const multi = this.redisClient.multi();
747
+ this.writeDeltas(multi, this.keys.learningModel(), deltas, weights);
748
+ multi.hIncrBy(this.keys.learningStats(), 'rewards', 1);
749
+ multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', reward);
750
+ await multi.exec();
751
+ }
752
+ /** Apply one bounded step to a target model (logistic for binary targets) */
753
+ async updateTargetModel(target, features, label) {
754
+ const active = this.activeFeatures(features);
755
+ if (active.length === 0)
756
+ return;
757
+ const key = this.keys.learningTargetModel(target);
758
+ const names = active.map(([name]) => name);
759
+ const weights = await this.readWeights(key, names);
760
+ let z = 0;
761
+ for (const [feature, value] of active)
762
+ z += (weights[feature] ?? 0) * value;
763
+ const prediction = target === 'quality' ? z : sigmoid(z);
764
+ const rate = this.targets?.learningRates?.[target];
765
+ const deltas = this.computeDeltas(active, weights, label - prediction, rate ?? this.learningRate);
766
+ const multi = this.redisClient.multi();
767
+ this.writeDeltas(multi, key, deltas, weights);
768
+ multi.hIncrBy(this.keys.learningStats(), `labels:${target}`, 1);
769
+ await multi.exec();
203
770
  }
204
771
  /**
205
772
  * Train the model directly with raw (features, reward) samples.
206
773
  * Enables offline/batch imports from external pipelines (data warehouses,
207
774
  * historical logs, post-processing jobs) without a live decision context.
208
775
  *
209
- * The model is loaded once and SGD is replayed locally, then the
210
- * accumulated deltas are written in a single batched round trip —
211
- * equivalent to per-sample updateModel calls when no concurrent writer
212
- * interleaves, and orders of magnitude cheaper for bulk imports.
776
+ * Samples are processed in bounded chunks and each chunk re-reads the
777
+ * weights it touches, so a long import cannot keep accumulating against a
778
+ * snapshot the live model has already moved away from.
213
779
  */
214
- async trainSamples(samples) {
780
+ async trainSamples(samples, chunkSize = 200) {
215
781
  if (samples.length === 0)
216
782
  return 0;
217
- const weights = await this.getModel();
218
- const local = {};
219
- for (const [feature, raw] of Object.entries(weights)) {
220
- local[feature] = Number(raw) || 0;
221
- }
222
- const deltas = new Map();
223
- let totalReward = 0;
224
- for (const sample of samples) {
225
- const prediction = this.predict(sample.features, local);
226
- const error = sample.reward - prediction;
227
- for (const [feature, value] of Object.entries(sample.features)) {
228
- if (value === 0)
229
- continue;
230
- const delta = this.learningRate * error * value;
231
- deltas.set(feature, (deltas.get(feature) ?? 0) + delta);
232
- local[feature] = (local[feature] ?? 0) + delta;
233
- }
234
- totalReward += sample.reward;
235
- }
236
- const multi = this.redisClient.multi();
237
- for (const [feature, delta] of deltas) {
238
- multi.hIncrByFloat(this.keys.learningModel(), feature, delta);
783
+ const valid = samples.filter((s) => s &&
784
+ typeof s.reward === 'number' &&
785
+ Number.isFinite(s.reward) &&
786
+ s.features &&
787
+ typeof s.features === 'object');
788
+ if (valid.length === 0)
789
+ return 0;
790
+ let applied = 0;
791
+ for (let start = 0; start < valid.length; start += chunkSize) {
792
+ const chunk = valid.slice(start, start + chunkSize);
793
+ const names = new Set();
794
+ const actives = chunk.map((sample) => {
795
+ const active = this.activeFeatures(sample.features);
796
+ for (const [name] of active)
797
+ names.add(name);
798
+ return active;
799
+ });
800
+ const nameList = Array.from(names);
801
+ const weights = await this.readWeights(this.keys.learningModel(), nameList);
802
+ const local = { ...weights };
803
+ const totals = {};
804
+ let totalReward = 0;
805
+ chunk.forEach((sample, i) => {
806
+ const active = actives[i];
807
+ let prediction = 0;
808
+ for (const [feature, value] of active)
809
+ prediction += (local[feature] ?? 0) * value;
810
+ const reward = clampFinite(sample.reward, this.maxRewardMagnitude);
811
+ const deltas = this.computeDeltas(active, local, reward - prediction);
812
+ for (const [feature, delta] of Object.entries(deltas)) {
813
+ totals[feature] = (totals[feature] ?? 0) + delta;
814
+ local[feature] = (local[feature] ?? 0) + delta;
815
+ }
816
+ totalReward += reward;
817
+ });
818
+ const multi = this.redisClient.multi();
819
+ this.writeDeltas(multi, this.keys.learningModel(), totals, weights);
820
+ multi.hIncrBy(this.keys.learningStats(), 'rewards', chunk.length);
821
+ multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', totalReward);
822
+ await multi.exec();
823
+ applied += chunk.length;
239
824
  }
240
- multi.hIncrBy(this.keys.learningStats(), 'rewards', samples.length);
241
- multi.hIncrByFloat(this.keys.learningStats(), 'totalReward', totalReward);
242
- await multi.exec();
243
- return samples.length;
825
+ return applied;
244
826
  }
827
+ // ------------------------------------------------------------------
828
+ // Per-tag evidence
829
+ // ------------------------------------------------------------------
245
830
  /**
246
- * Update per-user, per-tag reward aggregates (count + reward sum).
247
- * Uses atomic hash increments only - O(tags) with no read-modify-write -
248
- * so high-throughput outcome streams scale without contention.
831
+ * Update per-user, per-tag reward aggregates.
832
+ *
833
+ * Without decay these are plain atomic increments — O(tags), no
834
+ * read-modify-write, so high-throughput outcome streams scale without
835
+ * contention. With decay the sums must be rescaled to "as of now" before
836
+ * the observation lands, which the batched Lua script does for every tag
837
+ * of an observation in ONE call.
249
838
  */
250
- async updateTagStats(userId, tags, reward, terminal) {
839
+ async updateTagStats(userId, tags, reward, terminal, countAttempt) {
251
840
  if (!this.trackTagStats || !tags || tags.length === 0)
252
841
  return;
253
842
  if (this.autoWeights.terminalOnlyTagStats && !terminal)
254
843
  return;
844
+ const cleanTags = tags.filter(Boolean);
845
+ if (cleanTags.length === 0)
846
+ return;
255
847
  const needVariance = this.needsVarianceTracking();
256
848
  const now = Date.now();
257
849
  const halfLife = this.autoWeights.decayHalfLifeMs ?? 0;
258
850
  if (halfLife > 0) {
259
- // With decay configured, the stored sums must be rescaled to "as of
260
- // now" BEFORE the new outcome is added, atomically per tag. Plain
261
- // increments plus a timestamp reset would (a) never change the
262
- // mean (count and sum decay identically) and (b) resurrect fully
263
- // decayed history the moment one fresh outcome landed.
264
- for (const tag of tags) {
265
- if (!tag)
266
- continue;
851
+ for (let i = 0; i < cleanTags.length; i += 100) {
267
852
  await this.redisClient.eval(DECAYED_TAG_OUTCOME_LUA, {
268
853
  keys: [
269
854
  this.keys.learningUserTagCounts(userId),
270
855
  this.keys.learningUserTagRewards(userId),
271
856
  this.keys.learningUserTagRewardSq(userId),
272
857
  this.keys.learningUserTagTs(userId),
858
+ this.keys.learningUserTagWeightSq(userId),
859
+ this.keys.learningUserTagAttempts(userId),
860
+ ],
861
+ arguments: [
862
+ String(now),
863
+ String(halfLife),
864
+ String(reward),
865
+ countAttempt ? '1' : '0',
866
+ ...cleanTags.slice(i, i + 100),
273
867
  ],
274
- arguments: [tag, String(now), String(halfLife), String(reward)],
275
868
  });
276
869
  }
277
- await this.redisClient.sAdd(this.keys.learningUsers(), userId);
870
+ const post = this.redisClient.multi();
871
+ post.sAdd(this.keys.learningUsers(), userId);
872
+ if (countAttempt)
873
+ post.incr(this.keys.learningUserAttempts(userId));
874
+ await post.exec();
278
875
  return;
279
876
  }
280
877
  const multi = this.redisClient.multi();
281
- for (const tag of tags) {
282
- if (!tag)
283
- continue;
878
+ for (const tag of cleanTags) {
284
879
  multi.hIncrBy(this.keys.learningUserTagCounts(userId), tag, 1);
285
880
  multi.hIncrByFloat(this.keys.learningUserTagRewards(userId), tag, reward);
881
+ if (countAttempt)
882
+ multi.hIncrBy(this.keys.learningUserTagAttempts(userId), tag, 1);
286
883
  if (needVariance) {
287
884
  multi.hIncrByFloat(this.keys.learningUserTagRewardSq(userId), tag, reward * reward);
885
+ multi.hIncrByFloat(this.keys.learningUserTagWeightSq(userId), tag, 1);
288
886
  multi.hSet(this.keys.learningUserTagTs(userId), tag, now.toString());
289
887
  }
290
888
  }
291
889
  multi.sAdd(this.keys.learningUsers(), userId);
890
+ if (countAttempt)
891
+ multi.incr(this.keys.learningUserAttempts(userId));
292
892
  await multi.exec();
293
893
  }
294
- /** True when the configured policy/decay needs reward variance/timestamps. */
894
+ /**
895
+ * Replace a tag observation's reward without changing its count — the
896
+ * exact correction a revised label calls for.
897
+ */
898
+ async reviseTagStats(episode, previousReward, revisedReward) {
899
+ if (!this.trackTagStats || !episode.tags || episode.tags.length === 0)
900
+ return;
901
+ const cleanTags = episode.tags.filter(Boolean);
902
+ if (cleanTags.length === 0)
903
+ return;
904
+ const halfLife = this.autoWeights.decayHalfLifeMs ?? 0;
905
+ const now = Date.now();
906
+ if (halfLife > 0) {
907
+ for (let i = 0; i < cleanTags.length; i += 100) {
908
+ await this.redisClient.eval(DECAYED_TAG_REVISION_LUA, {
909
+ keys: [
910
+ this.keys.learningUserTagCounts(episode.userId),
911
+ this.keys.learningUserTagRewards(episode.userId),
912
+ this.keys.learningUserTagRewardSq(episode.userId),
913
+ this.keys.learningUserTagTs(episode.userId),
914
+ ],
915
+ arguments: [
916
+ String(now),
917
+ String(halfLife),
918
+ String(episode.tagStatsAt ?? episode.timestamp),
919
+ String(previousReward),
920
+ String(revisedReward),
921
+ ...cleanTags.slice(i, i + 100),
922
+ ],
923
+ });
924
+ }
925
+ return;
926
+ }
927
+ const needVariance = this.needsVarianceTracking();
928
+ const multi = this.redisClient.multi();
929
+ for (const tag of cleanTags) {
930
+ multi.hIncrByFloat(this.keys.learningUserTagRewards(episode.userId), tag, revisedReward - previousReward);
931
+ if (needVariance) {
932
+ multi.hIncrByFloat(this.keys.learningUserTagRewardSq(episode.userId), tag, revisedReward * revisedReward - previousReward * previousReward);
933
+ }
934
+ }
935
+ await multi.exec();
936
+ }
937
+ /**
938
+ * True when the configured policy needs reward variance and per-tag
939
+ * write timestamps. A veto cooldown counts: without a last-observation
940
+ * timestamp there is no way to tell that a veto has gone stale, so the
941
+ * cooldown would silently never fire.
942
+ */
295
943
  needsVarianceTracking() {
296
944
  const policy = this.autoWeights.policy;
297
- return policy === 'confidence' || policy === 'thompson' || (this.autoWeights.decayHalfLifeMs ?? 0) > 0;
945
+ return (policy === 'confidence' ||
946
+ policy === 'thompson' ||
947
+ (this.autoWeights.decayHalfLifeMs ?? 0) > 0 ||
948
+ this.autoWeights.vetoCooldownMs !== undefined);
298
949
  }
299
950
  /** Per-user, per-tag reward statistics aggregated from observed outcomes */
300
951
  async getUserTagStats(userId) {
301
952
  const needVariance = this.needsVarianceTracking();
302
- const [counts, rewards, sq, ts] = await Promise.all([
953
+ const [counts, rewards, sq, ts, w2, attempts] = await Promise.all([
303
954
  this.redisClient.hGetAll(this.keys.learningUserTagCounts(userId)),
304
955
  this.redisClient.hGetAll(this.keys.learningUserTagRewards(userId)),
305
956
  needVariance ? this.redisClient.hGetAll(this.keys.learningUserTagRewardSq(userId)) : Promise.resolve({}),
306
957
  needVariance ? this.redisClient.hGetAll(this.keys.learningUserTagTs(userId)) : Promise.resolve({}),
958
+ needVariance ? this.redisClient.hGetAll(this.keys.learningUserTagWeightSq(userId)) : Promise.resolve({}),
959
+ this.redisClient.hGetAll(this.keys.learningUserTagAttempts(userId)),
307
960
  ]);
308
961
  const halfLife = this.autoWeights.decayHalfLifeMs;
309
962
  const now = Date.now();
@@ -311,7 +964,9 @@ class LearningManager {
311
964
  let count = Number(rawCount) || 0;
312
965
  let rewardSum = Number(rewards[tag]) || 0;
313
966
  let rewardSqSum = needVariance ? Number(sq[tag]) || 0 : undefined;
314
- let lastUpdatedAt = needVariance ? Number(ts[tag]) || undefined : undefined;
967
+ let sumWeightsSq = needVariance ? Number(w2[tag]) || 0 : undefined;
968
+ const lastUpdatedAt = needVariance ? Number(ts[tag]) || undefined : undefined;
969
+ const attemptCount = Number(attempts[tag]) || undefined;
315
970
  if (halfLife && halfLife > 0 && lastUpdatedAt) {
316
971
  const elapsed = now - lastUpdatedAt;
317
972
  const factor = Math.pow(2, -elapsed / halfLife);
@@ -319,17 +974,27 @@ class LearningManager {
319
974
  rewardSum *= factor;
320
975
  if (rewardSqSum !== undefined)
321
976
  rewardSqSum *= factor;
977
+ // Squared weights decay by the square of the factor.
978
+ if (sumWeightsSq !== undefined)
979
+ sumWeightsSq *= factor * factor;
322
980
  }
323
981
  const meanReward = count > 0 ? rewardSum / count : 0;
982
+ // Kish effective sample size. Without decay every weight is 1 and
983
+ // this reduces to the count; with decay it is strictly smaller,
984
+ // which is the number evidence thresholds must be judged against.
985
+ const effectiveSampleSize = sumWeightsSq && sumWeightsSq > 0 ? (count * count) / sumWeightsSq : needVariance ? count : count;
324
986
  let variance;
325
987
  let standardError;
326
988
  if (needVariance && rewardSqSum !== undefined && count > 0) {
327
989
  variance = Math.max(0, rewardSqSum / count - meanReward * meanReward);
328
- standardError = Math.sqrt(variance / count);
990
+ standardError = Math.sqrt(variance / Math.max(1e-9, effectiveSampleSize));
329
991
  }
330
992
  return {
331
993
  tag,
332
994
  count,
995
+ effectiveSampleSize,
996
+ sumWeightsSq,
997
+ attempts: attemptCount,
333
998
  rewardSum,
334
999
  meanReward,
335
1000
  rewardSqSum,
@@ -353,38 +1018,211 @@ class LearningManager {
353
1018
  * instead of the flat `priorWeight`.
354
1019
  */
355
1020
  async getLearnedRoutingWeights(userId, knownTags, existingWeights) {
356
- const stats = await this.getUserTagStats(userId);
1021
+ const rows = await this.explainLearnedRoutingWeights(userId, knownTags, existingWeights);
1022
+ const weights = {};
1023
+ for (const row of rows)
1024
+ weights[row.tag] = row.weight;
1025
+ return weights;
1026
+ }
1027
+ /** Independent attempts observed for a worker, counted once per attempt. */
1028
+ async getUserAttemptTotal(userId) {
1029
+ const raw = await this.redisClient.get(this.keys.learningUserAttempts(userId));
1030
+ const value = Number(raw);
1031
+ return Number.isFinite(value) && value > 0 ? value : undefined;
1032
+ }
1033
+ /**
1034
+ * The same synthesis with its reasoning attached — estimate, uncertainty,
1035
+ * evidence, last observation and next reassessment per tag.
1036
+ */
1037
+ async explainLearnedRoutingWeights(userId, knownTags, existingWeights) {
1038
+ const [stats, totalAttempts] = await Promise.all([this.getUserTagStats(userId), this.getUserAttemptTotal(userId)]);
357
1039
  if (stats.length === 0 && (!knownTags || knownTags.length === 0))
358
- return {};
359
- return (0, auto_weights_1.synthesizeRoutingWeights)(stats, this.autoWeights, knownTags, existingWeights);
1040
+ return [];
1041
+ return (0, auto_weights_1.explainRoutingWeights)(stats, { ...this.autoWeights, totalAttempts }, knownTags, existingWeights);
1042
+ }
1043
+ // ------------------------------------------------------------------
1044
+ // Worker performance aggregates (batch-loaded features)
1045
+ // ------------------------------------------------------------------
1046
+ /**
1047
+ * Fold one lifecycle outcome into the per-worker and team aggregates the
1048
+ * performance features read. Pure counters — no per-candidate reads ever
1049
+ * happen against these; a matching pass loads one hash per worker.
1050
+ */
1051
+ async updatePerformance(userId, tags, outcome, appliedEvents) {
1052
+ const cleanTags = (tags ?? []).filter(Boolean);
1053
+ const accepted = appliedEvents.includes('outcome:accept');
1054
+ const fields = [];
1055
+ if (outcome === 'accept')
1056
+ fields.push(['offers', 1], ['accepts', 1]);
1057
+ else if (outcome === 'reject')
1058
+ fields.push(['offers', 1]);
1059
+ else if (outcome === 'expire' && !accepted)
1060
+ fields.push(['offers', 1]);
1061
+ else if (outcome === 'complete')
1062
+ fields.push(['accepted', 1], ['successes', 1]);
1063
+ else if (outcome === 'fail')
1064
+ fields.push(['accepted', 1]);
1065
+ else if (outcome === 'expire' && accepted)
1066
+ fields.push(['accepted', 1]);
1067
+ if (fields.length === 0)
1068
+ return;
1069
+ const userKey = this.keys.learningUserPerformance(userId);
1070
+ const teamKey = this.keys.learningTeamPerformance();
1071
+ const multi = this.redisClient.multi();
1072
+ for (const [field, amount] of fields) {
1073
+ multi.hIncrBy(userKey, field, amount);
1074
+ multi.hIncrBy(teamKey, field, amount);
1075
+ for (const tag of cleanTags) {
1076
+ multi.hIncrBy(userKey, `${field}:${tag}`, amount);
1077
+ multi.hIncrBy(teamKey, `${field}:${tag}`, amount);
1078
+ }
1079
+ }
1080
+ await multi.exec();
1081
+ }
1082
+ /** Record an observed handling time (accept -> complete) for a worker */
1083
+ async recordHandlingTime(userId, tags, durationMs) {
1084
+ if (!this.trackPerformance || !Number.isFinite(durationMs) || durationMs < 0)
1085
+ return;
1086
+ const cleanTags = (tags ?? []).filter(Boolean);
1087
+ const userKey = this.keys.learningUserPerformance(userId);
1088
+ const teamKey = this.keys.learningTeamPerformance();
1089
+ const multi = this.redisClient.multi();
1090
+ multi.hIncrByFloat(userKey, 'handleMs', durationMs);
1091
+ multi.hIncrBy(userKey, 'handleN', 1);
1092
+ multi.hIncrByFloat(teamKey, 'handleMs', durationMs);
1093
+ multi.hIncrBy(teamKey, 'handleN', 1);
1094
+ for (const tag of cleanTags) {
1095
+ multi.hIncrByFloat(userKey, `handleMs:${tag}`, durationMs);
1096
+ multi.hIncrBy(userKey, `handleN:${tag}`, 1);
1097
+ multi.hIncrByFloat(teamKey, `handleMs:${tag}`, durationMs);
1098
+ multi.hIncrBy(teamKey, `handleN:${tag}`, 1);
1099
+ }
1100
+ await multi.exec();
1101
+ }
1102
+ /** Team-wide priors the per-worker rates are shrunk toward */
1103
+ async loadTeamPriors() {
1104
+ const raw = (await this.redisClient.hGetAll(this.keys.learningTeamPerformance()));
1105
+ const num = (field) => Number(raw[field]) || 0;
1106
+ const offers = num('offers');
1107
+ const acceptedTotal = num('accepted');
1108
+ const handleN = num('handleN');
1109
+ return {
1110
+ acceptanceRate: offers > 0 ? num('accepts') / offers : undefined,
1111
+ successRate: acceptedTotal > 0 ? num('successes') / acceptedTotal : undefined,
1112
+ handlingTimeMs: handleN > 0 ? num('handleMs') / handleN : undefined,
1113
+ };
1114
+ }
1115
+ /**
1116
+ * Load one worker's performance aggregates and shrink them toward the
1117
+ * team priors. A worker with no history gets the prior, not zero — an
1118
+ * unjustifiably pessimistic estimate is how a new worker starves.
1119
+ */
1120
+ async loadPerformance(userId, priors) {
1121
+ const raw = (await this.redisClient.hGetAll(this.keys.learningUserPerformance(userId)));
1122
+ return this.shrinkPerformance(raw, priors);
1123
+ }
1124
+ /** Pure shrinkage of a raw aggregate hash toward team priors. */
1125
+ shrinkPerformance(raw, priors) {
1126
+ const k = this.performancePriorStrength;
1127
+ const num = (field) => Number(raw[field]) || 0;
1128
+ const tagsOf = (prefix) => Object.keys(raw)
1129
+ .filter((f) => f.startsWith(`${prefix}:`))
1130
+ .map((f) => f.slice(prefix.length + 1));
1131
+ const shrink = (successes, trials, prior) => {
1132
+ if (prior === undefined && trials === 0)
1133
+ return undefined;
1134
+ const p = prior ?? 0.5;
1135
+ return (successes + k * p) / (trials + k);
1136
+ };
1137
+ const acceptanceRate = {};
1138
+ const attempts = {};
1139
+ for (const tag of new Set([...tagsOf('offers'), ...tagsOf('accepts')])) {
1140
+ const trials = num(`offers:${tag}`);
1141
+ attempts[tag] = trials;
1142
+ const value = shrink(num(`accepts:${tag}`), trials, priors.acceptanceRate);
1143
+ if (value !== undefined)
1144
+ acceptanceRate[tag] = value;
1145
+ }
1146
+ const successRate = {};
1147
+ for (const tag of new Set([...tagsOf('accepted'), ...tagsOf('successes')])) {
1148
+ const value = shrink(num(`successes:${tag}`), num(`accepted:${tag}`), priors.successRate);
1149
+ if (value !== undefined)
1150
+ successRate[tag] = value;
1151
+ }
1152
+ const handlingTimeMs = {};
1153
+ for (const tag of tagsOf('handleN')) {
1154
+ const n = num(`handleN:${tag}`);
1155
+ if (n > 0)
1156
+ handlingTimeMs[tag] = num(`handleMs:${tag}`) / n;
1157
+ }
1158
+ return {
1159
+ acceptanceRate,
1160
+ overallAcceptanceRate: shrink(num('accepts'), num('offers'), priors.acceptanceRate),
1161
+ successRate,
1162
+ overallSuccessRate: shrink(num('successes'), num('accepted'), priors.successRate),
1163
+ handlingTimeMs,
1164
+ attempts,
1165
+ };
1166
+ }
1167
+ // ------------------------------------------------------------------
1168
+ // Stats & lifecycle
1169
+ // ------------------------------------------------------------------
1170
+ async bumpStat(field) {
1171
+ await this.redisClient.hIncrBy(this.keys.learningStats(), field, 1);
360
1172
  }
361
1173
  /** Aggregate learning statistics */
362
1174
  async getStats() {
363
- const raw = await this.redisClient.hGetAll(this.keys.learningStats());
364
- const decisions = Number(raw.decisions) || 0;
365
- const rewards = Number(raw.rewards) || 0;
366
- const totalReward = Number(raw.totalReward) || 0;
1175
+ const [raw, generation] = await Promise.all([
1176
+ this.redisClient.hGetAll(this.keys.learningStats()),
1177
+ this.currentGeneration(),
1178
+ ]);
1179
+ const hash = raw;
1180
+ const rewards = Number(hash.rewards) || 0;
1181
+ const totalReward = Number(hash.totalReward) || 0;
367
1182
  return {
368
- decisions,
1183
+ decisions: Number(hash.decisions) || 0,
369
1184
  rewards,
370
1185
  totalReward,
371
1186
  averageReward: rewards > 0 ? totalReward / rewards : 0,
1187
+ duplicateEvents: Number(hash.duplicateEvents) || 0,
1188
+ staleEvents: Number(hash.staleEvents) || 0,
1189
+ orphanEvents: Number(hash.orphanEvents) || 0,
1190
+ supersededEvents: Number(hash.supersededEvents) || 0,
1191
+ ambiguousFeedback: Number(hash.ambiguousFeedback) || 0,
1192
+ invalidFeedback: Number(hash.invalidFeedback) || 0,
1193
+ generation,
372
1194
  };
373
1195
  }
374
- /** Reset model weights, statistics, and per-user tag statistics */
1196
+ /**
1197
+ * Reset model weights, statistics, and per-user tag statistics.
1198
+ *
1199
+ * The generation counter is bumped rather than cleared: attempts that are
1200
+ * still in flight were committed against the old model, and applying
1201
+ * their outcomes to the fresh one would silently repopulate what was just
1202
+ * reset. Those events are rejected and counted as `supersededEvents`.
1203
+ */
375
1204
  async resetModel() {
376
1205
  const trackedUsers = await this.listTrackedUsers();
377
1206
  const multi = this.redisClient.multi();
378
1207
  multi.del(this.keys.learningModel());
1208
+ for (const target of this.activeTargets)
1209
+ multi.del(this.keys.learningTargetModel(target));
379
1210
  multi.del(this.keys.learningStats());
380
1211
  for (const userId of trackedUsers) {
381
1212
  multi.del(this.keys.learningUserTagCounts(userId));
382
1213
  multi.del(this.keys.learningUserTagRewards(userId));
383
1214
  multi.del(this.keys.learningUserTagRewardSq(userId));
384
1215
  multi.del(this.keys.learningUserTagTs(userId));
1216
+ multi.del(this.keys.learningUserTagWeightSq(userId));
1217
+ multi.del(this.keys.learningUserTagAttempts(userId));
1218
+ multi.del(this.keys.learningUserAttempts(userId));
1219
+ multi.del(this.keys.learningUserPerformance(userId));
385
1220
  }
1221
+ multi.del(this.keys.learningTeamPerformance());
386
1222
  multi.del(this.keys.learningUsers());
1223
+ multi.incr(this.keys.learningGeneration());
387
1224
  await multi.exec();
1225
+ this.generationCache = undefined;
388
1226
  }
389
1227
  }
390
1228
  exports.LearningManager = LearningManager;