Explore · Workflow integration
Workflow Integration
Integrate fairness checks into every stage of the development lifecycle: experiment tracking, version control, CI/CD pipelines, testing, and collaborative review.
The features below ensure fairness is not a one-time audit but a continuous, automated practice.
Experiment Tracking
Log fairness metrics to MLflow and Weights & Biases alongside model performance.
Version Control
Pre-commit hooks validate fairness configs and model cards before every commit.
CI/CD Gates
Deployment gates block unfair models. Hierarchical checking covers intersectional groups.
Testing
pytest plugin with markers, fixtures, and terminal summary. JUnit XML for CI/CD.
Report Card
Auto-generated markdown reports for PR comments with pass/fail metrics and warnings.
DevOps Templates
Ready-to-use GitHub Actions, GitLab CI, and PR template files.
vfairness_8_workflow_integration.ipynb End-to-end validation of MLflow/W&B tracking, pre-commit hooks, CI/CD gates, pytest fixtures & report cardsOpen it to see this run end to end. Every notebook is executed on each build, so the code here matches the library you installed.
Experiment Tracking
vfairness provides first-class integration with both MLflow and
Weights & Biases. Both functions accept either a FairnessAnalyzer
instance or a raw report dictionary and log metrics, confidence intervals, effect sizes,
and group statistics.
Group names are coded by default. A tracker run is read by many people,
so both functions replace every group name they write with a keyed code such as
g_3fa91c07d2e4 (HMAC-SHA256 under a team secret, never a plain hash, which
a short list of likely names would undo). The same key gives the same codes in every run,
so model versions stay comparable. Set the key once, kept like a password, in the
environment variable VFAIRNESS_GROUP_LABEL_KEY (or pass label_key=);
without it the functions refuse before anything is written. group_labels="names"
writes the real names on purpose. The mapping from name to code is never written to the
tracker; see the API reference for how to rebuild it
on your own machine.
MLflow
import mlflow
from vfairness import FairnessAnalyzer, log_fairness_to_mlflow
# export VFAIRNESS_GROUP_LABEL_KEY=... (once, in the shell)
with mlflow.start_run():
analyzer = FairnessAnalyzer(y_true, y_pred, gender)
logged = log_fairness_to_mlflow(analyzer, prefix="model_v1")
print(f"Logged {len(logged)} metrics")
Weights & Biases NEW
import wandb
from vfairness import FairnessAnalyzer, log_fairness_to_wandb
wandb.init(project="fairness-audit")
analyzer = FairnessAnalyzer(y_true, y_pred, gender)
logged = log_fairness_to_wandb(analyzer, prefix="model_v1")
wandb.finish()
Auto-Logging Decorator NEW
from vfairness import auto_log_fairness
# Group names coded with VFAIRNESS_GROUP_LABEL_KEY, as above.
@auto_log_fairness(backend="mlflow", prefix="eval")
def evaluate_model(X_test, y_test, sensitive_attr):
y_pred = model.predict(X_test)
return y_pred, y_test, sensitive_attr # (y_pred, y_true, sensitive_attr)
# Fairness metrics are automatically logged when called
evaluate_model(X_test, y_test, gender)
Model Register fingerprints PRE-RELEASE
A team that keeps its models in its own MLflow can register an assessed model version with the
Validant Model Register without sending the model, the data or the results anywhere in clear.
The pre-release module vfairness._register (since 0.2.0) identifies a version by its
bytes where the model lives: model_fingerprint() returns the SHA-256 of a model file,
or the manifest digest of a model folder (sorted path, NUL, file SHA-256 lines), and an
MLflow URI (models:/<name>/<version>, models:/<name>@<alias>,
runs:/...) is first downloaded through your own MLflow client into a temporary folder.
A symbolic link in a model folder is refused. One evidence bundle per assessed version
(validant.register.evidence.v1) holds the fingerprint, the dataset fingerprint, the
system type, the MLflow identifiers (model_uri, model_id, run_id,
version) and the results you choose to keep; unknown MLflow keys and values that are not
JSON are refused.
from vfairness._register import (
build_evidence_bundle, dataset_fingerprint, model_fingerprint, write_evidence_bundle,
)
identity = model_fingerprint("models:/credit-scoring@candidate") # or a file or folder path
data = dataset_fingerprint("data/holdout.csv") # a file path or bytes
bundle = build_evidence_bundle(
identity,
dataset_sha256=data.digest,
mlflow={"model_uri": "models:/credit-scoring@candidate"},
results={"demographic_parity_difference": 0.04},
)
write_evidence_bundle(bundle, "evidence.json")
Private on purpose. The module has not been through the library's grading yet, so it
is outside the frozen public surface, the capability ledger and the beta gate, and its names may
change; it becomes the public vfairness.register once its units are graded. Reading an
MLflow URI needs the mlops extra (pip install 'vfairness[mlops]'). See the
0.2.0 release notes.
Version Control Hooks
vfairness provides pre-commit hooks that validate fairness-related files before every commit, ensuring documentation and configuration standards are met.
Pre-commit Configuration
# .pre-commit-config.yaml
repos:
- repo: https://github.com/validantai/vfairness
rev: v0.3.0 # vfairness 0.3.0, released 4 Dec 2026
hooks:
- id: vfairness-check-config # Validates fairness config files
additional_dependencies: ["PyYAML>=6.0"] # needed to read .yml/.yaml configs
- id: vfairness-check-model-card # Checks model cards for fairness sections
Hooks
| Hook | Description | Files Matched |
|---|---|---|
vfairness-check-config |
Validates that fairness config files contain required keys (metrics, thresholds) |
files ending in fairness, bias, or gate + .json/.yml/.yaml (regex (fairness|bias|gate)\.(json|ya?ml)$) |
vfairness-check-model-card |
Verifies model cards include fairness-related sections | files ending in model-card.md, model_card.md, or modelcard.md |
CI/CD Fairness Gates
The ModelFairnessGate class acts as a deployment gate in CI/CD pipelines,
evaluating model fairness against configurable thresholds and deciding whether deployment should proceed.
from vfairness import ModelFairnessGate
gate = ModelFairnessGate(
metrics=['demographic_parity_difference', 'equalized_odds_difference'],
thresholds={
'demographic_parity_difference': 0.1,
'equalized_odds_difference': 0.1,
},
blocking_metrics=['demographic_parity_difference'],
)
decision = gate.evaluate(y_true, y_pred, protected_attr)
if decision.approved:
deploy_model()
else:
print(decision.blocking_reasons)
The gate returns a GateDecision with status
APPROVED, CONDITIONAL, or BLOCKED.
Use gate.create_github_check(decision) to generate a GitHub Checks API payload.
Each metric's verdict is read off its interval, not its point estimate:
within when the 90% interval lies inside the threshold,
beyond when the 95% interval lies wholly outside it, and
inconclusive otherwise (MetricEvaluation.verdict, with the
bounds in MetricEvaluation.interval). An inconclusive blocking metric
blocks and a non-blocking one makes the decision CONDITIONAL; neither is
approved. evaluate() computes the intervals for the rate metrics it
computes itself. evaluate_from_metrics() receives point estimates, so a
value inside its bound reads inconclusive unless its interval is passed in
intervals=.
Hierarchical Intersectional Gate NEW
The evaluate_hierarchical() method checks fairness at three levels:
- Overall — across all groups
- Single-attribute — per individual protected attribute (gender, race, etc.)
- Intersectional — combinations of attributes (gender × race)
from vfairness import HierarchicalGateConfig
hconfig = HierarchicalGateConfig(
check_overall=True,
check_single_attributes=True,
check_intersections=True,
intersection_depth=2,
min_group_size=30,
default_intersection_threshold_multiplier=1.2, # 20% relaxed
per_intersection_thresholds={
'Female_Black': {'demographic_parity_difference': 0.15},
},
)
decision = gate.evaluate_hierarchical(
y_true, y_pred,
protected_attrs={'gender': gender, 'race': race},
hierarchical_config=hconfig,
)
for level, result in decision.level_results.items():
print(f"{level}: {result.status.value}")
for warning in decision.small_sample_warnings:
print(f"WARNING: {warning.message}")
Small-Sample Warnings
Groups with fewer samples than min_group_size emit
SmallSampleWarning objects instead of silently producing unreliable metrics.
Each warning includes the group name, sample size, and recommended minimum.
Deployment Policies: Required Coverage NEW
The gate knows what it was configured to check, not what a deployment
requires. So switching a check off, leaving an attribute out or loosening a
threshold still ends in approved=True on the levels that ran.
A CoveragePolicy states the requirement separately from the
configuration, and evaluate_against_policy() compares the two.
It does not change the measurement: it names every difference.
Worked example: required scope versus executed scope
400 applicants in four cells of 100. Each attribute alone is balanced, so women, men, group x and group y are all selected at 50%. The combined cells are selected at 80%, 20%, 20% and 80%. The policy requires gender, race and their intersection; the pipeline has intersections switched off.
from vfairness import CoveragePolicy, GateConfig, HierarchicalGateConfig, ModelFairnessGate
# REQUIRED scope: what the deployment policy says must be covered.
policy = CoveragePolicy(
policy_id="hiring-eu",
version="3",
required_attributes=["gender", "race"],
required_intersections=[("gender", "race")],
required_metrics={"demographic_parity_difference": 0.1},
min_group_size=30,
)
# EXECUTED scope: what this pipeline is configured to run.
gate = ModelFairnessGate(config=GateConfig(
metrics=["demographic_parity_difference"],
thresholds={"demographic_parity_difference": 0.1},
))
decision = gate.evaluate_against_policy(
policy, y_true, y_pred, {"gender": gender, "race": race},
hierarchical_config=HierarchicalGateConfig(check_intersections=False),
)
decision.measurement.status # GateStatus.APPROVED (the levels that ran)
decision.permitted # False (the deployment decision)
for item in decision.items:
print(item.label, item.state.value, item.outcome.value)
# gender assessed pass
# race assessed pass
# gender × race omitted_by_configuration not_measured
decision.reasons
# ['gender × race, demographic_parity_difference: omitted by configuration:
# check_intersections is off, so no level compared this intersection']
With the intersection switched on (and
default_intersection_threshold_multiplier=1.0, see below) the
same policy reports gender × race as assessed with a
measured breach of 0.6 against the bound of 0.1, and the measurement itself
is BLOCKED. Still not permitted, now for the right reason.
Four coverage states, and the outcome kept apart
| State | Means | Next action |
|---|---|---|
assessed | A level compared it, enforced at least as strictly as the policy, on groups large enough | Read the outcome |
insufficient_evidence | It ran, but a group or a rate denominator is below the policy's minimum, or the value could not be measured | Collect more data |
omitted_by_configuration | A level switched off, the metric not configured or not blocking, or a threshold looser than the policy bound. The reason names the setting | Fix the settings |
input_absent | An attribute it needs was not supplied. The required scope is never reduced to what was supplied | Supply the attribute |
The measured outcome (pass, fail,
not_measured) is graded against the policy bound and recorded
separately, so a five-person group that happens to pass is still
insufficient evidence, never a pass, and never a fairness failure either.
permitted is True only when every required item is assessed and
passes and the measurement was not blocked.
What does not change
- Without a policy, every result is the same as before. Every decision now also
carries
evaluated_scope: the levels that ran, the thresholds they applied, and the group sets left out with the setting that left them out. approvedstill means "nothing blocked on the levels that ran", andCONDITIONALkeeps its meaning. Under a policy neither means "may be deployed";decision.permitteddoes.gate.create_github_check(decision)reportsfailurewhenever a supplied policy is not met.FairnessReportCard(decision)leads with the policy result instead of "Approved for deployment".
The default intersection relaxation
HierarchicalGateConfig relaxes intersection thresholds by 1.2 by
default, so 0.1 becomes 0.12 at the intersection. Under a policy bound of 0.1
that is looser, and the intersection is reported as omitted by configuration
with the multiplier named. Set
default_intersection_threshold_multiplier=1.0, or write the relaxed
bound into the policy if the policy accepts it.
What belongs to the integration
The library compares, and nothing more. It has no parameter for an exception or an approver, so nothing a caller passes turns a coverage gap into a permission. Which policy applies to which deployment, who may grant an exception and how that person is verified, its scope, rationale, evidence, expiry and revocation belong to the integration that enforces the policy, which also keeps the historical assessment. Each decision carries SHA-256 fingerprints of the policy and of the effective configuration. They identify which policy and which settings were used; they are not signatures.
pytest Integration
vfairness provides multiple layers of pytest integration, from simple assertions to a full test suite with JUnit XML export.
assert_fairness()
# test_fairness.py
from vfairness import assert_fairness
def test_model_is_fair():
assert_fairness(
y_true, y_pred, gender,
metrics=['demographic_parity_difference'],
thresholds={'demographic_parity_difference': 0.1},
)
FairnessTestSuite
from vfairness import FairnessTestSuite
suite = FairnessTestSuite(
protected_attributes=['gender'],
metrics=['demographic_parity_difference'],
thresholds={'demographic_parity_difference': 0.1},
)
results = suite.test_predictions(
y_true, y_pred, gender,
attr_name="gender",
raise_on_failure=False, # record failures in the XML instead of raising
)
xml = suite.to_junit_xml() # For CI/CD integration
By default test_predictions raises FairnessAssertionError
on the first failing metric (pytest style). For CI reporting, pass
raise_on_failure=False so failing tests are recorded in the
JUnit XML and the pipeline gates on that report.
pytest Plugin NEW
The vfairness pytest plugin registers automatically via the pytest11 entry point.
It provides:
| Feature | Description |
|---|---|
@pytest.mark.fairness | Tag a test as a fairness test |
@pytest.mark.fairness_gate | Tag a test as a gate-level check |
fairness_gate fixture | Pre-configured ModelFairnessGate factory |
assert_fairness_fn fixture | The assert_fairness function as a fixture |
| Terminal summary | Prints fairness test results at end of run |
Fairness Report Card NEW
The FairnessReportCard generates structured markdown reports for automated
PR comments. It supports both simple and hierarchical gate decisions.
from vfairness import FairnessReportCard
card = FairnessReportCard(decision, model_name="loan-model-v3")
print(card.to_markdown())
# For GitHub API
payload = card.to_github_comment_payload()
# POST to /repos/{owner}/{repo}/issues/{pr_number}/comments
DevOps Templates
vfairness ships with ready-to-use templates for common DevOps platforms.
| File | Description |
|---|---|
.github/workflows/fairness-checks.yml |
GitHub Actions workflow: runs fairness tests, evaluates gate, posts PR comment |
.gitlab-ci-fairness.yml |
GitLab CI config with fairness-tests and fairness-gate jobs |
.github/PULL_REQUEST_TEMPLATE.md |
PR template with fairness checklist |
.pre-commit-hooks.yaml |
Pre-commit hook definitions for config and model card checks |
API Summary
| Function / Class | Module | Description |
|---|---|---|
log_fairness_to_mlflow() | evaluation | Log metrics to MLflow |
log_fairness_to_wandb() | evaluation | Log metrics to W&B |
@auto_log_fairness | evaluation | Auto-logging decorator |
ModelFairnessGate | operations.cicd | Deployment gate |
HierarchicalGateConfig | operations.cicd | Hierarchical gate config |
IntersectionalGateDecision | operations.cicd | Hierarchical gate result |
SmallSampleWarning | operations.cicd | Group size warning |
FairnessReportCard | operations.cicd | PR comment generator |
FairnessTestSuite | operations.cicd | Test suite with JUnit |
assert_fairness() | evaluation | pytest assertion |
check_fairness_config() | operations.cicd | Pre-commit: config check |
check_model_card() | operations.cicd | Pre-commit: model card check |
Implementation Overview
A summary of the workflow integration capabilities provided by vfairness.
| Capability | vfairness Implementation |
|---|---|
| Experiment tracking (MLflow) | log_fairness_to_mlflow() |
| Experiment tracking (W&B) | log_fairness_to_wandb() |
| Auto-logging wrappers | @auto_log_fairness |
| Pre-commit hooks | check_fairness_config(), check_model_card() |
| PR template | .github/PULL_REQUEST_TEMPLATE.md |
| CI/CD pipelines | GitHub Actions + GitLab CI YAML templates |
| Automated PR comments | FairnessReportCard |
| pytest plugin | pytest11 entry point + markers + fixtures |
| Intersectional gate checking | evaluate_hierarchical() + HierarchicalGateConfig |
| Per-intersection thresholds | HierarchicalGateConfig.per_intersection_thresholds |
| Small-sample warnings | SmallSampleWarning |
| Required coverage before deployment | CoveragePolicy + evaluate_against_policy() → PolicyDecision |