@memberjunction/predictive-studio 6.2.1 → 6.3.0-edge.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 (390) hide show
  1. package/README.md +16 -11
  2. package/dist/actions/base-predictive-studio.action.d.ts +7 -0
  3. package/dist/actions/base-predictive-studio.action.d.ts.map +1 -1
  4. package/dist/actions/base-predictive-studio.action.js +22 -0
  5. package/dist/actions/base-predictive-studio.action.js.map +1 -1
  6. package/dist/actions/driver-classes.d.ts +2 -0
  7. package/dist/actions/driver-classes.d.ts.map +1 -1
  8. package/dist/actions/driver-classes.js +2 -0
  9. package/dist/actions/driver-classes.js.map +1 -1
  10. package/dist/actions/evaluate-drift.action.d.ts +100 -0
  11. package/dist/actions/evaluate-drift.action.d.ts.map +1 -0
  12. package/dist/actions/evaluate-drift.action.js +512 -0
  13. package/dist/actions/evaluate-drift.action.js.map +1 -0
  14. package/dist/actions/index.d.ts +3 -0
  15. package/dist/actions/index.d.ts.map +1 -1
  16. package/dist/actions/index.js +7 -0
  17. package/dist/actions/index.js.map +1 -1
  18. package/dist/actions/migrate-pipelines.action.d.ts +19 -0
  19. package/dist/actions/migrate-pipelines.action.d.ts.map +1 -0
  20. package/dist/actions/migrate-pipelines.action.js +51 -0
  21. package/dist/actions/migrate-pipelines.action.js.map +1 -0
  22. package/dist/actions/promote-model.action.d.ts +12 -1
  23. package/dist/actions/promote-model.action.d.ts.map +1 -1
  24. package/dist/actions/promote-model.action.js +7 -2
  25. package/dist/actions/promote-model.action.js.map +1 -1
  26. package/dist/actions/promote-model.gate.d.ts +31 -2
  27. package/dist/actions/promote-model.gate.d.ts.map +1 -1
  28. package/dist/actions/promote-model.gate.js +84 -5
  29. package/dist/actions/promote-model.gate.js.map +1 -1
  30. package/dist/actions/run-experiment.action.d.ts.map +1 -1
  31. package/dist/actions/run-experiment.action.js +5 -4
  32. package/dist/actions/run-experiment.action.js.map +1 -1
  33. package/dist/actions/schedule-model-scoring.action.js +2 -2
  34. package/dist/actions/schedule-model-scoring.action.js.map +1 -1
  35. package/dist/actions/score-record-set.action.js +1 -1
  36. package/dist/actions/score-record-set.action.js.map +1 -1
  37. package/dist/actions/score-record-set.runner.d.ts +2 -2
  38. package/dist/actions/score-record-set.runner.js +3 -3
  39. package/dist/actions/score-record-set.runner.js.map +1 -1
  40. package/dist/actions/train-model.action.d.ts +28 -25
  41. package/dist/actions/train-model.action.d.ts.map +1 -1
  42. package/dist/actions/train-model.action.js +50 -39
  43. package/dist/actions/train-model.action.js.map +1 -1
  44. package/dist/agent/index.d.ts +1 -1
  45. package/dist/agent/index.js +1 -1
  46. package/dist/agent/modeling-plan-to-pipeline.d.ts +0 -2
  47. package/dist/agent/modeling-plan-to-pipeline.d.ts.map +1 -1
  48. package/dist/agent/modeling-plan-to-pipeline.js +30 -39
  49. package/dist/agent/modeling-plan-to-pipeline.js.map +1 -1
  50. package/dist/agent/pipeline-builder-agent.d.ts +47 -18
  51. package/dist/agent/pipeline-builder-agent.d.ts.map +1 -1
  52. package/dist/agent/pipeline-builder-agent.js +161 -92
  53. package/dist/agent/pipeline-builder-agent.js.map +1 -1
  54. package/dist/agent/pipeline-builder.d.ts +178 -56
  55. package/dist/agent/pipeline-builder.d.ts.map +1 -1
  56. package/dist/agent/pipeline-builder.js +333 -234
  57. package/dist/agent/pipeline-builder.js.map +1 -1
  58. package/dist/experiment/budget.d.ts +61 -0
  59. package/dist/experiment/budget.d.ts.map +1 -0
  60. package/dist/experiment/budget.js +72 -0
  61. package/dist/experiment/budget.js.map +1 -0
  62. package/dist/experiment/experiment-orchestrator.d.ts +43 -7
  63. package/dist/experiment/experiment-orchestrator.d.ts.map +1 -1
  64. package/dist/experiment/experiment-orchestrator.js +130 -33
  65. package/dist/experiment/experiment-orchestrator.js.map +1 -1
  66. package/dist/experiment/index.d.ts +2 -0
  67. package/dist/experiment/index.d.ts.map +1 -1
  68. package/dist/experiment/index.js +2 -0
  69. package/dist/experiment/index.js.map +1 -1
  70. package/dist/experiment/leaderboard.d.ts +15 -15
  71. package/dist/experiment/leaderboard.d.ts.map +1 -1
  72. package/dist/experiment/leaderboard.js +44 -18
  73. package/dist/experiment/leaderboard.js.map +1 -1
  74. package/dist/experiment/scores.d.ts +32 -0
  75. package/dist/experiment/scores.d.ts.map +1 -0
  76. package/dist/experiment/scores.js +62 -0
  77. package/dist/experiment/scores.js.map +1 -0
  78. package/dist/experiment/seams.d.ts +23 -20
  79. package/dist/experiment/seams.d.ts.map +1 -1
  80. package/dist/experiment/seams.js +54 -56
  81. package/dist/experiment/seams.js.map +1 -1
  82. package/dist/experiment/types.d.ts +55 -10
  83. package/dist/experiment/types.d.ts.map +1 -1
  84. package/dist/experiment/types.js.map +1 -1
  85. package/dist/feature-assembly/as-of/as-of-assembler.d.ts +412 -0
  86. package/dist/feature-assembly/as-of/as-of-assembler.d.ts.map +1 -0
  87. package/dist/feature-assembly/as-of/as-of-assembler.js +1239 -0
  88. package/dist/feature-assembly/as-of/as-of-assembler.js.map +1 -0
  89. package/dist/feature-assembly/as-of/feature-resolution.d.ts +84 -0
  90. package/dist/feature-assembly/as-of/feature-resolution.d.ts.map +1 -0
  91. package/dist/feature-assembly/as-of/feature-resolution.js +229 -0
  92. package/dist/feature-assembly/as-of/feature-resolution.js.map +1 -0
  93. package/dist/feature-assembly/as-of/index.d.ts +15 -0
  94. package/dist/feature-assembly/as-of/index.d.ts.map +1 -0
  95. package/dist/feature-assembly/as-of/index.js +15 -0
  96. package/dist/feature-assembly/as-of/index.js.map +1 -0
  97. package/dist/feature-assembly/as-of/read-by-keys.d.ts +30 -0
  98. package/dist/feature-assembly/as-of/read-by-keys.d.ts.map +1 -0
  99. package/dist/feature-assembly/as-of/read-by-keys.js +51 -0
  100. package/dist/feature-assembly/as-of/read-by-keys.js.map +1 -0
  101. package/dist/feature-assembly/as-of/record-history.d.ts +256 -0
  102. package/dist/feature-assembly/as-of/record-history.d.ts.map +1 -0
  103. package/dist/feature-assembly/as-of/record-history.js +505 -0
  104. package/dist/feature-assembly/as-of/record-history.js.map +1 -0
  105. package/dist/feature-assembly/as-of/refusal.d.ts +19 -0
  106. package/dist/feature-assembly/as-of/refusal.d.ts.map +1 -0
  107. package/dist/feature-assembly/as-of/refusal.js +13 -0
  108. package/dist/feature-assembly/as-of/refusal.js.map +1 -0
  109. package/dist/feature-assembly/as-of/series-features.d.ts +65 -0
  110. package/dist/feature-assembly/as-of/series-features.d.ts.map +1 -0
  111. package/dist/feature-assembly/as-of/series-features.js +97 -0
  112. package/dist/feature-assembly/as-of/series-features.js.map +1 -0
  113. package/dist/feature-assembly/as-of/windowed-aggregate.d.ts +36 -0
  114. package/dist/feature-assembly/as-of/windowed-aggregate.d.ts.map +1 -0
  115. package/dist/feature-assembly/as-of/windowed-aggregate.js +99 -0
  116. package/dist/feature-assembly/as-of/windowed-aggregate.js.map +1 -0
  117. package/dist/feature-assembly/as-of.d.ts +1 -9
  118. package/dist/feature-assembly/as-of.d.ts.map +1 -1
  119. package/dist/feature-assembly/as-of.js +2 -19
  120. package/dist/feature-assembly/as-of.js.map +1 -1
  121. package/dist/feature-assembly/assembly-metadata.d.ts +34 -0
  122. package/dist/feature-assembly/assembly-metadata.d.ts.map +1 -0
  123. package/dist/feature-assembly/assembly-metadata.js +26 -0
  124. package/dist/feature-assembly/assembly-metadata.js.map +1 -0
  125. package/dist/feature-assembly/data-access.d.ts +21 -2
  126. package/dist/feature-assembly/data-access.d.ts.map +1 -1
  127. package/dist/feature-assembly/data-access.js +14 -0
  128. package/dist/feature-assembly/data-access.js.map +1 -1
  129. package/dist/feature-assembly/feature-assembly-executor.d.ts.map +1 -1
  130. package/dist/feature-assembly/feature-assembly-executor.js +5 -2
  131. package/dist/feature-assembly/feature-assembly-executor.js.map +1 -1
  132. package/dist/feature-assembly/index.d.ts +3 -0
  133. package/dist/feature-assembly/index.d.ts.map +1 -1
  134. package/dist/feature-assembly/index.js +3 -0
  135. package/dist/feature-assembly/index.js.map +1 -1
  136. package/dist/feature-assembly/leakage-guard.d.ts +1 -1
  137. package/dist/feature-assembly/leakage-guard.js +1 -1
  138. package/dist/feature-assembly/read-policy.d.ts +27 -0
  139. package/dist/feature-assembly/read-policy.d.ts.map +1 -0
  140. package/dist/feature-assembly/read-policy.js +63 -0
  141. package/dist/feature-assembly/read-policy.js.map +1 -0
  142. package/dist/feature-pipelines/feature-pipeline-engine.d.ts.map +1 -1
  143. package/dist/feature-pipelines/feature-pipeline-engine.js +3 -1
  144. package/dist/feature-pipelines/feature-pipeline-engine.js.map +1 -1
  145. package/dist/index.d.ts +5 -2
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +16 -4
  148. package/dist/index.js.map +1 -1
  149. package/dist/maintenance/index.d.ts +1 -0
  150. package/dist/maintenance/index.d.ts.map +1 -1
  151. package/dist/maintenance/index.js +1 -0
  152. package/dist/maintenance/index.js.map +1 -1
  153. package/dist/maintenance/maintenance-engine.d.ts +16 -19
  154. package/dist/maintenance/maintenance-engine.d.ts.map +1 -1
  155. package/dist/maintenance/maintenance-engine.js +53 -53
  156. package/dist/maintenance/maintenance-engine.js.map +1 -1
  157. package/dist/maintenance/metrics.d.ts +19 -15
  158. package/dist/maintenance/metrics.d.ts.map +1 -1
  159. package/dist/maintenance/metrics.js +29 -24
  160. package/dist/maintenance/metrics.js.map +1 -1
  161. package/dist/maintenance/psi-drift-detector.d.ts +246 -0
  162. package/dist/maintenance/psi-drift-detector.d.ts.map +1 -0
  163. package/dist/maintenance/psi-drift-detector.js +1002 -0
  164. package/dist/maintenance/psi-drift-detector.js.map +1 -0
  165. package/dist/maintenance/types.d.ts +11 -2
  166. package/dist/maintenance/types.d.ts.map +1 -1
  167. package/dist/maintenance/types.js.map +1 -1
  168. package/dist/migration/index.d.ts +8 -0
  169. package/dist/migration/index.d.ts.map +1 -0
  170. package/dist/migration/index.js +8 -0
  171. package/dist/migration/index.js.map +1 -0
  172. package/dist/migration/legacy-pipeline-migration.d.ts +138 -0
  173. package/dist/migration/legacy-pipeline-migration.d.ts.map +1 -0
  174. package/dist/migration/legacy-pipeline-migration.js +273 -0
  175. package/dist/migration/legacy-pipeline-migration.js.map +1 -0
  176. package/dist/operations/delegation.d.ts +58 -46
  177. package/dist/operations/delegation.d.ts.map +1 -1
  178. package/dist/operations/delegation.js +90 -77
  179. package/dist/operations/delegation.js.map +1 -1
  180. package/dist/operations/promote-model.operation.d.ts +2 -2
  181. package/dist/operations/promote-model.operation.d.ts.map +1 -1
  182. package/dist/operations/promote-model.operation.js +6 -2
  183. package/dist/operations/promote-model.operation.js.map +1 -1
  184. package/dist/operations/refusals.d.ts +5 -0
  185. package/dist/operations/refusals.d.ts.map +1 -1
  186. package/dist/operations/refusals.js +26 -1
  187. package/dist/operations/refusals.js.map +1 -1
  188. package/dist/operations/start-experiment-session.operation.js +3 -3
  189. package/dist/operations/train-model.mapping.d.ts +91 -0
  190. package/dist/operations/train-model.mapping.d.ts.map +1 -0
  191. package/dist/operations/train-model.mapping.js +145 -0
  192. package/dist/operations/train-model.mapping.js.map +1 -0
  193. package/dist/operations/train-model.operation.d.ts +14 -9
  194. package/dist/operations/train-model.operation.d.ts.map +1 -1
  195. package/dist/operations/train-model.operation.js +30 -51
  196. package/dist/operations/train-model.operation.js.map +1 -1
  197. package/dist/prediction-unit/decision-date-advance.d.ts +46 -0
  198. package/dist/prediction-unit/decision-date-advance.d.ts.map +1 -0
  199. package/dist/prediction-unit/decision-date-advance.js +79 -0
  200. package/dist/prediction-unit/decision-date-advance.js.map +1 -0
  201. package/dist/prediction-unit/index.d.ts +12 -0
  202. package/dist/prediction-unit/index.d.ts.map +1 -0
  203. package/dist/prediction-unit/index.js +12 -0
  204. package/dist/prediction-unit/index.js.map +1 -0
  205. package/dist/prediction-unit/target-validation.d.ts +21 -0
  206. package/dist/prediction-unit/target-validation.d.ts.map +1 -0
  207. package/dist/prediction-unit/target-validation.js +54 -0
  208. package/dist/prediction-unit/target-validation.js.map +1 -0
  209. package/dist/prediction-unit/unit-row-reader.d.ts +108 -0
  210. package/dist/prediction-unit/unit-row-reader.d.ts.map +1 -0
  211. package/dist/prediction-unit/unit-row-reader.js +348 -0
  212. package/dist/prediction-unit/unit-row-reader.js.map +1 -0
  213. package/dist/prediction-unit/unit-store.d.ts +28 -0
  214. package/dist/prediction-unit/unit-store.d.ts.map +1 -0
  215. package/dist/prediction-unit/unit-store.js +41 -0
  216. package/dist/prediction-unit/unit-store.js.map +1 -0
  217. package/dist/prediction-unit/unit-versioning.d.ts +43 -0
  218. package/dist/prediction-unit/unit-versioning.d.ts.map +1 -0
  219. package/dist/prediction-unit/unit-versioning.js +71 -0
  220. package/dist/prediction-unit/unit-versioning.js.map +1 -0
  221. package/dist/protocol/index.d.ts +9 -0
  222. package/dist/protocol/index.d.ts.map +1 -0
  223. package/dist/protocol/index.js +9 -0
  224. package/dist/protocol/index.js.map +1 -0
  225. package/dist/protocol/protocol-defaults.d.ts +37 -0
  226. package/dist/protocol/protocol-defaults.d.ts.map +1 -0
  227. package/dist/protocol/protocol-defaults.js +59 -0
  228. package/dist/protocol/protocol-defaults.js.map +1 -0
  229. package/dist/protocol/protocol-versioning.d.ts +46 -0
  230. package/dist/protocol/protocol-versioning.d.ts.map +1 -0
  231. package/dist/protocol/protocol-versioning.js +48 -0
  232. package/dist/protocol/protocol-versioning.js.map +1 -0
  233. package/dist/protocol/search-guard.d.ts +45 -0
  234. package/dist/protocol/search-guard.d.ts.map +1 -0
  235. package/dist/protocol/search-guard.js +50 -0
  236. package/dist/protocol/search-guard.js.map +1 -0
  237. package/dist/scoring/artifact-loader.d.ts +5 -32
  238. package/dist/scoring/artifact-loader.d.ts.map +1 -1
  239. package/dist/scoring/artifact-loader.js +4 -59
  240. package/dist/scoring/artifact-loader.js.map +1 -1
  241. package/dist/scoring/auto-train.d.ts +25 -5
  242. package/dist/scoring/auto-train.d.ts.map +1 -1
  243. package/dist/scoring/auto-train.js +48 -31
  244. package/dist/scoring/auto-train.js.map +1 -1
  245. package/dist/scoring/index.d.ts +3 -0
  246. package/dist/scoring/index.d.ts.map +1 -1
  247. package/dist/scoring/index.js +3 -0
  248. package/dist/scoring/index.js.map +1 -1
  249. package/dist/scoring/ml-model-inference-processor.d.ts +137 -10
  250. package/dist/scoring/ml-model-inference-processor.d.ts.map +1 -1
  251. package/dist/scoring/ml-model-inference-processor.js +383 -40
  252. package/dist/scoring/ml-model-inference-processor.js.map +1 -1
  253. package/dist/scoring/model-readiness.d.ts +45 -0
  254. package/dist/scoring/model-readiness.d.ts.map +1 -1
  255. package/dist/scoring/model-readiness.js +49 -0
  256. package/dist/scoring/model-readiness.js.map +1 -1
  257. package/dist/scoring/register.d.ts +8 -3
  258. package/dist/scoring/register.d.ts.map +1 -1
  259. package/dist/scoring/register.js +28 -4
  260. package/dist/scoring/register.js.map +1 -1
  261. package/dist/scoring/seams.d.ts +18 -2
  262. package/dist/scoring/seams.d.ts.map +1 -1
  263. package/dist/scoring/seams.js +35 -10
  264. package/dist/scoring/seams.js.map +1 -1
  265. package/dist/scoring/shadow-scoring.d.ts +245 -0
  266. package/dist/scoring/shadow-scoring.d.ts.map +1 -0
  267. package/dist/scoring/shadow-scoring.js +510 -0
  268. package/dist/scoring/shadow-scoring.js.map +1 -0
  269. package/dist/scoring/startup-register.d.ts +3 -3
  270. package/dist/scoring/startup-register.d.ts.map +1 -1
  271. package/dist/scoring/startup-register.js +10 -4
  272. package/dist/scoring/startup-register.js.map +1 -1
  273. package/dist/scoring/storage-provider-artifact-loader.d.ts +14 -0
  274. package/dist/scoring/storage-provider-artifact-loader.d.ts.map +1 -0
  275. package/dist/scoring/storage-provider-artifact-loader.js +47 -0
  276. package/dist/scoring/storage-provider-artifact-loader.js.map +1 -0
  277. package/dist/scoring/training-keys.d.ts +27 -0
  278. package/dist/scoring/training-keys.d.ts.map +1 -0
  279. package/dist/scoring/training-keys.js +54 -0
  280. package/dist/scoring/training-keys.js.map +1 -0
  281. package/dist/scoring/types.d.ts +72 -7
  282. package/dist/scoring/types.d.ts.map +1 -1
  283. package/dist/scoring/types.js +4 -0
  284. package/dist/scoring/types.js.map +1 -1
  285. package/dist/sidecar-provider.d.ts +2 -2
  286. package/dist/sidecar-provider.js +3 -3
  287. package/dist/snapshot/code-version.d.ts +16 -0
  288. package/dist/snapshot/code-version.d.ts.map +1 -0
  289. package/dist/snapshot/code-version.js +39 -0
  290. package/dist/snapshot/code-version.js.map +1 -0
  291. package/dist/snapshot/holdout-carver.d.ts +110 -0
  292. package/dist/snapshot/holdout-carver.d.ts.map +1 -0
  293. package/dist/snapshot/holdout-carver.js +171 -0
  294. package/dist/snapshot/holdout-carver.js.map +1 -0
  295. package/dist/snapshot/index.d.ts +17 -0
  296. package/dist/snapshot/index.d.ts.map +1 -0
  297. package/dist/snapshot/index.js +17 -0
  298. package/dist/snapshot/index.js.map +1 -0
  299. package/dist/snapshot/snapshot-builder.d.ts +152 -0
  300. package/dist/snapshot/snapshot-builder.d.ts.map +1 -0
  301. package/dist/snapshot/snapshot-builder.js +286 -0
  302. package/dist/snapshot/snapshot-builder.js.map +1 -0
  303. package/dist/snapshot/snapshot-file-store.d.ts +161 -0
  304. package/dist/snapshot/snapshot-file-store.d.ts.map +1 -0
  305. package/dist/snapshot/snapshot-file-store.js +204 -0
  306. package/dist/snapshot/snapshot-file-store.js.map +1 -0
  307. package/dist/snapshot/snapshot-hash.d.ts +6 -0
  308. package/dist/snapshot/snapshot-hash.d.ts.map +1 -0
  309. package/dist/snapshot/snapshot-hash.js +16 -0
  310. package/dist/snapshot/snapshot-hash.js.map +1 -0
  311. package/dist/snapshot/snapshot-manifest.d.ts +43 -0
  312. package/dist/snapshot/snapshot-manifest.d.ts.map +1 -0
  313. package/dist/snapshot/snapshot-manifest.js +43 -0
  314. package/dist/snapshot/snapshot-manifest.js.map +1 -0
  315. package/dist/snapshot/snapshot-retrainer.d.ts +107 -0
  316. package/dist/snapshot/snapshot-retrainer.d.ts.map +1 -0
  317. package/dist/snapshot/snapshot-retrainer.js +194 -0
  318. package/dist/snapshot/snapshot-retrainer.js.map +1 -0
  319. package/dist/snapshot/snapshot-serialization.d.ts +99 -0
  320. package/dist/snapshot/snapshot-serialization.d.ts.map +1 -0
  321. package/dist/snapshot/snapshot-serialization.js +191 -0
  322. package/dist/snapshot/snapshot-serialization.js.map +1 -0
  323. package/dist/snapshot/training-snapshot-store.d.ts +38 -0
  324. package/dist/snapshot/training-snapshot-store.d.ts.map +1 -0
  325. package/dist/snapshot/training-snapshot-store.js +41 -0
  326. package/dist/snapshot/training-snapshot-store.js.map +1 -0
  327. package/dist/storage/ps-storage-provider.d.ts +108 -0
  328. package/dist/storage/ps-storage-provider.d.ts.map +1 -0
  329. package/dist/storage/ps-storage-provider.js +154 -0
  330. package/dist/storage/ps-storage-provider.js.map +1 -0
  331. package/dist/training/artifact-store.d.ts +12 -103
  332. package/dist/training/artifact-store.d.ts.map +1 -1
  333. package/dist/training/artifact-store.js +13 -137
  334. package/dist/training/artifact-store.js.map +1 -1
  335. package/dist/training/compute-cost.d.ts +23 -0
  336. package/dist/training/compute-cost.d.ts.map +1 -0
  337. package/dist/training/compute-cost.js +36 -0
  338. package/dist/training/compute-cost.js.map +1 -0
  339. package/dist/training/evaluation-protocol-store.d.ts +53 -0
  340. package/dist/training/evaluation-protocol-store.d.ts.map +1 -0
  341. package/dist/training/evaluation-protocol-store.js +54 -0
  342. package/dist/training/evaluation-protocol-store.js.map +1 -0
  343. package/dist/training/index.d.ts +9 -1
  344. package/dist/training/index.d.ts.map +1 -1
  345. package/dist/training/index.js +9 -1
  346. package/dist/training/index.js.map +1 -1
  347. package/dist/training/locked-holdout.d.ts +19 -4
  348. package/dist/training/locked-holdout.d.ts.map +1 -1
  349. package/dist/training/locked-holdout.js +29 -5
  350. package/dist/training/locked-holdout.js.map +1 -1
  351. package/dist/training/seams.d.ts +34 -8
  352. package/dist/training/seams.d.ts.map +1 -1
  353. package/dist/training/seams.js +74 -18
  354. package/dist/training/seams.js.map +1 -1
  355. package/dist/training/storage-provider-artifact-store.d.ts +49 -0
  356. package/dist/training/storage-provider-artifact-store.d.ts.map +1 -0
  357. package/dist/training/storage-provider-artifact-store.js +147 -0
  358. package/dist/training/storage-provider-artifact-store.js.map +1 -0
  359. package/dist/training/trainer-model-lineage.d.ts +32 -0
  360. package/dist/training/trainer-model-lineage.d.ts.map +1 -0
  361. package/dist/training/trainer-model-lineage.js +62 -0
  362. package/dist/training/trainer-model-lineage.js.map +1 -0
  363. package/dist/training/trainer-request.d.ts +50 -0
  364. package/dist/training/trainer-request.d.ts.map +1 -0
  365. package/dist/training/trainer-request.js +65 -0
  366. package/dist/training/trainer-request.js.map +1 -0
  367. package/dist/training/trainer-result.d.ts +30 -0
  368. package/dist/training/trainer-result.d.ts.map +1 -0
  369. package/dist/training/trainer-result.js +40 -0
  370. package/dist/training/trainer-result.js.map +1 -0
  371. package/dist/training/training-engine.d.ts +417 -64
  372. package/dist/training/training-engine.d.ts.map +1 -1
  373. package/dist/training/training-engine.js +869 -178
  374. package/dist/training/training-engine.js.map +1 -1
  375. package/dist/training/training-refusal.d.ts +15 -0
  376. package/dist/training/training-refusal.d.ts.map +1 -0
  377. package/dist/training/training-refusal.js +62 -0
  378. package/dist/training/training-refusal.js.map +1 -0
  379. package/dist/training/types.d.ts +133 -41
  380. package/dist/training/types.d.ts.map +1 -1
  381. package/dist/training/types.js +4 -4
  382. package/dist/training/unit-model-lineage.d.ts +72 -0
  383. package/dist/training/unit-model-lineage.d.ts.map +1 -0
  384. package/dist/training/unit-model-lineage.js +288 -0
  385. package/dist/training/unit-model-lineage.js.map +1 -0
  386. package/package.json +16 -13
  387. package/dist/operations/__tests__/helpers.d.ts +0 -30
  388. package/dist/operations/__tests__/helpers.d.ts.map +0 -1
  389. package/dist/operations/__tests__/helpers.js +0 -44
  390. package/dist/operations/__tests__/helpers.js.map +0 -1
