Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

ci: gate PR pytest by label and skip unused test-image builds (#7101)

LearningCircuit958aa8ab19b4
diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
index 053926868a..fdc099effe 100644
--- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
+++ b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md
@@ -4,7 +4,9 @@ Fixes #
## CI test coverage
-By default, this PR runs the unit/lint checks. Heavy E2E suites are label-gated — add the label that matches what you touched so the relevant workflow runs:
+Lint, security and focused checks run automatically. The shared test image is built only when full pytest or a selected focused check needs it. When this PR is nearly ready, a maintainer must add `test:pytest` to run the full pytest suite. Passing full pytest remains required before merge; until requested, that check reports a short failure explaining the missing label. Later pushes rerun the suite while the label remains.
+
+Additional heavy suites use these labels:
- `test:puppeteer` — Puppeteer E2E suite (~30–60 min; uses paid LLM/search API quotas). `test:e2e` is a legacy alias.
- `test:notes` — focused Notes Playwright E2E suite (re-runs on later pushes while the label remains).
diff --git a/.github/labels.yml b/.github/labels.yml
index 60c54470bb..4df50eb5e4 100644
--- a/.github/labels.yml
+++ b/.github/labels.yml
@@ -189,6 +189,9 @@
# Workflow/control labels. These are deliberately excluded from the AI
# reviewer's output allowlist.
+- name: 'test:pytest'
+ color: '0e8a16'
+ description: 'Maintainer request for full pytest before merge; reruns on later pushes while the label remains.'
- name: ai_code_review
color: '6f42c1'
description: 'Maintainer-only: apply or re-add to run AI code review. Release notes: 🔄 Automation (18/20).'
diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index ee9bf919a3..a25b64b926 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -2,6 +2,51 @@
This directory contains GitHub Actions workflows for automated development tasks.
+## Full pytest scheduling
+
+`docker-tests.yml` keeps **All Pytest Tests + Coverage** required before merge.
+A maintainer adds `test:pytest` when a PR is nearly ready. Adding that label
+starts full pytest against the PR's test merge commit; later pushes and reopen
+events rerun it while the label remains. Remove the label to stop full pytest
+on future pushes. Removing and re-adding it requests another run.
+
+Without the label, the required job fails a short guard before checkout or test
+setup. This is an intentional merge block, not a failing test. A skipped job
+would satisfy GitHub's required-check rule, so the job must not be skipped for
+an unrequested PR. Failed or cancelled image builds also cannot make it pass.
+Unrelated label events skip work under separate, non-required check names and
+cannot cancel a real PR run or overwrite its required checks.
+
+The shared test image is built only when full pytest is requested or an
+automatic focused check needs it (LLM, infrastructure, or accessibility paths).
+An unlabeled PR with none of those checks skips the image build while the
+required pytest request guard still blocks merging. Production-image smoke
+tests retain their separate path-based build and do not need the test image.
+
+Main retains automatic full pytest on pushes as a second check of the code that
+landed, plus a daily run at **03:23 UTC**. Both can publish validated coverage for
+the current main commit. Manual dispatch and reusable callers (including
+mandatory release validation and the full UI label) also run the full suite.
+Manual runs are useful for diagnosis; request PR validation with the label so
+the run uses a `pull_request` event and satisfies required checks.
+
+New direct PR runs cancel obsolete predecessors. The required pytest job uses
+`!cancelled()` at job level so cancellation can release it while it is queued,
+without waiting for a runner to execute a cancellation step. This explicit
+status function still runs the guard after a failed or skipped image build;
+ordinary dependency failure cannot skip the required check. A cancelled check
+does not satisfy the merge requirement.
+
+Main pushes share one concurrency group: the active run finishes, and only the
+newest pending run is retained. Intermediate queued main commits may therefore
+be superseded; the required pre-merge validation still applies to every PR.
+Reusable release runs and the daily run have isolated concurrency groups.
+
+The label is declared in `.github/labels.yml` and maintained by label sync.
+The existing required check name is preserved; no branch-rule change is
+needed. Existing PRs receive the policy when their workflow includes this
+change; merging this change does not cancel or rewrite already queued runs.
+
## Update NPM Dependencies Workflow
**File**: `update-npm-dependencies.yml`
diff --git a/.github/workflows/ci-policy-tests.yml b/.github/workflows/ci-policy-tests.yml
index 0e1e5e5601..7e7d1efe9e 100644
--- a/.github/workflows/ci-policy-tests.yml
+++ b/.github/workflows/ci-policy-tests.yml
@@ -8,6 +8,7 @@ on:
- ".github/scripts/retire_json_to_sarif.py"
- ".github/release-scan-policy.json"
- "tests/ci/standalone/test_release_scan_*.py"
+ - "tests/ci/standalone/test_pytest_scheduling.py"
workflow_dispatch:
permissions:
@@ -32,3 +33,5 @@ jobs:
python-version: '3.12'
- name: Test CI policies without loading the application
run: python -m unittest discover -s tests/ci/standalone -p 'test_release_scan*.py' -v
+ - name: Test pytest scheduling and required-check behavior
+ run: python -m unittest discover -s tests/ci/standalone -p 'test_pytest_scheduling.py' -v
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml
index 9c63d75b9e..384c8e9fd4 100644
--- a/.github/workflows/docker-tests.yml
+++ b/.github/workflows/docker-tests.yml
@@ -2,10 +2,13 @@ name: Docker Tests (Consolidated)
on:
pull_request:
- types: [opened, synchronize, reopened]
+ types: [opened, synchronize, reopened, labeled]
branches: [ main ]
push:
branches: [ main ]
+ schedule:
+ # Full pytest on main once daily, away from the top-of-hour queue.
+ - cron: '23 3 * * *'
workflow_call: # Called by ci-gate.yml for release pipeline
inputs:
strict-mode:
@@ -27,13 +30,23 @@ on:
required: false
workflow_dispatch:
-# Cancel an obsolete direct PR run before it can consume build/test capacity.
+# Cancel obsolete direct PR runs before they consume build/test capacity.
+# Main pushes share one group: finish the active run and retain only the newest
+# pending run (GitHub's default), so frequent merges do not starve validation.
+# Unrelated label events get isolated groups and distinct skipped check names:
+# they must neither cancel a real run nor replace a required check with a skip.
# Reusable invocations retain the caller's event context, so the explicit
# workflow_call marker keeps them on unique run-id groups instead of allowing
# them to cancel or queue behind the direct PR workflow.
concurrency:
- group: ${{ github.event_name == 'pull_request' && !inputs.reusable-invocation && format('docker-tests-direct-pr-{0}', github.event.pull_request.number) || format('docker-tests-isolated-run-{0}', github.run_id) }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' && !inputs.reusable-invocation }}
+ group: >-
+ ${{ !inputs.reusable-invocation && github.event_name == 'pull_request' &&
+ (github.event.action != 'labeled' || github.event.label.name == 'test:pytest') &&
+ format('docker-tests-direct-pr-{0}', github.event.pull_request.number) ||
+ !inputs.reusable-invocation && github.event_name == 'push' &&
+ github.ref == 'refs/heads/main' && 'docker-tests-direct-main' ||
+ format('docker-tests-isolated-run-{0}', github.run_id) }}
+ cancel-in-progress: ${{ !inputs.reusable-invocation && github.event_name == 'pull_request' && (github.event.action != 'labeled' || github.event.label.name == 'test:pytest') }}
# Top-level permissions set to minimum (OSSF Scorecard Token-Permissions)
permissions: {}
@@ -45,6 +58,8 @@ env:
jobs:
# Detect which paths changed to conditionally run certain jobs
detect-changes:
+ name: ${{ github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'test:pytest' && !inputs.reusable-invocation && 'Ignored label (change detection)' || 'detect-changes' }}
+ if: github.event_name != 'pull_request' || github.event.action != 'labeled' || github.event.label.name == 'test:pytest' || inputs.reusable-invocation
runs-on: ubuntu-latest
outputs:
llm: ${{ steps.filter.outputs.llm }}
@@ -124,14 +139,19 @@ jobs:
- 'lighthouserc.json'
- '.github/workflows/docker-tests.yml'
- # Build Docker image once and share via artifact
+ # Build once when a selected test needs the image. Unrequested PRs with no
+ # Docker-based focused checks must not spend capacity building an unused image.
build-test-image:
runs-on: ubuntu-latest
- name: Build Test Image
+ needs: detect-changes
+ name: ${{ github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'test:pytest' && !inputs.reusable-invocation && 'Ignored label (image build)' || 'Build Test Image' }}
if: |
- github.event_name == 'pull_request' ||
- github.ref == 'refs/heads/main' ||
- inputs.strict-mode == true
+ (github.event_name != 'pull_request' || github.event.action != 'labeled' || github.event.label.name == 'test:pytest' || inputs.reusable-invocation) &&
+ (github.event_name != 'pull_request' || inputs.reusable-invocation ||
+ contains(github.event.pull_request.labels.*.name, 'test:pytest') ||
+ needs.detect-changes.outputs.llm == 'true' ||
+ needs.detect-changes.outputs.infrastructure == 'true' ||
+ needs.detect-changes.outputs.accessibility == 'true')
steps:
- name: Harden the runner (Audit all outbound calls)
@@ -164,10 +184,17 @@ jobs:
path: /tmp/ldr-test.tar
retention-days: 1
- # Run all pytest tests with coverage
+ # Keep the existing required check. An unrequested PR fails a cheap guard;
+ # skipping this job for missing labels would satisfy branch protection.
+ # !cancelled() bypasses the implicit success() dependency check, so a failed
+ # or skipped image build still reaches the guard. Unlike always(), it lets
+ # cancellation release an obsolete queued job without first needing a runner.
pytest-tests:
runs-on: ubuntu-latest
- name: All Pytest Tests + Coverage
+ name: ${{ github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'test:pytest' && !inputs.reusable-invocation && 'Ignored label (pytest)' || 'All Pytest Tests + Coverage' }}
+ if: >-
+ !cancelled() &&
+ (github.event_name != 'pull_request' || github.event.action != 'labeled' || github.event.label.name == 'test:pytest' || inputs.reusable-invocation)
# Cap exists so a hung run doesn't inherit GitHub's 360-minute default
# (observed 2026-06-10 on PR #4491: a flaked run sat in the main pytest
# step for 2+ hours before being cancelled manually). The original
@@ -190,6 +217,23 @@ jobs:
pull-requests: write # Needed for PR comments
steps:
+ - name: Require a pytest request and successful image build
+ id: pytest_request
+ env:
+ PYTEST_REQUESTED: ${{ github.event_name != 'pull_request' || inputs.reusable-invocation || contains(github.event.pull_request.labels.*.name, 'test:pytest') }}
+ TEST_IMAGE_RESULT: ${{ needs.build-test-image.result }}
+ run: |
+ set -euo pipefail
+ if [ "$PYTEST_REQUESTED" != 'true' ]; then
+ echo 'Full pytest has not been requested. A maintainer must add test:pytest when this PR is ready for full validation.' >> "$GITHUB_STEP_SUMMARY"
+ echo '::error::Full pytest is required before merging. Add the test:pytest label to run it.'
+ exit 1
+ fi
+ if [ "$TEST_IMAGE_RESULT" != 'success' ]; then
+ echo '::error::Full pytest cannot pass without a successful test image build.'
+ exit 1
+ fi
+
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1
with:
@@ -329,7 +373,7 @@ jobs:
# collected") and this step fails hard (cf. #4411). If the last
# marked module goes away, delete this step in the same change.
- name: Run fd_canary FD-leak tests (serial, no coverage)
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
docker run --rm -t \
-v "$PWD":/app \
@@ -408,7 +452,7 @@ jobs:
# parity; the news scheduler is only read in the FastAPI lifespan,
# which a pytest lane never enters, so this is a no-op here today.
- name: Run serial + nonroot (process-global state, permission-bit) tests
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
docker run --rm -t \
--user ldruser \
@@ -437,17 +481,17 @@ jobs:
--ignore=tests/fuzz"
- name: Run JavaScript infrastructure tests
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
cd tests/infrastructure_tests && npm test
- name: Run Vitest JS unit tests
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
npm ci && npm test
- name: Validate coverage data
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
docker run --rm \
-v "$PWD":/app \
@@ -457,7 +501,7 @@ jobs:
coverage/coverage.xml coverage/coverage-summary.json
- name: Generate coverage summary
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
{
echo "## Coverage Report"
@@ -475,7 +519,7 @@ jobs:
echo ""
echo "📊 **[View Full Coverage Report](${{ env.PAGES_URL }})** - Interactive HTML report with line-by-line details"
echo ""
- echo "_Note: Report updates after merge to main/dev branch._"
+ echo "_Note: Published report updates after successful main validation._"
fi
else
echo "⚠️ Validated coverage summary not generated"
@@ -483,7 +527,7 @@ jobs:
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload coverage reports
- if: always() && hashFiles('coverage/**') != ''
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' && hashFiles('coverage/**') != '' }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: coverage-report
@@ -491,7 +535,7 @@ jobs:
# Fix permissions on coverage directory (Docker creates files as root)
- name: Fix coverage directory permissions
- if: always()
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' }}
run: |
if [ -d "coverage" ]; then
sudo chown -R "$(id -u):$(id -g)" coverage/
@@ -511,7 +555,7 @@ jobs:
# Add coverage summary as PR comment for easy visibility
- name: Comment coverage on PR
- if: always() && github.event_name == 'pull_request'
+ if: ${{ !cancelled() && steps.pytest_request.outcome == 'success' && github.event_name == 'pull_request' }}
continue-on-error: true # Don't fail the job if GitHub API is throttled
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
@@ -692,8 +736,8 @@ jobs:
});
}
- # Publish only a complete, validated report from the current direct main
- # push. Release-gate's nested strict-mode invocation produces its own
+ # Publish only a complete, validated report from a direct main push or daily run.
+ # Release-gate's nested strict-mode invocation produces its own
# coverage artifact but must not race this job for gh-pages or the badge.
publish-coverage:
runs-on: ubuntu-latest
@@ -703,8 +747,9 @@ jobs:
${{
!cancelled() &&
needs.pytest-tests.result == 'success' &&
- github.event_name == 'push' &&
+ (github.event_name == 'push' || github.event_name == 'schedule') &&
github.ref == 'refs/heads/main' &&
+ !inputs.reusable-invocation &&
inputs.strict-mode != true
}}
concurrency:
diff --git a/changelog.d/7101.misc.md b/changelog.d/7101.misc.md
new file mode 100644
index 0000000000..b20e17e1d7
--- /dev/null
+++ b/changelog.d/7101.misc.md
@@ -0,0 +1,5 @@
+Full pytest for pull requests is requested with the `test:pytest` label and
+remains required before merge; unused test-image builds are skipped. Main-push,
+daily, and release validation still run automatically, with the main queue
+retaining one active run and only the newest pending run. Superseded PR pytest
+jobs can be cancelled while queued without waiting for a runner.
diff --git a/tests/ci/standalone/test_pytest_scheduling.py b/tests/ci/standalone/test_pytest_scheduling.py
new file mode 100644
index 0000000000..d8b2cf68c7
--- /dev/null
+++ b/tests/ci/standalone/test_pytest_scheduling.py
@@ -0,0 +1,492 @@
+"""Exercise the actual workflow conditions and guard without app dependencies.
+
+Actionlint validates YAML and Actions syntax separately. The small expression
+interpreter below accepts only the operators/functions used by these conditions
+and rejects unknown syntax or context. Conditions also account for GitHub's
+implicit success() check. These are policy regressions, not a simulation of
+GitHub's scheduler or proof of a hosted run's final check conclusion.
+"""
+
+import ast
+import os
+import re
+import subprocess
+import tempfile
+import textwrap
+import unittest
+from itertools import product
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[3]
+WORKFLOW = (ROOT / ".github/workflows/docker-tests.yml").read_text()
+TOKEN = re.compile(
+ r"\s*('(?:[^']|'')*'|&&|\|\||==|!=|!|[(),]|"
+ r"[A-Za-z_][A-Za-z0-9_.*-]*|[0-9]+)"
+)
+REQUIRED = {
+ "detect-changes": "detect-changes",
+ "build-test-image": "Build Test Image",
+ "pytest-tests": "All Pytest Tests + Coverage",
+}
+
+
+def job(name):
+ match = re.search(
+ rf"^ {re.escape(name)}:\n(.*?)(?=^ [\w-]+:|\Z)",
+ WORKFLOW.split("\njobs:\n", 1)[1],
+ re.MULTILINE | re.DOTALL,
+ )
+ if match is None:
+ raise AssertionError(f"Missing job: {name}")
+ return match[1]
+
+
+def field(text, key, indent):
+ """Read a scalar at a known YAML indentation; not a general YAML parser."""
+ lines = text.splitlines()
+ prefix = " " * indent + key + ":"
+ for index, line in enumerate(lines):
+ if not line.startswith(prefix):
+ continue
+ value = line[len(prefix) :].strip()
+ if value not in {"|", ">", ">-", "|-"}:
+ return value
+ body = []
+ for following in lines[index + 1 :]:
+ if following.strip() and not following.startswith(
+ " " * (indent + 1)
+ ):
+ break
+ body.append(following)
+ return textwrap.dedent("\n".join(body)).strip()
+ raise AssertionError(f"Missing field: {key}")
+
+
+def steps():
+ return re.split(r"^ - ", job("pytest-tests"), flags=re.MULTILINE)[1:]
+
+
+def step_with_id(step_id):
+ return next(step for step in steps() if f" id: {step_id}\n" in step)
+
+
+def evaluate(expression, context, *, cancelled=False, success=True):
+ expression = expression.strip().removeprefix("${{").removesuffix("}}")
+ translated = []
+ functions = {
+ "always",
+ "cancelled",
+ "success",
+ "contains",
+ "format",
+ "hashFiles",
+ }
+ operators = {"&&": "and", "||": "or", "!": "not"}
+ position = 0
+ while position < len(expression.rstrip()):
+ match = TOKEN.match(expression, position)
+ if match is None:
+ raise AssertionError(
+ f"Unsupported expression: {expression[position:]}"
+ )
+ token = match[1]
+ position = match.end()
+ if token.startswith("'"):
+ translated.append(repr(token[1:-1].replace("''", "'")))
+ elif token in {"true", "false", "null"}:
+ translated.append(
+ {"true": "True", "false": "False", "null": "None"}[token]
+ )
+ elif re.match(r"[A-Za-z_]", token) and token not in functions:
+ translated.append(f"lookup({token!r})")
+ else:
+ translated.append(operators.get(token, token))
+
+ def lookup(path):
+ # Every referenced field must be modelled; missing fields never silently
+ # become false and conceal a new bypass in a workflow expression.
+ if path not in context:
+ raise AssertionError(f"Unmodelled context: {path}")
+ return context[path]
+
+ calls = {
+ "lookup": lookup,
+ "always": lambda: True,
+ "cancelled": lambda: cancelled,
+ "success": lambda: success,
+ "contains": lambda values, value: (
+ value.lower() in [item.lower() for item in (values or [])]
+ ),
+ "format": lambda template, value: template.format(value),
+ "hashFiles": lambda pattern: "test-coverage-hash",
+ }
+
+ def visit(node):
+ if isinstance(node, ast.Constant):
+ return node.value
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ return calls[node.func.id](*(visit(arg) for arg in node.args))
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
+ return not visit(node.operand)
+ if isinstance(node, ast.BoolOp):
+ result = visit(node.values[0])
+ for value in node.values[1:]:
+ if isinstance(node.op, ast.And) and not result:
+ break
+ if isinstance(node.op, ast.Or) and result:
+ break
+ result = visit(value)
+ return result
+ if isinstance(node, ast.Compare) and len(node.ops) == 1:
+ left, right = visit(node.left), visit(node.comparators[0])
+ if isinstance(left, str) and isinstance(right, str):
+ left, right = left.lower(), right.lower()
+ if isinstance(node.ops[0], ast.Eq):
+ return left == right
+ if isinstance(node.ops[0], ast.NotEq):
+ return left != right
+ raise AssertionError(f"Unsupported expression node: {ast.dump(node)}")
+
+ return visit(ast.parse(" ".join(translated).strip(), mode="eval").body)
+
+
+def evaluate_condition(expression, context, *, cancelled=False, success=True):
+ # GitHub adds success() unless the condition uses a status function. Without
+ # this rule a removed !cancelled() could silently skip the required guard
+ # after a failed/skipped build while these tests still pass.
+ if not re.search(
+ r"\b(?:always|cancelled|failure|success)\s*\(", expression
+ ):
+ if not success:
+ return False
+ return evaluate(expression, context, cancelled=cancelled, success=success)
+
+
+def context(
+ event="pull_request",
+ action="synchronize",
+ label="",
+ *,
+ requested=False,
+ reusable=False,
+):
+ return {
+ "github.event_name": event,
+ "github.event.action": action,
+ "github.event.label.name": label,
+ "github.event.pull_request.labels.*.name": ["test:pytest"]
+ if requested
+ else [],
+ "github.event.pull_request.number": 42,
+ "github.ref": "refs/pull/42/merge"
+ if event == "pull_request"
+ else "refs/heads/main",
+ "github.run_id": 123,
+ "inputs.reusable-invocation": reusable,
+ "inputs.strict-mode": reusable,
+ "needs.pytest-tests.result": "success",
+ "needs.detect-changes.outputs.llm": "false",
+ "needs.detect-changes.outputs.infrastructure": "false",
+ "needs.detect-changes.outputs.accessibility": "false",
+ "needs.detect-changes.outputs.docker": "false",
+ "steps.pytest_request.outcome": "success",
+ }
+
+
+class PytestSchedulingTests(unittest.TestCase):
+ def test_pr_lifecycle_keeps_pytest_required_and_skips_unused_images(self):
+ for action in ("opened", "synchronize", "reopened"):
+ for requested in (False, True):
+ ctx = context(action=action, requested=requested)
+ with self.subTest(action=action, requested=requested):
+ for name, required in REQUIRED.items():
+ self.assertEqual(
+ bool(evaluate(field(job(name), "if", 4), ctx)),
+ name != "build-test-image" or requested,
+ )
+ self.assertEqual(
+ evaluate(field(job(name), "name", 4), ctx), required
+ )
+ self.assertEqual(
+ evaluate(
+ field(job("pytest-tests"), "PYTEST_REQUESTED", 10),
+ ctx,
+ ),
+ requested,
+ )
+
+ def test_only_pytest_label_runs_or_replaces_required_checks(self):
+ for label in ("test:pytest", "bugfix", "test:notes"):
+ for requested in (False, True):
+ ctx = context(
+ action="labeled", label=label, requested=requested
+ )
+ relevant = label == "test:pytest"
+ with self.subTest(label=label, requested=requested):
+ for name, required in REQUIRED.items():
+ self.assertEqual(
+ bool(evaluate(field(job(name), "if", 4), ctx)),
+ relevant
+ and (name != "build-test-image" or requested),
+ )
+ self.assertEqual(
+ evaluate(field(job(name), "name", 4), ctx)
+ == required,
+ relevant,
+ )
+
+ def test_main_push_runs_full_pytest_without_a_pr_label(self):
+ ctx = context("push")
+ self.assertTrue(
+ evaluate(field(job("pytest-tests"), "PYTEST_REQUESTED", 10), ctx)
+ )
+ for name, required in REQUIRED.items():
+ self.assertTrue(evaluate(field(job(name), "if", 4), ctx))
+ self.assertEqual(
+ evaluate(field(job(name), "name", 4), ctx), required
+ )
+
+ def test_image_is_built_exactly_when_pytest_or_a_focused_consumer_needs_it(
+ self,
+ ):
+ job_names = re.findall(
+ r"^ ([\w-]+):$", WORKFLOW.split("\njobs:\n", 1)[1], re.MULTILINE
+ )
+ focused_consumers = [
+ name
+ for name in job_names
+ if name != "pytest-tests"
+ and re.search(
+ r"^ needs:.*\bbuild-test-image\b", job(name), re.MULTILINE
+ )
+ ]
+ self.assertTrue(focused_consumers)
+ self.assertEqual(
+ field(job("build-test-image"), "needs", 4), "detect-changes"
+ )
+ for requested, llm, infrastructure, accessibility, docker in product(
+ (False, True), repeat=5
+ ):
+ ctx = context(requested=requested)
+ for path, changed in (
+ ("llm", llm),
+ ("infrastructure", infrastructure),
+ ("accessibility", accessibility),
+ ("docker", docker),
+ ):
+ ctx[f"needs.detect-changes.outputs.{path}"] = str(
+ changed
+ ).lower()
+ selected = any(
+ evaluate(field(job(name), "if", 4), ctx)
+ for name in focused_consumers
+ )
+ with self.subTest(
+ requested=requested,
+ llm=llm,
+ infrastructure=infrastructure,
+ accessibility=accessibility,
+ docker=docker,
+ ):
+ self.assertEqual(
+ bool(
+ evaluate(field(job("build-test-image"), "if", 4), ctx)
+ ),
+ requested or selected,
+ )
+
+ def test_daily_manual_and_release_callers_run_full_pytest(self):
+ cases = [context("schedule"), context("workflow_dispatch")]
+ cases += [
+ context(
+ event,
+ action="labeled",
+ label="test:ui-full-shards",
+ reusable=True,
+ )
+ for event in (
+ "push",
+ "pull_request",
+ "workflow_dispatch",
+ "schedule",
+ )
+ ]
+ for ctx in cases:
+ with self.subTest(context=ctx):
+ self.assertTrue(
+ evaluate(field(job("build-test-image"), "if", 4), ctx)
+ )
+ self.assertTrue(
+ evaluate(field(job("pytest-tests"), "if", 4), ctx)
+ )
+ self.assertTrue(
+ evaluate(
+ field(job("pytest-tests"), "PYTEST_REQUESTED", 10), ctx
+ )
+ )
+ self.assertEqual(
+ evaluate(field(job("pytest-tests"), "name", 4), ctx),
+ REQUIRED["pytest-tests"],
+ )
+ self.assertRegex(
+ WORKFLOW, r"schedule:\s*\n\s*#.*\n\s*- cron: '23 3 \* \* \*'"
+ )
+ release_caller = (ROOT / ".github/workflows/ci-gate.yml").read_text()
+ self.assertRegex(
+ release_caller,
+ r"uses: \$/\.github/workflows/docker-tests.yml\s+with:\s+strict-mode: true",
+ )
+
+ def test_concurrency_cancels_only_relevant_direct_pr_runs(self):
+ group = field(WORKFLOW, "group", 2)
+ cancel = field(WORKFLOW, "cancel-in-progress", 2)
+ direct = context()
+ label = context(action="labeled", label="test:pytest", requested=True)
+ self.assertEqual(evaluate(group, direct), evaluate(group, label))
+ for ctx in (direct, label):
+ self.assertTrue(evaluate(cancel, ctx))
+ for ctx in (
+ context(action="labeled", label="bugfix"),
+ context("schedule"),
+ context(reusable=True),
+ context("push", reusable=True),
+ ):
+ self.assertFalse(evaluate(cancel, ctx))
+ self.assertNotEqual(evaluate(group, ctx), evaluate(group, direct))
+ self.assertNotEqual(
+ evaluate(group, ctx), evaluate(group, context("push"))
+ )
+
+ def test_main_pushes_keep_active_run_and_share_single_pending_slot(self):
+ group = field(WORKFLOW, "group", 2)
+ cancel = field(WORKFLOW, "cancel-in-progress", 2)
+ first, latest = context("push"), context("push")
+ latest["github.run_id"] = 456
+ self.assertEqual(evaluate(group, first), evaluate(group, latest))
+ for ctx in (first, latest):
+ self.assertFalse(evaluate(cancel, ctx))
+ # GitHub retains just the newest pending run by default. Do not opt
+ # into queue: max, which would restore the main-push backlog.
+ concurrency = WORKFLOW.split("\nconcurrency:\n", 1)[1].split(
+ "\npermissions:", 1
+ )[0]
+ self.assertNotRegex(concurrency, r"\bqueue:\s*max\b")
+
+ def test_only_successful_direct_main_runs_publish_coverage(self):
+ condition = field(job("publish-coverage"), "if", 4)
+ for event in ("push", "pull_request", "schedule", "workflow_dispatch"):
+ for reusable in (False, True):
+ for result in ("success", "failure", "cancelled", "skipped"):
+ ctx = context(event, reusable=reusable)
+ ctx["needs.pytest-tests.result"] = result
+ expected = (
+ event in {"push", "schedule"}
+ and not reusable
+ and result == "success"
+ )
+ self.assertEqual(bool(evaluate(condition, ctx)), expected)
+ self.assertFalse(evaluate(condition, ctx, cancelled=True))
+
+ def test_guard_fails_closed_before_checkout_or_testing(self):
+ pytest = job("pytest-tests")
+ guard = step_with_id("pytest_request")
+ script = field(guard, "run", 8)
+ self.assertNotIn("continue-on-error", guard)
+ self.assertLess(
+ pytest.index("id: pytest_request"),
+ pytest.index("actions/checkout@"),
+ )
+ for requested in ("true", "false", "", "unexpected"):
+ for image_result in (
+ "success",
+ "failure",
+ "cancelled",
+ "skipped",
+ "",
+ ):
+ with (
+ self.subTest(
+ requested=requested, image_result=image_result
+ ),
+ tempfile.TemporaryDirectory() as temp,
+ ):
+ result = subprocess.run(
+ ["bash", "-c", script],
+ env={
+ **os.environ,
+ "PYTEST_REQUESTED": requested,
+ "TEST_IMAGE_RESULT": image_result,
+ "GITHUB_STEP_SUMMARY": str(Path(temp) / "summary"),
+ },
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ self.assertEqual(
+ result.returncode == 0,
+ requested == "true" and image_result == "success",
+ )
+ if requested == "false":
+ self.assertIn("test:pytest", result.stdout)
+
+ def test_unsuccessful_image_build_cannot_skip_required_guard(self):
+ condition = field(job("pytest-tests"), "if", 4)
+ for requested, image_result in product(
+ (False, True), ("failure", "skipped", "cancelled")
+ ):
+ ctx = context(requested=requested)
+ ctx["needs.build-test-image.result"] = image_result
+ with self.subTest(requested=requested, image_result=image_result):
+ self.assertTrue(
+ evaluate_condition(condition, ctx, success=False)
+ )
+
+ def test_cancellation_releases_pytest_without_waiting_for_a_runner(self):
+ condition = field(job("pytest-tests"), "if", 4)
+ cases = [
+ context(),
+ context(requested=True),
+ context(action="labeled", label="test:pytest", requested=True),
+ context("push"),
+ context("schedule"),
+ context("workflow_dispatch"),
+ context(reusable=True),
+ ]
+ for ctx, image_result in product(
+ cases, ("success", "failure", "cancelled", "skipped")
+ ):
+ ctx = {**ctx, "needs.build-test-image.result": image_result}
+ with self.subTest(context=ctx):
+ # Cancellation is evaluated at the job, before a runner can
+ # execute any step. A cancelled() shell guard cannot release
+ # an obsolete queued job from its workflow concurrency group.
+ self.assertFalse(
+ evaluate_condition(
+ condition,
+ ctx,
+ cancelled=True,
+ success=image_result == "success",
+ )
+ )
+
+ def test_failure_cleanup_stops_after_guard_failure_or_cancellation(self):
+ guarded_steps = 0
+ for step in steps():
+ if " if:" not in step:
+ continue # GitHub's default success() already stops these.
+ condition = field(step, "if", 8)
+ guarded_steps += 1
+ for result in ("failure", "cancelled", "skipped"):
+ ctx = context(requested=False)
+ ctx["steps.pytest_request.outcome"] = result
+ self.assertFalse(evaluate(condition, ctx))
+ self.assertTrue(evaluate(condition, context(requested=True)))
+ self.assertFalse(
+ evaluate(condition, context(requested=True), cancelled=True)
+ )
+ self.assertGreater(guarded_steps, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()