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.

Jupyter notebook, Workflow Integration Demo: 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

python
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

python
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

python
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.

python
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

yaml
# .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

HookDescriptionFiles 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.

python
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:

  1. Overall — across all groups
  2. Single-attribute — per individual protected attribute (gender, race, etc.)
  3. Intersectional — combinations of attributes (gender × race)
python
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.

python
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

StateMeansNext action
assessedA level compared it, enforced at least as strictly as the policy, on groups large enoughRead the outcome
insufficient_evidenceIt ran, but a group or a rate denominator is below the policy's minimum, or the value could not be measuredCollect more data
omitted_by_configurationA level switched off, the metric not configured or not blocking, or a threshold looser than the policy bound. The reason names the settingFix the settings
input_absentAn attribute it needs was not supplied. The required scope is never reduced to what was suppliedSupply 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.
  • approved still means "nothing blocked on the levels that ran", and CONDITIONAL keeps its meaning. Under a policy neither means "may be deployed"; decision.permitted does.
  • gate.create_github_check(decision) reports failure whenever 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()

python
# 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

python
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:

FeatureDescription
@pytest.mark.fairnessTag a test as a fairness test
@pytest.mark.fairness_gateTag a test as a gate-level check
fairness_gate fixturePre-configured ModelFairnessGate factory
assert_fairness_fn fixtureThe assert_fairness function as a fixture
Terminal summaryPrints 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.

python
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.

FileDescription
.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 / ClassModuleDescription
log_fairness_to_mlflow()evaluationLog metrics to MLflow
log_fairness_to_wandb()evaluationLog metrics to W&B
@auto_log_fairnessevaluationAuto-logging decorator
ModelFairnessGateoperations.cicdDeployment gate
HierarchicalGateConfigoperations.cicdHierarchical gate config
IntersectionalGateDecisionoperations.cicdHierarchical gate result
SmallSampleWarningoperations.cicdGroup size warning
FairnessReportCardoperations.cicdPR comment generator
FairnessTestSuiteoperations.cicdTest suite with JUnit
assert_fairness()evaluationpytest assertion
check_fairness_config()operations.cicdPre-commit: config check
check_model_card()operations.cicdPre-commit: model card check

Implementation Overview

A summary of the workflow integration capabilities provided by vfairness.

Capabilityvfairness Implementation
Experiment tracking (MLflow)log_fairness_to_mlflow()
Experiment tracking (W&B)log_fairness_to_wandb()
Auto-logging wrappers@auto_log_fairness
Pre-commit hookscheck_fairness_config(), check_model_card()
PR template.github/PULL_REQUEST_TEMPLATE.md
CI/CD pipelinesGitHub Actions + GitLab CI YAML templates
Automated PR commentsFairnessReportCard
pytest pluginpytest11 entry point + markers + fixtures
Intersectional gate checkingevaluate_hierarchical() + HierarchicalGateConfig
Per-intersection thresholdsHierarchicalGateConfig.per_intersection_thresholds
Small-sample warningsSmallSampleWarning
Required coverage before deploymentCoveragePolicy + evaluate_against_policy() → PolicyDecision