@memberjunction/predictive-studio 0.0.1 → 5.44.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.
Files changed (266) hide show
  1. package/README.md +101 -28
  2. package/dist/actions/base-predictive-studio.action.d.ts +63 -0
  3. package/dist/actions/base-predictive-studio.action.d.ts.map +1 -0
  4. package/dist/actions/base-predictive-studio.action.js +125 -0
  5. package/dist/actions/base-predictive-studio.action.js.map +1 -0
  6. package/dist/actions/index.d.ts +38 -0
  7. package/dist/actions/index.d.ts.map +1 -0
  8. package/dist/actions/index.js +49 -0
  9. package/dist/actions/index.js.map +1 -0
  10. package/dist/actions/model-scoring-action-generator.d.ts +108 -0
  11. package/dist/actions/model-scoring-action-generator.d.ts.map +1 -0
  12. package/dist/actions/model-scoring-action-generator.js +316 -0
  13. package/dist/actions/model-scoring-action-generator.js.map +1 -0
  14. package/dist/actions/promote-model.action.d.ts +102 -0
  15. package/dist/actions/promote-model.action.d.ts.map +1 -0
  16. package/dist/actions/promote-model.action.js +132 -0
  17. package/dist/actions/promote-model.action.js.map +1 -0
  18. package/dist/actions/promote-model.gate.d.ts +77 -0
  19. package/dist/actions/promote-model.gate.d.ts.map +1 -0
  20. package/dist/actions/promote-model.gate.js +205 -0
  21. package/dist/actions/promote-model.gate.js.map +1 -0
  22. package/dist/actions/run-experiment.action.d.ts +60 -0
  23. package/dist/actions/run-experiment.action.d.ts.map +1 -0
  24. package/dist/actions/run-experiment.action.js +134 -0
  25. package/dist/actions/run-experiment.action.js.map +1 -0
  26. package/dist/actions/run-experiment.deps.d.ts +47 -0
  27. package/dist/actions/run-experiment.deps.d.ts.map +1 -0
  28. package/dist/actions/run-experiment.deps.js +71 -0
  29. package/dist/actions/run-experiment.deps.js.map +1 -0
  30. package/dist/actions/schedule-model-scoring.action.d.ts +71 -0
  31. package/dist/actions/schedule-model-scoring.action.d.ts.map +1 -0
  32. package/dist/actions/schedule-model-scoring.action.js +148 -0
  33. package/dist/actions/schedule-model-scoring.action.js.map +1 -0
  34. package/dist/actions/score-record-set.action.d.ts +133 -0
  35. package/dist/actions/score-record-set.action.d.ts.map +1 -0
  36. package/dist/actions/score-record-set.action.js +136 -0
  37. package/dist/actions/score-record-set.action.js.map +1 -0
  38. package/dist/actions/score-record-set.runner.d.ts +192 -0
  39. package/dist/actions/score-record-set.runner.d.ts.map +1 -0
  40. package/dist/actions/score-record-set.runner.js +416 -0
  41. package/dist/actions/score-record-set.runner.js.map +1 -0
  42. package/dist/actions/train-model.action.d.ts +57 -0
  43. package/dist/actions/train-model.action.d.ts.map +1 -0
  44. package/dist/actions/train-model.action.js +111 -0
  45. package/dist/actions/train-model.action.js.map +1 -0
  46. package/dist/agent/index.d.ts +14 -0
  47. package/dist/agent/index.d.ts.map +1 -0
  48. package/dist/agent/index.js +14 -0
  49. package/dist/agent/index.js.map +1 -0
  50. package/dist/agent/model-dev-orchestrator-agent.d.ts +42 -0
  51. package/dist/agent/model-dev-orchestrator-agent.d.ts.map +1 -0
  52. package/dist/agent/model-dev-orchestrator-agent.js +76 -0
  53. package/dist/agent/model-dev-orchestrator-agent.js.map +1 -0
  54. package/dist/agent/modeling-plan-to-pipeline.d.ts +49 -0
  55. package/dist/agent/modeling-plan-to-pipeline.d.ts.map +1 -0
  56. package/dist/agent/modeling-plan-to-pipeline.js +101 -0
  57. package/dist/agent/modeling-plan-to-pipeline.js.map +1 -0
  58. package/dist/agent/pipeline-builder-agent.d.ts +58 -0
  59. package/dist/agent/pipeline-builder-agent.d.ts.map +1 -0
  60. package/dist/agent/pipeline-builder-agent.js +101 -0
  61. package/dist/agent/pipeline-builder-agent.js.map +1 -0
  62. package/dist/agent/pipeline-builder.d.ts +67 -0
  63. package/dist/agent/pipeline-builder.d.ts.map +1 -0
  64. package/dist/agent/pipeline-builder.js +114 -0
  65. package/dist/agent/pipeline-builder.js.map +1 -0
  66. package/dist/experiment/concurrency.d.ts +41 -0
  67. package/dist/experiment/concurrency.d.ts.map +1 -0
  68. package/dist/experiment/concurrency.js +54 -0
  69. package/dist/experiment/concurrency.js.map +1 -0
  70. package/dist/experiment/experiment-orchestrator.d.ts +136 -0
  71. package/dist/experiment/experiment-orchestrator.d.ts.map +1 -0
  72. package/dist/experiment/experiment-orchestrator.js +408 -0
  73. package/dist/experiment/experiment-orchestrator.js.map +1 -0
  74. package/dist/experiment/index.d.ts +17 -0
  75. package/dist/experiment/index.d.ts.map +1 -0
  76. package/dist/experiment/index.js +17 -0
  77. package/dist/experiment/index.js.map +1 -0
  78. package/dist/experiment/leaderboard.d.ts +50 -0
  79. package/dist/experiment/leaderboard.d.ts.map +1 -0
  80. package/dist/experiment/leaderboard.js +91 -0
  81. package/dist/experiment/leaderboard.js.map +1 -0
  82. package/dist/experiment/seams.d.ts +95 -0
  83. package/dist/experiment/seams.d.ts.map +1 -0
  84. package/dist/experiment/seams.js +126 -0
  85. package/dist/experiment/seams.js.map +1 -0
  86. package/dist/experiment/types.d.ts +228 -0
  87. package/dist/experiment/types.d.ts.map +1 -0
  88. package/dist/experiment/types.js +19 -0
  89. package/dist/experiment/types.js.map +1 -0
  90. package/dist/experiment/wave-strategist.d.ts +31 -0
  91. package/dist/experiment/wave-strategist.d.ts.map +1 -0
  92. package/dist/experiment/wave-strategist.js +50 -0
  93. package/dist/experiment/wave-strategist.js.map +1 -0
  94. package/dist/feature-assembly/as-of.d.ts +74 -0
  95. package/dist/feature-assembly/as-of.d.ts.map +1 -0
  96. package/dist/feature-assembly/as-of.js +136 -0
  97. package/dist/feature-assembly/as-of.js.map +1 -0
  98. package/dist/feature-assembly/data-access.d.ts +114 -0
  99. package/dist/feature-assembly/data-access.d.ts.map +1 -0
  100. package/dist/feature-assembly/data-access.js +68 -0
  101. package/dist/feature-assembly/data-access.js.map +1 -0
  102. package/dist/feature-assembly/feature-assembly-executor.d.ts +273 -0
  103. package/dist/feature-assembly/feature-assembly-executor.d.ts.map +1 -0
  104. package/dist/feature-assembly/feature-assembly-executor.js +521 -0
  105. package/dist/feature-assembly/feature-assembly-executor.js.map +1 -0
  106. package/dist/feature-assembly/index.d.ts +13 -0
  107. package/dist/feature-assembly/index.d.ts.map +1 -0
  108. package/dist/feature-assembly/index.js +13 -0
  109. package/dist/feature-assembly/index.js.map +1 -0
  110. package/dist/feature-assembly/leakage-guard.d.ts +86 -0
  111. package/dist/feature-assembly/leakage-guard.d.ts.map +1 -0
  112. package/dist/feature-assembly/leakage-guard.js +111 -0
  113. package/dist/feature-assembly/leakage-guard.js.map +1 -0
  114. package/dist/feature-assembly/vision-llm.d.ts +125 -0
  115. package/dist/feature-assembly/vision-llm.d.ts.map +1 -0
  116. package/dist/feature-assembly/vision-llm.js +211 -0
  117. package/dist/feature-assembly/vision-llm.js.map +1 -0
  118. package/dist/feature-pipelines/feature-pipeline-engine.d.ts +159 -0
  119. package/dist/feature-pipelines/feature-pipeline-engine.d.ts.map +1 -0
  120. package/dist/feature-pipelines/feature-pipeline-engine.js +298 -0
  121. package/dist/feature-pipelines/feature-pipeline-engine.js.map +1 -0
  122. package/dist/feature-pipelines/index.d.ts +13 -0
  123. package/dist/feature-pipelines/index.d.ts.map +1 -0
  124. package/dist/feature-pipelines/index.js +13 -0
  125. package/dist/feature-pipelines/index.js.map +1 -0
  126. package/dist/feature-pipelines/types.d.ts +72 -0
  127. package/dist/feature-pipelines/types.d.ts.map +1 -0
  128. package/dist/feature-pipelines/types.js +17 -0
  129. package/dist/feature-pipelines/types.js.map +1 -0
  130. package/dist/index.d.ts +37 -0
  131. package/dist/index.d.ts.map +1 -0
  132. package/dist/index.js +80 -0
  133. package/dist/index.js.map +1 -0
  134. package/dist/maintenance/index.d.ts +19 -0
  135. package/dist/maintenance/index.d.ts.map +1 -0
  136. package/dist/maintenance/index.js +19 -0
  137. package/dist/maintenance/index.js.map +1 -0
  138. package/dist/maintenance/maintenance-engine.d.ts +152 -0
  139. package/dist/maintenance/maintenance-engine.d.ts.map +1 -0
  140. package/dist/maintenance/maintenance-engine.js +412 -0
  141. package/dist/maintenance/maintenance-engine.js.map +1 -0
  142. package/dist/maintenance/metrics.d.ts +37 -0
  143. package/dist/maintenance/metrics.d.ts.map +1 -0
  144. package/dist/maintenance/metrics.js +85 -0
  145. package/dist/maintenance/metrics.js.map +1 -0
  146. package/dist/maintenance/seams.d.ts +85 -0
  147. package/dist/maintenance/seams.d.ts.map +1 -0
  148. package/dist/maintenance/seams.js +166 -0
  149. package/dist/maintenance/seams.js.map +1 -0
  150. package/dist/maintenance/types.d.ts +318 -0
  151. package/dist/maintenance/types.d.ts.map +1 -0
  152. package/dist/maintenance/types.js +27 -0
  153. package/dist/maintenance/types.js.map +1 -0
  154. package/dist/operations/__tests__/helpers.d.ts +30 -0
  155. package/dist/operations/__tests__/helpers.d.ts.map +1 -0
  156. package/dist/operations/__tests__/helpers.js +44 -0
  157. package/dist/operations/__tests__/helpers.js.map +1 -0
  158. package/dist/operations/control-experiment-session.operation.d.ts +33 -0
  159. package/dist/operations/control-experiment-session.operation.d.ts.map +1 -0
  160. package/dist/operations/control-experiment-session.operation.js +71 -0
  161. package/dist/operations/control-experiment-session.operation.js.map +1 -0
  162. package/dist/operations/create-scoring-process.operation.d.ts +30 -0
  163. package/dist/operations/create-scoring-process.operation.d.ts.map +1 -0
  164. package/dist/operations/create-scoring-process.operation.js +65 -0
  165. package/dist/operations/create-scoring-process.operation.js.map +1 -0
  166. package/dist/operations/delegation.d.ts +113 -0
  167. package/dist/operations/delegation.d.ts.map +1 -0
  168. package/dist/operations/delegation.js +139 -0
  169. package/dist/operations/delegation.js.map +1 -0
  170. package/dist/operations/index.d.ts +40 -0
  171. package/dist/operations/index.d.ts.map +1 -0
  172. package/dist/operations/index.js +55 -0
  173. package/dist/operations/index.js.map +1 -0
  174. package/dist/operations/promote-model.operation.d.ts +57 -0
  175. package/dist/operations/promote-model.operation.d.ts.map +1 -0
  176. package/dist/operations/promote-model.operation.js +113 -0
  177. package/dist/operations/promote-model.operation.js.map +1 -0
  178. package/dist/operations/run-feature-pipeline.operation.d.ts +56 -0
  179. package/dist/operations/run-feature-pipeline.operation.d.ts.map +1 -0
  180. package/dist/operations/run-feature-pipeline.operation.js +94 -0
  181. package/dist/operations/run-feature-pipeline.operation.js.map +1 -0
  182. package/dist/operations/score-record-set.operation.d.ts +47 -0
  183. package/dist/operations/score-record-set.operation.d.ts.map +1 -0
  184. package/dist/operations/score-record-set.operation.js +113 -0
  185. package/dist/operations/score-record-set.operation.js.map +1 -0
  186. package/dist/operations/start-experiment-session.operation.d.ts +66 -0
  187. package/dist/operations/start-experiment-session.operation.d.ts.map +1 -0
  188. package/dist/operations/start-experiment-session.operation.js +132 -0
  189. package/dist/operations/start-experiment-session.operation.js.map +1 -0
  190. package/dist/operations/train-model.operation.d.ts +50 -0
  191. package/dist/operations/train-model.operation.d.ts.map +1 -0
  192. package/dist/operations/train-model.operation.js +114 -0
  193. package/dist/operations/train-model.operation.js.map +1 -0
  194. package/dist/scheduling/index.d.ts +13 -0
  195. package/dist/scheduling/index.d.ts.map +1 -0
  196. package/dist/scheduling/index.js +13 -0
  197. package/dist/scheduling/index.js.map +1 -0
  198. package/dist/scheduling/scheduled-model-scoring.d.ts +169 -0
  199. package/dist/scheduling/scheduled-model-scoring.d.ts.map +1 -0
  200. package/dist/scheduling/scheduled-model-scoring.js +189 -0
  201. package/dist/scheduling/scheduled-model-scoring.js.map +1 -0
  202. package/dist/scoring/artifact-loader.d.ts +65 -0
  203. package/dist/scoring/artifact-loader.d.ts.map +1 -0
  204. package/dist/scoring/artifact-loader.js +97 -0
  205. package/dist/scoring/artifact-loader.js.map +1 -0
  206. package/dist/scoring/index.d.ts +26 -0
  207. package/dist/scoring/index.d.ts.map +1 -0
  208. package/dist/scoring/index.js +26 -0
  209. package/dist/scoring/index.js.map +1 -0
  210. package/dist/scoring/ml-model-inference-processor.d.ts +154 -0
  211. package/dist/scoring/ml-model-inference-processor.d.ts.map +1 -0
  212. package/dist/scoring/ml-model-inference-processor.js +320 -0
  213. package/dist/scoring/ml-model-inference-processor.js.map +1 -0
  214. package/dist/scoring/ml-model-score-enricher.d.ts +80 -0
  215. package/dist/scoring/ml-model-score-enricher.d.ts.map +1 -0
  216. package/dist/scoring/ml-model-score-enricher.js +139 -0
  217. package/dist/scoring/ml-model-score-enricher.js.map +1 -0
  218. package/dist/scoring/register.d.ts +81 -0
  219. package/dist/scoring/register.d.ts.map +1 -0
  220. package/dist/scoring/register.js +105 -0
  221. package/dist/scoring/register.js.map +1 -0
  222. package/dist/scoring/scoring-binding.d.ts +72 -0
  223. package/dist/scoring/scoring-binding.d.ts.map +1 -0
  224. package/dist/scoring/scoring-binding.js +76 -0
  225. package/dist/scoring/scoring-binding.js.map +1 -0
  226. package/dist/scoring/scoring-process-shared.d.ts +105 -0
  227. package/dist/scoring/scoring-process-shared.d.ts.map +1 -0
  228. package/dist/scoring/scoring-process-shared.js +141 -0
  229. package/dist/scoring/scoring-process-shared.js.map +1 -0
  230. package/dist/scoring/scoring-process.d.ts +128 -0
  231. package/dist/scoring/scoring-process.d.ts.map +1 -0
  232. package/dist/scoring/scoring-process.js +146 -0
  233. package/dist/scoring/scoring-process.js.map +1 -0
  234. package/dist/scoring/seams.d.ts +40 -0
  235. package/dist/scoring/seams.d.ts.map +1 -0
  236. package/dist/scoring/seams.js +66 -0
  237. package/dist/scoring/seams.js.map +1 -0
  238. package/dist/scoring/startup-register.d.ts +49 -0
  239. package/dist/scoring/startup-register.d.ts.map +1 -0
  240. package/dist/scoring/startup-register.js +72 -0
  241. package/dist/scoring/startup-register.js.map +1 -0
  242. package/dist/scoring/types.d.ts +134 -0
  243. package/dist/scoring/types.d.ts.map +1 -0
  244. package/dist/scoring/types.js +26 -0
  245. package/dist/scoring/types.js.map +1 -0
  246. package/dist/training/artifact-store.d.ts +124 -0
  247. package/dist/training/artifact-store.d.ts.map +1 -0
  248. package/dist/training/artifact-store.js +163 -0
  249. package/dist/training/artifact-store.js.map +1 -0
  250. package/dist/training/index.d.ts +13 -0
  251. package/dist/training/index.d.ts.map +1 -0
  252. package/dist/training/index.js +13 -0
  253. package/dist/training/index.js.map +1 -0
  254. package/dist/training/seams.d.ts +57 -0
  255. package/dist/training/seams.d.ts.map +1 -0
  256. package/dist/training/seams.js +103 -0
  257. package/dist/training/seams.js.map +1 -0
  258. package/dist/training/training-engine.d.ts +96 -0
  259. package/dist/training/training-engine.d.ts.map +1 -0
  260. package/dist/training/training-engine.js +300 -0
  261. package/dist/training/training-engine.js.map +1 -0
  262. package/dist/training/types.d.ts +159 -0
  263. package/dist/training/types.d.ts.map +1 -0
  264. package/dist/training/types.js +16 -0
  265. package/dist/training/types.js.map +1 -0
  266. package/package.json +44 -7
