CI/CD for Machine Learning: Automating Model Testing, Training and Deployment with GitHub Actions
A student builds a machine learning API that accepts six house measurements and returns a historical price estimate. The class has already learned how to monitor it for data drift. Now three team members start changing different things: one edits the FastAPI prediction endpoint, another retrains the Random Forest, and a third updates the Python dependencies. The code still looks familiar—but will the application return valid predictions, load the correct model and remain secure after everyone’s changes? How can the team catch problems before users encounter them?
This is the purpose of CI/CD for machine learning. In this tutorial, you will create a GitHub Actions continuous integration workflow, automate Python tests and candidate training, apply a model evaluation gate, prepare an approved container-image release, and design deployment approval and rollback procedures. The project builds on Topic 94: MLOps and Monitoring and Topic 93: Building ML APIs with FastAPI without repeating the entire earlier lessons.
Verification disclosure (25 November 2026): An original companion project was created with three GitHub Actions YAML workflows, a complete FastAPI implementation, source-verification and training scripts, a conservative release gate, synthetic-model tests, a Dockerfile and operational documentation. Its local pytest suite passed 16 tests; those tests use controlled fictional model fixtures and do not establish accuracy on Ames Housing. No actual GitHub repository or Action run, trusted approved Ames artifact, GHCR image, Docker build, protected release environment, public API or hosted deployment was created. Current GitHub documentation was checked for workflow conventions and action-pinning guidance; production workflows require verified full-length action commit SHAs and authorized environment setup.
What does CI/CD mean in machine learning?
Continuous integration (CI) means automatically checking and testing code changes as they are introduced to a shared project. Continuous delivery means keeping a tested change in a condition where authorized people can decide to release it. Continuous deployment goes further: qualified changes are released automatically under an established policy. These terms are closely related, but the last two should not be treated as interchangeable.
Our beginner project adopts continuous integration plus controlled continuous delivery. Pull requests run unprivileged tests. Approved code can trigger separate candidate-model training. A new model must pass a predefined evaluation gate and a human review before packaging. Publication of a Docker image to a registry is another step; running the image on an authorized public host is a separate deployment operation.
Why ML CI/CD needs more than ordinary software tests
Traditional software pipelines often check imports, code syntax, unit tests, integrations, dependencies and packaging. A machine learning system has additional moving parts: training data, feature definitions, fitted preprocessing, model hyperparameters, evaluation sets, saved artifacts and changes in real-world populations. A change to one of these can silently alter predictions even if every HTTP endpoint still responds with status 200.
A high validation score also does not prove that the API will load on the intended server, reject malformed JSON or protect credentials. Software correctness and model validity must be evaluated independently. This is why the project has inexpensive tests using synthetic model fixtures, a separate genuine-data candidate-training workflow, and another gated release process.
| Check | Conventional software | Machine learning extension |
|---|---|---|
| Code | Syntax, tests, dependencies | Feature transformation and inference |
| Data | Input validation | Source version, leakage, target and cohort |
| Quality | Application correctness | Validation MAE and performance regressions |
| Release | Build, approval, deployment | Model provenance and rollback-compatible schema |
| Operations | Availability, errors | Data drift and actual predictive performance |
Git and GitHub: learn the vocabulary before YAML
Git records versions of source files. A repository contains those files and their history. A commit is a recorded change; a branch lets someone work independently; and a pull request proposes changes for discussion and review. When approved changes are merged into the main branch, they become part of that branch’s history. A commit SHA identifies a particular recorded revision.
GitHub is a service for hosting repositories and collaborating on them. GitHub Actions can execute jobs in response to eligible repository events. A GitHub repository is not itself a running FastAPI server, and a green check on a pull request does not mean anything has been deployed to users. A responsible project keeps software changes, training runs and production releases distinct.
How GitHub Actions workflows operate
A workflow is written in YAML inside .github/workflows/. It names the events that trigger automation, the jobs to perform, the steps inside each job and the runner that executes them. An action such as actions/setup-python performs a reusable setup task; a shell step such as python -m pytest -q runs ordinary code.
A hosted runner is a temporary computing environment, not a permanent data store. Separate jobs generally do not share a filesystem. Transfer approved outputs through explicit artifacts or another controlled storage mechanism. The needs field can express job dependencies, while if decides whether a step or job should execute. These concepts make longer pipelines understandable and auditable.
Understand the triggers: pull_request, push, dispatch and schedule
A pull_request event lets eligible proposed changes trigger CI. A push event can run checks after changes reach main. workflow_dispatch lets authorized users trigger a workflow manually. A schedule event can run periodically, though GitHub scheduling has default-branch and timing conditions and scheduled jobs may be delayed.
In this project, CI responds to pull requests and main-branch pushes. Candidate training is manual rather than automatically attached to every inexpensive code change. Image release is also manual and approval-oriented. None of these workflows includes an active retraining schedule. A scheduled training job, if justified later, should create a candidate report—not silently replace the current approved model.
YAML structure, indentation and expressions
YAML uses indentation to group named settings and lists. A simple workflow has fields such as name, on, permissions and jobs. A list item begins with a dash; nested values are indented below their parent. YAML is sensitive to indentation, and GitHub Actions also interprets special expression syntax such as ${{ github.ref }}.
General YAML parsers can disagree about special keys and may not validate GitHub-specific semantics. For real workflows, use a workflow-aware tool such as actionlint and execute the pipeline in a properly configured repository. The included YAML is a project starting point whose logical steps correspond to files actually present in the ZIP; it has not been executed on GitHub in this session.
name: Hello CI
on:
workflow_dispatch:
permissions:
contents: read
jobs:
example:
runs-on: ubuntu-latest
steps:
- name: Print message
run: echo "GitHub Actions started"
# Educational YAML: the workflow must be committed to GitHub to run.
The complete CI/CD architecture: three deliberately separated workflows
The first workflow, ci.yml, performs syntax, feature-schema, basic Ruff linting and pytest checks without production secrets or a downloaded real model. The second, train-candidate.yml, requires an authorized manual trigger and checks a genuine dataset before training two historical candidate configurations. It saves reports and unapproved candidate artifacts for inspection. The third, release-image.yml, prepares controlled publication of a container image only after trusted approved model files are provisioned.
There is no automatic link that transfers a model from an unprivileged pull request into production. Such a link would create a supply-chain risk. This division also reduces cost: a typo fix can be checked quickly without retraining the Random Forest, while a deliberate modeling change can receive its own evaluation and approval process.