@@ -1,93 +1,890 @@
1
1
  /**
2
2
  * @module training/training-engine
3
3
  *
4
- * The **TrainingEngine** — Predictive Studio's training orchestrator (plan §3 /
5
- * §4.3 / §4.4 / §6 / §8.2 / §11). It composes the FeatureAssembly executor, the
6
- * Python sidecar, and artifact storage into one auditable flow that produces an
7
- * **immutable, versioned `MJ: ML Models`** row plus the `MJ: ML Training Runs`
8
- * row that recorded the attempt.
4
+ * The **TrainingEngine** — Predictive Studio's training orchestrator. Every pipeline trains under the Prediction
5
+ * Unit and the Evaluation Protocol version it is bound to, and the run produces an **immutable, versioned
6
+ * `MJ: ML Models`** row (when the gate ships an artifact) plus the `MJ: ML Training Runs` row that recorded the attempt.
7
+ * A pipeline without a Prediction Unit is refused before any run row is written (`unit-required`): the "Migrate
8
+ * Pipelines to Prediction Units and Evaluation Protocols" Action binds one, or holds the pipeline with the reason.
9
9
  *
10
- * ## Flow ({@link TrainingEngine.trainModel})
11
- * 1. Resolve the pipeline (parse its JSON columns via the core type contracts),
12
- * then refuse — before any row is written — an as-of mode training would ignore
13
- * ({@link AsOfSettingHasNoEffectError}) and an unknown `MajorityBaselineRule`
14
- * (`InvalidMajorityBaselineRuleError`).
15
- * 2. Create the training-run row (`Status='Running'`, `StartedAt`).
16
- * 3. Assemble the raw matrix + schema + preprocessing ops via FeatureAssembly
17
- * (context `'train'`), carrying the label column. The target read is ordered by
18
- * the entity's primary key, so the same data always arrives in the same order.
19
- * 4. **Carve the locked holdout FIRST** (§8.2 — never trained/tuned on) with the
20
- * seeded, stratified {@link LockedHoldoutSplitter}; the remaining
21
- * `train_test_split`/`kfold`/`holdout` validation is delegated to the sidecar
22
- * with the same seed. Build the sidecar `ValidationConfig`.
23
- * 5. Build the `TrainRequest` and call the sidecar → `TrainResponse`; the locked
24
- * holdout is scored exactly once → `HoldoutMetrics`.
25
- * 6. Persist the artifact to `MJ: Files` via the injected store → `ArtifactFileID`.
26
- * 7. Create the immutable `MJ: ML Models` row (Status `Draft`).
27
- * 8. **Leakage guard (§6.4):** single-feature-dominance check; a dominant feature
28
- * flags the run, keeps the model `Draft`, and NEVER auto-promotes.
29
- * 9. Finalize the run (`Completed`/`Failed`, results, costs, notes).
10
+ * A pipeline is trained only under the Evaluation Protocol version its `EvaluationProtocolID` names: a pipeline without one, a missing
11
+ * protocol row, a row that does not parse, or more candidates than the protocol's budget allows are
12
+ * refused before any run row is written, and so is a pipeline that declares a time index
13
+ * (`ValidationStrategy.TimeIndexColumn`) under a protocol whose holdout does not respect time (seeded-random:
14
+ * `time-index-needs-time-holdout`), and so is a pipeline whose stored AsOfStrategy the unit overrides (`input-not-accepted`); deps without a snapshot
15
+ * file store or a trainer fail there too. Only then does an advancing fixed decision date move to the run's day (a new
16
+ * unit version). The protocol row must predate the run row, and a protocol
17
+ * that does not fit the unit is refused on the run. The unit row reader then reads every unit row
18
+ * (censored and label-known rows excluded and counted), the target is validated, and the matrix is
19
+ * assembled as of each row's decision date by {@link TrainingEngine.AssembleForTraining} — the same
20
+ * `AsOfFeatureAssembler` the scoring path calls. The assembled rows are frozen into an immutable
21
+ * Training Snapshot (the locked holdout is the one the protocol declares: a date carve on its cutoff, with
22
+ * rows on or after its `holdoutEnd` left out of the snapshot; a seeded row-hash carve; or a forecast's
23
+ * rolling-origin test periods; identical content reuses the existing snapshot; the protocol decides the
24
+ * incumbent-score and slice columns). The protocol trainer (`TrainingDeps.trainer`) is sent pre-authorised downloads of the
25
+ * snapshot files, its result is recorded on the run (compute, code version), and the gate is decided
26
+ * in TypeScript ({@link GateRecords.BuildStoredGateRecord}): a sidecar decision that differs from the transcription
27
+ * refuses the run (`sidecar-gate-mismatch`). Every returned artifact is stored in `MJ: Files`, and the model row is
28
+ * created from the artifact the decision ships only: the finalist's for `model` (with the trainer's held-out
29
+ * permutation importance), the kept simple baseline member's for `keep-simple-baseline`, and none for `no-signal` or
30
+ * a kept heuristic rule. A single feature dominating the finalist's importance flags the run (a LEAKAGE WARNING note on the
31
+ * run) and the model stays `Draft`; every trainer model's Lineage records that leakage audit, so a kept baseline (whose
32
+ * own importance is `{}`) is judged by it at promotion. A shipped finalist of a probability task whose holdout
33
+ * calibration hides its family ({@link TrainerContract.CalibrationHidesFamily}) is held: a CALIBRATION HOLD note on
34
+ * the run and a `calibrationHold` on its Lineage, which the promotion gate never lets through. The run stores the
35
+ * trainer's result with its artifacts
36
+ * as file references, never their bytes, the unit resolution counts, the holdout carve's summary, the gate record and
37
+ * the request settings a retrain replays; the model Lineage names the unit version, the typed feature columns, the kept
38
+ * categorical levels scoring reuses, the snapshot's ID and content hash, and the protocol. A refusal
39
+ * is recorded on the run as a `refused` envelope ({@link TrainingRefusedError}); a failed trainer
40
+ * result is a `trainer` refusal.
30
41
  *
31
42
  * Every external dependency is injected (see {@link TrainingDeps}) so the engine
32
43
  * is unit-testable with no live database and no live sidecar.
33
44
  */
