Production machine-learning engineering workflow for data contracts, reproducible training, model evaluation, deployment, monitoring, and rollback. Use when building, reviewing, or hardening ML systems beyond one-off notebooks.
Use this skill to turn model work into a production ML system with clear data contracts, repeatable training, measurable quality gates, deployable artifacts, and operational monitoring.
When to Activate
Planning or reviewing a production ML feature, model refresh, ranking system, recommender, classifier, embedding workflow, or forecasting pipeline
Converting notebook code into a reusable training, evaluation, batch inference, or online inference pipeline
Designing model promotion criteria, offline/online evals, experiment tracking, or rollback paths
Debugging failures caused by data drift, label leakage, stale features, artifact mismatch, or inconsistent training and serving logic
Adding model monitoring, canary rollout, shadow traffic, or post-deploy quality checks
Scope Calibration
Use only the lanes that fit the system in front of you. This skill is useful for ranking, search, recommendations, classifiers, forecasting, embeddings, LLM workflows, anomaly detection, and batch analytics, but it should not force one architecture onto all of them.
Do not assume every model has supervised labels, online serving, a feature store, PyTorch, GPUs, human review, A/B tests, or real-time feedback.
Do not add heavyweight MLOps machinery when a data contract, baseline, eval script, and rollback note would make the change reviewable.
Do make assumptions explicit when the project lacks labels, delayed outcomes, slice definitions, production traffic, or monitoring ownership.
Treat examples as interchangeable scaffolds. Replace metrics, serving mode, data stores, and rollout mechanics with the project-native equivalents.
Related Skills
python-patterns and python-testing for Python implementation and pytest coverage
pytorch-patterns for deep learning models, data loaders, device handling, and training loops
eval-harness and ai-regression-testing for promotion gates and agent-assisted regression checks
database-migrations, postgres-patterns, and clickhouse-io for data storage and analytics surfaces
deployment-patterns, docker-patterns, and security-review for serving, secrets, containers, and production hardening
Reuse the SWE Surface
Do not treat MLE as separate from software engineering. Most ECC SWE workflows apply directly to ML systems, often with stricter failure modes:
The recommended minimal --with capability:machine-learning install keeps the core agent surface available alongside this skill. For skill-only or agent-limited harnesses, pair skill:mle-workflow with agent:mle-reviewer where the target supports agents.
Version labels, feature snapshots, prediction logs, experiment metrics, and drift analytics
deployment-patterns / docker-patterns
Package reproducible training and serving images with health checks, resource limits, and rollback
canary-watch / dashboard-builder
Make rollout health visible with model-version, slice, drift, latency, cost, and delayed-label dashboards
security-review / security-scan
Check model artifacts, notebooks, prompts, datasets, and logs for secrets, PII, unsafe deserialization, and supply-chain risk
e2e-testing / browser-qa / accessibility
Test critical product flows that consume predictions, including explainability and fallback UI states
benchmark / performance-optimizer
Measure throughput, p95 latency, memory, GPU utilization, and cost per prediction or retrain
cost-aware-llm-pipeline / token-budget-advisor
Route LLM/embedding workloads by quality, latency, and budget instead of defaulting to the largest model
documentation-lookup / search-first
Verify current library behavior for model serving, feature stores, vector DBs, and eval tooling before coding
git-workflow / github-ops / opensource-pipeline
Package MLE changes for review with crisp scope, generated artifacts excluded, and reproducible test evidence
strategic-compact / dmux-workflows
Split long ML work into parallel tracks: data contract, eval harness, serving path, monitoring, and docs
Ten MLE Task Simulations
Use these simulations as coverage checks when planning or reviewing MLE work. A strong MLE workflow should reduce each task to explicit contracts, reusable SWE surfaces, automated evidence, and a reviewable artifact.
ID
Common MLE task
Streamlined ECC path
Required output
Pipeline lanes covered
MLE-01
Frame an ambiguous prediction, ranking, recommender, classifier, embedding, or forecast capability
Prediction endpoint or batch job with response envelope, timeout, batching, fallback, model version, confidence, feedback logging, and product-flow tests
serving, batch inference, fallback, user workflow
MLE-09
Roll out a model with shadow traffic, canary, A/B test, or rollback
Observation ledger and refresh plan with drift checks, delayed-label health, alert owners, runbook updates, retrain criteria, and PR evidence
monitoring, incident response, retraining
Iteration Compact
Before touching model code, compress the work into one reviewable artifact. This should be short enough to fit in a PR description and precise enough that another engineer can challenge the tradeoffs.
Goal:
Who cares:
Decision owner:
User or system action changed by the model:
Success metric:
Guardrail metrics:
Mistake budget:
Unacceptable mistakes:
Acceptable mistakes:
Assumptions:
Constraints:
Labels and data snapshot:
Baseline:
Candidate signals:
Threshold or config plan:
Eval slices:
Known risks:
Next experiment:
Rollback or fallback:
This compact is the MLE equivalent of a strong SWE design note. It keeps the team from optimizing a metric no one trusts, adding features that do not address the real error mode, or shipping complexity without a rollback.
Decision Brain
Use this loop whenever the task is ambiguous, high-impact, or metric-heavy:
Start from the decision, not the model. Name the action that changes downstream behavior.
Name who cares and why. Different stakeholders pay different costs for false positives, false negatives, latency, compute spend, opacity, or missed opportunities.
Convert ambiguity into hypotheses. Ask what signal would separate outcomes, what evidence would disprove it, and what simple baseline should be hard to beat.
Research prior art or a nearby known problem before inventing a bespoke system.
Score choices with (probability, confidence) x (cost, severity, importance, impact).
Consider adversarial behavior, incentives, selective disclosure, distribution shift, and feedback loops.
Prefer the simplest change that reduces the most important mistake. Simplicity is not laziness; it is a way to minimize blunders while preserving iteration speed.
Capture the decision, evidence, counterargument, and next reversible step.
Metric and Mistake Economics
Choose metrics from failure costs, not habit:
Use a confusion matrix early so the team can discuss concrete false positives and false negatives instead of abstract accuracy.
Favor precision when the cost of an incorrect positive decision dominates.
Favor recall when the cost of a missed positive dominates.
Use F1 only when the precision/recall tradeoff is genuinely balanced and explainable.
Use AUC or ranking metrics when ordering quality matters more than a single threshold.
Track latency, throughput, memory, and cost as first-class metrics because they shape feasible model complexity.
Compare against a baseline and the current production model before celebrating an offline gain.
Treat real-world feedback signals as delayed labels with bias, lag, and coverage gaps; do not treat them as ground truth without analysis.
Every metric choice should state which mistake it makes cheaper, which mistake it makes more likely, and who absorbs that cost.
Data and Feature Hypotheses
Features should come from a theory of separation:
Text, categorical fields, numeric histories, graph relationships, recency, frequency, and aggregates are candidate signal families, not automatic features.
For every feature family, state why it should separate outcomes and how it could leak future information.
For noisy labels, consider adjudication, label confidence, soft targets, or confidence weighting.
For class imbalance, compare weighted loss, resampling, threshold movement, and calibrated decision rules.
For missing values, decide whether absence is informative, imputable, or a reason to abstain.
For outliers, decide whether to clip, bucket, investigate, or preserve them as rare but important signal.
For correlated features, check whether they are redundant, unstable, or proxies for unavailable future state.
Do not add model complexity until error analysis shows that the baseline is failing for a reason additional signal or capacity can plausibly fix.
Error Analysis Loop
After each baseline, training run, threshold change, or config change:
Split mistakes into false positives, false negatives, abstentions, low-confidence cases, and system failures.
Cluster errors by shared traits: language, entity type, source, time, geography, device, sparsity, recency, feature freshness, label source, or model version.
Separate model mistakes from data bugs, label ambiguity, product ambiguity, instrumentation gaps, and serving mismatches.
Trace each major cluster to one of four moves: better labels, better features, better threshold/config, or better product fallback.
Preserve every important mistake as a regression test, eval slice, dashboard panel, or runbook entry.
Write the next iteration as a falsifiable experiment, not a vague "improve model" task.
The strongest MLE loop is not train -> metric -> ship. It is mistake -> cluster -> hypothesis -> experiment -> evidence -> simpler system.
Observation Ledger
Keep a compact decision and evidence trail beside the code, PR, experiment report, or runbook:
Use the ledger to make model work cumulative. The goal is for each iteration to make the next decision easier, not merely to produce another artifact.
Core Workflow
1. Define the Prediction Contract
Capture the product-level contract before writing model code:
Prediction target and decision owner
Input entity, output schema, confidence/calibration fields, and allowed latency
Batch, online, streaming, or hybrid serving mode
Fallback behavior when the model, feature store, or dependency is unavailable
Human review or override path for high-impact decisions
Privacy, retention, and audit requirements for inputs, predictions, and labels
Do not accept "improve the model" as a requirement. Tie the model to an observable product behavior and a measurable acceptance gate.
2. Lock the Data Contract
Every ML task needs an explicit data contract:
Entity grain and primary key
Label definition, label timestamp, and label availability delay
Feature timestamp, freshness SLA, and point-in-time join rules
Train, validation, test, and backtest split policy
Required columns, allowed nulls, ranges, categories, and units
PII or sensitive fields that must not enter training artifacts or logs
Dataset version or snapshot ID for reproducibility
Guard against leakage first. If a feature is not available at prediction time, or is joined using future information, remove it or move it to an analysis-only path.
3. Build a Reproducible Pipeline
Training code should be runnable by another engineer without hidden notebook state:
Use typed config files or dataclasses for all hyperparameters and paths
Pin package and model dependencies
Set random seeds and document any nondeterministic GPU behavior
Record dataset version, code SHA, config hash, metrics, and artifact URI
Save preprocessing logic with the model artifact, not separately in a notebook
Keep train, eval, and inference transformations shared or generated from one source
Make every step idempotent so retries do not corrupt artifacts or metrics
Prefer immutable values and pure transformation functions. Avoid mutating shared data frames or global config during feature generation.
import hashlib
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class TrainingConfig:
dataset_uri: str
model_dir: Path
seed: int
learning_rate: float
batch_size: int
def artifact_name(config: TrainingConfig, code_sha: str) -> str:
config_key = f"{config.dataset_uri}:{config.seed}:{config.learning_rate}:{config.batch_size}"
config_hash = hashlib.sha256(config_key.encode("utf-8")).hexdigest()[:12]
return f"{code_sha[:12]}-{config_hash}"
4. Evaluate Before Promotion
Promotion criteria should be declared before training finishes:
Baseline model and current production model comparison
Primary metric aligned to product behavior
Guardrail metrics for latency, calibration, fairness slices, cost, and error concentration
Slice metrics for important cohorts, geographies, devices, languages, or data sources
Confidence intervals or repeated-run variance when metrics are noisy
Failure examples reviewed by a human for high-impact models
Explicit "do not ship" thresholds
PROMOTION_GATES = {
"auc": ("min", 0.82),
"calibration_error": ("max", 0.04),
"p95_latency_ms": ("max", 80),
}
def assert_promotion_ready(metrics: dict[str, float]) -> None:
missing = sorted(name for name in PROMOTION_GATES if name not in metrics)
if missing:
raise ValueError(f"Model promotion metrics missing required gates: {missing}")
failures = {
name: value
for name, (direction, threshold) in PROMOTION_GATES.items()
for value in [metrics[name]]
if (direction == "min" and value < threshold)
or (direction == "max" and value > threshold)
}
if failures:
raise ValueError(f"Model failed promotion gates: {failures}")
Use offline metrics as gates, not guarantees. When the model changes product behavior, plan shadow evaluation, canary rollout, or A/B testing before full rollout.
5. Package for Serving
An ML artifact is production-ready only when the serving contract is testable:
Model artifact includes version, training data reference, config, and preprocessing
Input schema rejects invalid, stale, or out-of-range features
Output schema includes model version and confidence or explanation fields when useful
Serving path has timeout, batching, resource limits, and fallback behavior
CPU/GPU requirements are explicit and tested
Prediction logs avoid PII and include enough identifiers for debugging and label joins
Integration tests cover missing features, stale features, bad types, empty batches, and fallback path
Never let training-only feature code diverge from serving feature code without a test that proves equivalence.
6. Operate the Model
Model monitoring needs both system and quality signals:
Availability, error rate, timeout rate, queue depth, and p50/p95/p99 latency
Feature null rate, range drift, categorical drift, and freshness drift
Prediction distribution drift and confidence distribution drift
Label arrival health and delayed quality metrics
Business KPI guardrails and rollback triggers
Per-version dashboards for canaries and rollbacks
Every deployment should have a rollback plan that names the previous artifact, config, data dependency, and traffic-switch mechanism.
Review Checklist
Prediction contract is explicit and testable
Data contract defines entity grain, label timing, feature timing, and snapshot/version
Leakage risks were checked against prediction-time availability
Training is reproducible from code, config, data version, and seed
Metrics compare against baseline and current production model
Slice metrics and guardrails are included for high-risk cohorts
Promotion gates are automated and fail closed
Training and serving transformations are shared or equivalence-tested
Model artifact carries version, config, dataset reference, and preprocessing
Serving path validates inputs and has timeout, fallback, and rollback behavior
Monitoring covers system health, feature drift, prediction drift, and delayed labels
Sensitive data is excluded from artifacts, logs, prompts, and examples
Anti-Patterns
Notebook state is required to reproduce the model
Random split leaks future data into validation or test sets
Feature joins ignore event time and label availability
Offline metric improves while important slices regress
Thresholds are tuned on the test set repeatedly
Training preprocessing is copied manually into serving code
Model version is missing from prediction logs
Monitoring only checks service uptime, not data or prediction quality
Rollback requires retraining instead of switching to a known-good artifact
Output Expectations
When using this skill, return concrete artifacts: data contract, promotion gates, pipeline steps, test plan, deployment plan, or review findings. Call out unknowns that block production readiness instead of filling them with assumptions.
Also appears in:affaan-m/ECC/.kiro/skills/mle-workflow/SKILL.md, affaan-m/ECC/.agents/skills/mle-workflow/SKILL.md
1---
2name: mle-workflow
3description: "Production machine-learning engineering workflow for data contracts, reproducible training, model evaluation, deployment, monitoring, and rollback. Use when building, reviewing, or hardening ML systems beyond one-off notebooks."
4category: devops-and-infra
5source_repo: affaan-m/ECC
6source_path: "skills/mle-workflow/SKILL.md"
7source_url: https://github.com/affaan-m/ECC/blob/HEAD/skills/mle-workflow/SKILL.md
8metadata:
9 source: https://skillmd.com/skills/thedixitjain/mle-workflow
10---
1112# Machine Learning Engineering Workflow
1314Use this skill to turn model work into a production ML system with clear data contracts, repeatable training, measurable quality gates, deployable artifacts, and operational monitoring.
1516## When to Activate
1718- Planning or reviewing a production ML feature, model refresh, ranking system, recommender, classifier, embedding workflow, or forecasting pipeline
19- Converting notebook code into a reusable training, evaluation, batch inference, or online inference pipeline
20- Designing model promotion criteria, offline/online evals, experiment tracking, or rollback paths
21- Debugging failures caused by data drift, label leakage, stale features, artifact mismatch, or inconsistent training and serving logic
22- Adding model monitoring, canary rollout, shadow traffic, or post-deploy quality checks
2324## Scope Calibration
2526Use only the lanes that fit the system in front of you. This skill is useful for ranking, search, recommendations, classifiers, forecasting, embeddings, LLM workflows, anomaly detection, and batch analytics, but it should not force one architecture onto all of them.
2728- Do not assume every model has supervised labels, online serving, a feature store, PyTorch, GPUs, human review, A/B tests, or real-time feedback.
29- Do not add heavyweight MLOps machinery when a data contract, baseline, eval script, and rollback note would make the change reviewable.
30- Do make assumptions explicit when the project lacks labels, delayed outcomes, slice definitions, production traffic, or monitoring ownership.
31- Treat examples as interchangeable scaffolds. Replace metrics, serving mode, data stores, and rollout mechanics with the project-native equivalents.
3233## Related Skills
3435- `python-patterns` and `python-testing` for Python implementation and pytest coverage
36- `pytorch-patterns` for deep learning models, data loaders, device handling, and training loops
37- `eval-harness` and `ai-regression-testing` for promotion gates and agent-assisted regression checks
38- `database-migrations`, `postgres-patterns`, and `clickhouse-io` for data storage and analytics surfaces
39- `deployment-patterns`, `docker-patterns`, and `security-review` for serving, secrets, containers, and production hardening
4041## Reuse the SWE Surface
4243Do not treat MLE as separate from software engineering. Most ECC SWE workflows apply directly to ML systems, often with stricter failure modes:
4445The recommended `minimal --with capability:machine-learning` install keeps the core agent surface available alongside this skill. For skill-only or agent-limited harnesses, pair `skill:mle-workflow` with `agent:mle-reviewer` where the target supports agents.
4647| SWE surface | MLE use |
48|-------------|---------|
49| `product-capability` / `architecture-decision-records` | Turn model work into explicit product contracts and record irreversible data, model, and rollout choices |
50| `repo-scan` / `codebase-onboarding` / `code-tour` | Find existing training, feature, serving, eval, and monitoring paths before introducing a parallel ML stack |
51| `plan` / `feature-dev` | Scope model changes as product capabilities with data, eval, serving, and rollback phases |
52| `tdd-workflow` / `python-testing` | Test feature transforms, split logic, metric calculations, artifact loading, and inference schemas before implementation |
53| `code-reviewer` / `mle-reviewer` | Review code quality plus ML-specific leakage, reproducibility, promotion, and monitoring risks |
54| `build-fix` / `pr-test-analyzer` | Diagnose broken CI, flaky evals, missing fixtures, and environment-specific model or dependency failures |
55| `quality-gate` / `test-coverage` | Require automated evidence for transforms, metrics, inference contracts, promotion gates, and rollback behavior |
56| `eval-harness` / `verification-loop` | Turn offline metrics, slice checks, latency budgets, and rollback drills into repeatable gates |
57| `ai-regression-testing` | Preserve every production bug as a regression: missing feature, stale label, bad artifact, schema drift, or serving mismatch |
58| `api-design` / `backend-patterns` | Design prediction APIs, batch jobs, idempotent retraining endpoints, and response envelopes |
59| `database-migrations` / `postgres-patterns` / `clickhouse-io` | Version labels, feature snapshots, prediction logs, experiment metrics, and drift analytics |
60| `deployment-patterns` / `docker-patterns` | Package reproducible training and serving images with health checks, resource limits, and rollback |
61| `canary-watch` / `dashboard-builder` | Make rollout health visible with model-version, slice, drift, latency, cost, and delayed-label dashboards |
62| `security-review` / `security-scan` | Check model artifacts, notebooks, prompts, datasets, and logs for secrets, PII, unsafe deserialization, and supply-chain risk |
63| `e2e-testing` / `browser-qa` / `accessibility` | Test critical product flows that consume predictions, including explainability and fallback UI states |
64| `benchmark` / `performance-optimizer` | Measure throughput, p95 latency, memory, GPU utilization, and cost per prediction or retrain |
65| `cost-aware-llm-pipeline` / `token-budget-advisor` | Route LLM/embedding workloads by quality, latency, and budget instead of defaulting to the largest model |
66| `documentation-lookup` / `search-first` | Verify current library behavior for model serving, feature stores, vector DBs, and eval tooling before coding |
67| `git-workflow` / `github-ops` / `opensource-pipeline` | Package MLE changes for review with crisp scope, generated artifacts excluded, and reproducible test evidence |
68| `strategic-compact` / `dmux-workflows` | Split long ML work into parallel tracks: data contract, eval harness, serving path, monitoring, and docs |
6970## Ten MLE Task Simulations
7172Use these simulations as coverage checks when planning or reviewing MLE work. A strong MLE workflow should reduce each task to explicit contracts, reusable SWE surfaces, automated evidence, and a reviewable artifact.
7374| ID | Common MLE task | Streamlined ECC path | Required output | Pipeline lanes covered |
75|----|-----------------|----------------------|-----------------|------------------------|
76| MLE-01 | Frame an ambiguous prediction, ranking, recommender, classifier, embedding, or forecast capability | `product-capability`, `plan`, `architecture-decision-records`, `mle-workflow` | Iteration Compact naming who cares, decision owner, success metric, unacceptable mistakes, assumptions, constraints, and first experiment | product contract, stakeholder loss, risk, rollout |
77| MLE-02 | Define metric goals, labels, data sources, and the mistake budget | `repo-scan`, `database-reviewer`, `database-migrations`, `postgres-patterns`, `clickhouse-io` | Data and metric contract with entity grain, label timing, label confidence, feature timing, point-in-time joins, split policy, and dataset snapshot | data contract, metric design, leakage, reproducibility |
78| MLE-03 | Build a baseline model and scoring path before adding complexity | `tdd-workflow`, `python-testing`, `python-patterns`, `code-reviewer` | Baseline scorer with confusion matrix, calibration notes, latency/cost estimate, known weaknesses, and tests for score shape and determinism | baseline, scoring, testing, serving parity |
79| MLE-04 | Generate features from hypotheses about what separates outcomes | `python-patterns`, `pytorch-patterns`, `docker-patterns`, `deployment-patterns` | Feature plan and transform module covering signal source, missing values, outliers, correlations, leakage checks, and train/serve equivalence | feature pipeline, leakage, training, artifacts |
80| MLE-05 | Tune thresholds, configs, and model complexity under tradeoffs | `eval-harness`, `ai-regression-testing`, `quality-gate`, `test-coverage` | Threshold/config report comparing precision, recall, F1, AUC, calibration, group slices, latency, cost, complexity, and acceptable error classes | evaluation, threshold, promotion, regression |
81| MLE-06 | Run error analysis and turn mistakes into the next experiment | `eval-harness`, `ai-regression-testing`, `mle-reviewer`, `silent-failure-hunter` | Error cluster report for false positives, false negatives, ambiguous labels, stale features, missing signals, and bug traces with lessons captured | error analysis, bug trace, iteration, regression |
82| MLE-07 | Package a model artifact for batch or online inference | `api-design`, `backend-patterns`, `security-review`, `security-scan` | Versioned artifact bundle with preprocessing, config, dependency constraints, schema validation, safe loading, and PII-safe logs | artifact, security, inference contract |
83| MLE-08 | Ship online serving or batch scoring with feedback capture | `api-design`, `backend-patterns`, `e2e-testing`, `browser-qa`, `accessibility` | Prediction endpoint or batch job with response envelope, timeout, batching, fallback, model version, confidence, feedback logging, and product-flow tests | serving, batch inference, fallback, user workflow |
84| MLE-09 | Roll out a model with shadow traffic, canary, A/B test, or rollback | `canary-watch`, `dashboard-builder`, `verification-loop`, `performance-optimizer` | Rollout plan naming traffic split, dashboards, p95 latency, cost, quality guardrails, rollback artifact, and rollback trigger | deployment, canary, rollback |
85| MLE-10 | Operate, debug, and refresh a production model after launch | `silent-failure-hunter`, `dashboard-builder`, `mle-reviewer`, `doc-updater`, `github-ops` | Observation ledger and refresh plan with drift checks, delayed-label health, alert owners, runbook updates, retrain criteria, and PR evidence | monitoring, incident response, retraining |
8687## Iteration Compact
8889Before touching model code, compress the work into one reviewable artifact. This should be short enough to fit in a PR description and precise enough that another engineer can challenge the tradeoffs.
9091```text
92Goal:
93Who cares:
94Decision owner:
95User or system action changed by the model:
96Success metric:
97Guardrail metrics:
98Mistake budget:
99Unacceptable mistakes:
100Acceptable mistakes:
101Assumptions:
102Constraints:
103Labels and data snapshot:
104Baseline:
105Candidate signals:
106Threshold or config plan:
107Eval slices:
108Known risks:
109Next experiment:
110Rollback or fallback:
111```
112113This compact is the MLE equivalent of a strong SWE design note. It keeps the team from optimizing a metric no one trusts, adding features that do not address the real error mode, or shipping complexity without a rollback.
114115## Decision Brain
116117Use this loop whenever the task is ambiguous, high-impact, or metric-heavy:
1181191. Start from the decision, not the model. Name the action that changes downstream behavior.
1202. Name who cares and why. Different stakeholders pay different costs for false positives, false negatives, latency, compute spend, opacity, or missed opportunities.
1213. Convert ambiguity into hypotheses. Ask what signal would separate outcomes, what evidence would disprove it, and what simple baseline should be hard to beat.
1224. Research prior art or a nearby known problem before inventing a bespoke system.
1235. Score choices with `(probability, confidence) x (cost, severity, importance, impact)`.
1246. Consider adversarial behavior, incentives, selective disclosure, distribution shift, and feedback loops.
1257. Prefer the simplest change that reduces the most important mistake. Simplicity is not laziness; it is a way to minimize blunders while preserving iteration speed.
1268. Capture the decision, evidence, counterargument, and next reversible step.
127128## Metric and Mistake Economics
129130Choose metrics from failure costs, not habit:
131132- Use a confusion matrix early so the team can discuss concrete false positives and false negatives instead of abstract accuracy.
133- Favor precision when the cost of an incorrect positive decision dominates.
134- Favor recall when the cost of a missed positive dominates.
135- Use F1 only when the precision/recall tradeoff is genuinely balanced and explainable.
136- Use AUC or ranking metrics when ordering quality matters more than a single threshold.
137- Track latency, throughput, memory, and cost as first-class metrics because they shape feasible model complexity.
138- Compare against a baseline and the current production model before celebrating an offline gain.
139- Treat real-world feedback signals as delayed labels with bias, lag, and coverage gaps; do not treat them as ground truth without analysis.
140141Every metric choice should state which mistake it makes cheaper, which mistake it makes more likely, and who absorbs that cost.
142143## Data and Feature Hypotheses
144145Features should come from a theory of separation:
146147- Text, categorical fields, numeric histories, graph relationships, recency, frequency, and aggregates are candidate signal families, not automatic features.
148- For every feature family, state why it should separate outcomes and how it could leak future information.
149- For noisy labels, consider adjudication, label confidence, soft targets, or confidence weighting.
150- For class imbalance, compare weighted loss, resampling, threshold movement, and calibrated decision rules.
151- For missing values, decide whether absence is informative, imputable, or a reason to abstain.
152- For outliers, decide whether to clip, bucket, investigate, or preserve them as rare but important signal.
153- For correlated features, check whether they are redundant, unstable, or proxies for unavailable future state.
154155Do not add model complexity until error analysis shows that the baseline is failing for a reason additional signal or capacity can plausibly fix.
156157## Error Analysis Loop
158159After each baseline, training run, threshold change, or config change:
1601611. Split mistakes into false positives, false negatives, abstentions, low-confidence cases, and system failures.
1622. Cluster errors by shared traits: language, entity type, source, time, geography, device, sparsity, recency, feature freshness, label source, or model version.
1633. Separate model mistakes from data bugs, label ambiguity, product ambiguity, instrumentation gaps, and serving mismatches.
1644. Trace each major cluster to one of four moves: better labels, better features, better threshold/config, or better product fallback.
1655. Preserve every important mistake as a regression test, eval slice, dashboard panel, or runbook entry.
1666. Write the next iteration as a falsifiable experiment, not a vague "improve model" task.
167168The strongest MLE loop is not train -> metric -> ship. It is mistake -> cluster -> hypothesis -> experiment -> evidence -> simpler system.
169170## Observation Ledger
171172Keep a compact decision and evidence trail beside the code, PR, experiment report, or runbook:
173174```text
175Iteration:
176Change:
177Why this mattered:
178Metric movement:
179Slice movement:
180False positives:
181False negatives:
182Unexpected errors:
183Decision:
184Tradeoff accepted:
185Lesson captured:
186Regression added:
187Debt created:
188Next iteration:
189```
190191Use the ledger to make model work cumulative. The goal is for each iteration to make the next decision easier, not merely to produce another artifact.
192193## Core Workflow
194195### 1. Define the Prediction Contract
196197Capture the product-level contract before writing model code:
198199- Prediction target and decision owner
200- Input entity, output schema, confidence/calibration fields, and allowed latency
201- Batch, online, streaming, or hybrid serving mode
202- Fallback behavior when the model, feature store, or dependency is unavailable
203- Human review or override path for high-impact decisions
204- Privacy, retention, and audit requirements for inputs, predictions, and labels
205206Do not accept "improve the model" as a requirement. Tie the model to an observable product behavior and a measurable acceptance gate.
207208### 2. Lock the Data Contract
209210Every ML task needs an explicit data contract:
211212- Entity grain and primary key
213- Label definition, label timestamp, and label availability delay
214- Feature timestamp, freshness SLA, and point-in-time join rules
215- Train, validation, test, and backtest split policy
216- Required columns, allowed nulls, ranges, categories, and units
217- PII or sensitive fields that must not enter training artifacts or logs
218- Dataset version or snapshot ID for reproducibility
219220Guard against leakage first. If a feature is not available at prediction time, or is joined using future information, remove it or move it to an analysis-only path.
221222### 3. Build a Reproducible Pipeline
223224Training code should be runnable by another engineer without hidden notebook state:
225226- Use typed config files or dataclasses for all hyperparameters and paths
227- Pin package and model dependencies
228- Set random seeds and document any nondeterministic GPU behavior
229- Record dataset version, code SHA, config hash, metrics, and artifact URI
230- Save preprocessing logic with the model artifact, not separately in a notebook
231- Keep train, eval, and inference transformations shared or generated from one source
232- Make every step idempotent so retries do not corrupt artifacts or metrics
233234Prefer immutable values and pure transformation functions. Avoid mutating shared data frames or global config during feature generation.
235236```python
237import hashlib
238from dataclasses import dataclass
239from pathlib import Path
240241242@dataclass(frozen=True)
243class TrainingConfig:
244 dataset_uri: str
245 model_dir: Path
246 seed: int
247 learning_rate: float
248 batch_size: int
249250251def artifact_name(config: TrainingConfig, code_sha: str) -> str:
252 config_key = f"{config.dataset_uri}:{config.seed}:{config.learning_rate}:{config.batch_size}"
253 config_hash = hashlib.sha256(config_key.encode("utf-8")).hexdigest()[:12]
254 return f"{code_sha[:12]}-{config_hash}"
255```
256257### 4. Evaluate Before Promotion
258259Promotion criteria should be declared before training finishes:
260261- Baseline model and current production model comparison
262- Primary metric aligned to product behavior
263- Guardrail metrics for latency, calibration, fairness slices, cost, and error concentration
264- Slice metrics for important cohorts, geographies, devices, languages, or data sources
265- Confidence intervals or repeated-run variance when metrics are noisy
266- Failure examples reviewed by a human for high-impact models
267- Explicit "do not ship" thresholds
268269```python
270PROMOTION_GATES = {
271 "auc": ("min", 0.82),
272 "calibration_error": ("max", 0.04),
273 "p95_latency_ms": ("max", 80),
274}
275276277def assert_promotion_ready(metrics: dict[str, float]) -> None:
278 missing = sorted(name for name in PROMOTION_GATES if name not in metrics)
279 if missing:
280 raise ValueError(f"Model promotion metrics missing required gates: {missing}")
281282 failures = {
283 name: value
284 for name, (direction, threshold) in PROMOTION_GATES.items()
285 for value in [metrics[name]]
286 if (direction == "min" and value < threshold)
287 or (direction == "max" and value > threshold)
288 }
289 if failures:
290 raise ValueError(f"Model failed promotion gates: {failures}")
291```
292293Use offline metrics as gates, not guarantees. When the model changes product behavior, plan shadow evaluation, canary rollout, or A/B testing before full rollout.
294295### 5. Package for Serving
296297An ML artifact is production-ready only when the serving contract is testable:
298299- Model artifact includes version, training data reference, config, and preprocessing
300- Input schema rejects invalid, stale, or out-of-range features
301- Output schema includes model version and confidence or explanation fields when useful
302- Serving path has timeout, batching, resource limits, and fallback behavior
303- CPU/GPU requirements are explicit and tested
304- Prediction logs avoid PII and include enough identifiers for debugging and label joins
305- Integration tests cover missing features, stale features, bad types, empty batches, and fallback path
306307Never let training-only feature code diverge from serving feature code without a test that proves equivalence.
308309### 6. Operate the Model
310311Model monitoring needs both system and quality signals:
312313- Availability, error rate, timeout rate, queue depth, and p50/p95/p99 latency
314- Feature null rate, range drift, categorical drift, and freshness drift
315- Prediction distribution drift and confidence distribution drift
316- Label arrival health and delayed quality metrics
317- Business KPI guardrails and rollback triggers
318- Per-version dashboards for canaries and rollbacks
319320Every deployment should have a rollback plan that names the previous artifact, config, data dependency, and traffic-switch mechanism.
321322## Review Checklist
323324- [ ] Prediction contract is explicit and testable
325- [ ] Data contract defines entity grain, label timing, feature timing, and snapshot/version
326- [ ] Leakage risks were checked against prediction-time availability
327- [ ] Training is reproducible from code, config, data version, and seed
328- [ ] Metrics compare against baseline and current production model
329- [ ] Slice metrics and guardrails are included for high-risk cohorts
330- [ ] Promotion gates are automated and fail closed
331- [ ] Training and serving transformations are shared or equivalence-tested
332- [ ] Model artifact carries version, config, dataset reference, and preprocessing
333- [ ] Serving path validates inputs and has timeout, fallback, and rollback behavior
334- [ ] Monitoring covers system health, feature drift, prediction drift, and delayed labels
335- [ ] Sensitive data is excluded from artifacts, logs, prompts, and examples
336337## Anti-Patterns
338339- Notebook state is required to reproduce the model
340- Random split leaks future data into validation or test sets
341- Feature joins ignore event time and label availability
342- Offline metric improves while important slices regress
343- Thresholds are tuned on the test set repeatedly
344- Training preprocessing is copied manually into serving code
345- Model version is missing from prediction logs
346- Monitoring only checks service uptime, not data or prediction quality
347- Rollback requires retraining instead of switching to a known-good artifact
348349## Output Expectations
350351When using this skill, return concrete artifacts: data contract, promotion gates, pipeline steps, test plan, deployment plan, or review findings. Call out unknowns that block production readiness instead of filling them with assumptions.
352353---
354355**Source:** [`affaan-m/ECC`](https://github.com/affaan-m/ECC) → `skills/mle-workflow/SKILL.md`
356357**Also appears in:** `affaan-m/ECC/.kiro/skills/mle-workflow/SKILL.md`, `affaan-m/ECC/.agents/skills/mle-workflow/SKILL.md`
Run npx get-skill add thedixitjain/mle-workflow in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Production machine-learning engineering workflow for data contracts, reproducible training, model evaluation, deployment, monitoring, and rollback. Use when building, reviewing, or hardening ML systems beyond one-off notebooks. It is listed under DevOps & Infra on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: makes network calls, reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
thedixitjain (@thedixitjain) published this skill. Their other Agent Skills are listed on their SkillMD profile.