@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.
- package/README.md +16 -11
- package/dist/actions/base-predictive-studio.action.d.ts +7 -0
- package/dist/actions/base-predictive-studio.action.d.ts.map +1 -1
- package/dist/actions/base-predictive-studio.action.js +22 -0
- package/dist/actions/base-predictive-studio.action.js.map +1 -1
- package/dist/actions/driver-classes.d.ts +2 -0
- package/dist/actions/driver-classes.d.ts.map +1 -1
- package/dist/actions/driver-classes.js +2 -0
- package/dist/actions/driver-classes.js.map +1 -1
- package/dist/actions/evaluate-drift.action.d.ts +100 -0
- package/dist/actions/evaluate-drift.action.d.ts.map +1 -0
- package/dist/actions/evaluate-drift.action.js +512 -0
- package/dist/actions/evaluate-drift.action.js.map +1 -0
- package/dist/actions/index.d.ts +3 -0
- package/dist/actions/index.d.ts.map +1 -1
- package/dist/actions/index.js +7 -0
- package/dist/actions/index.js.map +1 -1
- package/dist/actions/migrate-pipelines.action.d.ts +19 -0
- package/dist/actions/migrate-pipelines.action.d.ts.map +1 -0
- package/dist/actions/migrate-pipelines.action.js +51 -0
- package/dist/actions/migrate-pipelines.action.js.map +1 -0
- package/dist/actions/promote-model.action.d.ts +12 -1
- package/dist/actions/promote-model.action.d.ts.map +1 -1
- package/dist/actions/promote-model.action.js +7 -2
- package/dist/actions/promote-model.action.js.map +1 -1
- package/dist/actions/promote-model.gate.d.ts +31 -2
- package/dist/actions/promote-model.gate.d.ts.map +1 -1
- package/dist/actions/promote-model.gate.js +84 -5
- package/dist/actions/promote-model.gate.js.map +1 -1
- package/dist/actions/run-experiment.action.d.ts.map +1 -1
- package/dist/actions/run-experiment.action.js +5 -4
- package/dist/actions/run-experiment.action.js.map +1 -1
- package/dist/actions/schedule-model-scoring.action.js +2 -2
- package/dist/actions/schedule-model-scoring.action.js.map +1 -1
- package/dist/actions/score-record-set.action.js +1 -1
- package/dist/actions/score-record-set.action.js.map +1 -1
- package/dist/actions/score-record-set.runner.d.ts +2 -2
- package/dist/actions/score-record-set.runner.js +3 -3
- package/dist/actions/score-record-set.runner.js.map +1 -1
- package/dist/actions/train-model.action.d.ts +28 -25
- package/dist/actions/train-model.action.d.ts.map +1 -1
- package/dist/actions/train-model.action.js +50 -39
- package/dist/actions/train-model.action.js.map +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/modeling-plan-to-pipeline.d.ts +0 -2
- package/dist/agent/modeling-plan-to-pipeline.d.ts.map +1 -1
- package/dist/agent/modeling-plan-to-pipeline.js +30 -39
- package/dist/agent/modeling-plan-to-pipeline.js.map +1 -1
- package/dist/agent/pipeline-builder-agent.d.ts +47 -18
- package/dist/agent/pipeline-builder-agent.d.ts.map +1 -1
- package/dist/agent/pipeline-builder-agent.js +161 -92
- package/dist/agent/pipeline-builder-agent.js.map +1 -1
- package/dist/agent/pipeline-builder.d.ts +178 -56
- package/dist/agent/pipeline-builder.d.ts.map +1 -1
- package/dist/agent/pipeline-builder.js +333 -234
- package/dist/agent/pipeline-builder.js.map +1 -1
- package/dist/experiment/budget.d.ts +61 -0
- package/dist/experiment/budget.d.ts.map +1 -0
- package/dist/experiment/budget.js +72 -0
- package/dist/experiment/budget.js.map +1 -0
- package/dist/experiment/experiment-orchestrator.d.ts +43 -7
- package/dist/experiment/experiment-orchestrator.d.ts.map +1 -1
- package/dist/experiment/experiment-orchestrator.js +130 -33
- package/dist/experiment/experiment-orchestrator.js.map +1 -1
- package/dist/experiment/index.d.ts +2 -0
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +2 -0
- package/dist/experiment/index.js.map +1 -1
- package/dist/experiment/leaderboard.d.ts +15 -15
- package/dist/experiment/leaderboard.d.ts.map +1 -1
- package/dist/experiment/leaderboard.js +44 -18
- package/dist/experiment/leaderboard.js.map +1 -1
- package/dist/experiment/scores.d.ts +32 -0
- package/dist/experiment/scores.d.ts.map +1 -0
- package/dist/experiment/scores.js +62 -0
- package/dist/experiment/scores.js.map +1 -0
- package/dist/experiment/seams.d.ts +23 -20
- package/dist/experiment/seams.d.ts.map +1 -1
- package/dist/experiment/seams.js +54 -56
- package/dist/experiment/seams.js.map +1 -1
- package/dist/experiment/types.d.ts +55 -10
- package/dist/experiment/types.d.ts.map +1 -1
- package/dist/experiment/types.js.map +1 -1
- package/dist/feature-assembly/as-of/as-of-assembler.d.ts +412 -0
- package/dist/feature-assembly/as-of/as-of-assembler.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/as-of-assembler.js +1239 -0
- package/dist/feature-assembly/as-of/as-of-assembler.js.map +1 -0
- package/dist/feature-assembly/as-of/feature-resolution.d.ts +84 -0
- package/dist/feature-assembly/as-of/feature-resolution.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/feature-resolution.js +229 -0
- package/dist/feature-assembly/as-of/feature-resolution.js.map +1 -0
- package/dist/feature-assembly/as-of/index.d.ts +15 -0
- package/dist/feature-assembly/as-of/index.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/index.js +15 -0
- package/dist/feature-assembly/as-of/index.js.map +1 -0
- package/dist/feature-assembly/as-of/read-by-keys.d.ts +30 -0
- package/dist/feature-assembly/as-of/read-by-keys.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/read-by-keys.js +51 -0
- package/dist/feature-assembly/as-of/read-by-keys.js.map +1 -0
- package/dist/feature-assembly/as-of/record-history.d.ts +256 -0
- package/dist/feature-assembly/as-of/record-history.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/record-history.js +505 -0
- package/dist/feature-assembly/as-of/record-history.js.map +1 -0
- package/dist/feature-assembly/as-of/refusal.d.ts +19 -0
- package/dist/feature-assembly/as-of/refusal.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/refusal.js +13 -0
- package/dist/feature-assembly/as-of/refusal.js.map +1 -0
- package/dist/feature-assembly/as-of/series-features.d.ts +65 -0
- package/dist/feature-assembly/as-of/series-features.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/series-features.js +97 -0
- package/dist/feature-assembly/as-of/series-features.js.map +1 -0
- package/dist/feature-assembly/as-of/windowed-aggregate.d.ts +36 -0
- package/dist/feature-assembly/as-of/windowed-aggregate.d.ts.map +1 -0
- package/dist/feature-assembly/as-of/windowed-aggregate.js +99 -0
- package/dist/feature-assembly/as-of/windowed-aggregate.js.map +1 -0
- package/dist/feature-assembly/as-of.d.ts +1 -9
- package/dist/feature-assembly/as-of.d.ts.map +1 -1
- package/dist/feature-assembly/as-of.js +2 -19
- package/dist/feature-assembly/as-of.js.map +1 -1
- package/dist/feature-assembly/assembly-metadata.d.ts +34 -0
- package/dist/feature-assembly/assembly-metadata.d.ts.map +1 -0
- package/dist/feature-assembly/assembly-metadata.js +26 -0
- package/dist/feature-assembly/assembly-metadata.js.map +1 -0
- package/dist/feature-assembly/data-access.d.ts +21 -2
- package/dist/feature-assembly/data-access.d.ts.map +1 -1
- package/dist/feature-assembly/data-access.js +14 -0
- package/dist/feature-assembly/data-access.js.map +1 -1
- package/dist/feature-assembly/feature-assembly-executor.d.ts.map +1 -1
- package/dist/feature-assembly/feature-assembly-executor.js +5 -2
- package/dist/feature-assembly/feature-assembly-executor.js.map +1 -1
- package/dist/feature-assembly/index.d.ts +3 -0
- package/dist/feature-assembly/index.d.ts.map +1 -1
- package/dist/feature-assembly/index.js +3 -0
- package/dist/feature-assembly/index.js.map +1 -1
- package/dist/feature-assembly/leakage-guard.d.ts +1 -1
- package/dist/feature-assembly/leakage-guard.js +1 -1
- package/dist/feature-assembly/read-policy.d.ts +27 -0
- package/dist/feature-assembly/read-policy.d.ts.map +1 -0
- package/dist/feature-assembly/read-policy.js +63 -0
- package/dist/feature-assembly/read-policy.js.map +1 -0
- package/dist/feature-pipelines/feature-pipeline-engine.d.ts.map +1 -1
- package/dist/feature-pipelines/feature-pipeline-engine.js +3 -1
- package/dist/feature-pipelines/feature-pipeline-engine.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -4
- package/dist/index.js.map +1 -1
- package/dist/maintenance/index.d.ts +1 -0
- package/dist/maintenance/index.d.ts.map +1 -1
- package/dist/maintenance/index.js +1 -0
- package/dist/maintenance/index.js.map +1 -1
- package/dist/maintenance/maintenance-engine.d.ts +16 -19
- package/dist/maintenance/maintenance-engine.d.ts.map +1 -1
- package/dist/maintenance/maintenance-engine.js +53 -53
- package/dist/maintenance/maintenance-engine.js.map +1 -1
- package/dist/maintenance/metrics.d.ts +19 -15
- package/dist/maintenance/metrics.d.ts.map +1 -1
- package/dist/maintenance/metrics.js +29 -24
- package/dist/maintenance/metrics.js.map +1 -1
- package/dist/maintenance/psi-drift-detector.d.ts +246 -0
- package/dist/maintenance/psi-drift-detector.d.ts.map +1 -0
- package/dist/maintenance/psi-drift-detector.js +1002 -0
- package/dist/maintenance/psi-drift-detector.js.map +1 -0
- package/dist/maintenance/types.d.ts +11 -2
- package/dist/maintenance/types.d.ts.map +1 -1
- package/dist/maintenance/types.js.map +1 -1
- package/dist/migration/index.d.ts +8 -0
- package/dist/migration/index.d.ts.map +1 -0
- package/dist/migration/index.js +8 -0
- package/dist/migration/index.js.map +1 -0
- package/dist/migration/legacy-pipeline-migration.d.ts +138 -0
- package/dist/migration/legacy-pipeline-migration.d.ts.map +1 -0
- package/dist/migration/legacy-pipeline-migration.js +273 -0
- package/dist/migration/legacy-pipeline-migration.js.map +1 -0
- package/dist/operations/delegation.d.ts +58 -46
- package/dist/operations/delegation.d.ts.map +1 -1
- package/dist/operations/delegation.js +90 -77
- package/dist/operations/delegation.js.map +1 -1
- package/dist/operations/promote-model.operation.d.ts +2 -2
- package/dist/operations/promote-model.operation.d.ts.map +1 -1
- package/dist/operations/promote-model.operation.js +6 -2
- package/dist/operations/promote-model.operation.js.map +1 -1
- package/dist/operations/refusals.d.ts +5 -0
- package/dist/operations/refusals.d.ts.map +1 -1
- package/dist/operations/refusals.js +26 -1
- package/dist/operations/refusals.js.map +1 -1
- package/dist/operations/start-experiment-session.operation.js +3 -3
- package/dist/operations/train-model.mapping.d.ts +91 -0
- package/dist/operations/train-model.mapping.d.ts.map +1 -0
- package/dist/operations/train-model.mapping.js +145 -0
- package/dist/operations/train-model.mapping.js.map +1 -0
- package/dist/operations/train-model.operation.d.ts +14 -9
- package/dist/operations/train-model.operation.d.ts.map +1 -1
- package/dist/operations/train-model.operation.js +30 -51
- package/dist/operations/train-model.operation.js.map +1 -1
- package/dist/prediction-unit/decision-date-advance.d.ts +46 -0
- package/dist/prediction-unit/decision-date-advance.d.ts.map +1 -0
- package/dist/prediction-unit/decision-date-advance.js +79 -0
- package/dist/prediction-unit/decision-date-advance.js.map +1 -0
- package/dist/prediction-unit/index.d.ts +12 -0
- package/dist/prediction-unit/index.d.ts.map +1 -0
- package/dist/prediction-unit/index.js +12 -0
- package/dist/prediction-unit/index.js.map +1 -0
- package/dist/prediction-unit/target-validation.d.ts +21 -0
- package/dist/prediction-unit/target-validation.d.ts.map +1 -0
- package/dist/prediction-unit/target-validation.js +54 -0
- package/dist/prediction-unit/target-validation.js.map +1 -0
- package/dist/prediction-unit/unit-row-reader.d.ts +108 -0
- package/dist/prediction-unit/unit-row-reader.d.ts.map +1 -0
- package/dist/prediction-unit/unit-row-reader.js +348 -0
- package/dist/prediction-unit/unit-row-reader.js.map +1 -0
- package/dist/prediction-unit/unit-store.d.ts +28 -0
- package/dist/prediction-unit/unit-store.d.ts.map +1 -0
- package/dist/prediction-unit/unit-store.js +41 -0
- package/dist/prediction-unit/unit-store.js.map +1 -0
- package/dist/prediction-unit/unit-versioning.d.ts +43 -0
- package/dist/prediction-unit/unit-versioning.d.ts.map +1 -0
- package/dist/prediction-unit/unit-versioning.js +71 -0
- package/dist/prediction-unit/unit-versioning.js.map +1 -0
- package/dist/protocol/index.d.ts +9 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +9 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/protocol/protocol-defaults.d.ts +37 -0
- package/dist/protocol/protocol-defaults.d.ts.map +1 -0
- package/dist/protocol/protocol-defaults.js +59 -0
- package/dist/protocol/protocol-defaults.js.map +1 -0
- package/dist/protocol/protocol-versioning.d.ts +46 -0
- package/dist/protocol/protocol-versioning.d.ts.map +1 -0
- package/dist/protocol/protocol-versioning.js +48 -0
- package/dist/protocol/protocol-versioning.js.map +1 -0
- package/dist/protocol/search-guard.d.ts +45 -0
- package/dist/protocol/search-guard.d.ts.map +1 -0
- package/dist/protocol/search-guard.js +50 -0
- package/dist/protocol/search-guard.js.map +1 -0
- package/dist/scoring/artifact-loader.d.ts +5 -32
- package/dist/scoring/artifact-loader.d.ts.map +1 -1
- package/dist/scoring/artifact-loader.js +4 -59
- package/dist/scoring/artifact-loader.js.map +1 -1
- package/dist/scoring/auto-train.d.ts +25 -5
- package/dist/scoring/auto-train.d.ts.map +1 -1
- package/dist/scoring/auto-train.js +48 -31
- package/dist/scoring/auto-train.js.map +1 -1
- package/dist/scoring/index.d.ts +3 -0
- package/dist/scoring/index.d.ts.map +1 -1
- package/dist/scoring/index.js +3 -0
- package/dist/scoring/index.js.map +1 -1
- package/dist/scoring/ml-model-inference-processor.d.ts +137 -10
- package/dist/scoring/ml-model-inference-processor.d.ts.map +1 -1
- package/dist/scoring/ml-model-inference-processor.js +383 -40
- package/dist/scoring/ml-model-inference-processor.js.map +1 -1
- package/dist/scoring/model-readiness.d.ts +45 -0
- package/dist/scoring/model-readiness.d.ts.map +1 -1
- package/dist/scoring/model-readiness.js +49 -0
- package/dist/scoring/model-readiness.js.map +1 -1
- package/dist/scoring/register.d.ts +8 -3
- package/dist/scoring/register.d.ts.map +1 -1
- package/dist/scoring/register.js +28 -4
- package/dist/scoring/register.js.map +1 -1
- package/dist/scoring/seams.d.ts +18 -2
- package/dist/scoring/seams.d.ts.map +1 -1
- package/dist/scoring/seams.js +35 -10
- package/dist/scoring/seams.js.map +1 -1
- package/dist/scoring/shadow-scoring.d.ts +245 -0
- package/dist/scoring/shadow-scoring.d.ts.map +1 -0
- package/dist/scoring/shadow-scoring.js +510 -0
- package/dist/scoring/shadow-scoring.js.map +1 -0
- package/dist/scoring/startup-register.d.ts +3 -3
- package/dist/scoring/startup-register.d.ts.map +1 -1
- package/dist/scoring/startup-register.js +10 -4
- package/dist/scoring/startup-register.js.map +1 -1
- package/dist/scoring/storage-provider-artifact-loader.d.ts +14 -0
- package/dist/scoring/storage-provider-artifact-loader.d.ts.map +1 -0
- package/dist/scoring/storage-provider-artifact-loader.js +47 -0
- package/dist/scoring/storage-provider-artifact-loader.js.map +1 -0
- package/dist/scoring/training-keys.d.ts +27 -0
- package/dist/scoring/training-keys.d.ts.map +1 -0
- package/dist/scoring/training-keys.js +54 -0
- package/dist/scoring/training-keys.js.map +1 -0
- package/dist/scoring/types.d.ts +72 -7
- package/dist/scoring/types.d.ts.map +1 -1
- package/dist/scoring/types.js +4 -0
- package/dist/scoring/types.js.map +1 -1
- package/dist/sidecar-provider.d.ts +2 -2
- package/dist/sidecar-provider.js +3 -3
- package/dist/snapshot/code-version.d.ts +16 -0
- package/dist/snapshot/code-version.d.ts.map +1 -0
- package/dist/snapshot/code-version.js +39 -0
- package/dist/snapshot/code-version.js.map +1 -0
- package/dist/snapshot/holdout-carver.d.ts +110 -0
- package/dist/snapshot/holdout-carver.d.ts.map +1 -0
- package/dist/snapshot/holdout-carver.js +171 -0
- package/dist/snapshot/holdout-carver.js.map +1 -0
- package/dist/snapshot/index.d.ts +17 -0
- package/dist/snapshot/index.d.ts.map +1 -0
- package/dist/snapshot/index.js +17 -0
- package/dist/snapshot/index.js.map +1 -0
- package/dist/snapshot/snapshot-builder.d.ts +152 -0
- package/dist/snapshot/snapshot-builder.d.ts.map +1 -0
- package/dist/snapshot/snapshot-builder.js +286 -0
- package/dist/snapshot/snapshot-builder.js.map +1 -0
- package/dist/snapshot/snapshot-file-store.d.ts +161 -0
- package/dist/snapshot/snapshot-file-store.d.ts.map +1 -0
- package/dist/snapshot/snapshot-file-store.js +204 -0
- package/dist/snapshot/snapshot-file-store.js.map +1 -0
- package/dist/snapshot/snapshot-hash.d.ts +6 -0
- package/dist/snapshot/snapshot-hash.d.ts.map +1 -0
- package/dist/snapshot/snapshot-hash.js +16 -0
- package/dist/snapshot/snapshot-hash.js.map +1 -0
- package/dist/snapshot/snapshot-manifest.d.ts +43 -0
- package/dist/snapshot/snapshot-manifest.d.ts.map +1 -0
- package/dist/snapshot/snapshot-manifest.js +43 -0
- package/dist/snapshot/snapshot-manifest.js.map +1 -0
- package/dist/snapshot/snapshot-retrainer.d.ts +107 -0
- package/dist/snapshot/snapshot-retrainer.d.ts.map +1 -0
- package/dist/snapshot/snapshot-retrainer.js +194 -0
- package/dist/snapshot/snapshot-retrainer.js.map +1 -0
- package/dist/snapshot/snapshot-serialization.d.ts +99 -0
- package/dist/snapshot/snapshot-serialization.d.ts.map +1 -0
- package/dist/snapshot/snapshot-serialization.js +191 -0
- package/dist/snapshot/snapshot-serialization.js.map +1 -0
- package/dist/snapshot/training-snapshot-store.d.ts +38 -0
- package/dist/snapshot/training-snapshot-store.d.ts.map +1 -0
- package/dist/snapshot/training-snapshot-store.js +41 -0
- package/dist/snapshot/training-snapshot-store.js.map +1 -0
- package/dist/storage/ps-storage-provider.d.ts +108 -0
- package/dist/storage/ps-storage-provider.d.ts.map +1 -0
- package/dist/storage/ps-storage-provider.js +154 -0
- package/dist/storage/ps-storage-provider.js.map +1 -0
- package/dist/training/artifact-store.d.ts +12 -103
- package/dist/training/artifact-store.d.ts.map +1 -1
- package/dist/training/artifact-store.js +13 -137
- package/dist/training/artifact-store.js.map +1 -1
- package/dist/training/compute-cost.d.ts +23 -0
- package/dist/training/compute-cost.d.ts.map +1 -0
- package/dist/training/compute-cost.js +36 -0
- package/dist/training/compute-cost.js.map +1 -0
- package/dist/training/evaluation-protocol-store.d.ts +53 -0
- package/dist/training/evaluation-protocol-store.d.ts.map +1 -0
- package/dist/training/evaluation-protocol-store.js +54 -0
- package/dist/training/evaluation-protocol-store.js.map +1 -0
- package/dist/training/index.d.ts +9 -1
- package/dist/training/index.d.ts.map +1 -1
- package/dist/training/index.js +9 -1
- package/dist/training/index.js.map +1 -1
- package/dist/training/locked-holdout.d.ts +19 -4
- package/dist/training/locked-holdout.d.ts.map +1 -1
- package/dist/training/locked-holdout.js +29 -5
- package/dist/training/locked-holdout.js.map +1 -1
- package/dist/training/seams.d.ts +34 -8
- package/dist/training/seams.d.ts.map +1 -1
- package/dist/training/seams.js +74 -18
- package/dist/training/seams.js.map +1 -1
- package/dist/training/storage-provider-artifact-store.d.ts +49 -0
- package/dist/training/storage-provider-artifact-store.d.ts.map +1 -0
- package/dist/training/storage-provider-artifact-store.js +147 -0
- package/dist/training/storage-provider-artifact-store.js.map +1 -0
- package/dist/training/trainer-model-lineage.d.ts +32 -0
- package/dist/training/trainer-model-lineage.d.ts.map +1 -0
- package/dist/training/trainer-model-lineage.js +62 -0
- package/dist/training/trainer-model-lineage.js.map +1 -0
- package/dist/training/trainer-request.d.ts +50 -0
- package/dist/training/trainer-request.d.ts.map +1 -0
- package/dist/training/trainer-request.js +65 -0
- package/dist/training/trainer-request.js.map +1 -0
- package/dist/training/trainer-result.d.ts +30 -0
- package/dist/training/trainer-result.d.ts.map +1 -0
- package/dist/training/trainer-result.js +40 -0
- package/dist/training/trainer-result.js.map +1 -0
- package/dist/training/training-engine.d.ts +417 -64
- package/dist/training/training-engine.d.ts.map +1 -1
- package/dist/training/training-engine.js +869 -178
- package/dist/training/training-engine.js.map +1 -1
- package/dist/training/training-refusal.d.ts +15 -0
- package/dist/training/training-refusal.d.ts.map +1 -0
- package/dist/training/training-refusal.js +62 -0
- package/dist/training/training-refusal.js.map +1 -0
- package/dist/training/types.d.ts +133 -41
- package/dist/training/types.d.ts.map +1 -1
- package/dist/training/types.js +4 -4
- package/dist/training/unit-model-lineage.d.ts +72 -0
- package/dist/training/unit-model-lineage.d.ts.map +1 -0
- package/dist/training/unit-model-lineage.js +288 -0
- package/dist/training/unit-model-lineage.js.map +1 -0
- package/package.json +16 -13
- package/dist/operations/__tests__/helpers.d.ts +0 -30
- package/dist/operations/__tests__/helpers.d.ts.map +0 -1
- package/dist/operations/__tests__/helpers.js +0 -44
- package/dist/operations/__tests__/helpers.js.map +0 -1
|
@@ -0,0 +1,1239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module feature-assembly/as-of/as-of-assembler
|
|
3
|
+
*
|
|
4
|
+
* The one assembly function for training and scoring. Every value is read as of the row's decision day from a dated
|
|
5
|
+
* source; every column is typed; refusals name what is wrong and there is no partial matrix. Values are read by key
|
|
6
|
+
* through the same functions in both contexts, so a row assembled for training and for scoring at the same decision
|
|
7
|
+
* date is identical.
|
|
8
|
+
*
|
|
9
|
+
* "As of the decision day" means everything recorded on or before that UTC day: a change or an effective date counts
|
|
10
|
+
* when it falls before the start of the following day.
|
|
11
|
+
*
|
|
12
|
+
* Current values: a value read from the stored row (an `immutable-field` source, the key field a row joins through, or
|
|
13
|
+
* the fields a windowed aggregate reads from its child rows) is used only when it is the value the row held on every
|
|
14
|
+
* decision day. A field the metadata declares not updatable is read (on a tracked entity its history is read too, only
|
|
15
|
+
* to learn when the record was created); an updatable field is read only when the entity
|
|
16
|
+
* tracks Record Changes, its history covers the decision day (else `decision-date-before-change-history`, naming where
|
|
17
|
+
* the history starts) and none of them updated it afterwards (else `select-changes-after-decision-date`); an updatable
|
|
18
|
+
* field of an untracked entity refuses `decision-date-before-change-history`, since its past value cannot be known.
|
|
19
|
+
* Both refusals count distinct unit rows. One rule covers a row whose decision day is on or after the assembly's own
|
|
20
|
+
* UTC day (`AssembledAt`, the clock training and scoring are run with), for a field read directly, replayed, as a join
|
|
21
|
+
* key or as a child row's field: on a tracked entity the history is consulted first, and only where it does not reach
|
|
22
|
+
* that day (no history, or one that starts after it) is the stored value read, as covered — except that a history
|
|
23
|
+
* whose rows in force end in a Delete reads as deleted even with a current row and no anchor, on every reader and for a
|
|
24
|
+
* field declared not updatable; a history that does not reach a past decision day excludes the row under
|
|
25
|
+
* exclude-and-count on both updatable readers (the replayed field and the stored read of an updatable field); a field
|
|
26
|
+
* declared not updatable reads its stored value there, as it does through a continuity mismatch; on the stored-value
|
|
27
|
+
* reader of an updatable field a change row after
|
|
28
|
+
* the decision outranks the coverage judgement and refuses `select-changes-after-decision-date` under either policy
|
|
29
|
+
* (the precedence of stored-read verdicts is deleted, created after, changed after the decision, continuity mismatch
|
|
30
|
+
* and an ineligible external row, coverage, value: a later change refuses through a mismatch); a covering history replays
|
|
31
|
+
* (or, read directly, refuses an update dated after the day, exactly as for a past day). On an untracked entity
|
|
32
|
+
* nothing can be consulted, so the stored value is read for such a row. A record created after the decision day still
|
|
33
|
+
* reads as missing. Rows with a past decision day keep the rule above. On any decision day, past or later, a record
|
|
34
|
+
* whose history reaches the day but cannot be replayed (a continuity mismatch, a deletion, an ineligible external row)
|
|
35
|
+
* makes the rows reading it uncovered, read directly or replayed alike; it never reads the stored value, except for a
|
|
36
|
+
* field declared not updatable read directly, which reads its stored value through a continuity mismatch, an
|
|
37
|
+
* ineligible external row and an unreached history by the not-updatable rule above (only a deletion, the creation
|
|
38
|
+
* instant and an earlier incarnation are consulted for it: a record re-created after the decision day reads the
|
|
39
|
+
* incarnation that stood then, from the Delete row that ended it). Child rows are judged for the whole batch, against the earliest decision day: a child row re-owned or re-dated
|
|
40
|
+
* after a decision day can move between owners, so every child row read passes the rule for its owner key, date, value
|
|
41
|
+
* and filter fields (void and end dates are compared with the decision day and need no check), and one the rule
|
|
42
|
+
* excludes makes every unit row uncovered. On a child entity that tracks Record Changes, the child rows include every
|
|
43
|
+
* child hard-deleted since (its history ends in a Delete, no current row is left) that an owner of the batch ever held:
|
|
44
|
+
* for an owner row decided while it stood (its Delete at or after the row's as-of instant) it is read and judged on its
|
|
45
|
+
* Delete row exactly as a present child is; for a row decided after its Delete it is absent, neither counted nor judged.
|
|
46
|
+
* A child row, or the unit row a join key is read through, deleted and re-created after a decision day is read for
|
|
47
|
+
* that day from the Delete row that ended the incarnation standing then (the child's owner key, date, value and filter
|
|
48
|
+
* fields; the unit row's key field), as a field declared not updatable is, never from the re-created row.
|
|
49
|
+
*
|
|
50
|
+
* Coverage: every Record Changes history the assembly reads (replayed fields and the stable-value rule) is reported in
|
|
51
|
+
* the result's `Coverage`, one entry per entity and field. A history is loaded once per assembly for one entity, field
|
|
52
|
+
* list and key set, however many features read it (a windowed aggregate loads its child entity's history over every
|
|
53
|
+
* child row it read, present and hard-deleted, judged or not, so each child record is counted once); two loads of one
|
|
54
|
+
* field (other keys, another join, a child entity) merge: no history start wins, else the later start, and the
|
|
55
|
+
* continuity counts add.
|
|
56
|
+
*
|
|
57
|
+
* Record creation: a record created after a row's decision day did not exist then, so its value reads as missing
|
|
58
|
+
* (version `created-after-decision`), never the stored value and never as uncovered. When creation is known: on an
|
|
59
|
+
* entity that tracks Record Changes, from the record's own Create row (a history that starts with a Snapshot says
|
|
60
|
+
* nothing about creation, and the column below is consulted instead); on any entity that lists `__mj_CreatedAt`, from
|
|
61
|
+
* that column, unless the history holds a change row before the column's instant other than its own opening Create
|
|
62
|
+
* (an earlier incarnation: the column then dates a re-creation and is ignored); when both tell, the later of the two (a record is never read before either
|
|
63
|
+
* says it existed); when neither tells, the unit's premise that its records exist on their decision days applies. The rule
|
|
64
|
+
* is consulted on every current read: fields declared not updatable and the key a unit row joins through included,
|
|
65
|
+
* and by the stable-value rule before it judges a history that starts after the decision day. A
|
|
66
|
+
* unit row created after its decision day resolves its join key as null, so every value read through that key is
|
|
67
|
+
* missing. A child row created after an owner row's decision day (late-entered) is dropped from that owner's window
|
|
68
|
+
* before its aggregate is computed; the number of drops is recorded on the column's provenance (`lateEnteredDropped`).
|
|
69
|
+
*
|
|
70
|
+
* System timestamp columns: `__mj_CreatedAt` and `__mj_UpdatedAt` are requested only when the entity's metadata lists
|
|
71
|
+
* them. An immutable field's provenance carries the record's creation instant when it is known (version
|
|
72
|
+
* `created:<instant>`), else the record key only (version `immutable-after-create`, computed at the assembly time);
|
|
73
|
+
* without `__mj_UpdatedAt`, a windowed aggregate's version hashes the IDs of the child rows it read.
|
|
74
|
+
*
|
|
75
|
+
* Categorical columns: when a column has more distinct levels than its encoding's `cardinalityCap`, the least frequent
|
|
76
|
+
* levels beyond the cap (by count, ties by value) fold into one `__other` level, recorded on the column's provenance.
|
|
77
|
+
* The kept levels are a fitted encoding step, like the sidecar's one-hot vocabulary: training returns them
|
|
78
|
+
* (`CategoryLevels` on the result) and scoring passes them back (`CategoryLevels` on the input), so a value is folded
|
|
79
|
+
* the same way in both contexts; a value not among the kept levels becomes `__other` and nothing is recounted. A
|
|
80
|
+
* scoring assembly without training's levels for a categorical column fails, and so does a stored value equal to
|
|
81
|
+
* `__other`, which the fold could not tell apart from folded levels.
|
|
82
|
+
* One-hot is the only categorical method the sidecar fits; any other method fails loudly.
|
|
83
|
+
*/
|
|
84
|
+
import { createHash } from 'node:crypto';
|
|
85
|
+
import { UtcDay, MS_PER_DAY } from '@memberjunction/predictive-studio-core';
|
|
86
|
+
import { EscapeSQLString, OrdinalCompare } from '@memberjunction/global';
|
|
87
|
+
import { CompleteReader } from '../read-policy.js';
|
|
88
|
+
import { KeyedReader } from './read-by-keys.js';
|
|
89
|
+
import { RecordHistory } from './record-history.js';
|
|
90
|
+
import { AssemblyRefused } from './refusal.js';
|
|
91
|
+
import { WindowedAggregates } from './windowed-aggregate.js';
|
|
92
|
+
import { SeriesFeatures } from './series-features.js';
|
|
93
|
+
/** How severe a verdict is: a read's verdict is its most severe one over its rows' decision instants. */
|
|
94
|
+
const STABLE_OUTCOME_SEVERITY = { 'created-after': 0, stable: 1, excluded: 2, uncovered: 3, changed: 4 };
|
|
95
|
+
/** The level the least frequent categories beyond a column's cardinality cap fold into. */
|
|
96
|
+
export const OTHER_CATEGORY_LEVEL = '__other';
|
|
97
|
+
/** The Feature Value columns a pinned read selects. */
|
|
98
|
+
const FEATURE_VALUE_FIELDS = ['ID', 'RecordID', 'EffectiveAsOf', 'ComputedAt', 'ValueNumeric', 'ValueText', 'ValueBoolean', 'ValueDate'];
|
|
99
|
+
export class AsOfFeatureAssembler {
|
|
100
|
+
/** Impute (with a missing indicator) every column, one-hot every categorical, then the pipeline's explicit ops. */
|
|
101
|
+
static BuildPreprocessingOps(columns, features, explicit = []) {
|
|
102
|
+
const ops = [];
|
|
103
|
+
const byFeature = new Map(features.map((f) => [f.name, f]));
|
|
104
|
+
for (const c of columns) {
|
|
105
|
+
const f = byFeature.get(c.FeatureName);
|
|
106
|
+
if (!f)
|
|
107
|
+
continue;
|
|
108
|
+
const fill = f.missing.impute === 'constant' && f.missing.constant !== null ? { fillValue: f.missing.constant } : {};
|
|
109
|
+
ops.push({ op: 'impute', col: c.Name, strategy: f.missing.impute, ...fill, indicator: f.missing.indicator });
|
|
110
|
+
if (c.Encoding === 'categorical')
|
|
111
|
+
ops.push({ op: 'onehot', col: c.Name });
|
|
112
|
+
}
|
|
113
|
+
return [...ops, ...explicit];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Adapter for the training step and the sidecar request: matrix + schema + preprocessing. With `labels` the label is
|
|
117
|
+
* appended as `labelColumn` (training); with null no label column is added (scoring).
|
|
118
|
+
*/
|
|
119
|
+
static ToFeatureAssemblyResult(assembled, labels, labelColumn) {
|
|
120
|
+
const names = assembled.Columns.map((c) => c.Name);
|
|
121
|
+
return {
|
|
122
|
+
matrix: {
|
|
123
|
+
columns: labels === null ? names : [...names, labelColumn],
|
|
124
|
+
// `??`: a label of 0 is a real label (count tasks); only a missing one becomes null.
|
|
125
|
+
rows: assembled.Rows.map((r) => (labels === null ? [...r.Values] : [...r.Values, labels.get(r.RowID) ?? null])),
|
|
126
|
+
},
|
|
127
|
+
featureSchema: assembled.Columns.map((c) => ({ Name: c.Name, Kind: c.Encoding === 'categorical' ? 'categorical' : 'numeric' })),
|
|
128
|
+
preprocessing: [...assembled.Preprocessing],
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** Assembles the dated matrix, or the first refusal met (caught with `instanceof`, never by message). */
|
|
132
|
+
async Assemble(input) {
|
|
133
|
+
try {
|
|
134
|
+
return await this.assemble(input);
|
|
135
|
+
}
|
|
136
|
+
catch (e) {
|
|
137
|
+
if (e instanceof AssemblyRefused)
|
|
138
|
+
return { Status: 'refused', Refusal: e.Refusal };
|
|
139
|
+
throw e;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async assemble(input) {
|
|
143
|
+
const state = { Coverage: new Map(), Histories: new Map(), LateEntered: new Map() };
|
|
144
|
+
const readers = await this.buildReaders(input, state);
|
|
145
|
+
const columns = readers.flatMap((r) => AsOfFeatureAssembler.ColumnsFor(r.Spec));
|
|
146
|
+
const assembled = this.assembleRows(input, readers);
|
|
147
|
+
const first = assembled.Uncovered[0];
|
|
148
|
+
if (input.Unit.history.onUncoveredRow === 'refuse' && first) {
|
|
149
|
+
throw new AssemblyRefused({ kind: 'decision-date-before-change-history', entity: first.Entity, field: first.Field, historyStart: first.HistoryStart, rowsAffected: first.Rows });
|
|
150
|
+
}
|
|
151
|
+
const counted = input.DevelopmentRowsOf ? input.DevelopmentRowsOf(assembled.Rows) : null;
|
|
152
|
+
const folded = AsOfFeatureAssembler.foldCategoricals(columns, input.Features, assembled.Rows, counted, input.CategoryLevels, input.Context);
|
|
153
|
+
return {
|
|
154
|
+
Status: 'assembled',
|
|
155
|
+
Columns: columns,
|
|
156
|
+
Rows: folded.Rows,
|
|
157
|
+
ExcludedRowIDs: assembled.Excluded,
|
|
158
|
+
UncoveredRowsExcluded: assembled.Uncovered.map((u) => ({ entity: u.Entity, field: u.Field, rows: u.Rows })),
|
|
159
|
+
Coverage: [...state.Coverage.values()],
|
|
160
|
+
Preprocessing: AsOfFeatureAssembler.BuildPreprocessingOps(columns, input.Features, input.ExplicitOps || []),
|
|
161
|
+
ColumnProvenance: readers.map((r) => AsOfFeatureAssembler.columnProvenance(r.Spec, input, state, folded.Folds.get(r.Spec.name))),
|
|
162
|
+
CategoryLevels: folded.Levels,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
static columnProvenance(spec, input, state, fold) {
|
|
166
|
+
const base = { column: spec.name, source: spec.source.kind, sourceRef: AsOfFeatureAssembler.describeSource(spec), sourceVersion: AsOfFeatureAssembler.columnVersion(spec, input, state) };
|
|
167
|
+
const dropped = state.LateEntered.get(spec.name);
|
|
168
|
+
const withDrops = dropped === undefined ? base : { ...base, lateEnteredDropped: dropped };
|
|
169
|
+
return fold && fold.folded.length > 0 ? { ...withDrops, categoryFold: fold } : withDrops;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Caps every categorical column's levels. With training's kept levels for a column (`given`), every other value becomes
|
|
173
|
+
* `__other`. Otherwise the levels are counted over the `counted` rows (every row when null) and the most frequent
|
|
174
|
+
* `cap` of them are kept (count descending, then value ascending, so the fold is deterministic); every value of any
|
|
175
|
+
* row outside the kept levels becomes `__other` and is listed as folded. Returns the kept levels of every categorical
|
|
176
|
+
* column and the fold of each column that folded anything.
|
|
177
|
+
*/
|
|
178
|
+
static foldCategoricals(columns, features, rows, counted, given, context) {
|
|
179
|
+
const byFeature = new Map(features.map((f) => [f.name, f]));
|
|
180
|
+
const folds = new Map();
|
|
181
|
+
const levels = new Map();
|
|
182
|
+
const kept = new Map();
|
|
183
|
+
columns.forEach((c, i) => {
|
|
184
|
+
const encoding = byFeature.get(c.FeatureName)?.encoding;
|
|
185
|
+
if (c.Encoding !== 'categorical' || !encoding || encoding.kind !== 'categorical')
|
|
186
|
+
return;
|
|
187
|
+
const values = rows.map((r) => r.Values[i]);
|
|
188
|
+
AsOfFeatureAssembler.assertFoldable(c.Name, values, given, context);
|
|
189
|
+
// The kept levels: training's, else those of the counted rows; every row is then folded to them, as scoring folds.
|
|
190
|
+
const countedValues = counted === null ? null : rows.filter((r) => counted.has(r.RowID)).map((r) => r.Values[i]);
|
|
191
|
+
const keptLevels = given?.get(c.Name) || (countedValues === null ? undefined : AsOfFeatureAssembler.levelFold(countedValues, encoding.cardinalityCap, undefined).kept);
|
|
192
|
+
const fold = AsOfFeatureAssembler.levelFold(values, encoding.cardinalityCap, keptLevels);
|
|
193
|
+
levels.set(c.Name, fold.kept);
|
|
194
|
+
folds.set(c.Name, fold);
|
|
195
|
+
if (fold.folded.length > 0)
|
|
196
|
+
kept.set(i, new Set(fold.kept));
|
|
197
|
+
});
|
|
198
|
+
if (kept.size === 0)
|
|
199
|
+
return { Rows: [...rows], Folds: folds, Levels: levels };
|
|
200
|
+
const foldedRows = rows.map((r) => ({ ...r, Values: r.Values.map((v, i) => AsOfFeatureAssembler.foldedValue(v, kept.get(i))) }));
|
|
201
|
+
return { Rows: foldedRows, Folds: folds, Levels: levels };
|
|
202
|
+
}
|
|
203
|
+
/** A string outside its column's kept levels becomes the other level; a column with no fold (no kept set) keeps its values. */
|
|
204
|
+
static foldedValue(v, keptLevels) {
|
|
205
|
+
return typeof v === 'string' && keptLevels !== undefined && !keptLevels.has(v) ? OTHER_CATEGORY_LEVEL : v;
|
|
206
|
+
}
|
|
207
|
+
/** A column the fold cannot treat honestly fails: scoring without training's levels, or a stored `__other` value. */
|
|
208
|
+
static assertFoldable(column, values, given, context) {
|
|
209
|
+
if (context === 'score' && !given?.has(column)) {
|
|
210
|
+
throw new Error(`Column ${column}: a scoring assembly needs the categorical levels training kept for it, and none were given`);
|
|
211
|
+
}
|
|
212
|
+
if (values.some((v) => v === OTHER_CATEGORY_LEVEL)) {
|
|
213
|
+
throw new Error(`Column ${column}: a stored value equals the fold level "${OTHER_CATEGORY_LEVEL}", which would merge it with folded levels`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The kept and folded levels of one column's values. With `trained` levels the kept levels are exactly those and the
|
|
218
|
+
* folded ones are the other values seen; without, the most frequent `cap` levels are kept.
|
|
219
|
+
*/
|
|
220
|
+
static levelFold(values, cap, trained) {
|
|
221
|
+
const counts = new Map();
|
|
222
|
+
for (const v of values)
|
|
223
|
+
if (typeof v === 'string')
|
|
224
|
+
counts.set(v, (counts.get(v) || 0) + 1);
|
|
225
|
+
const ordered = [...counts.entries()].sort((a, b) => b[1] - a[1] || OrdinalCompare(a[0], b[0])).map(([level]) => level);
|
|
226
|
+
if (trained) {
|
|
227
|
+
const keep = new Set(trained);
|
|
228
|
+
return { kept: [...trained], folded: ordered.filter((level) => !keep.has(level)) };
|
|
229
|
+
}
|
|
230
|
+
return { kept: ordered.slice(0, cap), folded: ordered.slice(cap) };
|
|
231
|
+
}
|
|
232
|
+
/** One dated reader per non-identifier column; record-changes readers append their coverage. */
|
|
233
|
+
async buildReaders(input, state) {
|
|
234
|
+
const readers = [];
|
|
235
|
+
for (const spec of input.Features) {
|
|
236
|
+
if (!AsOfFeatureAssembler.isAssembled(spec))
|
|
237
|
+
continue;
|
|
238
|
+
AsOfFeatureAssembler.assertEncodable(spec);
|
|
239
|
+
readers.push({ Spec: spec, Read: await this.readerFor(spec, input, state) });
|
|
240
|
+
}
|
|
241
|
+
return readers;
|
|
242
|
+
}
|
|
243
|
+
/** One-hot is the only categorical method the sidecar fits; any other is a pipeline the assembly cannot honour. */
|
|
244
|
+
static assertEncodable(spec) {
|
|
245
|
+
if (spec.encoding.kind === 'categorical' && spec.encoding.method !== 'onehot') {
|
|
246
|
+
throw new Error(`Column ${spec.name}: the categorical method "${spec.encoding.method}" is not supported; only one-hot is fitted`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Reads every row through every reader. A row with an uncovered value is excluded; every reader still runs, so the row
|
|
251
|
+
* is counted once against each entity/field it is uncovered for (in the order first met), and the `refuse` policy can
|
|
252
|
+
* name the first one with its row count. An excluded row's other values are not encoded.
|
|
253
|
+
*/
|
|
254
|
+
assembleRows(input, readers) {
|
|
255
|
+
const out = { Rows: [], Excluded: new Set(), Uncovered: [] };
|
|
256
|
+
const tallies = new Map();
|
|
257
|
+
for (const row of input.Rows) {
|
|
258
|
+
const values = [];
|
|
259
|
+
const provenance = [];
|
|
260
|
+
const uncovered = [];
|
|
261
|
+
for (const r of readers) {
|
|
262
|
+
const raw = r.Read(row);
|
|
263
|
+
if ('Uncovered' in raw) {
|
|
264
|
+
if (!uncovered.some((u) => u.Entity === raw.Entity && u.Field === raw.Field))
|
|
265
|
+
uncovered.push(raw);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (uncovered.length > 0)
|
|
269
|
+
continue;
|
|
270
|
+
values.push(...this.encode(r.Spec, raw.Value, row.DecisionDate));
|
|
271
|
+
provenance.push(raw.Provenance);
|
|
272
|
+
}
|
|
273
|
+
if (uncovered.length === 0) {
|
|
274
|
+
out.Rows.push({ RowID: row.RowID, Values: values, Provenance: provenance });
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
out.Excluded.add(row.RowID);
|
|
278
|
+
for (const u of uncovered)
|
|
279
|
+
AsOfFeatureAssembler.tally(tallies, out.Uncovered, u);
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
/** Counts one uncovered row against its entity/field. */
|
|
284
|
+
static tally(tallies, ordered, u) {
|
|
285
|
+
const k = `${u.Entity}|${u.Field}`;
|
|
286
|
+
const existing = tallies.get(k);
|
|
287
|
+
if (existing) {
|
|
288
|
+
existing.Rows++;
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const created = { Entity: u.Entity, Field: u.Field, HistoryStart: u.HistoryStart, Rows: 1 };
|
|
292
|
+
tallies.set(k, created);
|
|
293
|
+
ordered.push(created);
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* The names of the matrix columns the assembly writes for these feature columns, in order: one per column, one per
|
|
297
|
+
* date part of a date column (`<name>__<part>`), none for an identifier. The assembler names its columns with
|
|
298
|
+
* {@link ColumnsFor}, so a caller that needs the names before assembling (training checks a protocol's slice fields
|
|
299
|
+
* against them) gets exactly the assembled names.
|
|
300
|
+
*/
|
|
301
|
+
static ColumnNamesOf(features) {
|
|
302
|
+
return features.filter((spec) => AsOfFeatureAssembler.isAssembled(spec)).flatMap((spec) => AsOfFeatureAssembler.ColumnsFor(spec).map((c) => c.Name));
|
|
303
|
+
}
|
|
304
|
+
/** An identifier column is excluded from the matrix; every other feature column is assembled. */
|
|
305
|
+
static isAssembled(spec) {
|
|
306
|
+
return spec.encoding.kind !== 'identifier';
|
|
307
|
+
}
|
|
308
|
+
/** The matrix columns one feature column is written as (its date parts for a date column). */
|
|
309
|
+
static ColumnsFor(spec) {
|
|
310
|
+
const source = AsOfFeatureAssembler.describeSource(spec);
|
|
311
|
+
if (spec.encoding.kind === 'date-parts') {
|
|
312
|
+
return spec.encoding.parts.map((p) => ({ Name: `${spec.name}__${p.replace(/-/g, '_')}`, Encoding: 'numeric', SourceColumn: source, FeatureName: spec.name }));
|
|
313
|
+
}
|
|
314
|
+
return [{ Name: spec.name, Encoding: spec.encoding.kind === 'boolean' ? 'numeric' : spec.encoding.kind, SourceColumn: source, FeatureName: spec.name }];
|
|
315
|
+
}
|
|
316
|
+
/** Typed encoding: no variant writes 0 for a value it cannot read; non-numeric text in a numeric column refuses. */
|
|
317
|
+
encode(spec, value, decision) {
|
|
318
|
+
const missing = value === null || value === undefined || (typeof value === 'string' && value.trim() === '');
|
|
319
|
+
switch (spec.encoding.kind) {
|
|
320
|
+
case 'numeric': return [missing ? null : AsOfFeatureAssembler.numberOf(spec, value)];
|
|
321
|
+
case 'boolean': return [missing ? null : AsOfFeatureAssembler.booleanOf(spec, value)];
|
|
322
|
+
case 'categorical': return [missing ? null : value instanceof Date ? UtcDay.UtcDayIso(value) : String(value).trim()];
|
|
323
|
+
case 'date-parts': return this.encodeDateParts(spec, spec.encoding.parts, missing ? null : value, decision);
|
|
324
|
+
case 'identifier': return [];
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** A present value as a finite number; a boolean reads as 1/0, a date or text that is not a number refuses. */
|
|
328
|
+
static numberOf(spec, value) {
|
|
329
|
+
const n = typeof value === 'number' ? value
|
|
330
|
+
: typeof value === 'boolean' ? (value ? 1 : 0)
|
|
331
|
+
: value instanceof Date ? Number.NaN
|
|
332
|
+
: Number(String(value).trim());
|
|
333
|
+
if (!Number.isFinite(n)) {
|
|
334
|
+
throw new AssemblyRefused({ kind: 'non-numeric-in-numeric-column', column: spec.name, sampleValue: value instanceof Date ? value.toISOString() : String(value) });
|
|
335
|
+
}
|
|
336
|
+
return n;
|
|
337
|
+
}
|
|
338
|
+
/** A present value as 1/0; anything that is not a recognisable boolean refuses. */
|
|
339
|
+
static booleanOf(spec, value) {
|
|
340
|
+
if (value === true || value === 1 || value === '1' || value === 'true')
|
|
341
|
+
return 1;
|
|
342
|
+
if (value === false || value === 0 || value === '0' || value === 'false')
|
|
343
|
+
return 0;
|
|
344
|
+
throw new AssemblyRefused({ kind: 'non-numeric-in-numeric-column', column: spec.name, sampleValue: String(value) });
|
|
345
|
+
}
|
|
346
|
+
/** Date parts of a dated value; a value that is not a date refuses (never 0). */
|
|
347
|
+
encodeDateParts(spec, parts, value, decision) {
|
|
348
|
+
const day = value === null ? null : UtcDay.ToUtcDay(value);
|
|
349
|
+
if (value !== null && day === null)
|
|
350
|
+
throw new AssemblyRefused({ kind: 'non-numeric-in-numeric-column', column: spec.name, sampleValue: String(value) });
|
|
351
|
+
const decisionDay = AsOfFeatureAssembler.decisionDay(decision);
|
|
352
|
+
return parts.map((p) => {
|
|
353
|
+
if (day === null)
|
|
354
|
+
return null;
|
|
355
|
+
switch (p) {
|
|
356
|
+
case 'days-since-decision': return Math.round((decisionDay.getTime() - day.getTime()) / MS_PER_DAY);
|
|
357
|
+
case 'year': return day.getUTCFullYear();
|
|
358
|
+
case 'month': return day.getUTCMonth() + 1;
|
|
359
|
+
case 'dow': return day.getUTCDay();
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
async readerFor(spec, input, state) {
|
|
364
|
+
const source = spec.source;
|
|
365
|
+
switch (source.kind) {
|
|
366
|
+
case 'immutable-field':
|
|
367
|
+
case 'record-changes': return this.fieldReader(spec, source, input, state);
|
|
368
|
+
case 'windowed-aggregate': return this.aggregateReader(spec, source, input, state);
|
|
369
|
+
case 'series': return this.seriesReader(spec, source, input);
|
|
370
|
+
case 'feature-value': return this.featureValueReader(spec, source, input);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* A field read as of the decision day: replayed from Record Changes (updatable fields), or read from the stored row
|
|
375
|
+
* when the stable-value rule says the stored value is the value on every decision day.
|
|
376
|
+
*/
|
|
377
|
+
async fieldReader(spec, source, input, state) {
|
|
378
|
+
const entity = source.entity === input.RowEntity.Name ? input.RowEntity : input.Metadata.Entity(source.entity);
|
|
379
|
+
if (!entity)
|
|
380
|
+
throw new AssemblyRefused({ kind: 'unresolved-column', entity: source.entity, field: source.field });
|
|
381
|
+
const join = await this.keyResolver(source.keyField, input, (row) => row.RowID, state);
|
|
382
|
+
const keyOf = join.KeyOf;
|
|
383
|
+
if (source.kind === 'immutable-field')
|
|
384
|
+
return AsOfFeatureAssembler.throughJoin(spec, join, await this.currentValueReader(spec, source, entity, keyOf, input, state), input);
|
|
385
|
+
if (entity.Fields.some((f) => f.Name === source.field && f.IsVirtual))
|
|
386
|
+
return AsOfFeatureAssembler.throughJoin(spec, join, await AsOfFeatureAssembler.virtualFieldReader(spec, source, entity, keyOf, input), input);
|
|
387
|
+
const today = input.Rows.filter((r) => AsOfFeatureAssembler.onAssemblyDayOrLater(r, input));
|
|
388
|
+
const keysOf = (rs) => rs.map((r) => keyOf(r)).filter((k) => k !== null);
|
|
389
|
+
const history = await AsOfFeatureAssembler.loadHistory(entity, keysOf(input.Rows), [source.field], input, state);
|
|
390
|
+
const stored = today.length > 0 ? await AsOfFeatureAssembler.presentOrDeleted(entity, keysOf(today), [source.field], input, async () => history) : new Map();
|
|
391
|
+
const createdAt = await AsOfFeatureAssembler.storedCreatedAts(entity, history, keysOf(input.Rows), input);
|
|
392
|
+
return AsOfFeatureAssembler.throughJoin(spec, join, this.replayReader(spec, source, entity, keyOf, { History: history, Stored: stored, CreatedAt: createdAt }, input), input);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* `__mj_CreatedAt` of the records whose history gives no creation instant (it starts with a Snapshot, or is empty),
|
|
396
|
+
* read by key in one read; empty, with no read, when the entity does not list the column or every history starts
|
|
397
|
+
* with a Create row. A hard-deleted record's is the one its Delete row recorded (null when it recorded none). The keys
|
|
398
|
+
* go to the read as given (the keyed read matches case-insensitively and keys its rows lower-cased); a lower-cased key
|
|
399
|
+
* would miss a mixed-case key on a case-sensitive collation.
|
|
400
|
+
*/
|
|
401
|
+
static async storedCreatedAts(entity, history, keys, input) {
|
|
402
|
+
const none = new Map();
|
|
403
|
+
if (!AsOfFeatureAssembler.hasField(entity, '__mj_CreatedAt'))
|
|
404
|
+
return none;
|
|
405
|
+
const unknown = AsOfFeatureAssembler.uniqueKeys(keys).filter((k) => history.CreatedAt(k) === null);
|
|
406
|
+
if (unknown.length === 0)
|
|
407
|
+
return none;
|
|
408
|
+
const rows = await AsOfFeatureAssembler.presentOrDeleted(entity, unknown, ['__mj_CreatedAt'], input, async () => history);
|
|
409
|
+
return new Map(AsOfFeatureAssembler.uniqueKeys(unknown).map((k) => [k.toLowerCase(), AsOfFeatureAssembler.storedFieldOf(rows, history, k, '__mj_CreatedAt', input)]));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* A virtual field: the entity's view joins it from a related record, so its stored value is that record's value
|
|
413
|
+
* today and no history replays it. It is read by the module's one rule for rows decided on the assembly's day or
|
|
414
|
+
* later (the stored value is the value on that day); a row decided earlier refuses the whole read (`virtual-field`),
|
|
415
|
+
* since nothing can say what the joined value was then.
|
|
416
|
+
*/
|
|
417
|
+
static async virtualFieldReader(spec, source, entity, keyOf, input) {
|
|
418
|
+
if (input.Rows.some((r) => !AsOfFeatureAssembler.onAssemblyDayOrLater(r, input)))
|
|
419
|
+
throw new AssemblyRefused({ kind: 'virtual-field', entity: entity.Name, field: source.field });
|
|
420
|
+
const keys = input.Rows.map((r) => keyOf(r)).filter((k) => k !== null);
|
|
421
|
+
// The history is read only to explain a key with no stored row (a hard-deleted record). Nothing replays a virtual
|
|
422
|
+
// field, so the read records no coverage entry: one would report a continuity check of a field no history serves.
|
|
423
|
+
let history = null;
|
|
424
|
+
const historyOf = async () => {
|
|
425
|
+
history = entity.TrackRecordChanges ? await input.History.Load(entity, AsOfFeatureAssembler.uniqueKeys(keys), [source.field], input.Unit.history, input.AssembledAt) : null;
|
|
426
|
+
return history;
|
|
427
|
+
};
|
|
428
|
+
const stored = keys.length > 0 ? await AsOfFeatureAssembler.presentOrDeleted(entity, keys, [source.field], input, historyOf) : new Map();
|
|
429
|
+
return (row) => {
|
|
430
|
+
const key = keyOf(row);
|
|
431
|
+
return key === null ? AsOfFeatureAssembler.missingValue(spec, 'none', 'none', input) : AsOfFeatureAssembler.storedOnDecisionDay(spec, source, entity, key, row, stored, history, input);
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The stored rows of `keys` with `fields`, by lower-cased key. A key with no row is explained only when the entity's
|
|
436
|
+
* history says the record was hard-deleted (`EntityHistory.DeletedRecordAt` is not null), and its stored values are
|
|
437
|
+
* then read through that history; any other key with no row is a short read. `historyOf` is asked only when a key
|
|
438
|
+
* has no row, and gives null for an entity without change history, which explains no missing key.
|
|
439
|
+
*
|
|
440
|
+
* @throws AssemblyRefused `truncated-read` when a key with no row is not a hard-deleted record
|
|
441
|
+
*/
|
|
442
|
+
static async presentOrDeleted(entity, keys, fields, input, historyOf) {
|
|
443
|
+
const read = await KeyedReader.ReadPresentByKeys(input.DataAccess, entity.Name, entity.PrimaryKey, keys, fields);
|
|
444
|
+
if (read.MissingKeys.length === 0)
|
|
445
|
+
return read.Rows;
|
|
446
|
+
const history = await historyOf();
|
|
447
|
+
if (read.MissingKeys.some((k) => history === null || history.DeletedRecordAt(k, input.AssembledAt) === null)) {
|
|
448
|
+
throw new AssemblyRefused({ kind: 'truncated-read', entity: entity.Name, rowsExpected: read.Rows.size + read.MissingKeys.length, rowsRead: read.Rows.size });
|
|
449
|
+
}
|
|
450
|
+
return read.Rows;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* A field of `key` as stored: from its current row, else from the record a hard-deleted record's Delete row recorded
|
|
454
|
+
* (the instant does not change the recorded row), else null.
|
|
455
|
+
*/
|
|
456
|
+
static storedFieldOf(rows, history, key, field, input) {
|
|
457
|
+
const rec = rows.get(key.toLowerCase());
|
|
458
|
+
if (rec !== undefined)
|
|
459
|
+
return rec[field] ?? null;
|
|
460
|
+
return history?.DeletedRecordAt(key, input.AssembledAt)?.Row.get(field) ?? null;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* The entity's history for `keys` and `fields`, loaded once per assembly for one entity, field list and key set (keys
|
|
464
|
+
* case-folded and deduplicated), so every feature that reads the same records shares one load, and that load's
|
|
465
|
+
* coverage is recorded once.
|
|
466
|
+
*/
|
|
467
|
+
static async loadHistory(entity, keys, fields, input, state) {
|
|
468
|
+
const unique = AsOfFeatureAssembler.uniqueKeys(keys);
|
|
469
|
+
const cacheKey = JSON.stringify([entity.Name, [...fields].sort(OrdinalCompare), unique.map((k) => k.toLowerCase()).sort(OrdinalCompare)]);
|
|
470
|
+
const cached = state.Histories.get(cacheKey);
|
|
471
|
+
if (cached)
|
|
472
|
+
return cached;
|
|
473
|
+
const history = await input.History.Load(entity, unique, fields, input.Unit.history, input.AssembledAt);
|
|
474
|
+
state.Histories.set(cacheKey, history);
|
|
475
|
+
for (const field of fields)
|
|
476
|
+
AsOfFeatureAssembler.recordCoverage(state.Coverage, entity, field, history);
|
|
477
|
+
return history;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Records one history load for one entity and field. A second load of the same field (another key set, through
|
|
481
|
+
* another join or as a child entity's field) merges into the first: no history start wins over any start, else the
|
|
482
|
+
* later start, and the continuity counts add.
|
|
483
|
+
*/
|
|
484
|
+
static recordCoverage(coverage, entity, field, history) {
|
|
485
|
+
const k = `${entity.Name}|${field}`;
|
|
486
|
+
const read = { ...history.Coverage, field };
|
|
487
|
+
const prior = coverage.get(k);
|
|
488
|
+
coverage.set(k, prior ? AsOfFeatureAssembler.mergeCoverage(prior, read) : read);
|
|
489
|
+
}
|
|
490
|
+
static mergeCoverage(a, b) {
|
|
491
|
+
// History starts are ISO instants, so the ordinal order is the time order.
|
|
492
|
+
const historyStart = a.historyStart === null || b.historyStart === null ? null : OrdinalCompare(a.historyStart, b.historyStart) >= 0 ? a.historyStart : b.historyStart;
|
|
493
|
+
return {
|
|
494
|
+
...a,
|
|
495
|
+
historyStart,
|
|
496
|
+
continuity: { checkedAt: a.continuity.checkedAt, recordsReplayed: a.continuity.recordsReplayed + b.continuity.recordsReplayed, recordsMismatched: a.continuity.recordsMismatched + b.continuity.recordsMismatched },
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* The value Record Changes say the field held as of the decision day. A row with no join key has no record to replay,
|
|
501
|
+
* so its value is missing; so is a record created after the decision day. A row the history cannot replay is uncovered,
|
|
502
|
+
* with one exception, the module's one rule: a row decided on the assembly's day or later whose history does not reach
|
|
503
|
+
* that day (no history, or one that starts after it) reads the stored value as covered. A history that reaches the day
|
|
504
|
+
* but cannot be replayed (an ineligible external change, a continuity mismatch, a deletion) stays uncovered.
|
|
505
|
+
*/
|
|
506
|
+
replayReader(spec, source, entity, keyOf, reads, input) {
|
|
507
|
+
return (row) => {
|
|
508
|
+
const key = keyOf(row);
|
|
509
|
+
if (key === null)
|
|
510
|
+
return AsOfFeatureAssembler.missingValue(spec, 'none', 'none', input);
|
|
511
|
+
const history = reads.History;
|
|
512
|
+
const asOf = AsOfFeatureAssembler.asOfInstant(row.DecisionDate);
|
|
513
|
+
const hv = history.ValueAt(key, source.field, asOf);
|
|
514
|
+
if (hv.Status === 'uncovered') {
|
|
515
|
+
// A Delete in force reads as deleted before any other verdict: a record re-created later was not created after the decision.
|
|
516
|
+
if (hv.Reason === 'deleted')
|
|
517
|
+
return { Uncovered: true, Entity: entity.Name, Field: source.field, HistoryStart: history.Coverage.historyStart };
|
|
518
|
+
const unreached = hv.Reason === 'no-history' || hv.Reason === 'before-history-start';
|
|
519
|
+
if (unreached && AsOfFeatureAssembler.onAssemblyDayOrLater(row, input))
|
|
520
|
+
return AsOfFeatureAssembler.storedOnDecisionDay(spec, source, entity, key, row, reads.Stored, history, input);
|
|
521
|
+
if (AsOfFeatureAssembler.createdAfter(history, key, asOf, reads.CreatedAt.get(key.toLowerCase()) ?? null))
|
|
522
|
+
return AsOfFeatureAssembler.missingValue(spec, AsOfFeatureAssembler.fieldRef(entity, key, source.field), 'created-after-decision', input);
|
|
523
|
+
return { Uncovered: true, Entity: entity.Name, Field: source.field, HistoryStart: history.Coverage.historyStart };
|
|
524
|
+
}
|
|
525
|
+
return {
|
|
526
|
+
Value: hv.Value,
|
|
527
|
+
Provenance: { column: spec.name, source: 'record-changes', sourceRef: AsOfFeatureAssembler.fieldRef(entity, key, source.field), sourceVersion: hv.ChangeID, computedAt: hv.ChangedAt.toISOString() },
|
|
528
|
+
};
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* The stored value of a field for a row decided on the assembly's day or later. A key with no stored row is a
|
|
533
|
+
* hard-deleted record (the stored read refused any other, see {@link presentOrDeleted}): it reads the value its
|
|
534
|
+
* Delete row recorded when the Delete is not before the row's as-of instant, and is uncovered (`deleted`) when it is.
|
|
535
|
+
*
|
|
536
|
+
* @throws Error when a key has neither a stored row nor a hard-deleted history: the stored read was built from other keys
|
|
537
|
+
*/
|
|
538
|
+
static storedOnDecisionDay(spec, source, entity, key, row, stored, history, input) {
|
|
539
|
+
const rec = stored.get(key.toLowerCase());
|
|
540
|
+
const sourceRef = AsOfFeatureAssembler.fieldRef(entity, key, source.field);
|
|
541
|
+
if (rec !== undefined)
|
|
542
|
+
return { Value: rec[source.field], Provenance: { column: spec.name, source: 'record-changes', sourceRef, sourceVersion: 'stored-on-decision-day', computedAt: input.AssembledAt.toISOString() } };
|
|
543
|
+
const deleted = history === null ? null : history.DeletedRecordAt(key, AsOfFeatureAssembler.asOfInstant(row.DecisionDate));
|
|
544
|
+
if (history === null || deleted === null)
|
|
545
|
+
throw new Error(`AsOfFeatureAssembler: ${sourceRef} has no stored row and no hard-deleted history; the stored read was built from other keys`);
|
|
546
|
+
if (deleted.Status === 'deleted')
|
|
547
|
+
return { Uncovered: true, Entity: entity.Name, Field: source.field, HistoryStart: history.Coverage.historyStart };
|
|
548
|
+
return { Value: deleted.Row.get(source.field) ?? null, Provenance: { column: spec.name, source: 'record-changes', sourceRef, sourceVersion: deleted.ChangeID, computedAt: deleted.ChangedAt.toISOString() } };
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* The stored value of a field the stable-value rule admits. A record created after a row's decision day (by the one
|
|
552
|
+
* creation rule, `creationInstant`) reads as missing, never as its stored value; a record the rule excludes makes its
|
|
553
|
+
* row uncovered. The provenance carries the creation instant when it is known. A hard-deleted record (no stored row)
|
|
554
|
+
* is read from its Delete row: the value that row recorded when the Delete is not before the row's as-of instant
|
|
555
|
+
* (provenance naming the Delete row), uncovered (`deleted`) when it is. A field declared not updatable of a record
|
|
556
|
+
* re-created after a row's as-of instant reads the incarnation that stood then: the Delete row that ended it
|
|
557
|
+
* ({@link EntityHistory.EarlierIncarnationEnd}), provenance naming that row.
|
|
558
|
+
*/
|
|
559
|
+
async currentValueReader(spec, source, entity, keyOf, input, state) {
|
|
560
|
+
const reads = AsOfFeatureAssembler.rowReads(input.Rows, keyOf);
|
|
561
|
+
const keys = reads.map((r) => r.Key);
|
|
562
|
+
const hasCreatedAt = AsOfFeatureAssembler.hasField(entity, '__mj_CreatedAt');
|
|
563
|
+
// Read first: a key with no record is a short read, whatever the history of the records that exist, unless the
|
|
564
|
+
// history says the record was deleted (the same load the stable-value rule then reuses).
|
|
565
|
+
let history = null;
|
|
566
|
+
const historyOf = async () => {
|
|
567
|
+
history = entity.TrackRecordChanges ? await AsOfFeatureAssembler.loadHistory(entity, keys, [source.field], input, state) : null;
|
|
568
|
+
return history;
|
|
569
|
+
};
|
|
570
|
+
const current = await AsOfFeatureAssembler.presentOrDeleted(entity, keys, hasCreatedAt ? [source.field, '__mj_CreatedAt'] : [source.field], input, historyOf);
|
|
571
|
+
const storedCreatedAt = (key) => (hasCreatedAt ? AsOfFeatureAssembler.storedFieldOf(current, history, key, '__mj_CreatedAt', input) : null);
|
|
572
|
+
const stable = await this.assertStableCurrentValue(entity, source.field, reads, storedCreatedAt, input, state);
|
|
573
|
+
const outcomes = AsOfFeatureAssembler.outcomesByRow(reads, stable);
|
|
574
|
+
const notUpdatable = entity.Fields.some((f) => f.Name === source.field && f.AllowUpdateAPI === false);
|
|
575
|
+
return (row) => {
|
|
576
|
+
const key = keyOf(row);
|
|
577
|
+
if (outcomes.get(row.RowID) === 'excluded')
|
|
578
|
+
return { Uncovered: true, Entity: entity.Name, Field: source.field, HistoryStart: stable.HistoryStart };
|
|
579
|
+
const asOf = AsOfFeatureAssembler.asOfInstant(row.DecisionDate);
|
|
580
|
+
const ended = key === null || !notUpdatable || stable.History === null ? null : stable.History.EarlierIncarnationEnd(key, asOf);
|
|
581
|
+
const rec = key === null || ended !== null ? undefined : current.get(key.toLowerCase());
|
|
582
|
+
const deleted = ended ?? (key === null || rec !== undefined || stable.History === null ? null : stable.History.DeletedRecordAt(key, asOf));
|
|
583
|
+
if (deleted?.Status === 'deleted')
|
|
584
|
+
return { Uncovered: true, Entity: entity.Name, Field: source.field, HistoryStart: stable.HistoryStart };
|
|
585
|
+
const created = key === null ? null : AsOfFeatureAssembler.creationInstant(stable.History, key, storedCreatedAt(key));
|
|
586
|
+
const createdAfter = !AsOfFeatureAssembler.existedBefore(created, asOf);
|
|
587
|
+
const fromDeleteRow = deleted !== null && !createdAfter;
|
|
588
|
+
const version = createdAfter ? 'created-after-decision' : fromDeleteRow ? deleted.ChangeID : created !== null ? `created:${created.toISOString()}` : 'immutable-after-create';
|
|
589
|
+
const value = createdAfter ? null : rec ? rec[source.field] : deleted ? deleted.Row.get(source.field) ?? null : null;
|
|
590
|
+
return {
|
|
591
|
+
Value: value,
|
|
592
|
+
Provenance: {
|
|
593
|
+
column: spec.name, source: 'immutable-field', sourceRef: AsOfFeatureAssembler.fieldRef(entity, key, source.field), sourceVersion: version,
|
|
594
|
+
computedAt: fromDeleteRow ? deleted.ChangedAt.toISOString() : created !== null ? created.toISOString() : input.AssembledAt.toISOString(),
|
|
595
|
+
},
|
|
596
|
+
};
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* The stable-value rule for values read from stored rows: a field, the key field a row joins through, or the fields a
|
|
601
|
+
* windowed aggregate reads from its child rows. Each read is one stored record and the unit rows whose values its
|
|
602
|
+
* stored fields stand for; it is judged at each of those rows' decision instants, and its verdict is the most severe
|
|
603
|
+
* one (`changed`, then `uncovered`, `excluded`, `stable`, and `created-after` only when the record existed at none).
|
|
604
|
+
* The instants at which a read is `excluded` are reported, so a caller can mark only the rows decided then.
|
|
605
|
+
* The stored value stands (`stable`) when the field is declared not updatable, or the entity tracks Record Changes,
|
|
606
|
+
* the history covers that instant and no change row follows it that changed the field or replaced the record (an
|
|
607
|
+
* Update listing it, a Delete, or a row of any type recording a different value). A record created after a row's decision
|
|
608
|
+
* instant did not exist then (`created-after`); one the history cannot replay for another reason (a continuity
|
|
609
|
+
* mismatch, a deletion, an ineligible external row) is `excluded`, as a replayed field treats it. An update after the
|
|
610
|
+
* instant refuses `select-changes-after-decision-date`; a history that starts after it with a Snapshot, or no history,
|
|
611
|
+
* refuses `decision-date-before-change-history` under the `refuse` policy and is `excluded` under `exclude-and-count`,
|
|
612
|
+
* as a replayed field's uncovered row is; both refusals count the distinct unit rows whose own decision instant is
|
|
613
|
+
* affected. A Delete in force at an instant is `excluded` before any other verdict, a field declared not updatable
|
|
614
|
+
* included. An updatable field of an untracked entity cannot be known on a past day and refuses for every unit row.
|
|
615
|
+
* On a tracked entity the history is read for every field, a field declared not updatable included: its stored value
|
|
616
|
+
* is the value since creation, so only the creation instant is consulted for it (the reader reads an earlier
|
|
617
|
+
* incarnation's value from the Delete row that ended it, see `currentValueReader`). Creation follows the one creation
|
|
618
|
+
* rule, so a record whose history starts with a Snapshot after the decision day but whose `__mj_CreatedAt`
|
|
619
|
+
* (`storedCreatedAt`, null when the entity does not list it) is after it too did not exist then, and is not uncovered.
|
|
620
|
+
* The history is loaded over `historyKeys` (by default the reads' keys); a caller that reads other records of the
|
|
621
|
+
* entity too passes the whole key set, so the entity's history is loaded, and its coverage recorded, once.
|
|
622
|
+
*/
|
|
623
|
+
async assertStableCurrentValue(entity, field, reads, storedCreatedAt, input, state, historyKeys = reads.map((r) => r.Key)) {
|
|
624
|
+
const info = entity.Fields.find((f) => f.Name === field);
|
|
625
|
+
if (!info)
|
|
626
|
+
throw new AssemblyRefused({ kind: 'unresolved-column', entity: entity.Name, field });
|
|
627
|
+
const unread = { Outcomes: reads.map(() => 'stable'), ExcludedInstants: new Set(), History: null, HistoryStart: null };
|
|
628
|
+
if (reads.length === 0)
|
|
629
|
+
return unread;
|
|
630
|
+
if (!entity.TrackRecordChanges) {
|
|
631
|
+
if (info.AllowUpdateAPI === false)
|
|
632
|
+
return unread;
|
|
633
|
+
// Only rows decided before the assembly's day are refused: the stored value is the value on today or later.
|
|
634
|
+
const pastRows = AsOfFeatureAssembler.distinctPastRows(reads, input);
|
|
635
|
+
if (pastRows === 0)
|
|
636
|
+
return unread;
|
|
637
|
+
throw new AssemblyRefused({ kind: 'decision-date-before-change-history', entity: entity.Name, field, historyStart: null, rowsAffected: pastRows });
|
|
638
|
+
}
|
|
639
|
+
const history = await AsOfFeatureAssembler.loadHistory(entity, historyKeys, [field], input, state);
|
|
640
|
+
const onDayOrLater = AsOfFeatureAssembler.asOfInstant(input.AssembledAt).getTime();
|
|
641
|
+
// Under exclude-and-count a history that does not reach a past decision day excludes its rows, as a replayed field does.
|
|
642
|
+
const uncoveredVerdict = input.Unit.history.onUncoveredRow === 'refuse' ? 'uncovered' : 'excluded';
|
|
643
|
+
const judgeOnce = (key, at) => {
|
|
644
|
+
if (info.AllowUpdateAPI === false) {
|
|
645
|
+
const hv = history.ValueAt(key, field, at);
|
|
646
|
+
if (hv.Status === 'uncovered' && hv.Reason === 'deleted')
|
|
647
|
+
return 'excluded';
|
|
648
|
+
return AsOfFeatureAssembler.createdAfter(history, key, at, storedCreatedAt(key)) ? 'created-after' : 'stable';
|
|
649
|
+
}
|
|
650
|
+
const verdict = AsOfFeatureAssembler.judgeStoredValue(history, key, field, at, storedCreatedAt(key));
|
|
651
|
+
if (verdict !== 'uncovered')
|
|
652
|
+
return verdict;
|
|
653
|
+
// The replay rule: only a history that does not reach a day on or after the assembly's reads the stored value.
|
|
654
|
+
return at.getTime() >= onDayOrLater ? 'stable' : uncoveredVerdict;
|
|
655
|
+
};
|
|
656
|
+
// A verdict depends on the instant only through the change rows before it, whether the record existed then and
|
|
657
|
+
// whether the instant is on or after the assembly's day; judging each such combination once keeps a child read,
|
|
658
|
+
// judged at every unit row's instant, linear in the instants.
|
|
659
|
+
const verdicts = new Map();
|
|
660
|
+
const judge = (key, at) => {
|
|
661
|
+
const existed = !AsOfFeatureAssembler.createdAfter(history, key, at, storedCreatedAt(key));
|
|
662
|
+
const signature = `${key.toLowerCase()}|${history.RowsBefore(key, at)}|${existed}|${at.getTime() >= onDayOrLater}`;
|
|
663
|
+
const known = verdicts.get(signature);
|
|
664
|
+
if (known !== undefined)
|
|
665
|
+
return known;
|
|
666
|
+
const verdict = judgeOnce(key, at);
|
|
667
|
+
verdicts.set(signature, verdict);
|
|
668
|
+
return verdict;
|
|
669
|
+
};
|
|
670
|
+
const instants = AsOfFeatureAssembler.instantsOf(reads);
|
|
671
|
+
const excludedInstants = new Set();
|
|
672
|
+
const outcomes = reads.map((r) => AsOfFeatureAssembler.outcomeOf(r, AsOfFeatureAssembler.instantsFor(instants, r.Rows), judge, excludedInstants));
|
|
673
|
+
const changed = AsOfFeatureAssembler.affectedRows(reads, outcomes, 'changed', judge);
|
|
674
|
+
if (changed > 0)
|
|
675
|
+
throw new AssemblyRefused({ kind: 'select-changes-after-decision-date', entity: entity.Name, field, changesAfter: changed });
|
|
676
|
+
const uncovered = AsOfFeatureAssembler.affectedRows(reads, outcomes, 'uncovered', judge);
|
|
677
|
+
if (uncovered > 0)
|
|
678
|
+
throw new AssemblyRefused({ kind: 'decision-date-before-change-history', entity: entity.Name, field, historyStart: history.Coverage.historyStart, rowsAffected: uncovered });
|
|
679
|
+
return { Outcomes: outcomes, ExcludedInstants: excludedInstants, History: history, HistoryStart: history.Coverage.historyStart };
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* The rule's verdict on one stored record at one instant, in the stored-read precedence (D3-251): deleted, created
|
|
683
|
+
* after, changed after the decision, then what the replay says (a continuity mismatch or an ineligible external row
|
|
684
|
+
* excludes, an unreached history is uncovered, else the value stands).
|
|
685
|
+
*/
|
|
686
|
+
static judgeStoredValue(history, key, field, at, storedCreatedAt) {
|
|
687
|
+
const hv = history.ValueAt(key, field, at);
|
|
688
|
+
if (hv.Status === 'uncovered' && hv.Reason === 'deleted')
|
|
689
|
+
return 'excluded';
|
|
690
|
+
if (AsOfFeatureAssembler.createdAfter(history, key, at, storedCreatedAt))
|
|
691
|
+
return 'created-after';
|
|
692
|
+
if (history.ChangesAfter(key, field, at) > 0)
|
|
693
|
+
return 'changed';
|
|
694
|
+
if (hv.Status === 'value')
|
|
695
|
+
return 'stable';
|
|
696
|
+
return hv.Reason === 'before-history-start' || hv.Reason === 'no-history' ? 'uncovered' : 'excluded';
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Whether the record came into existence (by the one creation rule, `stored` being its `__mj_CreatedAt` or null) at
|
|
700
|
+
* or after `at`: it did not exist on the decision day `at` closes.
|
|
701
|
+
*/
|
|
702
|
+
static createdAfter(history, key, at, stored) {
|
|
703
|
+
return !AsOfFeatureAssembler.existedBefore(AsOfFeatureAssembler.creationInstant(history, key, stored), at);
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* The one rule for when a record came into existence: its own Create row when the entity tracks Record Changes and
|
|
707
|
+
* its history starts with one; else `__mj_CreatedAt` when the entity lists the column (`stored` is its value for the
|
|
708
|
+
* record); when both are known, the later one, so neither source can make a record readable before the other says it
|
|
709
|
+
* existed; else null, and the unit's premise that its records exist on their decision days applies. A change row
|
|
710
|
+
* before the column's instant (other than the history's own opening Create, which dates the same incarnation) proves
|
|
711
|
+
* an earlier incarnation; the column then dates a re-creation and is ignored, so creation is unknown and the premise
|
|
712
|
+
* applies, unless the history's opening Create dates it.
|
|
713
|
+
*/
|
|
714
|
+
static creationInstant(history, key, stored) {
|
|
715
|
+
const fromHistory = history === null ? null : history.CreatedAt(key);
|
|
716
|
+
const fromColumn = AsOfFeatureAssembler.instantOf(stored);
|
|
717
|
+
const column = fromColumn !== null && AsOfFeatureAssembler.earlierIncarnation(history, key, fromHistory, fromColumn) ? null : fromColumn;
|
|
718
|
+
if (fromHistory === null || column === null)
|
|
719
|
+
return fromHistory || column;
|
|
720
|
+
return fromHistory.getTime() >= column.getTime() ? fromHistory : column;
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Whether the history holds a change row before `columnAt` (the stored `__mj_CreatedAt`) other than its own opening
|
|
724
|
+
* Create (`createdAt`, from {@link EntityHistory.CreatedAt}): the record existed before the column's instant, so the
|
|
725
|
+
* column dates a re-creation.
|
|
726
|
+
*/
|
|
727
|
+
static earlierIncarnation(history, key, createdAt, columnAt) {
|
|
728
|
+
if (history === null)
|
|
729
|
+
return false;
|
|
730
|
+
const openingCreateBefore = createdAt !== null && createdAt.getTime() < columnAt.getTime() ? 1 : 0;
|
|
731
|
+
return history.RowsBefore(key, columnAt) - openingCreateBefore > 0;
|
|
732
|
+
}
|
|
733
|
+
/** Whether a record with creation instant `created` (null = unknown, the premise applies) existed before `at`. */
|
|
734
|
+
static existedBefore(created, at) {
|
|
735
|
+
return created === null || created.getTime() < at.getTime();
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* A read's verdict: the most severe of its verdicts at each of its instants, or `created-after` when the record
|
|
739
|
+
* existed at none. Every instant at which the read is `excluded` is added to `excludedInstants`.
|
|
740
|
+
*/
|
|
741
|
+
static outcomeOf(read, instants, judge, excludedInstants) {
|
|
742
|
+
let worst = 'created-after';
|
|
743
|
+
for (const at of instants) {
|
|
744
|
+
const outcome = judge(read.Key, at);
|
|
745
|
+
if (outcome === 'excluded')
|
|
746
|
+
excludedInstants.add(at.getTime());
|
|
747
|
+
if (STABLE_OUTCOME_SEVERITY[outcome] > STABLE_OUTCOME_SEVERITY[worst])
|
|
748
|
+
worst = outcome;
|
|
749
|
+
}
|
|
750
|
+
return worst;
|
|
751
|
+
}
|
|
752
|
+
/** The distinct unit rows whose own decision instant gives `outcome`, over the reads whose verdict it is. */
|
|
753
|
+
static affectedRows(reads, outcomes, outcome, judge) {
|
|
754
|
+
const ids = new Set();
|
|
755
|
+
reads.forEach((r, i) => {
|
|
756
|
+
if (outcomes[i] !== outcome)
|
|
757
|
+
return;
|
|
758
|
+
const byInstant = new Map();
|
|
759
|
+
for (const row of r.Rows) {
|
|
760
|
+
const at = AsOfFeatureAssembler.asOfInstant(row.DecisionDate);
|
|
761
|
+
if (!byInstant.has(at.getTime()))
|
|
762
|
+
byInstant.set(at.getTime(), judge(r.Key, at) === outcome);
|
|
763
|
+
if (byInstant.get(at.getTime()))
|
|
764
|
+
ids.add(row.RowID);
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
return ids.size;
|
|
768
|
+
}
|
|
769
|
+
/** The distinct decision instants of each reads' rows, ascending, computed once per rows list (child reads share one). */
|
|
770
|
+
static instantsOf(reads) {
|
|
771
|
+
const out = new Map();
|
|
772
|
+
for (const r of reads) {
|
|
773
|
+
if (out.has(r.Rows))
|
|
774
|
+
continue;
|
|
775
|
+
const times = [...new Set(r.Rows.map((row) => AsOfFeatureAssembler.asOfInstant(row.DecisionDate).getTime()))].sort((a, b) => a - b);
|
|
776
|
+
out.set(r.Rows, times.map((t) => new Date(t)));
|
|
777
|
+
}
|
|
778
|
+
return out;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The decision instants of one read's rows. `instantsOf` keys every read's `Rows` array, so a miss means the map was
|
|
782
|
+
* built from other reads: an internal error, not a data condition.
|
|
783
|
+
*
|
|
784
|
+
* @throws Error when the rows have no entry
|
|
785
|
+
*/
|
|
786
|
+
static instantsFor(instants, rows) {
|
|
787
|
+
const found = instants.get(rows);
|
|
788
|
+
if (found === undefined)
|
|
789
|
+
throw new Error('AsOfFeatureAssembler: no decision instants for a read; the instants were built from other reads');
|
|
790
|
+
return found;
|
|
791
|
+
}
|
|
792
|
+
/** The number of distinct unit rows the reads stand for whose decision day is before the assembly's day. */
|
|
793
|
+
static distinctPastRows(reads, input) {
|
|
794
|
+
const ids = new Set();
|
|
795
|
+
for (const rows of new Set(reads.map((r) => r.Rows))) {
|
|
796
|
+
for (const row of rows)
|
|
797
|
+
if (!AsOfFeatureAssembler.onAssemblyDayOrLater(row, input))
|
|
798
|
+
ids.add(row.RowID);
|
|
799
|
+
}
|
|
800
|
+
return ids.size;
|
|
801
|
+
}
|
|
802
|
+
/** Whether a row's decision day is on or after the assembly's own UTC day: its stored values are the values on that day. */
|
|
803
|
+
static onAssemblyDayOrLater(row, input) {
|
|
804
|
+
return AsOfFeatureAssembler.decisionDay(row.DecisionDate).getTime() >= AsOfFeatureAssembler.decisionDay(input.AssembledAt).getTime();
|
|
805
|
+
}
|
|
806
|
+
/** One read per unit row with a key: the record it reads, standing for that row alone. */
|
|
807
|
+
static rowReads(rows, keyOf) {
|
|
808
|
+
const reads = [];
|
|
809
|
+
for (const row of rows) {
|
|
810
|
+
const key = keyOf(row);
|
|
811
|
+
if (key !== null)
|
|
812
|
+
reads.push({ Key: key, Rows: [row] });
|
|
813
|
+
}
|
|
814
|
+
return reads;
|
|
815
|
+
}
|
|
816
|
+
/** The verdict of each unit row's own read (reads built by `rowReads`), by row id. */
|
|
817
|
+
static outcomesByRow(reads, stable) {
|
|
818
|
+
return new Map(reads.map((r, i) => [r.Rows[0].RowID, stable.Outcomes[i]]));
|
|
819
|
+
}
|
|
820
|
+
/** The keys with case-insensitive duplicates removed (first spelling kept), as a keyed read deduplicates them. */
|
|
821
|
+
static uniqueKeys(keys) {
|
|
822
|
+
const seen = new Map();
|
|
823
|
+
for (const k of keys)
|
|
824
|
+
if (!seen.has(k.toLowerCase()))
|
|
825
|
+
seen.set(k.toLowerCase(), k);
|
|
826
|
+
return [...seen.values()];
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* A windowed aggregate over the owner's child rows; its version hashes the contributing rows (and their update times).
|
|
830
|
+
* Every child row read passes the stable-value rule before any value is used, and a child row that did not exist on
|
|
831
|
+
* the owner row's decision day (late-entered) is dropped from that owner's window; the drops are recorded per column.
|
|
832
|
+
* A child hard-deleted after an owner row's decision day counts for that row as its Delete row recorded it, and one
|
|
833
|
+
* deleted before is absent (see {@link childIndex}). A child deleted and re-created after an owner row's decision day
|
|
834
|
+
* counts for that row as the incarnation that stood then, read from the Delete row that ended it (see
|
|
835
|
+
* {@link childRowsAt}).
|
|
836
|
+
*/
|
|
837
|
+
async aggregateReader(spec, source, input, state) {
|
|
838
|
+
// The contract: a null owner key field means the row's entity key.
|
|
839
|
+
const join = await this.keyResolver(source.ownerKeyField, input, (row) => row.EntityKey, state);
|
|
840
|
+
const ownerKeys = AsOfFeatureAssembler.uniqueKeys(input.Rows.map((row) => join.KeyOf(row)).filter((k) => k !== null));
|
|
841
|
+
const { Child: child, Index: index, Keys: keys, CreatedAt: createdAt, DeletedAt: deletedAt } = await this.childIndex(source, ownerKeys, input);
|
|
842
|
+
const excludedFor = await this.assertStableChildRows(child, source, keys, deletedAt, (key) => createdAt.get(key.toLowerCase()) || null, input, state);
|
|
843
|
+
const history = child.TrackRecordChanges && keys.length > 0 ? await AsOfFeatureAssembler.loadHistory(child, keys, [source.foreignKey], input, state) : null;
|
|
844
|
+
const rowsAt = AsOfFeatureAssembler.childRowsAt(child, source, index, keys, history, input.Rows);
|
|
845
|
+
const existedAt = (c, at) => AsOfFeatureAssembler.existedBefore(AsOfFeatureAssembler.creationInstant(history, c.Id, createdAt.get(c.Id.toLowerCase())), at)
|
|
846
|
+
&& AsOfFeatureAssembler.standsAt(deletedAt, c.Id, at);
|
|
847
|
+
const values = new Map();
|
|
848
|
+
let dropped = 0;
|
|
849
|
+
for (const row of input.Rows) {
|
|
850
|
+
if (join.CreatedAfter(row) || join.UncoveredFor(row) !== null || excludedFor(row) !== null)
|
|
851
|
+
continue;
|
|
852
|
+
const owner = join.KeyOf(row);
|
|
853
|
+
if (owner === null) {
|
|
854
|
+
values.set(row, AsOfFeatureAssembler.aggregateValue(spec, source, null, row, [], null, input));
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
const agg = AsOfFeatureAssembler.aggregateOfPresentRows(rowsAt, owner, row, source, existedAt, deletedAt);
|
|
858
|
+
dropped += agg.Dropped;
|
|
859
|
+
values.set(row, AsOfFeatureAssembler.aggregateValue(spec, source, owner, row, agg.Contributors, agg.Value, input));
|
|
860
|
+
}
|
|
861
|
+
// A column whose every row is uncovered read no window, so it has no drop count to report.
|
|
862
|
+
if (!(input.Rows.length > 0 && input.Rows.every((row) => excludedFor(row) !== null)))
|
|
863
|
+
state.LateEntered.set(spec.name, dropped);
|
|
864
|
+
return AsOfFeatureAssembler.throughJoin(spec, join, (row) => {
|
|
865
|
+
const excluded = excludedFor(row);
|
|
866
|
+
if (excluded)
|
|
867
|
+
return excluded;
|
|
868
|
+
const v = values.get(row);
|
|
869
|
+
if (!v)
|
|
870
|
+
throw new Error(`Windowed aggregate ${spec.name}: row ${row.RowID} was not computed`);
|
|
871
|
+
return v;
|
|
872
|
+
}, input);
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* One owner's aggregate as of its decision day over the child rows that existed then: the rows the full window would
|
|
876
|
+
* have read but that were entered after the decision day are dropped and counted, and the aggregate is recomputed
|
|
877
|
+
* over the owner's remaining rows. The owner's rows are those that stood at the as-of instant (`rowsAt`). A
|
|
878
|
+
* hard-deleted child whose Delete is before the decision instant (`deletedAt`, by lower-cased child key) is not in the
|
|
879
|
+
* full window at all: it is absent, not late-entered.
|
|
880
|
+
*/
|
|
881
|
+
static aggregateOfPresentRows(rowsAt, owner, row, source, existedAt, deletedAt) {
|
|
882
|
+
const asOf = AsOfFeatureAssembler.asOfInstant(row.DecisionDate);
|
|
883
|
+
const standing = rowsAt(owner, asOf).filter((c) => AsOfFeatureAssembler.standsAt(deletedAt, c.Id, asOf));
|
|
884
|
+
const window = new Map([[owner.toLowerCase(), standing]]);
|
|
885
|
+
const full = WindowedAggregates.ComputeWindowedAggregate(window, owner, row.DecisionDate, source);
|
|
886
|
+
const late = full.Contributors.filter((c) => !existedAt(c, asOf)).length;
|
|
887
|
+
if (late === 0)
|
|
888
|
+
return { ...full, Dropped: 0 };
|
|
889
|
+
const present = standing.filter((c) => existedAt(c, asOf));
|
|
890
|
+
const recomputed = WindowedAggregates.ComputeWindowedAggregate(new Map([[owner.toLowerCase(), present]]), owner, row.DecisionDate, source);
|
|
891
|
+
return { ...recomputed, Dropped: late };
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Every child row the index was built from passes the stable-value rule for the fields that decide what an aggregate
|
|
895
|
+
* reads, judged at every unit row's decision instant (each read stands for every unit row): a child row re-owned or
|
|
896
|
+
* re-dated after a decision day can move between owners, so none is exempt for contributing to no row. Every field is
|
|
897
|
+
* judged, so a later field's refusal is never hidden by an earlier field's exclusion. A child row the rule excludes
|
|
898
|
+
* at a unit row's decision instant makes that row uncovered for that field, since the child's owner on that day cannot
|
|
899
|
+
* be trusted; rows decided at instants where every child row is stable are read. A hard-deleted child (`deletedAt`,
|
|
900
|
+
* by lower-cased key) stands for the unit rows decided while it stood (its Delete at or after their as-of instant),
|
|
901
|
+
* judged on its Delete row as its stored value; after its Delete it is absent and judged for no row. Each field's
|
|
902
|
+
* history is loaded over every child key read (`keys`), judged or not, so the aggregate's own load of the owner key
|
|
903
|
+
* is the same load and coverage counts each child record once. Returns, per unit row, the first such field's
|
|
904
|
+
* marker, else null.
|
|
905
|
+
*/
|
|
906
|
+
async assertStableChildRows(child, source, keys, deletedAt, storedCreatedAt, input, state) {
|
|
907
|
+
const reads = AsOfFeatureAssembler.childReads(keys, deletedAt, input.Rows);
|
|
908
|
+
const excludedByField = [];
|
|
909
|
+
for (const field of AsOfFeatureAssembler.childStableFields(source)) {
|
|
910
|
+
const stable = await this.assertStableCurrentValue(child, field, reads, storedCreatedAt, input, state, keys);
|
|
911
|
+
if (stable.ExcludedInstants.size > 0)
|
|
912
|
+
excludedByField.push({ Instants: stable.ExcludedInstants, Marker: { Uncovered: true, Entity: child.Name, Field: field, HistoryStart: stable.HistoryStart } });
|
|
913
|
+
}
|
|
914
|
+
return (row) => {
|
|
915
|
+
const at = AsOfFeatureAssembler.asOfInstant(row.DecisionDate).getTime();
|
|
916
|
+
const hit = excludedByField.find((e) => e.Instants.has(at));
|
|
917
|
+
return hit ? hit.Marker : null;
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* One read per child key: a present child stands for every unit row; a hard-deleted one for the rows decided while it
|
|
922
|
+
* stood, and for none after its Delete (it is then dropped). Hard-deleted children deleted at one instant share one
|
|
923
|
+
* rows list, so their decision instants are computed once.
|
|
924
|
+
*/
|
|
925
|
+
static childReads(keys, deletedAt, rows) {
|
|
926
|
+
const byDelete = new Map();
|
|
927
|
+
const reads = [];
|
|
928
|
+
for (const key of keys) {
|
|
929
|
+
const del = deletedAt.get(key.toLowerCase());
|
|
930
|
+
if (del === undefined) {
|
|
931
|
+
reads.push({ Key: key, Rows: rows });
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
const standing = byDelete.get(del.getTime()) || rows.filter((row) => AsOfFeatureAssembler.standsAt(deletedAt, key, AsOfFeatureAssembler.asOfInstant(row.DecisionDate)));
|
|
935
|
+
byDelete.set(del.getTime(), standing);
|
|
936
|
+
if (standing.length > 0)
|
|
937
|
+
reads.push({ Key: key, Rows: standing });
|
|
938
|
+
}
|
|
939
|
+
return reads;
|
|
940
|
+
}
|
|
941
|
+
/** Whether a child still stood at `at`: it is not hard-deleted, or its Delete is at or after `at` (as `DeletedRecordAt` reads `held`). */
|
|
942
|
+
static standsAt(deletedAt, key, at) {
|
|
943
|
+
const del = deletedAt.get(key.toLowerCase());
|
|
944
|
+
return del === undefined || del.getTime() >= at.getTime();
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* An owner's child rows as they stood at an as-of instant. A child whose incarnation at the instant ended with a later
|
|
948
|
+
* Delete that a later change row follows (deleted and re-created after it, {@link EntityHistory.EarlierIncarnationEnd})
|
|
949
|
+
* is read from that Delete row, owner key, date, value and filter fields included, so it counts under the owner it
|
|
950
|
+
* had then and the rows read today stand only for the instants after the re-creation. Re-creation can happen only
|
|
951
|
+
* after the earliest instant if it happens after any, so only the children re-created after the earliest decision
|
|
952
|
+
* instant are consulted, once per instant. Without a history (an untracked child entity) the rows read are the rows.
|
|
953
|
+
*/
|
|
954
|
+
static childRowsAt(child, source, index, keys, history, rows) {
|
|
955
|
+
const read = (owner) => index.get(owner.toLowerCase()) || [];
|
|
956
|
+
if (history === null || rows.length === 0)
|
|
957
|
+
return read;
|
|
958
|
+
const earliest = new Date(AsOfFeatureAssembler.earliestAsOf(rows));
|
|
959
|
+
const recreated = AsOfFeatureAssembler.uniqueKeys(keys).filter((k) => history.EarlierIncarnationEnd(k, earliest) !== null);
|
|
960
|
+
if (recreated.length === 0)
|
|
961
|
+
return read;
|
|
962
|
+
const byInstant = new Map();
|
|
963
|
+
return (owner, asOf) => {
|
|
964
|
+
const at = byInstant.get(asOf.getTime()) || AsOfFeatureAssembler.earlierIncarnationsAt(child, source, recreated, history, asOf);
|
|
965
|
+
byInstant.set(asOf.getTime(), at);
|
|
966
|
+
if (at.Ended.size === 0)
|
|
967
|
+
return read(owner);
|
|
968
|
+
const kept = read(owner).filter((c) => !at.Ended.has(c.Id.toLowerCase()));
|
|
969
|
+
return [...kept, ...(at.Rows.get(owner.toLowerCase()) || [])].sort(WindowedAggregates.CompareChildRows);
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
/** The incarnations of the `recreated` children that stood at `asOf` and ended with a later Delete, as those Delete rows recorded them. */
|
|
973
|
+
static earlierIncarnationsAt(child, source, recreated, history, asOf) {
|
|
974
|
+
const ended = new Set();
|
|
975
|
+
const deleteRows = [];
|
|
976
|
+
for (const key of recreated) {
|
|
977
|
+
const end = history.EarlierIncarnationEnd(key, asOf);
|
|
978
|
+
if (end === null)
|
|
979
|
+
continue;
|
|
980
|
+
ended.add(key.toLowerCase());
|
|
981
|
+
deleteRows.push(AsOfFeatureAssembler.recordedChildRow(child, key, end.Row));
|
|
982
|
+
}
|
|
983
|
+
return { Ended: ended, Rows: WindowedAggregates.BuildChildRowIndex(deleteRows, source, child.PrimaryKey) };
|
|
984
|
+
}
|
|
985
|
+
/** One aggregate value; a row with no owner key has no child rows ('' would read the bucket of ownerless child rows). */
|
|
986
|
+
static aggregateValue(spec, source, owner, row, contributors, value, input) {
|
|
987
|
+
const sourceRef = owner === null ? 'none'
|
|
988
|
+
: `${source.childEntity}?${source.foreignKey}=${owner.toLowerCase()}&as-of=${UtcDay.UtcDayIso(AsOfFeatureAssembler.decisionDay(row.DecisionDate))}&aggregate=${source.aggregate}`;
|
|
989
|
+
return { Value: value, Provenance: { column: spec.name, source: 'windowed-aggregate', sourceRef, sourceVersion: AsOfFeatureAssembler.ContributorsVersion(contributors), computedAt: input.AssembledAt.toISOString() } };
|
|
990
|
+
}
|
|
991
|
+
/** The child fields whose stored values decide what an aggregate reads: the owner key, the date, the value and every filter. */
|
|
992
|
+
static childStableFields(source) {
|
|
993
|
+
return [...new Set([source.foreignKey, source.dateField, source.valueField, ...source.filter.map((f) => f.field)].filter((f) => !!f))];
|
|
994
|
+
}
|
|
995
|
+
/** A declared lag or rolling window of the unit's own series, read as of the row's decision day and the assembly day ({@link SeriesFeatures.ComputeSeriesFeature}). */
|
|
996
|
+
seriesReader(spec, source, input) {
|
|
997
|
+
const t = input.Unit.temporal;
|
|
998
|
+
const history = input.SeriesHistory;
|
|
999
|
+
if (!t || !history)
|
|
1000
|
+
throw new AssemblyRefused({ kind: 'unresolved-column', entity: input.RowEntity.Name, field: `TemporalSpec.${source.feature.kind}[${source.feature.index}]` });
|
|
1001
|
+
return (row) => {
|
|
1002
|
+
const s = SeriesFeatures.ComputeSeriesFeature(history, row.EntityKey, row.Period || row.DecisionDate, t, source.feature, row.DecisionDate, input.AssembledAt);
|
|
1003
|
+
return {
|
|
1004
|
+
Value: s.Value,
|
|
1005
|
+
Provenance: { column: spec.name, source: 'series', sourceRef: `${input.RowEntity.Name}/label/${s.SourceRowIDs.join('+')}`, sourceVersion: `labelVersion:${input.Unit.label.labelVersion}`, computedAt: input.AssembledAt.toISOString() },
|
|
1006
|
+
};
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
/** The latest effective-dated, pinned Feature Value on or before the decision day; an unpinned source is refused. */
|
|
1010
|
+
async featureValueReader(spec, source, input) {
|
|
1011
|
+
const pin = AsOfFeatureAssembler.pinOf(source);
|
|
1012
|
+
const read = await CompleteReader.ReadCompletely(input.DataAccess, {
|
|
1013
|
+
EntityName: 'MJ: Feature Values', KeyField: 'ID', ExtraFilter: AsOfFeatureAssembler.featureValueFilter(input.RowEntity, source.featureName, pin), Fields: FEATURE_VALUE_FIELDS,
|
|
1014
|
+
}, input.Read);
|
|
1015
|
+
if (read.Status === 'refused')
|
|
1016
|
+
throw new AssemblyRefused(read.Refusal);
|
|
1017
|
+
const byRecord = AsOfFeatureAssembler.featureValuesByRecord(read.Rows);
|
|
1018
|
+
const version = AsOfFeatureAssembler.pinVersion(pin);
|
|
1019
|
+
return (row) => {
|
|
1020
|
+
const asOf = AsOfFeatureAssembler.asOfInstant(row.DecisionDate).getTime();
|
|
1021
|
+
const candidates = (byRecord.get(row.RowID.toLowerCase()) || []).filter((v) => AsOfFeatureAssembler.effectiveAt(v) < asOf);
|
|
1022
|
+
const v = candidates[candidates.length - 1];
|
|
1023
|
+
return {
|
|
1024
|
+
// `??`: 0, '' and false are real feature values; only an absent typed column falls through to the next.
|
|
1025
|
+
Value: v ? (v.ValueNumeric ?? v.ValueText ?? v.ValueBoolean ?? v.ValueDate ?? null) : null,
|
|
1026
|
+
Provenance: { column: spec.name, source: 'feature-value', sourceRef: v ? `MJ: Feature Values/${String(v.ID).toLowerCase()}` : 'none', sourceVersion: version, computedAt: v ? AsOfFeatureAssembler.isoOf(v.ComputedAt) : '' },
|
|
1027
|
+
};
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* The source's pin, when it names a version: a whole-number pipeline version (0 included) or a prompt version hash.
|
|
1032
|
+
* No pin, a fractional version, or a pin naming neither refuses: such a pin cannot select one version of a value.
|
|
1033
|
+
*/
|
|
1034
|
+
static pinOf(source) {
|
|
1035
|
+
const pin = source.pin;
|
|
1036
|
+
const unpinned = new AssemblyRefused({ kind: 'unpinned-feature-version', featureName: source.featureName });
|
|
1037
|
+
if (pin === null)
|
|
1038
|
+
throw unpinned;
|
|
1039
|
+
if (pin.pipelineVersion !== null && !Number.isInteger(pin.pipelineVersion))
|
|
1040
|
+
throw unpinned;
|
|
1041
|
+
if (pin.pipelineVersion === null && !pin.promptVersionHash)
|
|
1042
|
+
throw unpinned;
|
|
1043
|
+
return pin;
|
|
1044
|
+
}
|
|
1045
|
+
/** The version a valid Feature Value pin names: its feature pipeline and the pipeline version or prompt version it read. */
|
|
1046
|
+
static pinVersion(pin) {
|
|
1047
|
+
return `${pin.featurePipelineRecordProcessId}@${pin.pipelineVersion !== null ? pin.pipelineVersion : pin.promptVersionHash}`;
|
|
1048
|
+
}
|
|
1049
|
+
/** The Feature Values of one feature of the row entity that a pin selects; undated values are never read. */
|
|
1050
|
+
static featureValueFilter(rowEntity, featureName, pin) {
|
|
1051
|
+
// Every value interpolated here comes from metadata or a pin (JSON), so each is escaped.
|
|
1052
|
+
return [
|
|
1053
|
+
`[EntityID]='${EscapeSQLString(rowEntity.ID)}'`, `[FeatureName]='${EscapeSQLString(featureName)}'`,
|
|
1054
|
+
`[RecordProcessID]='${EscapeSQLString(pin.featurePipelineRecordProcessId)}'`, '[EffectiveAsOf] IS NOT NULL',
|
|
1055
|
+
...(pin.promptVersionHash ? [`[PromptVersionHash]='${EscapeSQLString(pin.promptVersionHash)}'`] : []),
|
|
1056
|
+
// The Feature Value key columns: a pin names the pipeline version, model and parameters it read.
|
|
1057
|
+
...(pin.pipelineVersion !== null ? [`[PipelineVersion]=${pin.pipelineVersion}`] : []),
|
|
1058
|
+
...(pin.aiModelId ? [`[AIModelID]='${EscapeSQLString(pin.aiModelId)}'`] : []),
|
|
1059
|
+
...(pin.parametersHash ? [`[ParametersHash]='${EscapeSQLString(pin.parametersHash)}'`] : []),
|
|
1060
|
+
].join(' AND ');
|
|
1061
|
+
}
|
|
1062
|
+
/** Feature Values keyed by lower-cased record key, each list in effective-date order. */
|
|
1063
|
+
static featureValuesByRecord(rows) {
|
|
1064
|
+
const byRecord = new Map();
|
|
1065
|
+
for (const v of rows) {
|
|
1066
|
+
const k = RecordHistory.KeyOfRecordID(String(v.RecordID));
|
|
1067
|
+
const list = byRecord.get(k) || [];
|
|
1068
|
+
list.push(v);
|
|
1069
|
+
byRecord.set(k, list);
|
|
1070
|
+
}
|
|
1071
|
+
for (const list of byRecord.values())
|
|
1072
|
+
list.sort((a, b) => AsOfFeatureAssembler.effectiveAt(a) - AsOfFeatureAssembler.effectiveAt(b));
|
|
1073
|
+
return byRecord;
|
|
1074
|
+
}
|
|
1075
|
+
static effectiveAt(v) {
|
|
1076
|
+
return (v.EffectiveAsOf instanceof Date ? v.EffectiveAsOf : new Date(String(v.EffectiveAsOf))).getTime();
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* How a row finds the record a source reads: through a key field on the row entity, or (no key field) `fallback` —
|
|
1080
|
+
* the row's own id for a field, the row's entity key for an aggregate owner. A unit row deleted and re-created after
|
|
1081
|
+
* its decision day resolves the key its earlier incarnation's Delete row recorded
|
|
1082
|
+
* ({@link EntityHistory.EarlierIncarnationEnd}).
|
|
1083
|
+
*/
|
|
1084
|
+
async keyResolver(keyField, input, fallback, state) {
|
|
1085
|
+
if (keyField === null)
|
|
1086
|
+
return { KeyOf: fallback, CreatedAfter: () => false, UncoveredFor: () => null };
|
|
1087
|
+
const reads = AsOfFeatureAssembler.rowReads(input.Rows, (row) => row.RowID);
|
|
1088
|
+
const hasCreatedAt = AsOfFeatureAssembler.hasField(input.RowEntity, '__mj_CreatedAt');
|
|
1089
|
+
// Read first, as a current value is: a unit row with no record is a short read, whatever its history.
|
|
1090
|
+
const rowsById = await KeyedReader.ReadByKeys(input.DataAccess, input.RowEntity.Name, input.RowEntity.PrimaryKey, reads.map((r) => r.Key), hasCreatedAt ? [keyField, '__mj_CreatedAt'] : [keyField]);
|
|
1091
|
+
if (rowsById.Status === 'refused')
|
|
1092
|
+
throw new AssemblyRefused(rowsById.Refusal);
|
|
1093
|
+
const storedCreatedAt = (key) => (hasCreatedAt ? rowsById.Rows.get(key.toLowerCase())?.__mj_CreatedAt : null);
|
|
1094
|
+
const stable = await this.assertStableCurrentValue(input.RowEntity, keyField, reads, storedCreatedAt, input, state);
|
|
1095
|
+
const outcomes = AsOfFeatureAssembler.outcomesByRow(reads, stable);
|
|
1096
|
+
const createdAfter = (row) => {
|
|
1097
|
+
const created = AsOfFeatureAssembler.creationInstant(stable.History, row.RowID, storedCreatedAt(row.RowID));
|
|
1098
|
+
return !AsOfFeatureAssembler.existedBefore(created, AsOfFeatureAssembler.asOfInstant(row.DecisionDate));
|
|
1099
|
+
};
|
|
1100
|
+
const uncoveredFor = (row) => (outcomes.get(row.RowID) === 'excluded' ? { Uncovered: true, Entity: input.RowEntity.Name, Field: keyField, HistoryStart: stable.HistoryStart } : null);
|
|
1101
|
+
return {
|
|
1102
|
+
CreatedAfter: createdAfter,
|
|
1103
|
+
UncoveredFor: uncoveredFor,
|
|
1104
|
+
KeyOf: (row) => {
|
|
1105
|
+
if (createdAfter(row) || uncoveredFor(row) !== null)
|
|
1106
|
+
return null;
|
|
1107
|
+
// A unit row deleted and re-created after its decision day joins through the key its earlier incarnation recorded.
|
|
1108
|
+
const ended = stable.History === null ? null : stable.History.EarlierIncarnationEnd(row.RowID, AsOfFeatureAssembler.asOfInstant(row.DecisionDate));
|
|
1109
|
+
const v = ended !== null ? ended.Row.get(keyField) : rowsById.Rows.get(row.RowID.toLowerCase())?.[keyField];
|
|
1110
|
+
return v === null || v === undefined ? null : String(v);
|
|
1111
|
+
},
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
/** A reader behind a join: a row uncovered for the key field is uncovered; one created after its decision day reads as missing. */
|
|
1115
|
+
static throughJoin(spec, join, read, input) {
|
|
1116
|
+
return (row) => {
|
|
1117
|
+
const uncovered = join.UncoveredFor(row);
|
|
1118
|
+
if (uncovered !== null)
|
|
1119
|
+
return uncovered;
|
|
1120
|
+
return join.CreatedAfter(row) ? AsOfFeatureAssembler.missingValue(spec, 'none', 'created-after-decision', input) : read(row);
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
/** A missing value with the given source reference and version, computed at the assembly time. */
|
|
1124
|
+
static missingValue(spec, sourceRef, sourceVersion, input) {
|
|
1125
|
+
return { Value: null, Provenance: { column: spec.name, source: spec.source.kind, sourceRef, sourceVersion, computedAt: input.AssembledAt.toISOString() } };
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* The child entity, its indexed rows, the keys of every row read (the index skips undated and filtered-out rows),
|
|
1129
|
+
* when the entity lists `__mj_CreatedAt` each row's value of it by lower-cased key, and the Delete instant of every
|
|
1130
|
+
* hard-deleted child by lower-cased key. On a child entity that tracks Record Changes the rows read are the current
|
|
1131
|
+
* rows plus every child whose history ends in a Delete, that has no current row and that one of `ownerKeys` held
|
|
1132
|
+
* (`IRecordHistoryReader.LoadDeletedChildren`), read from its Delete row: a child deleted after an owner row's
|
|
1133
|
+
* decision day existed then, and today's set of rows would silently leave it out of that row's aggregate. Only a
|
|
1134
|
+
* hard-deleted child that bears on a unit row is read (its Delete at or after the as-of instant of at least one row
|
|
1135
|
+
* of the batch); one deleted before every row's as-of instant is absent for every row, so it is left out of the
|
|
1136
|
+
* child history's key set and shapes neither its history start nor its continuity counts.
|
|
1137
|
+
*/
|
|
1138
|
+
async childIndex(source, ownerKeys, input) {
|
|
1139
|
+
const child = input.Metadata.Entity(source.childEntity);
|
|
1140
|
+
if (!child)
|
|
1141
|
+
throw new AssemblyRefused({ kind: 'unresolved-column', entity: source.childEntity, field: '*' });
|
|
1142
|
+
const hasCreatedAt = AsOfFeatureAssembler.hasField(child, '__mj_CreatedAt');
|
|
1143
|
+
const fields = [
|
|
1144
|
+
child.PrimaryKey, source.foreignKey, source.dateField, source.endDateField, source.voidedAtField, source.valueField, ...source.filter.map((f) => f.field),
|
|
1145
|
+
AsOfFeatureAssembler.hasField(child, '__mj_UpdatedAt') ? '__mj_UpdatedAt' : null, hasCreatedAt ? '__mj_CreatedAt' : null,
|
|
1146
|
+
].filter((f) => !!f);
|
|
1147
|
+
const read = await CompleteReader.ReadCompletely(input.DataAccess, { EntityName: child.Name, KeyField: child.PrimaryKey, Fields: [...new Set(fields)] }, input.Read);
|
|
1148
|
+
if (read.Status === 'refused')
|
|
1149
|
+
throw new AssemblyRefused(read.Refusal);
|
|
1150
|
+
const keyOf = (r) => String(r[child.PrimaryKey]);
|
|
1151
|
+
const present = new Set(read.Rows.map((r) => keyOf(r).toLowerCase()));
|
|
1152
|
+
const earliest = AsOfFeatureAssembler.earliestAsOf(input.Rows);
|
|
1153
|
+
const deleted = child.TrackRecordChanges && ownerKeys.length > 0
|
|
1154
|
+
? (await input.History.LoadDeletedChildren(child, source.foreignKey, ownerKeys)).filter((d) => !present.has(d.Key) && d.ChangedAt.getTime() >= earliest)
|
|
1155
|
+
: [];
|
|
1156
|
+
const rowsRead = [...read.Rows, ...deleted.map((d) => AsOfFeatureAssembler.recordedChildRow(child, d.Key, d.Row))];
|
|
1157
|
+
return {
|
|
1158
|
+
Child: child,
|
|
1159
|
+
Index: WindowedAggregates.BuildChildRowIndex(rowsRead, source, child.PrimaryKey),
|
|
1160
|
+
Keys: rowsRead.map(keyOf),
|
|
1161
|
+
CreatedAt: new Map(hasCreatedAt ? rowsRead.map((r) => [keyOf(r).toLowerCase(), r.__mj_CreatedAt]) : []),
|
|
1162
|
+
DeletedAt: new Map(deleted.map((d) => [d.Key, d.ChangedAt])),
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
/** The earliest as-of instant of the rows, in epoch milliseconds (positive infinity for no rows). */
|
|
1166
|
+
static earliestAsOf(rows) {
|
|
1167
|
+
return rows.reduce((min, row) => Math.min(min, AsOfFeatureAssembler.asOfInstant(row.DecisionDate).getTime()), Number.POSITIVE_INFINITY);
|
|
1168
|
+
}
|
|
1169
|
+
/** A child as a Delete row recorded it, as a stored row: the row's fields, keyed by `key` when the row omits the key. */
|
|
1170
|
+
static recordedChildRow(child, key, recordedRow) {
|
|
1171
|
+
const row = {};
|
|
1172
|
+
for (const [f, v] of recordedRow)
|
|
1173
|
+
row[f] = v;
|
|
1174
|
+
const recorded = row[child.PrimaryKey];
|
|
1175
|
+
if (recorded === null || recorded === undefined)
|
|
1176
|
+
row[child.PrimaryKey] = key;
|
|
1177
|
+
return row;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* A windowed aggregate's source version: the sha-256 of the contributing rows, `ID:updatedAt` per row (or the ID
|
|
1181
|
+
* alone when the row has no update time), sorted, one per line. The one rule for the version, so a reader that
|
|
1182
|
+
* rebuilds the contributor set can check a stored version against it.
|
|
1183
|
+
*/
|
|
1184
|
+
static ContributorsVersion(contributors) {
|
|
1185
|
+
const lines = contributors.map((c) => (c.UpdatedAt ? `${c.Id}:${c.UpdatedAt}` : c.Id)).sort();
|
|
1186
|
+
return createHash('sha256').update(lines.join('\n')).digest('hex');
|
|
1187
|
+
}
|
|
1188
|
+
/** The per-column version summary stored on the snapshot (per-value versions are in the provenance file). */
|
|
1189
|
+
static columnVersion(spec, input, state) {
|
|
1190
|
+
const s = spec.source;
|
|
1191
|
+
switch (s.kind) {
|
|
1192
|
+
case 'record-changes': return `history-start:${state.Coverage.get(`${s.entity}|${s.field}`)?.historyStart || 'none'}`;
|
|
1193
|
+
case 'immutable-field': return 'immutable-after-create';
|
|
1194
|
+
case 'windowed-aggregate': return `window:${s.windowDays === null ? 'all' : s.windowDays};aggregate:${s.aggregate}`;
|
|
1195
|
+
case 'series': return `labelVersion:${input.Unit.label.labelVersion}`;
|
|
1196
|
+
case 'feature-value': return s.pin ? AsOfFeatureAssembler.pinVersion(s.pin) : 'unpinned';
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
static describeSource(spec) {
|
|
1200
|
+
const s = spec.source;
|
|
1201
|
+
switch (s.kind) {
|
|
1202
|
+
case 'immutable-field':
|
|
1203
|
+
case 'record-changes': return `${s.entity}.${s.field}`;
|
|
1204
|
+
case 'windowed-aggregate': return `${s.childEntity}.${s.valueField || s.dateField}`;
|
|
1205
|
+
case 'series': return `series.${s.feature.kind}[${s.feature.index}]`;
|
|
1206
|
+
case 'feature-value': return `feature-value.${s.featureName}`;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
/** `<entity>/<lower-cased key>/<field>`: the record and field a value was read from. */
|
|
1210
|
+
static fieldRef(entity, key, field) {
|
|
1211
|
+
return `${entity.Name}/${(key || '').toLowerCase()}/${field}`;
|
|
1212
|
+
}
|
|
1213
|
+
static hasField(entity, name) {
|
|
1214
|
+
return entity.Fields.some((f) => f.Name === name);
|
|
1215
|
+
}
|
|
1216
|
+
/** A stored timestamp as an instant; an absent or unparseable one is null. */
|
|
1217
|
+
static instantOf(value) {
|
|
1218
|
+
const d = value instanceof Date ? value : typeof value === 'string' ? new Date(value) : null;
|
|
1219
|
+
return d === null || Number.isNaN(d.getTime()) ? null : d;
|
|
1220
|
+
}
|
|
1221
|
+
/** A stored timestamp as an ISO instant; an absent one is ''. */
|
|
1222
|
+
static isoOf(value) {
|
|
1223
|
+
if (value instanceof Date)
|
|
1224
|
+
return value.toISOString();
|
|
1225
|
+
return value === null || value === undefined ? '' : String(value);
|
|
1226
|
+
}
|
|
1227
|
+
/** The decision's UTC day; an invalid decision date is a caller defect, not a refusal. */
|
|
1228
|
+
static decisionDay(decision) {
|
|
1229
|
+
const day = UtcDay.ToUtcDay(decision);
|
|
1230
|
+
if (day === null)
|
|
1231
|
+
throw new Error('As-of assembly: a row has an invalid decision date');
|
|
1232
|
+
return day;
|
|
1233
|
+
}
|
|
1234
|
+
/** The start of the day after the decision day: anything strictly before it was known on the decision day. */
|
|
1235
|
+
static asOfInstant(decision) {
|
|
1236
|
+
return UtcDay.AddUtcDays(AsOfFeatureAssembler.decisionDay(decision), 1);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
//# sourceMappingURL=as-of-assembler.js.map
|