34
45
  import { LogError } from '@memberjunction/core';
35
- import { DOMINANCE_THRESHOLD_DEFAULT, resolveOutcomeConfig, EvaluationLineage, } from '@memberjunction/predictive-studio-core';
36
- import { FeatureAssemblyExecutor, detectSingleFeatureDominance } from '../feature-assembly/index.js';
37
- import { AsOfSettingHasNoEffectError } from './as-of-refusal.js';
38
- import { LockedHoldoutSplitter, DEFAULT_SPLIT_SEED } from './locked-holdout.js';
46
+ import { UUIDsEqual } from '@memberjunction/global';
47
+ import { DOMINANCE_THRESHOLD_DEFAULT, resolveOutcomeConfig, EvaluationLineage, LABEL_COLUMN, PredictionUnit, TaskTypeRules, UtcDay, TRAINING_RUN_RESULTS_SCHEMA, TrainerContract, CALIBRATION_SLOPE_RANGE, PREDICTOR_ARTIFACT_FORMAT, InnerScoreSelection, GateRecords, GateRules, } from '@memberjunction/predictive-studio-core';
48
+ import { detectSingleFeatureDominance } from '../feature-assembly/index.js';
49
+ import { RunViewDataAccess } from '../feature-assembly/data-access.js';
50
+ import { ProviderAssemblyMetadata } from '../feature-assembly/assembly-metadata.js';
51
+ import { AsOfFeatureAssembler } from '../feature-assembly/as-of/as-of-assembler.js';
52
+ import { FeatureResolver } from '../feature-assembly/as-of/feature-resolution.js';
53
+ import { RunViewRecordHistoryReader } from '../feature-assembly/as-of/record-history.js';
54
+ import { SeriesFeatures } from '../feature-assembly/as-of/series-features.js';
55
+ import { PredictionUnitRowReader } from '../prediction-unit/unit-row-reader.js';
56
+ import { UnitTargetValidator } from '../prediction-unit/target-validation.js';
57
+ import { RunViewPredictionUnitStore } from '../prediction-unit/unit-store.js';
58
+ import { DecisionDateAdvance } from '../prediction-unit/decision-date-advance.js';
59
+ import { TrainingRefusedError } from './training-refusal.js';
60
+ import { HoldoutCarvers } from '../snapshot/holdout-carver.js';
61
+ import { TrainingSnapshotBuilder } from '../snapshot/snapshot-builder.js';
62
+ import { RunViewTrainingSnapshotStore } from '../snapshot/training-snapshot-store.js';
63
+ import { SnapshotHash } from '../snapshot/snapshot-hash.js';
64
+ import { LockedHoldoutSplitter } from './locked-holdout.js';
65
+ import { TrainerRequestBuilder } from './trainer-request.js';
66
+ import { TrainerRunRecorder, TrainerLineageRefusedError } from './trainer-result.js';
67
+ import { EvaluationProtocolSpecs, RunViewEvaluationProtocolStore } from './evaluation-protocol-store.js';
68
+ import { ProtocolSearchGuard } from '../protocol/search-guard.js';
69
+ import { ComputePricing } from './compute-cost.js';
39
70
  /**
40
71
  * Training orchestrator. Stateless across calls; construct once and reuse. All
41
72
  * dependencies are supplied per call via {@link TrainingDeps}.
42
73
  */
