@memberjunction/predictive-studio 6.2.0 → 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
@@ -0,0 +1,1002 @@
1
+ /**
2
+ * @module maintenance/psi-drift-detector
3
+ *
4
+ * Population Stability Index (PSI), Confidence-Floor Degradation, and
5
+ * Champion-vs-Challenger Divergence evaluation (`WS-4.4`).
6
+ *
7
+ * Mathematical definition of PSI across $B$ bins:
8
+ * $$\text{PSI} = \sum_{i=1}^{B} (p_i - q_i) \ln\left(\frac{p_i}{q_i}\right)$$
9
+ * where $q_i$ is the baseline (expected) proportion in bin $i$, $p_i$ is the evaluation
10
+ * (observed) proportion in bin $i$, and empty bins are regularized with Laplace smoothing
11
+ * $\epsilon = 10^{-4}$.
12
+ *
13
+ * Thresholds:
14
+ * - $\text{PSI} < 0.10$: `'None'` (stable distribution)
15
+ * - $0.10 \le \text{PSI} < 0.25$: `'Warning'` (moderate distributional shift)
16
+ * - $\text{PSI} \ge 0.25$: `'Critical'` (severe distributional shift)
17
+ */
18
+ import { LogError, RunView } from '@memberjunction/core';
19
+ import { EscapeSQLString, NormalizeUUID, UUIDMap, UUIDSet } from '@memberjunction/global';
20
+ /** Default Laplace smoothing constant for zero-count bins. */
21
+ export const DEFAULT_PSI_EPSILON = 1e-4;
22
+ /** Default warning threshold for Population Stability Index. */
23
+ export const PSI_WARNING_THRESHOLD = 0.10;
24
+ /** Default critical drift threshold for Population Stability Index. */
25
+ export const PSI_CRITICAL_THRESHOLD = 0.25;
26
+ /** Default minimum valid sample size required before PSI or confidence drift is evaluated. */
27
+ export const DEFAULT_MIN_SAMPLE_SIZE = 100;
28
+ /** Default maximum `MJ: Feature Values` rows loaded per window (baseline, evaluation) in a single drift evaluation. */
29
+ export const DEFAULT_DRIFT_MAX_ROWS = 100000;
30
+ /** Batch size (in Record Processes) when running scheduled drift sweeps across multiple processes. */
31
+ export const DRIFT_SWEEP_BATCH_SIZE = 10;
32
+ /**
33
+ * Classify a PSI value into `'None'`, `'Warning'`, or `'Critical'`.
34
+ */
35
+ export function ClassifyPSISeverity(psi, warningThreshold = PSI_WARNING_THRESHOLD, criticalThreshold = PSI_CRITICAL_THRESHOLD) {
36
+ if (!Number.isFinite(psi) || psi < warningThreshold) {
37
+ return 'None';
38
+ }
39
+ if (psi >= criticalThreshold) {
40
+ return 'Critical';
41
+ }
42
+ return 'Warning';
43
+ }
44
+ /**
45
+ * Validate PSI threshold and smoothing parameters, throwing an explicit `INVALID_PARAMETER` error
46
+ * when out of range or inverted.
47
+ */
48
+ export function ValidateDriftThresholds(warningThreshold, criticalThreshold, epsilon) {
49
+ if (!Number.isFinite(warningThreshold) || warningThreshold <= 0) {
50
+ throw new Error(`INVALID_PARAMETER: WarningPSIThreshold must be a finite positive number (received ${String(warningThreshold)}).`);
51
+ }
52
+ if (!Number.isFinite(criticalThreshold) || criticalThreshold <= 0) {
53
+ throw new Error(`INVALID_PARAMETER: CriticalPSIThreshold must be a finite positive number (received ${String(criticalThreshold)}).`);
54
+ }
55
+ if (warningThreshold >= criticalThreshold) {
56
+ throw new Error(`INVALID_PARAMETER: WarningPSIThreshold (${warningThreshold}) must be strictly less than CriticalPSIThreshold (${criticalThreshold}).`);
57
+ }
58
+ if (!Number.isFinite(epsilon) || epsilon <= 0 || epsilon > 0.01) {
59
+ throw new Error(`INVALID_PARAMETER: Epsilon must be in (0, 0.01] (received ${String(epsilon)}).`);
60
+ }
61
+ }
62
+ /**
63
+ * Compute Population Stability Index (PSI) across two bin count/proportion arrays:
64
+ * $$\text{PSI} = \sum_{i=1}^{B} (p_i - q_i) \ln\left(\frac{p_i}{q_i}\right)$$
65
+ * applying Laplace smoothing $\epsilon$ (`1e-4` by default) to zero or near-zero bins
66
+ * and normalizing both distributions to sum to `1.0`.
67
+ */
68
+ export function ComputePopulationStabilityIndex(baselineBins, evaluationBins, epsilon = DEFAULT_PSI_EPSILON) {
69
+ const binCount = Math.max(baselineBins.length, evaluationBins.length);
70
+ if (binCount === 0) {
71
+ return 0;
72
+ }
73
+ const smoothEps = Number.isFinite(epsilon) && epsilon > 0 ? epsilon : DEFAULT_PSI_EPSILON;
74
+ const rawQ = [];
75
+ const rawP = [];
76
+ for (let i = 0; i < binCount; i++) {
77
+ const bVal = baselineBins[i] ?? 0;
78
+ const eVal = evaluationBins[i] ?? 0;
79
+ rawQ.push(Number.isFinite(bVal) && bVal > 0 ? bVal : 0);
80
+ rawP.push(Number.isFinite(eVal) && eVal > 0 ? eVal : 0);
81
+ }
82
+ const sumQ = rawQ.reduce((a, b) => a + b, 0);
83
+ const sumP = rawP.reduce((a, b) => a + b, 0);
84
+ if (sumQ <= 0 || sumP <= 0) {
85
+ return 0;
86
+ }
87
+ // Convert to proportions and apply Laplace smoothing for empty bins, then re-normalize
88
+ const smoothedQ = rawQ.map((v) => Math.max(v / sumQ, smoothEps));
89
+ const smoothedP = rawP.map((v) => Math.max(v / sumP, smoothEps));
90
+ const normQSum = smoothedQ.reduce((a, b) => a + b, 0);
91
+ const normPSum = smoothedP.reduce((a, b) => a + b, 0);
92
+ let psi = 0;
93
+ for (let i = 0; i < binCount; i++) {
94
+ const q = smoothedQ[i] / normQSum;
95
+ const p = smoothedP[i] / normPSum;
96
+ psi += (p - q) * Math.log(p / q);
97
+ }
98
+ return Math.max(0, psi);
99
+ }
100
+ /**
101
+ * Compute PSI for a continuous/numeric feature by constructing empirical quantile bins from
102
+ * the baseline distribution (with open boundary tails `(-inf, q_1)` and `[q_{B-1}, +inf)`
103
+ * and deduplicated interior edges when ties exist), tracking missing/non-finite rates in a
104
+ * dedicated missingness bin.
105
+ */
106
+ export function ComputeNumericFeaturePSI(featureName, baselineValues, evaluationValues, numBins = 10, epsilon = DEFAULT_PSI_EPSILON, warningThreshold = PSI_WARNING_THRESHOLD, criticalThreshold = PSI_CRITICAL_THRESHOLD, minSampleSize = DEFAULT_MIN_SAMPLE_SIZE) {
107
+ const cleanBaseline = [];
108
+ for (const v of baselineValues) {
109
+ if (typeof v === 'number' && Number.isFinite(v)) {
110
+ cleanBaseline.push(v);
111
+ }
112
+ }
113
+ const cleanEval = [];
114
+ for (const v of evaluationValues) {
115
+ if (typeof v === 'number' && Number.isFinite(v)) {
116
+ cleanEval.push(v);
117
+ }
118
+ }
119
+ const bins = Math.max(2, Math.floor(numBins));
120
+ const minSamples = Math.max(1, Math.floor(minSampleSize));
121
+ const baseTotal = baselineValues.length;
122
+ const evalTotal = evaluationValues.length;
123
+ const baseMissingCount = baseTotal - cleanBaseline.length;
124
+ const evalMissingCount = evalTotal - cleanEval.length;
125
+ const baseMissingRate = baseTotal > 0 ? baseMissingCount / baseTotal : 0;
126
+ const evalMissingRate = evalTotal > 0 ? evalMissingCount / evalTotal : 0;
127
+ const missingRateDelta = Math.abs(evalMissingRate - baseMissingRate);
128
+ const severeMissingSurge = cleanBaseline.length >= minSamples &&
129
+ evalTotal >= minSamples &&
130
+ (cleanEval.length === 0 || missingRateDelta >= criticalThreshold);
131
+ if (!severeMissingSurge && (cleanBaseline.length < minSamples || cleanEval.length < minSamples)) {
132
+ return {
133
+ FeatureName: featureName,
134
+ FeatureType: 'Numeric',
135
+ PSI: 0,
136
+ Severity: 'None',
137
+ BinCount: bins,
138
+ BaselineSampleCount: cleanBaseline.length,
139
+ EvaluationSampleCount: cleanEval.length,
140
+ InsufficientData: true,
141
+ BaselineMissingRate: baseMissingRate,
142
+ EvaluationMissingRate: evalMissingRate,
143
+ MissingRateDelta: missingRateDelta,
144
+ };
145
+ }
146
+ const sortedBaseline = [...cleanBaseline].sort((a, b) => a - b);
147
+ const minVal = sortedBaseline[0];
148
+ const maxVal = sortedBaseline[sortedBaseline.length - 1];
149
+ let baseCounts;
150
+ let evalCounts;
151
+ if (minVal === maxVal) {
152
+ // Constant baseline: bin 0 = exact baseline value, bin 1 = any shifted value
153
+ baseCounts = [cleanBaseline.length, 0];
154
+ let exactEval = 0;
155
+ let shiftedEval = 0;
156
+ for (const v of cleanEval) {
157
+ if (v === minVal) {
158
+ exactEval++;
159
+ }
160
+ else {
161
+ shiftedEval++;
162
+ }
163
+ }
164
+ evalCounts = [exactEval, shiftedEval];
165
+ }
166
+ else {
167
+ // Empirical baseline quantile interior edges q_1 .. q_{bins-1}, deduplicating collapsed edges
168
+ const edges = [];
169
+ for (let k = 1; k < bins; k++) {
170
+ const pos = (k / bins) * (sortedBaseline.length - 1);
171
+ const lower = Math.floor(pos);
172
+ const upper = Math.ceil(pos);
173
+ const weight = pos - lower;
174
+ const q = sortedBaseline[lower] * (1 - weight) + sortedBaseline[upper] * weight;
175
+ if (edges.length === 0 || q > edges[edges.length - 1]) {
176
+ edges.push(q);
177
+ }
178
+ }
179
+ const effectiveBins = edges.length + 1;
180
+ baseCounts = new Array(effectiveBins).fill(0);
181
+ evalCounts = new Array(effectiveBins).fill(0);
182
+ const toQuantileBinIndex = (val) => {
183
+ let lo = 0;
184
+ let hi = edges.length;
185
+ while (lo < hi) {
186
+ const mid = (lo + hi) >>> 1;
187
+ if (val >= edges[mid]) {
188
+ lo = mid + 1;
189
+ }
190
+ else {
191
+ hi = mid;
192
+ }
193
+ }
194
+ return lo;
195
+ };
196
+ for (const v of cleanBaseline) {
197
+ baseCounts[toQuantileBinIndex(v)]++;
198
+ }
199
+ for (const v of cleanEval) {
200
+ evalCounts[toQuantileBinIndex(v)]++;
201
+ }
202
+ }
203
+ if (baseMissingCount > 0 || evalMissingCount > 0) {
204
+ baseCounts.push(baseMissingCount);
205
+ evalCounts.push(evalMissingCount);
206
+ }
207
+ const psi = ComputePopulationStabilityIndex(baseCounts, evalCounts, epsilon);
208
+ let severity = ClassifyPSISeverity(psi, warningThreshold, criticalThreshold);
209
+ if (severeMissingSurge && severity !== 'Critical') {
210
+ severity = 'Critical';
211
+ }
212
+ return {
213
+ FeatureName: featureName,
214
+ FeatureType: 'Numeric',
215
+ PSI: psi,
216
+ Severity: severity,
217
+ BinCount: baseCounts.length,
218
+ BaselineSampleCount: cleanBaseline.length,
219
+ EvaluationSampleCount: cleanEval.length,
220
+ InsufficientData: false,
221
+ BaselineMissingRate: baseMissingRate,
222
+ EvaluationMissingRate: evalMissingRate,
223
+ MissingRateDelta: missingRateDelta,
224
+ };
225
+ }
226
+ /**
227
+ * Compute PSI for a categorical feature across the union of observed baseline and evaluation categories,
228
+ * tracking missing (`null`/`undefined`) rates in a dedicated bucket.
229
+ */
230
+ export function ComputeCategoricalFeaturePSI(featureName, baselineCategories, evaluationCategories, epsilon = DEFAULT_PSI_EPSILON, warningThreshold = PSI_WARNING_THRESHOLD, criticalThreshold = PSI_CRITICAL_THRESHOLD, minSampleSize = DEFAULT_MIN_SAMPLE_SIZE) {
231
+ const minSamples = Math.max(1, Math.floor(minSampleSize));
232
+ const cleanBaseline = [];
233
+ for (const raw of baselineCategories) {
234
+ if (typeof raw === 'string') {
235
+ cleanBaseline.push(raw);
236
+ }
237
+ }
238
+ const cleanEval = [];
239
+ for (const raw of evaluationCategories) {
240
+ if (typeof raw === 'string') {
241
+ cleanEval.push(raw);
242
+ }
243
+ }
244
+ const baseTotal = baselineCategories.length;
245
+ const evalTotal = evaluationCategories.length;
246
+ const baseMissingCount = baseTotal - cleanBaseline.length;
247
+ const evalMissingCount = evalTotal - cleanEval.length;
248
+ const baseMissingRate = baseTotal > 0 ? baseMissingCount / baseTotal : 0;
249
+ const evalMissingRate = evalTotal > 0 ? evalMissingCount / evalTotal : 0;
250
+ const missingRateDelta = Math.abs(evalMissingRate - baseMissingRate);
251
+ const severeMissingSurge = cleanBaseline.length >= minSamples &&
252
+ evalTotal >= minSamples &&
253
+ (cleanEval.length === 0 || missingRateDelta >= criticalThreshold);
254
+ if (!severeMissingSurge && (cleanBaseline.length < minSamples || cleanEval.length < minSamples)) {
255
+ return {
256
+ FeatureName: featureName,
257
+ FeatureType: 'Categorical',
258
+ PSI: 0,
259
+ Severity: 'None',
260
+ BinCount: 0,
261
+ BaselineSampleCount: cleanBaseline.length,
262
+ EvaluationSampleCount: cleanEval.length,
263
+ InsufficientData: true,
264
+ BaselineMissingRate: baseMissingRate,
265
+ EvaluationMissingRate: evalMissingRate,
266
+ MissingRateDelta: missingRateDelta,
267
+ };
268
+ }
269
+ const categories = new Set();
270
+ const baseMap = new Map();
271
+ const evalMap = new Map();
272
+ for (const key of cleanBaseline) {
273
+ categories.add(key);
274
+ baseMap.set(key, (baseMap.get(key) ?? 0) + 1);
275
+ }
276
+ for (const key of cleanEval) {
277
+ categories.add(key);
278
+ evalMap.set(key, (evalMap.get(key) ?? 0) + 1);
279
+ }
280
+ const orderedKeys = Array.from(categories).sort();
281
+ const baseCounts = orderedKeys.map((k) => baseMap.get(k) ?? 0);
282
+ const evalCounts = orderedKeys.map((k) => evalMap.get(k) ?? 0);
283
+ if (baseMissingCount > 0 || evalMissingCount > 0) {
284
+ baseCounts.push(baseMissingCount);
285
+ evalCounts.push(evalMissingCount);
286
+ }
287
+ const psi = ComputePopulationStabilityIndex(baseCounts, evalCounts, epsilon);
288
+ let severity = ClassifyPSISeverity(psi, warningThreshold, criticalThreshold);
289
+ if (severeMissingSurge && severity !== 'Critical') {
290
+ severity = 'Critical';
291
+ }
292
+ return {
293
+ FeatureName: featureName,
294
+ FeatureType: 'Categorical',
295
+ PSI: psi,
296
+ Severity: severity,
297
+ BinCount: baseCounts.length,
298
+ BaselineSampleCount: cleanBaseline.length,
299
+ EvaluationSampleCount: cleanEval.length,
300
+ InsufficientData: false,
301
+ BaselineMissingRate: baseMissingRate,
302
+ EvaluationMissingRate: evalMissingRate,
303
+ MissingRateDelta: missingRateDelta,
304
+ };
305
+ }
306
+ /**
307
+ * Compute confidence-floor degradation and champion-vs-challenger divergence metrics.
308
+ */
309
+ export function ComputeConfidenceAndChallengerDivergence(input = {}) {
310
+ const confidenceFloor = input.ConfidenceFloor ?? 0.60;
311
+ const maxBelowFloorRate = input.MaxBelowFloorRate ?? 0.20;
312
+ const maxMeanConfidenceDrop = input.MaxMeanConfidenceDrop ?? 0.10;
313
+ const minAgreementRate = input.MinAgreementRate ?? 0.85;
314
+ const maxMeanAbsScoreDelta = input.MaxMeanAbsoluteScoreDelta ?? 0.15;
315
+ const maxP95LatencyRatio = input.MaxP95LatencyRatio ?? 3.0;
316
+ const minSamples = Math.max(1, Math.floor(input.MinSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE));
317
+ const scoreTolerance = input.ScoreAgreementTolerance ?? maxMeanAbsScoreDelta;
318
+ const baseConf = (input.BaselineConfidences ?? []).filter((v) => typeof v === 'number' && Number.isFinite(v));
319
+ const evalConf = (input.EvaluationConfidences ?? []).filter((v) => typeof v === 'number' && Number.isFinite(v));
320
+ const baselineMeanConfidence = baseConf.length > 0 ? baseConf.reduce((a, b) => a + b, 0) / baseConf.length : null;
321
+ const evaluationMeanConfidence = evalConf.length > 0 ? evalConf.reduce((a, b) => a + b, 0) / evalConf.length : null;
322
+ const belowFloorRate = evalConf.length > 0 ? evalConf.filter((c) => c < confidenceFloor).length / evalConf.length : null;
323
+ const confidenceInsufficientData = (evalConf.length > 0 && evalConf.length < minSamples) ||
324
+ (baseConf.length > 0 && baseConf.length < minSamples);
325
+ const meanDropExceeded = !confidenceInsufficientData &&
326
+ baselineMeanConfidence !== null &&
327
+ evaluationMeanConfidence !== null &&
328
+ baselineMeanConfidence - evaluationMeanConfidence > maxMeanConfidenceDrop;
329
+ const floorBreached = !confidenceInsufficientData && belowFloorRate !== null && belowFloorRate > maxBelowFloorRate;
330
+ const confidenceDegraded = meanDropExceeded || floorBreached;
331
+ const pairs = input.Pairs ?? [];
332
+ /** Pairs with a champion output: the only rows that count, here and in the sample gate below. */
333
+ let pairedCount = 0;
334
+ let labelPairs = 0;
335
+ let labelAgreements = 0;
336
+ let challengerTimeoutCount = 0;
337
+ let challengerFailureCount = 0;
338
+ const scoreDeltas = [];
339
+ const champLatencies = [];
340
+ const challLatencies = [];
341
+ for (const pair of pairs) {
342
+ const hasChampOutput = typeof pair.ChampionScore === 'number' || typeof pair.ChampionLabel === 'string';
343
+ // A challenger row with no champion to compare against says nothing about agreement, failures or latency.
344
+ if (!hasChampOutput) {
345
+ continue;
346
+ }
347
+ pairedCount++;
348
+ const isTimedOut = pair.TimedOut === true;
349
+ const hasError = typeof pair.ErrorMessage === 'string' && pair.ErrorMessage.trim().length > 0;
350
+ const hasChallOutput = typeof pair.ChallengerScore === 'number' || typeof pair.ChallengerLabel === 'string';
351
+ if (isTimedOut) {
352
+ challengerTimeoutCount++;
353
+ }
354
+ if (isTimedOut || hasError || !hasChallOutput) {
355
+ challengerFailureCount++;
356
+ labelPairs++;
357
+ }
358
+ else if (pair.ChampionLabel !== undefined && pair.ChallengerLabel !== undefined) {
359
+ labelPairs++;
360
+ if (pair.ChampionLabel === pair.ChallengerLabel) {
361
+ labelAgreements++;
362
+ }
363
+ }
364
+ else if (typeof pair.ChampionScore === 'number' &&
365
+ Number.isFinite(pair.ChampionScore) &&
366
+ typeof pair.ChallengerScore === 'number' &&
367
+ Number.isFinite(pair.ChallengerScore)) {
368
+ labelPairs++;
369
+ const useToleranceBand = input.ProblemType === 'regression' ||
370
+ input.ScoreAgreementTolerance !== undefined ||
371
+ pair.ChampionScore < 0 ||
372
+ pair.ChampionScore > 1 ||
373
+ pair.ChallengerScore < 0 ||
374
+ pair.ChallengerScore > 1;
375
+ if (useToleranceBand) {
376
+ if (Math.abs(pair.ChampionScore - pair.ChallengerScore) <= scoreTolerance) {
377
+ labelAgreements++;
378
+ }
379
+ }
380
+ else {
381
+ const champPositive = pair.ChampionScore >= 0.5;
382
+ const challPositive = pair.ChallengerScore >= 0.5;
383
+ if (champPositive === challPositive) {
384
+ labelAgreements++;
385
+ }
386
+ }
387
+ }
388
+ if (!isTimedOut &&
389
+ !hasError &&
390
+ typeof pair.ChampionScore === 'number' &&
391
+ Number.isFinite(pair.ChampionScore) &&
392
+ typeof pair.ChallengerScore === 'number' &&
393
+ Number.isFinite(pair.ChallengerScore)) {
394
+ scoreDeltas.push(Math.abs(pair.ChampionScore - pair.ChallengerScore));
395
+ }
396
+ if (typeof pair.ChampionLatencyMs === 'number' && pair.ChampionLatencyMs > 0) {
397
+ champLatencies.push(pair.ChampionLatencyMs);
398
+ }
399
+ if (typeof pair.ChallengerLatencyMs === 'number' && pair.ChallengerLatencyMs >= 0) {
400
+ challLatencies.push(pair.ChallengerLatencyMs);
401
+ }
402
+ }
403
+ const agreementRate = labelPairs > 0 ? labelAgreements / labelPairs : null;
404
+ const meanAbsoluteScoreDelta = scoreDeltas.length > 0 ? scoreDeltas.reduce((a, b) => a + b, 0) / scoreDeltas.length : null;
405
+ const p95Champ = computePercentile(champLatencies, 0.95);
406
+ const p95Chall = computePercentile(challLatencies, 0.95);
407
+ const p95LatencyRatio = p95Champ !== null && p95Champ > 0 && p95Chall !== null ? p95Chall / p95Champ : null;
408
+ // A challenger row with no champion to compare against is not a sample.
409
+ const divergenceInsufficientData = pairs.length > 0 && pairedCount < minSamples;
410
+ const agreementBreached = !divergenceInsufficientData && agreementRate !== null && agreementRate < minAgreementRate;
411
+ const deltaBreached = !divergenceInsufficientData && meanAbsoluteScoreDelta !== null && meanAbsoluteScoreDelta > maxMeanAbsScoreDelta;
412
+ const latencyBreached = !divergenceInsufficientData && p95LatencyRatio !== null && p95LatencyRatio > maxP95LatencyRatio;
413
+ const challengerDiverged = agreementBreached || deltaBreached || latencyBreached;
414
+ return {
415
+ BaselineMeanConfidence: baselineMeanConfidence,
416
+ EvaluationMeanConfidence: evaluationMeanConfidence,
417
+ BelowFloorRate: belowFloorRate,
418
+ ConfidenceDegraded: confidenceDegraded,
419
+ ConfidenceInsufficientData: confidenceInsufficientData,
420
+ DivergenceInsufficientData: divergenceInsufficientData,
421
+ PairCount: pairedCount,
422
+ ChallengerTimeoutCount: challengerTimeoutCount,
423
+ ChallengerFailureCount: challengerFailureCount,
424
+ AgreementRate: agreementRate,
425
+ MeanAbsoluteScoreDelta: meanAbsoluteScoreDelta,
426
+ P95LatencyRatio: p95LatencyRatio,
427
+ ChallengerDiverged: challengerDiverged,
428
+ };
429
+ }
430
+ /**
431
+ * Evaluate feature PSI across numeric, categorical, and pre-binned features along with
432
+ * confidence-floor and champion-vs-challenger divergence metrics.
433
+ */
434
+ export function EvaluateFeatureAndPredictionDrift(input) {
435
+ const epsilon = input.Epsilon ?? DEFAULT_PSI_EPSILON;
436
+ const warnThreshold = input.WarningPSIThreshold ?? PSI_WARNING_THRESHOLD;
437
+ const critThreshold = input.CriticalPSIThreshold ?? PSI_CRITICAL_THRESHOLD;
438
+ const minSampleSize = input.MinSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE;
439
+ ValidateDriftThresholds(warnThreshold, critThreshold, epsilon);
440
+ const featureResults = [];
441
+ if (input.PrebinnedFeatures) {
442
+ for (const [featureName, spec] of Object.entries(input.PrebinnedFeatures)) {
443
+ const baseSampleCount = spec.BaselineSampleCount ?? spec.BaselineProportions.length;
444
+ const evalSampleCount = spec.EvaluationSampleCount ?? spec.EvaluationProportions.length;
445
+ const explicitCountsUnderMin = (spec.BaselineSampleCount !== undefined && spec.BaselineSampleCount < minSampleSize) ||
446
+ (spec.EvaluationSampleCount !== undefined && spec.EvaluationSampleCount < minSampleSize);
447
+ if (explicitCountsUnderMin) {
448
+ featureResults.push({
449
+ FeatureName: featureName,
450
+ FeatureType: 'Prebinned',
451
+ PSI: 0,
452
+ Severity: 'None',
453
+ BinCount: Math.max(spec.BaselineProportions.length, spec.EvaluationProportions.length),
454
+ BaselineSampleCount: baseSampleCount,
455
+ EvaluationSampleCount: evalSampleCount,
456
+ InsufficientData: true,
457
+ });
458
+ }
459
+ else {
460
+ const psi = ComputePopulationStabilityIndex(spec.BaselineProportions, spec.EvaluationProportions, epsilon);
461
+ featureResults.push({
462
+ FeatureName: featureName,
463
+ FeatureType: 'Prebinned',
464
+ PSI: psi,
465
+ Severity: ClassifyPSISeverity(psi, warnThreshold, critThreshold),
466
+ BinCount: Math.max(spec.BaselineProportions.length, spec.EvaluationProportions.length),
467
+ BaselineSampleCount: baseSampleCount,
468
+ EvaluationSampleCount: evalSampleCount,
469
+ InsufficientData: false,
470
+ });
471
+ }
472
+ }
473
+ }
474
+ if (input.NumericFeatures) {
475
+ for (const [featureName, spec] of Object.entries(input.NumericFeatures)) {
476
+ featureResults.push(ComputeNumericFeaturePSI(featureName, spec.Baseline, spec.Evaluation, spec.Bins ?? 10, epsilon, warnThreshold, critThreshold, minSampleSize));
477
+ }
478
+ }
479
+ if (input.CategoricalFeatures) {
480
+ for (const [featureName, spec] of Object.entries(input.CategoricalFeatures)) {
481
+ featureResults.push(ComputeCategoricalFeaturePSI(featureName, spec.Baseline, spec.Evaluation, epsilon, warnThreshold, critThreshold, minSampleSize));
482
+ }
483
+ }
484
+ const divergenceInput = input.ConfidenceAndDivergence
485
+ ? {
486
+ ...input.ConfidenceAndDivergence,
487
+ MinSampleSize: input.ConfidenceAndDivergence.MinSampleSize ?? minSampleSize,
488
+ }
489
+ : undefined;
490
+ const divergence = ComputeConfidenceAndChallengerDivergence(divergenceInput);
491
+ const driftedFeatures = featureResults.filter((f) => f.Severity !== 'None');
492
+ const maxPSI = featureResults.reduce((max, f) => Math.max(max, f.PSI), 0);
493
+ const insufficientData = featureResults.length > 0
494
+ ? featureResults.some((f) => f.InsufficientData === true) ||
495
+ divergence.ConfidenceInsufficientData === true
496
+ : divergence.ConfidenceInsufficientData === true ||
497
+ divergence.DivergenceInsufficientData === true ||
498
+ divergence.PairCount === 0;
499
+ let overallSeverity = ClassifyPSISeverity(maxPSI, warnThreshold, critThreshold);
500
+ for (const f of featureResults) {
501
+ if (f.Severity === 'Critical') {
502
+ overallSeverity = 'Critical';
503
+ break;
504
+ }
505
+ if (f.Severity === 'Warning' && overallSeverity === 'None') {
506
+ overallSeverity = 'Warning';
507
+ }
508
+ }
509
+ if (overallSeverity === 'None' && (divergence.ConfidenceDegraded || divergence.ChallengerDiverged)) {
510
+ overallSeverity = 'Warning';
511
+ }
512
+ const shouldAlert = overallSeverity !== 'None' || divergence.ConfidenceDegraded || divergence.ChallengerDiverged;
513
+ const summaryParts = [
514
+ `OverallSeverity=${overallSeverity}`,
515
+ `MaxPSI=${maxPSI.toFixed(4)}`,
516
+ `DriftedFeatures=${driftedFeatures.length}/${featureResults.length}`,
517
+ ];
518
+ if (insufficientData) {
519
+ summaryParts.push('InsufficientData=true');
520
+ }
521
+ if (divergence.DivergenceInsufficientData) {
522
+ summaryParts.push(`DivergenceInsufficientData=true (PairCount=${divergence.PairCount}/${minSampleSize})`);
523
+ }
524
+ if (divergence.ConfidenceDegraded) {
525
+ summaryParts.push(`ConfidenceDegraded=true (BelowFloorRate=${(divergence.BelowFloorRate ?? 0).toFixed(2)})`);
526
+ }
527
+ if (divergence.ChallengerDiverged) {
528
+ summaryParts.push(`ChallengerDiverged=true (AgreementRate=${(divergence.AgreementRate ?? 1).toFixed(2)}, MeanDelta=${(divergence.MeanAbsoluteScoreDelta ?? 0).toFixed(4)}, Timeouts=${divergence.ChallengerTimeoutCount}, Failures=${divergence.ChallengerFailureCount})`);
529
+ }
530
+ if (input.Truncated) {
531
+ summaryParts.push('Truncated=true');
532
+ }
533
+ return {
534
+ ModelID: input.ModelID,
535
+ RecordProcessID: input.RecordProcessID,
536
+ OverallSeverity: overallSeverity,
537
+ MaxPSI: maxPSI,
538
+ FeatureResults: featureResults,
539
+ DriftedFeatures: driftedFeatures,
540
+ DivergenceMetrics: divergence,
541
+ ShouldAlert: shouldAlert,
542
+ InsufficientData: insufficientData,
543
+ Truncated: input.Truncated,
544
+ Summary: summaryParts.join(', '),
545
+ };
546
+ }
547
+ const DAY_MS = 86_400_000;
548
+ /**
549
+ * The evaluation window defaults to the last 7 days and the baseline to the 28 days before it;
550
+ * explicit `EvaluationWindowStart` / `BaselineWindowEnd` values override them.
551
+ */
552
+ function resolveDriftWindows(options) {
553
+ const nowMs = Date.now();
554
+ const parsedEvalStart = options.EvaluationWindowStart ? new Date(options.EvaluationWindowStart).getTime() : NaN;
555
+ const evaluationStartMs = Number.isFinite(parsedEvalStart) ? parsedEvalStart : nowMs - 7 * DAY_MS;
556
+ const parsedBaselineEnd = options.BaselineWindowEnd ? new Date(options.BaselineWindowEnd).getTime() : NaN;
557
+ const baselineEndMs = Number.isFinite(parsedBaselineEnd) ? parsedBaselineEnd : evaluationStartMs;
558
+ return { BaselineStartMs: baselineEndMs - 28 * DAY_MS, BaselineEndMs: baselineEndMs, EvaluationStartMs: evaluationStartMs };
559
+ }
560
+ /** The `MJ: Feature Values` columns every drift read selects. */
561
+ const DRIFT_ROW_FIELDS = [
562
+ 'ID',
563
+ 'RecordProcessID',
564
+ 'ProcessRunID',
565
+ 'EntityID',
566
+ 'RecordID',
567
+ 'FeatureName',
568
+ 'Role',
569
+ 'AIModelID',
570
+ 'MLModelID',
571
+ 'Source',
572
+ 'ValueNumeric',
573
+ 'ValueText',
574
+ 'Confidence',
575
+ 'Reasoning',
576
+ 'ComputedAt',
577
+ ];
578
+ /** RecordIDs per pairing read, so a long list becomes several `IN (…)` views in the same batch. */
579
+ const PAIRING_RECORD_ID_CHUNK = 500;
580
+ /**
581
+ * The two bounded `MJ: Feature Values` reads behind one drift load of one record process (or model): the baseline
582
+ * window, and everything computed since the evaluation window starts. Rows in a gap between the two windows are read by
583
+ * neither, so they never count toward a window's cap. Each is read newest-first and capped on its own, so a capped load
584
+ * keeps the newest rows of BOTH windows; one row over the cap is fetched to tell a full window from a truncated one.
585
+ */
586
+ function featureValueDriftViews(options, windows, maxRows) {
587
+ const target = typeof options.RecordProcessID === 'string' && options.RecordProcessID.trim().length > 0
588
+ ? `RecordProcessID = '${EscapeSQLString(options.RecordProcessID.trim())}' AND `
589
+ : typeof options.ModelID === 'string' && options.ModelID.trim().length > 0
590
+ ? `MLModelID = '${EscapeSQLString(options.ModelID.trim())}' AND `
591
+ : '';
592
+ const at = (ms) => EscapeSQLString(new Date(ms).toISOString());
593
+ const view = (window) => ({
594
+ EntityName: 'MJ: Feature Values',
595
+ ExtraFilter: `${target}${window} AND Source = 'Pipeline'`,
596
+ OrderBy: 'ComputedAt DESC',
597
+ Fields: [...DRIFT_ROW_FIELDS],
598
+ ResultType: 'simple',
599
+ MaxRows: maxRows + 1,
600
+ SkipTotalRowCount: true,
601
+ });
602
+ return [
603
+ view(`ComputedAt >= '${at(windows.BaselineStartMs)}' AND ComputedAt < '${at(windows.BaselineEndMs)}'`),
604
+ view(`ComputedAt >= '${at(windows.EvaluationStartMs)}'`),
605
+ ];
606
+ }
607
+ /** The per-window row cap: a positive whole number, defaulting to {@link DEFAULT_DRIFT_MAX_ROWS}. */
608
+ function resolveDriftMaxRows(maxRows) {
609
+ const value = maxRows ?? DEFAULT_DRIFT_MAX_ROWS;
610
+ if (!Number.isInteger(value) || value <= 0) {
611
+ throw new Error('INVALID_PARAMETER: MaxRows must be a positive whole number.');
612
+ }
613
+ return value;
614
+ }
615
+ /**
616
+ * Both windows' rows, each cut to `maxRows`, oldest first; `Truncated` when either window had more.
617
+ * `windowRows` are the two {@link featureValueDriftViews} results, each newest-first.
618
+ */
619
+ function capDriftWindows(windowRows, maxRows, label) {
620
+ const truncated = windowRows.some((rows) => rows.length > maxRows);
621
+ if (truncated) {
622
+ LogError(`Drift evaluation for '${label}' was truncated at MaxRows (${maxRows}) per window: the oldest rows of a full window were not read.`);
623
+ }
624
+ const rows = windowRows.flatMap((w) => w.slice(0, maxRows));
625
+ rows.sort((a, b) => new Date(a.ComputedAt).getTime() - new Date(b.ComputedAt).getTime());
626
+ return { Rows: rows, Truncated: truncated };
627
+ }
628
+ /** The key a challenger is paired on: its record and feature. */
629
+ function pairingKey(row) {
630
+ return `${row.RecordID}::${row.FeatureName || 'Prediction'}`;
631
+ }
632
+ /**
633
+ * Reads of the current champion rows for the evaluation-window challengers that have no champion in the loaded
634
+ * windows. A champion whose value has not changed is never rewritten, so its `ComputedAt` can predate both windows;
635
+ * without these rows a stable model's challengers would go unpaired. One view per record process, feature and chunk
636
+ * of {@link PAIRING_RECORD_ID_CHUNK} RecordIDs, newest first. Bounded by the RecordID list, so `IgnoreMaxRows`.
637
+ */
638
+ function pairingChampionViews(rows, windows) {
639
+ const championKeys = new Set(rows.filter((r) => r.Role !== 'Challenger').map(pairingKey));
640
+ const unpaired = new Map();
641
+ for (const r of rows) {
642
+ if (r.Role !== 'Challenger' ||
643
+ (r.Source && r.Source !== 'Pipeline') ||
644
+ !r.RecordProcessID ||
645
+ !r.FeatureName ||
646
+ new Date(r.ComputedAt).getTime() < windows.EvaluationStartMs ||
647
+ championKeys.has(pairingKey(r))) {
648
+ continue;
649
+ }
650
+ const groupKey = `${NormalizeUUID(r.RecordProcessID)}::${r.FeatureName}`;
651
+ const group = unpaired.get(groupKey) ?? { RecordProcessID: r.RecordProcessID, FeatureName: r.FeatureName, RecordIDs: new Set() };
652
+ group.RecordIDs.add(r.RecordID);
653
+ unpaired.set(groupKey, group);
654
+ }
655
+ const views = [];
656
+ for (const group of unpaired.values()) {
657
+ const ids = [...group.RecordIDs];
658
+ for (let i = 0; i < ids.length; i += PAIRING_RECORD_ID_CHUNK) {
659
+ const idList = ids.slice(i, i + PAIRING_RECORD_ID_CHUNK).map((id) => `'${EscapeSQLString(id)}'`).join(', ');
660
+ views.push({
661
+ EntityName: 'MJ: Feature Values',
662
+ ExtraFilter: `RecordProcessID = '${EscapeSQLString(group.RecordProcessID)}' AND Role = 'Champion' AND Source = 'Pipeline'` +
663
+ ` AND FeatureName = '${EscapeSQLString(group.FeatureName)}' AND RecordID IN (${idList})`,
664
+ OrderBy: 'ComputedAt DESC',
665
+ Fields: [...DRIFT_ROW_FIELDS],
666
+ ResultType: 'simple',
667
+ IgnoreMaxRows: true,
668
+ });
669
+ }
670
+ }
671
+ return views;
672
+ }
673
+ /**
674
+ * Each row set's out-of-window champion rows for pairing ({@link pairingChampionViews}), from one batched `RunViews`
675
+ * as the caller across every set. A failed view is logged and leaves its challengers unpaired (InsufficientData, never
676
+ * a false alarm).
677
+ */
678
+ async function loadPairingChampions(rowSets, windows, options) {
679
+ const views = [];
680
+ const owners = [];
681
+ rowSets.forEach((rows, i) => {
682
+ for (const view of pairingChampionViews(rows, windows)) {
683
+ views.push(view);
684
+ owners.push(i);
685
+ }
686
+ });
687
+ const champions = rowSets.map(() => []);
688
+ if (views.length === 0) {
689
+ return champions;
690
+ }
691
+ const results = await RunView.FromMetadataProvider(options.Provider).RunViews(views, options.ContextUser);
692
+ views.forEach((_view, k) => {
693
+ const res = results[k];
694
+ if (!res?.Success) {
695
+ LogError(`Drift evaluation could not read the champion rows to pair challengers with: ${res?.ErrorMessage ?? 'unknown error'}`);
696
+ return;
697
+ }
698
+ champions[owners[k]].push(...(res.Results ?? []));
699
+ });
700
+ return champions;
701
+ }
702
+ /** The ML model of a process's newest champion row; `rows` are oldest first. Undefined for non-ML processes. */
703
+ function championMLModelID(rows) {
704
+ for (let i = rows.length - 1; i >= 0; i--) {
705
+ if (rows[i].Role !== 'Challenger' && rows[i].MLModelID) {
706
+ return rows[i].MLModelID ?? undefined;
707
+ }
708
+ }
709
+ return undefined;
710
+ }
711
+ /**
712
+ * Each named ML model's `ProblemType`, by ID, from one `MJ: ML Models` read as the caller. A failed read is logged and
713
+ * yields no entries, so divergence falls back to its score-range heuristic rather than failing the load.
714
+ */
715
+ async function loadModelProblemTypes(modelIDs, options) {
716
+ const ids = [...new UUIDSet(modelIDs.filter((id) => !!id))];
717
+ const problemTypes = new UUIDMap();
718
+ if (ids.length === 0) {
719
+ return problemTypes;
720
+ }
721
+ const res = await RunView.FromMetadataProvider(options.Provider).RunView({
722
+ EntityName: 'MJ: ML Models',
723
+ ExtraFilter: `ID IN (${ids.map((id) => `'${EscapeSQLString(id)}'`).join(', ')})`,
724
+ Fields: ['ID', 'ProblemType'],
725
+ ResultType: 'simple',
726
+ }, options.ContextUser);
727
+ if (!res.Success) {
728
+ LogError(`Drift evaluation could not read the ProblemType of ML Models ${ids.join(', ')}: ${res.ErrorMessage ?? 'unknown error'}`);
729
+ return problemTypes;
730
+ }
731
+ for (const model of res.Results ?? []) {
732
+ problemTypes.Set(model.ID, model.ProblemType);
733
+ }
734
+ return problemTypes;
735
+ }
736
+ /**
737
+ * The ML model behind a process's newest champion: from the windows, else (a stable model whose champions are all
738
+ * older) from the pairing champions, which are newest first.
739
+ */
740
+ function processChampionMLModelID(rows, pairingChampions) {
741
+ return championMLModelID(rows) ?? pairingChampions.find((r) => r.MLModelID)?.MLModelID ?? undefined;
742
+ }
743
+ /** A caller-supplied ProblemType, else the one of the ML model behind the process's newest champion row. */
744
+ function withChampionProblemType(options, modelID, problemTypes) {
745
+ return { ...options, ProblemType: options.ProblemType ?? problemTypes.Get(modelID) };
746
+ }
747
+ /**
748
+ * Load baseline and rolling evaluation feature distributions, confidence distributions, and
749
+ * champion-vs-challenger pairs from pipeline-generated `MJ: Feature Values` (`Source = 'Pipeline'`)
750
+ * for a given `RecordProcessID` or `MJ: ML Models` `ModelID` (`MLModelID`).
751
+ *
752
+ * Important semantics:
753
+ * - Champion rows are upserted in place by `ValueKeyHash` (`EntityID + RecordID + FeatureName`), so each
754
+ * window holds values *computed* (i.e. changed) in that window rather than a full historical population
755
+ * snapshot.
756
+ * - Each challenger row computed in the evaluation window is paired with the latest champion row for the
757
+ * same record and feature (the latest champion value is all that exists). A champion that has not changed keeps
758
+ * its old `ComputedAt`, so champions older than the windows are read for pairing only (one batched read).
759
+ * - An ML Model Record Process with no challenger configured writes no Feature Values, so it has no drift
760
+ * population and the sweep reports `InsufficientData: true` for it.
761
+ * - `MJ: Feature Values` rows carry no latency metrics, so the scheduled sweep reports no P95 latency
762
+ * ratio (`LatencyRatio` is evaluated only when callers pass inline latencies).
763
+ */
764
+ export async function LoadFeatureAndPredictionDriftFromFeatureValues(options) {
765
+ const windows = resolveDriftWindows(options);
766
+ const maxRows = resolveDriftMaxRows(options.MaxRows);
767
+ const results = await RunView.FromMetadataProvider(options.Provider).RunViews(featureValueDriftViews(options, windows, maxRows), options.ContextUser);
768
+ if (results.length !== 2 || results.some((r) => !r?.Success)) {
769
+ throw new Error(`Failed to load MJ: Feature Values for drift evaluation: ${results.find((r) => r && !r.Success)?.ErrorMessage ?? 'unknown error'}`);
770
+ }
771
+ const capped = capDriftWindows(results.map((r) => r.Results ?? []), maxRows, options.RecordProcessID ?? options.ModelID ?? '');
772
+ const [pairingChampions] = await loadPairingChampions([capped.Rows], windows, options);
773
+ const modelID = processChampionMLModelID(capped.Rows, pairingChampions);
774
+ const problemTypes = options.ProblemType
775
+ ? new UUIDMap()
776
+ : await loadModelProblemTypes([modelID], options);
777
+ return {
778
+ ...buildDriftInputFromRows(capped.Rows, windows, withChampionProblemType(options, modelID, problemTypes), pairingChampions),
779
+ Truncated: capped.Truncated,
780
+ };
781
+ }
782
+ /**
783
+ * Drift inputs for several record processes in one batched `RunViews` round trip (one bounded view per
784
+ * process), so a sweep never reads in a loop. A failed view is reported for its own process only.
785
+ * Sweeps are chunked in batches of {@link DRIFT_SWEEP_BATCH_SIZE} (10).
786
+ */
787
+ export async function LoadFeatureAndPredictionDriftForRecordProcesses(recordProcessIDs, options) {
788
+ const maxRows = resolveDriftMaxRows(options.MaxRows);
789
+ if (recordProcessIDs.length === 0) {
790
+ return [];
791
+ }
792
+ const windows = resolveDriftWindows(options);
793
+ const allLoads = [];
794
+ for (let c = 0; c < recordProcessIDs.length; c += DRIFT_SWEEP_BATCH_SIZE) {
795
+ const chunkIDs = recordProcessIDs.slice(c, c + DRIFT_SWEEP_BATCH_SIZE);
796
+ const perProcess = chunkIDs.map((id) => ({
797
+ ...options,
798
+ RecordProcessID: id,
799
+ }));
800
+ // Two views per process (baseline window, evaluation window), all in one round trip.
801
+ const results = await RunView.FromMetadataProvider(options.Provider).RunViews(perProcess.flatMap((o) => featureValueDriftViews(o, windows, maxRows)), options.ContextUser);
802
+ const chunkLoads = perProcess.map((o, i) => {
803
+ const recordProcessID = o.RecordProcessID ?? '';
804
+ const windowResults = [results[2 * i], results[2 * i + 1]];
805
+ if (windowResults.some((r) => !r?.Success)) {
806
+ return {
807
+ RecordProcessID: recordProcessID,
808
+ ErrorMessage: `Failed to load MJ: Feature Values for drift evaluation: ${windowResults.find((r) => r && !r.Success)?.ErrorMessage ?? 'unknown error'}`,
809
+ };
810
+ }
811
+ return {
812
+ RecordProcessID: recordProcessID,
813
+ Options: o,
814
+ Capped: capDriftWindows(windowResults.map((r) => r?.Results ?? []), maxRows, recordProcessID),
815
+ };
816
+ });
817
+ // One pairing read for the chunk (champions older than the windows), then one ML Models read: each ML process's
818
+ // ProblemType comes from its champion's model.
819
+ const loadedRows = chunkLoads.map((l) => ('Capped' in l && l.Capped ? l.Capped.Rows : []));
820
+ const pairingChampions = await loadPairingChampions(loadedRows, windows, options);
821
+ const modelIDs = loadedRows.map((rows, i) => processChampionMLModelID(rows, pairingChampions[i]));
822
+ const problemTypes = options.ProblemType
823
+ ? new UUIDMap()
824
+ : await loadModelProblemTypes(modelIDs, options);
825
+ chunkLoads.forEach((load, i) => {
826
+ if (!('Capped' in load) || !load.Capped) {
827
+ allLoads.push(load);
828
+ return;
829
+ }
830
+ allLoads.push({
831
+ RecordProcessID: load.RecordProcessID,
832
+ Input: {
833
+ ...buildDriftInputFromRows(load.Capped.Rows, windows, withChampionProblemType(load.Options, modelIDs[i], problemTypes), pairingChampions[i]),
834
+ Truncated: load.Capped.Truncated,
835
+ },
836
+ });
837
+ });
838
+ }
839
+ return allLoads;
840
+ }
841
+ /**
842
+ * Splits loaded Feature Value rows into the two windows' feature distributions and champion/challenger pairs.
843
+ * `pairingChampions` (champion rows older than the windows, newest first) only pair challengers that have no champion
844
+ * in `rows`; they never enter a window.
845
+ */
846
+ function buildDriftInputFromRows(rows, windows, options, pairingChampions = []) {
847
+ const championByFeature = new Map();
848
+ const latestChampionByRecordFeature = new Map();
849
+ const challengerRows = [];
850
+ for (const row of rows) {
851
+ if (row.Source && row.Source !== 'Pipeline') {
852
+ continue;
853
+ }
854
+ const rowTs = new Date(row.ComputedAt).getTime();
855
+ if (row.Role === 'Challenger') {
856
+ if (rowTs >= windows.EvaluationStartMs) {
857
+ challengerRows.push(row);
858
+ }
859
+ }
860
+ else {
861
+ const featureName = row.FeatureName || 'Prediction';
862
+ const list = championByFeature.get(featureName) ?? [];
863
+ list.push(row);
864
+ championByFeature.set(featureName, list);
865
+ latestChampionByRecordFeature.set(`${row.RecordID}::${featureName}`, row);
866
+ }
867
+ }
868
+ for (const row of pairingChampions) {
869
+ const key = pairingKey(row);
870
+ if (!latestChampionByRecordFeature.has(key)) {
871
+ latestChampionByRecordFeature.set(key, row);
872
+ }
873
+ }
874
+ const numericFeatures = {};
875
+ const categoricalFeatures = {};
876
+ const baselineConfidences = [];
877
+ const evaluationConfidences = [];
878
+ for (const [featureName, featureRows] of championByFeature.entries()) {
879
+ const sorted = [...featureRows].sort((a, b) => new Date(a.ComputedAt).getTime() - new Date(b.ComputedAt).getTime());
880
+ const baselineWindow = sorted.filter((r) => {
881
+ const ts = new Date(r.ComputedAt).getTime();
882
+ return ts >= windows.BaselineStartMs && ts < windows.BaselineEndMs;
883
+ });
884
+ const evalWindow = sorted.filter((r) => new Date(r.ComputedAt).getTime() >= windows.EvaluationStartMs);
885
+ const hasNumeric = sorted.some((r) => typeof r.ValueNumeric === 'number');
886
+ const hasCategorical = sorted.some((r) => typeof r.ValueText === 'string' && r.ValueNumeric === null);
887
+ if (hasNumeric) {
888
+ numericFeatures[featureName] = {
889
+ Baseline: baselineWindow.map((r) => (typeof r.ValueNumeric === 'number' ? r.ValueNumeric : null)),
890
+ Evaluation: evalWindow.map((r) => (typeof r.ValueNumeric === 'number' ? r.ValueNumeric : null)),
891
+ };
892
+ }
893
+ else if (hasCategorical) {
894
+ categoricalFeatures[featureName] = {
895
+ Baseline: baselineWindow.map((r) => (typeof r.ValueText === 'string' ? r.ValueText : null)),
896
+ Evaluation: evalWindow.map((r) => (typeof r.ValueText === 'string' ? r.ValueText : null)),
897
+ };
898
+ }
899
+ for (const r of baselineWindow) {
900
+ if (typeof r.Confidence === 'number' && Number.isFinite(r.Confidence)) {
901
+ baselineConfidences.push(r.Confidence);
902
+ }
903
+ }
904
+ for (const r of evalWindow) {
905
+ if (typeof r.Confidence === 'number' && Number.isFinite(r.Confidence)) {
906
+ evaluationConfidences.push(r.Confidence);
907
+ }
908
+ }
909
+ }
910
+ const pairs = [];
911
+ for (const chall of challengerRows) {
912
+ const champ = latestChampionByRecordFeature.get(pairingKey(chall));
913
+ const reasoning = chall.Reasoning ?? '';
914
+ const isTimeout = reasoning.includes('SHADOW_TIMEOUT');
915
+ const isError = reasoning.includes('SHADOW_ERROR');
916
+ pairs.push({
917
+ RecordID: chall.RecordID,
918
+ ChampionScore: typeof champ?.ValueNumeric === 'number' ? champ.ValueNumeric : undefined,
919
+ ChallengerScore: typeof chall.ValueNumeric === 'number' ? chall.ValueNumeric : undefined,
920
+ ChampionLabel: typeof champ?.ValueText === 'string' ? champ.ValueText : undefined,
921
+ ChallengerLabel: typeof chall.ValueText === 'string' ? chall.ValueText : undefined,
922
+ TimedOut: isTimeout ? true : undefined,
923
+ ErrorMessage: isError ? reasoning : undefined,
924
+ });
925
+ }
926
+ return {
927
+ ModelID: options.ModelID,
928
+ RecordProcessID: options.RecordProcessID,
929
+ NumericFeatures: Object.keys(numericFeatures).length > 0 ? numericFeatures : undefined,
930
+ CategoricalFeatures: Object.keys(categoricalFeatures).length > 0 ? categoricalFeatures : undefined,
931
+ ConfidenceAndDivergence: {
932
+ BaselineConfidences: baselineConfidences,
933
+ EvaluationConfidences: evaluationConfidences,
934
+ Pairs: pairs,
935
+ MinSampleSize: options.MinSampleSize,
936
+ ProblemType: options.ProblemType,
937
+ },
938
+ WarningPSIThreshold: options.WarningPSIThreshold,
939
+ CriticalPSIThreshold: options.CriticalPSIThreshold,
940
+ Epsilon: options.Epsilon,
941
+ MinSampleSize: options.MinSampleSize,
942
+ };
943
+ }
944
+ /**
945
+ * Statistical PSI-backed implementation of {@link IDriftDetector} for `MaintenanceEngine`.
946
+ * Only `OverallSeverity === 'Critical'` sets `drifted: true` (triggering automatic retraining);
947
+ * `Warning` severity alerts via `ShouldAlert` without triggering retrain.
948
+ */
949
+ export class PSIDriftDetector {
950
+ constructor(providerFn, warningThreshold = PSI_WARNING_THRESHOLD, criticalThreshold = PSI_CRITICAL_THRESHOLD, minSampleSize = DEFAULT_MIN_SAMPLE_SIZE) {
951
+ this.providerFn = providerFn;
952
+ this.warningThreshold = warningThreshold;
953
+ this.criticalThreshold = criticalThreshold;
954
+ this.minSampleSize = minSampleSize;
955
+ }
956
+ async detectDrift(context) {
957
+ let input;
958
+ if (this.providerFn) {
959
+ input = await this.providerFn(context.modelId);
960
+ }
961
+ else if (context.provider && (context.recordProcessId || context.modelId)) {
962
+ input = await LoadFeatureAndPredictionDriftFromFeatureValues({
963
+ RecordProcessID: context.recordProcessId,
964
+ ModelID: context.modelId,
965
+ Provider: context.provider,
966
+ ContextUser: context.contextUser,
967
+ WarningPSIThreshold: this.warningThreshold,
968
+ CriticalPSIThreshold: this.criticalThreshold,
969
+ MinSampleSize: this.minSampleSize,
970
+ });
971
+ }
972
+ else {
973
+ return {
974
+ drifted: false,
975
+ score: 0,
976
+ detail: 'No feature distribution provider configured for PSIDriftDetector.',
977
+ };
978
+ }
979
+ const report = EvaluateFeatureAndPredictionDrift({
980
+ ...input,
981
+ ModelID: context.modelId,
982
+ RecordProcessID: context.recordProcessId ?? input.RecordProcessID,
983
+ WarningPSIThreshold: input.WarningPSIThreshold ?? this.warningThreshold,
984
+ CriticalPSIThreshold: input.CriticalPSIThreshold ?? this.criticalThreshold,
985
+ MinSampleSize: input.MinSampleSize ?? this.minSampleSize,
986
+ });
987
+ return {
988
+ drifted: report.OverallSeverity === 'Critical',
989
+ score: report.MaxPSI,
990
+ detail: report.Summary,
991
+ };
992
+ }
993
+ }
994
+ function computePercentile(values, quantile) {
995
+ if (values.length === 0) {
996
+ return null;
997
+ }
998
+ const sorted = [...values].sort((a, b) => a - b);
999
+ const pos = Math.min(sorted.length - 1, Math.max(0, Math.ceil(quantile * sorted.length) - 1));
1000
+ return sorted[pos];
1001
+ }
1002
+ //# sourceMappingURL=psi-drift-detector.js.map