8000 ci: light gate on pull requests, full gate before a release by rafatahmed · Pull Request #220 · rafatahmed/Flahax · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,20 @@ jobs:
python -m unittest tests.test_product_phreeqc tests.test_acid_reference -v
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

# The full tier of the Test workflow on the tagged commit: Python 3.11-3.14, Windows, macOS and
# the exact three-OS coverage gate. Nothing is built or published unless it passes.
full-gate:
name: Full gate
needs: guard
if: needs.guard.outputs.publish == 'true'
uses: ./.github/workflows/test.yml
secrets: inherit
permissions:
contents: read

build:
name: Build distribution
needs: [guard, test, phreeqc-live]
needs: [guard, test, phreeqc-live, full-gate]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand Down
98 changes: 82 additions & 16 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,57 @@ on:
branches: [main]
pull_request:
workflow_dispatch:
# The release workflow calls this one: a release is the full tier.
workflow_call:

permissions:
contents: read

env:
CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }}

# A newer push to the same pull request replaces the run that is still going.
concurrency:
group: test-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

# Two tiers (docs/adr/0002). Pull requests and pushes to main run the light tier: Linux on
# Python 3.11-3.13 and one clean wheel/sdist check. A manual run of this workflow (Actions >
# Test > Run workflow) and the release workflow are the full tier: Python 3.14, Windows and macOS,
# the exact three-OS coverage gate and the Codecov upload.
jobs:
scope:
name: scope
runs-on: ubuntu-latest
outputs:
full: ${{ steps.scope.outputs.full }}
code: ${{ steps.scope.outputs.code }}
matrix: ${{ steps.scope.outputs.matrix }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
- id: scope
name: Choose the tier and whether code changed
env:
EVENT: ${{ github.event_name }}
BASE: ${{ github.event.pull_request.base.sha }}
run: |
full=false; code=true
light='{"include":[{"os":"ubuntu-latest","python-version":"3.11"},{"os":"ubuntu-latest","python-version":"3.12"},{"os":"ubuntu-latest","python-version":"3.13"}]}'
all='{"include":[{"os":"ubuntu-latest","python-version":"3.11"},{"os":"ubuntu-latest","python-version":"3.12"},{"os":"ubuntu-latest","python-version":"3.13"},{"os":"ubuntu-latest","python-version":"3.14"},{"os":"windows-latest","python-version":"3.13"},{"os":"macos-latest","python-version":"3.13"}]}'
matrix=$light
if [ "$EVENT" = workflow_dispatch ] || [ "$EVENT" = release ]; then
full=true; matrix=$all
elif [ "$EVENT" = pull_request ]; then
# Only documentation (docs/ and top-level .md files) changed: no code to test.
# A comparison that fails fails this job; it is never read as documentation only.
decision=$(python tools/ci_scope.py "$BASE" "$CANDIDATE_SHA")
code=${decision#code=}
fi
{ echo "full=$full"; echo "code=$code"; echo "matrix=$matrix"; } >> "$GITHUB_OUTPUT"

style:
runs-on: ubuntu-latest
steps:
Expand All @@ -32,17 +75,18 @@ jobs:
test:
# Linux keeps the check names "test (3.11)" ... that branch protection requires.
name: ${{ matrix.os == 'ubuntu-latest' && format('test ({0})', matrix.python-version) || format('test ({0}, {1})', matrix.os, matrix.python-version) }}
needs: scope
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ["3.11", "3.12", "3.13", "3.14"]
include:
- os: windows-latest
python-version: "3.13"
- os: macos-latest
python-version: "3.13"
matrix: ${{ fromJSON(needs.scope.outputs.matrix) }}
env:
# What this job does: the coverage run (full tier, 3.13), the plain run (the other light
# and full jobs), and the wheel/sdist check (every full job, one light job).
COVERAGE_RUN: ${{ needs.scope.outputs.code == 'true' && needs.scope.outputs.full == 'true' && matrix.python-version == '3.13' }}
PLAIN_RUN: ${{ needs.scope.outputs.code == 'true' && !(needs.scope.outputs.full == 'true' && matrix.python-version == '3.13') }}
DIST_RUN: ${{ needs.scope.outputs.code == 'true' && (needs.scope.outputs.full == 'true' || (matrix.os == 'ubuntu-latest' && matrix.python-version == '3.13')) }}
DOCS_ONLY_RUN: ${{ needs.scope.outputs.code != 'true' && matrix.python-version == '3.13' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand All @@ -51,15 +95,22 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- name: Install
if: needs.scope.outputs.code == 'true' || env.DOCS_ONLY_RUN == 'true'
run: python -m pip install -e . build
- name: Unit tests
if: matrix.python-version != '3.13'
if: env.PLAIN_RUN == 'true' && matrix.python-version != '3.13'
run: python -m unittest discover -s tests -t .
- name: Install coverage and support-test dependencies
if: matrix.python-version == '3.13'
if: (env.PLAIN_RUN == 'true' || env.COVERAGE_RUN == 'true' || env.DOCS_ONLY_RUN == 'true') && matrix.python-version == '3.13'
run: python -m pip install coverage==7.17.0 PyYAML==6.0.3 -r benchmarks/requirements.txt -r tools/requirements-benchmark-report.txt
- name: Unit tests (support dependencies installed)
if: env.PLAIN_RUN == 'true' && matrix.python-version == '3.13'
run: python -m unittest discover -s tests -t .
- name: Documentation tests (only documentation changed)
if: env.DOCS_ONLY_RUN == 'true'
run: python -m unittest tests.test_docs_site tests.test_docs_structure tests.test_documentation_migration tests.test_changelog tests.test_release_hygiene tests.test_file_headers
- name: Candidate-bound native coverage
if: matrix.python-version == '3.13'
if: env.COVERAGE_RUN == 'true'
shell: bash
env:
COVERAGE_FILE: build/coverage/.coverage
Expand All @@ -72,42 +123,49 @@ jobs:
python -m tools.ci_coverage report --candidate "$CANDIDATE_SHA" --output build/coverage
exit "$test_status"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always() && matrix.python-version == '3.13'
if: always() && env.COVERAGE_RUN == 'true'
with:
name: coverage-evidence-${{ matrix.os }}-${{ matrix.python-version }}
include-hidden-files: true
if-no-files-found: error
path: build/coverage/
- name: Clean wheel and sdist verification
if: env.DIST_RUN == 'true'
run: python tools/verify_distribution.py
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
if: always() && env.DIST_RUN == 'true'
with:
name: distribution-evidence-${{ matrix.os }}-${{ matrix.python-version }}
path: build/distribution-verification.json

phreeqc-live:
needs: scope
runs-on: windows-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: needs.scope.outputs.code == 'true'
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
if: needs.scope.outputs.code == 'true'
with:
python-version: "3.13"
- name: Install package
if: needs.scope.outputs.code == 'true'
run: python -m pip install .
- name: Provision hash-pinned external PHREEQC
if: needs.scope.outputs.code == 'true'
shell: pwsh
run: ./tools/provision_phreeqc.ps1
- name: Required live reference replay and runtime equivalence
if: needs.scope.outputs.code == 'true'
shell: pwsh
run: |
python -m unittest tests.test_product_phreeqc tests.test_acid_reference tests.test_preserved_chemistry_evidence tests.test_live_reference_policy tests.test_reference_integrity -v 2>&1 | Tee-Object -FilePath phreeqc-validation.log
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
if: always() && needs.scope.outputs.code == 'true'
with:
name: phreeqc-live-evidence
path: phreeqc-validation.log
Expand All @@ -128,7 +186,8 @@ jobs:

coverage-gate:
name: coverage-gate
needs: [style, test, phreeqc-live, docs]
# Light tier: only the prerequisites must pass. Full tier: the exact three-OS coverage gate too.
needs: [scope, style, test, phreeqc-live, docs]
if: always() && !cancelled()
runs-on: ubuntu-latest
steps:
Expand All @@ -138,23 +197,30 @@ jobs:
run: |
python -c 'import json, os; results = json.loads(os.environ["REQUIRED_RESULTS"]); assert results and all(v["result"] == "success" for v in results.values()), results'
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: needs.scope.outputs.full == 'true'
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
if: needs.scope.outputs.full == 'true'
with:
python-version: "3.13"
- name: Install exact coverage reporter
if: needs.scope.outputs.full == 'true'
run: python -m pip install coverage==7.17.0
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
if: needs.scope.outputs.full == 'true'
with:
pattern: coverage-evidence-*
path: build/native-coverage
- name: Enforce revision, native shards and exact statement/branch counts
id: aggregate
if: needs.scope.outputs.full == 'true'
run: python -m tools.ci_coverage aggregate --candidate "$CANDIDATE_SHA" --inputs build/native-coverage --output build/coverage-gate
- name: Verify validated upload input
if: needs.scope.outputs.full == 'true'
run: python -m tools.ci_coverage verify-upload --candidate "$CANDIDATE_SHA" --output build/coverage-gate
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
if: needs.scope.outputs.full == 'true'
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: build/coverage-gate/coverage.xml
Expand All @@ -169,7 +235,7 @@ jobs:
if: always() && steps.aggregate.outcome == 'success'
run: python -m tools.ci_coverage verify-upload --candidate "$CANDIDATE_SHA" --output build/coverage-gate
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
if: always() && needs.scope.outputs.full == 'true'
with:
name: coverage-gate-${{ env.CANDIDATE_SHA }}
include-hidden-files: true
Expand Down
20 changes: 20 additions & 0 deletions docs/adr/0002-light-pull-request-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Pull requests run a light gate; the full gate runs before a release

Date: 2026-11-05

A pull request ran the whole suite on six interpreter and operating-system combinations, three of them under branch coverage with an exact three-OS gate. A one-line fix waited 25 to 60 minutes, and a documentation change waited as long as a chemistry change. FlahaX is a pure-Python package with no runtime dependencies, so an operating-system-only break is unlikely and is cheap to find before a release.

Pull requests and pushes to `main` now run the light tier: lint, the documentation build, the PHREEQC replay (skipped when only documentation changed), Linux on Python 3.11, 3.12 and 3.13, and one clean wheel and sdist check. A pull request that changes only `docs/` or top-level `.md` files runs lint, the documentation build and the documentation tests. The full tier is a manual run of the Test workflow before a release: it adds Python 3.14, Windows and macOS, the exact three-OS coverage gate and the Codecov upload. A release calls the full tier on the tagged commit, and nothing is built or published unless it passes.

## Considered options

- **Keep the full gate on every pull request:** rejected. It cost an hour per change and failed Dependabot pull requests that cannot read the Codecov secret.
- **Coverage on Linux only for pull requests:** rejected. The gate is exact, and `terminal.py` has Windows-only and POSIX-only branches, so one operating system can never reach it.
- **Shard the full gate across parallel jobs:** deferred. It keeps every guarantee but changes the coverage tool and its tests; revisit if the full run becomes the bottleneck.

## Consequences

- A coverage gap or an operating-system-only failure is found when the full tier runs, not on the pull request. The fix is a follow-up commit.
- The required check names `test (3.11)`, `test (3.12)`, `test (3.13)`, `phreeqc-live` and `coverage-gate` are unchanged, so branch protection needs no edit. In the light tier `coverage-gate` only requires its prerequisites to pass.
- A release runs the full tier through `publish.yml`, so exact coverage on all three operating systems is enforced where it matters. A failing gate stops the publication; fix it and publish again.
- Run the Test workflow by hand before tagging to find those failures early.
10 changes: 6 additions & 4 deletions tests/test_ci_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,9 @@ def test_candidate_dependency_and_upload_contract(self):
(root / '.github/workflows/test.yml').read_text(encoding='utf-8'),
Loader=yaml.BaseLoader,
)
self.assertEqual(set(workflow['on']), {'push', 'pull_request', 'workflow_dispatch'})
self.assertEqual(
set(workflow['on']), {'push', 'pull_request', 'workflow_dispatch', 'workflow_call'}
)
candidate = '${{ github.event.pull_request.head.sha || github.sha }}'
self.assertEqual(workflow['env']['CANDIDATE_SHA'], candidate)
for job in workflow['jobs'].values():
Expand All @@ -396,7 +398,7 @@ def test_candidate_dependency_and_upload_contract(self):
)
self.assertEqual(checkout['with']['ref'], candidate)
gate = workflow['jobs']['coverage-gate']
self.assertEqual(set(gate['needs']), {'style', 'test', 'phreeqc-live', 'docs'})
self.assertEqual(set(gate['needs']), {'scope', 'style', 'test', 'phreeqc-live', 'docs'})
self.assertEqual(gate['if'], 'always() && !cancelled()')
self.assertIn('all(v["result"] == "success"', gate['steps'][0]['run'])
steps = gate['steps']
Expand Down Expand Up @@ -427,13 +429,13 @@ def test_candidate_dependency_and_upload_contract(self):
self.assertNotIn('merge-multiple', download['with'])
< 10BC8 /td> test = workflow['jobs']['test']
self.assertIn("format('test ({0})'", test['name'])
self.assertEqual(len(test['strategy']['matrix']['include']), 2)
self.assertEqual(test['strategy']['matrix'], '${{ fromJSON(needs.scope.outputs.matrix) }}')
measure = next(
s for s in test['steps'] if s.get('name') == 'Candidate-bound native coverage'
)
self.assertIn('test_status=${PIPESTATUS[0]}', measure['run'])
self.assertIn('exit "$test_status"', measure['run'])
self.assertEqual(measure['if'], "matrix.python-version == '3.13'")
self.assertEqual(measure['if'], "env.COVERAGE_RUN == 'true'")
self.assertFalse(any(s.get('uses', '').startswith('codecov/') for s in test['steps']))
config = yaml.load(
(root / 'codecov.yml').read_text(encoding='utf-8'), Loader=yaml.BaseLoader
Expand Down
97 changes: 97 additions & 0 deletions tests/test_ci_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# SPDX-FileCopyrightText: 2026 Flaha. Created by Rafat A. Al Khashan.
# SPDX-License-Identifier: Apache-2.0
# Disclaimer: planning software provided without warranty (Apache-2.0, section 7);
# its results are calculations, not dosing instructions.
"""A pull request counts as documentation only when git says so; an error never does."""

import contextlib
import io
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch

from tools import ci_scope


def git(root, *args):
subprocess.run(['git', *args], cwd=root, check=True, capture_output=True)


class ScopeTests(unittest.TestCase):
def repository(self, folder, *changes):
"""A repository whose last commit changes the given paths; returns (root, base, head)."""
root = Path(folder)
git(root, 'init', '-q')
git(root, 'config', 'user.email', 'ci@example.invalid')
git(root, 'config', 'user.name', 'ci')
git(root, 'commit', '-q', '--allow-empty', '-m', 'base')
base = self.head(root)
for path in changes:
(root / path).parent.mkdir(parents=True, exist_ok=True)
(root / path).write_text('x', encoding='utf-8')
git(root, 'add', '-A')
git(root, 'commit', '-q', '--allow-empty', '-m', 'change')
return root, base, self.head(root)

def head(self, root):
return subprocess.run(
['git', 'rev-parse', 'HEAD'], cwd=root, capture_output=True, text=True, check=True
).stdout.strip()

def scope(self, root, base, head):
out = io.StringIO()
with contextlib.redirect_stdout(out):
ci_scope.main([base, head], root)
return out.getvalue().strip()

def test_a_readme_only_change_is_documentation(self):
with tempfile.TemporaryDirectory() as folder:
self.assertEqual(self.scope(*self.repository(folder, 'README.md')), 'code=false')

def test_documentation_folders_and_the_changelog_are_documentation(self):
with tempfile.TemporaryDirectory() as folder:
repo = self.repository(
folder, 'docs/site/index.md', 'docs/site/conf.py', 'CHANGELOG.md'
)
self.assertEqual(self.scope(*repo), 'code=false')

def test_a_readme_with_python_is_code(self):
with tempfile.TemporaryDirectory() as folder:
repo = self.repository(folder, 'README.md', 'src/flahax/engine.py')
self.assertEqual(self.scope(*repo), 'code=true')

def test_a_markdown_file_inside_the_package_is_code(self):
with tempfile.TemporaryDirectory() as folder:
repo = self.repository(folder, 'src/flahax/data/USER_GUIDE.md')
self.assertEqual(self.scope(*repo), 'code=true')

def test_an_empty_change_is_not_called_documentation(self):
with tempfile.TemporaryDirectory() as folder:
self.assertEqual(self.scope(*self.repository(folder)), 'code=true')

def test_a_comparison_that_fails_fails_instead_of_reading_as_documentation(self):
with tempfile.TemporaryDirectory() as folder:
root, _, head = self.repository(folder, 'README.md')
with self.assertRaises(subprocess.CalledProcessError):
self.scope(root, 'not-a-revision', head)

def test_the_command_line_reads_its_revisions_and_prints_the_decision(self):
with tempfile.TemporaryDirectory() as folder:
root, base, head = self.repository(folder, 'README.md')
out = io.StringIO()
with (
patch.object(sys, 'argv', ['ci_scope.py', base, head]),
contextlib.chdir(root),
contextlib.redirect_stdout(out),
self.assertRaises(SystemExit) as stop,
):
runpy.run_path(str(Path(ci_scope.__file__)), run_name='__main__')
self.assertEqual((stop.exception.code, out.getvalue().strip()), (0, 'code=false'))


if __name__ == '__main__':
unittest.main()
Loading
Loading
0