43
74
  export class TrainingEngine {
44
- /**
45
- * @param assembler optional FeatureAssembly executor override (tests may inject one)
46
- */
47
- constructor(assembler) {
48
- this.assembler = assembler ?? new FeatureAssemblyExecutor();
75
+ constructor() {
76
+ this.unitReader = new PredictionUnitRowReader();
49
77
  }
50
78
  /**
51
79
  * Train a model end-to-end from a pipeline definition.
52
80
  *
53
- * @param input the pipeline id + optional session-iteration / as-of inputs
54
- * @param deps the injected dependency bundle (entity factory, loader, sidecar, store)
55
- * @returns the produced `Draft` model and the `Completed`/`Failed` training run
81
+ * @param input the pipeline id + optional session-iteration inputs
82
+ * @param deps the injected dependency bundle (entity factory, loader, trainer, stores)
83
+ * @returns the produced `Draft` model (null when the gate ships nothing) and the training run
84
+ * @throws TrainingRefusedError (`unit-required`) before any run row when the pipeline has no Prediction Unit
56
85
  */
57
86
  async trainModel(input, deps) {
87
+ // The compute rate is read before anything is written or trained, so a misconfigured rate fails fast.
88
+ const usdPerSecond = ComputePricing.ReadComputeRate();
58
89
  const resolved = await this.resolvePipeline(input.pipelineId, deps);
59
- if (AsOfSettingHasNoEffectError.WouldBeIgnored(resolved.asOf)) {
60
- throw new AsOfSettingHasNoEffectError('pipeline', resolved.asOf.Mode, resolved.pipeline.ID);
90
+ if (!resolved.pipeline.PredictionUnitID)
91
+ throw TrainingEngine.UnitRequired(resolved.pipeline.ID);
92
+ return this.trainUnitPipeline(resolved, resolved.pipeline.PredictionUnitID, input, deps, usdPerSecond);
93
+ }
94
+ /**
95
+ * Moves an advancing fixed decision date to the run's UTC day after every pipeline-stage refusal and deps check
96
+ * (protocol, budget, time index, a stored AsOfStrategy override, snapshot file store, trainer) and before the run row (a new unit
97
+ * version, the pipeline bound to it), so the run reads features as they stand on its own day, its lineage names that
98
+ * version, and a refused pipeline never mints a version. Returns the unit to train under.
99
+ */
100
+ async advanceDecisionDate(pipeline, deps) {
101
+ return DecisionDateAdvance.AdvanceFixedDecisionDate(pipeline, {
102
+ Store: deps.predictionUnits || new RunViewPredictionUnitStore(this.requireProvider(deps), deps.contextUser),
103
+ RunDay: UtcDay.UtcDayIso(deps.now?.() || new Date()),
104
+ Metadata: deps.assemblyMetadata || new ProviderAssemblyMetadata(this.requireProvider(deps)),
105
+ EntityFactory: deps.entityFactory,
106
+ ContextUser: deps.contextUser,
107
+ });
108
+ }
109
+ /**
110
+ * The refusal of a pipeline without a Prediction Unit, raised before any run row is written; the reason names how to
111
+ * bind one (a held pipeline's Description names what to declare).
112
+ */
113
+ static UnitRequired(pipelineId) {
114
+ return new TrainingRefusedError({
115
+ stage: 'pipeline',
116
+ reason: { kind: 'unit-required', pipelineId, why: 'this pipeline has no Prediction Unit; run the "Migrate Pipelines to Prediction Units and Evaluation Protocols" Action or bind a unit (a held pipeline names what to declare in its Description)' },
117
+ });
118
+ }
119
+ /** Record a run that ended in an error: a refusal as the `refused` envelope, any other error as a failure. */
120
+ async recordRunError(run, err, deps) {
121
+ if (err instanceof TrainingRefusedError) {
122
+ await this.finalizeRunRefused(run, err);
61
123
  }
62
- // Validates the evaluation settings (D2-C5d: an unknown MajorityBaselineRule is refused) before any row is written.
124
+ else {
125
+ await this.finalizeRunFailure(run, err, deps);
126
+ }
127
+ }
128
+ // region: Prediction Unit pipelines -------------------------------------------
129
+ /**
130
+ * Train a pipeline that points at a Prediction Unit. The bound Evaluation Protocol version is resolved first: a
131
+ * missing protocol, more candidates than its budget allows, or a pipeline that declares a time index under a holdout
132
+ * that does not respect time (`time-index-needs-time-holdout`) is refused before any run row is written. The unit
133
+ * decides the rows, their decision dates and their labels: a pipeline whose stored AsOfStrategy would override them
134
+ * is refused (the Train surfaces refuse a row cap and label-event dates by name before training), and deps without a snapshot file store or a trainer
135
+ * fail (a wiring error), both before anything is written. Only then does an advancing fixed decision date move to the
136
+ * run's day (a new unit version), and the run row is written. Censored and label-known rows are excluded and
137
+ * counted, and a protocol that does not fit the unit or a target that cannot train a model is refused before anything
138
+ * is assembled. The matrix is assembled as of each decision date ({@link AssembleForTraining}), frozen into a
139
+ * Training Snapshot the run references, and trained through the protocol trainer. A refusal after the run row exists
140
+ * is recorded on it as a `refused` envelope.
141
+ */
142
+ async trainUnitPipeline(resolved, boundUnitId, input, deps, usdPerSecond) {
63
143
  const majorityBaselineRule = EvaluationLineage.ParseMajorityBaselineRule(resolved.validation.MajorityBaselineRule);
144
+ const { Training: training, SnapshotFiles: snapshotFiles } = await this.requireUnitRunPrerequisites(resolved, input, deps);
145
+ const protocol = training.Protocol;
146
+ // Every pipeline-stage refusal and deps check writes nothing; only a pipeline that passes them all advances its
147
+ // decision date (a new unit version), and the run row follows.
148
+ // `||`: no advance (null) keeps the unit the pipeline is bound to.
149
+ const unitId = (await this.advanceDecisionDate(resolved.pipeline, deps)) || boundUnitId;
64
150
  const run = await this.createRunRow(resolved, input, deps);
65
151
  try {
66
- const assembly = await this.assemble(resolved, input, deps);
67
- const targetIdx = assembly.matrix.columns.indexOf(resolved.targetVariable);
68
- const cleanRows = targetIdx >= 0
69
- ? assembly.matrix.rows.filter((r) => r[targetIdx] !== null && r[targetIdx] !== undefined)
70
- : assembly.matrix.rows;
71
- const cleanMatrix = { columns: assembly.matrix.columns, rows: cleanRows };
72
- const split = this.carveLockedHoldout(cleanMatrix, resolved, DEFAULT_SPLIT_SEED);
73
- const validation = this.buildValidationConfig(resolved.validation);
74
- const trainRequest = this.buildTrainRequest(resolved, assembly, split.Training, validation);
75
- const response = await deps.sidecar.train(trainRequest, split.LockedHoldout);
76
- const evaluation = EvaluationLineage.Build(resolved.validation, {
77
- ValidationOutOfSample: response.validation_out_of_sample === true,
78
- ImportanceKind: response.feature_importance_kind || null,
79
- MajorityBaselineRule: majorityBaselineRule,
152
+ TrainingEngine.refuseProtocolNewerThanRun(protocol, run);
153
+ const unit = await this.loadUnitSpec(unitId, deps);
154
+ // A protocol that does not fit the unit is refused before any row is read or assembled.
155
+ const mismatch = ProtocolSearchGuard.CheckProtocolForUnit(protocol, unit);
156
+ if (mismatch !== null)
157
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: mismatch });
158
+ const seams = this.unitSeams(deps);
159
+ const unitRead = await this.readUnitRows(unit, seams, deps);
160
+ // Carve first: validation and assembly see only the rows training may use.
161
+ const rowCarve = TrainingEngine.CarveUnitRows(protocol.Protocol, unit, unitRead);
162
+ const validation = UnitTargetValidator.ValidateUnitTargets(rowCarve.Development, unit.label.outcome, unitRead.Counts);
163
+ if (validation.status === 'refused')
164
+ throw new TrainingRefusedError({ stage: 'unit', reason: validation.reason });
165
+ const assembly = await this.AssembleForTraining(resolved.pipeline.ID, deps, {
166
+ Resolved: resolved, Unit: unit, UnitRead: unitRead, DataAccess: seams.DataAccess, Metadata: seams.Metadata, SliceFields: protocol.Protocol.slices.subgroups,
167
+ ProtocolExclusions: protocol.Protocol.exclusions, Carve: rowCarve,
168
+ });
169
+ if (assembly.Assembled.Status === 'refused')
170
+ throw new TrainingRefusedError({ stage: 'assembly', reason: assembly.Assembled.Refusal });
171
+ const { Snapshot: snapshot, Carve: carve } = await this.freezeSnapshot(resolved, assembly, assembly.Assembled, rowCarve, snapshotFiles, protocol, deps);
172
+ run.TrainingSnapshotID = snapshot.Entity.ID;
173
+ const unitResolved = { ...resolved, targetEntityName: unitRead.RowEntity.Name, targetVariable: LABEL_COLUMN, problemType: TaskTypeRules.LegacyProblemTypeForTask(unit.label.outcome) };
174
+ const model = await this.trainThroughTrainer({
175
+ Run: run, Resolved: unitResolved, Input: input, Unit: unit, Snapshot: snapshot, Carve: carve, Files: snapshotFiles, Training: training,
176
+ UnitLineage: this.unitLineage(unit, resolved, unitRead, assembly.Features, assembly.Assembled.CategoryLevels, snapshot.Entity),
177
+ Counts: unitRead.Counts, Uncovered: assembly.Assembled.UncoveredRowsExcluded, MajorityBaselineRule: majorityBaselineRule, UsdPerSecond: usdPerSecond, Deps: deps,
80
178
  });
81
- const dominance = this.checkLeakage(response, resolved.leakageGuard);
82
- const model = await this.createModelRow(resolved, input, assembly, split, response, evaluation, deps);
83
- await this.finalizeRunSuccess(run, model, assembly, resolved, response, dominance, evaluation, deps);
84
179
  return { model, run };
85
180
  }
86
181
  catch (err) {
87
- await this.finalizeRunFailure(run, err, deps);
182
+ await this.recordRunError(run, err, deps);
183
+ throw err;
184
+ }
185
+ }
186
+ /**
187
+ * The checks a unit pipeline passes before anything is written: the bound protocol (missing, or over its budget), a
188
+ * time-indexed pipeline under a holdout that does not respect time (`time-index-needs-time-holdout`), a stored
189
+ * AsOfStrategy that would override the unit, deps without a snapshot file store or a trainer, and an artifact store
190
+ * that cannot write here ({@link requireWritableArtifactStore}). Each throws.
191
+ */
192
+ async requireUnitRunPrerequisites(resolved, input, deps) {
193
+ const protocol = await this.requireBoundProtocol(resolved, input, deps);
194
+ const timeIndex = ProtocolSearchGuard.CheckTimeIndexHoldout(protocol, resolved.pipeline.ID, resolved.validation.TimeIndexColumn);
195
+ if (timeIndex !== null)
196
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: timeIndex });
197
+ TrainingEngine.refuseUnitOverrides(resolved);
198
+ const snapshotFiles = TrainingEngine.requireSnapshotFiles(deps);
199
+ const trainer = TrainingEngine.requireTrainer(deps);
200
+ await TrainingEngine.requireWritableArtifactStore(deps);
201
+ return { Training: { Protocol: protocol, Trainer: trainer }, SnapshotFiles: snapshotFiles };
202
+ }
203
+ /**
204
+ * The artifact store must be able to write here before anything of the run is written: a run whose snapshot is
205
+ * reused writes no snapshot file, so without this check a store whose provider is not configured on this server would
206
+ * first fail after the trainer has spent the run's compute. A store that cannot write is a configuration error (not a
207
+ * refusal of the pipeline), so no run row is written.
208
+ *
209
+ * @throws Error stating the run was refused before training, with the store's reason
210
+ */
211
+ static async requireWritableArtifactStore(deps) {
212
+ try {
213
+ await deps.artifactStore.AssertWritable();
214
+ }
215
+ catch (error) {
216
+ throw new Error(`TrainingEngine: the run was refused before training: ${error instanceof Error ? error.message : String(error)}`);
217
+ }
218
+ }
219
+ /**
220
+ * The Evaluation Protocol version the pipeline is bound to, read through `deps.protocols` (default: RunView on the
221
+ * request's provider). No binding, a missing row or more candidates than its budget allows is refused here, before
222
+ * any run row exists, so a refused search leaves none.
223
+ *
224
+ * @throws TrainingRefusedError (`protocol-required`, `too-many-candidates`, `protocol-invalid`)
225
+ */
226
+ async requireBoundProtocol(resolved, input, deps) {
227
+ const store = deps.protocols || new RunViewEvaluationProtocolStore(this.requireProvider(deps), deps.contextUser);
228
+ // `??`: an explicit empty candidate list counts as 0 candidates, as it is sent.
229
+ const requirement = await ProtocolSearchGuard.RequireProtocolForSearch(store, resolved.pipeline, input.candidates?.length ?? 1);
230
+ if (requirement.Ok === false)
231
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: requirement.Refusal });
232
+ return requirement.Loaded;
233
+ }
234
+ /** A run is judged only under a protocol row that existed before it: both instants come from the database clock. */
235
+ static refuseProtocolNewerThanRun(protocol, run) {
236
+ const runCreatedAt = run.__mj_CreatedAt;
237
+ if (ProtocolSearchGuard.ProtocolPrecedesRun(protocol.CreatedAt, runCreatedAt))
238
+ return;
239
+ throw new TrainingRefusedError({
240
+ stage: 'pipeline',
241
+ reason: { kind: 'protocol-created-after-run', protocolId: protocol.RowID, protocolCreatedAt: protocol.CreatedAt.toISOString(), runCreatedAt: runCreatedAt.toISOString() },
242
+ });
243
+ }
244
+ /** The unit decides decision dates, so a pipeline whose stored AsOfStrategy asks for point-in-time assembly is refused. */
245
+ static refuseUnitOverrides(resolved) {
246
+ if (resolved.asOf.Mode !== 'none')
247
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: { kind: 'input-not-accepted', input: 'asOf', why: 'decision dates come from the Prediction Unit' } });
248
+ }
249
+ /**
250
+ * The deps' snapshot file store. A unit run trains only from a Training Snapshot, so deps without one are incomplete
251
+ * (a wiring error, not a refusal of the pipeline) and training fails before anything is written, rather than training
252
+ * from rows nothing recorded.
253
+ */
254
+ static requireSnapshotFiles(deps) {
255
+ if (!deps.snapshotFiles) {
256
+ throw new Error('TrainingEngine: the training deps are incomplete: a Prediction Unit pipeline trains from a Training Snapshot, and no snapshot file store (snapshotFiles) was supplied');
257
+ }
258
+ return deps.snapshotFiles;
259
+ }
260
+ /**
261
+ * The deps' trainer. Every unit run trains only through it, so deps without one are incomplete (a wiring error) and
262
+ * training fails before anything is written.
263
+ */
264
+ static requireTrainer(deps) {
265
+ if (!deps.trainer) {
266
+ throw new Error('TrainingEngine: the training deps are incomplete: a Prediction Unit pipeline trains through the trainer, and no trainer (trainer) was supplied');
267
+ }
268
+ return deps.trainer;
269
+ }
270
+ /**
271
+ * The bound protocol's carve over a run's unit rows ({@link TrainingRowCarve}), by the carver the protocol declares
272
+ * ({@link HoldoutCarvers.CarverForProtocol}).
273
+ *
274
+ * @throws TrainingRefusedError (`carve` stage) when the protocol's holdout cannot be carved from the unit rows
275
+ */
276
+ static CarveUnitRows(protocol, unit, unitRead) {
277
+ const carver = HoldoutCarvers.CarverForProtocol(protocol, unit);
278
+ const byId = new Map(unitRead.Rows.map((r) => [r.RowID, r]));
279
+ const roles = carver.AssignRoles(unitRead.Rows, byId).Roles;
280
+ const kept = unitRead.Rows.filter((r) => roles.has(r.RowID));
281
+ const leftOut = unitRead.Rows.filter((r) => !roles.has(r.RowID));
282
+ return {
283
+ Kept: kept,
284
+ Development: kept.filter((r) => roles.get(r.RowID) === 'development'),
285
+ CarveRows: (rows) => carver.AssignRoles([...rows, ...leftOut], byId),
286
+ };
287
+ }
288
+ /**
289
+ * Freeze the assembled rows into a Training Snapshot: each row gets its manifest role from the run's carve
290
+ * ({@link TrainingRowCarve.CarveRows} over the assembled rows); rows the carve leaves out (a date carve's rows on or
291
+ * after `holdoutEnd`, never assembled) are not in the snapshot and are counted in the summary. Identical content reuses the
292
+ * snapshot that already holds it. The bound protocol decides the evaluation columns: the incumbent-score column when
293
+ * it declares an incumbent-heuristic baseline and the unit has a rule to score it, and one slice column per subgroup
294
+ * field it declares. Returns the snapshot and the carve's summary.
295
+ *
296
+ * @throws TrainingRefusedError (`carve` stage) when the protocol's holdout cannot be carved from the rows
297
+ */
298
+ async freezeSnapshot(resolved, assembly, assembled, rowCarve, files, loaded, deps) {
299
+ const protocol = loaded.Protocol;
300
+ const carve = rowCarve.CarveRows(assembled.Rows);
301
+ const snapshots = deps.snapshots || new RunViewTrainingSnapshotStore(this.requireProvider(deps), deps.contextUser);
302
+ const snapshot = await new TrainingSnapshotBuilder().Build({
303
+ PipelineID: resolved.pipeline.ID,
304
+ FeatureSpecVersion: resolved.pipeline.Version,
305
+ Unit: assembly.Unit,
306
+ UnitRead: assembly.UnitRead,
307
+ Features: assembly.Features,
308
+ Assembled: assembled,
309
+ Roles: carve.Roles,
310
+ EvaluationProtocolID: loaded.RowID,
311
+ IncumbentScore: assembly.Unit.incumbent.kind === 'rule' && protocol.baselines.some((b) => b.kind === 'incumbent-heuristic'),
312
+ SliceFields: protocol.slices.subgroups,
313
+ Files: files,
314
+ EntityFactory: deps.entityFactory,
315
+ ContextUser: deps.contextUser,
316
+ ExistingByContentHash: (contentHash) => snapshots.FindByContentHash(contentHash),
317
+ });
318
+ return { Snapshot: snapshot, Carve: carve.Summary };
319
+ }
320
+ /**
321
+ * Train a unit run through the trainer: build the request over the frozen snapshot (the search's candidates, or the
322
+ * pipeline's own algorithm as the single candidate; the timeout is the protocol's compute budget, or less when an
323
+ * enclosing budget has less left), record the result on the run (compute, code version, status), decide the gate
324
+ * and refuse a sidecar decision that differs from it, store every returned artifact in `MJ: Files`, create the model
325
+ * row from the artifact the decision ships (none for `no-signal` or a kept heuristic rule) and complete the run with
326
+ * the stored result (artifacts as file references, never bytes), the holdout carve's summary, the gate record, the
327
+ * request settings a retrain replays, the leakage note of the single-feature-dominance check over the trainer's
328
+ * importance and, for a shipped finalist whose calibration hides its family, the calibration hold. A failed result is the refusal `trainer-failed` and a result whose code version cannot be recorded is
329
+ * `lineage-incomplete`; both keep the compute they recorded. The gate stage's refusals are stored before any artifact. When a step after the artifacts are stored fails (the model row or the run's completion cannot be saved), the model row and the stored artifacts are deleted best-effort ({@link discardStoredOutput}) and the original error is rethrown.
330
+ *
331
+ * @returns the model row, or null when the decision ships no artifact
332
+ */
333
+ async trainThroughTrainer(x) {
334
+ const { Run: run, Resolved: resolved, Snapshot: snapshot, Training: training, Deps: deps } = x;
335
+ const candidates = x.Input.candidates || [TrainerRequestBuilder.CandidateFromPipeline(resolved.algorithmDriverKey, resolved.pipeline.AlgorithmID, resolved.algorithmDriverKey, resolved.pipeline.Hyperparameters)];
336
+ // Each call pre-authorises fresh snapshot downloads: the first attempt sends one, every retry another.
337
+ const issue = () => TrainerRequestBuilder.BuildTrainerRequest({
338
+ TrainingRunID: run.ID, Snapshot: snapshot.Entity, Files: x.Files, Protocol: training.Protocol.Protocol, Task: x.Unit.label.outcome,
339
+ Candidates: candidates, TimeoutSeconds: TrainingEngine.TimeoutSecondsFor(training.Protocol.Protocol, x.Input),
340
+ });
341
+ const request = await issue();
342
+ const result = TrainingEngine.recordTrainerResult(run, await training.Trainer.RunTrainer(request, issue), x.UsdPerSecond);
343
+ TrainingEngine.checkAnswerBelongsToRun(run, snapshot, result);
344
+ TrainingEngine.checkSelection(result);
345
+ const gate = TrainingEngine.buildGateRecord(x, result);
346
+ const shipped = TrainingEngine.shippedArtifact(gate.decision, result);
347
+ const fileIds = await this.storeTrainerArtifacts(run, result, deps);
348
+ let model = null;
349
+ try {
350
+ const outcome = this.trainerOutcome(x, result, candidates, shipped);
351
+ model = shipped === null ? null : await this.createTrainerModelRow(x, outcome, shipped, TrainingEngine.storedFileOf(fileIds, shipped.Name));
352
+ await this.completeTrainerRun(x, request, outcome, gate, fileIds, model);
353
+ return model;
354
+ }
355
+ catch (err) {
356
+ await TrainingEngine.discardStoredOutput(run, model, fileIds, deps);
88
357
  throw err;
89
358
  }
90
359
  }