Understand the downloadable project folder
The ZIP includes app/ for the FastAPI service, scripts/ for schema validation, data verification, training, evaluation and release checks, tests/ for automated logic, data/dataset_manifest.json for source provenance, and model/feature_schema.json for the exact six-field contract. Three YAML files live in .github/workflows/, while a Dockerfile and documentation explain release requirements.
The model/approved_model.joblib and matching approved metadata are intentionally absent. Nobody has generated an authentic Ames model in this task, and inventing one would make the exercise scientifically misleading. The README documents the exact steps needed to obtain the source, compare candidate models, approve a real artifact and verify its runtime before exposing predictions.
ml-ci-cd-github-actions/
app/main.py # FastAPI endpoints
app/schemas.py # Ordered feature definitions
scripts/fetch_verified_data.py
scripts/train_candidate.py
scripts/evaluate_candidate.py
scripts/check_release_gate.py
scripts/validate_feature_schema.py
scripts/verify_artifact.py
tests/ # 16 passing local tests
data/dataset_manifest.json
model/feature_schema.json
.github/workflows/ci.yml
.github/workflows/train-candidate.yml
.github/workflows/release-image.yml
Dockerfile
requirements.txt
requirements-ci.txt
README.md
docs/
Six input fields: your machine learning API contract
The educational housing service uses GrLivArea, OverallQual, YearBuilt, TotalBsmtSF, GarageCars and FullBath to predict SalePrice. The area values use square feet; the quality variable is an ordinal rating; construction year is a calendar year; and the remaining inputs are quantities or counts. The service accepts a named JSON object validated by Pydantic before constructing a DataFrame with the saved column order.
Schema compatibility testing matters because switching square feet to square metres or reordering bare positional values can produce plausible-looking errors. The included tests verify that the documented feature list has the intended order and no duplicates, and that an actual fitted synthetic test Pipeline expects a complete six-column input. This is stronger than checking the length of a list alone, though genuine Ames compatibility still requires verification of a real approved model.
Separate inexpensive tests from real-model evaluation
Every untrusted pull request should be able to run cheap code tests without installing deployment secrets, calling production APIs or deserializing unknown model files. The companion project uses controlled, generated numeric records to train a small Random Forest fixture in memory. Tests inspect finite inference outputs, reject an incomplete feature schema, save and reload their own temporary trusted Pipeline, and exercise FastAPI routes with a test model.
These tests can catch programming bugs without proving historical predictive performance. They are explicitly synthetic software checks. A genuine model evaluation must later use the real, permitted historical Ames records and the agreed chronological split. A service can pass every fixture test yet still make large errors for actual properties.
Automated code quality and Python syntax checks
Ruff checks selected Python style and probable coding errors, while python -m compileall -q app scripts tests checks Python syntax compilation. The CI file runs a conservative Ruff error selection plus a separate schema script and pytest. The package includes a pyproject.toml configuration so lint decisions are visible rather than implicit.
Static checks help find certain defects but cannot prove the model’s accuracy, eliminate data leakage or certify the security of a deployment. A formatter can make code consistent without making its logic correct. Teams should gradually expand lint and typing policies after establishing a clean baseline, rather than disabling failing checks simply to obtain a green status.
A tested release gate, not automatic deployment authorization
An evaluation gate compares measurements against a documented policy. In this project, candidate-model MAE must improve by at least 2% relative to the reference configuration on the same approved validation period. The program also checks minimum sample count, expected dataset ID, period compatibility, nonfinite metrics and a provenance flag. If basic conditions fail, it exits with failure rather than writing an approval label.
The 2% threshold is a hypothetical classroom policy, not an industry law. More importantly, passing the metric gate is not human release approval. It does not certify fairness, robustness, input compatibility, safe deserialization or infrastructure readiness. The script returns a limited metric verdict, which a human reviewer must combine with other evidence.
Calculate a fictional improvement and regression correctly
Suppose a champion has validation MAE of $24,000 and a challenger has $21,600. The difference is $2,400 and the relative reduction is (24,000−21,600)/24,000 × 100 = 10%. In a second fictional scenario, a challenger has MAE of $25,200: the error is $1,200 higher, a 5% deterioration relative to the same $24,000 champion. Under a non-inferiority-style rule requiring no increase, the second candidate fails.
The calculations were verified as ordinary arithmetic and are included in release-gate tests. They are not actual Ames Housing results. A seemingly small advantage should be interpreted with validation sample size, uncertainty, subgroup performance and operational cost in mind. The code is designed to prevent a nonfinite metric or an inappropriately tiny validation set from passing.

