run-ab-test-models
Design and execute A/B tests for ML models in production using traffic splitting, statistical significance testing, and canary/shadow deployment. Measure performance differences and make data-driven rollout decisions. Use to validate a new model before full rollout, compare candidate models from different algorithms, measure business metric impact of model changes, or meet regulatory gradual rollout requirements.
Best use case
run-ab-test-models is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Design and execute A/B tests for ML models in production using traffic splitting, statistical significance testing, and canary/shadow deployment. Measure performance differences and make data-driven rollout decisions. Use to validate a new model before full rollout, compare candidate models from different algorithms, measure business metric impact of model changes, or meet regulatory gradual rollout requirements.
Teams using run-ab-test-models should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/run-ab-test-models/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How run-ab-test-models Compares
| Feature / Agent | run-ab-test-models | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Design and execute A/B tests for ML models in production using traffic splitting, statistical significance testing, and canary/shadow deployment. Measure performance differences and make data-driven rollout decisions. Use to validate a new model before full rollout, compare candidate models from different algorithms, measure business metric impact of model changes, or meet regulatory gradual rollout requirements.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Run A/B Test for Models > See [Extended Examples](references/EXAMPLES.md) for complete configuration files and templates. Execute controlled experiments comparing model versions using traffic splitting and statistical analysis. ## When to Use - Deploying a new model version and validating improvement before full rollout - Comparing multiple candidate models from different algorithms or features - Testing impact of hyperparameter changes on business metrics - Measuring model performance in production without risking full traffic - Regulatory requirements for gradual rollout (e.g., medical ML) - Evaluating cost-performance tradeoffs between model sizes ## Inputs - **Required**: Champion model (current production version) - **Required**: Challenger model(s) (new version to test) - **Required**: Traffic allocation percentage (e.g., 5% to challenger) - **Required**: Success metrics (business and ML) - **Required**: Minimum sample size or test duration - **Optional**: Guardrail metrics (latency, error rate thresholds) - **Optional**: User segments for stratified testing ## Procedure ### Step 1: Design Experiment Define test parameters, success criteria, and statistical requirements. ```python # ab_test/experiment_config.py from dataclasses import dataclass from typing import List, Dict import numpy as np from scipy.stats import norm @dataclass # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Experiment config with statistically sound sample size — typically 5-10k samples per variant for 5-10% MDE. **If fail:** With required sample size too large, increase traffic allocation, extend duration, or accept larger MDE; verify baseline metric estimate is accurate; consider sequential testing for continuous monitoring. ### Step 2: Implement Traffic Splitting Set up routing logic to randomly assign requests to models. ```python # ab_test/traffic_router.py import hashlib import random from typing import Dict, Optional from dataclasses import dataclass import logging logger = logging.getLogger(__name__) # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Consistent user-to-variant assignment, accurate traffic split matching configured percentages, all assignments logged. **If fail:** Verify hash function produces uniform distribution (test with 10k user IDs), check user_id is stable across requests (not session_id), ensure logs capture all prediction events, validate traffic split in first 1000 requests. ### Step 3: Implement Shadow Deployment (Optional) Run challenger model in parallel without affecting users (shadow mode). ```python # ab_test/shadow_deployment.py import asyncio from typing import Dict, Any import logging from concurrent.futures import ThreadPoolExecutor import time logger = logging.getLogger(__name__) # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Champion predictions served with normal latency, challenger predictions logged async without blocking, prediction differences captured. **If fail:** Set challenger timeout < champion SLA to avoid blocking, handle challenger errors gracefully, monitor memory usage (two models loaded), consider sampling (log only 10% of shadow predictions). ### Step 4: Collect and Analyze Metrics Gather experiment data and perform statistical tests. ```python # ab_test/analysis.py import pandas as pd import numpy as np from scipy import stats from typing import Dict, Tuple import logging logger = logging.getLogger(__name__) # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Statistical test results with p-values, confidence intervals, and clear decision (rollout/keep/inconclusive) — typically after 7-14 days or reaching sample size. **If fail:** Verify ground truth labels are available (may need delayed analysis), check for sample ratio mismatch (SRM) indicating assignment bugs, ensure sufficient sample size reached, look for novelty/primacy effects in early data, consider sequential testing if fixed-horizon test is too slow. ### Step 5: Monitor Guardrail Metrics Continuously check that challenger does not violate safety thresholds. ```python # ab_test/guardrails.py import pandas as pd import logging from typing import Dict, List logger = logging.getLogger(__name__) # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Guardrail violations detected within 5-15 minutes, automated experiment stop if critical thresholds breached (latency, errors), alerts sent to team. **If fail:** Verify guardrail thresholds are realistic (not too tight), ensure monitoring loop is running continuously, check that stop_experiment() actually updates routing, test alert delivery channels. ### Step 6: Make Rollout Decision Based on results, decide whether to roll out the challenger. ```python # ab_test/rollout_decision.py import logging from typing import Dict from dataclasses import dataclass logger = logging.getLogger(__name__) # ... (see EXAMPLES.md for complete implementation) ``` **Got:** Clear decision (full/gradual rollout, keep champion, or extend test) with justification and action items. **If fail:** With unclear decision, perform subgroup analysis (by user segment, time of day, device type), check for interaction effects, review business context (e.g., is 2% lift worth engineering cost?), consult stakeholders. ## Validation - [ ] Traffic split matches configured percentages (within 1%) - [ ] Same user always assigned to same variant (consistency check) - [ ] Sample size calculation produces reasonable numbers (5-50k per variant) - [ ] Statistical tests produce p-values consistent with manual calculation - [ ] Guardrail violations trigger alerts within 5 minutes - [ ] Shadow deployment shows <5% prediction divergence between models - [ ] Experiment reports include confidence intervals - [ ] Rollout decision documented with justification ## Pitfalls - **Sample ratio mismatch (SRM)**: If observed traffic split differs from configured (e.g., 95/5 becomes 92/8), indicates assignment bug; check hash function uniformity - **Peeking**: Checking results before reaching sample size inflates Type I error; use sequential testing or wait for pre-determined end date - **Novelty effect**: Users respond differently to new model initially; run for 2+ weeks to see steady-state behavior - **Carryover effects**: Previous variant exposure affects current behavior; use new users or sufficient washout period - **Multiple testing**: Testing many metrics increases false positive risk; correct with Bonferroni or focus on single primary metric - **Insufficient power**: Small traffic allocation may require months to detect realistic effects; balance statistical power with risk tolerance - **Ignoring segments**: Aggregate lift may hide negative impact on important user segments; perform subgroup analysis - **Attribution errors**: Ensure outcome metrics correctly attributed to model predictions (not other system changes) ## Related Skills - `deploy-ml-model-serving` - Model deployment infrastructure and versioning - `monitor-model-drift` - Ongoing performance monitoring post-rollout
Related Skills
write-testthat-tests
Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.
test-team-coordination
Execute a test scenario against a team, observing coordination pattern behaviors, evaluating acceptance criteria, and generating a structured RESULT.md. Use when validating that a team's coordination pattern produces the expected behaviors during a realistic task, comparing coordination patterns on equivalent workloads, or establishing baseline performance for a team composition.
test-a2a-interop
Test A2A interoperability between agents by validating Agent Card conformance, exercising all task lifecycle states, and verifying streaming and error handling. Use when verifying a new A2A server implementation before deployment, validating interoperability between two or more A2A agents, running conformance tests in CI/CD for A2A services, debugging failures in multi-agent A2A workflows, or certifying that an agent meets A2A protocol requirements for a registry.
run-puzzle-tests
Run jigsawR test suite via WSL R. Supports full suite, filtered by pattern, or single file. Interprets pass/fail/skip counts and identifies failing tests. Never use `--vanilla` (renv needs `.Rprofile` to activate). Use after R source changes, after adding a puzzle type or feature, before commits, or when debugging a specific failure.
skill-name-here
One to three sentences describing what this skill accomplishes, followed by key activation triggers. This field is the primary mechanism agents use to decide whether to activate the skill — it is read during discovery before the full body is loaded. Start with a verb. Include the most important "when to use" conditions inline. Max 1024 characters.
write-vignette
Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.
write-validation-documentation
Write IQ/OQ/PQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.
write-standard-operating-procedure
Write a GxP-compliant Standard Operating Procedure (SOP). Covers regulatory SOP template structure (purpose, scope, definitions, responsibilities, procedure, references, revision history), approval workflow design, periodic review scheduling, and operational procedures for system use. Use when a new validated system requires operational procedures, when existing informal procedures need formalisation, when an audit finding cites missing procedures, when a change control triggers SOP updates, or when periodic review identifies outdated procedural content.
write-roxygen-docs
Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.
write-incident-runbook
Create structured incident runbooks with diagnostic steps, resolution procedures, escalation paths, and communication templates for effective incident response. Use when documenting response procedures for recurring alerts, standardizing incident response across an on-call rotation, reducing MTTR with clear diagnostic steps, creating training materials for new team members, or linking alert annotations directly to resolution procedures.
write-helm-chart
Create production-ready Helm charts for Kubernetes application deployment with templating, values management, chart dependencies, hooks, and testing. Covers chart structure, Go template syntax, values.yaml design, chart repositories, versioning, and best practices for maintainable and reusable charts. Use when packaging a Kubernetes application for repeatable deployments, parameterizing manifests for multiple environments, managing complex multi-component applications with dependencies, or standardizing deployment practices with versioned rollback capability across teams.
write-continue-here
Write a CONTINUE_HERE.md file capturing current session state so a fresh Claude Code session can pick up where this one left off. Covers assessing recent work, structuring the continuation file with objective, completed, in-progress, next-steps, and context sections, and verifying the file is actionable. Use when ending a session with unfinished work, handing off context between sessions, or preserving task state that git alone cannot capture.