360
+ /**
361
+ * Best-effort removal of what a trainer run stored before a later step failed, so the failed run leaves no model row
362
+ * and no artifact nothing references: the model row (when it was saved) and the run's pointer to it, then every stored
363
+ * artifact. An artifact a model row that could not be deleted still references is kept. The run's completed result,
364
+ * features and hyperparameters are cleared too, so the Failed run never records a 'completed' result whose artifact
365
+ * file references were just deleted. Each failure is logged; the caller rethrows the original error.
366
+ */
367
+ static async discardStoredOutput(run, model, fileIds, deps) {
368
+ run.ResultingModelID = null;
369
+ run.ValidationResults = null;
370
+ run.FeaturesUsed = null;
371
+ run.Hyperparameters = null;
372
+ const stillReferenced = model === null ? null : await TrainingEngine.deleteModelRowOf(run, model);
373
+ const unreferenced = [...fileIds.values()].filter((id) => stillReferenced === null || !UUIDsEqual(id, stillReferenced));
374
+ await TrainingEngine.deleteArtifactFiles(run, unreferenced, deps);
375
+ }
376
+ /** Deletes a failed run's model row; returns the artifact file it references when the row could not be deleted, else null. */
377
+ static async deleteModelRowOf(run, model) {
378
+ let reason;
379
+ try {
380
+ reason = (await model.Delete()) ? null : model.LatestResult?.CompleteMessage || 'unknown error';
381
+ }
382
+ catch (error) {
383
+ reason = error instanceof Error ? error.message : String(error);
384
+ }
385
+ if (reason === null)
386
+ return null;
387
+ LogError(`TrainingEngine: could not delete model ${model.ID} of failed run ${run.ID}, so its artifact file ${model.ArtifactFileID} is kept: ${reason}`);
388
+ return model.ArtifactFileID;
389
+ }
390
+ /** Deletes artifact files through the run's store, every one attempted; each failure is logged. */
391
+ static async deleteArtifactFiles(run, fileIds, deps) {
392
+ const outcomes = await Promise.allSettled(fileIds.map((fileId) => deps.artifactStore.delete(fileId)));
393
+ outcomes.forEach((r, k) => {
394
+ if (r.status === 'rejected')
395
+ LogError(`TrainingEngine: could not delete artifact file ${fileIds[k]} of failed run ${run.ID}: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`);
396
+ });
397
+ }
398
+ /**
399
+ * Complete a trainer run: the envelope (the stored result with artifacts as file references, the carve, the gate
400
+ * record and the request settings), the resulting model (null when nothing ships), the features, the hyperparameters
401
+ * (the finalist's, except `{}` when a baseline member is kept: a member has none of its own) and the notes: the
402
+ * trainer's, the gate's reason (saying no model was created when nothing ships), the leakage note every run carries
403
+ * and a held model's CALIBRATION HOLD note.
404
+ */
405
+ async completeTrainerRun(x, request, outcome, gate, fileIds, model) {
406
+ const run = x.Run;
407
+ const results = {
408
+ schema: TRAINING_RUN_RESULTS_SCHEMA, status: 'completed', unitResolution: x.Counts,
409
+ trainer: TrainerContract.ToStoredTrainerResult(outcome.Result, fileIds), trainerRequest: TrainerRequestBuilder.TrainerRequestConfigOf(request),
410
+ carve: x.Carve, gate,
411
+ };
412
+ run.ResultingModelID = model === null ? null : model.ID;
413
+ run.FeaturesUsed = JSON.stringify(x.Snapshot.Content.Header.featureSchema.map((f) => f.Name));
414
+ run.Hyperparameters = JSON.stringify(gate.decision.outcome !== 'keep-simple-baseline' && outcome.Finalist ? outcome.Finalist.hyperparameters : {});
415
+ run.ValidationResults = JSON.stringify(results);
416
+ // The trainer's note, the gate's reason, the same leakage note every run carries (a dominant feature is a LEAKAGE
417
+ // WARNING), then a held model's CALIBRATION HOLD.
418
+ const gateNote = model === null ? `No model was created: ${gate.reason.text}` : gate.reason.text;
419
+ const leakageNote = this.buildRunNotes(outcome.Dominance, outcome.Evaluation, model !== null);
420
+ const notes = `${run.Notes || ''} ${gateNote} ${leakageNote} ${TrainingEngine.calibrationHoldNote(outcome.CalibrationHold)}`.trim();
421
+ run.Notes = TrainingEngine.withUncoveredNote(notes, x.Uncovered);
422
+ await this.saveOrThrow(run, 'finalize ML Training Run');
423
+ }
424
+ /**
425
+ * The run's gate record: the decision TypeScript derives from the trainer's paired intervals under the bound protocol,
426
+ * with its guards. Refused at the `gate` stage when a comparison the gate needs is missing or the sidecar decided
427
+ * differently (`sidecar-gate-mismatch`); runs before anything is stored.
428
+ */
429
+ static buildGateRecord(x, result) {
430
+ const built = GateRecords.BuildStoredGateRecord({ Result: result, Protocol: x.Training.Protocol.Protocol, Task: x.Unit.label.outcome, Carve: x.Carve });
431
+ if (built.Ok === false)
432
+ throw new TrainingRefusedError({ stage: 'gate', reason: built.Refusal });
433
+ return built.Record;
434
+ }
435
+ /**
436
+ * The artifact the decision ships: the finalist for `model`, the kept simple baseline member for
437
+ * `keep-simple-baseline`, and nothing for `no-signal` or a kept heuristic rule (a rule, not an artifact: the decision
438
+ * is stored and delivery publishes the rule). Runs before anything is stored.
439
+ *
440
+ * @throws Error when the kept member is not a simple baseline of the result, or the trainer returned no artifact for what ships
441
+ */
442
+ static shippedArtifact(decision, result) {
443
+ if (decision.outcome === 'no-signal')
444
+ return null;
445
+ const member = decision.outcome === 'model' ? null : TrainingEngine.keptMember(decision.shipped, result);
446
+ if (member !== null && member.baseline.kind === 'incumbent-heuristic')
447
+ return null;
448
+ if (!result.artifacts.some((a) => a.candidate === decision.shipped)) {
449
+ throw new Error(`TrainingEngine: the trainer returned no artifact for the shipped '${decision.shipped}' (returned: ${result.artifacts.map((a) => a.candidate).join(', ') || 'none'})`);
450
+ }
451
+ return { Name: decision.shipped, Member: member };
452
+ }
453
+ /** The simple baseline whose member name the decision kept. */
454
+ static keptMember(name, result) {
455
+ const member = result.baselines.find((b) => b.role === 'simple' && GateRules.BaselineMemberName(b.baseline) === name);
456
+ if (member === undefined)
457
+ throw new Error(`TrainingEngine: the gate kept '${name}', which is not a simple baseline of the trainer's result`);
458
+ return member;
459
+ }
460
+ /** The stored file of the shipped artifact (checked to be among the returned artifacts before they were stored). */
461
+ static storedFileOf(fileIds, name) {
462
+ const fileId = fileIds.get(name);
463
+ if (fileId === undefined)
464
+ throw new Error(`TrainingEngine: no stored file for the shipped artifact '${name}'`);
465
+ return fileId;
466
+ }
467
+ /**
468
+ * What a completed trainer result decides about the run and its model, computed once: the finalist candidate, the
469
+ * held-out permutation importance as the stored share map, the evaluation record, the single-feature-dominance
470
+ * check of that map against the pipeline's leakage guard (the check every run records) and the calibration hold of
471
+ * what ships ({@link calibrationHoldOf}).
472
+ */
473
+ trainerOutcome(x, result, candidates, shipped) {
474
+ const importance = TrainerContract.FeatureImportanceOf(result.importance);
475
+ return {
476
+ Result: result,
477
+ Finalist: TrainingEngine.finalistCandidate(candidates, result.finalist),
478
+ Importance: importance,
479
+ Evaluation: EvaluationLineage.Build(x.Resolved.validation, {
480
+ ValidationOutOfSample: true, ImportanceKind: TrainerContract.ImportanceKindOf(result.importance), MajorityBaselineRule: x.MajorityBaselineRule,
481
+ // A time-indexed pipeline trains only under a time-respecting holdout, so its model was tested on later periods.
482
+ HoldoutRespectsTime: ProtocolSearchGuard.TimeRespectingHoldouts.includes(x.Training.Protocol.Protocol.holdout.kind),
483
+ }),
484
+ Dominance: this.checkLeakage(importance, x.Resolved.leakageGuard),
485
+ CalibrationHold: TrainingEngine.calibrationHoldOf(shipped, result, x.Unit.label.outcome),
486
+ };
487
+ }
488
+ /**
489
+ * The calibration hold of what ships: only a shipped finalist is judged by the result's holdout calibration report,
490
+ * which is the finalist's (a kept baseline member, or nothing shipping, holds nothing). It holds when the report
491
+ * hides the task's family ({@link TrainerContract.CalibrationHidesFamily}), recording the slope, or null when the slope
492
+ * could not be measured.
493
+ */
494
+ static calibrationHoldOf(shipped, result, task) {
495
+ if (shipped === null || shipped.Member !== null)
496
+ return null;
497
+ if (!TrainerContract.CalibrationHidesFamily(result.calibration, task))
498
+ return null;
499
+ const slope = result.calibration === null || !Number.isFinite(result.calibration.slope) ? null : result.calibration.slope;
500
+ return { slope };
501
+ }
502
+ /**
503
+ * The run's leakage audit as a model Lineage stores it: the top feature of the finalist importance and its share, or
504
+ * null when no importance was measured.
505
+ */
506
+ static leakageAuditOf(dominance) {
507
+ if (dominance.TopFeature === undefined || dominance.TopShare === undefined)
508
+ return null;
509
+ return { topFeature: dominance.TopFeature, topShare: dominance.TopShare };
510
+ }
511
+ /** The plain-language CALIBRATION HOLD sentence of a held model's run; empty when nothing is held. */
512
+ static calibrationHoldNote(hold) {
513
+ if (hold === null)
514
+ return '';
515
+ const range = `${CALIBRATION_SLOPE_RANGE[0]}–${CALIBRATION_SLOPE_RANGE[1]}`;
516
+ const why = hold.slope === null
517
+ ? `the calibration slope of the model's probabilities could not be measured on the held-back rows, so they cannot be shown to fall in the ${range} range`
518
+ : `the model's probabilities are miscalibrated on the held-back rows (calibration slope ${hold.slope.toFixed(2)}, outside the ${range} range)`;
519
+ return `CALIBRATION HOLD: ${why}. Its family is hidden: the model is kept in Draft and the promotion gate will not move it to Validated or Published, with or without a sign-off.`;
520
+ }
521
+ /**
522
+ * Why a completed training run shipped no model: the reason of its stored gate decision (`no-signal`, or the unit's
523
+ * existing rule kept), or the run's notes when it stored no gate record.
524
+ */
525
+ static NoModelReason(result) {
526
+ const gate = GateRecords.ParseStoredGateRecord(result.run.ValidationResults);
527
+ return gate === null ? result.run.Notes || `training run ${result.run.ID} stored no gate decision` : gate.reason.text;
528
+ }
529
+ /**
530
+ * The trainer's timeout: the protocol's compute budget, or the seconds an enclosing budget has left when that is less.
531
+ * `??`: 0 seconds left in an enclosing budget is a real value, and only an absent one leaves the protocol's budget.
532
+ */
533
+ static TimeoutSecondsFor(protocol, input) {
534
+ return Math.min(protocol.budgets.maxComputeSeconds, input.timeoutSeconds ?? Number.POSITIVE_INFINITY);
535
+ }
536
+ /** The candidate the trainer chose, or null when its finalist is not one of the request's candidates (a baseline). */
537
+ static finalistCandidate(candidates, finalist) {
538
+ return candidates.find((c) => c.name === finalist) || null;
539
+ }
540
+ /**
541
+ * Record the trainer's result on the run and return it when it completed. A failed result is refused as
542
+ * `trainer-failed` and a completed one with lineage gaps as `lineage-incomplete`, each after its compute is recorded.
543
+ */
544
+ static recordTrainerResult(run, result, usdPerSecond) {
545
+ try {
546
+ TrainerRunRecorder.ApplyTrainerResultToRun(run, result, usdPerSecond);
547
+ }
548
+ catch (err) {
549
+ if (err instanceof TrainerLineageRefusedError)
550
+ throw new TrainingRefusedError({ stage: 'trainer', reason: { kind: 'lineage-incomplete', gaps: err.Gaps } });
551
+ throw err;
552
+ }
553
+ if (result.status === 'failed') {
554
+ throw new TrainingRefusedError({ stage: 'trainer', reason: { kind: 'trainer-failed', stage: result.stage, message: result.message, computeSeconds: result.computeSeconds } });
555
+ }
556
+ return result;
557
+ }
558
+ /**
559
+ * Refuse to store an answer that does not belong to this run: it names another training run (IDs compared as UUIDs),
560
+ * an artifact's bytes do not hash to the SHA-256 it states (that hash is what later checks of the artifact trust), or
561
+ * an artifact was built for another feature schema than the snapshot's. Runs before anything is stored.
562
+ *
563
+ * @throws Error naming the mismatch
564
+ */
565
+ static checkAnswerBelongsToRun(run, snapshot, result) {
566
+ if (!UUIDsEqual(result.trainingRunId, run.ID)) {
567
+ throw new Error(`TrainingEngine: the trainer answered for training run ${result.trainingRunId}, not ${run.ID}`);
568
+ }
569
+ for (const a of result.artifacts) {
570
+ const actual = SnapshotHash.Sha256Hex(decodeArtifact(a.bytesBase64));
571
+ if (actual !== a.sha256)
572
+ throw new Error(`TrainingEngine: artifact '${a.candidate}': its bytes hash to ${actual}, not the stated ${a.sha256}`);
573
+ if (a.featureSchemaHash !== snapshot.Entity.FeatureSchemaHash) {
574
+ throw new Error(`TrainingEngine: artifact '${a.candidate}' was built for feature schema ${a.featureSchemaHash}, not the snapshot's ${snapshot.Entity.FeatureSchemaHash}`);
575
+ }
576
+ }
577
+ }
578
+ /**
579
+ * Refuse a trainer report that breaks what the protocol guarantees about its search (`selection-invalid`): every
580
+ * candidate scored on every fold with a valid interval, and the holdout read for the finalist. Runs after the
581
+ * compute is recorded and before anything is stored, so the refused run keeps its compute and stores no artifact.
582
+ */
583
+ static checkSelection(result) {
584
+ const selection = InnerScoreSelection.CheckSelection(result.innerScores, result.finalist, result.holdoutAccess);
585
+ if (selection.Ok === false) {
586
+ throw new TrainingRefusedError({ stage: 'trainer', reason: { kind: 'selection-invalid', reason: selection.Reason, detail: selection.Detail } });
587
+ }
588
+ }
589
+ /**
590
+ * Store every returned artifact's decoded bytes as an `MJ: Files` row; the file IDs by candidate. When any save
591
+ * fails, the artifacts already saved are deleted through the same store before the error is rethrown, so a failed run
592
+ * leaves no artifact nothing references.
593
+ */
594
+ async storeTrainerArtifacts(run, result, deps) {
595
+ const outcomes = await Promise.allSettled(result.artifacts.map(async (a) => {
596
+ const fileId = await deps.artifactStore.save(decodeArtifact(a.bytesBase64), `trainer-${run.ID}-${a.candidate}.json`);
597
+ return [a.candidate, fileId];
598
+ }));
599
+ const saved = outcomes.flatMap((o) => (o.status === 'fulfilled' ? [o.value] : []));
600
+ const failure = outcomes.find((o) => o.status === 'rejected');
601
+ if (failure === undefined)
602
+ return new Map(saved);
603
+ await TrainingEngine.deleteArtifactFiles(run, saved.map(([, fileId]) => fileId), deps);
604
+ throw failure.reason instanceof Error ? failure.reason : new Error(String(failure.reason));
605
+ }
606
+ /**
607
+ * The model row of a trainer run, from the artifact the gate shipped (the trainer's envelope carries its own in-fold
608
+ * encoding, so there is no separate fitted preprocessing), and the split the trainer was sent (the snapshot's manifest
609
+ * roles). For the finalist: its algorithm (the pipeline's when the finalist is not a candidate), its inner score as
610
+ * `Metrics`, the holdout scores as `HoldoutMetrics` and the held-out permutation importance per source column as
611
+ * `FeatureImportance` (`{}` when the trainer measured none, as for a forecast). For a kept baseline member: the
612
+ * catalog algorithm of its driver ({@link shippedAlgorithmId}), its holdout score as `HoldoutMetrics`, and `{}` for
613
+ * `Metrics` and `FeatureImportance` (a baseline has no inner score and no importance of its own; its Lineage's
614
+ * leakage audit carries the finalist's, {@link trainerLineage}).
615
+ */
616
+ async createTrainerModelRow(x, outcome, shipped, artifactFileId) {
617
+ const { Resolved: resolved, Snapshot: snapshot, Deps: deps } = x;
618
+ const result = outcome.Result;
619
+ const content = snapshot.Content;
620
+ const split = LockedHoldoutSplitter.FromManifest(content, content.Header.labelColumn, resolved.problemType);
621
+ const version = await deps.recordLoader.nextModelVersion(resolved.pipeline.ID, deps.contextUser, deps.provider);
622
+ const model = await deps.entityFactory.getEntityObject('MJ: ML Models', deps.contextUser);
623
+ model.PipelineID = resolved.pipeline.ID;
624
+ model.Version = version;
625
+ model.AlgorithmID = await this.shippedAlgorithmId(x, outcome, shipped);
626
+ model.ArtifactFileID = artifactFileId;
627
+ model.FittedPreprocessing = '{}';
628
+ model.FeatureSchema = JSON.stringify(content.Header.featureSchema);
629
+ model.TargetVariable = PredictionUnit.DescribeLabelRule(x.Unit);
630
+ model.ProblemType = resolved.problemType;
631
+ const inner = shipped.Member === null ? result.innerScores.find((s) => s.candidate === result.finalist) : undefined;
632
+ model.Metrics = JSON.stringify(inner ? { [inner.inner.metric]: inner.inner.value } : {});
633
+ model.HoldoutMetrics = JSON.stringify(TrainerContract.HoldoutMetricsOf(shipped.Member === null ? result.holdout : { primary: shipped.Member.holdout, secondary: [] }));
634
+ model.FeatureImportance = JSON.stringify(shipped.Member === null ? outcome.Importance : {});
635
+ model.Lineage = JSON.stringify(this.trainerLineage(x, outcome, split, shipped));
636
+ model.TrainedAt = new Date();
637
+ model.TrainingDurationSec = Math.round(result.computeSeconds);
638
+ model.TrainingRowCount = split.TrainingRowCount;
639
+ model.Status = 'Draft';
640
+ await this.saveOrThrow(model, 'create ML Model');
641
+ return model;
642
+ }
643
+ /**
644
+ * The Lineage of a trainer run's model: the keys every model carries (the trainer's sidecar version, the snapshot's
645
+ * split), the unit's, and the protocol it was judged under with its artifact format. Its evaluation record states
646
+ * out-of-sample scoring (the holdout rows are scored once by the shipped artifact, which never trained on them) and the
647
+ * kind of the importance the row stores: the finalist's held-out importance, or none for a kept baseline member (its
648
+ * row stores `{}`). It names what shipped and that artifact's driver, the run's leakage audit (the finalist
649
+ * importance's top feature and share, whatever shipped: the promotion gate judges a kept baseline by it) and the
650
+ * calibration hold of a shipped finalist whose family is hidden.
651
+ */
652
+ trainerLineage(x, outcome, split, shipped) {
653
+ const evaluation = shipped.Member === null ? outcome.Evaluation : { ...outcome.Evaluation, ImportanceKind: 'none' };
654
+ return {
655
+ ...this.buildLineage(x.Resolved, x.Input, split, evaluation, x.UnitLineage),
656
+ sidecarVersion: outcome.Result.codeVersion.sidecarVersion,
657
+ evaluationProtocolId: x.Training.Protocol.RowID,
658
+ artifactFormat: PREDICTOR_ARTIFACT_FORMAT,
659
+ shippedMember: shipped.Name,
660
+ shippedDriver: TrainingEngine.shippedDriver(x, outcome, shipped),
661
+ trainingLeakageAudit: TrainingEngine.leakageAuditOf(outcome.Dominance),
662
+ calibrationHold: outcome.CalibrationHold,
663
+ };
664
+ }
665
+ /**
666
+ * The `MJ: ML Algorithms` row the model row names. The finalist: its candidate's algorithm, or the pipeline's when the
667
+ * finalist is not a candidate. A kept baseline member: the catalog row of its driver; a driver with no catalog row
668
+ * (the baseline-only count and non-negative GLMs, the forecast baselines) names the pipeline's algorithm, and the
669
+ * lineage's `shippedDriver` holds the driver that shipped.
670
+ */
671
+ async shippedAlgorithmId(x, outcome, shipped) {
672
+ if (shipped.Member === null)
673
+ return outcome.Finalist ? outcome.Finalist.algorithmId : x.Resolved.pipeline.AlgorithmID;
674
+ const catalogId = await x.Deps.recordLoader.resolveAlgorithmIDForDriver(TrainingEngine.shippedDriver(x, outcome, shipped), x.Deps.contextUser, x.Deps.provider);
675
+ return catalogId || x.Resolved.pipeline.AlgorithmID;
676
+ }
677
+ /** The driver key of the shipped artifact: the finalist candidate's (the pipeline's when not a candidate), or the kept member's. */
678
+ static shippedDriver(x, outcome, shipped) {
679
+ if (shipped.Member === null)
680
+ return outcome.Finalist ? outcome.Finalist.driverKey : x.Resolved.algorithmDriverKey;
681
+ return TrainingEngine.MemberDriverKey(shipped.Member.baseline, x.Unit.label.outcome);
682
+ }
683
+ /**
684
+ * The driver a shippable baseline member is fitted with, as the trainer fits it: the GLM and the one-feature baseline
685
+ * use the GLM of the task's family (a forecast's family is its value kind); the forecast baselines are their own
686
+ * series drivers. The dummy and the incumbent heuristic are yardsticks and never ship.
687
+ *
688
+ * @throws Error for a yardstick baseline
689
+ */
690
+ static MemberDriverKey(spec, task) {
691
+ switch (spec.kind) {
692
+ case 'glm':
693
+ case 'one-feature':
694
+ return TrainingEngine.glmDriver[task.kind === 'forecast' ? task.valueKind : task.kind];
695
+ case 'naive':
696
+ return 'naive';
697
+ case 'seasonal-naive':
698
+ return 'seasonal-naive';
699
+ case 'dummy':
700
+ case 'incumbent-heuristic':
701
+ throw new Error(`TrainingEngine: a ${spec.kind} baseline is a yardstick and never ships as an artifact`);
702
+ }
703
+ }
704
+ /** The GLM each task family's GLM baseline fits (the trainer's own table, `baselines.GLM_DRIVER`). */
705
+ static { this.glmDriver = {
706
+ binary: 'logistic_regression', multiclass: 'logistic_regression', continuous: 'ridge', count: 'poisson_glm', 'non-negative': 'tweedie_glm',
707
+ }; }
708
+ /**
709
+ * Assemble a unit pipeline's training matrix as of each unit row's decision date: the pipeline's steps resolve into
710
+ * typed columns (the bound protocol's exclusions and the pipeline's LeakageGuard deny lists excluded,
711
+ * {@link EffectiveExclusions}) and the as-of assembler reads them. This is the one
712
+ * assembly function training uses; the scoring path calls the same assembler with the columns and levels training
713
+ * stored. With `prepared` (a training run) the pipeline, unit and rows already read are reused; without it (a check
714
+ * that only needs the matrix) the pipeline, its bound protocol's exclusions, the unit and its rows are read here, and
715
+ * a pipeline without a unit is refused (`unit-required`). A training run's carve ({@link UnitAssemblyInputs.Carve})
716
+ * limits the assembled rows to the ones it keeps and the categorical fold to its development rows; the series history
717
+ * lags read from is still built from every unit row.
718
+ *
719
+ * @param pipelineId the `MJ: ML Training Pipelines` row
720
+ * @param deps the training deps (provider, user and the unit seams; `history` defaults to complete Record Changes reads)
721
+ * @param prepared what a training run has already read
722
+ */
723
+ async AssembleForTraining(pipelineId, deps, prepared) {
724
+ const inputs = prepared || (await this.prepareUnitAssembly(pipelineId, deps));
725
+ const { Resolved: resolved, Unit: unit, UnitRead: unitRead } = inputs;
726
+ const exclusions = TrainingEngine.EffectiveExclusions(resolved.leakageGuard, inputs.ProtocolExclusions);
727
+ const resolution = FeatureResolver.ResolveFeatureColumns(resolved.featureSteps, unit, unitRead.RowEntity, inputs.Metadata, exclusions);
728
+ if (resolution.Status === 'refused')
729
+ return { Unit: unit, UnitRead: unitRead, Features: [], Assembled: resolution };
730
+ // The names the assembly will write (date parts included), so this check accepts exactly what the builder does.
731
+ const columnNames = new Set(AsOfFeatureAssembler.ColumnNamesOf(resolution.Columns));
732
+ const sources = unitRead.Rows.map((r) => r.Source);
733
+ const unresolvedSlice = (inputs.SliceFields || []).find((field) => !TrainingSnapshotBuilder.SliceFieldResolves(field, columnNames, sources));
734
+ if (unresolvedSlice !== undefined) {
735
+ return { Unit: unit, UnitRead: unitRead, Features: [], Assembled: { Status: 'refused', Refusal: { kind: 'unresolved-column', entity: unit.name, field: unresolvedSlice } } };
736
+ }
737
+ const carve = inputs.Carve;
738
+ const assembled = await new AsOfFeatureAssembler().Assemble({
739
+ Context: 'train',
740
+ Unit: unit,
741
+ RowEntity: unitRead.RowEntity,
742
+ Rows: (carve ? carve.Kept : unitRead.Rows).map((r) => ({ RowID: r.RowID, EntityKey: r.EntityKey, DecisionDate: r.DecisionDate, Period: r.Period })),
743
+ Features: resolution.Columns,
744
+ SeriesHistory: TrainingEngine.SeriesHistoryFor(unit, unitRead.Rows),
745
+ Read: { mode: 'complete' },
746
+ DataAccess: inputs.DataAccess,
747
+ History: deps.history || new RunViewRecordHistoryReader(inputs.DataAccess, { mode: 'complete' }),
748
+ Metadata: inputs.Metadata,
749
+ AssembledAt: deps.now?.() || new Date(),
750
+ ExplicitOps: resolution.ExplicitOps,
751
+ ...(carve ? { DevelopmentRowsOf: (rows) => TrainingEngine.developmentIds(carve.CarveRows(rows)) } : {}),
752
+ });
753
+ return { Unit: unit, UnitRead: unitRead, Features: resolution.Columns, Assembled: assembled };
754
+ }
755
+ /** The ids a carve assigned the development role. */
756
+ static developmentIds(carve) {
757
+ return new Set([...carve.Roles].filter(([, role]) => role === 'development').map(([id]) => id));
758
+ }
759
+ /**
760
+ * The fields and sources kept out of a unit pipeline's matrix: the union of the bound protocol's `exclusions` (a guard
761
+ * field, set only in protocol configuration) and the pipeline's `LeakageGuard` deny lists. A union, so neither list
762
+ * can bring back a column the other keeps out.
763
+ *
764
+ * @param leakageGuard the pipeline's leakage guard
765
+ * @param protocolExclusions the bound protocol's exclusions, or null when the pipeline has no protocol
766
+ */
767
+ static EffectiveExclusions(leakageGuard, protocolExclusions) {
768
+ return {
769
+ denyFields: [...(leakageGuard.DenyFields || []), ...(protocolExclusions ? protocolExclusions.denyFields : [])],
770
+ denySources: [...(leakageGuard.DenySources || []), ...(protocolExclusions ? protocolExclusions.denySources : [])],
771
+ };
772
+ }
773
+ /**
774
+ * The series history a unit with a Temporal Spec reads its lags and rolling windows from: the unit rows' labels by
775
+ * entity and period. Null for a unit without one.
776
+ */
777
+ static SeriesHistoryFor(unit, rows) {
778
+ const temporal = unit.temporal;
779
+ return temporal ? SeriesFeatures.BuildSeriesHistory(rows.map((r) => TrainingEngine.toPoint(r)), temporal) : null;
780
+ }
781
+ /** A unit row as a series point; a forecast row always has a period and a numeric label once the target is validated. */
782
+ static toPoint(r) {
783
+ if (r.Period === null)
784
+ throw new Error(`TrainingEngine: unit row ${r.RowID} has no period, so it cannot be a series point`);
785
+ if (typeof r.Label !== 'number')
786
+ throw new Error(`TrainingEngine: unit row ${r.RowID} has the non-numeric label "${r.Label}", so it cannot be a series point`);
787
+ return { EntityKey: r.EntityKey, Period: r.Period, Value: r.Label, RowID: r.RowID, WindowEnd: r.WindowEnd };
788
+ }
789
+ /** Read the pipeline, its unit and the unit's rows, for an assembly that is not part of a training run. */
790
+ async prepareUnitAssembly(pipelineId, deps) {
791
+ const resolved = await this.resolvePipeline(pipelineId, deps);
792
+ const unitId = resolved.pipeline.PredictionUnitID;
793
+ if (!unitId) {
794
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: { kind: 'unit-required', pipelineId: resolved.pipeline.ID, why: 'only a pipeline that points at a Prediction Unit is assembled as of decision dates' } });
795
+ }
796
+ const protocolExclusions = await this.boundProtocolExclusions(resolved.pipeline, deps);
797
+ const unit = await this.loadUnitSpec(unitId, deps);
798
+ const seams = this.unitSeams(deps);
799
+ const unitRead = await this.readUnitRows(unit, seams, deps);
800
+ return { Resolved: resolved, Unit: unit, UnitRead: unitRead, DataAccess: seams.DataAccess, Metadata: seams.Metadata, ProtocolExclusions: protocolExclusions };
801
+ }
802
+ /**
803
+ * The exclusions of the protocol version the pipeline is bound to, read as a training run reads it; null when the
804
+ * pipeline names no protocol.
805
+ *
806
+ * @throws TrainingRefusedError (`protocol-required`) when the bound row does not exist, (`protocol-invalid`) when it does not parse
807
+ */
808
+ async boundProtocolExclusions(pipeline, deps) {
809
+ const protocolId = pipeline.EvaluationProtocolID;
810
+ if (!protocolId)
811
+ return null;
812
+ const store = deps.protocols || new RunViewEvaluationProtocolStore(this.requireProvider(deps), deps.contextUser);
813
+ const spec = await EvaluationProtocolSpecs.LoadSpec(store, protocolId);
814
+ if (spec === null)
815
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: { kind: 'protocol-required', pipelineId: pipeline.ID } });
816
+ return spec.exclusions;
817
+ }
818
+ /** The unit path reads through the request's provider (never a global RunView) unless the deps supply the seams. */
819
+ unitSeams(deps) {
820
+ return {
821
+ Metadata: deps.assemblyMetadata || new ProviderAssemblyMetadata(this.requireProvider(deps)),
822
+ DataAccess: deps.dataAccess || new RunViewDataAccess(deps.contextUser, this.requireProvider(deps)),
823
+ };
824
+ }
825
+ /** Every unit row, read completely; a refused read is the run's refusal. */
826
+ async readUnitRows(unit, seams, deps) {
827
+ const unitRead = await this.unitReader.Read(unit, { DataAccess: seams.DataAccess, Metadata: seams.Metadata, Read: { mode: 'complete' }, Now: deps.now?.() || new Date() });
828
+ if (unitRead.Status === 'refused')
829
+ throw new TrainingRefusedError(unitRead.Refusal);
830
+ return unitRead;
831
+ }
832
+ /** Load the pipeline's unit version and parse it; a missing or unparseable unit is the refusal `unit-invalid`. */
833
+ async loadUnitSpec(unitId, deps) {
834
+ const store = deps.predictionUnits || new RunViewPredictionUnitStore(this.requireProvider(deps), deps.contextUser);
835
+ const row = await store.Load(unitId);
836
+ if (!row)
837
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: { kind: 'unit-invalid', unitId, errors: ['not found'] } });
838
+ const parsed = PredictionUnit.ParsePredictionUnitRow(row);
839
+ if (parsed.Ok === false)
840
+ throw new TrainingRefusedError({ stage: 'pipeline', reason: { kind: 'unit-invalid', unitId, errors: parsed.Errors } });
841
+ return parsed.Value;
842
+ }
843
+ /** The unit's identity, the typed feature columns, the kept categorical levels and the snapshot, stored in the model Lineage. */
844
+ unitLineage(unit, resolved, unitRead, features, levels, snapshot) {
845
+ return {
846
+ predictionUnitId: unit.id,
847
+ predictionUnitVersion: unit.version,
848
+ labelVersion: unit.label.labelVersion,
849
+ featureSpecVersion: resolved.pipeline.Version,
850
+ unitRowEntity: unitRead.RowEntity.Name,
851
+ featureSpec: [...features],
852
+ categoryLevels: Object.fromEntries([...levels].map(([column, kept]) => [column, [...kept]])),
853
+ trainingSnapshotId: snapshot.ID,
854
+ snapshotContentHash: snapshot.ContentHash,
855
+ };
856
+ }
857
+ /** The provider the unit path's production seams read through; the unit path has no global fallback. */
858
+ requireProvider(deps) {
859
+ if (!deps.provider)
860
+ throw new Error('TrainingEngine: a metadata provider is required for Prediction Unit pipelines');
861
+ return deps.provider;
862
+ }
863
+ /**
864
+ * Record a refused run (best-effort — never masks the refusal): `Failed`, the `refused` envelope in
865
+ * ValidationResults and the refusal sentence in Notes. The caller rethrows the refusal.
866
+ */
867
+ async finalizeRunRefused(run, err) {
868
+ const results = { schema: TRAINING_RUN_RESULTS_SCHEMA, status: 'refused', refusal: err.Refusal };
869
+ run.Status = 'Failed';
870
+ run.CompletedAt = new Date();
871
+ run.ValidationResults = JSON.stringify(results);
872
+ run.Notes = err.message;
873
+ try {
874
+ if (!(await run.Save())) {
875
+ LogError(`TrainingEngine: failed to record the refusal on run ${run.ID}: ${run.LatestResult?.CompleteMessage || 'unknown error'}`);
876
+ }
877
+ }
878
+ catch (saveErr) {
879
+ LogError(`TrainingEngine: failed to record the refusal on run ${run.ID}: ${saveErr instanceof Error ? saveErr.message : String(saveErr)}`);
880
+ }
881
+ }
882
+ /** Rows excluded because a read field's history did not cover their decision date, named per entity and field. */
883
+ static withUncoveredNote(notes, uncovered) {
884
+ if (uncovered.length === 0)
885
+ return notes;
886
+ return `${notes} Excluded for uncovered history: ${uncovered.map((u) => `${u.entity}.${u.field} ${u.rows}`).join(', ')}.`;
887
+ }
91
888
  // region: pipeline resolution -------------------------------------------------