| Fictional candidate | Validation MAE | Relative result | Metric gate |
|---|---|---|---|
| Champion reference | $24,000 | Reference | N/A |
| Challenger A | $21,600 | 10% lower error | Passes 2% example |
| Challenger B | $25,200 | 5% higher error | Fails |
Model training must use a trusted and chronologically separated dataset
The intended source is OpenML dataset 42165, historical Ames Housing. Training uses sale years 2006–2008, validation uses 2009, and 2010 is reserved for an independent retrospective examination. Sale years help partition data; they are not secretly added to the six API features. The dataset manifest records the source and explicitly leaves a checksum unverified until a real source snapshot can be obtained.
The code checks required columns, numeric target validity, expected dataset size, year assignments and minimum period sizes before training. It does not invent exact per-year counts. If the downloaded representation unexpectedly differs, the workflow must stop for investigation instead of accepting a changed schema under the same dataset ID.
Champion–challenger training as a separate workflow
The candidate-training script fits two median-imputation Random Forest Pipelines on exactly the same 2006–2008 training records. The reference configuration uses 80 trees with minimum leaf size 2; the candidate uses 140 trees with minimum leaf size 4. Both use seed 95 and are compared using 2009 MAE on identical records. Their separately stored metadata include parameter settings, actual validation rows, MAE and artifact checksum.
This controlled comparison makes it possible to test a change without overwriting the approved model. The candidate is not assumed superior just because it has more trees or a newer version label. The workflow uploads unapproved candidate reports and model files only for authorized review; an artifact arriving from a workflow does not itself acquire release authorization.
Avoid leaking future outcomes into model selection
If students repeatedly compare model configurations against 2010 outcomes and choose the one with the best score, they have used the supposed final evaluation period for model selection. The resulting number can become optimistic. The project preserves 2010 outcomes for a separately declared retrospective check and uses 2009 for candidate comparison. It also fits the median imputer inside the training Pipeline rather than calculating replacement values from all time periods.
A chronological split is particularly appropriate when practising a historical sequence, though it still cannot guarantee how a model will behave in a future market. For classification projects, extra gates may need minority recall, Average Precision, calibration and false-negative costs; a regression MAE gate alone is not a universal model-selection procedure.
Artifact provenance, checksums and serialization risk
A model artifact should be traceable to a trusted source revision, dataset version, training configuration, evaluation report, dependency environment and approval. In the educational package, training produces a Joblib file and SHA-256 metadata. The local release verifier checks a supplied approved file against its recorded checksum, declared feature schema, Scikit-learn version and release-approval metadata. It rejects a missing artifact instead of creating a fake one.
Joblib relies on pickle-based deserialization, which can execute code when loading an untrusted object. Comparing a digest with a text file controlled by the same attacker does not establish independent authenticity. Thus provenance, review and restricted artifact promotion are mandatory. Never automatically deserialize model files uploaded from untrusted pull requests or use a dependency cache as a trusted model registry.
Dependency caches and workflow artifacts solve different problems
GitHub Actions caching can reuse dependency downloads to reduce repeated installation time. Its contents are optimizations, not an authorization mechanism. A workflow artifact preserves outputs such as reports or generated files and can transfer data between jobs or be available to reviewers. Retention policies, size limits and access rights apply.
A cache is not a model registry. Nor does an uploaded artifact automatically become safe for a privileged release step. A separate workflow must verify the origin and identity of any promoted model, its evaluation and the release approval. The example candidate-training workflow uses short-lived artifacts for review; it does not send untrusted blobs directly into the protected image publisher.
Least-privilege GitHub Actions permissions
A regular pull-request CI job usually only needs read access to repository contents. The example therefore sets permissions: contents: read, uses checkout without persisted credentials, and provides no production secrets. The separate image-publishing job may need packages: write to publish to GitHub Container Registry. These privileges should exist only where required.
More powerful tokens on untrusted pull requests create risks of secret exposure, repository modification and malicious releases. Avoid direct interpolation of attacker-controlled text into shell commands. Review workflow modifications carefully and be cautious with privileged events such as pull_request_target and downstream consumers of untrusted workflow artifacts.
Pin maintained actions and review changes
GitHub documentation advises pinning third-party Actions to verified full commit SHAs, because moving tags do not provide the same immutability guarantee. The educational workflows use readable published action version tags such as actions/checkout@v6 and actions/setup-python@v6, matching official examples checked during preparation. Those tags are not represented as immutable production pins.
Before using the workflows to publish real images, resolve the selected action releases to their actual trustworthy 40-character commit SHAs and follow your repository’s security policy. Never invent an SHA. A pinned version can still have vulnerabilities, so updates, review and dependency security checks remain necessary. GitHub’s feature availability and repository settings may also evolve.
Secrets, API credentials and OpenID Connect
Deployment tokens, private repository credentials, cloud keys and API secrets should not appear in committed source files, command logs or public WordPress JavaScript. Use supported GitHub repository or environment secrets where appropriate and grant access only to the jobs requiring them. For GHCR in eligible GitHub workflows, the built-in GITHUB_TOKEN may provide the required package-publishing permission without an additional personal access token.
OpenID Connect (OIDC) can allow compatible cloud platforms to trust short-lived GitHub identities instead of requiring long-lived stored cloud credentials. However, granting id-token: write alone does not create that trust. The provider must be configured to verify issuer, audience, repository, branch and environment claims and to grant only the required scope.
Review branches, pull requests and release environments
Protecting the main branch can require pull-request reviews, passing checks, limited force pushes and appropriately controlled workflow changes. GitHub deployment environments may offer required reviewers, branch restrictions and environment-specific secrets, depending on repository visibility and plan. These features must be configured in the actual account; naming an environment in YAML alone is not evidence that review protection is active.
The educational image-release workflow refers to an environment called release and intentionally cannot proceed without a real approved model being supplied. Before activation, an operator must verify actual protection rules, approved artifact provisioning and package access. Source-code reviews and model approval are related but different: a developer may approve a code change without certifying the new estimator.
Docker packaging and GitHub Container Registry
A Dockerfile describes an environment that installs Python dependencies, copies the FastAPI application and approved model files, runs under a non-root user and starts Uvicorn. A Docker build creates an image; a push uploads it to a registry such as GHCR; a deployment configures a hosting platform to execute it. These are separate operations with separate points of failure.
The release workflow illustrates an approved image tagged with the source commit SHA and published to ghcr.io. For operational release records, an immutable image digest is preferable to relying only on a mutable tag. In this session Docker was not executed and GHCR was not accessed. No real public URL, image or release success is claimed.
Safe promotion and independent deployment verification
A mature release process confirms the approved model version and commit, verifies the image digest and runtime dependencies, checks applicable authorization, deploys to a supported host, then tests real endpoints. For this FastAPI service the smoke test covers GET /health, GET /ready, GET /model-info, a valid POST /predict and invalid-input rejection. The model version should match the expected artifact.
A local TestClient success is valuable evidence about application code, but not proof that a cloud server is running or network-accessible. A GHCR upload is not equivalent to deployment. Because no authorized hosting target was connected to this task, the package leaves actual deployment provider-specific rather than inserting invented commands.
Why deployment concurrency matters
Two people might approve different changes at nearly the same time. Without controls, an older release could finish after a newer one and unexpectedly replace it. GitHub Actions concurrency can serialize or cancel eligible workflow runs according to a chosen group and cancellation policy. The example separates CI concurrency from controlled candidate-training and image-release groups.
Cancellation is not a universal safety improvement: abruptly terminating a deployment halfway through could cause inconsistent infrastructure or interrupt a release. The training and release examples deliberately avoid canceling active runs without an explicit procedure. In advanced systems, a single protected release controller or provider-native deployment lock may be preferable.
Plan rollback before publication
A rollback restores a previously approved compatible image and model if a release causes unacceptable errors. Operators must know the earlier immutable artifact reference, model version, feature schema and appropriate dependencies. The runbook says to stop further promotion, identify the previous approved image, restore it on the actual host and verify readiness and safe predictions.
A registry label change alone may not replace a model already loaded into a running FastAPI process. Likewise, redeploying an earlier image does not guarantee recovery if external data schemas have changed incompatibly. Real rollback requires rehearsal, authorization and a documented incident response; the ZIP provides a plan, not evidence that rollback infrastructure exists.
Monitoring connects CI/CD to the next decision
Topic 94 introduced data-quality checks, distribution drift, prediction drift and model performance with verified outcome labels. Those signals can lead to a new investigation and perhaps a candidate-training workflow. A monitoring alert does not automatically authorize retraining, and successful retraining does not automatically authorize model promotion. A safe process separates investigation, evaluation, review and release.
For a public model, operational monitoring also considers HTTP failures, request duration, resource usage and availability. Statistical monitoring may require privacy-preserving aggregate features and verified outcomes. Do not collect sensitive student, health or housing information merely because automation makes it easy.
Reproducibility, random seeds and evaluation uncertainty
Recording a random seed helps make random operations repeatable, but it is not sufficient for end-to-end reproducibility. The source snapshot, Python and package versions, feature definitions, data preparation, training algorithm, computing environment and exact commit also matter. Results may still vary across implementations or hardware. A saved model should preserve all fitted preprocessing steps required for inference.
The metric gate’s fictional 10% improvement is easy to calculate; a small actual difference between trained models may be noisy. Where the stakes warrant it, compare paired observations, uncertainty ranges, important subgroups and stability. Do not claim that a candidate is statistically superior simply because its MAE is slightly lower on one small validation cohort.
What the tests actually proved
The synthetic test suite checks feature-schema order, valid and invalid Pydantic requests, prediction finiteness, trusted model round-trip serialization, FastAPI responses with a controlled injected test model, and release-gate behaviour for improvement, regression, small-sample failure, nonfinite error and unverified reports. All 16 local pytest checks passed.
This evidence supports the correctness of those exercised code paths. It does not prove that GitHub Actions executed on a hosted runner, that authentic Ames records were downloaded, that a model was evaluated on real historical houses, or that a container is secure. Students must label each verification layer precisely in their reports.
How to debug failed workflows productively
If CI does not start, check the workflow path, event and branch filters. If dependencies fail to install, inspect supported Python versions, package compatibility and network restrictions. If a schema test fails, inspect the declared six fields rather than deleting the assertion. If pytest fails, reproduce the error locally and examine the smallest failing case. For a source-download failure, verify the data source and whether the environment allows outbound access.
For a candidate-training failure, examine target validity, partition sizes and evaluation JSON. If the performance gate fails, the correct outcome may be rejection rather than changing the threshold. If an image build fails, inspect Docker paths, pinned dependencies and approved artifact availability. If registry publishing or deployment fails, examine credentials, protected environments, package permissions and actual host logs. Never disable security or correctness checks merely to obtain a green icon.
A ten-task student capstone: a controlled ML release
Task 1: inspect Git and GitHub concepts and draw a pull-request workflow. Task 2: confirm six Ames feature names and target. Task 3: run compile, schema and synthetic model tests. Task 4: explain why untrusted PR jobs cannot load production secrets. Task 5: inspect ci.yml and identify its event, runner, permissions and testing steps.
Task 6: retrieve and verify the authentic historical dataset under a suitable account. Task 7: train reference and candidate configurations using 2006–2008 only; compare on 2009 without consulting the reserved 2010 outcomes. Task 8: calculate and interpret metric-gate results, write a release recommendation and review artifact provenance. Task 9: explain protected image publication, host deployment and smoke testing as separate operations. Task 10: write rollback, monitoring, security and reproducibility documentation identifying every completed and uncompleted step.
Thirty original practice questions with worked answers
Question 1: Define CI.
Worked answer: Continuous integration automatically checks code changes as they are integrated into a shared project.
Question 2: How is continuous delivery different from continuous deployment?
Worked answer: Delivery produces a release-ready change awaiting controlled approval; deployment automatically releases qualified changes under an authorized policy.
Question 3: What is a GitHub repository?
Worked answer: A version-controlled project hosted on GitHub.
Question 4: What does a pull request do?
Worked answer: It proposes changes for review and automated checks before merging.
Question 5: Where do GitHub workflow YAML files usually live?
Worked answer: .github/workflows/.
Question 6: Name the three workflow files in this project.
Worked answer: ci.yml, train-candidate.yml and release-image.yml.
Question 7: What is a GitHub Actions runner?
Worked answer: The computing environment that executes workflow jobs.
Question 8: What is a job?
Worked answer: A group of steps executed in a runner environment.
Question 9: What does workflow_dispatch mean?
Worked answer: An eligible workflow can be started manually by an authorized user.
Question 10: Does schedule automatically deploy a model?
Worked answer: No; scheduling is an event trigger, not a model approval policy.
Question 11: Why keep pull-request CI unprivileged?
Worked answer: Untrusted submitted code must not access production secrets or deployment rights.
Question 12: What does permissions: contents: read do?
Worked answer: It limits the workflow token’s repository-content permission to read.
Question 13: Why test feature order?
Worked answer: Misordered positional values can produce incorrect model predictions.
Question 14: What is the target of the Ames model?
Worked answer: SalePrice, a historical sale-price variable.
Question 15: How many primary prediction features are used?
Worked answer: Six named numerical property features.
Question 16: What do the 2006–2008, 2009 and 2010 periods mean?
Worked answer: Training, validation and reserved later retrospective evaluation respectively.
Question 17: Why should test fixtures be synthetic in unprivileged CI?
Worked answer: They support cheap controlled code checks without risky model artifacts or real-data downloads.
Question 18: Does a passing unit test prove model generalization?
Worked answer: No. Real predictive quality requires independent evaluation with suitable outcomes.
Question 19: Compute improvement from $24k to $21.6k MAE.
Worked answer: (24,000−21,600)/24,000 = 10% relative reduction.
Question 20: Compute deterioration from $24k to $25.2k MAE.
Worked answer: (25,200−24,000)/24,000 = 5% relative increase.
Question 21: Is the project’s 2% gate a universal industry threshold?
Worked answer: No, it is a documented fictional teaching policy.
Question 22: What should happen if MAE is NaN?
Worked answer: Reject the report or gate rather than treating it as valid.
Question 23: Why keep candidate artifacts separate?
Worked answer: To prevent overwriting an approved model and to preserve provenance.
Question 24: What is the difference between a cache and an artifact?
Worked answer: A cache helps reuse dependencies; an artifact preserves workflow outputs.
Question 25: Is an artifact automatically trusted because GitHub stores it?
Worked answer: No. Verify its source, integrity and approval.
Question 26: Why is arbitrary Joblib loading unsafe?
Worked answer: Pickle-based deserialization can execute attacker-controlled code.
Question 27: What is a full commit SHA action pin?
Worked answer: An immutable reference to a specific reviewed action revision.
Question 28: What does GHCR store?
Worked answer: Container images, not automatically running web services.
Question 29: What does a smoke test check after deployment?
Worked answer: Real endpoint reachability, readiness, schema behaviour, finite inference and expected version.
Question 30: What is a rollback?
Worked answer: A controlled restoration of a previous trusted and compatible released version.
Eight practical release decisions
Scenario 1: A pull request passes pytest but the real model was never evaluated.
Approve code quality only; require a separate authentic model evaluation before release.
Scenario 2: A candidate has 10% lower MAE but its artifact comes from an unknown sender.
Reject unsafe deserialization and confirm trusted artifact provenance before consideration.
Scenario 3: An approved model uses a different feature order from the API.
Block release and reconcile the exact schema, rather than silently changing values.
Scenario 4: A training workflow unexpectedly reads 2010 targets when selecting hyperparameters.
Stop; restore the reserved evaluation boundary and redesign selection.
Scenario 5: Two releases run at the same time and threaten to overwrite one another.
Apply a documented concurrency policy or deployment lock and preserve immutable version references.
Scenario 6: A pipeline succeeds in GHCR but /ready fails on the cloud host.
Treat registry publication as distinct from deployment; investigate runtime and model loading.
Scenario 7: An operator cannot find the previous working model’s image digest.
Pause release until rollback resources are complete and verified.
Scenario 8: A metric gate passes, but performance is worse for an important subgroup.
Require human review and a broader quality assessment; do not equate one gate with overall safety.
Four-week learning roadmap
Week 1 — Foundations: learn Git commits, branches, pull requests, CI, delivery and deployment; inspect YAML workflow events, jobs, steps and runners. Week 2 — Software reliability: run Python syntax and Ruff checks, test feature order and synthetic inference, then investigate a deliberately failing test and document its fix.
Week 3 — Model evidence: obtain a verified historical dataset, compare controlled candidate configurations, calculate the validation gate and review feature-schema provenance. Week 4 — Safe releases: inspect action pinning, branch protection, release environments, Docker packaging, GHCR versus hosting, smoke tests, monitoring and rollback. Complete the capstone report, clearly distinguishing simulated work from actual remote execution.
Frequently asked questions about CI/CD for machine learning
What is CI/CD in machine learning?
A structured process for testing code and data, evaluating models, packaging approved artifacts and releasing changes with operational safeguards.
Can GitHub Actions test Python automatically?
Yes, once a valid workflow is committed to an eligible repository and triggered.
Can it train a Random Forest?
Yes, if the runner has sufficient dependencies, approved data access and computing resources.
Should every pull request retrain a full model?
Not necessarily; inexpensive synthetic tests are usually more appropriate for ordinary CI.
Does a green GitHub check mean the model is accurate?
No. It only proves that the checks actually run by that workflow met their assertions.
Can CI/CD use FastAPI?
Yes. TestClient can exercise endpoints without an external server; deployment remains separate.
Are the historical Ames scores in this article verified?
No. The project was tested with synthetic fixtures; authentic source training is pending.
Can Docker be used without GitHub Actions?
Yes. Docker and GitHub Actions are separate tools that can be combined.
Does pushing an image to GHCR make my API live?
No. A hosting platform must separately execute and expose the container.
What is a protected environment?
A GitHub release/deployment context that can enforce controls supported by the repository’s plan and configuration.
Do I need production API secrets in CI?
No. Ordinary pull-request tests should not receive them.
What is OIDC?
A way to establish short-lived identity-based authentication to supported providers after trust is configured.
Why use action commit SHA pins?
To select an immutable action revision instead of relying only on a changeable tag.
Does a new model automatically deserve promotion?
No. It must satisfy evidence-based quality, compatibility, security and approval requirements.
Were any GitHub workflows actually enabled?
No. The downloadable workflow files have not been committed to an authorized GitHub repository.
Can I schedule retraining later?
Yes where justified and authorized, but candidate creation should remain separate from approval and deployment.
Authoritative sources and related Notes for SHS topics
Consult GitHub Actions documentation, workflow syntax, Python build-and-test guide, secure use recommendations, Docker image publishing, Docker CI guidance, Scikit-learn model persistence and OpenML historical housing data. Verify product-specific capabilities and prices against current official sources before enabling remote services.
The lesson follows Topic 94: Monitoring, Drift and Retraining, Topic 93: FastAPI Model Serving, Topic 92: Streamlit Deployment, Topic 90: Feature Engineering and Topic 89: Hyperparameter Tuning.
Conclusion: automate checks, not unexamined decisions
GitHub Actions can make machine-learning engineering more disciplined by automatically checking code, validating feature contracts, running safe fixture tests and preparing documented candidate training. The most reliable educational design preserves boundaries: untrusted pull requests cannot access production secrets, candidate models do not overwrite approved artifacts, performance gates do not substitute for human release approval, and registry publication does not count as a verified live deployment.
The provided project establishes a substantial reproducible foundation, backed by 16 passing local tests. Completing authentic Ames training, pinning verified action SHAs, configuring GitHub protections and approvals, provisioning a trusted model, building an image and checking a real public host are separate next steps. A trustworthy engineering report is as precise about what remains unverified as it is about the working code.
Downloadable project: The complete Topic 95 ZIP contains the FastAPI application, 3 GitHub Actions workflow files, model/data schema manifests, Python scripts for dataset verification, controlled training, evaluation and acceptance gates, 16 locally passing software tests, Dockerfile, original diagrams, release policy, security checklist and rollback runbook. This ZIP does not contain a fabricated Ames model, remote Action run, published Docker image or live service.
2 responses to “CI/CD for Machine Learning: Automating Model Testing, Training and Deployment with GitHub Actions”