Merge branch 'main' into fix/sender-test-auto-destination

This commit is contained in:
Vito
2026-11-21 08:31:22 -08:00
committed by GitHub
28 changed files with 1790 additions and 1143 deletions
+2 -9
View File
@@ -1,15 +1,8 @@
{
"required_status_checks": {
"strict": false,
"strict": true,
"contexts": [
"py3.12 on ubuntu-latest",
"coverage gate (85%)",
"black and flake8",
"frontend modules",
"all tests",
"viewerjs",
"real ComfyUI compatibility",
"bandit (high severity)"
"gate"
]
},
"enforce_admins": true,
@@ -1,58 +1,58 @@
name: Viewer.js vendor and compatibility
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
name: CI
permissions:
contents: read
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
# The gate (#666): everything a change must pass runs once, here, on the pull request. Nothing runs
# again in a merge queue or on main; branch protection requires the one context "gate" on a branch
# that is up to date with main, so the commit that was tested is the commit that merges. What only
# other browsers, other Pythons, Windows or a real ComfyUI can catch runs in nightly.yml.
on:
pull_request:
branches: [main]
workflow_dispatch:
# A newer push to a pull request cancels the older run. A manual run is never cancelled.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Timeouts are the measured job time plus at least 50%, and never under 20 minutes for a browser job,
# because runner speed varies. Before sharding (main 2cecfcf, one worker): frontend coverage 32m10s,
# page workflows firefox 18m59s, webkit 19m26s. First sharded run (PR #274 run 39712909047, 3 workers,
# no npm cache, where npm ci stalled for 5m in six of eight jobs): coverage shards 11m19s/10m47s/10m49s
# (tests 5m20s/4m42s/4m46s), merge 5m52s (report and check 4s), firefox shards 7m53s/9m27s (tests
# 4m41s/3m29s), webkit shards 12m25s+ (cancelled at the old 12-minute limit after its 267 tests passed in
# 6m29s) and 4m53s (tests 3m08s). With the npm cache hit (run 39725176320 at cbc8a61, npm ci 0-2s):
# coverage shards 7m34s/6m04s/5m22s (tests 6m38s/4m53s/4m04s), merge 54s, firefox 7m57s/5m21s (tests
# 7m08s/4m34s), webkit 8m16s/5m03s (tests 7m26s/3m58s); a cache miss adds up to 5m to npm ci, which
# the 20-minute limits absorb.
# Hangs (#425): a job killed at its limit keeps no log and skips its upload steps, so each browser
# test step has its own timeout-minutes (18) below the job's 20. At the step limit, SIGTERM makes
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time. The 3 minutes leave room for the Python runner's watchdog
# (120 s, tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes
# only with new measurements written here (TESTING.md "Time limits and hangs"). A job with no three
# green runs yet has an "estimate" line; replace it with its measurement after three green runs.
# tests/vendor/ci-workflow.test.mjs recomputes every limit from these lines.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python: 7m20s / 7m36s / 7m58s -> 15 min
# lint: 0m27s / 0m52s / 0m49s -> 5 min
# js-test: 0m27s / 0m35s / 0m36s -> 5 min
# changes: 0m10s / 0m06s / 0m07s -> 5 min
# Measured 2026-11-21 on runs 44861123782 (a1f7447), 44547399248 (b3bb55f), 44519472003 (fa31644):
# security: 0m22s / 0m20s / 0m24s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# frontend-coverage-merge: 0m53s / 0m57s / 0m51s -> 5 min
# gate: 0m02s / 0m06s / 0m03s -> 5 min
# estimate package: one stdlib test module without an install, under 1 minute -> 5 min
# estimate tooling: the pip and npm installs of a browser shard (about 1 minute) and 2 minutes of tests -> 8 min
# estimate frontend-coverage: the same four shards ran Chromium and touch together in 7m55s-16m48s;
# Chromium alone is about half of that, 9 minutes at most -> 17 min
#
# Browser jobs (#425): a job killed at its limit keeps no log and skips its upload steps, so the page
# test step has its own timeout-minutes, 2 below the job's. At the step limit, SIGTERM makes
# tools/vendor/running-tests-reporter.mjs print the tests still running and hand over to Playwright's
# interrupt, which writes the blob report; the always() uploads then run.
# Measured on main (runs 40725289094, 40719375442, 40700439399): setup before the test step <= 52s,
# uploads <= 35s; test steps up to 14m42s (webkit shard 1/2) and 13m05s for coverage (shard 1/3:
# 12m53s, node units and the viewer suite before 11.8m of workflows), so coverage is the tight one
# in its 18 minutes. This holds only when the npm cache hits: a cold cache adds up to 5m to npm ci,
# and then the job limit can still end the job before the step limit does.
# #473: firefox/webkit shard 1/2 reached its 18-minute step limit (queue run 40866252975: webkit 622 tests
# passed in 17m56s, 48.5 worker-minutes vs 28.0 in shard 2/2; recent shard 1/2 jobs 13.7m-18.9m, shard 2/2
# 7.3m-12.2m), because --shard splits by test count and the slow concept specs sort into shard 1. The page
# workflows now run in three shards per browser with the limits unchanged; the per-shard times are
# re-measured after three green main runs.
# #563: coverage shards reached their 18-minute step limit three times on 2026-10-31 with no failing
# test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564
# shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the
# limits unchanged; the per-shard times are re-measured after three green main runs.
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor of test.yml).
# interrupt, which writes the blob report; the always() uploads then run. The limits assume the npm
# cache hits: a cold cache adds up to 5 minutes to npm ci.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "viewerjs" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" and "docs"
# (nothing here can break), "release" (only the version line of pyproject.toml), or "code" (anything
# else, and every case of doubt). The jobs below run for one class only, and "gate" fails unless
# this job succeeded and each job did what the class asks. The clone has every commit but no file
# contents (blob:none): the script compares file names, and reads pyproject.toml only when it is
# the one file that changed.
changes:
name: change class
runs-on: ubuntu-latest
@@ -69,15 +69,162 @@ jobs:
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
# The suite runs once, under coverage: the same run proves the tests pass and the 85% floor holds.
python:
name: python 3.12 with coverage (85%)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run the suite under coverage
run: python -m coverage run -m tests.run_suite -v
- name: Coverage gate
run: |
python -m coverage combine
python -m coverage report --fail-under=85
# A release (only the version line changed) cannot break a test, but it is what the Registry
# publishes, so the package-content rules are checked. Standard library only: nothing to install.
package:
name: package contents
needs: changes
if: ${{ needs.changes.outputs.class == 'release' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- run: python -m unittest -v tests.test_package_contents
lint:
name: black and flake8
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
security:
name: bandit (high severity)
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
js-test:
name: frontend modules
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The vendor pins and the tooling tests (tests/vendor). Same image and Python as the browser shards:
# some tooling tests start the browser test server.
tooling:
name: tooling tests and pins
needs: changes
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 8
steps:
- uses: actions/checkout@v7
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- run: npm run --prefix tools/vendor check
- run: npm run --prefix tools/vendor test
frontend-coverage:
name: frontend coverage (shard ${{ matrix.shard }}/4)
# Code changes only (#639): no browser test reads a docs or inert file.
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
@@ -85,7 +232,7 @@ jobs:
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 20
timeout-minutes: 17
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
@@ -120,14 +267,10 @@ jobs:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
# Shard 1 also runs the node units and the viewer suite, so the vendor pins and the tooling tests
# run on the lightest shard instead.
- if: matrix.shard == 4
run: npm run --prefix tools/vendor check
- if: matrix.shard == 4
run: npm run --prefix tools/vendor test
# Desktop Chromium only, without tests tagged @quarantine (tools/vendor/frontend-coverage.mjs).
# Shard 1 also runs the node units and the viewer suite.
- name: Page workflows with coverage, shard ${{ matrix.shard }}/4
timeout-minutes: 18
timeout-minutes: 15
run: npm run --prefix tools/vendor test:coverage:shard -- ${{ matrix.shard }}/4
- name: Upload raw coverage
uses: actions/upload-artifact@v7
@@ -137,7 +280,7 @@ jobs:
if-no-files-found: error
retention-days: 3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload Chromium and touch traces
- name: Upload Chromium traces
if: always()
uses: actions/upload-artifact@v7
with:
@@ -147,14 +290,15 @@ jobs:
frontend-coverage-merge:
name: frontend coverage (merge)
# Runs only when every shard succeeded (the implicit success() check).
needs: [changes, frontend-coverage]
if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
if: ${{ needs.changes.outputs.class == 'code' }}
runs-on: ubuntu-latest
# Same image as the shards: the raw files name sources by the container's workspace path.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 10
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- run: node --version && node --version | grep -q '^v24\.'
@@ -214,97 +358,50 @@ jobs:
!coverage/js/raw/**
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Merge queue, main and manual runs only (#420); pull requests run the Chromium/touch coverage shards.
# Code changes only (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 20
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 18
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# Branch protection requires the exact context "viewerjs". This job keeps that
# name and fails unless every coverage shard and the coverage merge succeeded and
# the browser shards succeeded, or, on a pull request only, were skipped (#420).
# Any failure, cancellation or other skip fails it. For a docs or inert change (#639) all three
# must be skipped. The classifier itself must succeed, and a class it does not print fails the gate.
viewerjs:
needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows]
# The one required context. Branch protection names only "gate", so renaming or adding a job above
# never strands a pull request. It passes only when the classifier succeeded and every job did what
# the class asks: for "code" every test job succeeded and the release check was skipped; for
# "release" only the package check ran, and it succeeded; for "docs" and "inert" everything was
# skipped. A failed, cancelled or wrongly skipped job fails it, and so does a class the classifier
# does not print.
gate:
needs: [changes, python, package, lint, security, js-test, tooling, frontend-coverage, frontend-coverage-merge]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every frontend job to succeed
- name: Require every job the change class asks for
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
CHANGES_RESULT: ${{ needs.changes.result }}
PYTHON_RESULT: ${{ needs.python.result }}
PACKAGE_RESULT: ${{ needs.package.result }}
LINT_RESULT: ${{ needs.lint.result }}
SECURITY_RESULT: ${{ needs.security.result }}
JS_RESULT: ${{ needs.js-test.result }}
TOOLING_RESULT: ${{ needs.tooling.result }}
COVERAGE_RESULT: ${{ needs.frontend-coverage.result }}
MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }}
WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }}
run: |
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
code) code=success; release=skipped ;;
release) code=skipped; release=success ;;
docs|inert) code=skipped; release=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_only)"
echo "frontend-coverage: $COVERAGE_RESULT"
echo "frontend-coverage-merge: $MERGE_RESULT"
echo "browser-workflows: $WORKFLOWS_RESULT"
test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only"
failed=0
require() {
echo "$1: $2 (must be $3)"
if [ "$2" != "$3" ]; then echo "::error::$1 is $2, must be $3"; failed=1; fi
}
require python "$PYTHON_RESULT" "$code"
require lint "$LINT_RESULT" "$code"
require security "$SECURITY_RESULT" "$code"
require js-test "$JS_RESULT" "$code"
require tooling "$TOOLING_RESULT" "$code"
require frontend-coverage "$COVERAGE_RESULT" "$code"
require frontend-coverage-merge "$MERGE_RESULT" "$code"
require package "$PACKAGE_RESULT" "$release"
exit "$failed"
-71
View File
@@ -1,71 +0,0 @@
name: Code Quality
permissions:
contents: read
on:
merge_group:
push:
branches: [main]
pull_request:
branches: [main]
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required context still reports. This workflow has no gate job, so the scan runs whenever the
# class is not "docs" or "inert": a classifier that fails or prints nothing means a full scan. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
security:
name: bandit (high severity)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665,
# 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. change class (#639): 5 min, the floor.
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python 3.12
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install bandit
run: pip install bandit[toml]
# Medium findings are reported without failing until they are triaged.
# High severity is a hard gate.
- name: Security report (medium and above, informational)
run: bandit -r . -ll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules --exit-zero
- name: Security scan (high severity gate)
run: bandit -r . -lll -q --exclude ./tests,./reference,./venv,./tools/vendor/node_modules
+359
View File
@@ -0,0 +1,359 @@
name: Nightly
permissions:
contents: read
# Everything that is not in the gate (#666): other browsers, the phone-size project, other Pythons,
# Windows, a real mount, a real ComfyUI and the wall-clock budget. It never runs on a pull request or
# a merge and no context here is required. A failing job opens or updates one issue
# ("nightly: <job> failing"); the next green run closes it. To try a branch before it merges:
# gh workflow run nightly.yml --ref <branch> (a branch run files no issues).
on:
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never
# under 5, timed as whole-job wall time; a matrix job takes its slowest leg. A job with no three
# green runs yet has an "estimate" line. tests/vendor/ci-workflow.test.mjs recomputes every limit.
# Measured 2026-11-21 on runs 44861123845 (a1f7447), 44547399478 (b3bb55f), 44519471869 (fa31644):
# python-linux: 6m12s / 5m14s / 5m37s -> 13 min
# comfyui: 20m21s / 20m39s / 21m06s -> 35 min
# perf-budget: 0m23s / 0m29s / 0m28s -> 5 min
# Measured 2026-11-21 on runs 44730775403 (b3bb55f), 44518136123 (9943a61), 44298521973 (1d509c8):
# python-windows: 8m04s / 8m41s / 9m27s -> 18 min
# native-trash-linux: 0m29s / 0m19s / 0m29s -> 5 min
# Measured 2026-11-21 on runs 44861123725 (a1f7447), 44547398683 (b3bb55f), 44519471975 (fa31644):
# browser-workflows: 12m44s / 15m55s / 14m55s -> 27 min
# (the Firefox and WebKit legs; touch ran inside the coverage shards until #666 and has no
# measurement of its own: about half of a 7m55s-16m48s shard)
# estimate report: one script and a few API calls, under 1 minute -> 5 min
#
# Browser jobs (#425): the page test step has its own timeout-minutes, 2 below the job's, so a hang
# ends inside the step and the log, the blob report and the traces survive (see ci.yml).
jobs:
python-linux:
name: py${{ matrix.python-version }} on ubuntu-latest
runs-on: ubuntu-latest
timeout-minutes: 13
strategy:
fail-fast: false
matrix:
python-version: ["3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
run: python -m tests.run_suite -v
python-windows:
name: py${{ matrix.python-version }} on windows-latest
runs-on: windows-latest
timeout-minutes: 18
strategy:
fail-fast: false
matrix:
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 3
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets"). Shared-runner timing
# varies, so it never gates a pull request. A red run means fix the code.
name: perf budget
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
comfyui:
name: real ComfyUI compatibility
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 35
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
browser-workflows:
name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3)
# Firefox, WebKit and touch (phone-size Chromium): not first-class, so they report here instead of
# blocking a merge. Quarantined tests (@quarantine) run here too. One retry: a test that fails
# and then passes is listed as flaky in the job summary (tools/vendor/flaky-tests-reporter.mjs)
# instead of failing the job.
runs-on: ubuntu-latest
# Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the
# same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json;
# tests/vendor/browser-image.test.mjs checks it). Browsers and fonts come from the image.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 27
# Public-repo ubuntu-latest runners have 4 vCPUs: three Playwright workers, each with its own test
# server, leave one CPU for the servers and the runner.
env:
PM_TEST_WORKERS: 3
strategy:
fail-fast: false
matrix:
browser: [firefox, webkit, touch]
shard: [1, 2, 3]
steps:
- uses: actions/checkout@v7
# The image's own Python 3.12 and Node 24: setup-python/setup-node install the runner's toolcache
# builds, whose entry points name host paths that do not exist in the container. The image has no
# ensurepip and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv.
- name: Python environment
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
run: |
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
"$venv/bin/python" -m pip install --no-cache-dir -r requirements-dev.txt
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# npm's download cache, keyed on the lockfile; inside the container ~ is the job's HOME (/github/home),
# which npm also uses. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Page workflows in ${{ matrix.browser }}, shard ${{ matrix.shard }}/3
timeout-minutes: 25
run: npm run --prefix tools/vendor test:workflows -- --project ${{ matrix.browser }} --shard ${{ matrix.shard }}/3 --retries 1
# Traces and the blob report (test-results/blob/) of a failed, timed-out or cancelled step.
- name: Upload browser traces
if: always()
uses: actions/upload-artifact@v7
with:
name: browser-traces-${{ matrix.browser }}-shard-${{ matrix.shard }}
path: tools/vendor/test-results/
retention-days: 14
# One issue per job (tools/ci/nightly_report.py): a job with a failed leg opens "nightly: <job>
# failing" or comments on the open one; a job whose legs all passed closes its open issue. Shards
# of one browser count as one job. Only runs of main report: a manual run of a branch changes no
# issue.
report:
name: report by issue
needs: [python-linux, python-windows, native-trash-linux, perf-budget, comfyui, browser-workflows]
if: ${{ always() && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
contents: read
issues: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Open, update or close one issue per job
env:
GH_TOKEN: ${{ github.token }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: python3 tools/ci/nightly_report.py
-117
View File
@@ -1,117 +0,0 @@
name: Windows
permissions:
contents: read
# Non-blocking Windows runs (#420; macOS dropped from CI in #571): never on pull requests or in the merge queue, and no context
# here is a required check. A red run is fixed at its cause before the workspace cutover (#334).
on:
push:
branches: [main]
schedule:
- cron: "17 3 * * *"
workflow_dispatch:
# Every run gets its own group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.run_id }}
cancel-in-progress: false
env:
PYTHONFAULTHANDLER: "1"
# Time limit rule as in test.yml: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5, timed as whole-job wall time. One matrix job, so the slowest leg of each
# run counts (tests/vendor/ci-workflow.test.mjs recomputes it, #493).
# Measured 2026-10-29 on main runs 40935337099 (dd247e3), 40938407252 (dd247e3), 40941240624 (dd247e3):
# slowest leg: 7m24s (py3.12 windows) / 7m31s (py3.13 windows) / 7m32s (py3.14 windows) -> 15 min
# (windows 4m56s-7m32s)
# native-trash-linux (#543) has no green main runs yet: it installs the dev requirements and runs
# one test module, about 1 minute by the same estimate, so ceil(1.5 x 2) + 3 gives it 6 minutes.
# Recalibrate after three green runs.
jobs:
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [windows-latest]
python-version: ["3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
# The runner's TEMP is on C:, the OS disk, where a flush took about 6 ms
# and a test database's create-to-delete about 111 ms; on the D: work
# disk the same took 0.5 ms and 23 ms. Tests write their
# databases under TEMP, so it moves to a folder on D: (measured in #487,
# run 40915866444). The runner's TEMP was an 8.3 short name
# (C:\Users\RUNNER~1\...), so the new one is spelled by its short name too
# and paths still have to be resolved. D: makes no short names by default
# (run 40922502209), so they are switched on for it first.
- name: Keep test files on the work disk (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
fsutil 8dot3name set D: 0
$folder = New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP "PromptManagerTests")
$short = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($folder.FullName).ShortPath
Write-Output "test TEMP: $short (long name $($folder.FullName))"
if ($short -eq $folder.FullName) { Write-Output "::warning::D: gave the test TEMP no 8.3 short name" }
"TEMP=$short" >> $env:GITHUB_ENV
"TMP=$short" >> $env:GITHUB_ENV
- name: Run tests
env:
PM_TEST_SLOWEST: "40"
run: python -m tests.run_suite -v
# The same tests as the fake mount table, on a real ext4 mount used as the output root (#543). A
# runner can mount with sudo; the tests run as the normal user, so owner and mode checks are real.
native-trash-linux:
name: native trash on a real mount
runs-on: ubuntu-latest
timeout-minutes: 6
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Mount an ext4 image
run: |
truncate -s 64M "$RUNNER_TEMP/drive.img"
mkfs.ext4 -q "$RUNNER_TEMP/drive.img"
mkdir "$RUNNER_TEMP/drive"
sudo mount -o loop "$RUNNER_TEMP/drive.img" "$RUNNER_TEMP/drive"
sudo rmdir "$RUNNER_TEMP/drive/lost+found"
sudo chown "$(id -u):$(id -g)" "$RUNNER_TEMP/drive"
findmnt "$RUNNER_TEMP/drive"
- name: Native trash proof
timeout-minutes: 4
run: PM_TRASH_MOUNT="$RUNNER_TEMP/drive" python -m unittest tests.test_trash_mount_root -v
+6
View File
@@ -11,10 +11,16 @@ on:
permissions:
issues: write
# The only workflow a push to main starts (#666): the pull request's gate already tested the commit.
# It runs when pyproject.toml changed, and the action publishes when the version is new.
# Time limit rule as in ci.yml: ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
# Measured 2026-11-21 on runs 44547398738 (b3bb55f), 44189688689 (1d509c8), 41519786847 (71b55bc):
# publish-node: 0m33s / 0m31s / 1m16s -> 5 min
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
timeout-minutes: 5
if: ${{ github.repository_owner == 'ComfyAssets' }}
steps:
- name: Check out code
-354
View File
@@ -1,354 +0,0 @@
name: Tests
permissions:
contents: read
on:
merge_group:
pull_request:
branches: [main]
push:
branches: [main]
workflow_dispatch:
# Superseded PR pushes cancel their older run. Every main push gets its own
# group (run_id), so no main commit's run is ever cancelled or dropped as pending.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
PYTHONFAULTHANDLER: "1"
# Every job has a time limit: ceil(1.5 x the slowest of three recent green runs on main) + 3
# minutes, never under 5. The 3 minutes leave room for the Python runner's watchdog (120 s, see
# tests/run_suite.py) to print its stack dump before GitHub cancels the job. A limit changes only
# with new measurements written here (TESTING.md "Time limits and hangs").
# Measured 2026-10-26 on runs 40257217681 (3be0ada), 40240706568 (fb9134f), 40228167328 (f9835aa):
# py matrix, slowest py3.10 on windows-latest: 12m43s / 15m54s / 14m53s -> 27 min
# (ubuntu 5m27s-6m27s, macos 6m14s-8m30s, windows 11m42s-15m54s)
# 3.10 and 3.11 left the matrix and 3.14 joined it in #356; re-measure after three green main runs.
# Windows moved to portability.yml (#420; macOS left CI in #571), which has its own measured limit (#493);
# this Linux-only matrix keeps 27 minutes until it is re-measured.
# real ComfyUI compatibility: 13m32s / 8m55s / 11m46s -> 24 min
# coverage gate (85%): 7m26s / 7m22s / 7m54s -> 15 min
# perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s,
# frontend modules 23s / 19s / 29s -> 5 min (the floor)
# all tests: a result check without setup, 5 min (the floor)
# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor)
#
# Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend
# modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on
# Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set.
# Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge.
jobs:
# Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads
# them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The
# jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so
# the required contexts still report; "all tests" fails unless this job succeeded and each
# job did what the class asks. The clone has every commit but no file contents (blob:none): the
# script only compares file names between the base and the head.
changes:
name: change class
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
class: ${{ steps.classify.outputs.class }}
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Classify the changed files
id: classify
env:
EVENT_NAME: ${{ github.event_name }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT"
test:
name: py${{ matrix.python-version }} on ${{ matrix.os }}
# A skipped matrix job reports under its unexpanded name, which would leave the required context
# "py3.12 on ubuntu-latest" waiting for ever. So this job always runs: a docs change gets the 3.12
# leg only, and for an inert change the leg starts and its steps are skipped (#639).
needs: changes
if: ${{ !cancelled() }}
runs-on: ${{ matrix.os }}
timeout-minutes: 27
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ${{ (github.event_name == 'pull_request' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }}
steps:
- uses: actions/checkout@v7
if: needs.changes.outputs.class != 'inert'
- name: Set up Python ${{ matrix.python-version }}
if: needs.changes.outputs.class != 'inert'
uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
if: needs.changes.outputs.class != 'inert'
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run tests
if: needs.changes.outputs.class != 'inert'
run: python -m tests.run_suite -v
- name: Nothing to test
if: needs.changes.outputs.class == 'inert'
run: echo "Only inert files changed (tools/ci/change_class.py); no test can be affected."
comfyui:
name: real ComfyUI compatibility
# Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this
# required context never blocks a pull request; "all tests" fails if it is skipped anywhere else
# for a code change. Docs and inert changes skip it everywhere (#639).
needs: changes
if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
# Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in
# tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install
# pulled them from Ubuntu's apt mirror on every run, and three runs (#349, #378, #382) crawled at
# ~26 kB/s for 11-12 minutes until the job hit its limit after every test had passed.
container:
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
options: --user 1001
timeout-minutes: 24
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Read the reviewed runtime pins
id: runtime
run: |
node --input-type=module <<'JS' >> "$GITHUB_OUTPUT"
import runtime from './tools/vendor/comfyui-runtime.json' with { type: 'json' };
for (const [key, value] of Object.entries(runtime)) console.log(`${key}=${value}`);
import crossPack from './tools/vendor/cross-pack-runtime.json' with { type: 'json' };
console.log(`kikoRepository=${crossPack.repository}`);
console.log(`kikoRevision=${crossPack.revision}`);
JS
- name: Check out pinned ComfyUI
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.repository }}
ref: ${{ steps.runtime.outputs.revision }}
path: .ci-comfyui
persist-credentials: false
- name: Check out pinned KikoTools for compatibility
uses: actions/checkout@v7
with:
repository: ${{ steps.runtime.outputs.kikoRepository }}
ref: ${{ steps.runtime.outputs.kikoRevision }}
path: .ci-kikotools
persist-credentials: false
# The image's own Python and Node 24: setup-python/setup-node install the runner's toolcache builds,
# whose entry points name host paths that do not exist in the container. The image has no ensurepip
# and the job has no root, so a checksum-pinned pip wheel bootstraps a user-space venv. The image
# Python must be the reviewed host Python, so a pin or image bump that disagrees fails here.
- name: Python environment on the reviewed host Python
env:
PIP_WHEEL: https://files.pythonhosted.org/packages/f3/6e/1736e5b4ae2b778ef2f81c47d797de9f891d4d8acb047a24ca37a60294dd/pip-26.2.1-py3-none-any.whl
PIP_SHA256: 71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
PINNED_PYTHON: ${{ steps.runtime.outputs.pythonVersion }}
run: |
image="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
[ "$image" = "$PINNED_PYTHON" ] || { echo "::error::image Python $image is not the pinned $PINNED_PYTHON"; exit 1; }
venv="$RUNNER_TEMP/venv" wheel="$RUNNER_TEMP/pip-26.2.1-py3-none-any.whl"
python3 -m venv --without-pip "$venv"
curl -fsSL --retry 3 -o "$wheel" "$PIP_WHEEL"
echo "$PIP_SHA256 $wheel" | sha256sum -c -
"$venv/bin/python" "$wheel/pip" install --no-index --no-cache-dir "$wheel"
echo "$venv/bin" >> "$GITHUB_PATH"
- run: python --version && node --version && node --version | grep -q '^v24\.'
# pip's download cache (torch alone is ~200 MB); inside the container ~ is the job's HOME (/github/home).
- name: Cache pip downloads
uses: actions/cache@v6
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('requirements-dev.txt', '.ci-comfyui/requirements.txt', 'tools/vendor/comfyui-runtime.json') }}
- name: Install CPU runtime and test dependencies
run: |
pip install "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}" --index-url https://download.pytorch.org/whl/cpu
pip install -r .ci-comfyui/requirements.txt -r requirements-dev.txt "torch==${{ steps.runtime.outputs.torchVersion }}" "torchvision==${{ steps.runtime.outputs.torchvisionVersion }}"
# npm's download cache, keyed on the lockfile. node_modules itself is still built fresh by npm ci.
- name: Cache npm downloads
uses: actions/cache@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-playwright-v1.64.1-${{ hashFiles('tools/vendor/package-lock.json') }}
- run: npm ci --prefix tools/vendor --ignore-scripts
- name: Classic and Nodes 2.0 startup and compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:comfyui
- name: Real cached and headless execution history
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:executions
- name: Independent and combined pack compatibility
env:
PM_COMFY_ROOT: ${{ github.workspace }}/.ci-comfyui
PM_KIKO_ROOT: ${{ github.workspace }}/.ci-kikotools
PM_TEST_PYTHON: python
run: npm run --prefix tools/vendor test:compat
- name: Upload real-host reports and startup logs
if: always()
uses: actions/upload-artifact@v7
with:
name: real-comfyui-reports
path: tools/vendor/test-results/
if-no-files-found: ignore
retention-days: 14
coverage:
name: coverage gate (85%)
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Measure coverage
run: |
python -m coverage run -m tests.run_suite
python -m coverage combine
python -m coverage report --fail-under=85
perf-budget:
# The reference wall-clock measurement (TESTING.md "Performance budgets").
# Shared-runner timing varies, so it never gates a pull request: it runs on
# each push to main and on demand. A red run on main means fix the code.
name: perf budget
needs: changes
if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements-dev.txt
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Workspace filter budget
env:
PROMPTMANAGER_PERF_BUDGET: "1"
run: python -m unittest -v tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget
lint:
name: black and flake8
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
cache-dependency-path: requirements-dev.txt
# The exact black and flake8 pins from requirements-dev.txt, so a new release cannot turn CI red.
- run: pip install $(grep -E '^(black|flake8)==' requirements-dev.txt)
- run: black --check .
- run: flake8 .
js-test:
name: frontend modules
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: "24"
cache: npm
cache-dependency-path: tools/vendor/package-lock.json
- name: Check shipped extension and page modules parse
run: |
shopt -s globstar nullglob
for f in web/comfy/**/*.js web/comfy/**/*.mjs web/js/**/*.js web/js/**/*.mjs; do
node --input-type=module --check < "$f" || exit 1
done
- name: Install pinned shared test contracts
run: npm ci --prefix tools/vendor --ignore-scripts
- name: Run JS tests
run: node --test tests/js/*.test.js
# The required context "all tests". A dropped matrix leg never reports a check at all, so the eight
# legs that pull requests skip cannot be required by name; this gate requires them instead. Every
# job must succeed; real ComfyUI must be skipped on a pull request and succeed on every other event.
# For a docs or inert change (#639) the test matrix must still succeed and every other job must be
# skipped. The classifier itself must succeed, and a class it does not print fails the gate.
all-tests:
name: all tests
needs: [changes, test, comfyui, coverage, lint, js-test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Require every test job for this event
env:
EVENT_NAME: ${{ github.event_name }}
CHANGES_RESULT: ${{ needs.changes.result }}
CHANGE_CLASS: ${{ needs.changes.outputs.class }}
TEST_RESULT: ${{ needs.test.result }}
COMFYUI_RESULT: ${{ needs.comfyui.result }}
COVERAGE_RESULT: ${{ needs.coverage.result }}
LINT_RESULT: ${{ needs.lint.result }}
JS_RESULT: ${{ needs.js-test.result }}
run: |
echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)"
test "$CHANGES_RESULT" = success
case "$CHANGE_CLASS" in
code) code_only=success; queue_only=success ;;
docs|inert) code_only=skipped; queue_only=skipped ;;
*) echo "::error::unknown change class"; exit 1 ;;
esac
if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi
echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_only)"
echo "test matrix: $TEST_RESULT"
echo "comfyui: $COMFYUI_RESULT"
echo "coverage: $COVERAGE_RESULT"
echo "lint: $LINT_RESULT"
echo "js-test: $JS_RESULT"
test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only"
+1 -1
View File
@@ -13,7 +13,7 @@ repos:
language: system
types: [python]
# Fails at the severity CI enforces (code-quality.yml: -lll, high only), never stricter.
# Fails at the severity CI enforces (ci.yml: -lll, high only), never stricter.
# pre-commit appends the staged files, so no shell wrapper can drop the first one.
- id: bandit
name: bandit
+1 -2
View File
@@ -5,8 +5,7 @@
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![ComfyUI](https://img.shields.io/badge/ComfyUI-compatible-green.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
![Code Quality](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Code%20Quality/badge.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
A comprehensive ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, automatic image gallery system, folder-based organization, LoRA Manager integration, and powerful ComfyUI workflow metadata analysis using SQLite.
+2 -2
View File
@@ -8,7 +8,7 @@
![License](https://img.shields.io/badge/license-MIT-blue.svg)
![Python](https://img.shields.io/badge/python-3.12%2B-blue.svg)
![Tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/workflows/Tests/badge.svg)
![Nightly tests](https://github.com/ComfyAssets/ComfyUI_PromptManager/actions/workflows/nightly.yml/badge.svg)
Prompt Manager saves your prompts as you generate, links each image back to the prompt that made it, and gives you one page to browse, tag, compare and reuse all of it. Your library is a local SQLite database on your own machine.
@@ -246,7 +246,7 @@ The documentation for those pages is in [README-legacy.md](README-legacy.md).
| Browser | Over 60 Playwright spec files in Chromium, Firefox, WebKit and touch emulation |
| Real ComfyUI | A pinned CPU ComfyUI, started in Classic and Nodes 2.0, running real workflows |
Linux runs on every pull request and in the merge queue. Windows runs on every push to main and nightly. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
Every pull request runs the Python suite, the frontend tests and the browser tests in Chromium, once. Firefox, WebKit, touch emulation, Python 3.13 and 3.14, Windows and the real ComfyUI run every night. macOS is not tested; it should work, but support is best-effort. To run the tests yourself, see [TESTING.md](TESTING.md).
## License
+176 -122
View File
@@ -35,8 +35,8 @@ python -m tests.run_suite -q # what CI runs; see "Time limits and hangs"
npm ci --prefix tools/vendor --ignore-scripts
npx --prefix tools/vendor playwright install --with-deps chromium firefox webkit
npm run --prefix tools/vendor test
npm run --prefix tools/vendor test:coverage
npm run --prefix tools/vendor test:workflows -- --project firefox --project webkit
npm run --prefix tools/vendor test:coverage # desktop Chromium: what the gate runs
npm run --prefix tools/vendor test:workflows -- --project firefox --project webkit --project touch # what nightly runs
```
`python -m unittest discover -s tests` still works and finds the same tests;
@@ -191,23 +191,26 @@ exists. It uses the gate's own `discoverSources`, and `npm test` runs the same
check, so run it before pushing a new or deleted frontend file instead of
waiting for the `frontend coverage` jobs.
The `viewerjs` check runs on every PR, including backend-only changes. It is an
aggregate job. It requires the four `frontend coverage (shard N/4)` jobs and
`frontend coverage (merge)` to succeed on every event. The six
`page workflows (firefox|webkit, shard N/3)` jobs run only in the merge queue,
on `main` and on `workflow_dispatch` (see "Pull requests and the merge queue").
`viewerjs` requires them to be skipped on a pull request and to succeed
everywhere else. Any other failed, cancelled or skipped job fails it. Every browser job runs with `PM_TEST_WORKERS: 3` (the public
Frontend coverage is measured with desktop Chromium alone (#666): the gate's
four `frontend coverage (shard N/4)` jobs and `frontend coverage (merge)` run on
every pull request with a code change, including backend-only ones (see "The
gate and the nightly run"). The phone-size `touch` project, Firefox and WebKit
run nightly and add no coverage. Measured on main a1f74470 in the pinned image
(2026-11-21): with the node units and Chromium alone, without touch, all 126
files met their floors; the closest were `workspace/images-state.mjs` branches
(98.05 against 98) and `workspace/viewer-state.mjs` branches (95.06 against 95).
Every browser job runs with `PM_TEST_WORKERS: 3` (the public
runners have 4 vCPUs). Each coverage shard runs `test:coverage:shard -- N/4`
(shard 1 also runs the node units and the viewer suite, shard 4 the vendor pins
and tooling tests) and uploads its raw V8 files as `coverage-raw-N` (kept 3
days). The merge job downloads them, fails unless all three arrived with raw
(shard 1 also runs the node units and the viewer suite) and uploads its raw V8
files as `coverage-raw-N` (kept 3 days). The merge job downloads them, fails
unless all four arrived with raw
files and without clashing names, then runs `coverage:merge` (report plus
baseline check). `tests/vendor/ci-workflow.test.mjs` checks this shape. GitHub
baseline check). The vendor pins and the tooling tests run in their own job,
`tooling tests and pins`. `tests/vendor/ci-workflow.test.mjs` checks this shape. GitHub
artifacts named `frontend-test-reports` contain the merged HTML coverage and
JSON summary; `frontend-traces-shard-N` hold the Chromium/touch failure
screenshots/traces and `browser-traces-<browser>-shard-N` the other browsers'
traces. Open traces with Playwright's `show-trace` tool.
JSON summary; `frontend-traces-shard-N` hold the Chromium failure
screenshots/traces and, from the nightly run, `browser-traces-<browser>-shard-N`
the other projects' traces. Open traces with Playwright's `show-trace` tool.
Every `npm ci` first restores npm's download cache (`~/.npm`), keyed on the vendor
lockfile and the job's pinned image tag (`tests/vendor/ci-workflow.test.mjs` checks
@@ -235,8 +238,8 @@ need targeted validation.
## Time limits and hangs
CI and the pre-push hook run the Python suite as `python -m tests.run_suite`
(`-v`, `-q`, `-s START` and `-p PATTERN` as in `unittest discover`), and the
coverage job as `python -m coverage run -m tests.run_suite`. The runner
(`-v`, `-q`, `-s START` and `-p PATTERN` as in `unittest discover`); the gate
runs it once, under coverage, as `python -m coverage run -m tests.run_suite -v`. The runner
(`tests/run_suite.py`) discovers the same tests with the same `sys.path` and
warning filters as `python -m unittest discover -s tests`, exits 0, 1, or 5 when
no tests ran (Python 3.12+ behaviour, on every version), and adds a watchdog: it writes `start: <test id>` to stderr before every test, at every
@@ -264,13 +267,13 @@ the process exits non-zero.
job fails anyway and the dump is what matters.
- `PM_TEST_SLOWEST=N` (off by default) lists the N slowest tests after the
summary, each timed from its `start:` line to the next one like the hang
limit. The Windows jobs (`portability.yml`) set it to 40, so every
limit. The Windows jobs (`nightly.yml`) set it to 40, so every
run shows where its time went (#487). The list prints only when the run
ends: a job GitHub cancels or a watchdog exit prints none, so read the
timestamps between `start:` lines instead.
- On the Windows runners `TEMP` sits on the OS disk C:, where a flush took about
6 ms and a test database's create-to-delete about 111 ms (D: 0.5 ms and 23 ms,
macOS 19 ms). `portability.yml` points `TEMP`/`TMP` at a folder under
macOS 19 ms). `nightly.yml` points `TEMP`/`TMP` at a folder under
`RUNNER_TEMP` on D: before the suite. It switches 8.3 short names on for D:
and spells the folder by its short name, as the runner's own TEMP was
(`C:\Users\RUNNER~1\...`), logs it, and warns when there is none.
@@ -294,21 +297,25 @@ the process exits non-zero.
expects no ComfyUI nearby works two folders inside its temp folder, because
the output-folder fallback looks two levels up.
Every job in `test.yml`, `code-quality.yml`, `viewerjs-check.yml` and
`portability.yml` has `timeout-minutes` (`tests/vendor/ci-workflow.test.mjs`
checks it). The rule is ceil(1.5 x the slowest of three recent green runs on
`main`) + 3 minutes, never under 5, timed as whole-job wall time; the three run
ids, their times and the resulting limits are written in a comment above
`jobs:`. For `portability.yml` the tooling test recomputes the limit from that
comment (#493); its one matrix job takes the slowest Windows or macOS leg. The 3 minutes leave room for one watchdog firing, so
the dump prints before GitHub cancels the job. A job that hits its limit, or a
watchdog dump, is a failure like any other: read the dump, find the blocking
call, fix it. Never raise a limit or rerun to get green; a limit changes only
with new measurements written next to it.
Every job in `ci.yml`, `nightly.yml` and `publish.yml` has `timeout-minutes`.
The rule is ceil(1.5 x the slowest of three recent green runs) + 3 minutes,
never under 5, timed as whole-job wall time; a matrix job takes its slowest
leg. The three run ids, their times and the resulting limit are written in a
comment above `jobs:`, one line per job id
(`python: 7m20s / 7m36s / 7m58s -> 15 min`). A job that has no three green runs
yet has an `estimate <job id>: <why> -> N min` line instead; replace it with
the measurement once three green runs exist. `tests/vendor/ci-workflow.test.mjs`
recomputes every measured limit from its line and checks that each job has
exactly one line and uses its limit (#493). The 3 minutes leave room for one
watchdog firing, so the dump prints before GitHub cancels the job. A job that
hits its limit, or a watchdog dump, is a failure like any other: read the dump,
find the blocking call, fix it. Never raise a limit or rerun to get green; a
limit changes only with new measurements written next to it.
Browser jobs (#425): GitHub keeps no log of a job killed at its limit and skips
its upload steps, so the test step in each browser job in `viewerjs-check.yml`
has its own `timeout-minutes` (18, below the job's 20). At the step limit
its upload steps, so the page test step in each browser job (`frontend coverage`
in `ci.yml`, `page workflows` in `nightly.yml`) has its own `timeout-minutes`,
2 below the job's. At the step limit
GitHub sends SIGTERM, which would end Playwright without any report; under `CI`
`tools/vendor/running-tests-reporter.mjs` catches the first one, prints
`Still running when the run ended (SIGTERM): N` and one line per unfinished
@@ -324,10 +331,9 @@ runs the script, and that shell exits without passing it on. Delivery in CI,
where the step runs through `docker exec`, is not yet observed; the next real
step timeout will show it. That directory and the traces
upload with `if: always()`; `npx playwright merge-reports` opens the blob.
Each test keeps the 30 s default and there is no `globalTimeout`. Two limits
Each test keeps the 30 s default and there is no `globalTimeout`. One limit
of this: it assumes the npm cache hits (a cold cache adds up to 5 minutes to
`npm ci`, and the job limit can then still win), and coverage shard 1 (12m53s
measured) is the tight one in its 18-minute step. Local runs keep the `list`
`npm ci`, and the job limit can then still win). Local runs keep the `list`
reporter only; reproduce with `CI=1 timeout -s TERM 40 npm run --prefix
tools/vendor test:workflows -- --project=firefox`.
@@ -336,18 +342,17 @@ tools/vendor test:workflows -- --project=firefox`.
Follow the run for the commit you pushed, never an older one:
```sh
gh run list --commit <pushed sha> --workflow test.yml # the run id for that commit
gh run list --commit <pushed sha> --workflow ci.yml # the run id for that commit
gh run watch <run id> --exit-status # returns when the run ends
gh run view <run id> --json jobs # shows a job that already failed
gh run view --job <job id> --log-failed # that job's failed log, at once
```
Python 3.13/3.14, real ComfyUI and Firefox/WebKit failures first show up in the
merge queue, on the merge-group commit rather than the
pushed one. Find that run with `gh run list --event merge_group --workflow test.yml`
(or `viewerjs-check.yml`) and match its head branch
(`gh-readonly-queue/main/pr-<N>-...`). Windows failures show up only
after the merge, in `gh run list --workflow portability.yml`.
Everything that can block the merge is in that one run (#666). Firefox, WebKit,
touch, Python 3.13/3.14, Windows and real ComfyUI failures show up the next
morning, as an open `nightly: <job> failing` issue and in
`gh run list --workflow nightly.yml`; to see them before merging, run
`gh workflow run nightly.yml --ref <branch>`.
Start fixing as soon as a failed log shows the cause, but push the fix only after
the run for that commit has finished: pull-request runs use `cancel-in-progress`,
@@ -531,20 +536,20 @@ trim; `tests/test_utils_parallel.py` the pool's reuse, resize, nesting and shutd
`tools/perf/memory_drive.py` (manual, Linux, never in CI) measures RSS, heap, threads
and arenas under the #523 load against the disposable browser test server.
The `perf budget` job in `.github/workflows/test.yml` is the reference
The `perf budget` job in `.github/workflows/nightly.yml` is the reference
measurement: `ubuntu-latest`, one Python, no coverage, only the wall-clock tests.
It runs on every push to `main` and on `workflow_dispatch`, never on pull
requests, because shared-runner timing must not block a merge. Dispatch it on a
branch to measure before merging.
It runs nightly and on `workflow_dispatch`, never on pull
requests, because shared-runner timing must not block a merge. Dispatch
`nightly.yml` on a branch to measure before merging.
Shared Windows runners do not run them; the structural tests cover
portability. Run it locally with
`PROMPTMANAGER_PERF_BUDGET=1 python -m unittest tests.test_api_workspace_images.TestWorkspaceImages.test_filter_budget`
and quote the printed p95 in the PR body.
A red `perf budget` run on `main` means the code got slower: fix the code (or
A red `perf budget` run means the code got slower: fix the code (or
change the budget in the spec with a reason) in a follow-up PR. Never rerun it to
green. It is not a required check, and it cannot be one while it skips pull
requests (`.github/branch-protection.json`).
green. It is not a required check: only `gate` is
(`.github/branch-protection.json`).
## Images listing cache (#348)
@@ -735,114 +740,163 @@ Before changing paths, SQLite, streams, restore or cleanup:
open with `FirstWriterHold`) and give peers that must all succeed the
ordinary busy timeout; cross-thread handoffs wait on events with generous
ceilings, never a short wall clock (#242).
- Run native Windows CI early for these changes. Pull requests and the merge
queue run only Linux, so start Windows on the branch with
`gh workflow run portability.yml --ref <branch>`.
- Run native Windows CI early for these changes. Pull requests run only Linux,
so start Windows on the branch with
`gh workflow run nightly.yml --ref <branch>` (a branch run files no issues).
Include a Windows impact and evidence note in the PR. All three Windows
legs in that run, every Linux leg and every applicable
exact-head check must pass before merge. Portable `ntpath`/`PureWindowsPath`
controls do not establish native filesystem, locking or cleanup success.
## Pull requests and the merge queue
## The gate and the nightly run
Each PR runs the full matrix once, in the merge queue (#420). The event decides
what runs:
A change is tested once, on its pull request (#666). There is no merge queue
and a push to `main` runs no test. Three workflows:
| Job | `pull_request` | `merge_group`, push to `main`, `workflow_dispatch` |
| Workflow | Runs on | Jobs |
| --- | --- | --- |
| `py3.12 on ubuntu-latest` | runs | runs |
| `py3.13 on ubuntu-latest`, `py3.14 on ubuntu-latest` | not created | run |
| `real ComfyUI compatibility` | skipped | runs |
| `coverage gate (85%)`, `black and flake8`, `frontend modules`, `bandit (high severity)` | run | run |
| `frontend coverage (shard N/4)`, `frontend coverage (merge)` (vendor pins and tooling tests on shard 4) | run | run |
| `page workflows (firefox\|webkit, shard N/2)` | skipped | run |
| `all tests`, `viewerjs` (gates) | run | run |
| `perf budget` | skipped | push and dispatch only (not in the queue) |
| `py3.12-3.14 on windows-latest` (`portability.yml`) | not run | push to `main`, nightly, `workflow_dispatch` only; never required |
| `ci.yml` (the gate) | `pull_request`, `workflow_dispatch` | `change class`; `python 3.12 with coverage (85%)` (the suite, once, under coverage); `black and flake8`; `bandit (high severity)`; `frontend modules` (`tests/js`); `tooling tests and pins` (`tests/vendor`, vendor pins); `frontend coverage (shard N/4)` and `frontend coverage (merge)` (desktop Chromium page workflows with the per-file floors); `package contents` (a release only); `gate` |
| `nightly.yml` | 03:17 UTC, `workflow_dispatch` | `page workflows (firefox\|webkit\|touch, shard N/3)`; `py3.13`/`py3.14 on ubuntu-latest`; `py3.12`-`3.14 on windows-latest`; `native trash on a real mount`; `real ComfyUI compatibility`; `perf budget`; `report by issue` |
| `publish.yml` | push to `main` that changes `pyproject.toml`, `workflow_dispatch` | publishes to the Registry when the version is new |
GitHub has one required set for pull requests and the queue. A job skipped by
its `if:` reports Success. A dropped matrix leg never reports, so it would stay
pending. That is why `all tests` (in `test.yml`) and `viewerjs` carry the
guarantee:
- On a pull request they require the subset to succeed and the queue-only jobs
to be skipped.
- On every other event they require every job to succeed.
`gate` is the only required check. It needs every other job of `ci.yml` and
passes only when the classifier succeeded and each job did what the change
class asks (below): the class's jobs succeeded and every other job was
skipped. A failed, cancelled or wrongly skipped job fails it, and so does a
class the classifier does not print. Because branch protection names only
`gate`, adding or renaming a job never strands a pull request. Protection is
strict: the branch must be up to date with `main`, so the commit the gate
tested is the commit that merges. When `main` moved, press "Update branch" and
the gate runs once more.
So a merge group cannot turn green unless all three Linux Python legs, real
ComfyUI and the four browser shards passed.
Only desktop Chromium blocks a merge (maintainer, 2026-11-21). Firefox, WebKit
and the phone-size `touch` project are not first-class; with Python 3.13/3.14,
Windows, the real mount, real ComfyUI and the wall-clock budget they run
nightly on `main`. macOS is not tested in CI (maintainer, 2026-10-31, #571);
its code stays and support is best-effort. The cost: a break only those can
see is found the next morning, not before the merge. To see it before merging
a risky change, run `gh workflow run nightly.yml --ref <branch>`.
Windows (Python 3.12-3.14) is out of the blocking path for now
(maintainer, 2026-10-28). macOS is not tested in CI (maintainer, 2026-10-31, #571);
its code stays and support is best-effort. They run in `portability.yml` on every push to `main`,
nightly and on demand, and no context there is required. A red portability run
is still a failure: fix it at its cause, not by rerunning, and have every one
green before the workspace cutover (#334). `tests/vendor/ci-workflow.test.mjs` pins the
event split and runs both gate scripts for each event.
### Nightly reports by issue
Nothing waits for the nightly run, so it reports by issue
(`tools/ci/nightly_report.py`, the `report by issue` job, the only job in CI
with a write permission: `issues: write`). For each job of the run:
- a failed or timed-out leg opens `nightly: <job> failing`, or comments on the
open issue with that exact title, naming the run, the commit and the failed
legs;
- every leg green closes that issue with a comment naming the run;
- a cancelled or skipped job changes nothing.
Shards of one browser are one job (`nightly: page workflows (webkit) failing`).
Only a run of `main` reports; a manual run of a branch files nothing. A red
nightly job is a failure like any other: read the log, fix the cause. It blocks
no merge, and it is never rerun to green.
### Flaky tests and quarantine
- **No retries in the gate.** A retry hides a race. A gate test passes or fails
on its one attempt (`retries: 0` in both Playwright configs).
- **No rerun-to-green.** A red job is read and fixed at its cause. The one
exception is unchanged: a pure timeout with every test passing may be rerun.
- **A gate test that fails without a code cause is fixed or quarantined the
same day.** Open an issue, then tag the test with that issue, in exactly this
spelling (`tests/vendor/flake-policy.test.mjs` checks it):
```js
test('closing the viewer never blocks the page', { tag: '@quarantine', annotation: { type: 'issue', description: '#613' } }, async ({ page }) => {
```
The gate's page run passes `--grep-invert @quarantine`
(`tools/vendor/frontend-coverage.mjs`), so the test no longer blocks a merge;
the nightly run still runs it in Firefox, WebKit and touch. To run it in
Chromium while fixing it: `npm run --prefix tools/vendor test:workflows --
--project chromium --grep @quarantine`. Remove the tag in the PR that fixes
the test and closes the issue. A quarantined test adds no coverage, so a
floor that depended on it fails the merge job: that is the signal to fix
the test rather than leave it.
- **Nightly retries once** (`--retries 1`). A test that fails and then passes
does not turn its job red; `tools/vendor/flaky-tests-reporter.mjs` lists it
in the job summary under "Flaky tests". Treat a test listed there twice as a
bug to fix.
Nothing is quarantined today. Measured at the switch (the last 100
pull-request runs of the frontend workflow, 2026-10-31 to 2026-11-21): 9
failed. Six were caused by the pull request's own change (three coverage
floors, a tooling test, a new test that failed in touch, a Playwright bump),
one by a re-pushed image tag (fixed by the digest pin, #609), and two by
Chromium tests that failed without a cause in the pull request; both were
fixed at their cause (a production race, #611, and a spec that read a status
before its save answered, #631).
### Only changes that can affect code are tested (#639)
The table above is for a code change. Each of the three workflows starts with a
`change class` job that runs `tools/ci/change_class.py` over the files the pull
request, merge group or push touches, and the other jobs follow its answer:
The table above is for a code change. `ci.yml` starts with a `change class` job
that runs `tools/ci/change_class.py` over the files the pull request touches,
and every other job runs for one class only:
| Class | Files (allowlists in the script) | What runs |
| Class | Files | What runs |
| --- | --- | --- |
| `inert` | `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and the two gates. `py3.12 on ubuntu-latest` starts and skips its steps, because a skipped matrix job would never report that required context. |
| `docs` | `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | The above plus the real `py3.12 on ubuntu-latest` suite, which holds the tests that read them (`tests/test_brand_assets.py`, `tests/test_package_contents.py`). |
| `code` | Anything else | Everything in the table above. |
| `inert` | Only `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and `gate`: green in seconds. |
| `docs` | Only `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | `change class` and `gate`: green in seconds. |
| `release` | `pyproject.toml` alone, and in it only the `version = "..."` line rewritten | The above and `package contents` (`tests/test_package_contents.py`). |
| `code` | Anything else | The whole gate. |
A file on no list is code, and so is every case of doubt: no changed files, a
manual run, a range git cannot read. `docs/` is code, because the browser suite
compares production against `docs/concepts/workspace/`; `TESTING.md` is code,
because the tooling tests read its tables. Before adding a file to a list,
check that no test and no shipped code opens it.
manual run, a range git cannot read, a `pyproject.toml` change that is more
than the version line. `docs/` is code, because the browser suite compares
production against `docs/concepts/workspace/`; `TESTING.md` is code, because
the tooling tests read its tables; a test-only change is code. Before adding a
file to a list, check that no shipped code opens it.
The gates enforce the class: for `docs` and `inert` they require the classifier
to have succeeded, the Python matrix to have succeeded and every other job to
have been skipped; a class the script does not print fails them. `bandit` has no
gate, so it runs unless the class is `docs` or `inert`, which means a failed
classifier gets a full scan. The required contexts do not change.
Two Python tests read the `docs` files (`tests/test_brand_assets.py`,
`tests/test_package_contents.py`). CI no longer runs them for a `docs` change
(maintainer, 2026-11-21: documentation and image changes run no tests), so a
README or brand-asset edit that breaks one is caught by the pre-push hook, or
else by the next code change's gate. Run
`python -m unittest tests.test_brand_assets tests.test_package_contents` after
editing those files.
The pre-push hook uses the same script: it skips the Python suite when the
pushed commits are `inert` and runs it otherwise.
## Required merge checks
`.github/branch-protection.json` records the required checks:
`py3.12 on ubuntu-latest`, `coverage gate (85%)`, `black and flake8`,
`frontend modules`, `all tests`, `viewerjs`, `real ComfyUI compatibility` and
`bandit (high severity)`. Each one reports on a pull request.
`.github/branch-protection.json` records the required checks: the one context
`gate`, with `strict` (the branch must be up to date with `main`). It reports
on every pull request, whatever the change class.
The same set lives in two places, and both must change together: the `main`
ruleset (25960526, which also holds the merge queue) and the classic branch
protection on `main`, which the manifest mirrors. GitHub requires the union of
the two, so a context left in either one blocks every PR that does not report it.
It does not require an additional human approval.
ruleset (25960526) and the classic branch protection on `main`, which the
manifest mirrors. GitHub requires the union of the two, so a context left in
either one blocks every PR that does not report it. The ruleset has no
`merge_queue` rule (#666). Merging is the squash button. It does not require an
additional human approval.
A repository administrator applies the configuration after the new workflow is
passing, then verifies it:
A repository administrator applies the configuration, then verifies it:
```sh
gh api repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 \
| jq '.rules[] | select(.type == "required_status_checks") | [.parameters.required_status_checks[].context]'
| jq '.rules[] | select(.type == "required_status_checks") | .parameters'
```
A PUT replaces the whole `rules` array, so edit the current ruleset in place.
Keep the `deletion`, `non_fast_forward` and `merge_queue` rules, and give every
context `integration_id` 15368 (GitHub Actions), so no other integration can
post a required check. Save the current ruleset first; it is the rollback:
Keep the `deletion` and `non_fast_forward` rules, and give the context
`integration_id` 15368 (GitHub Actions), so no other integration can
post the required check. Save the current ruleset first; it is the rollback:
```sh
gh api repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 > ruleset-before.json
jq '{name, target, enforcement, conditions, bypass_actors, rules: [.rules[]
| select(.type != "merge_queue")
| if .type == "required_status_checks"
then .parameters.required_status_checks = [$ARGS.positional[] | {context: ., integration_id: 15368}]
else . end]}' ruleset-before.json --args "py3.12 on ubuntu-latest" "..." > ruleset-new.json
then .parameters.required_status_checks = [{context: "gate", integration_id: 15368}]
| .parameters.strict_required_status_checks_policy = true
else . end]}' ruleset-before.json > ruleset-new.json
gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/rulesets/25960526 --input ruleset-new.json
```
Afterwards, read it back. Check that the `merge_queue` rule is still there and
that every context keeps its `integration_id`. Then apply the manifest to the
classic protection and read both back:
Then apply the manifest to the classic protection and read both back:
```sh
gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protection \
@@ -850,9 +904,9 @@ gh api --method PUT repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protec
gh api repos/ComfyAssets/ComfyUI_PromptManager/branches/main/protection/required_status_checks
gh api repos/ComfyAssets/ComfyUI_PromptManager/rules/branches/main
```
Update the manifest whenever
required job names change. Keep the frontend check
free of path filters so a required check is never silently skipped.
Update the manifest whenever the required context changes. Keep `ci.yml`
free of path filters so the required check is never silently skipped.
## Unified workspace
@@ -2653,7 +2707,7 @@ job after `file_check` confirms containment and non-symlink, and the review step
checks intact. A root above the mount, a mount nested under the root, a source that is or
sits in the trash folder, and a link in place of the trash folder stay refused. Tests:
`tests/test_trash_mount_root.py`, on a fake mount table in the suite and, with
`PM_TRASH_MOUNT=<real mount>`, in portability.yml's `native-trash-linux` job (loop-mounted
`PM_TRASH_MOUNT=<real mount>`, in nightly.yml's `native-trash-linux` job (loop-mounted
ext4). Locally, without root: `unshare -Urm` over a tmpfs.
- **D190** (#543, beyond the concept): a trash review where nothing can move shows a primary
that clearly cannot act: `aria-disabled`, no danger colors (also on hover), and a press does
@@ -2790,7 +2844,7 @@ Recorded deviations on this page:
drive, UNC, non-ASCII, symlinked root, the any-tag union), `test_api_library.py`,
`test_saved_views.py`, the library-state and saved-views JS units, and
`tests/browser/workspace-library-filters.spec.mjs` (behavior, the Refine dialog against
the concept Filters dialog, artifact captures). Windows: run `portability.yml` on the PR.
the concept Filters dialog, artifact captures). Windows: run `nightly.yml` on the PR's branch.
`tests/browser/library-concept.spec.mjs` compares the shelf (#249 E3) on the
concept-shaped fixture, which creates the concept's prompts last to first so Recently
+89 -14
View File
@@ -1,8 +1,9 @@
"""CI runs tests only for changes that can affect code (#639).
``tools/ci/change_class.py`` sorts a change by the files it touches: ``inert``
(nothing reads the file at run or test time), ``docs`` (a Python test reads
it) or ``code`` (everything else, and every case of doubt).
(nothing reads the file at run or test time), ``docs`` (a document),
``release`` (only the version line of ``pyproject.toml``, #666) or ``code``
(everything else, and every case of doubt).
"""
import os
@@ -74,6 +75,29 @@ class TestClassify(unittest.TestCase):
def test_no_files_is_code(self):
self.assertEqual(change_class.classify([]), "code")
def test_a_version_bump_is_one_rewritten_version_line(self):
head = (
"diff --git a/pyproject.toml b/pyproject.toml\n"
"--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -4 +4 @@\n"
)
bump = head + '-version = "3.7.1"\n+version = "3.7.2"\n'
self.assertTrue(change_class.is_version_bump(bump))
self.assertTrue(change_class.is_version_bump(bump.replace("\n", "\r\n")))
for diff in (
"",
head,
head + '-version = "3.7.1"\n',
head + '+version = "3.7.2"\n',
bump + '+name = "x"\n',
bump + "@@ -9 +9 @@\n-a\n+b\n",
head + '-version = "3.7.1"\n+version = "3.7.1"\n',
head + '-version = "3.7.1"\n+ version = "3.7.2"\n',
head + '-version = "3.7.1"\n+version = "3.7.2" # x\n',
head + '-target-version = "a"\n+target-version = "b"\n',
"old mode 100644\nnew mode 100755\n" + bump,
):
self.assertFalse(change_class.is_version_bump(diff), diff)
def test_every_document_a_test_reads_exists(self):
for name in change_class.DOCS_FILES:
self.assertTrue((ROOT / name).is_file(), name)
@@ -155,17 +179,21 @@ class TestCommandLine(unittest.TestCase):
"class=inert",
)
def test_a_merge_group_and_a_push_are_classed_by_their_range(self):
def test_a_push_is_classed_by_its_range(self):
self.commit({"README.md": "r2\n"})
for event in ("merge_group", "push"):
self.assertEqual(
self.class_of(
EVENT_NAME=event, BASE_SHA=self.base, HEAD_SHA=self.head()
),
"class=docs",
event,
)
self.assertEqual(
self.class_of(EVENT_NAME="push", BASE_SHA=self.base, HEAD_SHA=self.head()),
"class=docs",
)
self.commit({"py/a.py": "c\n"})
self.assertEqual(
self.class_of(EVENT_NAME="push", BASE_SHA=self.base, HEAD_SHA=self.head()),
"class=code",
)
def test_no_merge_group_is_classed(self):
# The merge queue is gone (#666): its event is unknown, and doubt is code.
self.commit({"README.md": "r2\n"})
self.assertEqual(
self.class_of(
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
@@ -173,13 +201,60 @@ class TestCommandLine(unittest.TestCase):
"class=code",
)
PROJECT = '[project]\nname = "promptmanager"\nversion = "{}"\nrequires = []\n'
def bump(self, text, **more):
"""The class of a pull request whose one commit rewrites pyproject.toml."""
if not (self.repo / "pyproject.toml").exists():
self.commit({"pyproject.toml": self.PROJECT.format("3.7.1")})
base = self.head()
self.git("checkout", "-q", "-b", "release")
self.commit({"pyproject.toml": text, **more})
found = self.class_of(
EVENT_NAME="pull_request", BASE_SHA=base, HEAD_SHA=self.head()
)
self.git("checkout", "-q", "main")
self.git("branch", "-q", "-D", "release")
return found
def test_only_the_version_line_is_a_release(self):
self.assertEqual(self.bump(self.PROJECT.format("3.7.2")), "class=release")
def test_a_release_with_any_other_change_is_code(self):
bumped = self.PROJECT.format("3.7.2")
for text, more in (
# Another line of the same file.
(bumped.replace("requires = []", 'requires = ["x"]'), {}),
# Another file, even an inert one.
(bumped, {".github/FUNDING.yml": "x\n"}),
(bumped, {"py/a.py": "b\n"}),
# The version line removed or doubled, never rewritten.
(bumped.replace('version = "3.7.2"\n', ""), {}),
(bumped.replace("requires", 'version = "9"\nrequires'), {}),
# A line that only looks like the version.
(
self.PROJECT.format("3.7.1").replace("requires = []", "requires = [1]"),
{},
),
(self.PROJECT.format("3.7.1").replace("version =", "target-version ="), {}),
):
with self.subTest(text=text, more=more):
self.assertEqual(self.bump(text, **more), "class=code")
def test_a_pushed_release_is_a_release(self):
self.commit({"pyproject.toml": self.PROJECT.format("3.7.1")})
base = self.head()
self.commit({"pyproject.toml": self.PROJECT.format("3.8.0")})
self.assertEqual(
self.class_of(EVENT_NAME="push", BASE_SHA=base, HEAD_SHA=self.head()),
"class=release",
)
def test_a_deleted_or_renamed_file_counts_under_both_names(self):
self.git("mv", "py/a.py", "SECURITY.md")
self.git("commit", "-q", "-m", "rename")
self.assertEqual(
self.class_of(
EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head()
),
self.class_of(EVENT_NAME="push", BASE_SHA=self.base, HEAD_SHA=self.head()),
"class=code",
)
+221
View File
@@ -0,0 +1,221 @@
"""The nightly run reports by issue: one per failing job (#666).
``tools/ci/nightly_report.py`` against a recorded ``gh``: what it reads and
which issue it opens, comments on or closes for each kind of result.
"""
import json
import sys
import unittest
import unittest.mock
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "tools" / "ci"))
import nightly_report # noqa: E402
ENVIRONMENT = {
"GITHUB_REPOSITORY": "owner/repo",
"GITHUB_RUN_ID": "77",
"GITHUB_SHA": "0123456789abcdef",
"GITHUB_SERVER_URL": "https://github.example",
"RUN_ATTEMPT": "2",
}
RUN_URL = "https://github.example/owner/repo/actions/runs/77"
def job(name, conclusion):
return {"name": name, "conclusion": conclusion, "html_url": f"https://x/{name}"}
class FakeGh:
"""Answers the two reads from fixtures and records every call."""
def __init__(self, jobs, issues=()):
self.pages = [{"jobs": jobs[:2]}, {"jobs": jobs[2:]}]
self.issues = list(issues)
self.calls = []
def __call__(self, arguments):
self.calls.append(arguments)
if arguments[0] == "api":
return json.dumps(self.pages)
if arguments[:2] == ["issue", "list"]:
return json.dumps(self.issues)
return ""
def writes(self):
return [
call for call in self.calls if call[1] in ("create", "comment", "close")
]
class TestGrouping(unittest.TestCase):
def test_shards_report_as_one_job(self):
for name, group in (
("page workflows (webkit, shard 2/3)", "page workflows (webkit)"),
("frontend coverage (shard 1/4)", "frontend coverage"),
("py3.13 on ubuntu-latest", "py3.13 on ubuntu-latest"),
("real ComfyUI compatibility", "real ComfyUI compatibility"),
):
self.assertEqual(nightly_report.job_group(name), group)
def test_the_report_job_and_unfinished_jobs_are_left_out(self):
groups = nightly_report.group_jobs(
[
job("report by issue", None),
job("perf budget", None),
job("page workflows (touch, shard 1/3)", "success"),
job("page workflows (touch, shard 2/3)", "failure"),
]
)
self.assertEqual(list(groups), ["page workflows (touch)"])
self.assertEqual(len(groups["page workflows (touch)"]), 2)
def test_a_verdict_needs_a_failure_or_every_leg_green(self):
legs = lambda *conclusions: [job("j", c) for c in conclusions] # noqa: E731
self.assertEqual(nightly_report.verdict(legs("success", "failure")), "failing")
self.assertEqual(nightly_report.verdict(legs("timed_out")), "failing")
self.assertEqual(
nightly_report.verdict(legs("cancelled", "failure")), "failing"
)
self.assertEqual(nightly_report.verdict(legs("success", "success")), "passing")
self.assertIsNone(nightly_report.verdict(legs("success", "cancelled")))
self.assertIsNone(nightly_report.verdict(legs("skipped")))
self.assertIsNone(nightly_report.verdict([]))
class TestReport(unittest.TestCase):
def test_it_reads_every_page_of_this_attempts_jobs(self):
gh = FakeGh([job("a", "success"), job("b", "success"), job("c", "success")])
done = nightly_report.report(gh, ENVIRONMENT)
self.assertEqual(
gh.calls[0],
[
"api",
"--paginate",
"--slurp",
"repos/owner/repo/actions/runs/77/attempts/2/jobs?per_page=100",
],
)
self.assertEqual(done, ["a: passing", "b: passing", "c: passing"])
self.assertEqual(gh.writes(), [])
def test_a_failing_job_without_an_issue_opens_one(self):
gh = FakeGh(
[
job("page workflows (webkit, shard 1/3)", "success"),
job("page workflows (webkit, shard 2/3)", "failure"),
job("page workflows (webkit, shard 3/3)", "timed_out"),
],
# A longer title and another job's issue are not this job's issue.
issues=[
{
"number": 5,
"title": "nightly: page workflows (webkit) failing again",
},
{"number": 6, "title": "nightly: page workflows (firefox) failing"},
],
)
done = nightly_report.report(gh, ENVIRONMENT)
(create,) = gh.writes()
self.assertEqual(create[:4], ["issue", "create", "--repo", "owner/repo"])
self.assertEqual(
create[create.index("--title") + 1],
"nightly: page workflows (webkit) failing",
)
body = create[create.index("--body") + 1]
self.assertIn(f"{RUN_URL} failed at 0123456", body)
self.assertIn("shard 2/3)](https://x/", body)
self.assertIn("shard 3/3)", body)
self.assertIn("timed_out", body)
self.assertNotIn("shard 1/3", body)
self.assertEqual(done, ["page workflows (webkit): failing, opened an issue"])
search = gh.calls[1]
self.assertEqual(
search[search.index("--search") + 1],
'in:title "nightly: page workflows (webkit) failing"',
)
self.assertEqual(search[search.index("--state") + 1], "open")
def test_a_job_that_still_fails_comments_on_its_open_issue(self):
gh = FakeGh(
[job("perf budget", "failure")],
issues=[
{"number": 9, "title": "nightly: perf budget failing"},
{"number": 4, "title": "nightly: perf budget failing"},
],
)
done = nightly_report.report(gh, ENVIRONMENT)
(comment,) = gh.writes()
self.assertEqual(comment[:5], ["issue", "comment", "4", "--repo", "owner/repo"])
self.assertIn(RUN_URL, comment[-1])
self.assertEqual(done, ["perf budget: failing, commented on #4"])
def test_a_green_job_closes_its_open_issue_with_a_comment(self):
gh = FakeGh(
[job("perf budget", "success")],
issues=[{"number": 9, "title": "nightly: perf budget failing"}],
)
done = nightly_report.report(gh, ENVIRONMENT)
(close,) = gh.writes()
self.assertEqual(close[:5], ["issue", "close", "9", "--repo", "owner/repo"])
self.assertEqual(
close[close.index("--comment") + 1],
f"Passed in the nightly run {RUN_URL} at 0123456.",
)
self.assertEqual(done, ["perf budget: passing, closed #9"])
def test_a_cancelled_or_skipped_job_changes_nothing(self):
gh = FakeGh(
[job("perf budget", "cancelled"), job("real ComfyUI", "skipped")],
issues=[{"number": 9, "title": "nightly: perf budget failing"}],
)
done = nightly_report.report(gh, ENVIRONMENT)
self.assertEqual(gh.writes(), [])
self.assertEqual(len(gh.calls), 1, "no issue is even looked up")
self.assertEqual(
done,
[
"perf budget: no verdict, nothing changed",
"real ComfyUI: no verdict, nothing changed",
],
)
class TestCommandLine(unittest.TestCase):
def test_gh_is_called_and_its_failure_is_an_error(self):
ok = unittest.mock.Mock(returncode=0, stdout="out", stderr="")
with unittest.mock.patch.object(
nightly_report.subprocess, "run", return_value=ok
) as run:
self.assertEqual(nightly_report.run_gh(["issue", "list"]), "out")
run.assert_called_once_with(
["gh", "issue", "list"], capture_output=True, text=True, check=False
)
bad = unittest.mock.Mock(returncode=1, stdout="", stderr="HTTP 403\n")
with unittest.mock.patch.object(
nightly_report.subprocess, "run", return_value=bad
):
with self.assertRaisesRegex(RuntimeError, "HTTP 403"):
nightly_report.run_gh(["issue", "list"])
def test_main_prints_what_was_done_and_fails_when_a_call_fails(self):
with (
unittest.mock.patch.object(
nightly_report, "report", return_value=["a: passing"]
),
unittest.mock.patch("builtins.print") as printed,
):
self.assertEqual(nightly_report.main(), 0)
printed.assert_called_once_with("a: passing")
for error in (RuntimeError("gh api: HTTP 403"), KeyError("GITHUB_RUN_ID")):
with (
unittest.mock.patch.object(nightly_report, "report", side_effect=error),
unittest.mock.patch("builtins.print"),
):
self.assertEqual(nightly_report.main(), 1)
if __name__ == "__main__":
unittest.main()
+3 -3
View File
@@ -1,8 +1,8 @@
"""Native proof of the macOS trash backend (#499 design §10.2).
Runs only on macOS with ``PM_NATIVE_TRASH=macos`` (the ``native-trash`` job in
portability.yml), because it puts files into the real Trash of the user
running it. With the variable set, a bridge that cannot load fails the test
Runs only on macOS with ``PM_NATIVE_TRASH=macos`` (by hand: macOS left CI in
#571), because it puts files into the real Trash of the user running it.
With the variable set, a bridge that cannot load fails the test
rather than skipping it. Files moved into a trash folder are left there: the
runner is disposable and this test never deletes from a trash folder.
"""
+1 -1
View File
@@ -6,7 +6,7 @@ exactly the mount root; every walker and media route ignores them.
Every class runs on a disposable tree with a fake mount table. With
``PM_TRASH_MOUNT=<empty folder that is a real mount>`` the same tests run on that
real mount (``.github/workflows/portability.yml``, ``native-trash-linux``, or
real mount (``.github/workflows/nightly.yml``, ``native-trash-linux``, or
locally ``unshare -Urm`` over a tmpfs); that folder is the only real place they
touch, and the fake-table-only cases skip.
"""
+7 -4
View File
@@ -5,19 +5,22 @@ import { readFileSync } from 'node:fs';
// Concept comparisons measure layout, and layout depends on the fonts a browser falls back to (the concept names Inter,
// which neither environment ships). Page-workflow jobs therefore run in the same pinned Playwright image as local runs,
// so CI and a developer machine resolve identical fonts and engines.
const workflow = readFileSync(new URL('../../.github/workflows/viewerjs-check.yml', import.meta.url), 'utf8');
const workflows = {
'frontend-coverage': readFileSync(new URL('../../.github/workflows/ci.yml', import.meta.url), 'utf8'),
'browser-workflows': readFileSync(new URL('../../.github/workflows/nightly.yml', import.meta.url), 'utf8'),
};
const lock = JSON.parse(readFileSync(new URL('../../tools/vendor/package-lock.json', import.meta.url), 'utf8'));
const version = lock.packages['node_modules/@playwright/test'].version;
// The tag alone is not a pin: v1.64.1-noble was re-pushed with Node 26 (#609). The digest fixes the image's contents.
const pinnedImage = `^ container:\\n image: mcr\\.microsoft\\.com/playwright:v${version.replaceAll('.', '\\.')}-noble@sha256:[0-9a-f]{64}$`;
function job(name) {
const match = workflow.match(new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [a-z][a-z-]*:\\n|(?![\\s\\S]))`, 'm'));
const match = workflows[name].match(new RegExp(`^ ${name}:\\n([\\s\\S]*?)(?=^ [a-z][a-z-]*:\\n|(?![\\s\\S]))`, 'm'));
assert.ok(match, `${name} job exists`);
return match[1];
}
for (const name of ['frontend-coverage', 'browser-workflows']) {
for (const name of Object.keys(workflows)) {
test(`${name} runs in the pinned Playwright image matching @playwright/test`, () => {
const body = job(name);
assert.match(body, new RegExp(pinnedImage, 'm'));
@@ -36,7 +39,7 @@ for (const name of ['frontend-coverage', 'browser-workflows']) {
// the job hit its limit after every test had passed. The pinned image ships Chromium and its libraries, so the job runs
// there; the image Python must be the reviewed host Python from tools/vendor/comfyui-runtime.json.
test('real ComfyUI compatibility runs in the pinned Playwright image on the reviewed host Python', () => {
const testWorkflow = readFileSync(new URL('../../.github/workflows/test.yml', import.meta.url), 'utf8');
const testWorkflow = workflows['browser-workflows'];
const runtime = JSON.parse(readFileSync(new URL('../../tools/vendor/comfyui-runtime.json', import.meta.url), 'utf8'));
const match = testWorkflow.match(/^ {2}comfyui:\n([\s\S]*?)(?=^ {2}[a-z][a-z-]*:\n|(?![\s\S]))/m);
assert.ok(match, 'comfyui job exists');
+2 -1
View File
@@ -260,10 +260,11 @@ test('worker count follows PM_TEST_WORKERS, then one in CI, then a quarter of th
test('CI adds the running-tests reporter and a blob report under test-results/blob/, which the trace upload covers; local runs keep list', () => {
assert.equal(reporters({ env: {}, name: 'workflows' }), 'list');
const [list, running, blob] = reporters({ env: { CI: '1' }, name: 'workflows' });
const [list, running, flaky, blob] = reporters({ env: { CI: '1' }, name: 'workflows' });
assert.deepEqual(list, ['list']);
// Absolute: a config imported from another directory (workflow-artifacts.test.mjs) still finds it.
assert.ok(isAbsolute(running[0]) && running[0].endsWith('running-tests-reporter.mjs'), running[0]);
assert.ok(isAbsolute(flaky[0]) && flaky[0].endsWith('flaky-tests-reporter.mjs'), flaky[0]);
assert.deepEqual(blob, ['blob', { outputDir: './test-results/blob/workflows' }]);
});
+289 -275
View File
@@ -1,15 +1,20 @@
// Structural checks on .github/workflows/viewerjs-check.yml, plus the time limits of every CI workflow.
// Structural checks on the CI workflows (#666): ci.yml is the gate that runs once on a pull request,
// nightly.yml everything that blocks nothing, publish.yml the only workflow a push to main starts.
// The tooling has no YAML parser, so these read the workflow's fixed two-space layout: jobs at two
// spaces, their keys at four, steps at six.
import test from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtemp, mkdir, readdir, rm, writeFile } from 'node:fs/promises';
import { readFileSync } from 'node:fs';
import { readdirSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const workflow = readFileSync(new URL('../../.github/workflows/viewerjs-check.yml', import.meta.url), 'utf8');
const readRepoFile = path => readFileSync(new URL(`../../${path}`, import.meta.url), 'utf8');
const readWorkflow = name => readRepoFile(`.github/workflows/${name}`);
const workflow = readWorkflow('ci.yml');
const nightly = readWorkflow('nightly.yml');
const PINNED_IMAGE = /^\s+image: mcr\.microsoft\.com\/playwright:v\d+\.\d+\.\d+-noble@sha256:[0-9a-f]{64}$/m;
function jobs(text) {
@@ -62,21 +67,31 @@ function matrixList(jobText, key) {
}
const allJobs = jobs(workflow);
const browserJobIds = [...allJobs].filter(([, body]) => /npm run --prefix tools\/vendor test:(workflows|coverage)/.test(body))
.map(([id]) => id);
const nightlyJobs = jobs(nightly);
const BROWSER_TEST_STEP = /npm run --prefix tools\/vendor test:(workflows|coverage)/;
const browserJobs = [...allJobs, ...nightlyJobs].filter(([, body]) => BROWSER_TEST_STEP.test(body));
const mergeJob = () => allJobs.get('frontend-coverage-merge');
const verifyStep = () => steps(mergeJob()).find(step => /name: Verify every shard's raw coverage arrived/.test(step));
// #639: each workflow classifies the change first (tools/ci/change_class.py). Jobs that only a code
// change can affect skip for the classes "docs" and "inert", and run when the classifier failed.
const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const jobIf = condition => new RegExp(`^ {4}if: ${escapeRegExp(`\${{ ${condition} }}`)}$`, 'm');
const CODE_CLASS = "needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert'";
const CODE_ONLY_IF = jobIf(`!cancelled() && ${CODE_CLASS}`);
// Jobs that run only in the merge queue, on main and on demand (#420): skipped on pull_request.
const QUEUE_ONLY_IF = jobIf(`!cancelled() && github.event_name != 'pull_request' && ${CODE_CLASS}`);
const EVENTS = ['pull_request', 'merge_group', 'push', 'workflow_dispatch'];
const CLASSES = ['code', 'docs', 'inert'];
const triggersOf = text => {
const lines = text.split('\n');
const start = lines.indexOf('on:');
assert.notEqual(start, -1, 'workflow has an on: section');
const events = [];
for (const line of lines.slice(start + 1)) {
if (/^\S/.test(line)) break;
const event = /^ {2}([a-z_]+):/.exec(line);
if (event) events.push(event[1]);
}
return events.sort();
};
// The classes tools/ci/change_class.py prints, and the jobs each one asks for. Every other job must
// be skipped; a job that ran when its class did not ask for it is as wrong as one that failed.
const CODE_JOBS = ['python', 'lint', 'security', 'js-test', 'tooling', 'frontend-coverage', 'frontend-coverage-merge'];
const RELEASE_JOBS = ['package'];
const JOBS_OF_CLASS = { code: CODE_JOBS, release: RELEASE_JOBS, docs: [], inert: [] };
function gateVariables(jobText) {
return new Map([...jobText.matchAll(/^ {10}([A-Z_]+): \$\{\{ needs\.([\w-]+)\.result \}\}$/gm)]
@@ -93,62 +108,179 @@ function runGate(jobText, env) {
}
}
// A gate passes only when the classifier succeeded and every job did what the change class and the
// event ask (#639). For a code change: every always-on and code-only job succeeded, and every
// queue-only job is skipped on a pull request and succeeded on every other event. For a docs or
// inert change: every always-on job succeeded and every other job is skipped. Anything else fails
// it, and so does a class the classifier does not print.
function assertGateBehaviour(jobText, { queueOnly, codeOnly, always = [] }) {
assert.match(jobText, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m, 'the gate knows the event');
assert.match(jobText, /^ {10}CHANGE_CLASS: \$\{\{ needs\.changes\.outputs\.class \}\}$/m, 'the gate knows the change class');
const variables = gateVariables(jobText);
assert.deepEqual([...variables.keys()].sort(), ['changes', ...queueOnly, ...codeOnly, ...always].sort(),
'every job the gate reads has an expected result');
for (const changeClass of CLASSES) {
for (const event of EVENTS) {
const expected = id => {
if (id === 'changes' || always.includes(id)) return 'success';
if (changeClass !== 'code') return 'skipped';
return queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success';
};
const where = `${changeClass} change on ${event}`;
const green = { EVENT_NAME: event, CHANGE_CLASS: changeClass,
...Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])) };
assert.equal(runGate(jobText, green), true, `${where}: the expected results pass`);
for (const [id, name] of variables) {
for (const result of ['success', 'failure', 'cancelled', 'skipped']) {
if (result === expected(id)) continue;
assert.equal(runGate(jobText, { ...green, [name]: result }), false, `${where}: ${id}=${result} must fail the gate`);
}
}
for (const unknown of ['', 'other', 'code ']) {
assert.equal(runGate(jobText, { ...green, CHANGE_CLASS: unknown }), false, `${where}: class "${unknown}" must fail the gate`);
// ---- Triggers: one pass on the pull request, nothing on main but publish -------------------------
test('no workflow runs in a merge queue', () => {
const directory = fileURLToPath(new URL('../../.github/workflows/', import.meta.url));
const names = readdirSync(directory).filter(name => /\.ya?ml$/.test(name)).sort();
assert.deepEqual(names, ['ci.yml', 'nightly.yml', 'publish.yml', 'viewerjs-update.yml'],
'the old workflows are gone; a new workflow is added to this list and to the checks below');
for (const name of names) {
assert.doesNotMatch(readWorkflow(name), /merge_group/, `${name} has no merge_group trigger or condition`);
}
});
test('the gate runs on pull requests and on demand, never on a push', () => {
assert.deepEqual(triggersOf(workflow), ['pull_request', 'workflow_dispatch']);
assert.match(workflow, /^ {2}pull_request:\n {4}branches: \[main\]$/m);
assert.doesNotMatch(workflow, /^ {4}paths(-ignore)?:/m, 'no path filter may leave the required check pending');
assert.match(workflow, /^ {2}cancel-in-progress: \$\{\{ github\.event_name == 'pull_request' \}\}$/m);
});
test('nightly runs on its schedule and on demand, never on a pull request or a push', () => {
assert.deepEqual(triggersOf(nightly), ['schedule', 'workflow_dispatch']);
assert.doesNotMatch(nightly, /cancel-in-progress: true|cancel-in-progress: \$/, 'no nightly run is cancelled');
assert.doesNotMatch(nightly, /needs\.changes/, 'nightly tests main as it is: no change class');
});
test('a push to main starts only publish, and only when pyproject.toml changed', () => {
const publish = readWorkflow('publish.yml');
assert.deepEqual(triggersOf(publish), ['push', 'workflow_dispatch']);
assert.match(publish, /^ {4}paths:\n {6}- "pyproject\.toml"$/m);
for (const name of ['ci.yml', 'nightly.yml', 'viewerjs-update.yml']) {
assert.ok(!triggersOf(readWorkflow(name)).includes('push'), `${name} does not run on a push`);
}
});
// ---- The change class -----------------------------------------------------------------------------
test('the gate classifies the change first, from file names, and every other job waits for it', () => {
assert.equal([...allJobs.keys()][0], 'changes', 'the classifier is the first job');
const changes = allJobs.get('changes');
assert.match(changes, /^ {4}name: change class$/m);
assert.doesNotMatch(changes, /^ {4}(needs|if):/m, 'the classifier waits for nothing and always runs');
assert.match(changes, /^ {6}class: \$\{\{ steps\.classify\.outputs\.class \}\}$/m);
const [checkout, classify] = steps(changes);
assert.match(checkout, /uses: actions\/checkout@v\d+/);
assert.match(checkout, /^ {10}fetch-depth: 0$/m, 'the base commit must be in the clone');
assert.match(checkout, /^ {10}filter: blob:none$/m, 'file names need no file contents');
assert.match(checkout, /^ {10}persist-credentials: false$/m);
assert.match(classify, /^ {8}id: classify$/m);
assert.match(classify, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m);
assert.match(classify, /^ {10}BASE_SHA: \$\{\{ github\.event\.pull_request\.base\.sha \}\}$/m);
assert.match(classify, /^ {10}HEAD_SHA: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.sha \}\}$/m);
assert.match(classify, /^ {8}run: python3 tools\/ci\/change_class\.py \| tee -a "\$GITHUB_OUTPUT"$/m);
for (const [id, body] of allJobs) {
if (id !== 'changes') assert.ok(needsOf(body).includes('changes'), `job ${id} waits for the classifier`);
}
});
test('each job runs for exactly one change class', () => {
assert.deepEqual([...allJobs.keys()].sort(), ['changes', 'gate', ...CODE_JOBS, ...RELEASE_JOBS].sort());
// No status function in the condition, so the implicit success() also holds: a job never runs
// after a failed classifier, and the merge never runs after a failed shard.
for (const id of CODE_JOBS) assert.match(allJobs.get(id), jobIf("needs.changes.outputs.class == 'code'"), id);
for (const id of RELEASE_JOBS) assert.match(allJobs.get(id), jobIf("needs.changes.outputs.class == 'release'"), id);
const classes = [...readRepoFile('tools/ci/change_class.py').matchAll(/return "([a-z]+)"|found = "([a-z]+)"/g)]
.map(match => match[1] ?? match[2]);
assert.deepEqual([...new Set(classes)].sort(), Object.keys(JOBS_OF_CLASS).sort(), 'the gate knows every class the script prints');
});
test('a release runs the package-content check and nothing else', () => {
const body = allJobs.get('package');
assert.match(body, /^ {6}- run: python -m unittest -v tests\.test_package_contents$/m);
assert.doesNotMatch(body, /pip install/, 'the check needs nothing installed');
});
// ---- The gate ---------------------------------------------------------------------------------------
test('gate is the one required context and needs every other job', () => {
const gate = allJobs.get('gate');
assert.ok(gate, 'the required context is the job id gate');
assert.doesNotMatch(gate, /^ {4}name:/m, 'no display name may replace the context "gate"');
assert.equal([...allJobs.keys()].at(-1), 'gate');
const others = [...allJobs.keys()].filter(id => id !== 'gate');
assert.deepEqual([...needsOf(gate)].sort(), [...others].sort(), 'gate needs every other job in the workflow');
assert.match(gate, /^ {4}if: always\(\)$/m, 'gate runs (and fails) when a needed job failed or was skipped');
assert.deepEqual([...gateVariables(gate).keys()].sort(), [...others].sort(), 'every needed result reaches the gate');
assert.match(gate, /^ {10}CHANGE_CLASS: \$\{\{ needs\.changes\.outputs\.class \}\}$/m, 'the gate knows the change class');
assert.doesNotMatch(gate, /github\.event_name|EVENT_NAME/, 'the gate asks the same of every event');
});
// The gate passes only when the classifier succeeded and every job did what the class asks: the
// class's jobs succeeded and every other job was skipped. Any other result of any job fails it, and
// so does a failed classifier or a class the script does not print.
test('gate passes only when every job did what the change class asks', () => {
const gate = allJobs.get('gate');
const variables = gateVariables(gate);
for (const [changeClass, running] of Object.entries(JOBS_OF_CLASS)) {
const expected = id => (id === 'changes' || running.includes(id) ? 'success' : 'skipped');
const green = { CHANGE_CLASS: changeClass, ...Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])) };
assert.equal(runGate(gate, green), true, `${changeClass}: the expected results pass`);
for (const [id, name] of variables) {
for (const result of ['success', 'failure', 'cancelled', 'skipped', '']) {
if (result === expected(id)) continue;
assert.equal(runGate(gate, { ...green, [name]: result }), false, `${changeClass}: ${id}=${result || 'nothing'} must fail the gate`);
}
}
for (const unknown of ['', 'other', `${changeClass} `, 'tests-only']) {
assert.equal(runGate(gate, { ...green, CHANGE_CLASS: unknown }), false, `${changeClass}: class "${unknown}" must fail the gate`);
}
}
}
test('viewerjs keeps its name and needs every frontend job', () => {
const viewerjs = allJobs.get('viewerjs');
assert.ok(viewerjs, 'the required context is the job id viewerjs');
assert.doesNotMatch(viewerjs, /^ {4}name:/m, 'no display name may replace the context "viewerjs"');
const needs = needsOf(viewerjs);
const others = [...allJobs.keys()].filter(id => id !== 'viewerjs');
assert.deepEqual([...needs].sort(), [...others].sort(), 'viewerjs needs every other job in the workflow');
assert.deepEqual([...needs].sort(), ['browser-workflows', 'changes', 'frontend-coverage', 'frontend-coverage-merge']);
assert.match(viewerjs, /^ {4}if: always\(\)$/m, 'viewerjs runs (and fails) when a needed job failed or was skipped');
assert.deepEqual([...gateVariables(viewerjs).keys()].sort(), [...needs].sort(), 'every needed result reaches the check');
});
test('viewerjs requires the browser shards everywhere but on a pull request, and nothing for a docs or inert change', () => {
assertGateBehaviour(allJobs.get('viewerjs'), { queueOnly: ['browser-workflows'], codeOnly: ['frontend-coverage', 'frontend-coverage-merge'] });
test('branch protection requires only gate, on a branch that is up to date', () => {
const protection = JSON.parse(readRepoFile('.github/branch-protection.json'));
assert.deepEqual(protection.required_status_checks, { strict: true, contexts: ['gate'] });
assert.equal(protection.enforce_admins, true);
assert.equal(protection.allow_force_pushes, false);
});
test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event; both for code changes only', () => {
assert.match(allJobs.get('browser-workflows'), QUEUE_ONLY_IF);
assert.match(allJobs.get('frontend-coverage'), CODE_ONLY_IF);
// !cancelled() replaces the implicit success() check, so the merge names the shards' success itself.
assert.match(allJobs.get('frontend-coverage-merge'), jobIf(`!cancelled() && needs.frontend-coverage.result == 'success' && ${CODE_CLASS}`));
// ---- The gate's jobs ------------------------------------------------------------------------------
test('the Python suite runs once, under coverage, through the watchdog runner', () => {
const body = allJobs.get('python');
const suiteRuns = body.match(/tests\.run_suite/g) ?? [];
assert.equal(suiteRuns.length, 1, 'one run proves both the tests and the coverage floor');
assert.match(body, /^ {8}run: python -m coverage run -m tests\.run_suite -v$/m);
assert.match(body, /^ {10}python -m coverage combine$/m);
assert.match(body, /^ {10}python -m coverage report --fail-under=85$/m);
assert.doesNotMatch(body, /unittest discover/);
assert.match(body, /^ {10}python-version: "3\.12"$/m);
assert.doesNotMatch(body, /matrix/, 'other Pythons run nightly');
});
// CI hygiene (#352): lint tools are pinned, the bandit hook can fail, the JS job caches npm.
test('black and flake8 are pinned exactly and the lint job installs those pins', () => {
const requirements = readRepoFile('requirements-dev.txt');
assert.match(requirements, /^black==\d+\.\d+\.\d+$/m, 'black is pinned exactly');
assert.match(requirements, /^flake8==\d+\.\d+\.\d+$/m, 'flake8 is pinned exactly');
const lint = allJobs.get('lint');
assert.match(lint, /pip install \$\(grep -E '\^\(black\|flake8\)==' requirements-dev\.txt\)/);
assert.doesNotMatch(lint, /pip install black flake8/, 'lint no longer installs the latest releases');
});
test('the frontend modules job caches npm keyed on the vendor lockfile', () => {
const setupNode = steps(allJobs.get('js-test')).find(step => /uses: actions\/setup-node@v\d+/.test(step));
assert.match(setupNode, /^ {10}cache: npm$/m);
assert.match(setupNode, /^ {10}cache-dependency-path: tools\/vendor\/package-lock\.json$/m);
assert.match(allJobs.get('js-test'), /^ {8}run: node --test tests\/js\/\*\.test\.js$/m);
});
test('the bandit pre-commit hook fails at the severity CI enforces and passes every file', () => {
assert.match(allJobs.get('security'), /^ {8}run: bandit -r \. -lll -q --exclude /m, 'CI fails on high severity');
const hook = /- id: bandit\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
assert.ok(hook, 'the bandit hook exists');
assert.match(hook, /^ {8}entry: bandit -lll -q$/m, 'the hook enforces the same -lll level as CI');
assert.doesNotMatch(hook, /true|exit-zero|bash -c/, 'nothing masks the exit code or drops a file');
assert.doesNotMatch(hook, /pass_filenames: false/, 'the hook scans the staged files');
});
test('the pre-push hook runs the suite through the classifier', () => {
const hook = /- id: tests\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
assert.ok(hook, 'the tests hook exists');
assert.match(hook, /^ {8}entry: python tools\/ci\/change_class\.py --unless-inert python -m tests\.run_suite -q$/m);
assert.match(hook, /^ {8}stages: \[pre-push\]$/m);
});
test('the tooling job checks the pins and runs the tooling tests', () => {
const body = allJobs.get('tooling');
const commands = [...body.matchAll(/^ {6}- run: npm run --prefix tools\/vendor (\w+)$/gm)].map(match => match[1]);
assert.deepEqual(commands, ['check', 'test']);
assert.match(body, PINNED_IMAGE, 'the tooling tests see the image the browser jobs use');
for (const id of ['frontend-coverage', 'frontend-coverage-merge']) {
assert.doesNotMatch(allJobs.get(id), /tools\/vendor (check|test)$/m, `${id} runs no tooling step`);
}
});
test('coverage runs as four shards that each upload their raw coverage', () => {
@@ -156,6 +288,7 @@ test('coverage runs as four shards that each upload their raw coverage', () => {
assert.deepEqual(matrixList(coverage, 'shard'), ['1', '2', '3', '4']);
assert.match(coverage, /^ {4}name: frontend coverage \(shard \$\{\{ matrix\.shard \}\}\/4\)$/m);
assert.match(coverage, /npm run --prefix tools\/vendor test:coverage:shard -- \$\{\{ matrix\.shard \}\}\/4/);
assert.match(coverage, /^ {6}fail-fast: false$/m);
const upload = steps(coverage).find(step => /name: coverage-raw-\$\{\{ matrix\.shard \}\}/.test(step));
assert.ok(upload, 'each shard uploads coverage-raw-N');
assert.match(upload, /^ {10}path: coverage\/js\/raw\/?$/m);
@@ -222,40 +355,37 @@ test('merge refuses when a shard\'s raw coverage is missing', async t => {
assert.deepEqual(complete, { ok: true, raw: ['a.json', 'b.json', 'c.json', 'node.json'] });
});
// ---- Browser jobs, in the gate and nightly --------------------------------------------------------
test('every browser job sets PM_TEST_WORKERS and runs in the pinned image', () => {
assert.deepEqual([...browserJobIds].sort(), ['browser-workflows', 'frontend-coverage']);
for (const id of browserJobIds) {
const body = allJobs.get(id);
assert.deepEqual(browserJobs.map(([id]) => id).sort(), ['browser-workflows', 'frontend-coverage']);
for (const [id, body] of browserJobs) {
assert.match(body, /^ {6}PM_TEST_WORKERS: 3$/m, `${id} sets PM_TEST_WORKERS for the whole job`);
assert.match(body, PINNED_IMAGE, `${id} keeps the pinned Playwright image`);
assert.match(body, /PIP_SHA256: [0-9a-f]{64}/, `${id} keeps the pinned pip bootstrap`);
assert.match(body, /^ {4}timeout-minutes: \d+$/m);
}
assert.match(mergeJob(), PINNED_IMAGE, 'the merge sees the same workspace paths as the shards');
});
// #473: two shards split by test count put the slow concept specs in shard 1, which reached the 18-minute step limit.
test('page workflows run each browser in three shards', () => {
const workflows = allJobs.get('browser-workflows');
assert.deepEqual(matrixList(workflows, 'browser'), ['firefox', 'webkit']);
// #473: two shards split by test count put the slow concept specs in shard 1, which reached its step limit.
test('nightly page workflows run Firefox, WebKit and touch in three shards each', () => {
const workflows = nightlyJobs.get('browser-workflows');
assert.deepEqual(matrixList(workflows, 'browser'), ['firefox', 'webkit', 'touch']);
assert.deepEqual(matrixList(workflows, 'shard'), ['1', '2', '3']);
assert.match(workflows, /test:workflows -- --project \$\{\{ matrix\.browser \}\} --shard \$\{\{ matrix\.shard \}\}\/3/);
assert.match(workflows, /test:workflows -- --project \$\{\{ matrix\.browser \}\} --shard \$\{\{ matrix\.shard \}\}\/3 /);
assert.match(workflows, /^ {4}name: page workflows \(\$\{\{ matrix\.browser \}\}, shard \$\{\{ matrix\.shard \}\}\/3\)$/m);
assert.match(workflows, /name: Page workflows in \$\{\{ matrix\.browser \}\}, shard \$\{\{ matrix\.shard \}\}\/3$/m);
assert.doesNotMatch(workflows, /\/2\b/, 'no step still names two shards');
assert.match(workflows, /^ {6}fail-fast: false$/m);
assert.match(workflows, /name: browser-traces-\$\{\{ matrix\.browser \}\}-shard-\$\{\{ matrix\.shard \}\}/);
});
test('every npm ci restores the npm download cache keyed on the vendor lockfile first', () => {
const installing = [...allJobs].filter(([, body]) => /npm ci --prefix tools\/vendor/.test(body));
assert.deepEqual(installing.map(([id]) => id).sort(), ['browser-workflows', 'frontend-coverage', 'frontend-coverage-merge']);
test('every npm ci in a container restores the npm download cache keyed on the vendor lockfile first', () => {
const installing = [...allJobs, ...nightlyJobs].filter(([, body]) => /npm ci --prefix tools\/vendor/.test(body) && /^ {4}container:$/m.test(body));
assert.deepEqual(installing.map(([id]) => id).sort(), ['browser-workflows', 'comfyui', 'frontend-coverage', 'frontend-coverage-merge', 'tooling']);
for (const [id, body] of installing) {
const jobSteps = steps(body);
const cacheAt = jobSteps.findIndex(step => /uses: actions\/cache@v\d+/.test(step));
const cacheAt = jobSteps.findIndex(step => /uses: actions\/cache@v\d+/.test(step) && /path: ~\/\.npm$/m.test(step));
const installAt = jobSteps.findIndex(step => /npm ci --prefix tools\/vendor/.test(step));
assert.ok(cacheAt >= 0 && cacheAt < installAt, `${id} restores the npm cache before npm ci`);
assert.match(jobSteps[cacheAt], /^ {10}path: ~\/\.npm$/m, `${id} caches npm's download cache, not node_modules`);
assert.match(jobSteps[cacheAt], /hashFiles\('tools\/vendor\/package-lock\.json'\)/, `${id} keys the cache on the lockfile`);
assert.match(jobSteps[installAt], /npm ci --prefix tools\/vendor --ignore-scripts/, `${id} still installs without scripts`);
// The key names the job's own pinned image, so an image bump starts a fresh cache.
@@ -266,226 +396,110 @@ test('every npm ci restores the npm download cache keyed on the vendor lockfile
}
});
test('browser job timeouts keep a real margin over measured runs', () => {
for (const id of ['frontend-coverage', 'browser-workflows']) {
const minutes = Number(/^ {4}timeout-minutes: (\d+)$/m.exec(allJobs.get(id))[1]);
assert.ok(minutes >= 20, `${id} allows at least 20 minutes, since runner speed varies`);
}
});
// A hang (#425) must end inside the test step, before the job limit, so the log and the always()
// uploads survive: the step's timeout-minutes < the job's.
const BROWSER_TEST_STEP = /npm run --prefix tools\/vendor test:(workflows|coverage)/;
test('each browser test step stops itself before its job limit and its traces upload anyway', () => {
for (const id of browserJobIds) {
const body = allJobs.get(id);
for (const [id, body] of browserJobs) {
const jobMinutes = Number(/^ {4}timeout-minutes: (\d+)$/m.exec(body)[1]);
const jobSteps = steps(body);
const testAt = jobSteps.findIndex(step => BROWSER_TEST_STEP.test(step));
const testStep = jobSteps[testAt];
const stepMinutes = Number(/^ {8}timeout-minutes: (\d+)$/m.exec(testStep)?.[1]);
assert.ok(stepMinutes > 0, `${id}: the test step sets its own timeout-minutes`);
assert.ok(jobMinutes - stepMinutes >= 2, `${id}: the step limit leaves time for setup and the uploads`);
assert.equal(jobMinutes - stepMinutes, 2, `${id}: the step limit leaves 2 minutes for setup and the uploads`);
const upload = jobSteps.slice(testAt + 1).find(step => /^ {10}path: tools\/vendor\/test-results\/$/m.test(step));
assert.ok(upload, `${id} uploads tools/vendor/test-results/ (traces and blob report) after the tests`);
assert.match(upload, /^ {8}if: always\(\)$/m, `${id} uploads them when the step failed or timed out`);
}
});
// Every job is bounded (#350): a hang ends at a measured limit instead of GitHub's 6-hour default.
const GATING_WORKFLOWS = ['test.yml', 'code-quality.yml', 'viewerjs-check.yml'];
const BOUNDED_WORKFLOWS = [...GATING_WORKFLOWS, 'portability.yml'];
const readWorkflow = name => readFileSync(new URL(`../../.github/workflows/${name}`, import.meta.url), 'utf8');
// ---- Nightly ----------------------------------------------------------------------------------------
test('every job in the CI workflows has a numeric timeout-minutes', () => {
test('nightly runs what the gate leaves out: other Pythons, Windows, a real mount, real ComfyUI, the budget', () => {
assert.deepEqual([...nightlyJobs.keys()].sort(),
['browser-workflows', 'comfyui', 'native-trash-linux', 'perf-budget', 'python-linux', 'python-windows', 'report']);
const linux = nightlyJobs.get('python-linux');
assert.deepEqual(matrixList(linux, 'python-version'), ['"3.13"', '"3.14"'], '3.12 is the gate');
assert.match(linux, /^ {4}runs-on: ubuntu-latest$/m);
const windows = nightlyJobs.get('python-windows');
assert.deepEqual(matrixList(windows, 'python-version'), ['"3.12"', '"3.13"', '"3.14"']);
assert.match(windows, /^ {4}runs-on: windows-latest$/m);
for (const body of [linux, windows]) {
assert.match(body, /^ {6}fail-fast: false$/m);
assert.match(body, /^ {8}run: python -m tests\.run_suite -v$/m);
}
assert.doesNotMatch(nightly, /macos-/, 'macOS is not tested in CI (#571)');
assert.match(nightlyJobs.get('native-trash-linux'), /PM_TRASH_MOUNT="\$RUNNER_TEMP\/drive" python -m unittest tests\.test_trash_mount_root -v$/m);
assert.match(nightlyJobs.get('perf-budget'), /^ {10}PROMPTMANAGER_PERF_BUDGET: "1"$/m);
const commands = [...nightlyJobs.get('comfyui').matchAll(/^ {8}run: npm run --prefix tools\/vendor (test:[a-z]+)$/gm)].map(match => match[1]);
assert.deepEqual(commands, ['test:comfyui', 'test:executions', 'test:compat']);
});
test('nightly reports by issue after every other job, with the only write permission in CI', () => {
const report = nightlyJobs.get('report');
const others = [...nightlyJobs.keys()].filter(id => id !== 'report');
assert.deepEqual([...needsOf(report)].sort(), others.sort(), 'the report waits for every other job');
assert.match(report, jobIf("always() && github.ref == 'refs/heads/main'"), 'a failed job is reported; a branch run files nothing');
assert.match(report, /^ {4}permissions:\n {6}actions: read\n {6}contents: read\n {6}issues: write$/m);
assert.match(report, /^ {10}GH_TOKEN: \$\{\{ github\.token \}\}$/m);
assert.match(report, /^ {8}run: python3 tools\/ci\/nightly_report\.py$/m);
assert.match(nightly, /^permissions:\n {2}contents: read$/m, 'every other job only reads');
assert.match(workflow, /^permissions:\n {2}contents: read$/m, 'the gate only reads');
assert.doesNotMatch(workflow, /: write$/m);
for (const [id, body] of nightlyJobs) {
if (id !== 'report') assert.doesNotMatch(body, /^ {4}(needs|if):/m, `${id} always runs`);
}
});
// ---- Time limits ------------------------------------------------------------------------------------
// Every job is bounded (#350): a hang ends at a measured limit instead of GitHub's 6-hour default.
// The rule (#493): ceil(1.5 x the slowest of three green runs) + 3 minutes, never under 5, with the
// runs and times written above jobs: as "<job id>: 7m26s / 7m22s / 7m54s -> 15 min". A job without
// three green runs yet has "estimate <job id>: <why> -> N min" instead. That the runs were green is
// the author's word; that every job has one line and uses its limit is checked here.
const BOUNDED_WORKFLOWS = ['ci.yml', 'nightly.yml', 'publish.yml'];
const limitOf = seconds => Math.max(5, Math.ceil(1.5 * Math.max(...seconds) / 60) + 3);
function writtenLimits(name) {
const text = readWorkflow(name);
const comment = text.slice(0, text.indexOf('\njobs:'));
const runs = [...comment.matchAll(/^# Measured \d{4}-\d{2}-\d{2} on runs (\d+) \([0-9a-f]{7}\), (\d+) \([0-9a-f]{7}\), (\d+) \([0-9a-f]{7}\):$/gm)];
assert.ok(runs.length > 0, `${name} names the runs it measured`);
for (const run of runs) assert.equal(new Set(run.slice(1)).size, 3, `${name}: three different runs`);
const limits = new Map();
const time = '(\\d+)m([0-5]\\d)s';
for (const match of comment.matchAll(new RegExp(`^# ([\\w-]+): ${time} / ${time} / ${time} -> (\\d+) min$`, 'gm'))) {
const seconds = [2, 4, 6].map(i => Number(match[i]) * 60 + Number(match[i + 1]));
assert.equal(Number(match[8]), limitOf(seconds), `${name} ${match[1]}: the written limit follows the rule`);
assert.ok(!limits.has(match[1]), `${name} ${match[1]}: one measurement, no older one beside it`);
limits.set(match[1], Number(match[8]));
}
for (const match of comment.matchAll(/^# estimate ([\w-]+): [^\n]*(?:\n# [^\n]*)*? -> (\d+) min$/gm)) {
assert.ok(!limits.has(match[1]), `${name} ${match[1]}: a measurement or an estimate, not both`);
assert.ok(Number(match[2]) >= 5, `${name} ${match[1]}: never under 5 minutes`);
limits.set(match[1], Number(match[2]));
}
assert.equal(comment.match(/-> \d+ min/g).length, limits.size, `${name}: every "-> N min" is a job's line`);
return limits;
}
test('every CI job uses the time limit written for it above jobs:', () => {
for (const name of BOUNDED_WORKFLOWS) {
const found = jobs(readWorkflow(name));
assert.ok(found.size > 0, `${name} has jobs`);
const limits = writtenLimits(name);
assert.deepEqual([...limits.keys()].sort(), [...found.keys()].sort(), `${name}: one limit line per job`);
for (const [id, body] of found) {
const limit = /^ {4}timeout-minutes: (\d+)\s*$/m.exec(body);
assert.ok(limit, `${name} job ${id} sets a numeric timeout-minutes`);
assert.ok(Number(limit[1]) >= 5, `${name} job ${id} allows at least 5 minutes`);
assert.equal(Number(limit[1]), limits.get(id), `${name} job ${id} uses its written limit`);
}
}
});
test('the Python matrix and coverage run the suite through the watchdog runner', () => {
const found = jobs(readWorkflow('test.yml'));
assert.match(found.get('test'), /^ {8}run: python -m tests\.run_suite -v$/m);
assert.match(found.get('coverage'), /^ {10}python -m coverage run -m tests\.run_suite$/m);
for (const id of ['test', 'coverage']) {
assert.doesNotMatch(found.get(id), /unittest discover/, `${id} no longer runs the bare unittest discover`);
}
});
// CI hygiene (#352): lint tools are pinned, the bandit hook can fail, the JS job caches npm.
const readRepoFile = path => readFileSync(new URL(`../../${path}`, import.meta.url), 'utf8');
test('black and flake8 are pinned exactly and the lint job installs those pins', () => {
const requirements = readRepoFile('requirements-dev.txt');
assert.match(requirements, /^black==\d+\.\d+\.\d+$/m, 'black is pinned exactly');
assert.match(requirements, /^flake8==\d+\.\d+\.\d+$/m, 'flake8 is pinned exactly');
const lint = jobs(readWorkflow('test.yml')).get('lint');
assert.match(lint, /pip install \$\(grep -E '\^\(black\|flake8\)==' requirements-dev\.txt\)/);
assert.doesNotMatch(lint, /pip install black flake8/, 'lint no longer installs the latest releases');
});
test('the frontend modules job caches npm keyed on the vendor lockfile', () => {
const setupNode = steps(jobs(readWorkflow('test.yml')).get('js-test'))
.find(step => /uses: actions\/setup-node@v\d+/.test(step));
assert.match(setupNode, /^ {10}cache: npm$/m);
assert.match(setupNode, /^ {10}cache-dependency-path: tools\/vendor\/package-lock\.json$/m);
});
test('the bandit pre-commit hook fails at the severity CI enforces and passes every file', () => {
const quality = readWorkflow('code-quality.yml');
assert.match(quality, /^ {8}run: bandit -r \. -lll -q --exclude /m, 'CI fails on high severity');
const hook = /- id: bandit\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
assert.ok(hook, 'the bandit hook exists');
assert.match(hook, /^ {8}entry: bandit -lll -q$/m, 'the hook enforces the same -lll level as CI');
assert.doesNotMatch(hook, /true|exit-zero|bash -c/, 'nothing masks the exit code or drops a file');
assert.doesNotMatch(hook, /pass_filenames: false/, 'the hook scans the staged files');
});
// Event split (#420): pull requests run a fast subset, the merge queue and main run everything.
const testJobs = () => jobs(readWorkflow('test.yml'));
test('the Python matrix is Linux 3.12 on a pull request or a docs or inert change and Linux 3.12-3.14 otherwise', () => {
const body = testJobs().get('test');
assert.deepEqual(matrixList(body, 'os'), ['ubuntu-latest'], 'Windows never gates a merge');
const match = /^ {8}python-version: \$\{\{ \(github\.event_name == 'pull_request' \|\| needs\.changes\.outputs\.class == 'docs' \|\| needs\.changes\.outputs\.class == 'inert'\) && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body);
assert.ok(match, 'python-version is chosen by event and change class');
assert.deepEqual({ small: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { small: ['3.12'], other: ['3.12', '3.13', '3.14'] });
assert.match(body, /^ {6}fail-fast: false$/m);
assert.match(body, /^ {4}name: py\$\{\{ matrix\.python-version \}\} on \$\{\{ matrix\.os \}\}$/m);
});
// #639: a skipped matrix job reports under its unexpanded name, so the required context
// "py3.12 on ubuntu-latest" would never report. The job therefore always starts, and an inert change
// skips its steps instead.
test('the Python matrix always starts and skips its steps for an inert change', () => {
const body = testJobs().get('test');
assert.deepEqual(needsOf(body), ['changes']);
assert.match(body, jobIf('!cancelled()'), 'it also runs, in full, when the classifier failed');
const jobSteps = steps(body);
const nothing = jobSteps.filter(step => /^ {8}if: needs\.changes\.outputs\.class == 'inert'$/m.test(step));
assert.equal(nothing.length, 1, 'one step says nothing needs testing');
assert.match(nothing[0], /^ {8}run: echo /m, 'and it only prints that');
for (const step of jobSteps.filter(step => step !== nothing[0])) {
assert.match(step, /^ {8}if: needs\.changes\.outputs\.class != 'inert'$/m, `every real step is skipped for an inert change: ${step.trim().split('\n')[0]}`);
}
assert.equal(jobSteps.length, 5);
});
test('Windows runs 3.12-3.14 on main, nightly and on demand, never on a PR or in the queue', () => {
const text = readWorkflow('portability.yml');
const triggers = text.slice(text.indexOf('\non:'), text.indexOf('\nconcurrency:'));
for (const event of ['push', 'schedule', 'workflow_dispatch']) assert.match(triggers, new RegExp(`^ {2}${event}:`, 'm'));
for (const event of ['pull_request', 'merge_group']) assert.doesNotMatch(triggers, new RegExp(`^ {2}${event}`, 'm'));
assert.match(triggers, /^ {4}branches: \[main\]$/m, 'push runs only for main');
const body = jobs(text).get('test');
assert.deepEqual(matrixList(body, 'os'), ['windows-latest'], 'macOS is not tested in CI (#571)');
assert.doesNotMatch(text, /macos-/, 'no macOS runner is used');
assert.deepEqual(matrixList(body, 'python-version'), ['"3.12"', '"3.13"', '"3.14"']);
assert.match(body, /^ {6}fail-fast: false$/m);
assert.match(body, /^ {8}run: python -m tests\.run_suite -v$/m);
assert.doesNotMatch(text, /cancel-in-progress: true|cancel-in-progress: \$/, 'no portability run is cancelled');
});
// #493: the portability limit follows the rule in its comment: ceil(1.5 x the slowest of three
// green main runs) + 3 minutes, never under 5, with those runs and times written above jobs:.
// The times are whole-job wall times. That the runs were green and on main is the author's word.
test('the portability limit is computed from three measured green main runs', () => {
const text = readWorkflow('portability.yml');
const comment = text.slice(0, text.indexOf('\njobs:'));
const runs = [...comment.matchAll(/^# Measured \d{4}-\d{2}-\d{2} on main runs (\d+) \([0-9a-f]{7}\), (\d+) \([0-9a-f]{7}\), (\d+) \([0-9a-f]{7}\):$/gm)];
assert.equal(runs.length, 1, 'the comment names the three runs it measured, once');
assert.equal(new Set(runs[0].slice(1)).size, 3, 'three different runs');
const time = '(\\d+)m([0-5]\\d)s \\(([^)]+)\\)';
const slowest = new RegExp(`^#\\s+slowest leg: ${time} / ${time} / ${time} -> (\\d+) min$`, 'm').exec(comment);
assert.ok(slowest, 'the comment gives the slowest leg of each run and the limit');
const seconds = [1, 4, 7].map(i => Number(slowest[i]) * 60 + Number(slowest[i + 1]));
const expected = Math.max(5, Math.ceil(1.5 * Math.max(...seconds) / 60) + 3);
assert.equal(Number(slowest[10]), expected, 'the written limit follows the rule');
assert.equal(comment.match(/-> \d+ min/g).length, 1, 'no older measurement stays beside it');
const limit = Number(/^ {4}timeout-minutes: (\d+)\s*$/m.exec(jobs(text).get('test'))[1]);
assert.equal(limit, expected, 'the job uses the written limit');
});
test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event; all for code changes only', () => {
const found = testJobs();
assert.match(found.get('comfyui'), QUEUE_ONLY_IF);
for (const id of ['coverage', 'lint', 'js-test']) {
assert.match(found.get(id), CODE_ONLY_IF, `${id} runs on every event for a code change`);
}
assert.match(found.get('perf-budget'),
jobIf(`!cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && ${CODE_CLASS}`));
});
test('all tests needs every gating test.yml job and requires the full set outside pull requests', () => {
const found = testJobs();
const gate = found.get('all-tests');
assert.ok(gate, 'the aggregate gate exists');
assert.match(gate, /^ {4}name: all tests$/m, 'the required context is "all tests"');
assert.match(gate, /^ {4}if: always\(\)$/m);
const gating = [...found.keys()].filter(id => !['all-tests', 'perf-budget'].includes(id));
assert.deepEqual([...needsOf(gate)].sort(), gating.sort(), 'the gate needs every job but the non-gating perf budget');
assert.deepEqual([...gateVariables(gate).keys()].sort(), gating.sort(), 'every needed result reaches the gate');
assertGateBehaviour(gate, { queueOnly: ['comfyui'], codeOnly: ['coverage', 'lint', 'js-test'], always: ['test'] });
});
test('the CI workflows run on pull_request, merge_group and push without path filters', () => {
for (const name of GATING_WORKFLOWS) {
const text = readWorkflow(name);
const triggers = text.slice(text.indexOf('\non:'), text.indexOf('\n', text.indexOf('\non:') + 1) + 400);
for (const event of ['merge_group', 'pull_request', 'push']) {
assert.match(triggers, new RegExp(`^ {2}${event}:`, 'm'), `${name} runs on ${event}`);
}
assert.doesNotMatch(text, /^ {4}paths(-ignore)?:/m, `${name} has no path filter that would leave a required check pending`);
}
assert.match(jobs(readWorkflow('code-quality.yml')).get('security'), CODE_ONLY_IF, 'bandit runs on every event for a code change');
});
// #639: the change is classified once per workflow, before anything else, from file names alone.
test('each gating workflow classifies the change first and every other job waits for it', () => {
for (const name of GATING_WORKFLOWS) {
const found = jobs(readWorkflow(name));
assert.equal([...found.keys()][0], 'changes', `${name} starts with the classifier`);
const changes = found.get('changes');
assert.match(changes, /^ {4}name: change class$/m);
assert.doesNotMatch(changes, /^ {4}(needs|if):/m, `${name}: the classifier waits for nothing and always runs`);
assert.match(changes, /^ {6}class: \$\{\{ steps\.classify\.outputs\.class \}\}$/m);
const [checkout, classify] = steps(changes);
assert.match(checkout, /uses: actions\/checkout@v\d+/);
assert.match(checkout, /^ {10}fetch-depth: 0$/m, 'the base commit must be in the clone');
assert.match(checkout, /^ {10}filter: blob:none$/m, 'file names need no file contents');
assert.match(checkout, /^ {10}persist-credentials: false$/m);
assert.match(classify, /^ {8}id: classify$/m);
assert.match(classify, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m);
assert.match(classify, /^ {10}BASE_SHA: \$\{\{ github\.event\.pull_request\.base\.sha \|\| github\.event\.merge_group\.base_sha \|\| github\.event\.before \}\}$/m);
assert.match(classify, /^ {10}HEAD_SHA: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.event\.merge_group\.head_sha \|\| github\.sha \}\}$/m);
assert.match(classify, /^ {8}run: python3 tools\/ci\/change_class\.py \| tee -a "\$GITHUB_OUTPUT"$/m);
for (const [id, body] of found) {
if (id !== 'changes') assert.ok(needsOf(body).includes('changes'), `${name} job ${id} waits for the classifier`);
}
}
});
test('the pre-push hook runs the suite through the classifier', () => {
const hook = /- id: tests\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1];
assert.ok(hook, 'the tests hook exists');
assert.match(hook, /^ {8}entry: python tools\/ci\/change_class\.py --unless-inert python -m tests\.run_suite -q$/m);
assert.match(hook, /^ {8}stages: \[pre-push\]$/m);
});
test('every required check reports on a pull request and the gates carry the full matrix', () => {
const contexts = JSON.parse(readRepoFile('.github/branch-protection.json')).required_status_checks.contexts;
assert.deepEqual([...contexts].sort(), [
'all tests', 'bandit (high severity)', 'black and flake8', 'coverage gate (85%)', 'frontend modules',
'py3.12 on ubuntu-latest', 'real ComfyUI compatibility', 'viewerjs',
].sort());
assert.equal(contexts.filter(context => /^py/.test(context)).length, 1,
'a dropped matrix leg never reports on a pull request, so it cannot be required');
assert.ok(!contexts.some(context => /windows|macos/.test(context)), 'Windows never gates a merge');
test('the limit rule: 1.5 x the slowest run, rounded up, plus 3, never under 5', () => {
assert.equal(limitOf([440, 456, 478]), 15);
assert.equal(limitOf([20, 22, 24]), 5);
assert.equal(limitOf([1221, 1239, 1266]), 35);
});
+1 -1
View File
@@ -59,7 +59,7 @@ test('execution config refuses live-host URLs and binds a managed loopback port'
});
test('CI retains stock, execution and pack suites in order with uploaded execution reports', () => {
const workflow = readFileSync(new URL('../../.github/workflows/test.yml', import.meta.url), 'utf8');
const workflow = readFileSync(new URL('../../.github/workflows/nightly.yml', import.meta.url), 'utf8');
const commands = [...workflow.matchAll(/^ run: npm run --prefix tools\/vendor (test:[a-z]+)$/gm)].map(match => match[1]);
assert.deepEqual(commands, ['test:comfyui', 'test:executions', 'test:compat']);
assert.match(workflow, /path: tools\/vendor\/test-results\//);
+77
View File
@@ -0,0 +1,77 @@
// The flake policy (#666, TESTING.md "Flaky tests and quarantine"): the gate never retries and skips
// tests tagged @quarantine; the nightly run retries once, runs the quarantined tests and lists what
// was flaky in the job summary.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import FlakyTestsReporter from '../../tools/vendor/flaky-tests-reporter.mjs';
import { GATE_PROJECTS, QUARANTINE_TAG } from '../../tools/vendor/frontend-coverage.mjs';
import viewerConfig from '../../tools/vendor/playwright.config.mjs';
import workflowConfig from '../../tools/vendor/playwright.workflows.config.mjs';
const root = fileURLToPath(new URL('../../', import.meta.url));
const read = path => readFileSync(join(root, path), 'utf8');
test('the gate runs desktop Chromium only and no gate config retries', () => {
assert.deepEqual(GATE_PROJECTS, ['chromium']);
assert.equal(QUARANTINE_TAG, '@quarantine');
assert.equal(workflowConfig.retries, 0, 'a retry hides a race');
assert.equal(viewerConfig.retries, 0, 'the viewer suite runs in the gate too');
assert.doesNotMatch(read('.github/workflows/ci.yml'), /--retries/, 'no gate step turns retries on');
});
test('the nightly page workflows retry once and run every project the gate leaves out', () => {
const nightly = read('.github/workflows/nightly.yml');
assert.match(nightly, /^ {8}browser: \[firefox, webkit, touch\]$/m);
assert.match(nightly, /test:workflows -- --project \$\{\{ matrix\.browser \}\} --shard \$\{\{ matrix\.shard \}\}\/3 --retries 1$/m);
assert.doesNotMatch(nightly, /grep-invert/, 'quarantined tests still run nightly');
const names = workflowConfig.projects.map(project => project.name).sort();
assert.deepEqual(names, [...GATE_PROJECTS, 'firefox', 'touch', 'webkit'].sort(), 'every project runs in the gate or nightly');
});
// A quarantined test names the issue that tracks it, in one fixed spelling, so the tag is never a
// way to forget a test: test('title', { tag: '@quarantine', annotation: { type: 'issue', description: '#613' } }, ...).
const QUARANTINED = /\{ tag: '@quarantine', annotation: \{ type: 'issue', description: '#\d+' \} \}/g;
test('every @quarantine tag carries its issue number', () => {
const directory = join(root, 'tests/browser');
for (const file of readdirSync(directory).filter(name => name.endsWith('.mjs'))) {
const text = readFileSync(join(directory, file), 'utf8');
const tags = text.match(/@quarantine/g)?.length ?? 0;
const complete = text.match(QUARANTINED)?.length ?? 0;
assert.equal(complete, tags, `${file}: each @quarantine is written as { tag: '@quarantine', annotation: { type: 'issue', description: '#N' } }`);
}
assert.match("test('t', { tag: '@quarantine', annotation: { type: 'issue', description: '#613' } }, async () => {});", QUARANTINED);
assert.doesNotMatch("test('t', { tag: '@quarantine' }, async () => {});", QUARANTINED);
});
function fakeTest(title, outcome, project = 'webkit') {
return { title, outcome: () => outcome, location: { file: '/repo/tests/browser/a.spec.mjs', line: 7 },
parent: { project: () => ({ name: project }) } };
}
function summaryOf(tests, env = { GITHUB_STEP_SUMMARY: '/tmp/summary.md' }) {
const written = [];
const reporter = new FlakyTestsReporter({ env, append: (file, text) => written.push([file, text]) });
assert.equal(reporter.printsToStdio(), false);
reporter.onBegin({ rootDir: '/repo/tests/browser' });
for (const item of tests) reporter.onTestEnd(item);
reporter.onEnd();
return written;
}
test('tests that passed only on the retry are listed once in the job summary', () => {
const flaky = fakeTest('closes `fast`', 'flaky');
const written = summaryOf([fakeTest('fine', 'expected'), flaky, flaky, fakeTest('broken', 'unexpected'),
fakeTest('another', 'flaky', 'touch')]);
assert.deepEqual(written, [['/tmp/summary.md',
'### Flaky tests (failed, then passed on the retry): 2\n\n'
+ "- `[touch] › a.spec.mjs:7 › another`\n- `[webkit] › a.spec.mjs:7 › closes 'fast'`\n\n"]]);
});
test('no flaky test, or no job summary, writes nothing', () => {
assert.deepEqual(summaryOf([fakeTest('fine', 'expected'), fakeTest('broken', 'unexpected')]), []);
assert.deepEqual(summaryOf([fakeTest('wobbly', 'flaky')], {}), []);
});
+3 -1
View File
@@ -77,7 +77,9 @@ test('a shard keeps raw coverage other shards wrote and passes its shard to Play
assert.ok(existsSync(earlier), 'raw files from another shard survive');
assert.equal(calls.length, 1, 'shard 2 runs only the workflows');
const [{ args, env }] = calls;
assert.deepEqual(args.slice(-6), ['--project', 'chromium', '--project', 'touch', '--shard', '2/3']);
// #666: the gate is desktop Chromium without quarantined tests; touch runs nightly, outside coverage.
assert.deepEqual(args.slice(-6), ['--project', 'chromium', '--grep-invert', '@quarantine', '--shard', '2/3']);
assert.ok(!args.includes('touch'));
assert.equal(env.PM_JS_COVERAGE, paths.raw);
});
+63 -20
View File
@@ -1,14 +1,17 @@
#!/usr/bin/env python3
"""Sort a change by the files it touches, so CI tests only what can break (#639).
Three classes, decided from allowlists:
Four classes. Two come from allowlists:
- ``inert``: every file is one nothing reads at run or test time (the funding
file, the security policy, the old README's screenshots, issue templates).
No test job runs.
- ``docs``: every file is inert or a document a Python test reads (the
READMEs and their images, checked by ``tests/test_brand_assets.py`` and
``tests/test_package_contents.py``). Only the Python 3.12 suite runs.
No test job runs, and the pre-push hook skips the suite.
- ``docs``: every file is inert or a document (the READMEs and their images).
No test job runs in CI (#666). Two Python tests read these files
(``tests/test_brand_assets.py``, ``tests/test_package_contents.py``), so
the pre-push hook still runs the suite for them.
- ``release``: ``pyproject.toml`` is the only file, and its ``version`` line
the only line, that changed. CI runs the package-content check only.
- ``code``: anything else. A file on no list is code, and so is every case of
doubt: no files, an unknown event, a range git cannot read.
@@ -20,10 +23,10 @@ code opens it.
Usage:
``change_class.py``
Prints ``class=<inert|docs|code>`` for the workflow's ``$GITHUB_OUTPUT``,
from ``EVENT_NAME``, ``BASE_SHA`` and ``HEAD_SHA``. A pull request is
compared with its merge base, so commits that landed on main meanwhile
do not count; a merge group and a push are compared end to end.
Prints ``class=<inert|docs|release|code>`` for the workflow's
``$GITHUB_OUTPUT``, from ``EVENT_NAME``, ``BASE_SHA`` and ``HEAD_SHA``.
A pull request is compared with its merge base, so commits that landed on
main meanwhile do not count; a push is compared end to end.
``change_class.py --unless-inert <command...>``
The pre-push hook: runs the command unless pre-commit's pushed range
@@ -34,6 +37,7 @@ Usage:
"""
import os
import re
import shutil
import subprocess
import sys
@@ -44,7 +48,10 @@ INERT_FOLDERS = ("images/", ".github/ISSUE_TEMPLATE/")
DOCS_FILES = frozenset({"README.md", "README-legacy.md"})
DOCS_FOLDERS = ("assets/readme/", "assets/brand/")
RANGE_EVENTS = frozenset({"pull_request", "merge_group", "push"})
VERSION_FILE = "pyproject.toml"
VERSION_LINE = re.compile(r'version = "[^"]+"')
RANGE_EVENTS = frozenset({"pull_request", "push"})
ENVIRONMENT = frozenset(
{
"EVENT_NAME",
@@ -70,27 +77,59 @@ def classify(paths: Iterable[str]) -> str:
return found
def changed_paths(base: str, head: str, three_dot: bool) -> Optional[list[str]]:
"""Paths that differ between two commits, or None when git cannot say.
def is_version_bump(diff: str) -> bool:
"""Whether a zero-context diff of one file changes only its version line.
Renames are listed under both names, so a file moved onto a listed name
still counts as the code file it was.
True for exactly one removed and one added line that are both
``version = "..."`` at the start of the line. A second changed line, an
added or removed line without its pair, or a changed mode is not a bump.
"""
if not base or not head or not base.strip("0") or not head.strip("0"):
return None
span = f"{base}...{head}" if three_dot else f"{base}..{head}"
removed, added = [], []
for line in diff.splitlines():
if line.startswith(("old mode", "new mode", "deleted file", "new file")):
return False
if line.startswith("-") and not line.startswith("--- "):
removed.append(line[1:])
elif line.startswith("+") and not line.startswith("+++ "):
added.append(line[1:])
if len(removed) != 1 or len(added) != 1 or removed == added:
return False
return all(VERSION_LINE.fullmatch(line.rstrip("\r")) for line in removed + added)
def _git_diff(span: str, *options: str) -> Optional[str]:
"""``git diff`` output for a range, or None when git cannot say."""
try:
result = subprocess.run(
["git", "diff", "--name-only", "--no-renames", "-z", span, "--"],
["git", "diff", *options, span, "--"],
capture_output=True,
text=True,
check=False,
)
except OSError:
return None
if result.returncode != 0:
return result.stdout if result.returncode == 0 else None
def _span(base: str, head: str, three_dot: bool) -> Optional[str]:
if not base or not head or not base.strip("0") or not head.strip("0"):
return None
return [path for path in result.stdout.split("\0") if path]
return f"{base}...{head}" if three_dot else f"{base}..{head}"
def changed_paths(base: str, head: str, three_dot: bool) -> Optional[list[str]]:
"""Paths that differ between two commits, or None when git cannot say.
Renames are listed under both names, so a file moved onto a listed name
still counts as the code file it was.
"""
span = _span(base, head, three_dot)
if span is None:
return None
names = _git_diff(span, "--name-only", "--no-renames", "-z")
if names is None:
return None
return [path for path in names.split("\0") if path]
def class_of_range(base: str, head: str, three_dot: bool = False) -> str:
@@ -99,6 +138,10 @@ def class_of_range(base: str, head: str, three_dot: bool = False) -> str:
return "code"
for path in paths:
print(f"changed: {path}", file=sys.stderr)
if paths == [VERSION_FILE]:
diff = _git_diff(_span(base, head, three_dot), "--unified=0", "--no-color")
if diff is not None and is_version_bump(diff):
return "release"
return classify(paths)
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Report a nightly run by issue: one issue per failing job (#666).
The nightly workflow (``.github/workflows/nightly.yml``) blocks nothing, so
its result has to reach someone. After the other jobs end, this script reads
the run's jobs and, for each one:
- a failed or timed-out leg: opens ``nightly: <job> failing``, or comments on
the open issue of that title, with the run, the commit and the failed legs;
- every leg passed: comments on the open issue of that title, if there is
one, and closes it;
- anything else (cancelled, skipped): changes nothing, because the run says
nothing about the job.
Matrix shards count as one job: ``page workflows (webkit, shard 2/3)`` reports
as ``page workflows (webkit)``. Titles are matched exactly, so an issue is
never opened twice and never closed by another job's result.
Runs with ``GH_TOKEN``, ``GITHUB_REPOSITORY``, ``GITHUB_RUN_ID``,
``GITHUB_SHA`` and ``GITHUB_SERVER_URL`` from the workflow, plus
``RUN_ATTEMPT``, and calls the ``gh`` CLI. It exits non-zero when a call
fails, so a report that could not be written shows as a red job.
"""
import json
import os
import re
import subprocess
import sys
from typing import Callable, Iterable, Optional
SHARD = re.compile(r", shard \d+/\d+| \(shard \d+/\d+\)")
FAILED = frozenset({"failure", "timed_out"})
OWN_JOB = "report by issue"
TITLE = "nightly: {} failing"
Gh = Callable[[list[str]], str]
def job_group(name: str) -> str:
"""The job a matrix leg belongs to: its name without the shard."""
return SHARD.sub("", name).strip()
def group_jobs(jobs: Iterable[dict]) -> dict[str, list[dict]]:
"""The run's finished jobs by group, without this script's own job."""
groups: dict[str, list[dict]] = {}
for job in jobs:
if job.get("name") == OWN_JOB or not job.get("conclusion"):
continue
groups.setdefault(job_group(job["name"]), []).append(job)
return groups
def verdict(legs: Iterable[dict]) -> Optional[str]:
"""``failing``, ``passing``, or None when the legs do not say."""
conclusions = [leg["conclusion"] for leg in legs]
if any(conclusion in FAILED for conclusion in conclusions):
return "failing"
if conclusions and all(conclusion == "success" for conclusion in conclusions):
return "passing"
return None
def run_gh(arguments: list[str]) -> str:
result = subprocess.run(
["gh", *arguments], capture_output=True, text=True, check=False
)
if result.returncode != 0:
raise RuntimeError(f"gh {' '.join(arguments[:3])}: {result.stderr.strip()}")
return result.stdout
def read_jobs(gh: Gh, repository: str, run_id: str, attempt: str) -> list[dict]:
path = f"repos/{repository}/actions/runs/{run_id}/attempts/{attempt}/jobs"
pages = gh(["api", "--paginate", "--slurp", f"{path}?per_page=100"])
return [job for page in json.loads(pages) for job in page["jobs"]]
def open_issue(gh: Gh, repository: str, title: str) -> Optional[int]:
"""The number of the open issue with exactly this title, if any."""
found = gh(
[
"issue",
"list",
"--repo",
repository,
"--state",
"open",
"--search",
f'in:title "{title}"',
"--json",
"number,title",
"--limit",
"100",
]
)
numbers = [
issue["number"] for issue in json.loads(found) if issue["title"] == title
]
return min(numbers) if numbers else None
def failure_text(legs: list[dict], run_url: str, sha: str) -> str:
failed = [leg for leg in legs if leg["conclusion"] in FAILED]
lines = [
f"- [{leg['name']}]({leg['html_url']}): {leg['conclusion']}" for leg in failed
]
return "\n".join(
[
f"The nightly run {run_url} failed at {sha}:",
"",
*lines,
"",
(
"Nothing is blocked by this. Read the job log, fix the cause, and the"
" next green nightly run closes this issue. Do not rerun to get green"
' (TESTING.md "Nightly").'
),
]
)
def report(gh: Gh, environment: dict[str, str]) -> list[str]:
"""Write the issues for one run; the lines saying what was done."""
repository = environment["GITHUB_REPOSITORY"]
run_id = environment["GITHUB_RUN_ID"]
sha = environment["GITHUB_SHA"][:7]
server = environment.get("GITHUB_SERVER_URL", "https://github.com")
run_url = f"{server}/{repository}/actions/runs/{run_id}"
jobs = read_jobs(gh, repository, run_id, environment.get("RUN_ATTEMPT", "1"))
done = []
for group, legs in sorted(group_jobs(jobs).items()):
state = verdict(legs)
if state is None:
done.append(f"{group}: no verdict, nothing changed")
continue
title = TITLE.format(group)
number = open_issue(gh, repository, title)
if state == "failing":
body = failure_text(legs, run_url, sha)
if number is None:
gh(
[
"issue",
"create",
"--repo",
repository,
"--title",
title,
"--body",
body,
]
)
done.append(f"{group}: failing, opened an issue")
else:
gh(
[
"issue",
"comment",
str(number),
"--repo",
repository,
"--body",
body,
]
)
done.append(f"{group}: failing, commented on #{number}")
elif number is not None:
body = f"Passed in the nightly run {run_url} at {sha}."
gh(["issue", "close", str(number), "--repo", repository, "--comment", body])
done.append(f"{group}: passing, closed #{number}")
else:
done.append(f"{group}: passing")
return done
def main() -> int:
try:
for line in report(run_gh, dict(os.environ)):
print(line)
except (RuntimeError, KeyError, ValueError, OSError) as error:
print(f"nightly_report: {error!r}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+44
View File
@@ -0,0 +1,44 @@
import { appendFileSync } from 'node:fs';
import { relative } from 'node:path';
// Lists the tests that failed and then passed on a retry (#666). Only the nightly run retries
// (`--retries 1`), so a flaky test does not turn its job red there; this reporter puts each one in the
// job summary instead, where the morning's reader sees it. The gate runs without retries: there a
// test either passes or fails, and this reporter writes nothing.
export default class FlakyTestsReporter {
constructor({ env = process.env, append = appendFileSync } = {}) {
this.summaryFile = env.GITHUB_STEP_SUMMARY;
this.append = append;
this.rootDir = process.cwd();
this.ended = new Set();
}
printsToStdio() {
return false;
}
onBegin(config) {
this.rootDir = config.rootDir;
}
onTestEnd(test) {
this.ended.add(test);
}
describe(test) {
const project = test.parent?.project()?.name;
const where = `${relative(this.rootDir, test.location.file)}:${test.location.line}`;
return `${project ? `[${project}] › ` : ''}${where} › ${test.title}`;
}
flaky() {
return [...this.ended].filter(test => test.outcome() === 'flaky').map(test => this.describe(test)).sort();
}
onEnd() {
const flaky = this.flaky();
if (!flaky.length || !this.summaryFile) return;
const lines = flaky.map(line => `- \`${line.replaceAll('`', "'")}\``);
this.append(this.summaryFile, `### Flaky tests (failed, then passed on the retry): ${flaky.length}\n\n${lines.join('\n')}\n\n`);
}
}
+9 -2
View File
@@ -12,6 +12,12 @@ const USAGE = 'usage: frontend-coverage.mjs [--update-baseline] | --shard I/N |
const FORWARDED_SIGNALS = ['SIGTERM', 'SIGINT'];
// What the gate runs and the coverage floors are measured with (#666): desktop Chromium only, without
// the tests tagged @quarantine (TESTING.md "Quarantine"). Firefox, WebKit, the phone-size touch
// project and the quarantined tests run nightly, outside coverage.
export const GATE_PROJECTS = ['chromium'];
export const QUARANTINE_TAG = '@quarantine';
// Runs one step's node child and waits for it. npm and a CI step timeout signal only this process,
// so SIGTERM and SIGINT are forwarded to the running child (#425): Playwright then reports the tests
// still running and writes its blob. The child gets its own process group, so a signal sent to the
@@ -48,7 +54,7 @@ function parseShard(value) {
}
// Turn the command line into the ordered steps of one coverage run:
// - no mode: the full run (clean, node units, viewer suite, chromium+touch
// - no mode: the full run (clean, node units, viewer suite, the gate's
// workflows, report, check), exactly as before shards existed;
// - --shard I/N: one slice of the workflows into coverage/js/raw, without wiping
// it or reporting; shard 1 also runs the node units and the viewer suite;
@@ -136,7 +142,8 @@ export async function runCoverage({ argv = process.argv.slice(2), run = runNode,
},
workflows({ shard }) {
return run([playwright, 'test', '--config', join(tools, 'playwright.workflows.config.mjs'),
'--project', 'chromium', '--project', 'touch', ...(shard ? ['--shard', shard] : [])], { PM_JS_COVERAGE: raw });
...GATE_PROJECTS.flatMap(project => ['--project', project]), '--grep-invert', QUARANTINE_TAG,
...(shard ? ['--shard', shard] : [])], { PM_JS_COVERAGE: raw });
},
report() {
return run([join(tools, 'node_modules/c8/bin/c8.js'), 'report', '--all', '--src', sourceRoot,
+2 -1
View File
@@ -8,7 +8,8 @@ export default defineConfig({
fullyParallel: true,
workers: 2,
forbidOnly: Boolean(process.env.CI),
retries: process.env.CI ? 1 : 0,
// No retries in the gate (#666): a retry hides a race.
retries: 0,
reporter: reporters({ name: 'viewer' }),
use: { browserName: 'chromium', headless: true, trace: 'retain-on-failure' },
projects: [
+1
View File
@@ -3,6 +3,7 @@ import { reporters, workflowWorkers } from './test-workers.mjs';
// No global webServer: tests/browser/fixtures.mjs starts one server per worker
// on an OS-chosen port. Files run in parallel; tests inside a file keep their order.
// Retries stay off here, so the gate never hides a race; the nightly run passes --retries 1 (#666).
export default defineConfig({
testDir: '../../tests/browser',
outputDir: './test-results/workflows',
+5 -2
View File
@@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
// Absolute, so a config that imports this one from another directory still finds it.
const RUNNING_TESTS_REPORTER = fileURLToPath(new URL('./running-tests-reporter.mjs', import.meta.url));
const FLAKY_TESTS_REPORTER = fileURLToPath(new URL('./flaky-tests-reporter.mjs', import.meta.url));
const MAX_LOCAL_WORKERS = 8;
const CPUS_PER_WORKER = 4;
@@ -22,8 +23,10 @@ export function workflowWorkers({ env = process.env, cpus = availableParallelism
}
// Under CI, running-tests-reporter.mjs names the tests a step timeout's signal cut off (`list`
// cannot: they never end), and a blob report beside the traces is uploaded with them.
// cannot: they never end), flaky-tests-reporter.mjs lists in the job summary the tests that passed
// only on a retry (the nightly run retries once, the gate never), and a blob report beside the traces
// is uploaded with them.
export function reporters({ env = process.env, name } = {}) {
if (!env.CI) return 'list';
return [['list'], [RUNNING_TESTS_REPORTER], ['blob', { outputDir: `./test-results/blob/${name}` }]];
return [['list'], [RUNNING_TESTS_REPORTER], [FLAKY_TESTS_REPORTER], ['blob', { outputDir: `./test-results/blob/${name}` }]];
}