92
889
  /** Load the pipeline and parse its JSON config columns into typed shapes. */
93
890
  async resolvePipeline(pipelineId, deps) {
@@ -129,28 +926,15 @@ export class TrainingEngine {
129
926
  if (input.experimentSessionIterationId) {
130
927
  run.ExperimentSessionIterationID = input.experimentSessionIterationId;
131
928
  }
929
+ if (resolved.pipeline.EvaluationProtocolID) {
930
+ run.EvaluationProtocolID = resolved.pipeline.EvaluationProtocolID;
931
+ }
132
932
  run.Hyperparameters = JSON.stringify(resolved.hyperparameters);
133
933
  run.Status = 'Running';
134
934
  run.StartedAt = new Date();
135
935
  await this.saveOrThrow(run, 'create ML Training Run');
136
936
  return run;
137
937
  }
138
- /** Mark the run `Completed`, attach the model + results, and record observations. */
139
- async finalizeRunSuccess(run, model, assembly, resolved, response, dominance, evaluation, deps) {
140
- run.ResultingModelID = model.ID;
141
- run.FeaturesUsed = JSON.stringify(assembly.featureSchema.map((s) => s.Name));
142
- run.Hyperparameters = JSON.stringify(resolved.hyperparameters);
143
- run.ValidationResults = JSON.stringify({
144
- metrics: response.metrics,
145
- holdoutMetrics: response.holdout_metrics ?? null,
146
- validationStrategy: resolved.validation,
147
- });
148
- run.Status = 'Completed';
149
- run.CompletedAt = new Date();
150
- run.ComputeCost = 0;
151
- run.Notes = this.buildRunNotes(dominance, evaluation);
152
- await this.saveOrThrow(run, 'finalize ML Training Run');
153
- }
154
938
  /** Record a failed run (best-effort — never masks the original error). */
155
939
  async finalizeRunFailure(run, err, _deps) {
156
940
  try {
@@ -164,12 +948,14 @@ export class TrainingEngine {
164
948
  }
165
949
  }
166
950
  /** Compose the plain-language run note, surfacing leakage suspicion loudly (§6.4). */
167
- buildRunNotes(dominance, evaluation) {
951
+ buildRunNotes(dominance, evaluation, modelCreated) {
952
+ const consequence = modelCreated
953
+ ? 'The model is kept in Draft and will NOT be auto-promoted: the promotion gate refuses it unless a promote request records a sign-off with a reason.'
954
+ : 'No model was created from this run, so there is nothing to promote.';
168
955
  const base = dominance.Dominant
169
956
  ? `LEAKAGE WARNING: one field ("${dominance.TopFeature}") is doing almost all the predicting ` +
170
957
  `(${((dominance.TopShare ?? 0) * 100).toFixed(1)}% of total importance, over the ${(dominance.Threshold * 100).toFixed(0)}% threshold). ` +
171
- `This often means we are accidentally peeking at the answer. The model is kept in Draft and will NOT be ` +
172
- `auto-promoted: the promotion gate refuses it unless a promote request records a sign-off with a reason.`
958
+ `This often means we are accidentally peeking at the answer. ${consequence}`
173
959
  : 'Training completed. No single-feature dominance detected.';
174
960
  if (!evaluation.WithheldReason) {
175
961
  return base;
@@ -177,108 +963,12 @@ export class TrainingEngine {
177
963
  return (`${base} Trust withheld — ${evaluation.WithheldReason}: the pipeline declares '${evaluation.TimeIndexColumn}' as its time index, ` +
178
964
  'but the model was scored on rows from its own training period, not on later periods.');
179
965
  }
180
- // region: assembly ------------------------------------------------------------
181
- /** Assemble the raw matrix + schema + preprocessing recipe (train context). */
182
- async assemble(resolved, input, deps) {
183
- return this.assembler.assemble({
184
- targetEntityName: resolved.targetEntityName,
185
- recordSet: { EntityName: resolved.targetEntityName, OrderBy: this.primaryKeyOrder(resolved.targetEntityName, deps), MaxRows: input.maxRows },
186
- sources: resolved.sourceBindings,
187
- steps: resolved.featureSteps,
188
- asOf: resolved.asOf,
189
- leakageGuard: resolved.leakageGuard,
190
- targetVariable: resolved.targetVariable,
191
- labelEventDates: input.labelEventDates,
192
- primaryKeyField: input.primaryKeyField,
193
- context: 'train',
194
- contextUser: deps.contextUser,
195
- provider: deps.provider,
196
- });
197
- }
198
- /**
199
- * The ORDER BY for the training read: the target entity's primary-key columns. Without it an uncapped read (the
200
- * default) has no ORDER BY at all, so the database may return rows in any order and the seeded holdout carve would
201
- * pick different rows between runs.
202
- */
203
- primaryKeyOrder(targetEntityName, deps) {
204
- const entity = deps.provider.EntityByName(targetEntityName);
205
- if (!entity || entity.PrimaryKeys.length === 0) {
206
- throw new Error(`TrainingEngine: target entity '${targetEntityName}' has no primary key in metadata, so its rows cannot be read in a fixed order.`);
207
- }
208
- return entity.PrimaryKeys.map((pk) => pk.Name).join(', ');
209
- }
210
- // region: validation + holdout ------------------------------------------------
211
- /**
212
- * Carve the locked holdout FIRST (§8.2), before any train/test split: a seeded sample of
213
- * `LockedHoldoutFraction` of the rows, stratified on the label for classification. The holdout
214
- * rows are never sent in the training `data`.
215
- */
216
- carveLockedHoldout(matrix, resolved, seed) {
217
- return LockedHoldoutSplitter.Carve(matrix, resolved.validation.LockedHoldoutFraction, resolved.targetVariable, resolved.problemType, seed);
218
- }
219
- /**
220
- * Translate the pipeline's {@link ValidationStrategy} into a sidecar {@link ValidationConfig}. The seed is sent
221
- * explicitly so the sidecar's splits use the same seed as the locked-holdout carve.
222
- */
223
- buildValidationConfig(validation) {
224
- return {
225
- strategy: validation.Strategy,
226
- test_size: validation.TestSize,
227
- k: validation.K,
228
- random_state: DEFAULT_SPLIT_SEED,
229
- };
230
- }
231
- // region: sidecar request -----------------------------------------------------
232
- /** Build the `/train` request from the resolved pipeline + assembled training matrix. */
233
- buildTrainRequest(resolved, assembly, trainingMatrix, validation) {
234
- return {
235
- algorithm: resolved.algorithmDriverKey,
236
- problem_type: resolved.problemType,
237
- hyperparameters: resolved.hyperparameters,
238
- validation,
239
- feature_schema: assembly.featureSchema,
240
- preprocessing: assembly.preprocessing,
241
- target: resolved.targetVariable,
242
- data: trainingMatrix,
243
- };
244
- }
245
966
  // region: leakage -------------------------------------------------------------
246
967
  /** Run the single-feature-dominance check against the leakage threshold (§6.4). */
247
- checkLeakage(response, guard) {
248
- return detectSingleFeatureDominance(response.feature_importance ?? {}, guard.SingleFeatureDominanceThreshold);
249
- }
250
- // region: model persistence ---------------------------------------------------
251
- /**
252
- * Persist the artifact, then create the immutable `MJ: ML Models` row in
253
- * `Draft` (never auto-promoted, even when leakage is clean — promotion is a
254
- * separate human/agent gate, §6.4 / PS-AGENT-7).
255
- */
256
- async createModelRow(resolved, input, assembly, split, response, evaluation, deps) {
257
- const version = await deps.recordLoader.nextModelVersion(resolved.pipeline.ID, deps.contextUser, deps.provider);
258
- const artifactName = `model-${resolved.pipeline.ID}-v${version}.bin`;
259
- const artifactFileId = await deps.artifactStore.save(decodeArtifact(response.artifact_b64), artifactName, deps.contextUser);
260
- const model = await deps.entityFactory.getEntityObject('MJ: ML Models', deps.contextUser);
261
- model.PipelineID = resolved.pipeline.ID;
262
- model.Version = version;
263
- model.AlgorithmID = resolved.pipeline.AlgorithmID;
264
- model.ArtifactFileID = artifactFileId;
265
- model.FittedPreprocessing = JSON.stringify(response.fitted_preprocessing ?? {});
266
- model.FeatureSchema = JSON.stringify(assembly.featureSchema);
267
- model.TargetVariable = resolved.targetVariable;
268
- model.ProblemType = resolved.problemType;
269
- model.Metrics = JSON.stringify(response.metrics ?? {});
270
- if (response.holdout_metrics) {
271
- model.HoldoutMetrics = JSON.stringify(response.holdout_metrics);
272
- }
273
- model.FeatureImportance = JSON.stringify(response.feature_importance ?? {});
274
- model.Lineage = JSON.stringify(this.buildLineage(resolved, input, split, evaluation));
275
- model.TrainedAt = new Date();
276
- model.TrainingDurationSec = Math.round(response.duration_sec ?? 0);
277
- model.TrainingRowCount = response.training_row_count ?? split.TrainingRowCount;
278
- model.Status = 'Draft';
279
- await this.saveOrThrow(model, 'create ML Model');
280
- return model;
968
+ checkLeakage(importance, guard) {
969
+ return detectSingleFeatureDominance(importance, guard.SingleFeatureDominanceThreshold);
281
970
  }
971
+ // region: model lineage ----------------------------------------------------------
282
972
  /**
283
973
  * Assemble the model lineage blob (provenance, §4.3). This blob must be
284
974
  * **self-contained enough to re-assemble features at score time** — the
@@ -287,10 +977,11 @@ export class TrainingEngine {
287
977
  * `asOfStrategy` when the pipeline row isn't separately loaded. Omitting
288
978
  * `targetEntityName` or `featureSteps` here would leave the model unable to
289
979
  * produce any feature columns at inference (train/serve break), so both are
290
- * persisted alongside the other provenance fields.
980
+ * persisted alongside the other provenance fields, after the model's {@link UnitModelLineage} (every model is trained on a unit).
291
981
  */
292
- buildLineage(resolved, input, split, evaluation) {
982
+ buildLineage(resolved, input, split, evaluation, unitLineage) {
293
983
  return {
984
+ ...unitLineage,
294
985
  pipelineId: resolved.pipeline.ID,
295
986
  pipelineVersion: resolved.pipeline.Version,
296
987
  targetEntityName: resolved.targetEntityName,