@@ -0,0 +1,189 @@
1
+ /**
2
+ * @module scheduling/scheduled-model-scoring
3
+ *
4
+ * **Scheduled model scoring** (plan PS2-6 — the north-star enabler). A one-call way
5
+ * to bind a trained `MJ: ML Models` to write its prediction into a target entity
6
+ * column on a recurring schedule (e.g. monthly): "build a model, write the renewal
7
+ * probability back into the member record, and re-score it on the 1st of every
8
+ * month." This is the helper the Model Dev Agent fulfils that goal with.
9
+ *
10
+ * ## How it works (composition, no new substrate)
11
+ * Everything underneath already exists; this helper just assembles a single
12
+ * `MJ: Record Processes` row that the existing machinery picks up:
13
+ *
14
+ * 1. {@link createScheduledModelScoring} creates + saves a Record Process with
15
+ * `WorkType='ML Model'` (the runtime-registered scoring work type, PS2-1),
16
+ * a `Configuration` of `{ modelId, primaryKeyField }`, an `OutputMapping` of
17
+ * `{ fields: { <outputField>: '$.score' } }` (write the prediction into a
18
+ * column), and `ScheduleEnabled=true` + a cron expression for the cadence.
19
+ * 2. Saving that row with `Status='Active'` + `ScheduleEnabled=true` + a
20
+ * `CronExpression` auto-creates an owned `MJ: Scheduled Jobs` row (via
21
+ * `MJRecordProcessEntityServer.Save → reconcileScheduledJob`).
22
+ * 3. `SchedulingEngine` dispatches that job on its cron through
23
+ * `RecordProcessScheduledJobDriver → RecordProcessExecutor.RunByID(...)`,
24
+ * which resolves the scope, scores each row with the model, and writes the
25
+ * prediction back per the `OutputMapping`.
26
+ * 4. AFTER the Record Process is saved, this helper also creates a
27
+ * `MJ: ML Model Scoring Bindings` row (`Mode='Scheduled'`) tying the model to
28
+ * that Record Process + target entity/column. The binding is the **lineage
29
+ * record** the new UX surfaces read — the model-prediction form panel and the
30
+ * "Models in Production" dashboard both list operationalized models from these
31
+ * binding rows — so without it the scheduled scoring would run but be invisible.
32
+ *
33
+ * So binding a model to a recurring write-back is a single create-and-save (plus a
34
+ * lineage binding) — no new scheduling, dispatch, or write-back code. This module
35
+ * only validates inputs, maps a cadence to a cron string, populates that one Record
36
+ * Process row, and records the binding for it.
37
+ *
38
+ * The shape + field-population primitives (scope model, value-kind → result-ref,
39
+ * `Configuration` / `OutputMapping` serialization, scope application, validation,
40
+ * entity resolution, lineage-binding creation) are shared with the on-demand sibling
41
+ * ({@link module:scoring/scoring-process}) in {@link module:scoring/scoring-process-shared};
42
+ * this module composes them and owns only the schedule-specific bits (cadence → cron).
43
+ *
44
+ * The `'ML Model'` `WorkType` is a runtime-registered extension (PS2-1) that the
45
+ * CodeGen'd `WorkType` value-list union (`'Action' | 'Agent' | 'FieldRules' |
46
+ * 'Infer'`) cannot represent, so it is set via `rp.Set('WorkType', 'ML Model')` —
47
+ * the same legitimate, documented exception PS2-1's scoring path uses.
48
+ */
49
+ import { Metadata } from '@memberjunction/core';
50
+ import { ML_MODEL_WORK_TYPE, applyScope, modelConfiguration, writeBackOutputMapping, createScoringBinding, countScopeSelectors, resolveTargetEntityID, isNonEmpty, } from '../scoring/scoring-process-shared.js';
51
+ /**
52
+ * The cron expression each named {@link ScoringCadence} maps to.
53
+ * - `Monthly` → `0 0 1 * *` (00:00 on the 1st of every month)
54
+ * - `Weekly` → `0 0 * * 0` (00:00 every Sunday)
55
+ * - `Daily` → `0 0 * * *` (00:00 every day)
56
+ */
57
+ export const CADENCE_CRON = {
58
+ Monthly: '0 0 1 * *',
59
+ Weekly: '0 0 * * 0',
60
+ Daily: '0 0 * * *',
61
+ };
62
+ /** The helper name used to prefix this module's errors + binding-failure logs. */
63
+ const HELPER_NAME = 'createScheduledModelScoring';
64
+ /**
65
+ * Create and save a scheduled Record Process that scores `targetEntity`'s rows with
66
+ * `modelId` on a recurring cadence. Operates in one of two modes, driven by whether
67
+ * `opts.outputField` is supplied:
68
+ *
69
+ * - **Write-back** (`outputField` present): each run writes the prediction into that
70
+ * target column (via the Record Process `OutputMapping`), AND this helper records a
71
+ * `MJ: ML Model Scoring Bindings` lineage row (`Mode='Scheduled'`) tying the model →
72
+ * Record Process → target entity/column so the operationalized model is discoverable
73
+ * by the UX surfaces that read those bindings. `result.binding` is the saved row.
74
+ * - **Generic** (`outputField` omitted): no `OutputMapping` is set and no binding is
75
+ * created — each run's predictions are recorded in the process run history
76
+ * (`MJ: Process Run Details`) only. `result.binding` is `null`.
77
+ *
78
+ * In both modes, saving the Record Process auto-creates its owned `MJ: Scheduled Jobs`
79
+ * row (so the run is live on the schedule immediately).
80
+ *
81
+ * @param opts the model + target + scope + cadence (see {@link ScheduleModelScoringOptions})
82
+ * @returns the saved Record Process AND — in write-back mode — its scoring binding
83
+ * (`null` in generic mode); see {@link ScheduledModelScoringResult}
84
+ * @throws if a required input is missing, the scope is not exactly one selector, the
85
+ * target entity is unknown, the Record Process fails to save, or — in write-back mode,
86
+ * after the Record Process was saved — the binding fails to save (the message carries
87
+ * the cause). The binding save is intentionally fail-loud (not swallowed): a saved RP
88
+ * without a binding would run invisibly to the lineage UX, so we surface the inconsistency.
89
+ */
90
+ export async function createScheduledModelScoring(opts) {
91
+ validateOptions(opts);
92
+ const provider = opts.provider ?? Metadata.Provider;
93
+ const entityID = resolveTargetEntityID(opts.targetEntityName, provider, HELPER_NAME);
94
+ const cron = cadenceToCron(opts.cadence);
95
+ const rp = await provider.GetEntityObject('MJ: Record Processes', opts.contextUser);
96
+ rp.NewRecord();
97
+ applyRecordProcessFields(rp, opts, entityID, cron);
98
+ if (!(await rp.Save())) {
99
+ throw new Error(`${HELPER_NAME}: failed to save Record Process for model '${opts.modelId}': ` +
100
+ `${rp.LatestResult?.CompleteMessage ?? 'unknown error'}`);
101
+ }
102
+ // Lineage binding only in write-back mode — generic output has no column to bind.
103
+ const binding = isNonEmpty(opts.outputField)
104
+ ? await createScoringBinding(opts.modelId, opts.outputField, rp.ID, entityID, 'Scheduled', provider, opts.contextUser, HELPER_NAME)
105
+ : null;
106
+ return { recordProcess: rp, binding };
107
+ }
108
+ // ----- field population --------------------------------------------------------
109
+ /**
110
+ * Populate the Record Process row from the (validated) options — the single place
111
+ * the scheduled-scoring contract is encoded onto the entity. Sets the lifecycle +
112
+ * work-type, the scope, the model `Configuration`, the schedule (cron + timezone),
113
+ * and enables on-demand runs too.
114
+ *
115
+ * The write-back `OutputMapping` is set ONLY in write-back mode (`opts.outputField`
116
+ * present). In generic mode it is left unset, so each run records its predictions in
117
+ * the process run history (`MJ: Process Run Details`) only — there is no target column.
118
+ */
119
+ function applyRecordProcessFields(rp, opts, entityID, cron) {
120
+ rp.Name = opts.name ?? defaultName(opts, cron);
121
+ rp.EntityID = entityID;
122
+ rp.Status = 'Active';
123
+ // 'ML Model' is the runtime-registered scoring work-type (PS2-1); the generated
124
+ // WorkType union (`'Action' | 'Agent' | 'FieldRules' | 'Infer'`) can't represent
125
+ // it, so Set() is the legitimate, documented exception (same as PS2-1's path).
126
+ rp.Set('WorkType', ML_MODEL_WORK_TYPE);
127
+ applyScope(rp, opts.scope);
128
+ rp.Configuration = modelConfiguration(opts.modelId, opts.primaryKeyField);
129
+ // Write-back mode only: map the prediction into the target column. Generic mode
130
+ // (no outputField) leaves OutputMapping unset — predictions land in run history only.
131
+ if (isNonEmpty(opts.outputField)) {
132
+ rp.OutputMapping = writeBackOutputMapping(opts.outputField, opts.valueKind);
133
+ }
134
+ rp.ScheduleEnabled = true;
135
+ rp.CronExpression = cron;
136
+ rp.Timezone = opts.timezone ?? 'UTC';
137
+ rp.OnDemandEnabled = true;
138
+ }
139
+ // ----- cadence + naming --------------------------------------------------------
140
+ /**
141
+ * Map a {@link ScoringCadence} to its cron expression. Named cadences resolve via
142
+ * {@link CADENCE_CRON}; an explicit `{ cron }` is passed through (trimmed). Defaults
143
+ * to `'Monthly'` when no cadence is supplied.
144
+ */
145
+ export function cadenceToCron(cadence) {
146
+ if (cadence == null) {
147
+ return CADENCE_CRON.Monthly;
148
+ }
149
+ if (typeof cadence === 'object') {
150
+ const cron = cadence.cron?.trim();
151
+ if (!cron) {
152
+ throw new Error(`${HELPER_NAME}: an explicit cadence must supply a non-empty \`cron\` expression.`);
153
+ }
154
+ return cron;
155
+ }
156
+ return CADENCE_CRON[cadence];
157
+ }
158
+ /**
159
+ * A descriptive default Record Process name. The base shape never implies a column —
160
+ * `Score <entity> with model <id> (<cadence>)` — which is exactly right for generic
161
+ * mode (no `outputField`). In write-back mode the target column is appended so the
162
+ * name records where the prediction lands (e.g.
163
+ * `Score Memberships with model <id> → RenewalScore (Monthly)`).
164
+ */
165
+ function defaultName(opts, cron) {
166
+ const label = typeof opts.cadence === 'object' || opts.cadence == null
167
+ ? (opts.cadence == null ? 'Monthly' : `cron ${cron}`)
168
+ : opts.cadence;
169
+ const writeBack = isNonEmpty(opts.outputField) ? ` → ${opts.outputField}` : '';
170
+ return `Score ${opts.targetEntityName} with model ${opts.modelId}${writeBack} (${label})`;
171
+ }
172
+ // ----- validation --------------------------------------------------------------
173
+ /**
174
+ * Validate the required inputs + exactly-one-scope rule, throwing a clear error on the
175
+ * first problem. `outputField` is NOT required — omitting it selects generic output
176
+ * (predictions recorded in run history only; see {@link createScheduledModelScoring}).
177
+ */
178
+ function validateOptions(opts) {
179
+ if (!isNonEmpty(opts.modelId)) {
180
+ throw new Error(`${HELPER_NAME}: \`modelId\` is required.`);
181
+ }
182
+ if (!isNonEmpty(opts.targetEntityName)) {
183
+ throw new Error(`${HELPER_NAME}: \`targetEntityName\` is required.`);
184
+ }
185
+ if (countScopeSelectors(opts.scope) !== 1) {
186
+ throw new Error(`${HELPER_NAME}: \`scope\` must populate exactly one of: filter, viewId, listId, all.`);
187
+ }
188
+ }
189
+ //# sourceMappingURL=scheduled-model-scoring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduled-model-scoring.js","sourceRoot":"","sources":["../../src/scheduling/scheduled-model-scoring.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,OAAO,EAAyC,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEvF,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,EACrB,UAAU,GAGX,MAAM,mCAAmC,CAAC;AA+D3C;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAA6D;IACpF,OAAO,EAAE,WAAW;IACpB,MAAM,EAAE,WAAW;IACnB,KAAK,EAAE,WAAW;CACnB,CAAC;AAEF,kFAAkF;AAClF,MAAM,WAAW,GAAG,6BAA6B,CAAC;AAuBlD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,IAAiC;IAEjC,eAAe,CAAC,IAAI,CAAC,CAAC;IAEtB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAC;IACpD,MAAM,QAAQ,GAAG,qBAAqB,CAAC,IAAI,CAAC,gBAAgB,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;IACrF,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAEzC,MAAM,EAAE,GAAG,MAAM,QAAQ,CAAC,eAAe,CAAwB,sBAAsB,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC3G,EAAE,CAAC,SAAS,EAAE,CAAC;IACf,wBAAwB,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,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AAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/E,OAAO,SAAS,IAAI,CAAC,gBAAgB,eAAe,IAAI,CAAC,OAAO,GAAG,SAAS,KAAK,KAAK,GAAG,CAAC;AAC5F,CAAC;AAED,kFAAkF;AAElF;;;;GAIG;AACH,SAAS,eAAe,CAAC,IAAiC;IACxD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,4BAA4B,CAAC,CAAC;IAC9D,CAAC;IACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACvC,MAAM,IAAI,KAAK,CAAC,GAAG,WAAW,qCAAqC,CAAC,CAAC;IACvE,CAAC;IACD,IAAI,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,KAAK,CACb,GAAG,WAAW,wEAAwE,CACvF,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @module scoring/artifact-loader
3
+ *
4
+ * Implementations of the {@link IArtifactLoader} seam (plan §11) — the read-side
5
+ * counterpart to the training `IArtifactStore`. The serialized model artifact is
6
+ * kept out of the `MJ: ML Models` row and referenced by file id; this module
7
+ * provides:
8
+ *
9
+ * - {@link InMemoryArtifactLoader} — for unit tests (no DB, no MJStorage), which
10
+ * can also bridge a training-time `InMemoryArtifactStore.Saved` map so a model
11
+ * trained in-memory can be scored in-memory in the same test.
12
+ * - {@link LocalArtifactLoader} — the read-side inverse of `MJFilesArtifactStore`.
13
+ * The fileId is the real `MJ: Files` row id and the bytes live on local disk at
14
+ * `<baseDir>/<fileId>.bin` (dev / on-prem); this reads that path and returns its
15
+ * bytes, or `null` when absent. **Production follow-up**: a provider `GetObject`
16
+ * keyed by the File id replaces the local `readFile`.
17
+ */
18
+ import { type UserInfo } from '@memberjunction/core';
19
+ import type { IArtifactLoader } from './types.js';
20
+ /**
21
+ * In-memory {@link IArtifactLoader} for unit tests. Holds artifact bytes keyed by
22
+ * file id and returns them on {@link load}. No database, no MJStorage.
23
+ *
24
+ * Bridges the training-side `InMemoryArtifactStore`: pass its `Saved` map (keyed
25
+ * by the returned file id, with `{ Bytes }`) so a model trained in-memory is
26
+ * directly loadable for scoring in the same test.
27
+ */
28
+ export declare class InMemoryArtifactLoader implements IArtifactLoader {
29
+ private readonly store;
30
+ /**
31
+ * @param initial optional seed: either a plain `fileId → bytes` map, or a
32
+ * training `InMemoryArtifactStore.Saved`-shaped map (`fileId → { Bytes }`).
33
+ */
34
+ constructor(initial?: Map<string, Uint8Array> | Map<string, {
35
+ Bytes: Uint8Array;
36
+ }>);
37
+ /** Register artifact bytes under a file id (test setup convenience). */
38
+ set(fileId: string, bytes: Uint8Array): void;
39
+ /** @inheritdoc */
40
+ load(fileId: string, _contextUser?: UserInfo): Promise<Uint8Array | null>;
41
+ }
42
+ /**
43
+ * The single production {@link IArtifactLoader} — the read-side inverse of
44
+ * {@link MJFilesArtifactStore}. Given a fileId (= the real `MJ: Files` row id the
45
+ * artifact was stored under), it reads the bytes from local disk at
46
+ * `<baseDir>/<fileId>.bin` and returns them, or `null` when the file is absent.
47
+ *
48
+ * A missing file is a normal, expected `null` (the model has no persisted artifact);
49
+ * only a genuine I/O failure (permissions, corruption) is logged.
50
+ *
51
+ * **NOT for multi-host production** — it can only read paths on the machine the
52
+ * artifact was written to. **Production follow-up**: replace the local `readFile`
53
+ * with a provider `GetObject` keyed by the File id; the id contract is unchanged.
54
+ */
55
+ export declare class LocalArtifactLoader implements IArtifactLoader {
56
+ private readonly baseDir;
57
+ /**
58
+ * @param baseDir optional base-directory override (defaults to
59
+ * {@link resolveLocalArtifactBaseDir}); must match the store's base dir
60
+ */
61
+ constructor(baseDir?: string);
62
+ /** @inheritdoc */
63
+ load(fileId: string, _contextUser?: UserInfo): Promise<Uint8Array | null>;
64
+ }
65
+ //# sourceMappingURL=artifact-loader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"artifact-loader.d.ts","sourceRoot":"","sources":["../../src/scoring/artifact-loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAG/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C;;;;;;;GAOG;AACH,qBAAa,sBAAuB,YAAW,eAAe;IAC5D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0B;IAEhD;;;OAGG;gBACS,OAAO,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,UAAU,CAAA;KAAE,CAAC;IASlF,wEAAwE;IACjE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,IAAI;IAInD,kBAAkB;IACL,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAGvF;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,mBAAoB,YAAW,eAAe;IACzD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC;;;OAGG;gBACS,OAAO,GAAE,MAAsC;IAI3D,kBAAkB;IACL,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAevF"}
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @module scoring/artifact-loader
3
+ *
4
+ * Implementations of the {@link IArtifactLoader} seam (plan §11) — the read-side
5
+ * counterpart to the training `IArtifactStore`. The serialized model artifact is
6
+ * kept out of the `MJ: ML Models` row and referenced by file id; this module
7
+ * provides:
8
+ *
9
+ * - {@link InMemoryArtifactLoader} — for unit tests (no DB, no MJStorage), which
10
+ * can also bridge a training-time `InMemoryArtifactStore.Saved` map so a model
11
+ * trained in-memory can be scored in-memory in the same test.
12
+ * - {@link LocalArtifactLoader} — the read-side inverse of `MJFilesArtifactStore`.
13
+ * The fileId is the real `MJ: Files` row id and the bytes live on local disk at
14
+ * `<baseDir>/<fileId>.bin` (dev / on-prem); this reads that path and returns its
15
+ * bytes, or `null` when absent. **Production follow-up**: a provider `GetObject`
16
+ * keyed by the File id replaces the local `readFile`.
17
+ */
18
+ import { readFile } from 'node:fs/promises';
19
+ import { LogError } from '@memberjunction/core';
20
+ import { resolveLocalArtifactBaseDir, localArtifactPath } from '../training/artifact-store.js';
21
+ /**
22
+ * In-memory {@link IArtifactLoader} for unit tests. Holds artifact bytes keyed by
23
+ * file id and returns them on {@link load}. No database, no MJStorage.
24
+ *
25
+ * Bridges the training-side `InMemoryArtifactStore`: pass its `Saved` map (keyed
26
+ * by the returned file id, with `{ Bytes }`) so a model trained in-memory is
27
+ * directly loadable for scoring in the same test.
28
+ */
29
+ export class InMemoryArtifactLoader {
30
+ /**
31
+ * @param initial optional seed: either a plain `fileId → bytes` map, or a
32
+ * training `InMemoryArtifactStore.Saved`-shaped map (`fileId → { Bytes }`).
33
+ */
34
+ constructor(initial) {
35
+ this.store = new Map();
36
+ if (initial) {
37
+ for (const [id, value] of initial.entries()) {
38
+ this.store.set(id, value instanceof Uint8Array ? value : value.Bytes);
39
+ }
40
+ }
41
+ }
42
+ /** Register artifact bytes under a file id (test setup convenience). */
43
+ set(fileId, bytes) {
44
+ this.store.set(fileId, bytes);
45
+ }
46
+ /** @inheritdoc */
47
+ async load(fileId, _contextUser) {
48
+ return this.store.get(fileId) ?? null;
49
+ }
50
+ }
51
+ /**
52
+ * The single production {@link IArtifactLoader} — the read-side inverse of
53
+ * {@link MJFilesArtifactStore}. Given a fileId (= the real `MJ: Files` row id the
54
+ * artifact was stored under), it reads the bytes from local disk at
55
+ * `<baseDir>/<fileId>.bin` and returns them, or `null` when the file is absent.
56
+ *
57
+ * A missing file is a normal, expected `null` (the model has no persisted artifact);
58
+ * only a genuine I/O failure (permissions, corruption) is logged.
59
+ *
60
+ * **NOT for multi-host production** — it can only read paths on the machine the
61
+ * artifact was written to. **Production follow-up**: replace the local `readFile`
62
+ * with a provider `GetObject` keyed by the File id; the id contract is unchanged.
63
+ */
64
+ export class LocalArtifactLoader {
65
+ /**
66
+ * @param baseDir optional base-directory override (defaults to
67
+ * {@link resolveLocalArtifactBaseDir}); must match the store's base dir
68
+ */
69
+ constructor(baseDir = resolveLocalArtifactBaseDir()) {
70
+ this.baseDir = baseDir;
71
+ }
72
+ /** @inheritdoc */
73
+ async load(fileId, _contextUser) {
74
+ const absolutePath = localArtifactPath(this.baseDir, fileId);
75
+ try {
76
+ const buffer = await readFile(absolutePath);
77
+ return new Uint8Array(buffer);
78
+ }
79
+ catch (error) {
80
+ // ENOENT is the expected "no persisted artifact" signal — return null quietly.
81
+ // Log only real I/O failures.
82
+ if (!isFileNotFoundError(error)) {
83
+ const message = error instanceof Error ? error.message : String(error);
84
+ LogError(`LocalArtifactLoader: failed to read artifact at '${absolutePath}': ${message}`);
85
+ }
86
+ return null;
87
+ }
88
+ }
89
+ }
90
+ /** Whether a caught error is a Node "file not found" (`ENOENT`) error. */
91
+ function isFileNotFoundError(error) {
92
+ return (typeof error === 'object' &&
93
+ error !== null &&
94
+ 'code' in error &&
95
+ error.code === 'ENOENT');
96
+ }
97
+ //# sourceMappingURL=artifact-loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"artifact-loader.js","sourceRoot":"","sources":["../../src/scoring/artifact-loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAiB,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,MAAM,4BAA4B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B,IAAI,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC;gBAChC,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACvE,QAAQ,CAAC,oDAAoD,YAAY,MAAM,OAAO,EAAE,CAAC,CAAC;YAC5F,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAED,0EAA0E;AAC1E,SAAS,mBAAmB,CAAC,KAAc;IACzC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACd,KAA4B,CAAC,IAAI,KAAK,QAAQ,CAChD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @module scoring
3
+ *
4
+ * Barrel for the Predictive Studio **scoring** layer (plan §10) — the
5
+ * {@link MLModelInferenceProcessor} Record Set Processing work type, its
6
+ * dependency-injection seams (model loader, artifact loader, sidecar predictor)
7
+ * and their production + in-memory implementations, the work-type registration +
8
+ * dynamic resolver, the startup sink that registers it at boot, the
9
+ * `MJ: ML Model Scoring Binding` lineage helper, and the scored-query enricher that
10
+ * lets RunQuery append model predictions to result rows (PS2-3). Also the on-demand
11
+ * `createScoringProcess` builder (the "Operate this model" flow) — the sibling of the
12
+ * scheduled helper that assembles an on-demand `WorkType='ML Model'` Record Process the
13
+ * generic run-now / scheduler dialog then targets.
14
+ *
15
+ * See `./ml-model-inference-processor` for the per-record scoring flow.
16
+ */
17
+ export * from './types.js';
18
+ export * from './artifact-loader.js';
19
+ export * from './seams.js';
20
+ export * from './ml-model-inference-processor.js';
21
+ export * from './register.js';
22
+ export * from './startup-register.js';
23
+ export * from './scoring-binding.js';
24
+ export * from './ml-model-score-enricher.js';
25
+ export * from './scoring-process.js';
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scoring/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,cAAc,SAAS,CAAC;AACxB,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,gCAAgC,CAAC;AAC/C,cAAc,YAAY,CAAC;AAC3B,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @module scoring
3
+ *
4
+ * Barrel for the Predictive Studio **scoring** layer (plan §10) — the
5
+ * {@link MLModelInferenceProcessor} Record Set Processing work type, its
6
+ * dependency-injection seams (model loader, artifact loader, sidecar predictor)
7
+ * and their production + in-memory implementations, the work-type registration +
8
+ * dynamic resolver, the startup sink that registers it at boot, the
9
+ * `MJ: ML Model Scoring Binding` lineage helper, and the scored-query enricher that
10
+ * lets RunQuery append model predictions to result rows (PS2-3). Also the on-demand
11
+ * `createScoringProcess` builder (the "Operate this model" flow) — the sibling of the
12
+ * scheduled helper that assembles an on-demand `WorkType='ML Model'` Record Process the
13
+ * generic run-now / scheduler dialog then targets.
14
+ *
15
+ * See `./ml-model-inference-processor` for the per-record scoring flow.
16
+ */
17
+ export * from './types.js';
18
+ export * from './artifact-loader.js';
19
+ export * from './seams.js';
20
+ export * from './ml-model-inference-processor.js';
21
+ export * from './register.js';
22
+ export * from './startup-register.js';
23
+ export * from './scoring-binding.js';
24
+ export * from './ml-model-score-enricher.js';
25
+ export * from './scoring-process.js';
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/scoring/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,cAAc,SAAS,CAAC;AACxB,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,gCAAgC,CAAC;AAC/C,cAAc,YAAY,CAAC;AAC3B,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,154 @@
1
+ /**
2
+ * @module scoring/ml-model-inference-processor
3
+ *
4
+ * The **MLModelInferenceProcessor** — Predictive Studio's **scoring** work type
5
+ * (plan §10). It is a Record Set Processing processor (implements
6
+ * `IRecordProcessor` from `@memberjunction/record-set-processor-base`, the same
7
+ * contract as the `InferProcessor` / `ActionRecordProcessor` /
8
+ * `AgentRecordProcessor` siblings) so it composes onto the existing batching /
9
+ * concurrency / rate-limit / budget / pause-resume / audit substrate.
10
+ *
11
+ * ## Per-record flow (single + batch)
12
+ * 1. **Resolve + warm-load the model** ({@link MLModelInferenceProcessor.ensureModel}).
13
+ * The `MJ: ML Models` row (its `ArtifactFileID`, `FittedPreprocessing`,
14
+ * `FeatureSchema`, `ProblemType`) + its pipeline assembly config are loaded
15
+ * **once per processor run** and reused across every record (the Python
16
+ * sidecar also warm-caches by model id — §3.1). The serialized artifact is
17
+ * fetched once via the injected {@link IArtifactLoader}.
18
+ * 2. **Assemble features** via the SAME {@link FeatureAssemblyExecutor} as
19
+ * training, in the **on-demand / transform-only** context, using the model's
20
+ * FROZEN `FeatureSchema` + `FittedPreprocessing` (never re-fit — the anti-skew
21
+ * guarantee, §6.2). The matrix shape matches what the model expects.
22
+ * 3. **Call the sidecar `/predict`** with the artifact + frozen preprocessing +
23
+ * feature schema + the assembled row(s) → predictions (score + class).
24
+ * 4. **Produce the per-record `RecordResult`** carrying the prediction.
25
+ * **Ephemeral by default**; when the Record Process has an `OutputMapping`,
26
+ * `RecordProcessExecutor` wraps this processor in the shared `WriteBackProcessor`
27
+ * (exactly as it does for the Action/Agent/Infer siblings) so the score lands
28
+ * as a sortable/filterable column or child record. The write-back is NOT done
29
+ * here — keeping it in the wrapper is how all work types share one declarative
30
+ * write-back.
31
+ *
32
+ * ## Registration (work-type key)
33
+ * Registered on the MJGlobal ClassFactory via
34
+ * `@RegisterClass(MLModelInferenceProcessor, 'ML Model')` (alias `'MLModelInference'`
35
+ * via {@link registerMLInferenceWorkType}). This establishes the clear work-type
36
+ * key and a static code path the bundler cannot tree-shake — WITHOUT modifying
37
+ * the `record-set-processor` substrate (its base package must not depend on
38
+ * Predictive Studio). A future `RecordProcessExecutor` extension resolves this
39
+ * processor dynamically by work-type key via {@link resolveMLInferenceProcessor}.
40
+ */
41
+ import type { IRecordProcessor, RecordProcessorContext, RecordRef, RecordResult } from '@memberjunction/record-set-processor-base';
42
+ import type { FeatureSchemaEntry, ProblemType, MatrixData } from '@memberjunction/predictive-studio-core';
43
+ import { FeatureAssemblyExecutor } from '../feature-assembly/index.js';
44
+ import type { MLModelInferenceProcessorOptions } from './types.js';
45
+ /** Stable work-type keys this processor is registered under on the ClassFactory. */
46
+ export declare const ML_INFERENCE_WORK_TYPE = "ML Model";
47
+ /** Alias work-type key (no spaces) for callers that prefer an identifier-style key. */
48
+ export declare const ML_INFERENCE_WORK_TYPE_ALIAS = "MLModelInference";
49
+ /**
50
+ * Record Set Processing **scoring** processor. Stateless across records except
51
+ * for a warm, lazily-loaded model cache (artifact + frozen contract) shared
52
+ * across a batch. Construct one per Record Process run.
53
+ */
54
+ export declare class MLModelInferenceProcessor implements IRecordProcessor {
55
+ private readonly modelId;
56
+ private readonly deps;
57
+ private readonly primaryKeyField;
58
+ private readonly datedSources?;
59
+ private readonly assembler;
60
+ /** Warm model cache — loaded once on first record, reused across the batch. */
61
+ private loadedModel;
62
+ /** Memoized in-flight load so concurrent records don't double-load the artifact. */
63
+ private loadPromise;
64
+ /**
65
+ * @param options model id + injected seams (+ optional pk field / dated sources)
66
+ * @param assembler optional FeatureAssembly executor override (tests may inject one)
67
+ */
68
+ constructor(options: MLModelInferenceProcessorOptions, assembler?: FeatureAssemblyExecutor);
69
+ /**
70
+ * Score one record. Warm-loads the model on first call, assembles the single
71
+ * record's features (transform-only), calls the sidecar, and returns the
72
+ * prediction as the record's `ResultPayload`. Write-back, if configured, is
73
+ * applied by the `WriteBackProcessor` wrapper — not here.
74
+ *
75
+ * @param record the record to score
76
+ * @param context the per-record execution context (user + provider)
77
+ */
78
+ ProcessRecord(record: RecordRef, context: RecordProcessorContext): Promise<RecordResult>;
79
+ /**
80
+ * Batch-score many records in one sidecar round-trip. The warm model is loaded
81
+ * once; features for all rows are assembled together (transform-only), then a
82
+ * single `/predict` carries every row. Returns one {@link RecordResult} per
83
+ * input record, positionally aligned. Useful for bulk / materialization paths;
84
+ * the per-record `WriteBackProcessor` wrapper still owns write-back when the
85
+ * engine drives records individually.
86
+ *
87
+ * @param records the records to score (each must carry/resolve a row of data)
88
+ * @param context the execution context (user + provider)
89
+ */
90
+ ProcessBatch(records: RecordRef[], context: RecordProcessorContext): Promise<RecordResult[]>;
91
+ /**
92
+ * Load the model + artifact ONCE and cache it for the run (§3.1 warm cache).
93
+ * Concurrent records share a single in-flight load via {@link loadPromise} so
94
+ * the artifact is fetched exactly once even under bounded concurrency.
95
+ */
96
+ private ensureModel;
97
+ /** Resolve the `MJ: ML Models` row + its frozen contract + the artifact bytes. */
98
+ private loadModel;
99
+ /** Assemble the frozen inference contract from a loaded model row + artifact bytes. */
100
+ private buildLoadedModel;
101
+ /**
102
+ * Resolve the assembly config (sources / steps / as-of / leakage / target
103
+ * entity) the model's features were built from. Read off the loaded model's
104
+ * `Pipeline` relationship when present; otherwise fall back to the model's own
105
+ * frozen lineage so scoring stays self-contained even without the pipeline row.
106
+ */
107
+ private resolvePipelineConfig;
108
+ /**
109
+ * Assemble the raw feature matrix for the given rows via the shared
110
+ * FeatureAssembly executor in the **on-demand / transform-only** context (§6.1).
111
+ * The model's frozen schema is the contract; preprocessing is NOT applied here
112
+ * (the sidecar applies the frozen `FittedPreprocessing`).
113
+ */
114
+ private assembleFeatures;
115
+ /**
116
+ * Build the `/predict` request from the model's frozen contract + the assembled
117
+ * matrix and call the sidecar. The matrix's row-arrays are mapped to the
118
+ * feature-name → value objects `/predict` expects, using the MODEL's frozen
119
+ * feature schema order (the inference input contract).
120
+ */
121
+ private callSidecar;
122
+ /** Shape a single sidecar prediction into the record result payload. */
123
+ private toPayload;
124
+ /** Extract a plain field map from the record (BaseEntity → GetAll(), plain object → as-is). */
125
+ private recordToPlain;
126
+ }
127
+ /** The structured payload a successful scoring run carries on its `RecordResult`. */
128
+ export interface MLInferenceResultPayload {
129
+ /** The model that produced the prediction (lineage). */
130
+ modelId: string;
131
+ /** The target/label the model predicts. */
132
+ target: string;
133
+ /** Classification or regression. */
134
+ problemType: ProblemType;
135
+ /** Numeric model output: probability (classification) or value (regression). */
136
+ score: number;
137
+ /** Predicted class label, present for classification problems. */
138
+ class?: string;
139
+ /**
140
+ * ISO-8601 UTC timestamp of when this prediction was produced. Lets write-back persist a
141
+ * dedicated "last scored at" column on the target entity via `OutputMapping`
142
+ * (`{ "LastScoredAt": "$.scoredAt" }`) — distinct from the row's whole-record `__mj_UpdatedAt`,
143
+ * which moves on any edit, not just scoring.
144
+ */
145
+ scoredAt: string;
146
+ }
147
+ /**
148
+ * Map a row-major {@link MatrixData} into the feature-name → value objects the
149
+ * sidecar `/predict` expects, in the model's FROZEN feature-schema order. Columns
150
+ * present in the matrix but not in the schema are dropped; schema columns missing
151
+ * from the matrix are emitted as `null` (the sidecar imputes via fitted params).
152
+ */
153
+ export declare function matrixToFeatureRows(matrix: MatrixData, featureSchema: FeatureSchemaEntry[]): Array<Record<string, string | number | boolean | null>>;
154
+ //# sourceMappingURL=ml-model-inference-processor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ml-model-inference-processor.d.ts","sourceRoot":"","sources":["../../src/scoring/ml-model-inference-processor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAIH,OAAO,KAAK,EACV,gBAAgB,EAChB,sBAAsB,EACtB,SAAS,EACT,YA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