Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6375be1a92 | ||
|
|
6f02277a1c | ||
|
|
8aad090c09 | ||
|
|
3d32e9183a | ||
|
|
a1f744708e | ||
|
|
b3bb55f2dc | ||
|
|
fa31644c4c | ||
|
|
0c023c7ec9 | ||
|
|
9943a61619 |
@@ -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"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -17,9 +17,18 @@ concurrency:
|
||||
group: viewerjs-update
|
||||
cancel-in-progress: false
|
||||
|
||||
# Time limit rule as in ci.yml (#662): ceil(1.5 x the slowest of three recent green runs) + 3 minutes, never under 5.
|
||||
# Measured 2026-11-21 on runs 44771628562 (b3bb55f), 44568715421 (b3bb55f), 44349316383 (1d509c8):
|
||||
# these nightly runs found no new release and took 0m09s / 0m13s / 0m12s, the 5-minute floor. None of
|
||||
# the 35 green runs since 2026-10-17 took the update path (tests, Chromium, the PR), so it is estimated
|
||||
# from its parts until three green update runs can be measured:
|
||||
# estimate update: npm ci on a cold cache up to 5m (as recorded for the browser jobs), Playwright
|
||||
# Chromium with its system packages about 2m, the pin check, tooling and unit tests about 1m, the
|
||||
# viewer suite (38s locally, 2 workers) and setup about 2m: 10 min, ceil(1.5 x 10) + 3 -> 18 min
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 18
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
@@ -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
@@ -5,8 +5,7 @@
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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
|
||||
|
||||
|
||||
+360
-168
@@ -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,26 @@ 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`, `publish.yml` and `viewerjs-update.yml`
|
||||
(#662) 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 +332,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 +343,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`,
|
||||
@@ -368,12 +374,18 @@ and the time left. The steps, in order:
|
||||
observer join get what is left, which can be 0 s. `stop()` joins watchdog's
|
||||
emitters without a limit, so it runs on a daemon thread and is waited for
|
||||
only until the deadline; a later stop waits for that same call (#561).
|
||||
3. `close_auto_thumbnails(final=True)` stops the preview worker (30 s),
|
||||
3. `stop_review_worker` stops the Needs review worker (`pm-review-recorder`,
|
||||
5 s, #659): it drops the queued and deferred paths (their count is logged;
|
||||
the next scan covers them), refuses every later `queue_review_file` and
|
||||
joins the thread, which finishes at most the file in hand. It always runs,
|
||||
so an image in hand cannot start the worker afterwards; it is reported as
|
||||
part `review` only when the worker started.
|
||||
4. `close_auto_thumbnails(final=True)` stops the preview worker (30 s),
|
||||
kills ffmpeg and shuts the interactive image pool down.
|
||||
4. `shutdown_job_pool` (`utils/parallel.py`) cancels the long-lived job pool's
|
||||
5. `shutdown_job_pool` (`utils/parallel.py`) cancels the long-lived job pool's
|
||||
queued items and joins its threads (5 s; part `workers`, only when a job
|
||||
used the pool, #523).
|
||||
5. `PromptTracker.shutdown` stops the prompt cleanup thread (2 s).
|
||||
6. `PromptTracker.shutdown` stops the prompt cleanup thread (2 s).
|
||||
|
||||
A failing step, or a second Ctrl+C, is logged with its traceback and does not
|
||||
skip the later steps. A clean run logs one INFO line to PromptManager's log:
|
||||
@@ -426,6 +438,7 @@ exit waits for the call in flight, as before. `tests/test_exit_cancel.py` runs a
|
||||
child process with three such calls running and requires its exit within 15 s.
|
||||
|
||||
Stop contract: `PromptTracker.shutdown(timeout)`,
|
||||
`ReviewRecordingMixin.stop_review_worker(timeout)` (final),
|
||||
`ImageGenerationHandler.shutdown(timeout)` (restartable),
|
||||
`ImageGenerationHandler.close(timeout)` (final: `schedule()` refuses and a
|
||||
sealed run's re-check is dropped) and `ImageMonitor.stop_monitoring(timeout)`
|
||||
@@ -438,7 +451,8 @@ Test rules:
|
||||
- Every test that constructs a real `PromptTracker`, `ImageGenerationHandler`
|
||||
or `ImageMonitor` ends with its final stop and an assertion
|
||||
(`tests/background_stops.py`: `close_handler`, `stop_monitor`,
|
||||
`stop_tracker`). The stop comes before the folder and databases are removed.
|
||||
`stop_tracker`). `ReviewTestCase.tearDownAsync` asserts
|
||||
`stop_review_worker` before its capture store and folder go. The stop comes before the folder and databases are removed.
|
||||
`tearDown` runs before `addCleanup` callbacks, so a class whose `tearDown`
|
||||
removes files stops the thread there.
|
||||
- A test waits for a state through an `Event` set by the code under test, or
|
||||
@@ -491,6 +505,19 @@ differ are files whose pixel data is undecodable or cut short: legacy found
|
||||
nothing, the walk keeps the text before the pixels. Animated PNGs still use
|
||||
`.text`.
|
||||
|
||||
WebP, AVIF and JPEG keep the same records in EXIF, not in text chunks.
|
||||
ComfyUI's `SaveAnimatedWEBP` writes `prompt:{json}` to EXIF tag 0x0110, then
|
||||
`workflow:{json}` and every other `extra_pnginfo` key to 0x010F and down; the
|
||||
AVIF writer uses that layout. `utils/exif_text.py` answers the `png_text` shape
|
||||
through Pillow's `getexif()`, and both metadata readers fall back to it when a
|
||||
file has no text chunks. Only a value shaped like a record counts (a key, a
|
||||
colon, then a JSON object, array or string), so camera EXIF stays out.
|
||||
`tests/test_exif_text.py` writes real still and animated WebP files, AVIF (where
|
||||
Pillow has it) and JPEG in that layout; `tests/test_metadata_extraction.py` and
|
||||
`tests/test_api_core.py` hold the two readers to it. No scan, monitor or
|
||||
gallery list collects `.avif` yet, so AVIF files are read correctly but never
|
||||
reach the readers; #652 tracks AVIF as a media type.
|
||||
|
||||
Image work runs on PromptManager's own threads (#523). glibc keeps each thread's
|
||||
malloc arena at its high-water mark, so image buffers spread over the default
|
||||
executor's threads stay resident. Interactive image work (view previews behind their
|
||||
@@ -510,20 +537,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)
|
||||
|
||||
@@ -714,114 +741,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 \
|
||||
@@ -829,9 +905,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
|
||||
|
||||
@@ -939,7 +1015,15 @@ WanImageToVideo by output slot). `ConditioningZeroOut` is an explicit empty text
|
||||
with source `zeroed-conditioning`. `easy ifElse` with a literal boolean follows that
|
||||
branch only; with a linked boolean both branches are traced, equal texts resolve and
|
||||
different texts make the sampler `ambiguous` with one candidate per choice (at most
|
||||
32, else `work-limit`). ConditioningCombine/Concat/Average resolve only when every
|
||||
32, else `work-limit`). A value is *proven* (#657, rgthree's `Any Switch (rgthree)`,
|
||||
strategy `first-present`, which outputs its first input that is not `None`) only by
|
||||
a literal or a traced path whose every node is a PromptManager node, a class the
|
||||
resolver handles in code (`Reroute`, `StringConcatenate`, `Text Concatenate`, the
|
||||
default string adapters) or an entry of the table's `encoders`, `strings`,
|
||||
`conditioning` or `composites` (`PROVEN_VALUE_CATEGORIES`). That allowlist is a rule
|
||||
for every future table entry: a class that can return `None` (a selector, an
|
||||
unknown node, a `runtime`, `facts` or `lineage` class) never goes into those four
|
||||
categories, and a test pins them. Both resolvers read the constant (`Semantics.proves_value`; the browser's copy in `local-resolver-support.mjs`), and `tests/test_proven_value_parity.py` fails when the browser copy drifts from it (#662). Otherwise the switch offers one candidate per distinct outcome of its inputs, and no PromptManager path is preferred. When a sampler is `ambiguous`, Inspect still shows a role every candidate resolves alike (same text, recipe and left-out parts) as resolved (#658); `resolution.state` stays `ambiguous`, so pair actions and ingestion are unchanged. ConditioningCombine/Concat/Average resolve only when every
|
||||
part has the same text, otherwise `unresolved` with `composite` naming the node
|
||||
(but see the added-conditioning floor below for a later stage).
|
||||
Results that depend on a forced choice are never memoized. A `FaceDetailer`
|
||||
@@ -2624,7 +2708,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
|
||||
@@ -2761,7 +2845,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
|
||||
@@ -4711,7 +4795,7 @@ the per-section hand-off panel, was retired by S12 (#329): every section is nati
|
||||
concept row's), `skipped tags add, preview, remove, save and reload (D202)`, `skipped
|
||||
tags preview checks library tags only …` (workspace-system-tagging.spec) and
|
||||
`suggestions omit skipped tags and say how many were hidden` (workspace-tagging.spec).
|
||||
- **D205** (Prompt library, #620, beyond the concept): the sort menu appends Recently used, Most used and Name Z–A
|
||||
- **D206** (Prompt library, #620, beyond the concept; numbered D205 until #662 found the id taken by #431): the sort menu appends Recently used, Most used and Name Z–A
|
||||
after Oldest first. These are the old Dashboard's sorts, kept before its removal because the community asked for
|
||||
them. A prompt never run sorts last in both use orders.
|
||||
- **D203** (Auto-tagging, #431, beyond the concept): "Saved instructions" replaces the
|
||||
@@ -6431,39 +6515,59 @@ never the metadata row.
|
||||
|
||||
Needs review items (#249, `utils/review_capture.py`, `database/review.py`,
|
||||
`tests/test_review.py`, `tests/test_review_outcome.py`,
|
||||
`tests/test_review_choosable.py`): a file is queued only when its final outcome
|
||||
is ambiguous and unlinked and there is something to choose. Only scans produce
|
||||
items; the monitor links new outputs and clears pending items it resolves
|
||||
(maintainer rulings, 2026-10-23). The output scan (Activity's
|
||||
`tests/test_review_choosable.py`, `tests/test_review_collapsed.py`): a file is queued only when its final outcome
|
||||
is ambiguous and unlinked and there is something to choose. The scan and the
|
||||
live monitor queue the same files (maintainer decision 2026-11-19, #659; it
|
||||
replaces the 2026-10-23 ruling that only scans add items, made when the
|
||||
monitor's pass queued files the scan's fallback went on to link): one per-file
|
||||
decision, `review_dispatch` (`py/api/review_recording.py`), serves both. The
|
||||
output scan (Activity's
|
||||
Scan for metadata and the legacy `/scan`) hands `record_ambiguous_file` a file
|
||||
the ingestion resolver finds `ambiguous` only when the browser-parser fallback
|
||||
then links nothing (status `ambiguous`) and no saved row links the file
|
||||
already; an ambiguous file a saved row links is reported `unchanged` ("Already
|
||||
linked to its prompt"), not Needs review. A file the fallback links, an exact
|
||||
pair the ingester stores, and `conflict` and `unresolved` files are not
|
||||
queued. Neither is an ambiguous file with nothing to choose: fewer than two of
|
||||
its candidates are `resolved` with non-blank positive text (`reviewable`). With
|
||||
none the file could not be traced; with exactly one, the untraced branches may
|
||||
still have made the file, so that text is not certain either. Both report
|
||||
`unresolved` ("could not be traced"), are never linked, and their pending,
|
||||
undecided items whose own evidence offers no choice (a limited item counts as
|
||||
a choice when it holds at least two candidates) leave the queue on the next
|
||||
scan (`settle_untraced_review_items`). The maintainer's
|
||||
second live check found 39 items whose 11 candidates were all "unresolved".
|
||||
queued. Neither is an ambiguous file with nothing to choose: none of its
|
||||
candidates is `resolved` with non-blank positive text (`reviewable`,
|
||||
`MIN_CHOOSABLE` = 1). Such a file could not be traced: it reports `unresolved`
|
||||
("could not be traced"), is never linked, and its pending, undecided items
|
||||
whose own evidence offers no choice (a limited item counts as a choice when it
|
||||
holds at least one candidate) leave the queue on the next scan
|
||||
(`settle_untraced_review_items`). The maintainer's second live check found 39
|
||||
items whose 11 candidates were all "unresolved". One readable candidate is
|
||||
enough (#657 addendum D1, maintainer 2026-11-20: "fine that we cannot tell,
|
||||
not fine to show nothing"): the untraced branches may still have made the
|
||||
file, so it is never linked from that text, but it is queued with the other
|
||||
branches listed (disabled, e.g. "Text is decided at run time") and the user
|
||||
may confirm it or leave it unresolved. The live case is the sweep with an LLM
|
||||
enhancer on rgthree Any Switch `any_01` (`tests/sweep_graphs.py`
|
||||
`enhanced_sweep_graph`, `TestOneReadableChoiceIsQueued`, scan and monitor).
|
||||
A default choice that is partial (a branch beside it has no prompt to choose,
|
||||
or it offers fewer than two: `partial_choice`) still asks the inspection
|
||||
profile, and the item is recorded from that profile when it offers more
|
||||
choosable candidates (`offers_more`; #657 review, `mixed_edit_graph`:
|
||||
a Qwen image-edit sampler only the inspection profile reads beside a
|
||||
CLIPTextEncode one, `TestPartialDefaultAsksInspection`, scan, monitor and a
|
||||
rescan that keeps the item an inspection item).
|
||||
Inspection-profile choices (`tests/test_review_inspection.py`, ruling a): when
|
||||
the default profile is ambiguous without a choice and nothing links the file,
|
||||
the scan (never the monitor) resolves it again with `INSPECTION_PROFILE`, which
|
||||
the default profile is ambiguous without a choice, or calls a file with a prompt
|
||||
graph `unresolved` (#659 C1/C2: `Decision.default_unresolved`, set before the
|
||||
blank-positive rewrite, so a blank positive does not count; "Unsupported latent
|
||||
ancestry" on the maintainer's model-compare sweep is the example), and nothing
|
||||
links the file, the scan and the monitor's review worker resolve it again with
|
||||
`INSPECTION_PROFILE`, which
|
||||
knows `TextEncodeQwenImageEdit`, `StringConstantMultiline`, `JoinStringMulti`
|
||||
and the rest of `web/js/inspection-semantics.json`. With at least two choosable
|
||||
candidates there, the file is `ambiguous` and is queued from that profile's
|
||||
and the rest of `web/js/inspection-semantics.json`. With a choosable
|
||||
candidate there, the file is `ambiguous` and is queued from that profile's
|
||||
evidence, which adds `profile: "inspection"` and `semantics`: the SHA-256 of
|
||||
`class_projection`, the table restricted to the graph's node classes plus its
|
||||
class-independent `schema` and `stage_inputs` (the resolver looks the table up
|
||||
only by a graph node's class). The item's `resolver_version` is
|
||||
`inspection_review_version(metadata)`, 2^40 plus 40 bits of SHA-256 over the
|
||||
profile with its budgets, `RESOLVER_VERSION`, `INSPECTION_RESOLVER_VERSION`
|
||||
(bump it when the inspection profile would resolve the same metadata otherwise)
|
||||
and that fingerprint. A table edit about the
|
||||
(bump it when the inspection profile would resolve the same metadata otherwise),
|
||||
`REVIEW_RULE_VERSION`, `REVIEW_EVIDENCE_VERSION` and that fingerprint. A table edit about the
|
||||
graph's classes behaves like a resolver change (I2); an edit about other
|
||||
classes changes nothing. One file never holds two pending items for the same
|
||||
bytes: a new version's item supersedes the byte record's other items when all
|
||||
@@ -6472,7 +6576,9 @@ delete); beside a decided or advanced item nothing new is stored, and the
|
||||
rescan's stat shortcut then skips those bytes under any version. A pending item
|
||||
stays applicable while the bytes still offer its chosen candidate.
|
||||
Apply re-resolves the capture with the profile the item recorded and re-checks
|
||||
the chosen hash; the link goes through the same compatible-only ingestion. The
|
||||
the chosen hash against every projected, de-duplicated candidate hash of the
|
||||
bytes (`candidate_hashes`, before any bound or collapse, so a reorder that
|
||||
changes the collapsed representatives still applies); the link goes through the same compatible-only ingestion. The
|
||||
inspection profile never links on its own, and ingestion keeps the default
|
||||
profile (D1). The heavier profile runs only for files already ambiguous without
|
||||
a choice, and once per file state: the capture reuses the scan's result when
|
||||
@@ -6499,19 +6605,59 @@ item versions, so older inspection items are recorded again once. Apply accepts
|
||||
the anchored pair and refuses a choice the anchor contradicts. Measured on the
|
||||
maintainer's 40,890 outputs: the queue is unchanged (249 files); the 242
|
||||
`gpu_unlock_bench` files the inspector resolves are linked by the parser
|
||||
floor. The 16-candidate limited
|
||||
rule and the 8 MiB bound apply unchanged. The queue heals itself: after each batch, the scan removes the pending
|
||||
floor. The 16-candidate collapse and the 8 MiB bound apply unchanged. The queue heals itself: after each batch, the scan removes the pending
|
||||
items of every listed file (read or skipped as known) that a saved row now
|
||||
links, and the monitor does the same for each ambiguous output it links
|
||||
(`settle_linked_review_items`; the review index revision moves). Only an
|
||||
undecided item goes (`pending`, revision 0, no decision row): a decision is
|
||||
never deleted or changed, so no schema state was added. The monitor never
|
||||
records an item (only scans add items, maintainer ruling 2026-10-23): an
|
||||
unlinked file passed to `record_review_file` is `skipped` with no capture,
|
||||
and only a linked one's pending items are settled
|
||||
(`test_monitor_never_records_an_unlinked_ambiguous_output`). The
|
||||
never deleted or changed, so no schema state was added. The monitor queues a
|
||||
file only at its final unlinked outcome, after run history had its say
|
||||
(`tests/test_foreign_save_to_library.py` `TestFinalUnlinkedOutcomesQueueForReview`):
|
||||
the ladder wait's sealed re-check left it unlinked, the settle lookup found the
|
||||
run's record and no certain prompt, the file is outside ComfyUI's output folder
|
||||
(it is never sealed) at the PromptManager or foreign exit, or the keyless
|
||||
history re-check found no prompt. A wait that expires or an entry dropped at the
|
||||
wait's cap is only logged and left to the next scan. At that point the handler's
|
||||
recorder, `queue_review_file`, puts the path on the review worker's queue and
|
||||
returns at once; linked ambiguous outputs go the same way, so their pending items
|
||||
leave the queue. The worker (thread `pm-review-recorder`, a daemon, started on the
|
||||
first queued path) runs `record_review_file`: the job blocker, root and linked
|
||||
checks, then the scan's own per-file steps for that one file, read only: the
|
||||
scan's metadata read, the ladder under `Policy.SCAN` with the file's recorded
|
||||
history (`_BatchHistory`) and the recorded-run check. A file any step would link,
|
||||
or whose prompt does not save, is `skipped` (the next scan links it; the worker
|
||||
links nothing); otherwise the answer is `review_dispatch`'s record outcome
|
||||
(`recorded`, `duplicate`, `decided`, `untraced`, `limited`), so the next scan
|
||||
finds the item a `duplicate` (`test_monitor_pass_queues_and_the_next_scan_reports_a_duplicate`).
|
||||
An untraced file also loses its pending items without a choice, as in the scan.
|
||||
A file without a prompt graph is never captured. Inspect records too (#657
|
||||
addendum D2, `tests/test_inspection_review.py`): its `review` field (`{"state":
|
||||
"pending", "item_id"}`, `{"state": "decided"}` or null, asked only for an
|
||||
ambiguous role of an unlinked file under an output root) runs
|
||||
`record_review_file`, the worker's own path, in the executor when no item
|
||||
exists at the inspected stat, then reads the item again; Images and History's
|
||||
current-file inspection share the reader (`review_reader(..., record=)`). A
|
||||
file the scan would link, an untraced one or a deferred pass records nothing;
|
||||
a failure is logged and the field stays null, never failing the response.
|
||||
Inspect calls `inspect_review_file` (`py/api/review_recording.py`): a pending
|
||||
item of a current item version needs nothing; one of an older version (e.g. a
|
||||
choiceless limited item from before D3) is recorded again, so the new item
|
||||
supersedes it. A busy capture store (`CaptureCapacity`, the worker copying a
|
||||
fresh output) is expected and logged at debug level, and the item is read
|
||||
once more after any failed recording. A state Inspect found unrecordable
|
||||
(`skipped`, `untraced`) is remembered per process by a 16-byte digest of its
|
||||
locator, size, `mtime_ns`, default item version and semantics table version
|
||||
(at most `MAX_INSPECT_MEMORY` = 4,096, oldest forgotten first), so a repeated
|
||||
Inspect does not copy it again.
|
||||
The queue coalesces by path (a
|
||||
path queued while it runs runs once more afterwards; one thread, so two
|
||||
recordings of one path never overlap) and holds at most `REVIEW_QUEUE_LIMIT` =
|
||||
4,096 paths, dropping the oldest with a log line, so the image worker never
|
||||
waits for it. A recorder failure is logged by the worker and undoes no link.
|
||||
`tests/test_review.py` `TestReviewWorker` covers the queue. The
|
||||
maintainer's live check of #284/#288 found the queue at 10,232 against a review
|
||||
group of 4,677: every fallback-linked ambiguous file had been queued. It captures
|
||||
group of 4,677: every fallback-linked ambiguous file had been queued; the
|
||||
worker's ladder pass is what keeps those files out now. It captures
|
||||
the file (scope `needs-review`), reads its metadata again from the capture,
|
||||
resolves it with the default profile and stores only an ambiguous result,
|
||||
bound to the capture's byte record (created or refreshed like an observe) and
|
||||
@@ -6519,8 +6665,26 @@ fenced by the capture's storage epoch. Evidence is the resolver reason plus one
|
||||
`{sampler_id, state, reason, positive, negative, hash}` per selectable
|
||||
candidate (nested ambiguous stages flattened, duplicates dropped; each side
|
||||
`{text, storage_text, provenance}`; `hash` = SHA-256 of the canonical candidate
|
||||
without it). More than 16 candidates, or evidence over 8 MiB, is a `limited`
|
||||
item without candidates. Recording is idempotent per `(byte_id,
|
||||
without it). More than 16 candidates are collapsed, not dropped (#657 addendum
|
||||
D3, the maintainer's ConsistentFace batch: 83 samplers, 81 prompts): the
|
||||
choosable ones are grouped by their (positive, negative) texts. With at most
|
||||
16 texts the item stays ordinary: one candidate per text, its first
|
||||
occurrence, and the branches without a prompt fill the remaining places in
|
||||
their order (20 samplers sharing three texts keep their run-time branches).
|
||||
With more than 16 texts the groups are ordered by size, largest first, then
|
||||
by first appearance, and the first 16 are kept, each by its first occurrence (its real sampler and hash, so Apply finds
|
||||
it again). The evidence is ordinary (not limited) and adds `collapsed:
|
||||
{shown, total, paths}` (groups shown, distinct choosable texts, candidates in
|
||||
all); the item detail returns it as `collapsed` (null otherwise) and the page
|
||||
reads "Showing the n most used of total prompts in this file". Evidence that
|
||||
cannot be projected, or is over 8 MiB, is a `limited` item without candidates.
|
||||
`REVIEW_EVIDENCE_VERSION` (`utils/review_capture.py`) names this shape and is
|
||||
folded into every item version: a default-profile item carries
|
||||
`default_item_version()` = `RESOLVER_VERSION` + `REVIEW_EVIDENCE_VERSION` (2
|
||||
now; items before it carry 1), an inspection item folds it into its seed. The
|
||||
next scan therefore records such a file again and the new item supersedes the
|
||||
pending, undecided limited one; a decided item is kept and no item is added
|
||||
beside it (`tests/test_review_collapsed.py`). Recording is idempotent per `(byte_id,
|
||||
resolver_version, evidence_hash)` and never touches an existing item or its
|
||||
decisions; changed bytes add a new pending item and keep the old one. The
|
||||
capture is released before the write; no model is loaded and no pixel is
|
||||
@@ -6538,14 +6702,21 @@ capture capacity), each only when N > 0. Recording captures in the background: i
|
||||
last worker or capture slot, which stay free for an interactive Tag dialog or
|
||||
Apply, and waits up to 2 s for room before counting the file as not added
|
||||
(`test_background_recording_leaves_a_worker_for_the_tag_dialog`). The monitor's
|
||||
pass runs after its own link, best effort: a failure is logged and the link
|
||||
stays. Recording follows the registry's `records`
|
||||
pass is best effort: a failure is logged and any link stays. Recording follows the registry's `records`
|
||||
admission (#289): the scan's recording runs under its own `records` job, and
|
||||
the monitor's pass (one file, not a job, which only settles) is refused
|
||||
while a `records` or `guarded` job or hold runs, except thumbnail work, which
|
||||
writes no records (S5 M7). It then writes nothing, logs that the file waits
|
||||
for the next scan, and answers `deferred`; the next "new" scan reads the ambiguous file
|
||||
again (`test_monitor_recording_is_refused_beside_record_changing_jobs`). A new item moves `review_index_revision`. A
|
||||
writes no records (S5 M7). It then writes nothing, logs it, and answers
|
||||
`deferred`. The worker keeps a deferred path in its own insertion-ordered set
|
||||
(`REVIEW_DEFERRED_LIMIT` = 1,000, oldest dropped first with a log line), waits on
|
||||
its queue with a `REVIEW_RETRY_SECONDS` = 5 s timeout while that set is not empty,
|
||||
and on each wake asks the registry's `blocker()` (a snapshot, safe from any
|
||||
thread); once none remains it replays the set through its queue, so the file is
|
||||
queued after the job ends with no other output, exactly once
|
||||
(`test_monitor_recording_is_refused_beside_record_changing_jobs`). A replay
|
||||
re-reads and re-decides: a file already queued is a `duplicate`, one the job
|
||||
linked is `linked`. The set lives in memory; a restart drops it and the next scan
|
||||
is the backstop. A new item moves `review_index_revision`. A
|
||||
rescan does not copy or hash an ambiguous file whose current size and
|
||||
`mtime_ns` equal the verified fingerprint of bytes an item already cites (a
|
||||
stat compare); the file still stays in the default "new" scope, because it is
|
||||
@@ -6590,9 +6761,10 @@ whose bytes are the item's, re-hashes the current file (`file-changed`
|
||||
otherwise, also for a fresh capture of new bytes), re-reads the capture and
|
||||
requires that its bytes are still ambiguous and still offer the chosen
|
||||
candidate (`review-conflict` otherwise; a resolver change that rewords the
|
||||
reason or reorders candidates leaves the item applicable, and
|
||||
`RESOLVER_VERSION` in `utils/prompt_pair_resolver.py` is the one version
|
||||
ingestion provenance and review share), then in one `_pair_transaction`
|
||||
reason or reorders candidates leaves the item applicable;
|
||||
`RESOLVER_VERSION` in `utils/prompt_pair_resolver.py` is ingestion's
|
||||
provenance version, and a review item's version folds it with
|
||||
`REVIEW_EVIDENCE_VERSION`, see above), then in one `_pair_transaction`
|
||||
checks the epoch, the item revision and state (`review-conflict` with the
|
||||
current item for a repeat), the re-hashed digest, the dependency fingerprint
|
||||
and the public ingester's compatible-only rules through
|
||||
@@ -6928,8 +7100,28 @@ handler's `_ingest_foreign`, `_recheck_foreign`, `_store_foreign`):
|
||||
file linked to another prompt is `conflict` and keeps its link. Logged at info
|
||||
"Foreign run: <status> prompt <id> for <file> (<source>)"; a failure is logged and
|
||||
the file stays unlinked.
|
||||
- **Never.** No tracker FIFO entry is read or consumed, nothing is counted (run count
|
||||
stays 0, no `last_used_at`), and nothing is queued for Needs review.
|
||||
- **Never.** No tracker FIFO entry is read or consumed and nothing is counted (run
|
||||
count stays 0, no `last_used_at`). At its final unlinked outcome the file is handed
|
||||
to the Needs review worker (#659, see "Needs review items").
|
||||
- **PromptManager runs (#659 Part 3).** A PromptManager output its metadata and its
|
||||
tracked run cannot link (`_find_prompt_from_run` returns `(prompt, cause)`; causes
|
||||
`RUN_SEVERAL_KEYS`, `RUN_BATCH_LATEST`, `RUN_NO_ENTRY`) takes the same path with run
|
||||
kind `promptmanager`; one outside ComfyUI's output folder (`RUN_OUTSIDE_OUTPUT`)
|
||||
asks the ladder once with `in_output=False`. A keyless image keeps its own
|
||||
history-only wait and a placeholder batch entry stays unlinked; neither, nor a file
|
||||
whose metadata could not be read, asks the ladder. Wait entries are
|
||||
`(path, deadline, kind)` and due re-checks `ForeignRecheck(reference, kind)`;
|
||||
`awaiting_foreign()` lists foreign entries only, `awaiting_ladder()` all. The kind
|
||||
is read in one place, `ladder_gate(kind)`: `foreign` gives
|
||||
`(save_foreign_runs(), RUN_MARKS)`, `promptmanager` gives
|
||||
`(MONITORING_ENABLED is not False, SCAN_MARKS)`, so `SAVE_FOREIGN_RUNS` off stops
|
||||
only foreign entries and the node's own Save to library applies through the
|
||||
ladder's #90 steps. Stored as "PromptManager run: <status> prompt <id> for <file>
|
||||
(<source>)"; a file waiting for its run logs "No certain prompt for <file> yet;
|
||||
left unlinked until its run ends". `Policy.MONITOR` stores no fallback guess, so
|
||||
the only new links are inspector and recorded-run answers, which the next scan
|
||||
would make too (`tests/test_foreign_save_to_library.py`
|
||||
`TestPromptManagerRunsAskTheLadder`).
|
||||
- **The setting.** `GalleryConfig.SAVE_FOREIGN_RUNS` (`gallery.monitoring.
|
||||
save_foreign_runs`, default true, only a bool applies) is read for every file, at
|
||||
settle, at the re-check and again just before the store, together with
|
||||
|
||||
+39
-13
@@ -156,12 +156,13 @@ try:
|
||||
_global_prompt_tracker = get_prompt_tracker(_global_db)
|
||||
_global_image_monitor = get_image_monitor(_global_db, _global_prompt_tracker)
|
||||
|
||||
# The Needs review pass for ambiguous new outputs runs through the API's
|
||||
# capture store (the one the scan and the Tag dialog use): a linked output
|
||||
# is never queued and its pending items leave the queue. The package
|
||||
# teardown detaches it before that store is closed at shutdown.
|
||||
# The Needs review pass runs on the API's review worker (#659), through
|
||||
# the capture store the scan and the Tag dialog use: an output the
|
||||
# monitor leaves unlinked at its final outcome is queued as a scan would
|
||||
# queue it, and a linked one's pending items leave the queue. The package
|
||||
# teardown detaches it and stops the worker before that store is closed.
|
||||
if api is not None:
|
||||
_global_image_monitor.set_review_recorder(api.record_review_file)
|
||||
_global_image_monitor.set_review_recorder(api.queue_review_file)
|
||||
# Every settled output's preview is queued for the API's background
|
||||
# worker (#249): the workspace never asks to generate thumbnails.
|
||||
_global_image_monitor.set_thumbnail_queue(api.queue_capture_thumbnail)
|
||||
@@ -292,15 +293,26 @@ def _teardown_logger():
|
||||
return logging.getLogger("prompt_manager.init")
|
||||
|
||||
|
||||
def _stop_background_work():
|
||||
"""Stop the image monitor, the preview worker, the job worker threads
|
||||
and the prompt cleanup thread against one TEARDOWN_SECONDS deadline, once.
|
||||
def _review_worker_started(api_object):
|
||||
"""Whether the API's Needs review worker ever started (False without
|
||||
one, or when the check fails)."""
|
||||
try:
|
||||
return bool(api_object is not None and api_object.review_worker_started())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
Returns ``{"monitor", "thumbnails", "workers", "tracker"}`` booleans
|
||||
(True: it stopped), leaving out parts that never started. Later calls return a
|
||||
copy of the first result. A Ctrl+C inside a step is logged and the
|
||||
step is False; one between steps is re-raised after the result (parts
|
||||
not reached are False) is stored and the ``atexit`` entry removed.
|
||||
|
||||
def _stop_background_work():
|
||||
"""Stop the image monitor, the Needs review worker, the preview worker,
|
||||
the job worker threads and the prompt cleanup thread against one
|
||||
TEARDOWN_SECONDS deadline, once.
|
||||
|
||||
Returns ``{"monitor", "review", "thumbnails", "workers", "tracker"}``
|
||||
booleans (True: it stopped), leaving out parts that never started.
|
||||
Later calls return a copy of the first result. A Ctrl+C inside a step is
|
||||
logged and the step is False; one between steps is re-raised after the
|
||||
result (parts not reached are False) is stored and the ``atexit`` entry
|
||||
removed.
|
||||
"""
|
||||
global _background_work_result
|
||||
with _background_work_lock:
|
||||
@@ -315,8 +327,10 @@ def _stop_background_work():
|
||||
|
||||
# A part whose global is set has started; False until its step says
|
||||
# otherwise, so an interrupt between steps leaves an honest result.
|
||||
reviews = thumbnails # the API also owns the review worker (#659)
|
||||
started = (
|
||||
("monitor", monitor),
|
||||
("review", _review_worker_started(reviews) or None),
|
||||
("thumbnails", thumbnails),
|
||||
("workers", parallel.job_pool_started() or None),
|
||||
("tracker", tracker),
|
||||
@@ -349,6 +363,18 @@ def _stop_background_work():
|
||||
result["monitor"] = _teardown_step(
|
||||
"the image monitor", stop_monitor, logger
|
||||
)
|
||||
if reviews is not None:
|
||||
|
||||
def stop_reviews():
|
||||
from .py.api.review_recording import REVIEW_STOP_SECONDS
|
||||
|
||||
return reviews.stop_review_worker(left(REVIEW_STOP_SECONDS))
|
||||
|
||||
# Always stopped, so no later output starts it; reported
|
||||
# only when it ran (an image in hand may have started it).
|
||||
stopped = _teardown_step("the review worker", stop_reviews, logger)
|
||||
if "review" in result or _review_worker_started(reviews):
|
||||
result["review"] = stopped
|
||||
if thumbnails is not None:
|
||||
|
||||
def close_previews():
|
||||
|
||||
+23
-1
@@ -114,6 +114,10 @@ _PENDING_AT_STAT = (
|
||||
f"JOIN {ITEMS_TABLE} i ON i.byte_id=b.id "
|
||||
"WHERE f.locator=? AND b.size=? AND b.mtime_ns=? AND i.state='pending'"
|
||||
)
|
||||
# The newest pending item of the bytes verified at one stat (Inspect, #659).
|
||||
_NEWEST_PENDING_AT_STAT = (
|
||||
_PENDING_AT_STAT + " ORDER BY i.created_at DESC, i.rowid DESC LIMIT 1"
|
||||
)
|
||||
# Pending items of one file: the candidates a link settles.
|
||||
_PENDING_OF_LOCATOR = (
|
||||
f"SELECT i.id FROM {FILES_TABLE} f " # nosec B608
|
||||
@@ -459,6 +463,24 @@ class ReviewOperations:
|
||||
)
|
||||
return row is not None
|
||||
|
||||
def review_item_at(self, locator: str, size: int, mtime_ns: int) -> dict | None:
|
||||
"""Inspect's ``review`` facet of the bytes verified at this stat (#659).
|
||||
|
||||
``{"state": "pending", "item_id": ...}`` names the newest pending item
|
||||
(any version); otherwise ``{"state": "decided"}`` when such bytes carry
|
||||
a decided item; else None. Two indexed reads, no file access.
|
||||
"""
|
||||
_validate_locator(locator)
|
||||
conn = self.model.get_connection()
|
||||
row = conn.execute(
|
||||
_NEWEST_PENDING_AT_STAT, (locator, size, mtime_ns)
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
return {"state": "pending", "item_id": row[0]}
|
||||
if conn.execute(_DECIDED_AT, (locator, size, mtime_ns)).fetchone() is not None:
|
||||
return {"state": "decided"}
|
||||
return None
|
||||
|
||||
def review_file_linked(self, spellings) -> bool:
|
||||
"""True when a saved row links the file under any of ``spellings``."""
|
||||
with self._annotation_read() as conn:
|
||||
@@ -536,7 +558,7 @@ class ReviewOperations:
|
||||
"""Remove the pending, undecided items that offer nothing to choose.
|
||||
|
||||
``locators`` are files the caller found ambiguous without a choice
|
||||
(fewer than two candidates carry a prompt). Of their items, one leaves
|
||||
(no candidate carries a prompt). Of their items, one leaves
|
||||
the queue only when its own stored evidence offers no choice either
|
||||
(``evidence_offers_choice``) and it is still ``pending`` at revision 0
|
||||
with no decision row, the same safe delete as
|
||||
|
||||
@@ -215,22 +215,24 @@ def choosable(candidate: Any) -> bool:
|
||||
|
||||
|
||||
# An item is worth a decision only when at least this many candidates offer
|
||||
# a prompt; with fewer there is nothing to choose between (maintainer test of
|
||||
# #284/#288: 39 items whose candidates were all "unresolved").
|
||||
MIN_CHOOSABLE = 2
|
||||
# a prompt; with none there is nothing to choose (maintainer test of
|
||||
# #284/#288: 39 items whose candidates were all "unresolved"). One is enough
|
||||
# (#657 addendum D1, 2026-11-20): the other branches stay listed, disabled,
|
||||
# and the user may still leave the file unresolved.
|
||||
MIN_CHOOSABLE = 1
|
||||
|
||||
|
||||
def evidence_offers_choice(evidence: Any) -> bool:
|
||||
"""False when stored evidence provably offers nothing to choose.
|
||||
|
||||
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates. A
|
||||
limited item stores none, only ``candidate_total``; it may offer a choice
|
||||
(more than ``MAX_CANDIDATES`` prompts) unless that total is too small.
|
||||
Unlimited evidence must list ``MIN_CHOOSABLE`` choosable candidates (the
|
||||
saver anchor's one pair, #390, counts like any other). A limited item
|
||||
stores none, only ``candidate_total``; it may offer a choice unless that
|
||||
total is too small.
|
||||
"""
|
||||
if not isinstance(evidence, dict):
|
||||
return False
|
||||
# The saver anchor's one pair (#390) is a suggestion to confirm.
|
||||
needed = 1 if evidence.get("anchor") == "saver" else MIN_CHOOSABLE
|
||||
needed = MIN_CHOOSABLE
|
||||
if evidence.get("limited"):
|
||||
total = evidence.get("candidate_total")
|
||||
return type(total) is int and total >= needed
|
||||
|
||||
@@ -12,7 +12,7 @@ code. This plan proposes implementation order and acceptance gates.
|
||||
- The native Prompt Library merged in [#210](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/210) for [#208](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/208): one positive parent, saved negative variants, full selected text and a shared filtered image gallery. It does not invent chronological runs from counters or scan dates.
|
||||
- [Durable history storage](prompt-history-storage.md) records job attempts and outcomes from [#212](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/212), frozen prompt contexts from [#213](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/213), and observed run-owned output locators from [#214](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/214). Those locators do not verify file bytes or establish gallery-image associations. That association contract and the chronological execution timeline remain pending under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209).
|
||||
- [#215](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/215) brings the shell, Images and natural-height Prompt Library presentation into the approved geometry and themes while retaining their existing operations. [#216](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/216) adds the shared current-file inspector with exact generation facts, scoped provenance, raw/download evidence and loaded-collection viewer controls, including a slideshow that pauses at native video. This delivery does not establish whole-application parity, change the default entry point or constitute a release. Recorded chronological run/context browsing continues under [#209](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/209); image tagging/review, System consolidation and remaining organization capabilities continue under #196.
|
||||
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable from Overview; its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
|
||||
- Local Inspect (#249, PRs L1–L3) replaces the `#/inspect` handoff with the concept's native "Inspect a file" page: one local image or video previews inline and opens the shared viewer and full inspector on a record read entirely in the browser, with nothing uploaded, imported or stored. The legacy metadata page (`web/metadata.html`, served at `/prompt_manager/gallery.html`) stays reachable by its address and from the legacy admin page; the workspace no longer links it (#621); its capabilities map to the shared inspector, including its one-click COPY ALL summary, which is the shared inspector's "Copy settings summary" (D117, LI-4). PR L3 ([#286](https://github.com/ComfyAssets/ComfyUI_PromptManager/pull/286)) shipped that button and local roles equal to the server's resolver (`web/js/workspace/local-resolver.mjs`, TESTING.md "Local roles (#249 PR L3, decision LI-1)"). Recorded deviations D60–D66 and D117 are in [TESTING.md](../TESTING.md).
|
||||
- Collections ([#331](https://github.com/ComfyAssets/ComfyUI_PromptManager/issues/331), three PRs) adds named, hand-picked groups of images, stored in the library database by file location as favorites are: a COLLECTIONS sidebar group whose rows open Images filtered to one collection (`#/collection/<id>`) with rename and delete, Add to collection and Remove from collection in the Images selection bar, a Collections… checklist in the shared inspector for the side panel and the viewer, and saved views that keep a collection. Membership survives restarts, source reordering and System › Maintenance duplicate cleanup; no file is copied, moved or changed.
|
||||
|
||||
## Scope and compatibility
|
||||
@@ -69,14 +69,16 @@ regression coverage with mockup-only tests.
|
||||
|
||||
## GitHub and release gates
|
||||
|
||||
Extend existing required workflows: the Python 3.10–3.13 matrix on Linux,
|
||||
Windows and macOS; 85% Python coverage; formatting; frontend units and per-file
|
||||
coverage floors; vendor checks; browser workflows; real ComfyUI compatibility.
|
||||
Extend existing required workflows: the Python suite on Linux (3.12 on a pull
|
||||
request, 3.12–3.14 in the merge queue; Windows 3.12–3.14 runs in `portability.yml`
|
||||
and does not gate a merge; macOS is not tested in CI, #571); 85% Python coverage;
|
||||
formatting; frontend units and per-file coverage floors; vendor checks; browser
|
||||
workflows; real ComfyUI compatibility. Python 3.12 is the floor.
|
||||
Publish traces, screenshots, logs and coverage artifacts on failures. See
|
||||
[TESTING.md](../TESTING.md) for commands and fixture isolation requirements.
|
||||
|
||||
Every PR must map acceptance criteria to tests, report relevant checks and include
|
||||
screenshots for visual changes. All required checks must pass before merging.
|
||||
Every PR must map acceptance criteria to tests, report relevant checks and describe
|
||||
visual changes in words; never attach screenshots or other images to a PR. All required checks must pass before merging.
|
||||
Use maintainer live review at meaningful visual and host-integration milestones;
|
||||
capture discovered regressions in automated tests. Notify the maintainer when
|
||||
Python changes require a ComfyUI restart.
|
||||
|
||||
+4
-2
@@ -99,19 +99,21 @@ class PromptManager(PromptManagerBase, ComfyNodeABC):
|
||||
"prepend_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to prepend to the main prompt (connected STRING "
|
||||
"nodes will be added before the main text)"
|
||||
)
|
||||
),
|
||||
},
|
||||
),
|
||||
"append_text": (
|
||||
IO.STRING,
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"Text to append to the main prompt (connected STRING "
|
||||
"nodes will be added after the main text)"
|
||||
)
|
||||
),
|
||||
},
|
||||
),
|
||||
"save_to_library": SAVE_TO_LIBRARY_INPUT,
|
||||
|
||||
+1
-35
@@ -7,7 +7,7 @@ duplicate code in prompt_manager.py and prompt_manager_text.py.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
try:
|
||||
from .utils.logging_config import get_logger
|
||||
@@ -396,40 +396,6 @@ class PromptManagerBase:
|
||||
tags = [tag.strip() for tag in tags_string.split(",") if tag.strip()]
|
||||
return tags if tags else None
|
||||
|
||||
def _search_prompts(self, search_text: str = "") -> List[Dict[str, Any]]:
|
||||
"""Search for past prompts by text content.
|
||||
|
||||
Args:
|
||||
search_text: Text to search for in prompt database
|
||||
|
||||
Returns:
|
||||
List of matching prompt dictionaries with metadata
|
||||
"""
|
||||
try:
|
||||
if not search_text or not search_text.strip():
|
||||
return []
|
||||
|
||||
try:
|
||||
from .py.config import PromptManagerConfig
|
||||
|
||||
max_results = PromptManagerConfig.MAX_SEARCH_RESULTS
|
||||
except Exception:
|
||||
max_results = 100
|
||||
|
||||
results = self.db.search_prompts(
|
||||
text=search_text.strip(),
|
||||
category=None,
|
||||
tags=None,
|
||||
rating_min=None,
|
||||
limit=max_results,
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error searching prompts: {e}")
|
||||
return []
|
||||
|
||||
def _start_gallery_system(self):
|
||||
"""Initialize and start the gallery monitoring system."""
|
||||
try:
|
||||
|
||||
+12
-42
@@ -30,7 +30,6 @@ import asyncio
|
||||
import datetime
|
||||
import functools
|
||||
import gzip as gzip_module
|
||||
import json
|
||||
import math
|
||||
import ntpath
|
||||
import os
|
||||
@@ -41,6 +40,7 @@ from pathlib import Path
|
||||
from aiohttp import web
|
||||
from PIL import Image
|
||||
|
||||
from . import json_body as _json_body
|
||||
from .prompts import PromptRoutesMixin
|
||||
from .revalidation import revalidated_response
|
||||
from .pairs import PairRoutesMixin
|
||||
@@ -89,6 +89,7 @@ from .source_rescope import SourceRescopeMixin
|
||||
|
||||
try:
|
||||
from ...database.operations import PromptDatabase
|
||||
from ...utils.exif_text import exif_text
|
||||
from ...utils.logging_config import get_logger
|
||||
from ...utils.native_memory import release_free_memory
|
||||
from ...utils.png_text import png_text
|
||||
@@ -100,6 +101,7 @@ except ImportError:
|
||||
0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
)
|
||||
from database.operations import PromptDatabase
|
||||
from utils.exif_text import exif_text
|
||||
from utils.logging_config import get_logger
|
||||
from utils.native_memory import release_free_memory
|
||||
from utils.png_text import png_text
|
||||
@@ -212,44 +214,10 @@ def _resolve_static_file(root, filepath, allowed=STATIC_MIME_TYPES):
|
||||
|
||||
|
||||
# ── JSON request bodies ────────────────────────────────────────────────
|
||||
JSON_BODY_MAX_BYTES = 1_000_000
|
||||
_JSON_READ_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
def _json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
|
||||
|
||||
async def _read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""Read and parse a JSON object body of at most ``max_bytes``.
|
||||
|
||||
The body is read in chunks so an oversized or chunked upload is refused
|
||||
as soon as it crosses the cap rather than buffered whole.
|
||||
|
||||
Returns:
|
||||
(data, None) on success, or (None, response) where ``response`` is a
|
||||
413 (body too large) or 400 (invalid JSON, or not a JSON object).
|
||||
"""
|
||||
too_large = _json_error(f"Request body too large (max {max_bytes} bytes)", 413)
|
||||
declared = request.content_length
|
||||
if declared is not None and declared > max_bytes:
|
||||
return None, too_large
|
||||
|
||||
chunks = []
|
||||
size = 0
|
||||
async for chunk in request.content.iter_chunked(_JSON_READ_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
return None, too_large
|
||||
chunks.append(chunk)
|
||||
|
||||
try:
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
return None, _json_error("Request body must be valid JSON", 400)
|
||||
if not isinstance(data, dict):
|
||||
return None, _json_error("Request body must be a JSON object", 400)
|
||||
return data, None
|
||||
# One bounded reader (json_body.py); these names stay for the mixins and tests.
|
||||
JSON_BODY_MAX_BYTES = _json_body.JSON_BODY_MAX_BYTES
|
||||
_json_error = _json_body.json_error
|
||||
_read_json_body = _json_body.read_json_body
|
||||
|
||||
|
||||
# ── Gzip compression middleware ────────────────────────────────────────
|
||||
@@ -1018,9 +986,11 @@ class PromptManagerAPI(
|
||||
return []
|
||||
|
||||
def _extract_comfyui_metadata(self, image_path):
|
||||
"""Embedded ComfyUI metadata of an image (PNG text chunks) or a video.
|
||||
"""Embedded ComfyUI metadata of an image (PNG text, EXIF) or a video.
|
||||
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523).
|
||||
PNG text is read without decoding the pixels (``utils.png_text``, #523);
|
||||
WebP, AVIF and JPEG keep the same records as EXIF strings, read through
|
||||
``utils.exif_text``.
|
||||
|
||||
Videos go through ffprobe (see utils/video_metadata). Unreadable files
|
||||
are a warning, not an error: a scan over a large output tree meets
|
||||
@@ -1030,7 +1000,7 @@ class PromptManagerAPI(
|
||||
return read_video_metadata(image_path)
|
||||
try:
|
||||
with Image.open(image_path) as img:
|
||||
return png_text(img)
|
||||
return png_text(img) or exif_text(img)
|
||||
except Exception as e:
|
||||
self.logger.warning(
|
||||
f"Unreadable image {os.path.basename(str(image_path))}: {e}"
|
||||
|
||||
+12
-25
@@ -1699,7 +1699,8 @@ class AdminRoutesMixin:
|
||||
review (best effort, counted in ``review`` when given); one a saved
|
||||
row already links is reported ``unchanged`` and never queued. An
|
||||
ambiguous file with nothing to choose is reported ``unresolved`` and
|
||||
its pending items without a choice leave the queue.
|
||||
its pending items without a choice leave the queue. The decision is
|
||||
``review_dispatch``'s, shared with the monitor's review worker (#659).
|
||||
"""
|
||||
counts = dict.fromkeys(SCAN_COUNT_KEYS, 0)
|
||||
|
||||
@@ -1713,14 +1714,12 @@ class AdminRoutesMixin:
|
||||
if self._scan_job and self._scan_job.cancelled:
|
||||
break
|
||||
counts["processed"] += 1
|
||||
ambiguous, untraced, records = [], [], {}
|
||||
records = {}
|
||||
try:
|
||||
outcome = self._ingest_scanned_file(
|
||||
media_file,
|
||||
metadata,
|
||||
detailed=True,
|
||||
ambiguous=ambiguous,
|
||||
untraced=untraced,
|
||||
records=records,
|
||||
history=history,
|
||||
)
|
||||
@@ -1729,24 +1728,9 @@ class AdminRoutesMixin:
|
||||
counts["failed"] += 1
|
||||
note(media_file, "error")
|
||||
continue
|
||||
if ambiguous and outcome == "ambiguous":
|
||||
if self._review_file_linked(media_file, roots):
|
||||
outcome = "unchanged" # already linked: not a review case
|
||||
else:
|
||||
# The records name the item versions that count; the
|
||||
# saver anchor (#390) is checked on the captured bytes.
|
||||
self._record_scanned_review(
|
||||
media_file,
|
||||
roots,
|
||||
review,
|
||||
scanned=(records.get("canonical"), None),
|
||||
)
|
||||
elif untraced and outcome == "unresolved":
|
||||
# Untraced by the default profile: the inspection profile may
|
||||
# still offer a choice (queued for review, never linked).
|
||||
outcome = self._untraced_scan_outcome(
|
||||
media_file, roots, records.get("canonical"), review
|
||||
)
|
||||
outcome, _recorded = self.review_dispatch(
|
||||
media_file, roots, records.get("decision"), outcome, review
|
||||
)
|
||||
if outcome is None:
|
||||
note(media_file, None)
|
||||
continue
|
||||
@@ -1783,11 +1767,12 @@ class AdminRoutesMixin:
|
||||
``ambiguous`` is a list, ``media_file`` is appended to it; only a file
|
||||
that then returns ``"ambiguous"`` (nothing linked it) is a Needs
|
||||
review case. An ambiguous result with nothing to choose
|
||||
(``reviewable`` is False: fewer than two candidates carry a prompt)
|
||||
(``reviewable`` is False: no candidate carries a prompt)
|
||||
goes to ``untraced`` instead and returns ``"unresolved"`` when nothing
|
||||
links it. The parsed records of either ambiguous file go to
|
||||
``records["canonical"]`` when ``records`` is a dict. ``history`` is
|
||||
the batch's lazy recorded-history lookup.
|
||||
``records["canonical"]`` when ``records`` is a dict, and the ladder's
|
||||
``Decision`` to ``records["decision"]`` (``review_dispatch``'s input).
|
||||
``history`` is the batch's lazy recorded-history lookup.
|
||||
"""
|
||||
path = str(media_file)
|
||||
if history is None: # one file: history is still asked once
|
||||
@@ -1800,6 +1785,8 @@ class AdminRoutesMixin:
|
||||
lookup=functools.partial(history.recorded, path),
|
||||
policy=Policy.SCAN,
|
||||
)
|
||||
if records is not None:
|
||||
records["decision"] = decision
|
||||
if decision.kind in (NOT_SAVED, NOT_SAVED_WIRED):
|
||||
# Save to library off (#90): no write, recorded-run fallback or
|
||||
# Needs review item
|
||||
|
||||
+35
-1
@@ -3,7 +3,7 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
from functools import wraps
|
||||
from functools import partial, wraps
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -31,7 +31,9 @@ from .inspection_service import (
|
||||
CurrentFileChanged,
|
||||
image_tags_reader,
|
||||
inspect_current_file,
|
||||
review_reader,
|
||||
)
|
||||
from .admin import _scan_roots
|
||||
from .images import image_category_key
|
||||
|
||||
try:
|
||||
@@ -717,6 +719,37 @@ class HistoryRoutesMixin:
|
||||
)
|
||||
return OWN_CATEGORY_UNREAD
|
||||
|
||||
def _history_review(self, target) -> Callable:
|
||||
"""The ``review`` reader of a reported current file (#659, C4).
|
||||
|
||||
Located as the scan locates it (``_review_location`` over the scan
|
||||
roots, resolved like the canonical target), only when the inspector
|
||||
asks; a file under no scan root reads None. A file reached through a
|
||||
linked subfolder is keyed by its resolved path here, so an item the
|
||||
scan stored under the linked spelling is not found (None, no choice).
|
||||
A file without an item is recorded first through the review worker's
|
||||
path (#657 addendum D2). The read closes its connection, as this
|
||||
route's other reads do.
|
||||
"""
|
||||
|
||||
def read(size: int, mtime_ns: int) -> dict | None:
|
||||
roots = _scan_roots(
|
||||
[os.path.realpath(root) for root in self._get_all_output_dirs()]
|
||||
)
|
||||
located = self._review_location(target, roots)
|
||||
if located is None:
|
||||
return None
|
||||
locator = os.path.normcase(located[3])
|
||||
return review_reader(
|
||||
self.db,
|
||||
locator,
|
||||
self.logger,
|
||||
close=True,
|
||||
record=partial(self.inspect_review_file, str(target)),
|
||||
)(size, mtime_ns)
|
||||
|
||||
return read
|
||||
|
||||
async def _history_current(
|
||||
self, request: web.Request, kind: str
|
||||
) -> web.StreamResponse:
|
||||
@@ -793,6 +826,7 @@ class HistoryRoutesMixin:
|
||||
recorded=recorded_output_lookup(
|
||||
db, close=True, reference=receipt["reference"]
|
||||
),
|
||||
review=self._history_review(resolved.canonical_target),
|
||||
)
|
||||
_reauthorize_current_target(resolved, scope)
|
||||
identity = {
|
||||
|
||||
@@ -259,7 +259,8 @@ def parse_image_tag_request(data: dict):
|
||||
``filter`` (a listing query object, parse_listing_filter) may stand in for
|
||||
``targets``; the start resolves it.
|
||||
"""
|
||||
fields = _FIELDS.get(data.get("mode"))
|
||||
mode = data.get("mode")
|
||||
fields = _FIELDS.get(mode) if isinstance(mode, str) else None
|
||||
if fields is None:
|
||||
return None, bad_request('mode must be "add" or "auto"')
|
||||
fields = fields | {"filter" if "filter" in data else "targets"}
|
||||
|
||||
+32
-26
@@ -25,6 +25,7 @@ from aiohttp import web
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .jobs import MAX_OUTCOME_ROWS, THUMBNAILS_JOB_KIND
|
||||
from .json_body import BodyTooLarge, json_error, read_json_object
|
||||
from . import gallery_listing
|
||||
from .gallery_listing import (
|
||||
DISCARDED,
|
||||
@@ -56,6 +57,7 @@ from .inspection_service import (
|
||||
VIDEO_EXTENSIONS,
|
||||
image_tags_reader,
|
||||
inspect_current_file,
|
||||
review_reader,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -548,7 +550,6 @@ def _thumbnail_is_fresh(src, dst):
|
||||
MAX_GALLERY_FILES = 50_000
|
||||
MAX_BULK_LIMIT = 5_000
|
||||
MAX_JSON_BODY_BYTES = 1024 * 1024
|
||||
_READ_CHUNK = 64 * 1024
|
||||
|
||||
|
||||
# Guards the first load of an API's workspace keys (#430, _workspace_keys).
|
||||
@@ -717,36 +718,17 @@ def _workspace_cursor_key(token: str, scope: str, order: str, secret: bytes) ->
|
||||
raise ValueError("Invalid gallery cursor; refresh the gallery") from None
|
||||
|
||||
|
||||
class _BodyTooLarge(Exception):
|
||||
"""Raised when a request body exceeds MAX_JSON_BODY_BYTES."""
|
||||
|
||||
|
||||
def _json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
# The shared bounded reader, at this module's own cap.
|
||||
_BodyTooLarge = BodyTooLarge
|
||||
_json_error = json_error
|
||||
|
||||
|
||||
async def _read_json_body(request):
|
||||
"""Read a JSON object body in bounded chunks.
|
||||
"""The JSON object body, or raise _BodyTooLarge past MAX_JSON_BODY_BYTES.
|
||||
|
||||
Raises _BodyTooLarge past MAX_JSON_BODY_BYTES (declared or streamed) and
|
||||
ValueError when the body is not a JSON object.
|
||||
Raises ValueError when the body is not a JSON object.
|
||||
"""
|
||||
limit = MAX_JSON_BODY_BYTES
|
||||
if request.content_length is not None and request.content_length > limit:
|
||||
raise _BodyTooLarge()
|
||||
chunks, size = [], 0
|
||||
while True:
|
||||
chunk = await request.content.read(_READ_CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise _BodyTooLarge()
|
||||
chunks.append(chunk)
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("JSON body must be an object")
|
||||
return data
|
||||
return await read_json_object(request, MAX_JSON_BODY_BYTES)
|
||||
|
||||
|
||||
async def _json_body_or_error(request):
|
||||
@@ -4149,6 +4131,9 @@ class ImageRoutesMixin:
|
||||
roots[index], Path(relative).parts
|
||||
),
|
||||
recorded=recorded_output_lookup(self.db),
|
||||
review=self._inspection_review(
|
||||
index, outputs, roots[index], Path(relative).parts
|
||||
),
|
||||
)
|
||||
except CurrentFileChanged:
|
||||
return None
|
||||
@@ -4193,6 +4178,27 @@ class ImageRoutesMixin:
|
||||
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
|
||||
return image_tags_reader(self.db, locator, self.logger)
|
||||
|
||||
def _inspection_review(
|
||||
self, index: int, outputs: list, root: Path, parts: tuple
|
||||
) -> Callable | None:
|
||||
"""The inspector's ``review`` reader for one rooted file (#659, C4).
|
||||
|
||||
Keyed as review items are (the normcased realpath of the root joined
|
||||
with the relative path). Only an output root is a scan root; a root
|
||||
past the output folders (a LoRA root) gives None. A file without an
|
||||
item is recorded first through the review worker's path (#657 D2).
|
||||
"""
|
||||
if index >= len(outputs):
|
||||
return None
|
||||
locator = os.path.normcase(os.path.join(os.path.realpath(root), *parts))
|
||||
path = os.path.join(str(root), *parts)
|
||||
return review_reader(
|
||||
self.db,
|
||||
locator,
|
||||
self.logger,
|
||||
record=functools.partial(self.inspect_review_file, path),
|
||||
)
|
||||
|
||||
def _read_own_category(self, sources, path):
|
||||
"""One file's own category, None, or OWN_CATEGORY_UNREAD (blocking).
|
||||
|
||||
|
||||
@@ -122,6 +122,67 @@ def image_tags_reader(
|
||||
return read
|
||||
|
||||
|
||||
def review_reader(
|
||||
db: Any,
|
||||
locator: str,
|
||||
logger: Any,
|
||||
*,
|
||||
close: bool = False,
|
||||
record: Callable[[dict | None], Any] | None = None,
|
||||
) -> Callable[[int, int], dict | None]:
|
||||
"""The inspector's ``review`` reader for one file *locator* (#659, C4).
|
||||
|
||||
The returned function takes the inspection's own stable stat and answers
|
||||
the file's Needs review item at exactly that ``(size, mtime_ns)``
|
||||
(``review_item_at``): pending with its id, decided, or None. A failed
|
||||
read is None, never an error. ``close`` closes the calling thread's
|
||||
connection afterwards, for routes that close theirs (History).
|
||||
|
||||
*record*, when given, is called with the found facet when there is no
|
||||
item at that stat or a pending one (#657 addendum D2: Inspect records the
|
||||
item, or records a stale one again, through the review worker's own
|
||||
per-file path; the caller decides whether anything needs doing). The
|
||||
item is then read once more, also after a failed recording (the worker
|
||||
may have recorded it meanwhile). A recording error is logged.
|
||||
"""
|
||||
|
||||
def read(size: int, mtime_ns: int) -> dict | None:
|
||||
try:
|
||||
found = db.review_item_at(locator, size, mtime_ns)
|
||||
if record is not None and (found is None or found["state"] == "pending"):
|
||||
_record(record, found, logger)
|
||||
found = db.review_item_at(locator, size, mtime_ns)
|
||||
return found
|
||||
except Exception:
|
||||
logger.warning("Inspection review item could not be read", exc_info=True)
|
||||
return None
|
||||
finally:
|
||||
if close:
|
||||
db.model.close()
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def _record(record: Callable[[dict | None], Any], found, logger: Any) -> None:
|
||||
"""Run *record* for the *found* facet; an error is logged, not raised."""
|
||||
try:
|
||||
record(found)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Inspection could not add the file to Needs review", exc_info=True
|
||||
)
|
||||
|
||||
|
||||
def _asks_review(evidence: dict, library: dict) -> bool:
|
||||
"""Whether Inspect may offer a choice: an ambiguous role, an unlinked file."""
|
||||
prompts = evidence.get("prompts") or {}
|
||||
ambiguous = any(
|
||||
isinstance(side, dict) and side.get("status") == "ambiguous"
|
||||
for side in prompts.values()
|
||||
)
|
||||
return ambiguous and isinstance(library, dict) and library.get("status") == "none"
|
||||
|
||||
|
||||
def inspect_current_file(
|
||||
path: Path,
|
||||
*,
|
||||
@@ -130,6 +191,7 @@ def inspect_current_file(
|
||||
library: dict,
|
||||
image_tags: Callable[[int, int], dict] | None = None,
|
||||
recorded: Callable[[Path], Any] | None = None,
|
||||
review: Callable[[int, int], dict | None] | None = None,
|
||||
) -> dict:
|
||||
"""Current-file evidence read between two equal stats of *path*.
|
||||
|
||||
@@ -139,6 +201,9 @@ def inspect_current_file(
|
||||
*recorded*, when given, is asked within the same stat window for what
|
||||
recorded run history knows about *path* (``RecordedOutput`` or None: the
|
||||
save node that wrote it and the texts PromptManager recorded, #386).
|
||||
*review*, when given, is called with the same stat only when a role is
|
||||
ambiguous and ``library["status"]`` is ``none``; its answer (or None) is
|
||||
returned as ``review`` (#659).
|
||||
"""
|
||||
before = _current_file_facts(path)
|
||||
try:
|
||||
@@ -173,6 +238,12 @@ def inspect_current_file(
|
||||
recorded_saver_id=run.saver_id if run is not None else None,
|
||||
recorded_texts=run.texts if run is not None else None,
|
||||
)
|
||||
if review is not None:
|
||||
facets["review"] = (
|
||||
review(before.st_size, before.st_mtime_ns)
|
||||
if _asks_review(evidence, library)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
"file": {
|
||||
"observation": "current-file",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""The one bounded reader for JSON object request bodies.
|
||||
|
||||
The body is read in chunks, so an oversized or chunked upload is refused as
|
||||
soon as it crosses the cap rather than buffered whole. ``read_json_object``
|
||||
raises; ``read_json_body`` answers with the API's ``{"success": false}``
|
||||
envelope.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
JSON_BODY_MAX_BYTES = 1_000_000
|
||||
_READ_CHUNK = 64 * 1024
|
||||
INVALID_JSON = "Request body must be valid JSON"
|
||||
NOT_AN_OBJECT = "Request body must be a JSON object"
|
||||
|
||||
|
||||
class BodyTooLarge(Exception):
|
||||
"""The request body is longer than the reader's ``max_bytes``."""
|
||||
|
||||
|
||||
def json_error(message, status):
|
||||
return web.json_response({"success": False, "error": message}, status=status)
|
||||
|
||||
|
||||
async def read_json_object(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""The request's JSON object body of at most ``max_bytes``.
|
||||
|
||||
Raises:
|
||||
BodyTooLarge: the declared or streamed body crosses ``max_bytes``.
|
||||
ValueError: the body is not UTF-8 JSON (``INVALID_JSON``) or not a
|
||||
JSON object (``NOT_AN_OBJECT``).
|
||||
"""
|
||||
declared = request.content_length
|
||||
if declared is not None and declared > max_bytes:
|
||||
raise BodyTooLarge()
|
||||
chunks, size = [], 0
|
||||
async for chunk in request.content.iter_chunked(_READ_CHUNK):
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise BodyTooLarge()
|
||||
chunks.append(chunk)
|
||||
try:
|
||||
data = json.loads(b"".join(chunks).decode("utf-8"))
|
||||
except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
|
||||
raise ValueError(INVALID_JSON) from None
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(NOT_AN_OBJECT)
|
||||
return data
|
||||
|
||||
|
||||
async def read_json_body(request, max_bytes=JSON_BODY_MAX_BYTES):
|
||||
"""``(data, None)``, or ``(None, response)`` with a 413 or 400 refusal."""
|
||||
try:
|
||||
return await read_json_object(request, max_bytes), None
|
||||
except BodyTooLarge:
|
||||
return None, json_error(f"Request body too large (max {max_bytes} bytes)", 413)
|
||||
except ValueError as exc:
|
||||
return None, json_error(str(exc), 400)
|
||||
+76
-38
@@ -64,6 +64,36 @@ def bad_request(message):
|
||||
return web.json_response({"success": False, "error": message}, status=400)
|
||||
|
||||
|
||||
def legacy_id_error(value, name):
|
||||
"""A 400 unless *value* is an id as the legacy pages send it (#662).
|
||||
|
||||
They send a number or the text they read from the page; SQLite matches
|
||||
either against an INTEGER column. A boolean, float, list or object is no
|
||||
id (``True`` would otherwise match prompt 1).
|
||||
"""
|
||||
if type(value) is int or isinstance(value, str):
|
||||
return None
|
||||
return bad_request(f"{name} must be a prompt id")
|
||||
|
||||
|
||||
def legacy_ids_error(value):
|
||||
"""A 400 unless *value* is a list of ``legacy_id_error`` ids (#662)."""
|
||||
if not isinstance(value, list):
|
||||
return bad_request("prompt_ids must be a list")
|
||||
for item in value:
|
||||
error = legacy_id_error(item, "prompt_ids")
|
||||
if error is not None:
|
||||
return error
|
||||
return None
|
||||
|
||||
|
||||
def text_field_error(data, name):
|
||||
"""A 400 when *name* is present in *data* but is not text (#662)."""
|
||||
if data.get(name) is not None and not isinstance(data[name], str):
|
||||
return bad_request(f"{name} must be text")
|
||||
return None
|
||||
|
||||
|
||||
def tags_error(tags):
|
||||
"""A 400 response when *tags* fail ``validate_tags``, else None."""
|
||||
try:
|
||||
@@ -605,18 +635,15 @@ class PromptRoutesMixin:
|
||||
{"success": False, "error": "Tag name required"}, status=400
|
||||
)
|
||||
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
raw_name = body.get("new_name")
|
||||
if not raw_name:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "New tag name required"}, status=400
|
||||
)
|
||||
error = tags_error([raw_name])
|
||||
error = text_field_error(body, "new_name") or tags_error([raw_name])
|
||||
if error is not None:
|
||||
return error
|
||||
new_name = raw_name.strip()
|
||||
@@ -678,12 +705,9 @@ class PromptRoutesMixin:
|
||||
async def merge_tags_endpoint(self, request):
|
||||
"""Merge source tags into a target tag."""
|
||||
try:
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
body, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
source_tags = body.get("source_tags", [])
|
||||
raw_target = body.get("target_tag")
|
||||
|
||||
@@ -697,7 +721,9 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(source_tags, list):
|
||||
return bad_request("Source tags must be a list")
|
||||
error = tags_error([*source_tags, raw_target])
|
||||
error = text_field_error(body, "target_tag") or tags_error(
|
||||
[*source_tags, raw_target]
|
||||
)
|
||||
if error is not None:
|
||||
return error
|
||||
target_tag = raw_target.strip()
|
||||
@@ -851,7 +877,11 @@ class PromptRoutesMixin:
|
||||
"""Update prompt text."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is None:
|
||||
error = text_field_error(data, "text")
|
||||
if error is not None:
|
||||
return error
|
||||
new_text = (data.get("text") or "").strip()
|
||||
|
||||
if not new_text:
|
||||
@@ -905,7 +935,9 @@ class PromptRoutesMixin:
|
||||
"""Update prompt rating."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
rating = data.get("rating")
|
||||
|
||||
try:
|
||||
@@ -945,14 +977,16 @@ class PromptRoutesMixin:
|
||||
"""Add tag to prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
raw_tag = data.get("tag")
|
||||
|
||||
if not raw_tag:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Tag cannot be empty"}, status=400
|
||||
)
|
||||
error = tags_error([raw_tag])
|
||||
error = text_field_error(data, "tag") or tags_error([raw_tag])
|
||||
if error is not None:
|
||||
return error
|
||||
new_tag = raw_tag.strip()
|
||||
@@ -994,7 +1028,9 @@ class PromptRoutesMixin:
|
||||
async def add_tags_to_prompt(self, request):
|
||||
"""Add multiple tags to a single prompt."""
|
||||
try:
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
prompt_id = data.get("prompt_id")
|
||||
new_tags = data.get("tags", [])
|
||||
|
||||
@@ -1002,6 +1038,9 @@ class PromptRoutesMixin:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Prompt ID is required"}, status=400
|
||||
)
|
||||
error = legacy_id_error(prompt_id, "prompt_id")
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
if not new_tags or not isinstance(new_tags, list):
|
||||
return web.json_response(
|
||||
@@ -1063,7 +1102,11 @@ class PromptRoutesMixin:
|
||||
"""Remove tag from prompt."""
|
||||
try:
|
||||
prompt_id = int(request.match_info["prompt_id"])
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is None:
|
||||
error = text_field_error(data, "tag")
|
||||
if error is not None:
|
||||
return error
|
||||
tag_to_remove = (data.get("tag") or "").strip()
|
||||
|
||||
prompt = await self._run_in_executor(self.db.get_prompt_by_id, prompt_id)
|
||||
@@ -1103,13 +1146,18 @@ class PromptRoutesMixin:
|
||||
async def bulk_delete_prompts(self, request):
|
||||
"""Bulk delete prompts."""
|
||||
try:
|
||||
data = await request.json()
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
prompt_ids = data.get("prompt_ids", [])
|
||||
|
||||
if not prompt_ids:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "No prompt IDs provided"}, status=400
|
||||
)
|
||||
error = legacy_ids_error(prompt_ids)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
deleted_count = await self._run_in_executor(
|
||||
self.db.bulk_delete_prompts, prompt_ids
|
||||
@@ -1138,12 +1186,9 @@ class PromptRoutesMixin:
|
||||
async def bulk_add_tags(self, request):
|
||||
"""Bulk add tags to prompts."""
|
||||
try:
|
||||
try:
|
||||
data = await request.json()
|
||||
except ValueError:
|
||||
return bad_request("Invalid JSON body")
|
||||
if not isinstance(data, dict):
|
||||
return bad_request("Expected a JSON object")
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
if "expected_epoch" in data:
|
||||
return await self._bulk_library_tags(data)
|
||||
prompt_ids = data.get("prompt_ids", [])
|
||||
@@ -1156,7 +1201,7 @@ class PromptRoutesMixin:
|
||||
)
|
||||
if not isinstance(new_tags, list):
|
||||
return bad_request("Tags must be a list")
|
||||
error = tags_error(new_tags)
|
||||
error = legacy_ids_error(prompt_ids) or tags_error(new_tags)
|
||||
if error is not None:
|
||||
return error
|
||||
|
||||
@@ -1185,16 +1230,9 @@ class PromptRoutesMixin:
|
||||
async def bulk_set_category(self, request):
|
||||
"""Bulk set category for prompts."""
|
||||
try:
|
||||
try:
|
||||
data = await request.json()
|
||||
except ValueError:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
if not isinstance(data, dict):
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Expected a JSON object"}, status=400
|
||||
)
|
||||
data, error = await self._read_json_body(request)
|
||||
if error is not None:
|
||||
return error
|
||||
if "images_filter" in data:
|
||||
return await self._bulk_category_by_filter(data)
|
||||
if "expected_epoch" in data:
|
||||
|
||||
+25
-7
@@ -45,16 +45,20 @@ try:
|
||||
from ...database.review_decisions import ReviewCommandError
|
||||
from ...utils.media_capture import CaptureError
|
||||
from ...utils.review_capture import (
|
||||
candidate_hashes,
|
||||
captured_review,
|
||||
item_profile,
|
||||
review_evidence,
|
||||
)
|
||||
except ImportError:
|
||||
from database.library import display_title
|
||||
from database.library_commands import LibraryCommandError
|
||||
from database.review_decisions import ReviewCommandError
|
||||
from utils.media_capture import CaptureError
|
||||
from utils.review_capture import captured_review, item_profile, review_evidence
|
||||
from utils.review_capture import (
|
||||
candidate_hashes,
|
||||
captured_review,
|
||||
item_profile,
|
||||
)
|
||||
|
||||
ITEMS_URL = "/prompt_manager/review/items"
|
||||
DEFAULT_LIMIT = 40
|
||||
@@ -393,12 +397,13 @@ class ReviewRoutesMixin:
|
||||
"library_epoch": item["epoch"],
|
||||
**view,
|
||||
"candidates": candidates,
|
||||
"collapsed": self._review_collapsed(item),
|
||||
"dependency_fingerprint": fingerprint,
|
||||
"sha256": item["sha256"],
|
||||
"total": item["total"],
|
||||
}
|
||||
if len(json.dumps(detail).encode("utf-8")) > MAX_DETAIL_BYTES:
|
||||
detail = {**detail, "candidates": [], "limited": True}
|
||||
detail = {**detail, "candidates": [], "collapsed": None, "limited": True}
|
||||
return web.json_response(detail, headers=_NO_STORE)
|
||||
|
||||
def _review_detail(self, item_id: str):
|
||||
@@ -413,6 +418,20 @@ class ReviewRoutesMixin:
|
||||
fingerprint = self.db.review_dependency_fingerprint(image_path, aliases)
|
||||
return item, view, fingerprint, self._review_candidates(item)
|
||||
|
||||
@staticmethod
|
||||
def _review_collapsed(item: dict):
|
||||
"""#657 D3: ``{shown, total, paths}`` when the stored list keeps only
|
||||
the most used prompts of the file, else None."""
|
||||
collapsed = None if item["limited"] else item["evidence"].get("collapsed")
|
||||
if not isinstance(collapsed, dict):
|
||||
return None
|
||||
counts = {key: collapsed.get(key) for key in ("shown", "total", "paths")}
|
||||
if not all(
|
||||
isinstance(n, int) and not isinstance(n, bool) for n in counts.values()
|
||||
):
|
||||
return None
|
||||
return counts
|
||||
|
||||
def _review_candidates(self, item: dict) -> list:
|
||||
"""The detail's candidates: role texts, a label and selectability."""
|
||||
if item["limited"]:
|
||||
@@ -749,7 +768,6 @@ def _candidate_still_offered(resolution: dict, choice: str) -> bool:
|
||||
resolution = {"state": "ambiguous", "candidates": [resolution]}
|
||||
if not isinstance(resolution, dict) or resolution.get("state") != "ambiguous":
|
||||
return False
|
||||
evidence, _count, limited = review_evidence(resolution)
|
||||
if limited:
|
||||
return False
|
||||
return any(c.get("hash") == choice for c in evidence.get("candidates", ()))
|
||||
# Every candidate the bytes offer, before any bound or collapse: a
|
||||
# reorder that changes the collapsed representatives still applies.
|
||||
return choice in candidate_hashes(resolution)
|
||||
|
||||
+533
-57
@@ -6,12 +6,22 @@ final outcome is ambiguous and unlinked. The strict resolver must find it
|
||||
``graph_prompt_text``) must not link it, and no saved row may link it
|
||||
already. A file the fallback links, an exact pair the ingester stored and an
|
||||
already linked file are never queued. Neither is an ambiguous file with
|
||||
nothing to choose: fewer than two of its candidates carry a prompt
|
||||
nothing to choose: none of its candidates carries a prompt
|
||||
(``utils.review_capture.reviewable``); the scan reports it unresolved ("could
|
||||
not be traced") unless the inspection profile finds a choice in it.
|
||||
not be traced") unless the inspection profile finds a choice in it. A file
|
||||
the default profile calls unresolved gets the same inspection-profile chance
|
||||
(#659 C1). ``review_dispatch`` is that one per-file decision.
|
||||
|
||||
Only scans add items (maintainer ruling, 2026-10-23). The monitor's pass
|
||||
records nothing: it only removes the pending items of an output it linked.
|
||||
The monitor queues what the scan would (maintainer decision 2026-11-19,
|
||||
#659; it replaces the 2026-10-23 ruling that only scans add items). At a
|
||||
file's final unlinked outcome, after run history had its say, the monitor
|
||||
hands the path to ``queue_review_file``. One review worker thread runs
|
||||
``record_review_file`` for it: the scan's own per-file steps for that file
|
||||
(the ladder under the scan policy with the sealed history, the recorded-run
|
||||
check), read only, then ``review_dispatch``. It never links a file, and a
|
||||
file the scan would link is left to the next scan. The queue coalesces by
|
||||
path and is bounded; a file deferred by a job blocker is kept and replayed
|
||||
once no blocker remains.
|
||||
|
||||
The queue heals itself: a pending item whose file is now linked (by the
|
||||
fallback, a later resolution or the monitor) is removed by the next scan
|
||||
@@ -25,25 +35,38 @@ changed (``settle_linked_review_items``).
|
||||
The scan records through ``_record_scanned_review`` (best effort: a failure
|
||||
is logged and counted), which goes through
|
||||
``utils.review_capture.record_ambiguous_file`` on the API's capture store;
|
||||
the monitor calls ``record_review_file`` from its worker thread after its
|
||||
own link. Nothing here links a file.
|
||||
the review worker calls ``record_review_file``, also for an output the
|
||||
monitor linked (its pending items leave the queue). Nothing here links a
|
||||
file.
|
||||
|
||||
Recording changes records, so it follows the registry's ``records``
|
||||
admission (#289). The scan records under its own ``records`` job. The
|
||||
monitor's pass lasts one file and is not a job: it is refused while a
|
||||
``records`` or ``guarded`` job runs (``deferred``), and the next scan reads
|
||||
the file again. Thumbnail work (the job and the gallery's generate and clear
|
||||
holds, kind ``thumbnails``) is ``guarded`` but only writes and removes preview
|
||||
files under ``thumbnails/`` and never touches the database, so it does not
|
||||
defer the recording (#249 S5 M7): a long rebuild no longer holds Needs review
|
||||
back for its whole run.
|
||||
``records`` or ``guarded`` job runs (``deferred``); the review worker keeps
|
||||
the path (at most ``REVIEW_DEFERRED_LIMIT``, in memory) and replays it once
|
||||
the job registry reports no blocker. Thumbnail work (the job and the
|
||||
gallery's generate and clear holds, kind ``thumbnails``) is ``guarded`` but
|
||||
only writes and removes preview files under ``thumbnails/`` and never touches
|
||||
the database, so it does not defer the recording (#249 S5 M7): a long
|
||||
rebuild no longer holds Needs review back for its whole run.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
|
||||
from .admin import SCAN_LOG_PREFIXES, _plural, _scan_location, _scan_roots
|
||||
from .admin import (
|
||||
SCAN_LOG_PREFIXES,
|
||||
_BatchHistory,
|
||||
_file_size,
|
||||
_plural,
|
||||
_scan_location,
|
||||
_scan_roots,
|
||||
)
|
||||
from .jobs import THUMBNAILS_JOB_KIND
|
||||
|
||||
# The kind the monitor's recording checks admission under (never registered).
|
||||
@@ -56,11 +79,30 @@ NEW_OUTCOMES = ("recorded", "limited")
|
||||
|
||||
try:
|
||||
from ...utils import review_capture
|
||||
from ...utils.file_prompt import NEVER, Policy, decide_file_prompt
|
||||
from ...utils.media_capture import CaptureCapacity
|
||||
from ...utils.parallel import note_refusal, refused_at_shutdown
|
||||
from ...utils.review_capture import record_ambiguous_file
|
||||
except ImportError:
|
||||
from utils import review_capture
|
||||
from utils.file_prompt import NEVER, Policy, decide_file_prompt
|
||||
from utils.media_capture import CaptureCapacity
|
||||
from utils.parallel import note_refusal, refused_at_shutdown
|
||||
from utils.review_capture import record_ambiguous_file
|
||||
|
||||
# The review worker (#659 C5): its thread's name, the bound of paths waiting
|
||||
# for it (the oldest is dropped beyond it), the bound of paths a job blocker
|
||||
# deferred, how often it asks the job registry again while paths are
|
||||
# deferred, and how long the package teardown waits for it.
|
||||
REVIEW_WORKER_NAME = "pm-review-recorder"
|
||||
REVIEW_QUEUE_LIMIT = 4096
|
||||
REVIEW_DEFERRED_LIMIT = 1000
|
||||
REVIEW_RETRY_SECONDS = 5
|
||||
REVIEW_STOP_SECONDS = 5
|
||||
_REVIEW_WORKER_LOCK = threading.Lock()
|
||||
# Guards the untraced memory, which the scan and the review worker share.
|
||||
_UNTRACED_MEMORY_LOCK = threading.Lock()
|
||||
|
||||
# Untraced files remembered per process so a rescan of an unchanged file does
|
||||
# not run the inspection profile again (oldest forgotten first). A plain dict
|
||||
# of 16-byte digests (the locator, and its size, mtime_ns and item version):
|
||||
@@ -78,6 +120,15 @@ def _memory_key(locator: str) -> bytes:
|
||||
return _digest(locator)
|
||||
|
||||
|
||||
# Files Inspect found it cannot record (#657 review), per process: a 16-byte
|
||||
# digest of the locator, its stat and the review versions, oldest forgotten
|
||||
# first. Inspect then does not run the recording again for that state.
|
||||
MAX_INSPECT_MEMORY = 4096
|
||||
# record_review_file outcomes that record nothing for the file's current
|
||||
# state (an expected outcome, not an error): remembered by Inspect.
|
||||
UNRECORDABLE_OUTCOMES = ("skipped", "untraced")
|
||||
|
||||
|
||||
# The scan log's reason for items that leave the queue with nothing to choose.
|
||||
NOTHING_TO_CHOOSE = "nothing to choose"
|
||||
|
||||
@@ -90,6 +141,7 @@ class ReviewRecordingMixin:
|
||||
|
||||
``scanned`` is the scan's ``(metadata, inspection_resolution)``; the
|
||||
resolution is None when the scan did not run the inspection profile.
|
||||
Returns the record outcome, None when recording failed.
|
||||
"""
|
||||
try:
|
||||
outcome = self._record_review_sync(
|
||||
@@ -102,13 +154,13 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return
|
||||
if review is None:
|
||||
return
|
||||
if outcome in NEW_OUTCOMES:
|
||||
review["added"] += 1
|
||||
if outcome in QUEUED_OUTCOMES:
|
||||
review["queued"] += 1
|
||||
return None
|
||||
if review is not None:
|
||||
if outcome in NEW_OUTCOMES:
|
||||
review["added"] += 1
|
||||
if outcome in QUEUED_OUTCOMES:
|
||||
review["queued"] += 1
|
||||
return outcome
|
||||
|
||||
def _record_review_sync(
|
||||
self, media_file, roots, review=None, inspection=False, scanned=None
|
||||
@@ -137,14 +189,55 @@ class ReviewRecordingMixin:
|
||||
self._settle_untraced_reviews([media_file], roots, review)
|
||||
return outcome
|
||||
|
||||
def review_dispatch(self, media_file, roots, decision, outcome, review=None):
|
||||
"""The one per-file Needs review decision (#659): ``(scan_status,
|
||||
record_outcome)`` for a file the caller stored nothing for in this
|
||||
pass.
|
||||
|
||||
``decision`` is the scan-policy ladder's ``Decision`` (None: nothing
|
||||
to decide) and ``outcome`` the file's scan status. An ambiguous file
|
||||
with a choice is recorded unless a saved row links it
|
||||
(``unchanged``). An untraced file, or one the default profile calls
|
||||
unresolved that has a prompt graph, gets the inspection profile's
|
||||
choice and the saver anchor (``_untraced_scan_outcome``). Any other
|
||||
file keeps its status and records nothing (``record_outcome`` None).
|
||||
The scan uses ``scan_status``, the review worker ``record_outcome``.
|
||||
"""
|
||||
if decision is None:
|
||||
return outcome, None
|
||||
if decision.review == "ambiguous" and outcome == "ambiguous":
|
||||
if self._review_file_linked(media_file, roots):
|
||||
return "unchanged", None # already linked: not a review case
|
||||
# The records name the item versions that count; the saver
|
||||
# anchor (#390) is checked on the captured bytes.
|
||||
scanned = (decision.canonical, None)
|
||||
recorded = self._record_scanned_review(
|
||||
media_file, roots, review, scanned=scanned
|
||||
)
|
||||
return outcome, recorded
|
||||
untraced = decision.review == "untraced"
|
||||
unreadable = (
|
||||
decision.review is None
|
||||
and decision.default_unresolved
|
||||
and bool(decision.canonical.get("prompt"))
|
||||
)
|
||||
if outcome == "unresolved" and (untraced or unreadable):
|
||||
# The inspection profile may still offer a choice (queued for
|
||||
# review, never linked).
|
||||
return self._untraced_scan_outcome(
|
||||
media_file, roots, decision.canonical, review
|
||||
)
|
||||
return outcome, None
|
||||
|
||||
def _untraced_scan_outcome(self, media_file, roots, canonical, review=None):
|
||||
"""The scan status of an unlinked file the default profile left
|
||||
ambiguous without a choice (blocking).
|
||||
"""``(scan_status, record_outcome)`` of an unlinked file the default
|
||||
profile left ambiguous without a choice, or unresolved (blocking).
|
||||
|
||||
``ambiguous`` when the inspection profile offers a choice: the file is
|
||||
recorded for review from that profile (never linked), or ``unchanged``
|
||||
when a saved row links it already. Otherwise ``unresolved``, and its
|
||||
pending items without a choice leave the queue. The profile runs at
|
||||
when a saved row links it already. Otherwise ``unresolved``
|
||||
(``untraced``), and its pending items without a choice leave the
|
||||
queue. The profile runs at
|
||||
most once per file state: not for bytes already queued (or decided)
|
||||
at the file's current size and ``mtime_ns`` under the version that
|
||||
its records depend on, and not again for a state it already found
|
||||
@@ -160,15 +253,17 @@ class ReviewRecordingMixin:
|
||||
)
|
||||
if review is not None:
|
||||
review["errors"] += 1
|
||||
return "unresolved"
|
||||
return "unresolved", None
|
||||
if choice is None:
|
||||
self._settle_untraced_reviews([media_file], roots, review)
|
||||
self._settle_stale_reviews(media_file, roots, canonical, review)
|
||||
return "unresolved"
|
||||
return "unresolved", "untraced"
|
||||
if self._review_file_linked(media_file, roots):
|
||||
return "unchanged"
|
||||
self._record_scanned_review(media_file, roots, review, scanned=choice)
|
||||
return "ambiguous"
|
||||
return "unchanged", None
|
||||
recorded = self._record_scanned_review(
|
||||
media_file, roots, review, scanned=choice
|
||||
)
|
||||
return "ambiguous", recorded
|
||||
|
||||
def _inspection_choice(self, media_file, roots, canonical):
|
||||
"""``(canonical, resolution_or_None)`` when the file offers a choice.
|
||||
@@ -198,17 +293,21 @@ class ReviewRecordingMixin:
|
||||
return canonical, None
|
||||
memory = self._untraced_memory()
|
||||
key = _memory_key(locator)
|
||||
if state is not None and memory.get(key) == state:
|
||||
return None
|
||||
# The scan and the review worker (#659) share the memory: every
|
||||
# read and change holds its lock (the resolve below does not).
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if state is not None and memory.get(key) == state:
|
||||
return None
|
||||
resolution = review_capture.inspection_choice(canonical, media_file.name)
|
||||
if resolution is not None:
|
||||
memory.pop(key, None)
|
||||
return canonical, resolution
|
||||
if state is not None:
|
||||
memory.pop(key, None) # re-inserted last: the newest state
|
||||
memory[key] = state
|
||||
while len(memory) > MAX_UNTRACED_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if resolution is not None:
|
||||
memory.pop(key, None)
|
||||
return canonical, resolution
|
||||
if state is not None:
|
||||
memory.pop(key, None) # re-inserted last: the newest state
|
||||
memory[key] = state
|
||||
while len(memory) > MAX_UNTRACED_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
return None
|
||||
|
||||
def _settle_stale_reviews(self, media_file, roots, canonical, review=None):
|
||||
@@ -248,10 +347,11 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def _untraced_memory(self):
|
||||
memory = getattr(self, "_untraced_inspections", None)
|
||||
if memory is None:
|
||||
memory = self._untraced_inspections = {}
|
||||
return memory
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory = getattr(self, "_untraced_inspections", None)
|
||||
if memory is None:
|
||||
memory = self._untraced_inspections = {}
|
||||
return memory
|
||||
|
||||
@staticmethod
|
||||
def _review_location(media_file, roots, real_roots=None):
|
||||
@@ -310,8 +410,8 @@ class ReviewRecordingMixin:
|
||||
def _settle_untraced_reviews(self, media_files, roots, review=None):
|
||||
"""Remove the pending items without a choice of untraced ``media_files``.
|
||||
|
||||
``media_files`` are files found ambiguous with fewer than two
|
||||
candidates that carry a prompt. Blocking; best effort like the linked
|
||||
``media_files`` are files found ambiguous without a candidate that
|
||||
carries a prompt. Blocking; best effort like the linked
|
||||
settle (a failure is logged and counted in ``review["errors"]``).
|
||||
Returns how many items left.
|
||||
"""
|
||||
@@ -335,18 +435,23 @@ class ReviewRecordingMixin:
|
||||
return removed
|
||||
|
||||
def record_review_file(self, image_path):
|
||||
"""Apply the Needs review rule to one monitor output (its worker thread).
|
||||
"""Apply the Needs review rule to one monitor output (review worker).
|
||||
|
||||
Only scans add items (maintainer ruling, 2026-10-23): the monitor
|
||||
only clears the items of outputs it links. Maps ``image_path`` to the
|
||||
gallery root that lists it; a file under no current root is
|
||||
``skipped``. A linked file's pending items are removed and the answer
|
||||
is ``linked``. Any other file is ``skipped``: nothing is captured or
|
||||
recorded, and the next scan reads it. While a job runs that a
|
||||
``records`` job may not run beside, other than thumbnail work
|
||||
(``PREVIEW_ONLY_KINDS``), nothing is written and the answer is
|
||||
``deferred``. Errors propagate: the monitor logs them and keeps its
|
||||
link.
|
||||
The monitor queues what the scan would (maintainer decision
|
||||
2026-11-19, #659): it hands a file over at its final unlinked
|
||||
outcome, after run history had its say, and after each ambiguous
|
||||
output it links. Maps ``image_path`` to the gallery root that lists
|
||||
it; a file under no current root is ``skipped``. A linked file's
|
||||
pending items are removed and the answer is ``linked``. Any other
|
||||
file runs the scan's own per-file steps, read only
|
||||
(``_review_unlinked_file``): a file the scan would link, or that
|
||||
does not save, is ``skipped`` (the next scan links it); otherwise
|
||||
the answer is ``review_dispatch``'s record outcome (``recorded``,
|
||||
``duplicate``, ``decided``, ``untraced``, ``limited``) or ``skipped``.
|
||||
While a job runs that a ``records`` job may not run beside, other
|
||||
than thumbnail work (``PREVIEW_ONLY_KINDS``), nothing is written and
|
||||
the answer is ``deferred`` (the worker replays it). Errors propagate:
|
||||
the worker logs them and the monitor keeps its link.
|
||||
"""
|
||||
busy = self._jobs.blocker(
|
||||
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
|
||||
@@ -366,7 +471,166 @@ class ReviewRecordingMixin:
|
||||
if self._review_file_linked(located, roots):
|
||||
self._settle_scanned_reviews([located], roots)
|
||||
return "linked"
|
||||
return "skipped"
|
||||
return self._review_unlinked_file(located, roots)
|
||||
|
||||
def _review_unlinked_file(self, media_file, roots):
|
||||
"""The scan's per-file steps for one unlinked file, read only.
|
||||
|
||||
The metadata read the scan uses, the ladder under ``Policy.SCAN``
|
||||
with the file's recorded history, then the recorded-run check; a
|
||||
file any step would link (or whose prompt does not save) is
|
||||
``skipped``. Otherwise ``review_dispatch`` decides, and its record
|
||||
outcome is the answer (``skipped`` when it records nothing).
|
||||
"""
|
||||
path = str(media_file)
|
||||
metadata = self._extract_comfyui_metadata(path)
|
||||
history = _BatchHistory(self, [media_file])
|
||||
decision = decide_file_prompt(
|
||||
metadata,
|
||||
file_name=media_file.name,
|
||||
file_size=functools.partial(_file_size, media_file),
|
||||
in_output=False, # only the monitor policy reads it
|
||||
lookup=functools.partial(history.recorded, path),
|
||||
policy=Policy.SCAN,
|
||||
)
|
||||
if decision.kind != NEVER:
|
||||
return "skipped" # it saves nothing, or the next scan links it
|
||||
if decision.try_recorded_run and history.get(path) is not None:
|
||||
return "skipped" # the scan's recorded-run step links it
|
||||
_status, recorded = self.review_dispatch(
|
||||
media_file, roots, decision, decision.unlinked_status
|
||||
)
|
||||
return recorded or "skipped"
|
||||
|
||||
def inspect_review_file(self, image_path, found=None):
|
||||
"""Inspect's recording of one file (#657 addendum D2, blocking).
|
||||
|
||||
``found`` is the file's ``review`` facet at the inspected stat (None
|
||||
or a pending item). A pending item of a current item version needs
|
||||
nothing (``current``); one of an older version is recorded again, so
|
||||
the new item supersedes it. Otherwise ``record_review_file`` runs,
|
||||
unless Inspect already found this state unrecordable (``skipped`` or
|
||||
``untraced``, remembered in ``MAX_INSPECT_MEMORY`` digests:
|
||||
``remembered``). A busy capture store (the worker copying a fresh
|
||||
output) is expected: logged at debug level, ``busy``.
|
||||
"""
|
||||
if found is not None and self._review_item_current(
|
||||
found["item_id"], image_path
|
||||
):
|
||||
return "current"
|
||||
key = self._inspect_memory_key(image_path)
|
||||
memory = self._inspect_memory()
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
if key is not None and key in memory:
|
||||
return "remembered"
|
||||
try:
|
||||
outcome = self.record_review_file(image_path)
|
||||
except CaptureCapacity:
|
||||
self.logger.debug(
|
||||
"Inspect left Needs review to the worker: captures are busy"
|
||||
)
|
||||
return "busy"
|
||||
if key is not None and outcome in UNRECORDABLE_OUTCOMES:
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory.pop(key, None)
|
||||
memory[key] = True
|
||||
while len(memory) > MAX_INSPECT_MEMORY:
|
||||
del memory[next(iter(memory))]
|
||||
return outcome
|
||||
|
||||
def _inspected_metadata(self, image_path):
|
||||
"""The file's metadata with its prompt graph decoded (or None)."""
|
||||
metadata = self._extract_comfyui_metadata(str(image_path)) or {}
|
||||
prompt = metadata.get("prompt")
|
||||
if isinstance(prompt, str):
|
||||
try:
|
||||
metadata = {**metadata, "prompt": json.loads(prompt)}
|
||||
except (ValueError, TypeError, RecursionError):
|
||||
return None
|
||||
return metadata if isinstance(metadata.get("prompt"), dict) else None
|
||||
|
||||
def _review_item_current(self, item_id, image_path):
|
||||
"""True when the item's version is one the file is queued under now
|
||||
(the file's metadata is read only for a non-default version)."""
|
||||
item = self.db.review_item(item_id)
|
||||
if item is None:
|
||||
return False
|
||||
version = item.get("resolver_version")
|
||||
if version == review_capture.default_item_version():
|
||||
return True
|
||||
metadata = self._inspected_metadata(image_path)
|
||||
return metadata is not None and version in review_capture.item_versions(
|
||||
metadata
|
||||
)
|
||||
|
||||
def _inspect_memory_key(self, image_path):
|
||||
"""The digest of the file's locator, stat and review versions."""
|
||||
full = os.path.abspath(str(image_path))
|
||||
located = os.path.join(
|
||||
os.path.realpath(os.path.dirname(full)), os.path.basename(full)
|
||||
)
|
||||
try:
|
||||
facts = os.lstat(located)
|
||||
except OSError:
|
||||
return None
|
||||
return _digest(
|
||||
f"{os.path.normcase(located)}:{facts.st_size}:{facts.st_mtime_ns}:"
|
||||
f"{review_capture.default_item_version()}:"
|
||||
f"{review_capture.semantics_version()}"
|
||||
)
|
||||
|
||||
def _inspect_memory(self):
|
||||
with _UNTRACED_MEMORY_LOCK:
|
||||
memory = getattr(self, "_inspect_unrecordable", None)
|
||||
if memory is None:
|
||||
memory = self._inspect_unrecordable = {}
|
||||
return memory
|
||||
|
||||
def _review_worker(self):
|
||||
"""The API's one review worker, made on first use (no thread yet)."""
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
if worker is None:
|
||||
with _REVIEW_WORKER_LOCK:
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
if worker is None:
|
||||
worker = ReviewWorker(
|
||||
# Late-bound on purpose: a record_review_file
|
||||
# replaced after the worker exists still runs.
|
||||
lambda path: self.record_review_file(path),
|
||||
self._review_admitted,
|
||||
self.logger,
|
||||
)
|
||||
self._review_recorder_worker = worker
|
||||
return worker
|
||||
|
||||
def _review_admitted(self):
|
||||
"""True while no job blocks Needs review writes (any thread)."""
|
||||
busy = self._jobs.blocker(
|
||||
REVIEW_RECORDING_KIND, admission="records", compatible=PREVIEW_ONLY_KINDS
|
||||
)
|
||||
return busy is None
|
||||
|
||||
def queue_review_file(self, image_path):
|
||||
"""Queue ``image_path`` for the review worker; never blocks.
|
||||
|
||||
The monitor's review recorder (#659). Returns ``queued``, or
|
||||
``stopped`` once the worker was stopped (the next scan reads it).
|
||||
"""
|
||||
return self._review_worker().queue(str(image_path))
|
||||
|
||||
def review_worker_started(self):
|
||||
"""Whether the review worker's thread was ever started."""
|
||||
worker = getattr(self, "_review_recorder_worker", None)
|
||||
return worker is not None and worker.started
|
||||
|
||||
def stop_review_worker(self, timeout=REVIEW_STOP_SECONDS):
|
||||
"""Stop the review worker for good and join it within ``timeout``.
|
||||
|
||||
Queued and deferred paths are dropped (their count is logged; the
|
||||
next scan covers them) and later ``queue_review_file`` calls are
|
||||
refused. True when no worker thread is left running.
|
||||
"""
|
||||
return self._review_worker().stop(timeout)
|
||||
|
||||
@staticmethod
|
||||
def _log_review_items(job, review):
|
||||
@@ -398,3 +662,215 @@ class ReviewRecordingMixin:
|
||||
f"{_plural(review['errors'], 'image')} could not be added to "
|
||||
"Needs review"
|
||||
)
|
||||
|
||||
|
||||
class ReviewWorker:
|
||||
"""One daemon thread that runs ``record(path)`` for queued paths (#659 C5).
|
||||
|
||||
The queue coalesces by path (a path queued again while it waits keeps
|
||||
its place; one queued while it runs runs once more afterwards) and holds
|
||||
at most ``REVIEW_QUEUE_LIMIT`` paths, dropping the oldest with a log
|
||||
line, so ``queue`` never blocks the monitor's image worker. One thread
|
||||
means two recordings of one path never run at once. A ``deferred``
|
||||
answer keeps the path in a bounded, insertion-ordered set; the thread
|
||||
waits on its queue with a ``REVIEW_RETRY_SECONDS`` timeout and, on each
|
||||
wake, replays that set once ``admitted()`` (no job blocker) says so.
|
||||
Everything lives in memory: a restart drops it and the next scan covers
|
||||
the files. A failure of ``record`` is logged and the worker goes on.
|
||||
"""
|
||||
|
||||
def __init__(self, record, admitted, logger):
|
||||
self._record = record
|
||||
self._admitted = admitted
|
||||
self._logger = logger
|
||||
self._changed = threading.Condition()
|
||||
self._pending = OrderedDict() # key -> path
|
||||
self._deferred = OrderedDict() # key -> path
|
||||
self._in_hand = None
|
||||
self._thread = None
|
||||
self._ever_started = False
|
||||
self._stopped = False
|
||||
|
||||
@property
|
||||
def started(self):
|
||||
return self._ever_started
|
||||
|
||||
@staticmethod
|
||||
def _key(path):
|
||||
return os.path.normcase(os.path.abspath(path))
|
||||
|
||||
def queue(self, path):
|
||||
"""Queue ``path``: ``queued``, or ``stopped`` after ``stop``."""
|
||||
key = self._key(path)
|
||||
with self._changed:
|
||||
if self._stopped:
|
||||
return "stopped"
|
||||
if key in self._pending:
|
||||
return "queued"
|
||||
self._pending[key] = path
|
||||
evicted = None
|
||||
if len(self._pending) > REVIEW_QUEUE_LIMIT:
|
||||
evicted = self._pending.popitem(last=False)[1]
|
||||
if self._thread is None and not self._start():
|
||||
self._pending.pop(key, None)
|
||||
return "stopped"
|
||||
self._changed.notify_all()
|
||||
if evicted is not None:
|
||||
self._logger.info(
|
||||
"Too many outputs wait for Needs review; "
|
||||
f"{os.path.basename(evicted)} is left to the next scan"
|
||||
)
|
||||
return "queued"
|
||||
|
||||
def _start(self):
|
||||
"""Start the thread (``_changed`` held); False when refused at exit."""
|
||||
thread = threading.Thread(
|
||||
target=self._run, name=REVIEW_WORKER_NAME, daemon=True
|
||||
)
|
||||
try:
|
||||
thread.start()
|
||||
except RuntimeError as error:
|
||||
if not refused_at_shutdown(error):
|
||||
raise
|
||||
note_refusal(self._logger, "The review worker")
|
||||
self._stopped = True
|
||||
return False
|
||||
self._thread = thread
|
||||
self._ever_started = True
|
||||
return True
|
||||
|
||||
def pending_count(self):
|
||||
with self._changed:
|
||||
return len(self._pending)
|
||||
|
||||
def deferred_count(self):
|
||||
with self._changed:
|
||||
return len(self._deferred)
|
||||
|
||||
def deferred_paths(self):
|
||||
with self._changed:
|
||||
return list(self._deferred.values())
|
||||
|
||||
def wait_idle(self, timeout):
|
||||
"""True once no path waits or is in hand (deferred ones may stay)."""
|
||||
with self._changed:
|
||||
return self._changed.wait_for(
|
||||
lambda: not self._pending and self._in_hand is None, timeout
|
||||
)
|
||||
|
||||
def _run(self):
|
||||
"""The thread body: an unexpected error ends it with a log line and
|
||||
clears the handle, so the next queued output starts a new thread
|
||||
(the paths still waiting stay queued)."""
|
||||
try:
|
||||
self._loop()
|
||||
except Exception:
|
||||
self._logger.error(
|
||||
"The review worker stopped on an unexpected error; "
|
||||
"the next output starts it again",
|
||||
exc_info=True,
|
||||
)
|
||||
finally:
|
||||
with self._changed:
|
||||
if self._thread is threading.current_thread():
|
||||
self._thread = None
|
||||
self._in_hand = None
|
||||
self._changed.notify_all()
|
||||
|
||||
def _loop(self):
|
||||
while True:
|
||||
with self._changed:
|
||||
path = self._next_locked()
|
||||
if path is None:
|
||||
return
|
||||
self._in_hand = path
|
||||
outcome = None
|
||||
try:
|
||||
outcome = self._run_one(path)
|
||||
finally:
|
||||
with self._changed:
|
||||
self._in_hand = None
|
||||
if outcome == "deferred":
|
||||
dropped = self._defer_locked(path)
|
||||
else:
|
||||
dropped = None
|
||||
self._changed.notify_all()
|
||||
if dropped is not None:
|
||||
self._logger.info(
|
||||
"Too many outputs wait for a job to end before Needs review; "
|
||||
f"{os.path.basename(dropped)} is left to the next scan"
|
||||
)
|
||||
|
||||
def _next_locked(self):
|
||||
"""The next path to record, waiting for one; None once stopped."""
|
||||
while not self._stopped:
|
||||
if self._deferred and self._replay_admitted():
|
||||
for key, path in self._deferred.items():
|
||||
self._pending.setdefault(key, path)
|
||||
self._deferred.clear()
|
||||
if self._pending:
|
||||
return self._pending.popitem(last=False)[1]
|
||||
self._changed.notify_all() # idle: ``wait_idle`` may return
|
||||
# Deferred paths: ask the job registry again after a while
|
||||
self._changed.wait(REVIEW_RETRY_SECONDS if self._deferred else None)
|
||||
return None
|
||||
|
||||
def _replay_admitted(self):
|
||||
try:
|
||||
return bool(self._admitted())
|
||||
except Exception:
|
||||
self._logger.debug("Job registry check failed", exc_info=True)
|
||||
return False
|
||||
|
||||
def _run_one(self, path):
|
||||
try:
|
||||
outcome = self._record(path)
|
||||
except Exception:
|
||||
self._logger.warning(
|
||||
f"{os.path.basename(path)} could not be added to Needs review",
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
self._logger.debug(f"Needs review {outcome}: {os.path.basename(path)}")
|
||||
return outcome
|
||||
|
||||
def _defer_locked(self, path):
|
||||
"""Keep a deferred path; returns the path dropped at the cap."""
|
||||
if self._stopped:
|
||||
return None
|
||||
key = self._key(path)
|
||||
self._deferred.pop(key, None)
|
||||
self._deferred[key] = path
|
||||
if len(self._deferred) > REVIEW_DEFERRED_LIMIT:
|
||||
return self._deferred.popitem(last=False)[1]
|
||||
return None
|
||||
|
||||
def stop(self, timeout):
|
||||
"""Stop for good, drop waiting paths, join within ``timeout``.
|
||||
|
||||
True when no thread is left running. Called on the worker's own
|
||||
thread, it only signals (False).
|
||||
"""
|
||||
with self._changed:
|
||||
self._stopped = True
|
||||
dropped = len(self._pending) + len(self._deferred)
|
||||
self._pending.clear()
|
||||
self._deferred.clear()
|
||||
thread = self._thread
|
||||
self._changed.notify_all()
|
||||
if dropped:
|
||||
self._logger.info(
|
||||
f"{_plural(dropped, 'output')} left for the next scan's Needs review"
|
||||
)
|
||||
if thread is None:
|
||||
return True
|
||||
if thread is threading.current_thread():
|
||||
return False
|
||||
thread.join(max(0.0, timeout))
|
||||
if thread.is_alive():
|
||||
self._logger.warning(
|
||||
f"review worker still running after {timeout} s; "
|
||||
"it stops after the file in hand"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -388,7 +388,6 @@ class AutoThumbnailer:
|
||||
self._worker_running = False
|
||||
self._closed = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
|
||||
@property
|
||||
def failure_count(self):
|
||||
@@ -548,7 +547,6 @@ class AutoThumbnailer:
|
||||
with self._changed:
|
||||
self._worker_running = False
|
||||
self._busy = False
|
||||
self._batch = 0
|
||||
self._changed.notify_all()
|
||||
|
||||
def _drain(self):
|
||||
@@ -563,7 +561,6 @@ class AutoThumbnailer:
|
||||
workers = max(1, int(self._workers() or 1))
|
||||
take = min(len(self._queue), workers)
|
||||
batch = [self._queue.popleft() for _ in range(take)]
|
||||
self._batch = len(batch)
|
||||
self._changed.notify_all()
|
||||
try:
|
||||
# The job pool's size is the setting; a smaller batch uses
|
||||
@@ -571,7 +568,6 @@ class AutoThumbnailer:
|
||||
map_parallel(self._write_queued, batch, workers)
|
||||
finally:
|
||||
with self._changed:
|
||||
self._batch = 0
|
||||
for key, *_rest in batch:
|
||||
self._queued.discard(key)
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "promptmanager"
|
||||
description = "A powerful ComfyUI custom node that extends the standard text encoder with persistent prompt storage, advanced search capabilities, and an automatic image gallery system using SQLite."
|
||||
version = "3.7.0"
|
||||
version = "3.7.2"
|
||||
license = {file = "LICENSE"}
|
||||
requires-python = ">=3.12"
|
||||
dependencies = ["watchdog>=2.1.0", "Pillow>=10.1.0"]
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// #659 (design Part 5): Inspect's Choose prompt. A queued ambiguous file (tests/browser/workspace_review_fixture.py,
|
||||
// recorded through the scan's recorder) shows its candidates in the Images details panel; choosing one links the file
|
||||
// and takes it out of Needs review, leaving it unresolved decides it, and an item with nothing to choose sends the user
|
||||
// to Needs review.
|
||||
import { startCoverage, saveCoverage } from '../../tools/vendor/browser-coverage.mjs';
|
||||
import { test, expect } from './fixtures.mjs';
|
||||
|
||||
const images = '/prompt_manager/workspace#/images';
|
||||
const details = page => page.getByRole('complementary', { name: 'Selected image details', exact: true });
|
||||
const choice = page => details(page).getByRole('region', { name: 'Choose prompt', exact: true });
|
||||
const context = page => choice(page).getByRole('combobox', { name: 'Sampler context', exact: true });
|
||||
const toast = page => page.locator('#workspace-toast');
|
||||
const OPTIONS = ['Sampler 11 · Golden dunes at dusk / Soft negative, blur', 'Sampler 13 · Harbor lights at night / Soft negative, blur'];
|
||||
|
||||
async function seed(request, data) {
|
||||
const response = await request.post('/__test__/review/reset', { data });
|
||||
await expect(response).toBeOK();
|
||||
return response.json();
|
||||
}
|
||||
const pending = async request => (await (await request.get('/prompt_manager/review/items?limit=1')).json()).total;
|
||||
const links = async request => (await (await request.get('/__test__/review/links')).json()).links;
|
||||
|
||||
/** The Images page with `filename`'s details open (a page may already have selected it). */
|
||||
async function inspect(page, filename) {
|
||||
await page.goto(images);
|
||||
const card = page.locator('article[data-image-key]').filter({ hasText: filename });
|
||||
await card.getByRole('button', { name: `Inspect ${filename}`, exact: true }).click();
|
||||
await expect(details(page).locator('.detail-inner > p.small').first()).toHaveText(filename);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page, browserName }) => {
|
||||
await startCoverage(page, browserName);
|
||||
page.choiceErrors = [];
|
||||
page.on('pageerror', error => page.choiceErrors.push(error.message));
|
||||
});
|
||||
test.afterEach(async ({ page, browserName, request }) => {
|
||||
await saveCoverage(page, browserName);
|
||||
expect(page.choiceErrors).toEqual([]);
|
||||
await request.post('/__test__/jobs/restart');
|
||||
});
|
||||
|
||||
test('choosing a candidate in Inspect links the file and takes it out of Needs review', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
expect(await pending(request)).toBe(1);
|
||||
await inspect(page, 'review_0000.png');
|
||||
// The section follows the file's own prompt blocks.
|
||||
await expect(choice(page)).toBeVisible();
|
||||
await expect(details(page).locator('.detail-inner > .inspect-choice')).toHaveCount(1);
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Golden dunes at dusk');
|
||||
await context(page).selectOption({ label: OPTIONS[1] });
|
||||
await expect(choice(page).locator('.prompt-section.positive .prompt-text')).toHaveText('Harbor lights at night');
|
||||
await expect(choice(page).locator('.prompt-section.negative .prompt-text')).toHaveText('Soft negative, blur');
|
||||
await expect(choice(page).getByRole('button', { name: 'Copy chosen positive prompt', exact: true })).toBeVisible();
|
||||
await expect(choice(page).getByRole('button', { name: 'Send chosen positive prompt to ComfyUI', exact: true })).toBeVisible();
|
||||
|
||||
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
|
||||
const reread = page.waitForResponse(response => response.url().includes('/prompt_manager/images/inspect/') && response.ok());
|
||||
await choice(page).getByRole('button', { name: 'Use this prompt', exact: true }).click();
|
||||
expect((await decided).status()).toBe(200);
|
||||
await reread;
|
||||
await expect(toast(page)).toHaveText('Association accepted.');
|
||||
// The inspection is read again: the file is linked, so the section is gone and Prompt history opens its prompt.
|
||||
await expect(choice(page)).toHaveCount(0);
|
||||
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toBeVisible();
|
||||
expect(await pending(request)).toBe(0);
|
||||
expect((await links(request)).map(row => [row.filename, row.prompt])).toEqual([['review_0000.png', 'Harbor lights at night']]);
|
||||
|
||||
await page.goto('/prompt_manager/workspace#/review');
|
||||
await expect(page.locator('#workspace-main .notice h2')).toHaveText('No images need a decision');
|
||||
});
|
||||
|
||||
test('Leave unresolved in Inspect decides the item and links nothing', async ({ page, request }) => {
|
||||
await seed(request, { items: 2 });
|
||||
await inspect(page, 'review_0001.png');
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
const decided = page.waitForResponse(response => /\/review\/items\/[^/]+\/decision$/.test(response.url()));
|
||||
await choice(page).getByRole('button', { name: 'Leave unresolved', exact: true }).click();
|
||||
expect((await decided).status()).toBe(200);
|
||||
await expect(toast(page)).toHaveText('Left unresolved.');
|
||||
// The item is decided: the section is gone and the file stays unlinked.
|
||||
await expect(choice(page)).toHaveCount(0);
|
||||
await expect(details(page).getByRole('button', { name: 'Prompt history', exact: true })).toHaveCount(0);
|
||||
expect(await pending(request)).toBe(1);
|
||||
expect(await links(request)).toEqual([]);
|
||||
});
|
||||
|
||||
test('an item with nothing to choose offers Open in Needs review', async ({ page, request }) => {
|
||||
await seed(request, { items: 0, limited: true });
|
||||
await inspect(page, 'limited.png');
|
||||
await expect(choice(page)).toContainText('None of the possible prompts can be applied here. Decide this image in Needs review.');
|
||||
await expect(context(page)).toBeHidden();
|
||||
await expect(choice(page).getByRole('button', { name: 'Use this prompt', exact: true })).toBeHidden();
|
||||
await choice(page).getByRole('button', { name: 'Open in Needs review', exact: true }).click();
|
||||
await expect(page).toHaveURL(/#\/review$/);
|
||||
await expect(page.locator('#workspace-main .notice h2')).toHaveText('1 image needs a decision');
|
||||
});
|
||||
|
||||
test('the viewer details show the same Choose prompt', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
await page.goto(images);
|
||||
const card = page.locator('article[data-image-key]').filter({ hasText: 'review_0000.png' });
|
||||
await card.getByRole('button', { name: 'Open review_0000.png', exact: true }).click();
|
||||
const viewer = page.locator('#viewer-dialog');
|
||||
await expect(viewer).toBeVisible();
|
||||
const section = viewer.getByRole('region', { name: 'Choose prompt', exact: true });
|
||||
await expect(section.getByRole('combobox', { name: 'Sampler context', exact: true }).locator('option')).toHaveText(OPTIONS);
|
||||
// Open in Needs review is offered only when nothing can be chosen.
|
||||
await expect(section.getByRole('button', { name: 'Open in Needs review', exact: true })).toBeHidden();
|
||||
});
|
||||
|
||||
test('#657 D3: Choose prompt says when the file\'s prompts were shortened to the most used', async ({ page, request }) => {
|
||||
await seed(request, { items: 1 });
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
await route.fulfill({ response, json: { ...(await response.json()), collapsed: { shown: 2, total: 81, paths: 165 } } });
|
||||
});
|
||||
await inspect(page, 'review_0000.png');
|
||||
await expect(context(page).locator('option')).toHaveText(OPTIONS);
|
||||
await expect(choice(page).locator('.review-collapsed')).toHaveText('Showing the 2 most used of 81 prompts in this file.');
|
||||
});
|
||||
@@ -21,7 +21,7 @@ export function mapLibraryConcept(reference) {
|
||||
// Save view is the concept's own (saved views, #249 D16 retired).
|
||||
const toolbar={...library.toolbar};
|
||||
toolbar.items=toolbar.items.map(item=>{
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D205
|
||||
// D14: the Library appends its Oldest first after the concept's sorts; D153 (#447) drops "Highest rated"; D206
|
||||
// (#620) appends the old Dashboard's three sorts.
|
||||
if(item.id==='sort')return {...item,options:[...item.options.filter(option=>option!=='Highest rated'),'Oldest first','Recently used','Most used','Name Z–A']};
|
||||
// D36: the category list is the Library's real list, sorted alphabetically; the concept lists prompt order.
|
||||
|
||||
@@ -102,11 +102,16 @@ test('inspection failures retry and a delayed previous selection cannot replace
|
||||
release();await expect(role(details(page),'Positive')).toContainText('Dog landscape');
|
||||
});
|
||||
|
||||
test('sender requires explicit destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
|
||||
test('sender chooses the only destination, previews full changes and acknowledges only the applied pair',async({page,context},testInfo)=>{
|
||||
const host=await fakeHost(context,page);
|
||||
try {
|
||||
await page.goto(workspace);await select(page,'0:shared/same.png');await details(page).getByRole('button',{name:/^Send prompt pair to ComfyUI: /}).click();
|
||||
const sender=dialog(page);await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeDisabled();
|
||||
const sender=dialog(page);
|
||||
// "One eligible node selects that node" (TESTING.md, D173); wait for discovery's
|
||||
// answer, since Apply is disabled only while the sender is still looking for windows.
|
||||
await expect(sender).toContainText('Sending to #pair-1 My prompt pair in Test ComfyUI.');
|
||||
await expect(sender.getByRole('button',{name:'Apply to ComfyUI',exact:true})).toBeEnabled();
|
||||
expect(await host.evaluate(()=>window.applied)).toEqual([]);
|
||||
const chosen=await chooseDestination(page);await chosen.getByRole('button',{name:'Preview changes',exact:true}).click();
|
||||
for(const text of ['Existing positive','Existing negative','Cat portrait','blurry, watermark','trigger Cat portrait detail'])await expect(chosen).toContainText(text);
|
||||
expect(await host.evaluate(()=>window.applied)).toEqual([]);
|
||||
|
||||
@@ -565,9 +565,11 @@ test('URLs and media end with their owning session', async ({ page }) => {
|
||||
// Replacement.
|
||||
await choose(page, parityPng('f02.png'));
|
||||
await expect(preview(page).locator('img.local-file-preview')).toBeVisible();
|
||||
// #653: a video still starting (inline, or in the viewer the selection opened) is held until it settles or
|
||||
// STARTING_VIDEO_MS (15 s) passes, so its release can follow the new preview: wait for it, never check once.
|
||||
let state = await urls(page);
|
||||
expect(state.revoked).toEqual([state.created[0]]);
|
||||
expect(await page.evaluate(() => window.__loads)).toBeGreaterThanOrEqual(1);
|
||||
await expect.poll(async () => (await urls(page)).revoked, { timeout: 20000 }).toEqual([state.created[0]]);
|
||||
await expect.poll(() => page.evaluate(() => window.__loads), { timeout: 20000 }).toBeGreaterThanOrEqual(1);
|
||||
// Route change, from the page (D155: the selection opened the viewer, which makes the sidebar inert).
|
||||
await closeOpened(page);
|
||||
await page.locator('aside.sidebar nav').getByRole('link', { name: 'Overview', exact: true }).click();
|
||||
|
||||
@@ -269,15 +269,77 @@ test('an empty queue shows the empty notice only', async ({ page, request }) =>
|
||||
await expect(reviewRow(page)).toHaveText('Needs review0');
|
||||
});
|
||||
|
||||
test('load more appends the next page', async ({ page, request }) => {
|
||||
const continuation = page => main(page).locator('.infinite-continuation');
|
||||
const scrollToContinuation = page => continuation(page).evaluate(node => node.scrollIntoView({ block: 'end' }));
|
||||
|
||||
test('#657 D5: scrolling to the end of the queue loads the next page', async ({ page, request }) => {
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images · more load as you scroll');
|
||||
// Scrolling does the work, so there is no button.
|
||||
await expect(continuation(page).getByRole('button')).toHaveCount(0);
|
||||
await scrollToContinuation(page);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
expect(reads.filter(read => read === 'more')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('#657 D5: a page that could not be read says so, and Retry reads it', async ({ page, request }) => {
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
let failing = true;
|
||||
await page.route(url => url.pathname === '/prompt_manager/review/items' && url.searchParams.has('cursor'),
|
||||
route => (failing ? route.fulfill({ status: 500, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, error: 'Internal error' }) }) : route.continue()));
|
||||
const failed = page.waitForResponse(item => item.url().includes('cursor=') && item.status() === 500);
|
||||
await scrollToContinuation(page);
|
||||
await failed;
|
||||
await expect(continuation(page).locator('p')).toHaveText('More items could not be loaded. Try again.');
|
||||
const retry = continuation(page).getByRole('button', { name: 'Retry', exact: true });
|
||||
await expect(retry).toBeVisible();
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
failing = false;
|
||||
await retry.click();
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
const frames = page => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
|
||||
test('#657 D5: nothing loads behind an open dialog; closing it loads the page in view', async ({ page, request }) => {
|
||||
// Two columns, so Link to a prompt… sits in the sticky panel beside the queue. At one column (touch) the panel
|
||||
// follows the queue just above the continuation: bringing Link into view there loads the next page by itself.
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await linkButton(page).scrollIntoViewIfNeeded();
|
||||
await frames(page);
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
|
||||
await linkButton(page).click();
|
||||
await expect(linkDialog(page)).toBeVisible();
|
||||
await scrollToContinuation(page);
|
||||
// Two frames: the observer's callback and the load it would schedule.
|
||||
await frames(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
expect(reads).not.toContain('more');
|
||||
await linkDialog(page).getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(linkDialog(page)).toHaveCount(0);
|
||||
// The continuation is still in view, where the observer stays silent: closing the dialog loads the page.
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
});
|
||||
|
||||
test('#657 D5: without IntersectionObserver, Load more pages the queue', async ({ page, request }) => {
|
||||
await page.addInitScript(() => { delete window.IntersectionObserver; });
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
const continuation = main(page).locator('.infinite-continuation');
|
||||
await expect(continuation.locator('p')).toHaveText('40 of 45 images');
|
||||
await continuation.getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await expect(continuation(page).locator('p')).toHaveText('40 of 45 images');
|
||||
await continuation(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await expect(continuation).toHaveCount(0);
|
||||
await expect(continuation(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('a scan job with review items offers Review metadata in Activity', async ({ page, request }) => {
|
||||
@@ -581,7 +643,7 @@ test('a live re-read keeps the loaded depth and the scroll position', async ({ p
|
||||
await seed(request, 45);
|
||||
await open(page);
|
||||
await expect.poll(async () => (await streams(request)).streams).toBe(1);
|
||||
await main(page).getByRole('button', { name: 'Load more images', exact: true }).click();
|
||||
await scrollToContinuation(page);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
await cards(page).last().scrollIntoViewIfNeeded();
|
||||
const scrollTop = () => cards(page).first().evaluate(node => {
|
||||
@@ -683,3 +745,151 @@ test('#536: a refused link stays in the dialog with the server\'s sentence', asy
|
||||
expect(await pending(request)).toBe(1);
|
||||
expect(await links(request)).toEqual([]);
|
||||
});
|
||||
|
||||
test('#657 D4: Link to a prompt first lists the image\'s own prompts, and choosing one applies it', async ({ page, request }) => {
|
||||
await seed(request, 2);
|
||||
await open(page);
|
||||
const harborHash = await context(page).locator('option', { hasText: 'Harbor lights at night' }).getAttribute('value');
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
await expect(dialog.locator('.review-link-heading')).toHaveText(['From this image', 'Library']);
|
||||
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur',
|
||||
'Harbor lights at night / Soft negative, blur']);
|
||||
// Typing searches the Library only; an empty box lists the image's prompts again.
|
||||
const search = dialog.getByRole('searchbox');
|
||||
await search.fill('zzz');
|
||||
await expect(own).toBeHidden();
|
||||
await expect(dialog.getByRole('status').first()).toHaveText('No prompt in the Library matches.');
|
||||
await search.fill('');
|
||||
await expect(own).toBeVisible();
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
const harbor = own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true });
|
||||
await harbor.click();
|
||||
await expect(harbor).toHaveAttribute('aria-pressed', 'true');
|
||||
// The candidate carries its own negative.
|
||||
await expect(dialog.getByRole('combobox', { name: 'Negative prompt', exact: true })).toBeHidden();
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const decided = page.waitForResponse(item => /\/review\/items\/[^/]+\/decision$/.test(item.url()));
|
||||
await submit.click();
|
||||
const response = await decided;
|
||||
expect(response.status()).toBe(200);
|
||||
expect(response.request().postDataJSON().choice).toBe(harborHash);
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await expect(toast(page)).toHaveText('Association accepted.');
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
expect(await links(request)).toEqual([{ filename: 'review_0000.png', prompt: 'Harbor lights at night',
|
||||
pair_id: expect.any(Number), positive: 'Harbor lights at night', negative: 'Soft negative, blur' }]);
|
||||
});
|
||||
|
||||
test('#657 D4: a refused candidate stays in the dialog with the server\'s sentence', async ({ page, request }) => {
|
||||
await seed(request, 1);
|
||||
await open(page);
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
await dialog.getByRole('group', { name: 'From this image', exact: true }).getByRole('button').first().click();
|
||||
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, code: 'association-conflict', error: 'This image is already linked.' }) }));
|
||||
await dialog.getByRole('button', { name: 'Link image', exact: true }).click();
|
||||
await expect(dialog.locator('.warning-note')).toHaveText('This image is already linked.');
|
||||
await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(await pending(request)).toBe(1);
|
||||
});
|
||||
|
||||
test('#657 D3: a file whose prompts were shortened to the most used says so', async ({ page, request }) => {
|
||||
await seed(request, 2);
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
const body = await response.json();
|
||||
const collapsed = body.filename === 'review_0000.png' ? { shown: 2, total: 81, paths: 165 } : null;
|
||||
await route.fulfill({ response, json: { ...body, collapsed } });
|
||||
});
|
||||
await open(page);
|
||||
const line = panel(page).locator('.review-collapsed');
|
||||
await expect(line).toHaveText('Showing the 2 most used of 81 prompts in this file.');
|
||||
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
await expect(line).toBeHidden();
|
||||
});
|
||||
|
||||
test('#657 D4: typing drops a choice from the image; Link waits for a Library prompt and links it', async ({ page, request }) => {
|
||||
await seed(request, 1, { unreadable: true });
|
||||
await open(page);
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0000.png');
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const search = dialog.getByRole('searchbox');
|
||||
await search.fill('harbor');
|
||||
await expect(own).toBeHidden();
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
// An empty box lists the image's prompts again, none chosen.
|
||||
await search.fill('');
|
||||
await expect(own).toBeVisible();
|
||||
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
await search.fill('harbor');
|
||||
await dialog.getByRole('button', { name: 'Quiet harbor', exact: true }).click();
|
||||
await dialog.getByRole('combobox', { name: 'Negative prompt', exact: true }).selectOption({ label: 'grainy' });
|
||||
await expect(submit).not.toHaveAttribute('aria-disabled', 'true');
|
||||
const sent = page.waitForRequest(item => /\/review\/items\/[^/]+\/(link|decision)$/.test(item.url()));
|
||||
await submit.click();
|
||||
const sentRequest = await sent;
|
||||
expect(sentRequest.url()).toMatch(/\/link$/);
|
||||
expect(sentRequest.postDataJSON()).toEqual(expect.objectContaining({ positive_id: expect.any(Number), pair_id: expect.any(Number) }));
|
||||
await expect(toast(page)).toHaveText('Linked to Quiet harbor.');
|
||||
const link = (await links(request)).find(row => row.filename === 'review_0000.png');
|
||||
expect([link.positive, link.negative]).toEqual(['Quiet harbor', 'grainy']);
|
||||
});
|
||||
|
||||
test('#657 D5: at one column, Info brings the panel into view without loading more until the reader moves', async ({ page, request }) => {
|
||||
await page.setViewportSize({ width: 420, height: 900 });
|
||||
await seed(request, 45);
|
||||
const reads = reviewReads(page);
|
||||
await open(page);
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
// The first cards are in view and the continuation, past the queue and the panel, is far away.
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top > window.innerHeight + 250)).toBe(true);
|
||||
await cards(page).nth(1).getByRole('button', { name: 'Inspect review_0001.png', exact: true }).click();
|
||||
await expect(panel(page).locator('p.small')).toHaveText('review_0001.png');
|
||||
await expect(panel(page)).toBeInViewport();
|
||||
// The continuation is near, but the panel stays put: two frames for the observer and the load it would schedule.
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
expect(await continuation(page).evaluate(node => node.getBoundingClientRect().top <= window.innerHeight + 250)).toBe(true);
|
||||
expect(reads).not.toContain('more');
|
||||
await expect(cards(page)).toHaveCount(40);
|
||||
// The reader's next move releases it.
|
||||
await page.mouse.wheel(0, 200);
|
||||
await expect(cards(page)).toHaveCount(45);
|
||||
});
|
||||
|
||||
test('#657 D4: a re-read that no longer offers the chosen image prompt drops it from the dialog', async ({ page, request }) => {
|
||||
await seed(request, 1);
|
||||
await open(page);
|
||||
await linkButton(page).click();
|
||||
const dialog = linkDialog(page);
|
||||
const own = dialog.getByRole('group', { name: 'From this image', exact: true });
|
||||
await own.getByRole('button', { name: 'Harbor lights at night / Soft negative, blur', exact: true }).click();
|
||||
// The decision is refused as stale, so the item is read again, and this time its Harbor path cannot be applied.
|
||||
await page.route(/\/decision$/, route => route.fulfill({ status: 409, contentType: 'application/json',
|
||||
body: JSON.stringify({ success: false, code: 'review-conflict', error: 'This item changed. Choose again.' }) }));
|
||||
await page.route(url => /\/prompt_manager\/review\/items\/[0-9a-f-]{36}$/.test(url.pathname), async route => {
|
||||
const response = await route.fetch();
|
||||
const body = await response.json();
|
||||
const candidates = body.candidates.map(candidate => (candidate.positive?.text === 'Harbor lights at night'
|
||||
? { ...candidate, state: 'unresolved', reason: 'Text is decided at run time' } : candidate));
|
||||
await route.fulfill({ response, json: { ...body, candidates } });
|
||||
});
|
||||
const submit = dialog.getByRole('button', { name: 'Link image', exact: true });
|
||||
await submit.click();
|
||||
await expect(own.getByRole('button')).toHaveText(['Golden dunes at dusk / Soft negative, blur']);
|
||||
await expect(own.locator('button[aria-pressed="true"]')).toHaveCount(0);
|
||||
await expect(submit).toHaveAttribute('aria-disabled', 'true');
|
||||
await expect(dialog.locator('.warning-note')).toHaveText('This item changed. Choose again.');
|
||||
expect(await pending(request)).toBe(1);
|
||||
});
|
||||
|
||||
@@ -15,8 +15,9 @@ after the plain ones in this order:
|
||||
- ``conflict``: an item whose file was linked to another prompt ("Misty
|
||||
forest path") after it was queued (the next scan or monitor pass would
|
||||
remove the item); applying a sampler path then conflicts with that link.
|
||||
- ``limited``: a graph of 17 samplers, each with its own prompt, which the
|
||||
recorder stores ``limited`` (more than 16 candidates, so none are stored).
|
||||
- ``limited``: an item recorded while its evidence is over the 8 MiB bound
|
||||
(simulated), so the recorder stores it ``limited`` without candidates.
|
||||
More than 16 candidates are collapsed instead (#657 addendum D3).
|
||||
An A1111 block with two negative lines is not queued any more: it offers
|
||||
no candidate to choose (#284).
|
||||
- ``unreadable`` (#536): an item whose stored candidates are all
|
||||
@@ -79,8 +80,6 @@ CONCEPT_POSITIVE = (
|
||||
"mountain peaks, cinematic composition, atmospheric mist, fine detail"
|
||||
)
|
||||
CONCEPT_NEGATIVE = "blurry, low quality, low resolution"
|
||||
# More candidates than an item stores (16): the ``limited`` item.
|
||||
LIMITED_SAMPLERS = 17
|
||||
# More than one queue page (40), so Load more has a second page.
|
||||
MAX_ITEMS = 45
|
||||
_TABLES = (
|
||||
@@ -210,6 +209,23 @@ def _linked_after_queueing(api: PromptManagerAPI, path: Path) -> None:
|
||||
api.db.link_image_to_prompt(prompt_id, str(path))
|
||||
|
||||
|
||||
def _limited(api: PromptManagerAPI, path: Path) -> None:
|
||||
"""Record ``path`` as if its evidence were over the 8 MiB bound."""
|
||||
from unittest.mock import patch
|
||||
|
||||
from utils import review_capture
|
||||
|
||||
real = review_capture.canonical_evidence
|
||||
|
||||
def capped(value):
|
||||
if value.get("candidates"):
|
||||
raise ValueError("Review evidence is larger than 8 MiB")
|
||||
return real(value)
|
||||
|
||||
with patch.object(review_capture, "canonical_evidence", side_effect=capped):
|
||||
_record(api, path, "limited")
|
||||
|
||||
|
||||
def _unavailable(api: PromptManagerAPI, root: Path, path: Path) -> None:
|
||||
from py.config import GalleryConfig
|
||||
|
||||
@@ -296,9 +312,8 @@ def seed_review(
|
||||
_png(path, (70, 40, 120))
|
||||
_unreadable(api, path)
|
||||
elif kind == "limited":
|
||||
many = tuple(f"{POSITIVES[0]} {n}" for n in range(LIMITED_SAMPLERS))
|
||||
_png(path, (90, 90, 90), graph=_graph(positives=many))
|
||||
_record(api, path, "limited")
|
||||
_png(path, (90, 90, 90))
|
||||
_limited(api, path)
|
||||
else:
|
||||
_png(path, (20, 140, 90))
|
||||
_unavailable(api, root, path)
|
||||
|
||||
+1
-1
@@ -935,7 +935,7 @@
|
||||
"reason_code": "multistage-differs",
|
||||
"selection": null,
|
||||
"positive": null,
|
||||
"negative": null,
|
||||
"negative": "blurry, lowres",
|
||||
"candidate_count": 0,
|
||||
"facts": {
|
||||
"seed": {
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -289,3 +289,19 @@ test('a fallback after a re-render returns focus to the same-role copy button, n
|
||||
const {fallbacks,copy,current}=await copyWithClipboard({writeText:async()=>{throw new Error('Denied');}},{detach:true});
|
||||
assert.equal(fallbacks.length,1);assert.notEqual(current,copy);assert.equal(fallbacks[0].trigger,current);
|
||||
});
|
||||
// #658: an ambiguous file whose candidates share one role shows that role resolved; the other keeps the ambiguous
|
||||
// line. The shared role has Copy and Send; the pair action needs both roles, so it is absent.
|
||||
test('one shared role beside an ambiguous one has its own actions and no pair action',()=>{
|
||||
const f=dom(),scope=createScope(),container=new f.Element('div'),sent=[];
|
||||
try{
|
||||
module.mountPromptBlocks(container,{parentScope:scope,sender:{open:roles=>sent.push(roles)},
|
||||
prompts:{positive:{status:'ambiguous',text:null,source:null},negative:{status:'resolved',text:'shared negative',source:'graph-inferred'}}});
|
||||
assert.deepEqual(statusLines(f,container),['Multiple possible prompts. Source could not be determined.']);
|
||||
assert.equal(f.walk(container,node=>node.dataset.sendRole==='pair').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.sendRole==='positive').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.copyRole==='positive').length,0);
|
||||
assert.equal(f.walk(container,node=>node.dataset.copyRole==='negative').length,1);
|
||||
const send=f.walk(container,node=>node.dataset.sendRole==='negative')[0];container.click(send);
|
||||
assert.deepEqual(sent,[{negative:'shared negative'}]);
|
||||
}finally{scope.dispose();f.restore();}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Run with: node --test tests/js/workspace-file-inspector-choice.test.js
|
||||
// #659: the inspector mounts Choose prompt after its prompt blocks while the file's review item is pending.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mountedDom } from './helpers/mounted-dom.mjs';
|
||||
|
||||
const { createScope } = await import('../../web/js/shared/toolkit/core.js');
|
||||
const { mountFileInspector } = await import('../../web/js/workspace/file-inspector.mjs');
|
||||
|
||||
const ITEM = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const OTHER = '0a1b2c3d-0000-4000-8000-00000000ffff';
|
||||
const EPOCH = '11111111-1111-4111-8111-111111111111';
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function settle(times = 8) { for (let i = 0; i < times; i++) await flush(); }
|
||||
|
||||
function record(review) {
|
||||
return {
|
||||
identity: { kind: 'rooted-file', key: '0:a.png', root_index: 0, path: 'a.png', root_scope: 'a'.repeat(64) },
|
||||
file: { format: 'PNG' }, download: null, preview: null, historyTarget: null, imageTags: null, metadata: null,
|
||||
prompts: { positive: { status: 'ambiguous', text: null, source: null }, negative: { status: 'ambiguous', text: null, source: null } },
|
||||
generation: {}, library: { status: 'none', tags: [] }, review,
|
||||
};
|
||||
}
|
||||
function detail(id) {
|
||||
return {
|
||||
success: true, library_epoch: EPOCH, id, state: 'pending', revision: 0, filename: 'a.png',
|
||||
target: { root_index: 0, root_scope: 'c'.repeat(64), path: 'a.png' }, unavailable: false, limited: false,
|
||||
candidate_count: 2, total: 1, sha256: 'd'.repeat(64), dependency_fingerprint: 'e'.repeat(64),
|
||||
candidates: [
|
||||
{ hash: 'a'.repeat(64), sampler_id: '11', state: 'resolved', reason: '', label: 'Dunes / blur', positive: { text: 'dunes' }, negative: { text: 'blur' } },
|
||||
{ hash: 'b'.repeat(64), sampler_id: '13', state: 'resolved', reason: '', label: 'Harbor / blur', positive: { text: 'harbor' }, negative: { text: 'blur' } },
|
||||
],
|
||||
};
|
||||
}
|
||||
function fakeApi() {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
api: {
|
||||
get: url => { calls.push(['GET', url]); return Promise.resolve(detail(url.split('/').at(-1))); },
|
||||
post: url => {
|
||||
calls.push(['POST', url]);
|
||||
return Promise.resolve(url.endsWith('/observe') ? { library_epoch: EPOCH, capture: { token: 't', sha256: 'd'.repeat(64) } }
|
||||
: { success: true, library_epoch: EPOCH, total: 0 });
|
||||
},
|
||||
del: () => Promise.resolve({}),
|
||||
},
|
||||
};
|
||||
}
|
||||
function mount(options = {}) {
|
||||
const f = mountedDom();
|
||||
f.doc.getElementById = () => null;
|
||||
const scope = createScope(), decided = [], { api, calls } = fakeApi();
|
||||
const view = mountFileInspector(f.container, { api, sender: { open() {} }, parentScope: scope, variant: 'panel',
|
||||
onReviewDecided: () => decided.push(true), ...options });
|
||||
const sections = () => f.walk(f.container, n => n.className === 'inspect-choice');
|
||||
return { f, view, calls, decided, sections, done() { view.dispose(); scope.dispose(); f.restore(); } };
|
||||
}
|
||||
|
||||
test('a pending review item mounts Choose prompt right after the prompt blocks', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [section] = m.sections();
|
||||
assert.ok(section, 'Choose prompt is mounted');
|
||||
const inner = section.parent;
|
||||
const index = inner.children.indexOf(section);
|
||||
assert.ok(inner.children[index - 1].children.some(n => n.className === 'prompt-section positive'),
|
||||
'the section follows the prompt blocks');
|
||||
assert.deepEqual(m.calls, [['GET', `/prompt_manager/review/items/${ITEM}`]]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a re-render keeps the same section, and another item replaces it', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [first] = m.sections();
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.equal(m.sections()[0], first);
|
||||
assert.equal(m.calls.length, 1, 'the item is read once');
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: OTHER }) });
|
||||
await settle();
|
||||
assert.notEqual(m.sections()[0], first);
|
||||
assert.equal(m.sections().length, 1);
|
||||
assert.deepEqual(m.calls.at(-1), ['GET', `/prompt_manager/review/items/${OTHER}`]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('no section without a pending item, or without a way to re-read the inspection', async () => {
|
||||
for (const review of [null, { state: 'decided' }, undefined]) {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record(review) });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0, JSON.stringify(review));
|
||||
assert.equal(m.calls.length, 0);
|
||||
} finally { m.done(); }
|
||||
}
|
||||
const m = mount({ onReviewDecided: undefined });
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a decision re-reads the inspection; a record without the item removes the section', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const use = m.f.walk(m.sections()[0], n => n.tagName === 'button' && n.textContent === 'Use this prompt')[0];
|
||||
use.fire('click');
|
||||
await settle();
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
m.view.setState({ record: { ...record(null), library: { status: 'linked', tags: [] } } });
|
||||
await settle();
|
||||
assert.equal(m.sections().length, 0);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('reading another file ends the section', async () => {
|
||||
const m = mount();
|
||||
try {
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
const [section] = m.sections();
|
||||
m.view.setState({ loading: true });
|
||||
assert.equal(m.sections().length, 0);
|
||||
m.view.setState({ record: record({ state: 'pending', item_id: ITEM }) });
|
||||
await settle();
|
||||
assert.notEqual(m.sections()[0], section, 'a new section for the newly read record');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
@@ -748,3 +748,24 @@ test('category chip names its origin visibly and shows an own category for any l
|
||||
assert.equal(chips.some(chip => /category: /.test(chip)), false, JSON.stringify(library));
|
||||
}
|
||||
});
|
||||
|
||||
// #658: an ambiguous file whose candidates share one role. The shared role has Copy and Send; the footer
|
||||
// "Send to ComfyUI" sends a pair, so it needs both roles resolved and is absent here, in both variants.
|
||||
test('one resolved and one ambiguous role: no footer Send to ComfyUI, the resolved role keeps its actions', async () => {
|
||||
const base = await localRecord(localPng('Shared Negative.png'));
|
||||
const record = {...base, prompts:{positive:{status:'ambiguous', text:null, source:null}, negative:{status:'resolved', text:'blurry, lowres', source:'graph-inferred'}}};
|
||||
for (const variant of ['panel', 'full']) {
|
||||
const f = mountedDom(), scope = createScope();
|
||||
const forbidden = new Proxy({}, {get(_, key) {assert.fail(`api.${String(key)} touched by a local record`);}});
|
||||
const view = mountFileInspector(f.container, {api:forbidden, sender:{open() {}}, parentScope:scope, variant});
|
||||
try {
|
||||
view.setState({loading:false, error:false, record});
|
||||
const buttons = f.walk(f.container, n => n.tagName === 'button');
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'pair').length, 0, variant);
|
||||
assert.equal(f.walk(f.container, n => n.textContent?.includes?.('Send to ComfyUI') && n.tagName === 'button').length, 0, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'negative').length, 1, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.copyRole === 'negative').length, 1, variant);
|
||||
assert.equal(buttons.filter(n => n.dataset.sendRole === 'positive' || n.dataset.copyRole === 'positive').length, 0, variant);
|
||||
} finally { view.dispose(); scope.dispose(); f.restore(); }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// Run with: node --test tests/js/workspace-inspect-choice.test.js
|
||||
// #659 (design Part 5): Inspect's Choose prompt over the review controller's single-item mode.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mountedDom } from './helpers/mounted-dom.mjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { createApiClient } = require('../../web/js/api-client.js');
|
||||
const { createScope } = await import('../../web/js/shared/toolkit/core.js');
|
||||
const module = await import('../../web/js/workspace/inspect-choice.mjs').catch(error => {
|
||||
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
|
||||
return {};
|
||||
});
|
||||
|
||||
const ITEM = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const EPOCH = '11111111-1111-4111-8111-111111111111';
|
||||
const SCOPE = 'c'.repeat(64);
|
||||
const HASH_A = 'a'.repeat(64), HASH_B = 'b'.repeat(64), HASH_C = 'f'.repeat(64);
|
||||
const ITEMS = '/prompt_manager/review/items';
|
||||
const OBSERVE = '/prompt_manager/image-annotations/observe';
|
||||
const CAPTURE = '/prompt_manager/image-annotations/capture/';
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function settle(times = 8) { for (let i = 0; i < times; i++) await flush(); }
|
||||
const response = (status, body) => ({ ok: status >= 200 && status < 300, status, statusText: `Status ${status}`, json: async () => body });
|
||||
const fail = (status, code, error) => response(status, { success: false, code, error });
|
||||
const candidate = (hash, sampler, label, positive, negative, state = 'resolved', reason = '') => ({
|
||||
hash, sampler_id: sampler, state, reason, label,
|
||||
positive: positive === null ? null : { text: positive }, negative: negative === null ? null : { text: negative },
|
||||
});
|
||||
function detail(overrides = {}) {
|
||||
return {
|
||||
success: true, library_epoch: EPOCH, id: ITEM, state: 'pending', revision: 0, filename: 'a.png',
|
||||
target: { root_index: 0, root_scope: SCOPE, path: 'a.png' }, unavailable: false, candidate_count: 3, limited: false,
|
||||
total: 1, sha256: 'd'.repeat(64), dependency_fingerprint: 'e'.repeat(64),
|
||||
candidates: [
|
||||
candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved', 'Unsupported latent ancestry'),
|
||||
candidate(HASH_A, '12', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate(HASH_B, '28', 'Harbor / Soft negative', 'harbor lights', 'blur'),
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
const observed = { success: true, library_epoch: EPOCH, capture: { token: 'capture-1', sha256: 'd'.repeat(64) } };
|
||||
function harness(routes = {}) {
|
||||
const calls = [];
|
||||
const fetch = (url, init = {}) => {
|
||||
const call = { url, method: init.method, body: init.body === undefined ? undefined : JSON.parse(init.body) };
|
||||
calls.push(call);
|
||||
const path = url.startsWith(CAPTURE) ? CAPTURE : url.split('?')[0];
|
||||
const all = {
|
||||
[`GET ${ITEMS}/${ITEM}`]: () => response(200, detail()),
|
||||
[`POST ${OBSERVE}`]: () => response(200, observed),
|
||||
[`POST ${ITEMS}/${ITEM}/decision`]: () => response(200, { success: true, library_epoch: EPOCH, total: 0 }),
|
||||
...routes,
|
||||
};
|
||||
const route = all[`${call.method} ${path}`];
|
||||
return Promise.resolve().then(() => (route ? route(call) : response(200, { success: true })));
|
||||
};
|
||||
return { api: createApiClient(fetch), calls, of: (method, prefix) => calls.filter(c => c.method === method && c.url.startsWith(prefix)) };
|
||||
}
|
||||
|
||||
function contract() {
|
||||
assert.equal(typeof module.mountInspectChoice, 'function', 'inspect-choice.mjs is not implemented');
|
||||
return module;
|
||||
}
|
||||
/** The section mounted in a minimal DOM, with its parts found by text and class. */
|
||||
async function mounted(routes, options = {}) {
|
||||
const { mountInspectChoice } = contract();
|
||||
const f = mountedDom();
|
||||
f.doc.getElementById = () => null;
|
||||
const h = harness(routes), scope = createScope(), decided = [], sent = [];
|
||||
const sender = { open: (roles, trigger) => sent.push({ roles, trigger }) };
|
||||
const view = mountInspectChoice({ api: h.api, itemId: ITEM, sender, parentScope: scope, onDecided: () => decided.push(true), ...options });
|
||||
f.container.append(view.root);
|
||||
await settle();
|
||||
const find = predicate => f.walk(view.root, predicate);
|
||||
const button = text => find(n => n.tagName === 'button' && n.textContent === text)[0];
|
||||
const visible = node => { for (let n = node; n && n !== view.root.parent; n = n.parent) if (n.hidden) return false; return true; };
|
||||
return {
|
||||
f, h, view, scope, decided, sent, button, visible,
|
||||
select: () => find(n => n.tagName === 'select')[0],
|
||||
options: () => find(n => n.tagName === 'option').map(n => [n.textContent, n.disabled]),
|
||||
warning: () => find(n => n.className === 'warning-note')[0],
|
||||
status: () => find(n => /inspect-choice-status/.test(n.className ?? ''))[0],
|
||||
texts: role => find(n => n.tagName === 'section' && n.className === `prompt-section ${role}`)
|
||||
.flatMap(section => f.walk(section, n => n.className === 'prompt-text').map(n => n.textContent)),
|
||||
done() { scope.dispose(); f.restore(); },
|
||||
};
|
||||
}
|
||||
const click = node => node.fire('click');
|
||||
|
||||
test('the section lists the server labels, with a disabled candidate and its reason', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
assert.equal(m.view.itemId, ITEM);
|
||||
assert.equal(m.view.root.className, 'inspect-choice');
|
||||
assert.ok(m.f.walk(m.view.root, n => n.textContent === 'Choose prompt').length);
|
||||
assert.deepEqual(m.options(), [
|
||||
['Sampler 9 · No positive / Soft negative (Unsupported latent ancestry)', true],
|
||||
['Sampler 12 · Dunes / Soft negative', false],
|
||||
['Sampler 28 · Harbor / Soft negative', false],
|
||||
]);
|
||||
assert.equal(m.select().value, HASH_A);
|
||||
assert.deepEqual(m.texts('positive'), ['golden dunes']);
|
||||
assert.deepEqual(m.texts('negative'), ['blur']);
|
||||
assert.equal(m.visible(m.button('Use this prompt')), true);
|
||||
assert.equal(m.visible(m.button('Leave unresolved')), true);
|
||||
assert.equal(m.visible(m.button('Open in Needs review')), false);
|
||||
assert.equal(m.visible(m.warning()), false);
|
||||
// Choosing another option shows its prompts; the prompt blocks' Send opens the shared sender.
|
||||
m.select().value = HASH_B;
|
||||
m.select().fire('change');
|
||||
assert.deepEqual(m.texts('positive'), ['harbor lights']);
|
||||
const send = m.f.walk(m.view.root, n => n.dataset?.sendRole === 'positive')[0];
|
||||
// The prompt blocks listen on their container (the section's parent).
|
||||
m.f.walk(m.view.root, n => n.className === 'prompt-section positive')[0].parent.fire('click', { target: send });
|
||||
assert.deepEqual(m.sent.map(entry => entry.roles), [{ positive: 'harbor lights' }]);
|
||||
assert.equal(m.h.of('GET', ITEMS).length, 1, 'only the item is read, never the queue');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('Use this prompt decides the chosen candidate and re-reads the inspection', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
m.select().value = HASH_B;
|
||||
m.select().fire('change');
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
const [decision] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(decision.body.capture_token, 'capture-1');
|
||||
assert.equal(m.h.of('POST', OBSERVE).length, 1);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
// A decided item offers nothing more.
|
||||
assert.equal(m.visible(m.button('Use this prompt')), false);
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.h.of('POST', `${ITEMS}/${ITEM}/decision`).length, 1);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('a refusal shows the server sentence and keeps the choice', async () => {
|
||||
const m = await mounted({ [`POST ${ITEMS}/${ITEM}/decision`]: () => fail(409, 'file-changed', 'The file changed since it was queued.') });
|
||||
try {
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.warning().textContent, 'The file changed since it was queued.');
|
||||
assert.equal(m.visible(m.warning()), true);
|
||||
assert.deepEqual(m.decided, []);
|
||||
assert.equal(m.select().value, HASH_A);
|
||||
assert.equal(m.button('Use this prompt').getAttribute('aria-disabled'), null);
|
||||
// The refused capture is released.
|
||||
assert.equal(m.h.of('DELETE', CAPTURE).length, 1);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('an unanswered decision is resent once by the next press', async () => {
|
||||
let attempts = 0;
|
||||
const m = await mounted({
|
||||
[`POST ${ITEMS}/${ITEM}/decision`]: () => (++attempts === 1 ? Promise.reject(new TypeError('Failed to fetch'))
|
||||
: response(200, { success: true, library_epoch: EPOCH, total: 0 })),
|
||||
});
|
||||
try {
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
assert.equal(m.warning().textContent, 'The decision may not have been saved. Apply again to send the same decision once more.');
|
||||
click(m.button('Use this prompt'));
|
||||
await settle();
|
||||
const [first, second] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(m.h.of('POST', OBSERVE).length, 1);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('Leave unresolved decides the item as unresolved', async () => {
|
||||
const m = await mounted();
|
||||
try {
|
||||
click(m.button('Leave unresolved'));
|
||||
await settle();
|
||||
const [decision] = m.h.of('POST', `${ITEMS}/${ITEM}/decision`);
|
||||
assert.equal(decision.body.choice, 'unresolved');
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
for (const [name, overrides] of [
|
||||
['a limited item', { limited: true, candidates: [], candidate_count: 0 }],
|
||||
['an item whose candidates cannot be applied', {
|
||||
candidates: [candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved', 'Unsupported latent ancestry')],
|
||||
}],
|
||||
['an unavailable file', { target: null, unavailable: true }],
|
||||
]) {
|
||||
test(`${name} offers Open in Needs review instead of options`, async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail(overrides)) });
|
||||
try {
|
||||
assert.equal(m.status().textContent, 'None of the possible prompts can be applied here. Decide this image in Needs review.');
|
||||
const open = m.button('Open in Needs review');
|
||||
assert.equal(m.visible(open), true);
|
||||
for (const text of ['Use this prompt', 'Leave unresolved']) assert.equal(m.visible(m.button(text)), false, text);
|
||||
assert.equal(m.visible(m.select()), false);
|
||||
click(open);
|
||||
assert.equal(m.f.win.location.hash, '#/review');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
}
|
||||
|
||||
test('a failed read offers Retry and Open in Needs review; Retry reads the item again', async () => {
|
||||
let reads = 0;
|
||||
const m = await mounted({
|
||||
[`GET ${ITEMS}/${ITEM}`]: () => (++reads === 1 ? fail(500, 'review-failed', 'The review queue could not be read.') : response(200, detail())),
|
||||
});
|
||||
try {
|
||||
assert.equal(m.visible(m.button('Retry')), true);
|
||||
assert.equal(m.visible(m.button('Open in Needs review')), true);
|
||||
assert.equal(m.warning().textContent, 'This item could not be read. Select it again to retry.');
|
||||
click(m.button('Retry'));
|
||||
await settle();
|
||||
assert.equal(reads, 2);
|
||||
assert.equal(m.visible(m.button('Retry')), false);
|
||||
assert.equal(m.visible(m.button('Use this prompt')), true);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('the loading state says so, and disposing stops the section', async () => {
|
||||
let answer;
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => new Promise(resolve => { answer = resolve; }) });
|
||||
try {
|
||||
assert.equal(m.status().textContent, 'Loading the possible prompts…');
|
||||
assert.equal(m.visible(m.button('Use this prompt')), false);
|
||||
m.view.dispose();
|
||||
m.view.dispose();
|
||||
answer(response(200, detail()));
|
||||
await settle();
|
||||
assert.equal(m.view.root.parent, null);
|
||||
assert.equal(m.status().textContent, 'Loading the possible prompts…');
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('an aborted parent mounts nothing', () => {
|
||||
const { mountInspectChoice } = contract();
|
||||
const f = mountedDom();
|
||||
try {
|
||||
const scope = createScope();
|
||||
scope.dispose();
|
||||
const view = mountInspectChoice({ api: null, itemId: ITEM, sender: null, parentScope: scope });
|
||||
assert.equal(view.root.children.length, 0);
|
||||
view.dispose();
|
||||
} finally { f.restore(); }
|
||||
});
|
||||
|
||||
test('choiceMode names what the section shows', () => {
|
||||
const { choiceMode } = contract();
|
||||
const ready = { detailStatus: 'ready', detail: detail(), options: [{ disabled: false }], decided: false };
|
||||
assert.equal(choiceMode(ready), 'choose');
|
||||
assert.equal(choiceMode({ ...ready, decided: true }), 'decided');
|
||||
assert.equal(choiceMode({ ...ready, detailStatus: 'error' }), 'error');
|
||||
assert.equal(choiceMode({ ...ready, detailStatus: 'loading', detail: null }), 'loading');
|
||||
assert.equal(choiceMode({ ...ready, options: [{ disabled: true }] }), 'review');
|
||||
});
|
||||
|
||||
test('an item decided elsewhere hides the section and re-reads the inspection once', async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail({ state: 'selected', revision: 1 })) });
|
||||
try {
|
||||
assert.equal(m.view.root.hidden, true);
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
await settle();
|
||||
assert.deepEqual(m.decided, [true]);
|
||||
} finally { m.done(); }
|
||||
});
|
||||
|
||||
test('#657 D3: collapsedLine names how many of the file\'s prompts are listed, or nothing', async () => {
|
||||
const { collapsedLine } = await import('../../web/js/workspace/review-options.mjs');
|
||||
assert.equal(collapsedLine({ collapsed: { shown: 16, total: 81, paths: 165 } }),
|
||||
'Showing the 16 most used of 81 prompts in this file.');
|
||||
assert.equal(collapsedLine({ collapsed: { shown: 16, total: 1234, paths: 2000 } }),
|
||||
'Showing the 16 most used of 1,234 prompts in this file.');
|
||||
assert.equal(collapsedLine({ collapsed: null }), '');
|
||||
assert.equal(collapsedLine({}), '');
|
||||
assert.equal(collapsedLine(null), '');
|
||||
});
|
||||
|
||||
test('#657 D3: a collapsed candidate list says so under the options, and only then', async () => {
|
||||
const m = await mounted({ [`GET ${ITEMS}/${ITEM}`]: () => response(200, detail({ collapsed: { shown: 2, total: 40, paths: 90 } })) });
|
||||
try {
|
||||
const line = m.f.walk(m.view.root, n => /review-collapsed/.test(n.className ?? ''))[0];
|
||||
assert.equal(line.textContent, 'Showing the 2 most used of 40 prompts in this file.');
|
||||
assert.equal(m.visible(line), true);
|
||||
} finally { m.done(); }
|
||||
const plain = await mounted();
|
||||
try {
|
||||
const line = plain.f.walk(plain.view.root, n => /review-collapsed/.test(n.className ?? ''))[0];
|
||||
assert.equal(plain.visible(line), false);
|
||||
} finally { plain.done(); }
|
||||
});
|
||||
@@ -966,3 +966,30 @@ test('a backslash inside a name is accepted only from a POSIX listing (#646)', (
|
||||
for (const bad of ['../a.png', 'a/../b.png', 'C:\\a.png', 'a//b.png', '/a.png'])
|
||||
assert.throws(() => inspectPath({root_index:0, path:bad, root_scope:scopeA, path_style:'posix'}), /Invalid inspection identity/);
|
||||
});
|
||||
|
||||
// #659: the file's Needs review item (`review`), kept as the server names it.
|
||||
test('record keeps the review facet: a pending item, decided, or null', () => {
|
||||
const toInspectionRecord = contract('toInspectionRecord'), entry = image();
|
||||
const item = '0a1b2c3d-0000-4000-8000-00000000abcd';
|
||||
const of = review => {
|
||||
const data = envelope(entry);
|
||||
if (review !== undefined) data.review = review;
|
||||
return toInspectionRecord(data, entry, extractGenerationFacts).review;
|
||||
};
|
||||
assert.deepEqual(of({ state: 'pending', item_id: item }), { state: 'pending', item_id: item });
|
||||
assert.deepEqual(of({ state: 'decided' }), { state: 'decided' });
|
||||
assert.equal(of(null), null);
|
||||
assert.equal(of(undefined), null);
|
||||
// Anything else offers no choice (and never fails the inspection).
|
||||
for (const review of ['pending', [], {}, { state: 'pending' }, { state: 'pending', item_id: 7 }, { state: 'pending', item_id: 'x' },
|
||||
{ state: 'pending', item_id: item.toUpperCase() }, { state: 'pending', item_id: item, extra: 1 }, { state: 'decided', item_id: item },
|
||||
{ state: 'unresolved' }]) assert.equal(of(review), null, JSON.stringify(review));
|
||||
const record = of({ state: 'pending', item_id: item });
|
||||
assert.ok(Object.isFrozen(record));
|
||||
});
|
||||
|
||||
test('a legacy payload carries no review facet', () => {
|
||||
const data = envelope(); delete data.inspection_version;
|
||||
const record = contract('projectInspectionPayload')({ ...data, review: { state: 'decided' } }, {}, null, () => ({}), true);
|
||||
assert.equal(record.review, null);
|
||||
});
|
||||
|
||||
@@ -41,3 +41,25 @@ test("without the API client nothing is fetched", async () => {
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
// #657: a `first-present` selector (rgthree Any Switch) has exactly `strategy` and a non-empty `input_prefix` of at most
|
||||
// 128 characters, as utils/inspection_semantics.py checks; the browser rejected nothing about a selector before.
|
||||
test("the compiler checks a first-present selector as strictly as the server", async () => {
|
||||
const { compileSemantics, SemanticsError } = await import("../../web/js/workspace/local-resolver.mjs");
|
||||
const real = compileSemantics(JSON.parse(TABLE));
|
||||
assert.deepEqual(real.selectors.get("Any Switch (rgthree)"), { strategy: "first-present", input_prefix: "any_" });
|
||||
const valid = { strategy: "first-present", input_prefix: "any_" };
|
||||
for (const entry of [{ ...valid, condition: "boolean" }, { strategy: "first-present" }, { ...valid, input_prefix: "" },
|
||||
{ ...valid, input_prefix: "a".repeat(129) }, { ...valid, input_prefix: 1 }]) {
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = entry;
|
||||
assert.throws(() => compileSemantics(doc), SemanticsError, JSON.stringify(entry));
|
||||
}
|
||||
// 128 code points, as Python's len(): an emoji is one, though two UTF-16 units.
|
||||
for (const [prefix, ok] of [["a".repeat(128), true], ["\u{1F600}".repeat(128), true], ["\u{1F600}".repeat(129), false]]) {
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = { ...valid, input_prefix: prefix };
|
||||
if (ok) assert.doesNotThrow(() => compileSemantics(doc));
|
||||
else assert.throws(() => compileSemantics(doc), SemanticsError);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -197,6 +197,57 @@ test('nothing selectable: the reasons are summed, there is no choice and apply s
|
||||
const linkRoute = (body = {}) => ({ [`POST ${ITEMS}/one/link`]: call => response(200, { success: true, library_epoch: EPOCH, total: 1,
|
||||
item: { ...QUEUE[0], state: 'selected', revision: 1 }, pair: { id: call.body.pair_id ?? 7, image_id: 3, status: 'added' }, ...body }) });
|
||||
|
||||
test('#657 D4: imageChoices lists the choosable candidates once per prompt pair, with non-blank positive text', async () => {
|
||||
const { imageChoices, contextOptions } = await load();
|
||||
const detail = detailOf(QUEUE[0], { candidates: [
|
||||
candidate(HASH_C, '9', 'No positive / Soft negative', null, 'blur', 'unresolved'),
|
||||
candidate(HASH_A, '12', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate('1'.repeat(64), '13', 'Dunes / Soft negative', 'golden dunes', 'blur'),
|
||||
candidate('2'.repeat(64), '14', ' / Soft negative', ' ', 'blur'),
|
||||
candidate(HASH_B, '28', 'Dunes / No negative', 'golden dunes', ''),
|
||||
] });
|
||||
const choices = imageChoices(contextOptions(detail));
|
||||
assert.deepEqual(choices.map(choice => [choice.value, choice.positive, choice.negative]),
|
||||
[[HASH_A, 'golden dunes', 'blur'], [HASH_B, 'golden dunes', '']]);
|
||||
assert.ok(Object.isFrozen(choices));
|
||||
// An unavailable file has nothing to apply.
|
||||
assert.deepEqual(imageChoices(contextOptions({ ...detail, target: null })), []);
|
||||
});
|
||||
|
||||
test('#657 D4: applyCandidate decides the open item with that candidate, as Apply association does', async () => {
|
||||
const { c, h } = await loaded();
|
||||
assert.equal(await c.applyCandidate({ itemId: 'two', hash: HASH_B }), false, 'not the open item');
|
||||
assert.equal(c.state.warning, '');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_C }), false, 'a disabled candidate');
|
||||
// The dialog's choice is no longer offered (the detail was read again meanwhile): it says so.
|
||||
assert.equal(c.state.warning, 'This prompt is no longer offered for this file. Choose again.');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: 'gone' }), false, 'a candidate the detail no longer lists');
|
||||
assert.equal(c.state.warning, 'This prompt is no longer offered for this file. Choose again.');
|
||||
assert.equal(h.of('POST', OBSERVE).length, 0);
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), true);
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(c.state.toast, 'Association accepted.');
|
||||
assert.equal(c.state.selectedId, 'two');
|
||||
});
|
||||
|
||||
test('#657 D4: an unanswered applyCandidate asks to press Link image again, and that resends the same body once', async () => {
|
||||
let attempts = 0;
|
||||
const { c, h } = await loaded({
|
||||
[`POST ${ITEMS}/one/decision`]: () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) return Promise.reject(new TypeError('Failed to fetch'));
|
||||
return response(200, { success: true, library_epoch: EPOCH, total: 1, item: { ...QUEUE[0], state: 'selected', revision: 1 } });
|
||||
},
|
||||
});
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), false);
|
||||
assert.equal(c.state.warning, 'The link may not have been saved. Press Link image again to send the same choice once more.');
|
||||
assert.equal(await c.applyCandidate({ itemId: 'one', hash: HASH_B }), true);
|
||||
const [first, second] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 1);
|
||||
});
|
||||
|
||||
test('link posts the chosen prompt and recipe with a fresh capture, then the next item opens', async () => {
|
||||
const { c, h } = await loaded({ ...linkRoute(), [`GET ${ITEMS}/one`]: () => response(200, unreadable()) });
|
||||
assert.equal(await c.link({ itemId: 'one', positiveId: 4, pairId: 9, title: 'Harbor' }), true);
|
||||
@@ -864,3 +915,175 @@ test('M5: an unanswered decision that landed finishes as recorded, not as decide
|
||||
assert.doesNotMatch(c.state.warning, /decided elsewhere/);
|
||||
assert.equal(h.of('DELETE', CAPTURE).length, 0, 'the server used the capture');
|
||||
});
|
||||
|
||||
// #659: the single-item mode Inspect's Choose prompt runs: one named item, its detail, one decision, no queue.
|
||||
async function single(extra, itemId = 'one') {
|
||||
const { createReviewController } = await load();
|
||||
const h = harness(routes(extra));
|
||||
const c = createReviewController({ api: h.api, itemId });
|
||||
await c.load();
|
||||
await settle();
|
||||
return { c, h };
|
||||
}
|
||||
const listReads = h => h.calls.filter(call => call.method === 'GET' && call.url.split('?')[0] === ITEMS);
|
||||
const detailReads = (h, id = 'one') => h.of('GET', `${ITEMS}/${id}`);
|
||||
|
||||
test('single-item mode never reads the list and loads its item', async () => {
|
||||
const { c, h } = await single();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
assert.equal(c.state.status, 'ready');
|
||||
assert.equal(c.state.selectedId, 'one');
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.decided, false);
|
||||
assert.deepEqual(c.state.options.map(option => [option.label, option.disabled]), [
|
||||
['Sampler 9 · No positive / Soft negative', true],
|
||||
['Sampler 12 · Dunes / Soft negative', false],
|
||||
['Sampler 28 · Dunes / Harsh negative', false],
|
||||
]);
|
||||
assert.equal(c.state.choice, HASH_A);
|
||||
assert.equal(c.state.warning, '');
|
||||
c.choose(HASH_B);
|
||||
assert.equal(c.state.prompts.negative.text, 'noise');
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item mode ends decided after a recorded decision, without reading the queue', async () => {
|
||||
const { c, h } = await single();
|
||||
c.choose(HASH_B);
|
||||
assert.equal(await c.apply(), true);
|
||||
await settle();
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, HASH_B);
|
||||
assert.equal(decision.body.capture_token, 'capture-1');
|
||||
assert.equal(decision.body.expected_epoch, EPOCH);
|
||||
assert.equal(c.state.phase, 'decided');
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.decisions, 1);
|
||||
assert.equal(c.state.toast, 'Association accepted.');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
// A decided controller decides nothing more.
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(await c.leaveUnresolved(), false);
|
||||
assert.equal(h.of('POST', `${ITEMS}/one/decision`).length, 1);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item Leave unresolved decides the item as unresolved', async () => {
|
||||
const { c, h } = await single();
|
||||
assert.equal(await c.leaveUnresolved(), true);
|
||||
const [decision] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.equal(decision.body.choice, 'unresolved');
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.toast, 'Left unresolved.');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
for (const code of ['review-conflict', 'review-missing']) {
|
||||
test(`single-item mode re-reads its detail after a ${code} refusal`, async () => {
|
||||
let reads = 0;
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => {
|
||||
reads += 1;
|
||||
return reads === 1 || code === 'review-conflict' ? response(200, detailOf(QUEUE[0], { revision: reads }))
|
||||
: fail(404, 'review-missing', 'This review item no longer exists. Reload the queue.');
|
||||
},
|
||||
[`POST ${ITEMS}/one/decision`]: () => fail(code === 'review-missing' ? 404 : 409, code, `refused: ${code}`),
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
await settle();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.equal(detailReads(h).length, 2);
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.decided, false);
|
||||
// The refused capture is released.
|
||||
assert.equal(h.of('DELETE', CAPTURE).length, 1);
|
||||
if (code === 'review-conflict') {
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.detail.revision, 2);
|
||||
assert.equal(c.state.warning, `refused: ${code}`);
|
||||
} else {
|
||||
// The item is gone: its sentence, and nothing more is read.
|
||||
assert.equal(c.state.detailStatus, 'error');
|
||||
assert.equal(c.state.warning, 'This review item no longer exists. Reload the queue.');
|
||||
await settle();
|
||||
assert.equal(detailReads(h).length, 2);
|
||||
}
|
||||
c.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
test('single-item refusal keeps the item open with the server sentence', async () => {
|
||||
const { c, h } = await single({
|
||||
[`POST ${ITEMS}/one/decision`]: () => fail(409, 'file-changed', 'The file changed since it was queued.'),
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(c.state.phase, 'idle');
|
||||
assert.equal(c.state.warning, 'The file changed since it was queued.');
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(detailReads(h).length, 1);
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item unanswered decision resends the same body once', async () => {
|
||||
let attempts = 0;
|
||||
const { c, h } = await single({
|
||||
[`POST ${ITEMS}/one/decision`]: call => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) return Promise.reject(new TypeError('Failed to fetch'));
|
||||
return response(200, { success: true, library_epoch: EPOCH, total: 1, item: { ...QUEUE[0], state: 'selected', revision: 1 } });
|
||||
},
|
||||
});
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(c.state.canRetry, true);
|
||||
assert.equal(c.state.warning, 'The decision may not have been saved. Apply again to send the same decision once more.');
|
||||
assert.equal(await c.retry(), true);
|
||||
const [first, second] = h.of('POST', `${ITEMS}/one/decision`);
|
||||
assert.deepEqual(second.body, first.body);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 1);
|
||||
assert.equal(c.state.decided, true);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item mode opens an item already decided as decided', async () => {
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => response(200, detailOf({ ...QUEUE[0], state: 'selected', revision: 1 })),
|
||||
});
|
||||
assert.equal(c.state.decided, true);
|
||||
assert.equal(c.state.phase, 'decided');
|
||||
assert.equal(await c.apply(), false);
|
||||
assert.equal(h.of('POST', OBSERVE).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item refresh re-reads the detail, never the list; leave does nothing', async () => {
|
||||
const { c, h } = await single();
|
||||
await c.refresh();
|
||||
await c.sync({ library_epoch: EPOCH, review_revision: 9 });
|
||||
await c.leave();
|
||||
await settle();
|
||||
assert.equal(listReads(h).length, 0);
|
||||
assert.ok(detailReads(h).length >= 2);
|
||||
assert.equal(c.state.selectedId, 'one');
|
||||
c.dispose();
|
||||
});
|
||||
|
||||
test('single-item failed detail read is an error with its retry', async () => {
|
||||
let reads = 0;
|
||||
const { c, h } = await single({
|
||||
[`GET ${ITEMS}/one`]: () => (++reads === 1 ? fail(500, 'review-failed', 'The review queue could not be read.') : response(200, detailOf(QUEUE[0]))),
|
||||
});
|
||||
assert.equal(c.state.detailStatus, 'error');
|
||||
assert.equal(c.state.warning, COPY_DETAIL_FAILED);
|
||||
await c.load();
|
||||
await settle();
|
||||
assert.equal(c.state.detailStatus, 'ready');
|
||||
assert.equal(c.state.warning, '');
|
||||
assert.equal(listReads(h).length, 0);
|
||||
c.dispose();
|
||||
});
|
||||
const COPY_DETAIL_FAILED = 'This item could not be read. Select it again to retry.';
|
||||
|
||||
@@ -915,6 +915,9 @@ def golden_cases():
|
||||
import unknown_node_graphs
|
||||
for name, graph in unknown_node_graphs.shapes().items():
|
||||
add(f"pass-through-{name}", graph)
|
||||
# #657: rgthree Any Switch, the first input proven to hold a value.
|
||||
for name, graph in unknown_node_graphs.first_present_shapes().items():
|
||||
add(f"first-present-{name}", graph)
|
||||
for name, records in {
|
||||
**unknown_node_graphs.recorded_shapes(),
|
||||
**unknown_node_graphs.review_shapes(),
|
||||
|
||||
@@ -13,9 +13,11 @@ import random
|
||||
|
||||
try:
|
||||
from tests import passthrough_graphs as shapes
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
from tests.local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
import passthrough_graphs as shapes
|
||||
import unknown_node_graphs as switch_graphs
|
||||
from local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
|
||||
|
||||
@@ -642,10 +644,80 @@ def _passthrough_edges():
|
||||
return {f"edge-{name}": graph for name, graph in cases.items()}
|
||||
|
||||
|
||||
def _shared_roles():
|
||||
"""#658: a role every candidate resolves alike is shown on its own."""
|
||||
same = _sampler(["6", 0], ["7", 0])
|
||||
prompt_manager = {
|
||||
"class_type": "PromptManager",
|
||||
"inputs": {
|
||||
"text": "fox",
|
||||
"prepend_text": "a",
|
||||
"append_text": "",
|
||||
"clip": ["4", 1],
|
||||
},
|
||||
}
|
||||
trigger = {"class_type": "TriggerWord Toggle (LoraManager)", "inputs": {"x": 1}}
|
||||
left_out = {
|
||||
"class_type": "PromptManager",
|
||||
"inputs": {"text": "blurry", "append_text": ["13", 0], "clip": ["4", 1]},
|
||||
}
|
||||
selector = {
|
||||
"class_type": "easy ifElse",
|
||||
"inputs": {"boolean": ["4", 0], "on_true": ["7", 0], "on_false": ["8", 0]},
|
||||
}
|
||||
return {
|
||||
"shared-negative": _base(**{"3": same, "9": _sampler(["8", 0], ["7", 0])}),
|
||||
"shared-negative-unresolved-branch": _base(
|
||||
**{"3": same, "9": _sampler(["missing", 0], ["7", 0])}
|
||||
),
|
||||
"shared-negative-other-recipe": _base(
|
||||
**{
|
||||
"3": _sampler(["10", 0], ["7", 0]),
|
||||
"9": _sampler(["11", 0], ["7", 0]),
|
||||
"10": _encode("a fox"),
|
||||
"11": prompt_manager,
|
||||
}
|
||||
),
|
||||
"shared-negative-left-out": _base(
|
||||
**{
|
||||
"3": same,
|
||||
"9": _sampler(["8", 0], ["12", 0]),
|
||||
"12": left_out,
|
||||
"13": trigger,
|
||||
}
|
||||
),
|
||||
"shared-positive-selector": _base(
|
||||
**{"3": _sampler(["6", 0], ["14", 0]), "14": selector}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _first_present():
|
||||
"""rgthree Any Switch (#657) beside a second sampler and in a detailer."""
|
||||
sweep = switch_graphs.any_switch_sweep_graph
|
||||
second = _sampler(["15", 0], ["16", 0], latent=["10", 0])
|
||||
unproven = switch_graphs.first_present_shapes()["through-unknown"]
|
||||
return {
|
||||
"first-present-two-samplers": {**sweep(), "36": second},
|
||||
"first-present-two-samplers-unproven": {**unproven, "36": second},
|
||||
"first-present-detailer": {
|
||||
**sweep(),
|
||||
"36": _detailer(["27", 0], ["15", 0], ["16", 0], wildcard=""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def selection_cases():
|
||||
"""Named record sets for every Task 9 path, each a ``read_inspection_file`` dict."""
|
||||
cases = {}
|
||||
for group in (_samplers(), _previews(), _detailers(), _passthrough()):
|
||||
for group in (
|
||||
_samplers(),
|
||||
_previews(),
|
||||
_detailers(),
|
||||
_passthrough(),
|
||||
_first_present(),
|
||||
_shared_roles(),
|
||||
):
|
||||
for name, graph in group.items():
|
||||
cases[f"select-{name}"] = {"prompt": json.dumps(graph, ensure_ascii=False)}
|
||||
cases.update(_parameters())
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Graphs of PromptManager runs the monitor asks the ladder for (#659).
|
||||
|
||||
``ambiguous_sweep_graph`` is the maintainer's model-compare sweep with its
|
||||
rgthree Any Switch replaced by a class no table lists: still ambiguous for
|
||||
the inspection profile after #657. ``joined_prompt_manager_graph`` is resolved only
|
||||
by the inspection profile; ``prompt_manager_shared_prefix`` only by the
|
||||
recorded saver.
|
||||
"""
|
||||
|
||||
try:
|
||||
from tests import saver_anchor_graphs as shapes
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
import saver_anchor_graphs as shapes
|
||||
import unknown_node_graphs as switch_graphs
|
||||
|
||||
PM_TEXT = "a quiet harbor"
|
||||
JOINED_TEXT = "a quiet harbor, golden hour"
|
||||
|
||||
|
||||
def joined_prompt_manager_graph(save=True):
|
||||
"""A PromptManagerText joined to a string node the default profile does
|
||||
not know: only the inspection profile resolves the positive."""
|
||||
return {
|
||||
"4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "m"}},
|
||||
"1": {
|
||||
"class_type": "PromptManagerText",
|
||||
"inputs": {"text": PM_TEXT, "save_to_library": save},
|
||||
},
|
||||
"5": {
|
||||
"class_type": "StringConstantMultiline",
|
||||
"inputs": {"string": "golden hour", "strip_newlines": True},
|
||||
},
|
||||
"7": {
|
||||
"class_type": "JoinStringMulti",
|
||||
"inputs": {
|
||||
"inputcount": 2,
|
||||
"delimiter": ", ",
|
||||
"return_list": False,
|
||||
"string_1": ["1", 0],
|
||||
"string_2": ["5", 0],
|
||||
},
|
||||
},
|
||||
"8": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": ["7", 0], "clip": ["4", 1]},
|
||||
},
|
||||
"2": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": "blurry", "clip": ["4", 1]},
|
||||
},
|
||||
"6": {"class_type": "EmptyLatentImage", "inputs": {"batch_size": 1}},
|
||||
"3": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"model": ["4", 0],
|
||||
"positive": ["8", 0],
|
||||
"negative": ["2", 0],
|
||||
"latent_image": ["6", 0],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def prompt_manager_shared_prefix():
|
||||
"""The dataset run with a PromptManagerText feeding branch 1: a
|
||||
PromptManager run only its recorded saver decides."""
|
||||
graph = shapes.shared_prefix()
|
||||
graph["50"] = {
|
||||
"class_type": "PromptManagerText",
|
||||
"inputs": {"text": shapes.BRANCH_TEXTS[0], "save_to_library": True},
|
||||
}
|
||||
graph["10"]["inputs"]["text"] = ["50", 0]
|
||||
return graph
|
||||
|
||||
|
||||
# The never-listed stand-in class of ``tests/unknown_node_graphs.py``
|
||||
UNKNOWN_SWITCH = "PMTest Unknown Multi"
|
||||
# The inspection profile's two candidate texts of ``ambiguous_sweep_graph``
|
||||
SWEEP_TEXTS = sorted(
|
||||
[switch_graphs.POSITIVE, f"{switch_graphs.SWEEP_PREFIX}, {switch_graphs.POSITIVE}"]
|
||||
)
|
||||
|
||||
|
||||
def ambiguous_sweep_graph(switch_class=UNKNOWN_SWITCH):
|
||||
"""The maintainer's model-compare sweep (``any_switch_sweep_graph``) with
|
||||
its switch's class replaced.
|
||||
|
||||
With the stand-in class no table lists, the default profile calls it
|
||||
unresolved and the inspection profile finds two resolved candidates
|
||||
(``SWEEP_TEXTS``): the shape the sweep had before rgthree's Any Switch
|
||||
got its ``first-present`` entry (#657). The real class resolves it.
|
||||
"""
|
||||
graph = switch_graphs.any_switch_sweep_graph()
|
||||
graph["14"]["class_type"] = switch_class
|
||||
return graph
|
||||
|
||||
|
||||
# The class of the maintainer's LLM prompt enhancer (no table lists it).
|
||||
ENHANCER = "KikoPromptEnhancer"
|
||||
# The one readable text of ``enhanced_sweep_graph`` (the joined ``any_02``).
|
||||
ENHANCED_TEXT = f"{switch_graphs.SWEEP_PREFIX}, {switch_graphs.POSITIVE}"
|
||||
|
||||
|
||||
def enhanced_sweep_graph():
|
||||
"""The sweep with an LLM enhancer (17) between PromptManagerText (12) and
|
||||
the switch's ``any_01`` (#657 addendum D1, live test 2026-11-20).
|
||||
|
||||
The inspection profile is ambiguous with two candidates: ``any_01`` is
|
||||
decided at run time (unresolved), ``any_02`` resolves to
|
||||
``ENHANCED_TEXT``. One readable choice: the file is reviewable.
|
||||
"""
|
||||
graph = switch_graphs.any_switch_sweep_graph()
|
||||
graph["17"] = {
|
||||
"class_type": ENHANCER,
|
||||
"inputs": {"prompt": ["12", 0], "seed": 1, "model": "local-llm"},
|
||||
}
|
||||
graph["14"]["inputs"]["any_01"] = ["17", 0]
|
||||
return graph
|
||||
@@ -1106,7 +1106,8 @@ class TestEnvelopes(AnnotationAPITestCase):
|
||||
)
|
||||
self.assertEqual(resp.status, 200)
|
||||
data = await self.json_of(resp)
|
||||
# Additive only: B3 adds the image_tags facet beside the Library facts.
|
||||
# Additive only: B3 adds the image_tags facet beside the Library facts,
|
||||
# #659 the review facet (null for a file without an ambiguous role).
|
||||
self.assertEqual(
|
||||
sorted(data),
|
||||
[
|
||||
@@ -1118,10 +1119,12 @@ class TestEnvelopes(AnnotationAPITestCase):
|
||||
"metadata",
|
||||
"prompts",
|
||||
"resolution",
|
||||
"review",
|
||||
"root_scope",
|
||||
"success",
|
||||
],
|
||||
)
|
||||
self.assertIsNone(data["review"])
|
||||
self.assertEqual(sorted(data["image"]), ["filename", "path", "root_index"])
|
||||
self.assertEqual(data["image_tags"], {"state": "none", "tags": []})
|
||||
self.assertEqual(
|
||||
|
||||
@@ -926,6 +926,24 @@ class TestMetadataParsing(unittest.TestCase):
|
||||
f.write(b"nope")
|
||||
self.assertEqual(self.api._extract_comfyui_metadata(garbage), {})
|
||||
|
||||
def test_extract_metadata_from_webp_exif(self):
|
||||
"""SaveAnimatedWEBP writes the records as EXIF, with no text chunks."""
|
||||
from PIL import Image
|
||||
|
||||
path = os.path.join(self.tmpdir, "m.webp")
|
||||
exif = Image.Exif()
|
||||
exif[0x0110] = 'prompt:{"1": {"class_type": "KSampler"}}'
|
||||
exif[0x010F] = 'workflow:{"nodes": [{"type": "CLIPTextEncode"}]}'
|
||||
Image.new("RGB", (1, 1)).save(path, "WEBP", exif=exif)
|
||||
|
||||
self.assertEqual(
|
||||
self.api._extract_comfyui_metadata(path),
|
||||
{
|
||||
"prompt": '{"1": {"class_type": "KSampler"}}',
|
||||
"workflow": '{"nodes": [{"type": "CLIPTextEncode"}]}',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1760,3 +1760,100 @@ class HistoryOutputAPITests(ImageAPITestCase):
|
||||
{"status": "resolved", "text": LLM_TEXT, "source": "execution"},
|
||||
)
|
||||
self.assertEqual(body["prompts"]["negative"]["text"], "")
|
||||
|
||||
def queue_review(self, path):
|
||||
"""One pending Needs review item for the bytes at ``path`` (#659)."""
|
||||
import hashlib
|
||||
|
||||
facts = path.stat()
|
||||
relative = path.relative_to(self.output_dir).parts
|
||||
spelled = os.path.join(os.path.realpath(self.output_dir), *relative)
|
||||
self.assertTrue(
|
||||
self.api.db.record_review_item(
|
||||
locator=os.path.normcase(spelled),
|
||||
spelled_path=spelled,
|
||||
sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
size=facts.st_size,
|
||||
mtime_ns=facts.st_mtime_ns,
|
||||
epoch=self.api.db.get_execution_epoch(),
|
||||
resolver_version=1,
|
||||
evidence={"candidates": []},
|
||||
candidate_count=0,
|
||||
limited=True,
|
||||
)
|
||||
)
|
||||
return self.api.db.review_items_for(os.path.normcase(spelled))[-1]["id"]
|
||||
|
||||
async def test_current_inspection_names_the_files_pending_review_item(self):
|
||||
"""#659 (C4): History's current-file read carries ``review`` as Images does."""
|
||||
from tests.test_inspection_review import two_samplers
|
||||
|
||||
path = png(self.output_dir / "image.png", prompt=two_samplers())
|
||||
start = self.capture([self.ref()])
|
||||
descriptor = await self.media(start)
|
||||
response = await self.current(descriptor["inspection_url"])
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertIsNone(body["review"])
|
||||
item_id = self.queue_review(path)
|
||||
response = await self.current(descriptor["inspection_url"])
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_current_inspection_finds_the_review_item_under_a_symlinked_output(
|
||||
self,
|
||||
):
|
||||
"""The served file is canonical; the item is keyed under the real root."""
|
||||
from tests.test_inspection_review import two_samplers
|
||||
|
||||
link = self.comfy_dir / "linked_output"
|
||||
self._make_symlink(self.output_dir, link, target_is_directory=True)
|
||||
self.api._get_all_output_dirs = lambda: [link]
|
||||
self.host_output = str(link)
|
||||
path = png(self.output_dir / "image.png", prompt=two_samplers())
|
||||
item_id = self.queue_review(path)
|
||||
start = self.capture([self.ref()])
|
||||
descriptor = await self.media(start)
|
||||
response = await self.current(descriptor["inspection_url"])
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_current_inspection_records_an_unqueued_file(self):
|
||||
"""#657 addendum D2: History's current-file read records as Images."""
|
||||
from tests.test_review import unlinkable_graph
|
||||
from utils.media_capture import CaptureStore
|
||||
|
||||
self.api._captures = CaptureStore(temp_parent=self.comfy_dir / "captures")
|
||||
self.addCleanup(self.api.close_annotation_captures)
|
||||
path = png(self.output_dir / "image.png", prompt=unlinkable_graph("a", "b"))
|
||||
start = self.capture([self.ref()])
|
||||
descriptor = await self.media(start)
|
||||
response = await self.current(descriptor["inspection_url"])
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
locator = os.path.normcase(os.path.realpath(path))
|
||||
(item,) = self.api.db.review_items_for(locator)
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item["id"]})
|
||||
|
||||
async def test_current_inspection_review_read_failure_is_null(self):
|
||||
from tests.test_inspection_review import two_samplers
|
||||
|
||||
path = png(self.output_dir / "image.png", prompt=two_samplers())
|
||||
self.queue_review(path)
|
||||
start = self.capture([self.ref()])
|
||||
descriptor = await self.media(start)
|
||||
with (
|
||||
self.assertLogs(self.api.logger, "WARNING"),
|
||||
patch.object(
|
||||
type(self.api.db),
|
||||
"review_item_at",
|
||||
side_effect=sqlite3.OperationalError("locked"),
|
||||
),
|
||||
):
|
||||
response = await self.current(descriptor["inspection_url"])
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
self.assertIsNone(body["review"])
|
||||
|
||||
@@ -90,6 +90,8 @@ class ImageAPITestCase(AioHTTPTestCase):
|
||||
await super().tearDownAsync() # closes the aiohttp test client
|
||||
# The automatic preview worker writes into the temp tree: stop it first.
|
||||
self.api.close_auto_thumbnails()
|
||||
# Inspect may record a Needs review item (#657 D2): drop its captures.
|
||||
self.api.close_annotation_captures()
|
||||
self._anchor_patch.stop()
|
||||
# Windows refuses to unlink a database that still has open handles.
|
||||
self.api.db.close_all()
|
||||
|
||||
@@ -188,11 +188,13 @@ class TestPromptInspector(ImageAPITestCase):
|
||||
for expected in ("ambiguous", "unresolved"):
|
||||
source = graph()
|
||||
if expected == "ambiguous":
|
||||
# Branches with different prompts (#249: identical ones resolve).
|
||||
# Branches with different prompts (#249: identical ones resolve;
|
||||
# #658: a role every branch shares is shown, so both differ).
|
||||
source["5"] = {"class_type": "CLIPTextEncode", "inputs": {"text": "x"}}
|
||||
source["6"] = {"class_type": "CLIPTextEncode", "inputs": {"text": "y"}}
|
||||
source["4"] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {"positive": ["5", 0], "negative": ["2", 0]},
|
||||
"inputs": {"positive": ["5", 0], "negative": ["6", 0]},
|
||||
}
|
||||
else:
|
||||
# No text and no links: nothing passes through it (#381).
|
||||
@@ -209,6 +211,95 @@ class TestPromptInspector(ImageAPITestCase):
|
||||
self.assertEqual(side["status"], expected)
|
||||
self.assertIsNone(side["text"])
|
||||
|
||||
def two_samplers(self, negative=("2", 0), positive=("5", 0)):
|
||||
"""Two unanchored samplers: node 3 reads 1 and 2, node 4 the given inputs."""
|
||||
source = graph()
|
||||
source["5"] = {"class_type": "CLIPTextEncode", "inputs": {"text": "x"}}
|
||||
source["6"] = {"class_type": "CLIPTextEncode", "inputs": {"text": "y"}}
|
||||
source["4"] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {"positive": list(positive), "negative": list(negative)},
|
||||
}
|
||||
return source
|
||||
|
||||
async def test_a_role_every_candidate_shares_is_shown_resolved(self):
|
||||
# #658: the negative is one text in every branch, so it is certain.
|
||||
png(self.output_dir / "image.png", prompt=self.two_samplers())
|
||||
_, result = await self.inspect()
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
self.assertEqual(result["prompts"]["negative"], self.side("blurry"))
|
||||
self.assertEqual(
|
||||
result["prompts"]["positive"],
|
||||
{"status": "ambiguous", "text": None, "source": None},
|
||||
)
|
||||
|
||||
async def test_a_role_with_an_unresolved_candidate_is_not_shared(self):
|
||||
# The second branch's positive fails, so its negative is never read.
|
||||
source = self.two_samplers(positive=("missing", 0))
|
||||
png(self.output_dir / "image.png", prompt=source)
|
||||
_, result = await self.inspect()
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
for role in ("positive", "negative"):
|
||||
self.assertEqual(result["prompts"][role]["status"], "ambiguous", role)
|
||||
self.assertIsNone(result["prompts"][role]["text"], role)
|
||||
|
||||
async def test_a_shared_role_needs_the_same_recipe(self):
|
||||
# Both positives read "a portrait", but one is a PromptManager recipe
|
||||
# ("portrait" with a prepend): the pair is ambiguous and the positive
|
||||
# is not shared; the negative is.
|
||||
source = self.two_samplers(positive=("7", 0))
|
||||
source["1"]["inputs"]["text"] = "a portrait"
|
||||
source["7"] = {
|
||||
"class_type": "PromptManager",
|
||||
"inputs": {"text": "portrait", "prepend_text": "a", "append_text": ""},
|
||||
}
|
||||
png(self.output_dir / "image.png", prompt=source)
|
||||
_, result = await self.inspect()
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
self.assertEqual(result["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertEqual(result["prompts"]["negative"], self.side("blurry"))
|
||||
|
||||
async def test_a_blank_shared_positive_is_withheld(self):
|
||||
from utils import prompt_inspector
|
||||
|
||||
def blank(item):
|
||||
return {
|
||||
**item,
|
||||
"positive": {**item["positive"], "text": " ", "storage_text": " "},
|
||||
}
|
||||
|
||||
png(self.output_dir / "image.png", prompt=self.two_samplers())
|
||||
real = prompt_inspector.inspection_resolution
|
||||
|
||||
def blanked(*args, **kwargs):
|
||||
inspected = real(*args, **kwargs)
|
||||
resolution = inspected.resolution
|
||||
resolution["candidates"] = [blank(c) for c in resolution["candidates"]]
|
||||
return inspected
|
||||
|
||||
with patch.object(prompt_inspector, "inspection_resolution", blanked):
|
||||
_, result = await self.inspect()
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
self.assertEqual(result["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertIsNone(result["prompts"]["positive"]["text"])
|
||||
self.assertEqual(result["prompts"]["negative"], self.side("blurry"))
|
||||
|
||||
async def test_any_switch_branches_share_their_negative(self):
|
||||
# #658 with #657: an unproven switch input offers two positives; the
|
||||
# negative encoder is the same in both, so it is shown.
|
||||
try:
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # discovered with ``-s tests``
|
||||
import unknown_node_graphs as switch_graphs
|
||||
source = switch_graphs.first_present_shapes()["through-unknown"]
|
||||
png(self.output_dir / "image.png", prompt=source)
|
||||
_, result = await self.inspect()
|
||||
self.assertEqual(result["resolution"]["state"], "ambiguous")
|
||||
self.assertEqual(result["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertEqual(
|
||||
result["prompts"]["negative"], self.side(switch_graphs.NEGATIVE)
|
||||
)
|
||||
|
||||
async def test_parameters_and_partial_resolution_are_conservative(self):
|
||||
path = self.output_dir / "image.png"
|
||||
png(path, parameters="A mountain\nNegative prompt: \nSteps: 20, Sampler: Euler")
|
||||
|
||||
@@ -744,6 +744,102 @@ class TestSaveRoute(RouteCoverageCase):
|
||||
self.assertFalse(data["success"])
|
||||
|
||||
|
||||
# #662 (F04): every legacy prompt route that reads a JSON body refuses a body
|
||||
# that is not a JSON object, or a field of the wrong type, with a 400.
|
||||
NOT_AN_OBJECT = [b"{bad", b"\xff", b"[]", b'"text"', b"123", b"null"]
|
||||
MALFORMED_BODY_ROUTES = (
|
||||
("PUT", "/prompt_manager/prompts/{id}", [{"text": 123}, {"text": ["a"]}]),
|
||||
("PUT", "/prompt_manager/prompts/{id}/rating", [{"rating": [1]}]),
|
||||
("POST", "/prompt_manager/prompts/{id}/tags", [{"tag": 123}, {"tag": ["a"]}]),
|
||||
(
|
||||
"DELETE",
|
||||
"/prompt_manager/prompts/{id}/tags",
|
||||
[{"tag": 123}, {"tag": True}, {"tag": ["a"]}],
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/prompt_manager/prompts/tags",
|
||||
[
|
||||
{"prompt_id": [1], "tags": ["a"]},
|
||||
{"prompt_id": True, "tags": ["a"]},
|
||||
{"prompt_id": 1.5, "tags": ["a"]},
|
||||
],
|
||||
),
|
||||
("PUT", "/prompt_manager/tags/old", [{"new_name": 123}, {"new_name": ["x"]}]),
|
||||
("POST", "/prompt_manager/tags/merge", [{"source_tags": ["old"], "target_tag": 5}]),
|
||||
(
|
||||
"POST",
|
||||
"/prompt_manager/bulk/delete",
|
||||
[
|
||||
{"prompt_ids": 123},
|
||||
{"prompt_ids": "1"},
|
||||
{"prompt_ids": [[1]]},
|
||||
{"prompt_ids": [True]},
|
||||
{"prompt_ids": [{"id": 1}]},
|
||||
],
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/prompt_manager/bulk/tags",
|
||||
[{"prompt_ids": 1, "tags": ["a"]}, {"prompt_ids": [[1]], "tags": ["a"]}],
|
||||
),
|
||||
("POST", "/prompt_manager/bulk/category", []),
|
||||
)
|
||||
|
||||
|
||||
class TestLegacyRoutesRefuseMalformedBodies(RouteCoverageCase):
|
||||
|
||||
async def test_each_malformed_body_is_400_and_changes_nothing(self):
|
||||
prompt_id = self._save_prompt("kept text", tags=["old"], rating=3)
|
||||
before = self.api.db.get_prompt_by_id(prompt_id)
|
||||
for method, template, wrong_types in MALFORMED_BODY_ROUTES:
|
||||
path = template.format(id=prompt_id)
|
||||
bodies = NOT_AN_OBJECT + [json.dumps(b).encode() for b in wrong_types]
|
||||
for body in bodies:
|
||||
with self.subTest(method=method, path=path, body=body):
|
||||
status, data = await self._json(
|
||||
method,
|
||||
path,
|
||||
data=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
self.assertEqual(status, 400)
|
||||
self.assertFalse(data["success"])
|
||||
self.assertIsInstance(data["error"], str)
|
||||
self.assertEqual(self.api.db.get_prompt_by_id(prompt_id), before)
|
||||
|
||||
async def test_valid_bodies_still_succeed(self):
|
||||
prompt_id = self._save_prompt("old text", tags=["old"])
|
||||
for method, path, body in (
|
||||
("PUT", f"/prompt_manager/prompts/{prompt_id}", {"text": "new text"}),
|
||||
("PUT", f"/prompt_manager/prompts/{prompt_id}/rating", {"rating": 4}),
|
||||
("POST", f"/prompt_manager/prompts/{prompt_id}/tags", {"tag": "b"}),
|
||||
("DELETE", f"/prompt_manager/prompts/{prompt_id}/tags", {"tag": "b"}),
|
||||
# The legacy page may send the id it read from the page as text.
|
||||
(
|
||||
"POST",
|
||||
"/prompt_manager/prompts/tags",
|
||||
{"prompt_id": str(prompt_id), "tags": ["c"]},
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/prompt_manager/bulk/tags",
|
||||
{"prompt_ids": [prompt_id], "tags": ["d"]},
|
||||
),
|
||||
):
|
||||
with self.subTest(method=method, path=path):
|
||||
status, data = await self._json(method, path, json=body)
|
||||
self.assertEqual(status, 200, data)
|
||||
stored = self.api.db.get_prompt_by_id(prompt_id)
|
||||
self.assertEqual(stored["text"], "new text")
|
||||
self.assertEqual(stored["rating"], 4)
|
||||
self.assertEqual(sorted(stored["tags"]), ["c", "d", "old"])
|
||||
status, data = await self._json(
|
||||
"POST", "/prompt_manager/bulk/delete", json={"prompt_ids": [prompt_id]}
|
||||
)
|
||||
self.assertEqual((status, data["deleted_count"]), (200, 1))
|
||||
|
||||
|
||||
class TestDeleteUpdateRatingRoutes(RouteCoverageCase):
|
||||
|
||||
async def test_delete_invalid_id_and_db_failure(self):
|
||||
|
||||
@@ -328,10 +328,20 @@ class TestQueueReads(ReviewRoutesTestCase):
|
||||
self._require_routes()
|
||||
self._roots()
|
||||
limited = self.output_dir / "limited.png"
|
||||
# More than 16 candidates with a prompt: limited, still a choice.
|
||||
many = [f"prompt {n}" for n in range(17)]
|
||||
write_png(limited, prompt=unlinkable_graph(*many))
|
||||
self.assertEqual(self._record_raw(str(limited)), "limited")
|
||||
# Evidence over the 8 MiB bound: limited, still a choice (more than
|
||||
# 16 prompts are collapsed instead, #657 D3).
|
||||
write_png(limited, prompt=unlinkable_graph("cat", "dog"))
|
||||
real = review_capture_module.canonical_evidence
|
||||
|
||||
def capped(value):
|
||||
if value.get("candidates"):
|
||||
raise ValueError("evidence exceeds the bound")
|
||||
return real(value)
|
||||
|
||||
with patch.object(
|
||||
review_capture_module, "canonical_evidence", side_effect=capped
|
||||
):
|
||||
self.assertEqual(self._record_raw(str(limited)), "limited")
|
||||
self._record(self._ambiguous("two.png"))
|
||||
items = (await self._list())["items"]
|
||||
self.assertEqual([i["limited"] for i in items], [True, False])
|
||||
@@ -361,6 +371,48 @@ class TestQueueReads(ReviewRoutesTestCase):
|
||||
self.assertFalse(data["success"])
|
||||
self._no_paths()
|
||||
|
||||
def _set_evidence(self, item_id, change):
|
||||
conn = self.api.db.model.get_connection()
|
||||
(text,) = conn.execute(
|
||||
"SELECT evidence FROM media_review_items WHERE id=?", (item_id,)
|
||||
).fetchone()
|
||||
evidence = json.loads(text)
|
||||
change(evidence)
|
||||
text = canonical_evidence(evidence)
|
||||
with conn:
|
||||
conn.execute(
|
||||
"UPDATE media_review_items SET evidence=?, evidence_hash=? WHERE id=?",
|
||||
(text, evidence_digest(text), item_id),
|
||||
)
|
||||
|
||||
async def test_detail_passes_a_collapsed_candidate_list_through(self):
|
||||
# #657 D3: a file with more distinct prompts than are kept says how many.
|
||||
self._require_routes()
|
||||
self._record(self._ambiguous("two.png"))
|
||||
item = (await self._list())["items"][0]
|
||||
self.assertIsNone((await self._detail(item["id"]))["collapsed"])
|
||||
collapsed = {"shown": 16, "total": 81, "paths": 165}
|
||||
self._set_evidence(
|
||||
item["id"], lambda evidence: evidence.update(collapsed=collapsed)
|
||||
)
|
||||
detail = await self._detail(item["id"])
|
||||
self.assertEqual(detail["collapsed"], collapsed)
|
||||
self.assertEqual(len(detail["candidates"]), 2)
|
||||
# Anything but three counts is not shown.
|
||||
for wrong in ({"shown": "16", "total": 81, "paths": 165}, [16], None):
|
||||
self._set_evidence(
|
||||
item["id"],
|
||||
lambda evidence, wrong=wrong: evidence.update(collapsed=wrong),
|
||||
)
|
||||
self.assertIsNone((await self._detail(item["id"]))["collapsed"])
|
||||
# A detail capped for size lists nothing, so nothing is collapsed either.
|
||||
self._set_evidence(
|
||||
item["id"], lambda evidence: evidence.update(collapsed=collapsed)
|
||||
)
|
||||
with patch.object(review_api, "MAX_DETAIL_BYTES", 200):
|
||||
capped = await self._detail(item["id"])
|
||||
self.assertEqual((capped["limited"], capped["collapsed"]), (True, None))
|
||||
|
||||
async def test_label_uses_library_title_of_a_saved_prompt(self):
|
||||
self._require_routes()
|
||||
prompt_id = self.api.db.save_prompt(
|
||||
@@ -524,7 +576,9 @@ class TestDecisions(ReviewRoutesTestCase):
|
||||
self.assertEqual(provenance["kind"], "user-selection")
|
||||
self.assertEqual(provenance["candidate_hash"], cat["hash"])
|
||||
self.assertEqual(provenance["reviewed_digest"], digest(path))
|
||||
self.assertEqual(provenance["resolver_version"], 1)
|
||||
self.assertEqual(
|
||||
provenance["resolver_version"], review_capture_module.default_item_version()
|
||||
)
|
||||
self.assertEqual(provenance["positive"]["text"], "cat")
|
||||
(decision,) = self._decisions()
|
||||
self.assertEqual(provenance["decision_id"], decision["id"])
|
||||
|
||||
@@ -273,6 +273,12 @@ class TestNodeIntegration(unittest.TestCase):
|
||||
# Check optional inputs
|
||||
self.assertIn("search_text", input_types["optional"])
|
||||
|
||||
# Every optional STRING starts empty, so the schema offers "" and not
|
||||
# null: the composition sockets used to be the only ones without a
|
||||
# default, although the node already treats them as empty.
|
||||
for name in ("category", "tags", "search_text", "prepend_text", "append_text"):
|
||||
self.assertEqual(input_types["optional"][name][1]["default"], "", name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""ComfyUI's EXIF records: what WebP, AVIF and JPEG carry instead of text.
|
||||
|
||||
ComfyUI's SaveAnimatedWEBP writes ``prompt:{json}`` to EXIF tag 0x0110, then
|
||||
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down;
|
||||
the AVIF writer uses that layout too. Pillow exposes them only through
|
||||
``getexif()``, so a reader that looks at ``image.info`` or the text chunks
|
||||
finds nothing. These tests write real files in that layout.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from PIL import Image, features
|
||||
|
||||
from utils.exif_text import exif_text
|
||||
|
||||
PROMPT = {"1": {"class_type": "KSampler", "inputs": {"seed": 7}}}
|
||||
WORKFLOW = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "cat"}}]}
|
||||
PAIRS = [{"positive": "cat", "negative": "dog"}]
|
||||
|
||||
|
||||
def comfyui_exif(prompt=PROMPT, extra=None):
|
||||
"""The tags ComfyUI writes: the prompt on 0x0110, extra_pnginfo from 0x010F."""
|
||||
exif = Image.Exif()
|
||||
if prompt is not None:
|
||||
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
|
||||
tag = 0x010F
|
||||
for key, value in ({"workflow": WORKFLOW} if extra is None else extra).items():
|
||||
exif[tag] = f"{key}:{json.dumps(value)}"
|
||||
tag -= 1
|
||||
return exif
|
||||
|
||||
|
||||
class ExifTextCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.folder = folder.name
|
||||
|
||||
def write(self, name, image_format, exif, **options):
|
||||
path = os.path.join(self.folder, name)
|
||||
Image.new("RGB", (8, 8), "red").save(path, image_format, exif=exif, **options)
|
||||
return path
|
||||
|
||||
def read(self, path):
|
||||
with Image.open(path) as image:
|
||||
return exif_text(image)
|
||||
|
||||
|
||||
class TestComfyuiRecords(ExifTextCase):
|
||||
def test_reads_the_records_of_a_webp(self):
|
||||
path = self.write("a.webp", "WEBP", comfyui_exif())
|
||||
|
||||
self.assertEqual(
|
||||
self.read(path),
|
||||
{"prompt": json.dumps(PROMPT), "workflow": json.dumps(WORKFLOW)},
|
||||
)
|
||||
|
||||
def test_reads_an_animated_webp(self):
|
||||
# SaveAnimatedWEBP writes the first frame's EXIF and appends the rest.
|
||||
frames = [Image.new("RGB", (8, 8), color) for color in ("red", "blue")]
|
||||
path = os.path.join(self.folder, "anim.webp")
|
||||
frames[0].save(
|
||||
path,
|
||||
"WEBP",
|
||||
save_all=True,
|
||||
append_images=frames[1:],
|
||||
duration=100,
|
||||
exif=comfyui_exif(),
|
||||
)
|
||||
|
||||
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
|
||||
|
||||
def test_reads_every_extra_pnginfo_key_and_not_only_the_workflow(self):
|
||||
exif = comfyui_exif(
|
||||
extra={"workflow": WORKFLOW, "comfyassets_prompt_pairs": PAIRS}
|
||||
)
|
||||
path = self.write("pairs.webp", "WEBP", exif)
|
||||
|
||||
self.assertEqual(self.read(path)["comfyassets_prompt_pairs"], json.dumps(PAIRS))
|
||||
|
||||
def test_reads_a_jpeg_in_the_same_layout(self):
|
||||
# Not a core saver, but a third-party one reusing the convention.
|
||||
path = self.write("a.jpg", "JPEG", comfyui_exif())
|
||||
|
||||
self.assertEqual(self.read(path)["prompt"], json.dumps(PROMPT))
|
||||
|
||||
@unittest.skipUnless(features.check("avif"), "Pillow has no AVIF support")
|
||||
def test_reads_an_avif(self):
|
||||
path = self.write("a.avif", "AVIF", comfyui_exif())
|
||||
|
||||
self.assertEqual(self.read(path)["workflow"], json.dumps(WORKFLOW))
|
||||
|
||||
|
||||
class TestOtherExif(ExifTextCase):
|
||||
def test_a_camera_exif_is_not_a_comfyui_record(self):
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "Canon" # Make
|
||||
exif[0x0110] = "Canon EOS R5" # Model
|
||||
exif[0x0131] = "GIMP 2.10.38" # Software
|
||||
exif[0x0132] = "2024:01:02 03:04:05" # DateTime
|
||||
path = self.write("camera.jpg", "JPEG", exif)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
def test_a_value_that_is_not_json_is_not_a_record(self):
|
||||
exif = Image.Exif()
|
||||
exif[0x010E] = "note:not json"
|
||||
exif[0x010D] = "make:Canon"
|
||||
path = self.write("notes.webp", "WEBP", exif)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
def test_a_png_answers_empty_its_records_are_text_chunks(self):
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
|
||||
info = PngInfo()
|
||||
info.add_text("workflow", json.dumps(WORKFLOW))
|
||||
path = os.path.join(self.folder, "a.png")
|
||||
Image.new("RGB", (8, 8)).save(path, pnginfo=info)
|
||||
|
||||
self.assertEqual(self.read(path), {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -13,6 +13,7 @@ from database.run_attribution import RecordedOutput
|
||||
from tests.test_pair_scan import flux_graph, sampled_graph
|
||||
from tests.test_prompt_attribution import issue_graph, pair_evidence
|
||||
from tests import test_save_to_library as save_tests
|
||||
from tests.sweep_graphs import ambiguous_sweep_graph
|
||||
from utils import file_prompt
|
||||
from utils.file_prompt import Policy, decide_file_prompt, junk_text
|
||||
from utils.prompt_inspector import InspectionResult
|
||||
@@ -20,9 +21,11 @@ from utils.prompt_inspector import InspectionResult
|
||||
try:
|
||||
from tests import inspection_parity as parity
|
||||
from tests import saver_anchor_graphs as shapes
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
import inspection_parity as parity
|
||||
import saver_anchor_graphs as shapes
|
||||
import unknown_node_graphs as switch_graphs
|
||||
|
||||
SHARED_NAME = "IMG_GEN_00371_.png"
|
||||
LORA = "<lora:style:1.00>"
|
||||
@@ -418,6 +421,17 @@ class TestUndecidedGraph(unittest.TestCase):
|
||||
self.assertEqual(decision.text, parity.POS)
|
||||
self.assertEqual(decision.resolution["state"], "unresolved")
|
||||
|
||||
def test_step_8_1_the_inspector_links_the_any_switch_sweep(self):
|
||||
# #657: the default profile cannot read rgthree's Any Switch; the
|
||||
# inspector proves its first input and links it under both policies.
|
||||
graph = switch_graphs.any_switch_sweep_graph()
|
||||
for policy in (Policy.SCAN, Policy.MONITOR):
|
||||
with self.subTest(policy=policy):
|
||||
decision = _decide(_graph(graph), policy=policy, lookup=_Lookup())
|
||||
self.assertEqual(decision.kind, "positive")
|
||||
self.assertEqual(decision.source, "inspector")
|
||||
self.assertEqual(decision.text, switch_graphs.POSITIVE)
|
||||
|
||||
def test_step_8_1_the_recorded_saver_names_its_branch(self):
|
||||
lookup = _Lookup("23")
|
||||
decision = _decide(_graph(shapes.shared_prefix()), lookup=lookup)
|
||||
@@ -761,5 +775,37 @@ class TestParseComfyuiPrompt(unittest.TestCase):
|
||||
self.assertIsNone(parsed["positive_prompt"])
|
||||
|
||||
|
||||
class TestDefaultUnresolved(unittest.TestCase):
|
||||
"""#659 C2: ``default_unresolved`` marks a graph the default profile
|
||||
itself calls unresolved, so a scan can still offer its inspection
|
||||
choices in Needs review."""
|
||||
|
||||
def test_the_sweep_graph_is_default_unresolved(self):
|
||||
decision = _decide(_graph(ambiguous_sweep_graph()), lookup=_Lookup())
|
||||
self.assertEqual(decision.kind, "never")
|
||||
self.assertIsNone(decision.review)
|
||||
self.assertTrue(decision.default_unresolved)
|
||||
self.assertEqual(decision.unlinked_status, "unresolved")
|
||||
|
||||
def test_a_blank_positive_is_not_default_unresolved(self):
|
||||
meta = {
|
||||
"prompt": json.dumps(issue_graph()),
|
||||
"comfyassets_prompt_pairs": json.dumps(pair_evidence()),
|
||||
}
|
||||
decision = _decide(meta, lookup=_Lookup())
|
||||
self.assertEqual(decision.resolution["state"], "unresolved")
|
||||
self.assertFalse(decision.default_unresolved)
|
||||
|
||||
def test_resolved_and_ambiguous_graphs_are_not_default_unresolved(self):
|
||||
for name, graph in (
|
||||
("resolved", sampled_graph("cat", "blur")),
|
||||
("ambiguous", shapes.shared_prefix()),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
decision = _decide(_graph(graph), lookup=_Lookup())
|
||||
self.assertFalse(decision.default_unresolved)
|
||||
self.assertFalse(_decide({}).default_unresolved)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -9,13 +9,22 @@ and leaves no wait behind.
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from tests import saver_anchor_graphs as shapes
|
||||
from tests import test_run_attribution as attribution
|
||||
from tests import test_save_to_library as save_tests
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
from tests.sweep_graphs import (
|
||||
JOINED_TEXT,
|
||||
joined_prompt_manager_graph,
|
||||
prompt_manager_shared_prefix,
|
||||
ambiguous_sweep_graph,
|
||||
)
|
||||
from tests.test_pair_scan import sampled_graph
|
||||
from utils.foreign_runs import ForeignRecheck
|
||||
from utils.hashing import generate_prompt_hash
|
||||
from utils.run_keys import prompt_node_key
|
||||
from py.config import GalleryConfig # after tests: it stubs the host
|
||||
|
||||
LOGGER = "prompt_manager.image_monitor"
|
||||
@@ -213,7 +222,9 @@ class TestForeignPathKeepsSaveToLibrary(attribution.RecordedRuns, unittest.TestC
|
||||
file waits for a foreign re-check."""
|
||||
cases = (
|
||||
("off", False, "opted_out", SKIPPED),
|
||||
("wired", ["52", 0], "unknown", "No certain prompt for"),
|
||||
# A PromptManager run asks the ladder (#659), whose #90 step
|
||||
# reads the wired switch: nothing is stored
|
||||
("wired", ["52", 0], "unknown", "Save to library is wired from a node"),
|
||||
)
|
||||
for name, save, state, line in cases:
|
||||
with self.subTest(name=name):
|
||||
@@ -326,5 +337,262 @@ class TestForeignPathKeepsSaveToLibrary(attribution.RecordedRuns, unittest.TestC
|
||||
self.assertEqual(self.linked_text(path), shapes.BRANCH_TEXTS[0])
|
||||
|
||||
|
||||
class TestPromptManagerRunsAskTheLadder(attribution.RecordedRuns, unittest.TestCase):
|
||||
"""#659 Part 3: a PromptManager run the default profile and the tracked
|
||||
run cannot link asks the ladder, as a foreign run does."""
|
||||
|
||||
close_databases = Fixture["close_databases"]
|
||||
wait_for = Fixture["wait_for"]
|
||||
image = Fixture["image"]
|
||||
linked_text = Fixture["linked_text"]
|
||||
key = Fixture["key"]
|
||||
prompt_count = Fixture["prompt_count"]
|
||||
settled = Fixture["settled"]
|
||||
seal = TestForeignPathKeepsSaveToLibrary.seal
|
||||
|
||||
def setUp(self):
|
||||
Fixture["setUp"](self)
|
||||
enabled = GalleryConfig.MONITORING_ENABLED
|
||||
self.addCleanup(setattr, GalleryConfig, "MONITORING_ENABLED", enabled)
|
||||
GalleryConfig.MONITORING_ENABLED = True
|
||||
|
||||
def prompt(self, text):
|
||||
return self.db.get_prompt_by_hash(generate_prompt_hash(text))
|
||||
|
||||
def test_an_output_the_inspector_resolves_links_at_settle(self):
|
||||
self.metadata = {"prompt": joined_prompt_manager_graph()}
|
||||
state, _ = self.handler._find_prompt_from_metadata(self.metadata)
|
||||
self.assertEqual(state, "unknown") # a PromptManager run, not foreign
|
||||
path = self.image("IMG_GEN_00001_.png")
|
||||
with self.assertLogs(LOGGER, "INFO") as logs:
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIn("(inspector)", "\n".join(logs.output))
|
||||
self.assertEqual(self.linked_text(path), JOINED_TEXT)
|
||||
prompt = self.prompt(JOINED_TEXT)
|
||||
self.assertEqual(prompt["category"], "scanned")
|
||||
self.assertIn("Auto-scanned from IMG_GEN_00001_.png", prompt["notes"])
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_an_output_only_history_decides_links_after_its_run_is_sealed(self):
|
||||
self.metadata = {"prompt": prompt_manager_shared_prefix()}
|
||||
path = self.image("IMG_GEN_00002_.png")
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIsNone(self.linked_text(path))
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [self.key(path)])
|
||||
# Foreign entries only: the PromptManager entry is not foreign
|
||||
self.assertEqual(self.handler.awaiting_foreign(), [])
|
||||
self.seal(path, nodes=("13",))
|
||||
self.assertTrue(self.wait_for(lambda: self.linked_text(path)))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertEqual(self.linked_text(path), shapes.BRANCH_TEXTS[0])
|
||||
prompt = self.prompt(shapes.BRANCH_TEXTS[0])
|
||||
self.assertIn("Auto-scanned from IMG_GEN_00002_.png", prompt["notes"])
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_the_rgthree_sweep_links_at_settle_from_the_inspector(self):
|
||||
"""#657: the real Any Switch outputs its first proven input, so the
|
||||
maintainer's sweep links to the PromptManagerText text."""
|
||||
self.metadata = {"prompt": switch_graphs.any_switch_sweep_graph()}
|
||||
path = self.image("sweep_00009_.png")
|
||||
with self.assertLogs(LOGGER, "INFO") as logs:
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIn("(inspector)", "\n".join(logs.output))
|
||||
self.assertEqual(self.linked_text(path), switch_graphs.POSITIVE)
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_an_output_the_inspector_calls_ambiguous_is_not_linked(self):
|
||||
self.metadata = {"prompt": ambiguous_sweep_graph()}
|
||||
path = self.image("sweep_00001_.png")
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIsNone(self.linked_text(path))
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [self.key(path)])
|
||||
self.seal(path, nodes=("28",))
|
||||
self.assertTrue(self.wait_for(lambda: not self.handler.awaiting_ladder()))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertIsNone(self.linked_text(path))
|
||||
self.assertEqual(self.prompt_count(), 0)
|
||||
|
||||
def test_save_to_library_off_stores_nothing(self):
|
||||
wired = joined_prompt_manager_graph(save=["20", 0])
|
||||
wired["20"] = {"class_type": "SomeBoolNode", "inputs": {}}
|
||||
cases = (
|
||||
("off", joined_prompt_manager_graph(save=False), SKIPPED),
|
||||
("wired", wired, "Save to library is wired from a node"),
|
||||
)
|
||||
for name, graph, line in cases:
|
||||
with self.subTest(name=name):
|
||||
self.metadata = {"prompt": graph}
|
||||
path = self.image(f"IMG_GEN_{name}_00001_.png")
|
||||
with self.assertLogs(LOGGER, "INFO") as logs:
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIn(line, "\n".join(logs.output))
|
||||
self.assertIsNone(self.linked_text(path))
|
||||
self.assertEqual(self.prompt_count(), 0)
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_the_foreign_setting_gates_foreign_entries_only(self):
|
||||
GalleryConfig.SAVE_FOREIGN_RUNS = False
|
||||
self.metadata = {"prompt": joined_prompt_manager_graph()}
|
||||
own = self.image("IMG_GEN_00003_.png")
|
||||
self.handler.process_new_image(own)
|
||||
self.assertEqual(self.linked_text(own), JOINED_TEXT)
|
||||
self.metadata = {"prompt": sampled_graph("a red barn", "blurry")}
|
||||
foreign = self.image("plain_00001_.png")
|
||||
self.handler.process_new_image(foreign)
|
||||
self.assertIsNone(self.linked_text(foreign))
|
||||
|
||||
def test_monitoring_off_stops_both_kinds(self):
|
||||
GalleryConfig.MONITORING_ENABLED = False
|
||||
self.metadata = {"prompt": joined_prompt_manager_graph()}
|
||||
own = self.image("IMG_GEN_00004_.png")
|
||||
self.handler.process_new_image(own)
|
||||
self.metadata = {"prompt": sampled_graph("a red barn", "blurry")}
|
||||
foreign = self.image("plain_00002_.png")
|
||||
self.handler.process_new_image(foreign)
|
||||
self.assertEqual([self.linked_text(own), self.linked_text(foreign)], [None] * 2)
|
||||
self.assertEqual(self.prompt_count(), 0)
|
||||
|
||||
def test_monitoring_off_after_the_settle_stores_nothing_at_the_recheck(self):
|
||||
self.metadata = {"prompt": prompt_manager_shared_prefix()}
|
||||
path = self.image("IMG_GEN_00005_.png")
|
||||
self.handler.process_new_image(path)
|
||||
GalleryConfig.MONITORING_ENABLED = False
|
||||
self.seal(path, nodes=("13",))
|
||||
self.assertTrue(self.wait_for(lambda: not self.handler.awaiting_ladder()))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertIsNone(self.linked_text(path))
|
||||
self.assertEqual(self.prompt_count(), 0)
|
||||
|
||||
def test_keyless_placeholder_and_unreadable_files_never_ask_the_ladder(self):
|
||||
from utils import image_monitor
|
||||
|
||||
graph = joined_prompt_manager_graph()
|
||||
self.tracker.mark_empty(prompt_node_key(graph, "1"), "run-1")
|
||||
placeholder = self.image("IMG_GEN_00006_.png")
|
||||
keyless = self.image("bare_00001_.png", subfolder="")
|
||||
unreadable = self.image("bare_00002_.png", subfolder="")
|
||||
with mock.patch.object(
|
||||
image_monitor, "decide_foreign", wraps=image_monitor.decide_foreign
|
||||
) as ladder:
|
||||
self.metadata = {"prompt": graph}
|
||||
self.handler.process_new_image(placeholder)
|
||||
self.metadata = None
|
||||
self.handler.process_new_image(keyless)
|
||||
with mock.patch.object(
|
||||
self.handler.metadata_extractor,
|
||||
"extract_metadata",
|
||||
side_effect=OSError("truncated"),
|
||||
):
|
||||
self.handler.process_new_image(unreadable)
|
||||
ladder.assert_not_called()
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
self.assertEqual(
|
||||
sorted(self.handler.awaiting_history()),
|
||||
sorted([self.key(keyless), self.key(unreadable)]),
|
||||
)
|
||||
self.assertIsNone(self.linked_text(placeholder))
|
||||
|
||||
|
||||
class TestFinalUnlinkedOutcomesQueueForReview(
|
||||
attribution.RecordedRuns, unittest.TestCase
|
||||
):
|
||||
"""#659 Part 4: the monitor hands a file to Needs review only at its
|
||||
final unlinked outcome, after run history had its say."""
|
||||
|
||||
close_databases = Fixture["close_databases"]
|
||||
wait_for = Fixture["wait_for"]
|
||||
image = Fixture["image"]
|
||||
linked_text = Fixture["linked_text"]
|
||||
key = Fixture["key"]
|
||||
settled = Fixture["settled"]
|
||||
seal = TestForeignPathKeepsSaveToLibrary.seal
|
||||
|
||||
def setUp(self):
|
||||
Fixture["setUp"](self)
|
||||
self.queued = []
|
||||
self.handler.review_recorder = lambda path: self.queued.append(
|
||||
os.path.basename(path)
|
||||
)
|
||||
|
||||
def test_nothing_is_queued_before_the_run_is_sealed(self):
|
||||
self.metadata = {"prompt": ambiguous_sweep_graph()}
|
||||
path = self.image("sweep_00001_.png")
|
||||
self.handler.process_new_image(path)
|
||||
self.assertEqual(self.queued, [])
|
||||
self.seal(path, nodes=("28",))
|
||||
self.assertTrue(self.wait_for(lambda: self.queued))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertEqual(self.queued, ["sweep_00001_.png"])
|
||||
|
||||
def test_a_foreign_file_unlinked_after_its_seal_is_queued(self):
|
||||
self.metadata = {"prompt": shapes.shared_prefix()}
|
||||
path = self.image("IMG_GEN_00001_.png")
|
||||
reported = [("dataset", "IMG_GEN_00001_.png")] * 2
|
||||
self.handler.process_new_image(path)
|
||||
self.assertEqual(self.queued, [])
|
||||
# One run reported it from two savers: a record, but no saver
|
||||
self.record_run(self.db, self.output, reported, [], nodes=["13", "23"])
|
||||
self.assertTrue(self.wait_for(lambda: self.queued))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertEqual(self.queued, ["IMG_GEN_00001_.png"])
|
||||
|
||||
def test_a_record_found_at_settle_without_a_prompt_queues_at_once(self):
|
||||
self.metadata = {"prompt": ambiguous_sweep_graph()}
|
||||
path = self.image("sweep_00002_.png")
|
||||
self.seal(path, nodes=("28",))
|
||||
self.handler.process_new_image(path)
|
||||
self.assertEqual(self.queued, ["sweep_00002_.png"])
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_a_file_outside_the_output_folder_is_queued_at_once(self):
|
||||
outside = self.image("sweep_00003_.png", subfolder="")
|
||||
with mock.patch(
|
||||
"utils.image_monitor.host_output_directory",
|
||||
return_value=os.path.join(self.output, "dataset"),
|
||||
):
|
||||
for graph in (ambiguous_sweep_graph(), shapes.shared_prefix()):
|
||||
self.metadata = {"prompt": graph}
|
||||
self.handler.process_new_image(outside)
|
||||
self.assertEqual(self.queued, ["sweep_00003_.png"] * 2)
|
||||
self.assertEqual(self.handler.awaiting_ladder(), [])
|
||||
|
||||
def test_a_linked_or_waiting_file_is_not_queued(self):
|
||||
self.metadata = {"prompt": joined_prompt_manager_graph()}
|
||||
self.handler.process_new_image(self.image("IMG_GEN_00002_.png"))
|
||||
self.metadata = {"prompt": prompt_manager_shared_prefix()}
|
||||
waiting = self.image("IMG_GEN_00003_.png")
|
||||
self.handler.process_new_image(waiting)
|
||||
self.seal(waiting, nodes=("13",))
|
||||
self.assertTrue(self.wait_for(lambda: self.linked_text(waiting)))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertEqual(self.queued, [])
|
||||
|
||||
def test_the_keyless_recheck_queues_a_file_history_does_not_name(self):
|
||||
path = self.image("bare_00001_.png", subfolder="")
|
||||
self.metadata = None
|
||||
self.handler.process_new_image(path)
|
||||
self.assertEqual(self.queued, [])
|
||||
self.record_run(self.db, self.output, [("", "bare_00001_.png")], [])
|
||||
self.assertTrue(self.wait_for(lambda: self.queued))
|
||||
self.assertTrue(self.settled())
|
||||
self.assertEqual(self.queued, ["bare_00001_.png"])
|
||||
|
||||
def test_a_recorder_failure_keeps_the_monitor_running(self):
|
||||
def broken(path):
|
||||
raise RuntimeError("recorder broke")
|
||||
|
||||
self.handler.review_recorder = broken
|
||||
self.metadata = {"prompt": ambiguous_sweep_graph()}
|
||||
path = self.image("sweep_00004_.png")
|
||||
self.seal(path, nodes=("28",))
|
||||
with self.assertLogs(LOGGER, "WARNING") as logs:
|
||||
self.handler.process_new_image(path)
|
||||
self.assertIn("could not be added to Needs review", "\n".join(logs.output))
|
||||
self.metadata = {"prompt": joined_prompt_manager_graph()}
|
||||
linked = self.image("IMG_GEN_00004_.png")
|
||||
self.handler.process_new_image(linked)
|
||||
self.assertEqual(self.linked_text(linked), JOINED_TEXT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -589,6 +589,9 @@ class TestStartAndExclusion(ImageTagJobTestCase):
|
||||
{"mode": "add", "targets": [target], "tags": ["x"], "extra": 1},
|
||||
{"mode": "add", "targets": [target], "tags": ["x"], "model_type": "hf"},
|
||||
{"mode": "remove", "targets": [target], "tags": ["x"]},
|
||||
# #662: a mode that is no text is a refusal, not a server error.
|
||||
{"mode": [], "targets": [target], "tags": ["x"]},
|
||||
{"mode": {}, "targets": [target], "tags": ["x"]},
|
||||
{"targets": [target], "tags": ["x"]},
|
||||
{"mode": "auto", "targets": [target], "model_type": "wd14-vit"},
|
||||
{"mode": "auto", "targets": [target], "model_type": "x", "options": {}},
|
||||
|
||||
@@ -815,6 +815,53 @@ class TestPackageTeardown(PackageTeardownCase):
|
||||
self.assertFalse(parallel.job_pool_started())
|
||||
self.assertFalse(any(t.is_alive() for t in threads))
|
||||
|
||||
def test_teardown_stops_the_review_worker_after_the_monitor(self):
|
||||
"""#659 C5: a started review worker is the part ``review``, stopped
|
||||
right after the monitor."""
|
||||
package = self.load()
|
||||
api, monitor = package.api, package._global_image_monitor
|
||||
self.assertEqual(monitor.review_recorder, api.queue_review_file)
|
||||
done = threading.Event()
|
||||
real_record = api.record_review_file
|
||||
|
||||
def record(path):
|
||||
try:
|
||||
return real_record(path)
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
order = []
|
||||
real_stop_monitor = monitor.stop_monitoring
|
||||
real_stop_review = api.stop_review_worker
|
||||
|
||||
def stop_monitor(timeout):
|
||||
order.append("monitor")
|
||||
return real_stop_monitor(timeout)
|
||||
|
||||
def stop_review(timeout):
|
||||
order.append("review")
|
||||
return real_stop_review(timeout)
|
||||
|
||||
with (
|
||||
mock.patch.object(api, "record_review_file", record),
|
||||
mock.patch.object(monitor, "stop_monitoring", stop_monitor),
|
||||
mock.patch.object(api, "stop_review_worker", stop_review),
|
||||
):
|
||||
self.assertEqual(
|
||||
api.queue_review_file(os.path.join(self.tmp.name, "x.png")), "queued"
|
||||
)
|
||||
self.assertTrue(done.wait(WAIT_SECONDS))
|
||||
thread = api._review_worker()._thread
|
||||
result = package._stop_background_work()
|
||||
|
||||
self.assertEqual(order, ["monitor", "review"])
|
||||
self.assertEqual(
|
||||
list(result), ["monitor", "review", "thumbnails", "tracker"], result
|
||||
)
|
||||
self.assertTrue(all(result.values()), result)
|
||||
self.assertFalse(thread.is_alive())
|
||||
self.assertEqual(api.queue_review_file("late.png"), "stopped")
|
||||
|
||||
def test_teardown_reports_a_job_thread_past_its_bound(self):
|
||||
package = self.load(require_stopped=False)
|
||||
parallel = sys.modules[package.__name__ + ".utils.parallel"]
|
||||
|
||||
@@ -918,6 +918,70 @@ class TestImageTagsFacet(unittest.TestCase):
|
||||
self.assertNotIn("image_tags", self.history_encoded(None))
|
||||
|
||||
|
||||
class TestReviewFacet(unittest.TestCase):
|
||||
"""#659 (C4): both envelopes carry ``review``: a pending item, decided, or null."""
|
||||
|
||||
ITEM = "0a1b2c3d-0000-4000-8000-00000000abcd"
|
||||
SHAPES = (
|
||||
{"state": "pending", "item_id": ITEM},
|
||||
{"state": "decided"},
|
||||
)
|
||||
INVALID = (
|
||||
"pending",
|
||||
["pending"],
|
||||
{},
|
||||
{"state": "pending"},
|
||||
{"state": "pending", "item_id": 123},
|
||||
{"state": "pending", "item_id": "not-an-id"},
|
||||
{"state": "pending", "item_id": ITEM.upper()},
|
||||
{"state": "pending", "item_id": ITEM, "locator": "/abs/a.png"},
|
||||
{"state": "decided", "item_id": ITEM},
|
||||
{"state": "unresolved"},
|
||||
)
|
||||
|
||||
def _common(self, review):
|
||||
return {
|
||||
"file": {"observation": "current-file", "size": 100},
|
||||
"prompts": PROMPTS,
|
||||
"resolution": {"state": "resolved", "sampler_id": "3", "reason": ""},
|
||||
"inspection": inspection({"prompt": graph_text()}),
|
||||
"library": {"status": "none"},
|
||||
**({} if review is ... else {"review": review}),
|
||||
}
|
||||
|
||||
def encoded(self, review=...):
|
||||
body = encode_inspection_response(
|
||||
image=IMAGE, root_scope="a" * 64, **self._common(review)
|
||||
)
|
||||
return json.loads(body)
|
||||
|
||||
def history_encoded(self, review=...):
|
||||
from utils.inspection_response import encode_history_inspection_response
|
||||
|
||||
body = encode_history_inspection_response(
|
||||
current_output={"history_epoch": "epoch"}, **self._common(review)
|
||||
)
|
||||
return json.loads(body)
|
||||
|
||||
def test_both_shapes_pass_through_both_envelopes(self):
|
||||
for review in self.SHAPES:
|
||||
for encode_with in (self.encoded, self.history_encoded):
|
||||
with self.subTest(review=review, envelope=encode_with.__name__):
|
||||
self.assertEqual(encode_with(review)["review"], review)
|
||||
|
||||
def test_null_is_the_default(self):
|
||||
for encode_with in (self.encoded, self.history_encoded):
|
||||
with self.subTest(envelope=encode_with.__name__):
|
||||
self.assertIsNone(encode_with()["review"])
|
||||
self.assertIsNone(encode_with(None)["review"])
|
||||
|
||||
def test_any_other_value_is_null(self):
|
||||
for review in self.INVALID:
|
||||
for encode_with in (self.encoded, self.history_encoded):
|
||||
with self.subTest(review=review, envelope=encode_with.__name__):
|
||||
self.assertIsNone(encode_with(review)["review"])
|
||||
|
||||
|
||||
class TestVideoProbeBoundsMatchPngBudgets(unittest.TestCase):
|
||||
"""ffprobe escapes tag text; the stdout bounds must never gate a record
|
||||
that the identical PNG reads within its decoded budget (I3)."""
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
"""Inspect's ``review`` field (#659, design Part 5, contract C4).
|
||||
|
||||
The Inspect response names the file's Needs review item when a role is
|
||||
ambiguous and the file is unlinked: ``{"state": "pending", "item_id": ...}``
|
||||
for an item that waits, ``{"state": "decided"}`` once the user decided it,
|
||||
``null`` otherwise. It is looked up by the file's locator and the stat the
|
||||
inspection took, never by hashing the file.
|
||||
|
||||
Inspect records the item (#657 addendum D2): when such a file has no item at
|
||||
that stat, the handler runs the review worker's own per-file path
|
||||
(``record_review_file``: the job blocker, the root and linked checks, the
|
||||
scan's ladder, ``review_dispatch``) in the executor and answers the new item.
|
||||
A file the scan would link or that offers nothing to choose records nothing;
|
||||
a recording error is logged and the field stays ``null``.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from unittest.mock import patch
|
||||
|
||||
try:
|
||||
from test_api_images import ImageAPITestCase
|
||||
from test_api_prompt_inspector import graph, png
|
||||
from test_review import unlinkable_graph
|
||||
except ImportError:
|
||||
from tests.test_api_images import ImageAPITestCase
|
||||
from tests.test_api_prompt_inspector import graph, png
|
||||
from tests.test_review import unlinkable_graph
|
||||
|
||||
from utils.media_capture import CaptureCapacity, CaptureStore
|
||||
from utils.review_capture import default_item_version as current_version
|
||||
|
||||
NOW = "2026-11-19T00:00:00+00:00"
|
||||
|
||||
|
||||
def two_samplers(first="golden dunes", second="harbor lights", negative="blur"):
|
||||
"""Two samplers, each with its own positive encoder: the inspector is ambiguous."""
|
||||
nodes = {
|
||||
"1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "m"}},
|
||||
"2": {"class_type": "CLIPTextEncode", "inputs": {"text": negative}},
|
||||
}
|
||||
for index, text in enumerate((first, second)):
|
||||
encoder, sampler = str(10 + 2 * index), str(11 + 2 * index)
|
||||
nodes[encoder] = {"class_type": "CLIPTextEncode", "inputs": {"text": text}}
|
||||
nodes[sampler] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"model": ["1", 0],
|
||||
"positive": [encoder, 0],
|
||||
"negative": ["2", 0],
|
||||
},
|
||||
}
|
||||
return nodes
|
||||
|
||||
|
||||
class ReviewItemsMixin:
|
||||
"""Queue items for a file under the output root, as the recorder stores them."""
|
||||
|
||||
def locator(self, path):
|
||||
relative = path.relative_to(self.output_dir).parts
|
||||
spelled = os.path.join(os.path.realpath(self.output_dir), *relative)
|
||||
return os.path.normcase(spelled), spelled
|
||||
|
||||
def queue(self, path, *, sha256=None, resolver_version=1, evidence=None):
|
||||
"""Store one pending item for the bytes at ``path``'s current stat."""
|
||||
facts = path.stat()
|
||||
locator, spelled = self.locator(path)
|
||||
stored = self.api.db.record_review_item(
|
||||
locator=locator,
|
||||
spelled_path=spelled,
|
||||
sha256=sha256 or hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
size=facts.st_size,
|
||||
mtime_ns=facts.st_mtime_ns,
|
||||
epoch=self.api.db.get_execution_epoch(),
|
||||
resolver_version=resolver_version,
|
||||
evidence=evidence or {"candidates": []},
|
||||
candidate_count=0,
|
||||
limited=True,
|
||||
)
|
||||
self.assertTrue(stored)
|
||||
return self.api.db.review_items_for(locator)[-1]["id"]
|
||||
|
||||
def decide(self, item_id):
|
||||
conn = self.api.db.model.get_connection()
|
||||
with conn:
|
||||
conn.execute(
|
||||
"UPDATE media_review_items SET state='unresolved', revision=1 "
|
||||
"WHERE id=?",
|
||||
(item_id,),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO media_review_decisions(id,item_id,decision_revision,"
|
||||
"created_at,outcome,candidate_hash,evidence) VALUES(?,?,?,?,?,?,?)",
|
||||
(
|
||||
"00000000-0000-4000-8000-0000000000d1",
|
||||
item_id,
|
||||
1,
|
||||
NOW,
|
||||
"unresolved",
|
||||
None,
|
||||
'{"kind":"user-selection"}',
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestReviewItemAt(ReviewItemsMixin, ImageAPITestCase):
|
||||
"""``database/review.py::review_item_at``."""
|
||||
|
||||
def stat(self, path):
|
||||
facts = path.stat()
|
||||
return self.locator(path)[0], facts.st_size, facts.st_mtime_ns
|
||||
|
||||
async def test_no_item_is_none(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.assertIsNone(self.api.db.review_item_at(*self.stat(path)))
|
||||
|
||||
async def test_pending_item_at_the_stat(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
item_id = self.queue(path)
|
||||
self.assertEqual(
|
||||
self.api.db.review_item_at(*self.stat(path)),
|
||||
{"state": "pending", "item_id": item_id},
|
||||
)
|
||||
|
||||
async def test_any_version_is_pending(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
item_id = self.queue(path, resolver_version=7)
|
||||
found = self.api.db.review_item_at(*self.stat(path))
|
||||
self.assertEqual(found, {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_another_stat_is_none(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.queue(path)
|
||||
locator, size, mtime_ns = self.stat(path)
|
||||
self.assertIsNone(self.api.db.review_item_at(locator, size + 1, mtime_ns))
|
||||
self.assertIsNone(self.api.db.review_item_at(locator, size, mtime_ns + 1))
|
||||
other = self.locator(self.output_dir / "b.png")[0]
|
||||
self.assertIsNone(self.api.db.review_item_at(other, size, mtime_ns))
|
||||
|
||||
async def test_two_pending_items_at_the_stat_give_the_newest(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
# Two byte records at one stat (rewritten bytes, mtime restored).
|
||||
self.queue(path, sha256="a" * 64)
|
||||
newest = self.queue(path, sha256="b" * 64)
|
||||
self.assertEqual(
|
||||
self.api.db.review_item_at(*self.stat(path)),
|
||||
{"state": "pending", "item_id": newest},
|
||||
)
|
||||
# Recorded within one timestamp: the later insert is still the newest.
|
||||
conn = self.api.db.model.get_connection()
|
||||
with conn:
|
||||
conn.execute("UPDATE media_review_items SET created_at=?", (NOW,))
|
||||
self.assertEqual(
|
||||
self.api.db.review_item_at(*self.stat(path)),
|
||||
{"state": "pending", "item_id": newest},
|
||||
)
|
||||
|
||||
async def test_decided_item_is_decided(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.decide(self.queue(path))
|
||||
self.assertEqual(
|
||||
self.api.db.review_item_at(*self.stat(path)), {"state": "decided"}
|
||||
)
|
||||
|
||||
async def test_pending_wins_over_a_decided_item_of_other_bytes(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.decide(self.queue(path, sha256="a" * 64))
|
||||
pending = self.queue(path, sha256="b" * 64)
|
||||
self.assertEqual(
|
||||
self.api.db.review_item_at(*self.stat(path)),
|
||||
{"state": "pending", "item_id": pending},
|
||||
)
|
||||
|
||||
async def test_invalid_locator_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.api.db.review_item_at("", 1, 1)
|
||||
|
||||
|
||||
class TestInspectReviewField(ReviewItemsMixin, ImageAPITestCase):
|
||||
"""``GET /prompt_manager/images/inspect/...`` carries ``review``."""
|
||||
|
||||
async def get_application(self):
|
||||
app = await super().get_application()
|
||||
# Inspect may record (D2): captures stay inside the test directory.
|
||||
self.api._captures = CaptureStore(temp_parent=self.comfy_dir / "captures")
|
||||
return app
|
||||
|
||||
async def tearDownAsync(self):
|
||||
self.api.close_annotation_captures()
|
||||
await super().tearDownAsync()
|
||||
|
||||
def items(self):
|
||||
conn = self.api.db.model.get_connection()
|
||||
return [row[0] for row in conn.execute("SELECT id FROM media_review_items")]
|
||||
|
||||
async def inspect(self, relative="a.png"):
|
||||
response = await self.client.get(
|
||||
f"/prompt_manager/images/inspect/{relative}", params={"root": "0"}
|
||||
)
|
||||
body = await response.json()
|
||||
self.assertEqual(response.status, 200, body)
|
||||
return body
|
||||
|
||||
async def test_unqueued_file_the_scan_would_link_is_null(self):
|
||||
"""The scan's fallback links ``two_samplers``: nothing is recorded."""
|
||||
png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertIn("review", body)
|
||||
self.assertIsNone(body["review"])
|
||||
self.assertEqual(self.items(), [])
|
||||
|
||||
async def test_unqueued_ambiguous_file_is_recorded_and_pending(self):
|
||||
"""D2: Inspect records the item as the scan would and names it."""
|
||||
png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "ambiguous")
|
||||
(item_id,) = self.items()
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
self.assertFalse(self.api.db.review_file_linked((str(self.output_dir),)))
|
||||
|
||||
async def test_a_second_inspect_records_nothing_new(self):
|
||||
png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
first = await self.inspect()
|
||||
with patch.object(
|
||||
type(self.api), "record_review_file", side_effect=AssertionError
|
||||
):
|
||||
second = await self.inspect()
|
||||
self.assertEqual(second["review"], first["review"])
|
||||
self.assertEqual(len(self.items()), 1)
|
||||
|
||||
async def test_a_decided_file_records_nothing(self):
|
||||
path = png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
self.decide(self.queue(path))
|
||||
with patch.object(
|
||||
type(self.api), "record_review_file", side_effect=AssertionError
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["review"], {"state": "decided"})
|
||||
|
||||
async def test_a_recording_error_keeps_the_response_and_is_logged(self):
|
||||
png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
with (
|
||||
self.assertLogs(self.api.logger, "WARNING") as logs,
|
||||
patch.object(
|
||||
type(self.api),
|
||||
"record_review_file",
|
||||
side_effect=sqlite3.OperationalError("locked"),
|
||||
),
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertIsNone(body["review"])
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertEqual(self.items(), [])
|
||||
self.assertIn("Needs review", "\n".join(logs.output))
|
||||
self.assertNotIn(str(self.output_dir), "\n".join(logs.output))
|
||||
|
||||
async def test_a_running_records_job_defers_and_records_nothing(self):
|
||||
png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
with patch.object(self.api, "record_review_file", return_value="deferred"):
|
||||
body = await self.inspect()
|
||||
self.assertIsNone(body["review"])
|
||||
self.assertEqual(self.items(), [])
|
||||
|
||||
async def test_a_busy_capture_store_is_expected_not_a_warning(self):
|
||||
"""The worker may hold the store while it copies a fresh output: a
|
||||
``CaptureCapacity`` is logged at debug level only (#657 review)."""
|
||||
png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
with (
|
||||
self.assertNoLogs(self.api.logger, "WARNING"),
|
||||
patch.object(
|
||||
type(self.api),
|
||||
"record_review_file",
|
||||
side_effect=CaptureCapacity("busy"),
|
||||
),
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertIsNone(body["review"])
|
||||
self.assertEqual(self.items(), [])
|
||||
|
||||
async def test_the_item_is_read_again_after_a_failed_recording(self):
|
||||
"""The worker recorded the file while Inspect waited for the store."""
|
||||
path = png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
queued = []
|
||||
|
||||
def worker_won(*_args):
|
||||
queued.append(self.queue(path, resolver_version=current_version()))
|
||||
raise CaptureCapacity("busy")
|
||||
|
||||
with patch.object(type(self.api), "record_review_file", side_effect=worker_won):
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": queued[0]})
|
||||
|
||||
async def test_an_unrecordable_file_is_not_tried_again_at_its_stat(self):
|
||||
"""A file the scan would link records nothing; Inspect remembers its
|
||||
stat and does not run the recording again (#657 review)."""
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
real = type(self.api).record_review_file
|
||||
calls = []
|
||||
|
||||
def counted(api, image_path):
|
||||
calls.append(image_path)
|
||||
return real(api, image_path)
|
||||
|
||||
with patch.object(type(self.api), "record_review_file", counted):
|
||||
await self.inspect()
|
||||
await self.inspect()
|
||||
self.assertEqual(len(calls), 1)
|
||||
facts = path.stat()
|
||||
os.utime(path, ns=(facts.st_atime_ns, facts.st_mtime_ns + 10**9))
|
||||
await self.inspect()
|
||||
self.assertEqual(len(calls), 2)
|
||||
self.assertEqual(self.items(), [])
|
||||
|
||||
async def test_an_old_version_pending_item_is_recorded_again(self):
|
||||
"""A pending item of an older item version (a choiceless limited
|
||||
item recorded before D3) is replaced by the current record."""
|
||||
path = png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
old = self.queue(path, resolver_version=1)
|
||||
body = await self.inspect()
|
||||
(item_id,) = self.items()
|
||||
self.assertNotEqual(item_id, old)
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_a_current_pending_item_is_not_recorded_again(self):
|
||||
path = png(self.output_dir / "a.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
item_id = self.queue(path, resolver_version=current_version())
|
||||
with patch.object(
|
||||
type(self.api), "record_review_file", side_effect=AssertionError
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_pending_item_names_its_id(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
item_id = self.queue(path)
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_pending_item_in_a_subfolder(self):
|
||||
path = png(self.output_dir / "batch" / "a.png", prompt=two_samplers())
|
||||
item_id = self.queue(path)
|
||||
body = await self.inspect("batch/a.png")
|
||||
self.assertEqual(body["review"], {"state": "pending", "item_id": item_id})
|
||||
|
||||
async def test_decided_item_is_decided(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.decide(self.queue(path))
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["review"], {"state": "decided"})
|
||||
|
||||
async def test_changed_bytes_are_null(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.queue(path)
|
||||
facts = path.stat()
|
||||
os.utime(path, ns=(facts.st_atime_ns, facts.st_mtime_ns + 10**9))
|
||||
body = await self.inspect()
|
||||
self.assertIsNone(body["review"])
|
||||
|
||||
async def test_unambiguous_file_is_null_even_when_queued(self):
|
||||
path = png(self.output_dir / "a.png", prompt=graph("portrait", "blurry"))
|
||||
self.queue(path)
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "resolved")
|
||||
self.assertIsNone(body["review"])
|
||||
|
||||
async def test_linked_file_is_null_and_never_reads_the_queue(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.queue(path)
|
||||
self._link_image(str(path), "golden dunes")
|
||||
with (
|
||||
patch.object(
|
||||
type(self.api.db), "review_item_at", side_effect=AssertionError
|
||||
),
|
||||
patch.object(
|
||||
type(self.api), "record_review_file", side_effect=AssertionError
|
||||
),
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertEqual(body["library"]["status"], "linked")
|
||||
self.assertIsNone(body["review"])
|
||||
|
||||
async def test_read_failure_is_null_and_logged(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.queue(path)
|
||||
with (
|
||||
self.assertLogs(self.api.logger, "WARNING") as logs,
|
||||
patch.object(
|
||||
type(self.api.db),
|
||||
"review_item_at",
|
||||
side_effect=sqlite3.OperationalError("locked"),
|
||||
),
|
||||
):
|
||||
body = await self.inspect()
|
||||
self.assertIsNone(body["review"])
|
||||
self.assertEqual(body["prompts"]["positive"]["status"], "ambiguous")
|
||||
self.assertNotIn(str(self.output_dir), "\n".join(logs.output))
|
||||
|
||||
async def test_lora_root_has_no_review_reader(self):
|
||||
"""A root past the output folders (a LoRA root) is never a scan root."""
|
||||
outputs = [self.output_dir]
|
||||
reader = self.api._inspection_review(0, outputs, self.output_dir, ("a.png",))
|
||||
self.assertTrue(callable(reader))
|
||||
lora = self.comfy_dir / "loras"
|
||||
self.assertIsNone(self.api._inspection_review(1, outputs, lora, ("a.png",)))
|
||||
|
||||
async def test_response_is_valid_json_with_the_field(self):
|
||||
path = png(self.output_dir / "a.png", prompt=two_samplers())
|
||||
self.queue(path)
|
||||
response = await self.client.get(
|
||||
"/prompt_manager/images/inspect/a.png", params={"root": "0"}
|
||||
)
|
||||
text = await response.text()
|
||||
self.assertIn('"review":', text)
|
||||
self.assertEqual(json.loads(text)["review"]["state"], "pending")
|
||||
@@ -594,7 +594,7 @@ class ValidationTest(_TableCase):
|
||||
),
|
||||
"guiders": frozenset({"cfg", "basic"}),
|
||||
"conditioning": frozenset({"passthrough", "zeroed"}),
|
||||
"selectors": frozenset({"boolean-select"}),
|
||||
"selectors": frozenset({"boolean-select", "first-present"}),
|
||||
"composites": frozenset({"combine"}),
|
||||
"encoders": frozenset(
|
||||
{"single", "parts-equal", "pm-compose", "flag-parts"}
|
||||
@@ -609,6 +609,58 @@ class ValidationTest(_TableCase):
|
||||
with self.assertRaises(TypeError):
|
||||
semantics.STRATEGIES["samplers"] = frozenset()
|
||||
|
||||
def test_proven_value_categories_are_the_text_returning_ones(self):
|
||||
# #657: a path through only these (plus code-traced classes) proves
|
||||
# that a switch input held a value. Selectors, runtime, facts and
|
||||
# lineage classes may return None or are not text, so never prove one.
|
||||
self.assertEqual(
|
||||
semantics.PROVEN_VALUE_CATEGORIES,
|
||||
frozenset({"encoders", "strings", "conditioning", "composites"}),
|
||||
)
|
||||
|
||||
def test_proves_value_reads_each_proven_category(self):
|
||||
# #662 (N1): one entry of each table; only the proven categories prove,
|
||||
# class-keyed ones by class, slot-keyed ones by (class, slot).
|
||||
table = semantics.get_semantics()
|
||||
outputs = {
|
||||
"composites": (next(iter(table.composites)), 0),
|
||||
"conditioning": next(iter(table.conditioning)),
|
||||
"encoders": next(iter(table.encoders)),
|
||||
"strings": next(iter(table.strings)),
|
||||
"selectors": (next(iter(table.selectors)), 0),
|
||||
}
|
||||
for category, (name, slot) in outputs.items():
|
||||
with self.subTest(category):
|
||||
proven = category in semantics.PROVEN_VALUE_CATEGORIES
|
||||
self.assertEqual(table.proves_value(name, slot), proven)
|
||||
with unittest.mock.patch.object(
|
||||
semantics, "PROVEN_VALUE_CATEGORIES", frozenset({category})
|
||||
):
|
||||
self.assertTrue(table.proves_value(name, slot))
|
||||
with unittest.mock.patch.object(
|
||||
semantics, "PROVEN_VALUE_CATEGORIES", frozenset()
|
||||
):
|
||||
self.assertFalse(table.proves_value(name, slot))
|
||||
name, slot = outputs["encoders"]
|
||||
self.assertFalse(table.proves_value(name, slot + 99))
|
||||
|
||||
def test_first_present_entry_shape_is_strict(self):
|
||||
valid = {"strategy": "first-present", "input_prefix": "any_"}
|
||||
doc = _minimal()
|
||||
doc["selectors"]["Any Switch (rgthree)"] = dict(valid)
|
||||
self.assertEqual(self.load_doc(doc).selectors["Any Switch (rgthree)"], valid)
|
||||
for label, entry, fragment in (
|
||||
("extra key", {**valid, "condition": "boolean"}, "unknown field"),
|
||||
("missing prefix", {"strategy": "first-present"}, "missing input"),
|
||||
("empty prefix", {**valid, "input_prefix": ""}, "input prefix"),
|
||||
("long prefix", {**valid, "input_prefix": "a" * 129}, "input prefix"),
|
||||
("prefix not text", {**valid, "input_prefix": 1}, "input prefix"),
|
||||
):
|
||||
with self.subTest(label):
|
||||
doc = _minimal()
|
||||
doc["selectors"]["Any Switch (rgthree)"] = entry
|
||||
self.assertRejected(doc, fragment)
|
||||
|
||||
def test_duplicate_output_key_rejected(self):
|
||||
doc = _minimal()
|
||||
doc["encoders"].append(copy.deepcopy(doc["encoders"][0]))
|
||||
@@ -874,6 +926,11 @@ class SamplerOptionsTest(_TableCase):
|
||||
table.selectors["Switch conditioning [Crystools]"],
|
||||
table.selectors["easy ifElse"],
|
||||
)
|
||||
# rgthree any_switch.py: the first ``any_*`` input that is not None.
|
||||
self.assertEqual(
|
||||
table.selectors["Any Switch (rgthree)"],
|
||||
{"strategy": "first-present", "input_prefix": "any_"},
|
||||
)
|
||||
self.assertEqual(
|
||||
table.encoders[("smZ CLIPTextEncode", 0)],
|
||||
{
|
||||
|
||||
@@ -193,7 +193,7 @@ class LegacyParityGateTest(unittest.TestCase):
|
||||
def test_the_reported_graph_reads_better_than_legacy(self):
|
||||
# Legacy found no positive here (cf0cef3 showed the positive text as
|
||||
# the negative); the floor is met, and the inspector now reads it.
|
||||
graph = unknown.any_switch_graph()
|
||||
graph = unknown.unknown_multi_graph()
|
||||
self.assertIsNone(legacy_positive(graph, None))
|
||||
result = resolver.resolve_prompt_pair(
|
||||
{"prompt": graph}, profile=resolver.INSPECTION_PROFILE
|
||||
|
||||
@@ -41,6 +41,31 @@ def _create_png(text_chunks=None, size=(64, 64)):
|
||||
return tmp.name
|
||||
|
||||
|
||||
def _create_webp(workflow=None, prompt=None, size=(64, 64)):
|
||||
"""Create a minimal WebP with the EXIF records ComfyUI writes.
|
||||
|
||||
SaveAnimatedWEBP puts ``prompt:{json}`` at EXIF tag 0x0110 and
|
||||
``workflow:{json}`` at 0x010F; the file has no text chunks at all.
|
||||
|
||||
Args:
|
||||
workflow: Workflow dict to embed as the workflow record.
|
||||
prompt: Prompt dict to embed as the prompt record.
|
||||
size: tuple (width, height).
|
||||
|
||||
Returns:
|
||||
Path to the temporary WebP file.
|
||||
"""
|
||||
exif = Image.Exif()
|
||||
if prompt is not None:
|
||||
exif[0x0110] = f"prompt:{json.dumps(prompt)}"
|
||||
if workflow is not None:
|
||||
exif[0x010F] = f"workflow:{json.dumps(workflow)}"
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".webp")
|
||||
tmp.close()
|
||||
Image.new("RGB", size, color=(128, 128, 128)).save(tmp.name, "WEBP", exif=exif)
|
||||
return tmp.name
|
||||
|
||||
|
||||
class MetadataTestCase(unittest.TestCase):
|
||||
"""Base class that cleans up temp files."""
|
||||
|
||||
@@ -58,6 +83,11 @@ class MetadataTestCase(unittest.TestCase):
|
||||
self.temp_files.append(path)
|
||||
return path
|
||||
|
||||
def _webp(self, workflow=None, prompt=None, size=(64, 64)):
|
||||
path = _create_webp(workflow, prompt, size)
|
||||
self.temp_files.append(path)
|
||||
return path
|
||||
|
||||
|
||||
class TestExtractMetadata(MetadataTestCase):
|
||||
"""Test extract_metadata method."""
|
||||
@@ -82,6 +112,17 @@ class TestExtractMetadata(MetadataTestCase):
|
||||
self.assertIsNotNone(result)
|
||||
self.assertIn("prompt", result)
|
||||
|
||||
def test_extracts_metadata_from_webp_exif(self):
|
||||
"""A WebP carries the records as EXIF, not as text chunks."""
|
||||
workflow = {"nodes": [{"type": "CLIPTextEncode", "inputs": {"text": "hi"}}]}
|
||||
prompt = {"1": {"class_type": "KSampler", "inputs": {}}}
|
||||
path = self._webp(workflow=workflow, prompt=prompt)
|
||||
result = self.extractor.extract_metadata(path)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result["workflow"]["nodes"][0]["type"], "CLIPTextEncode")
|
||||
self.assertIn("prompt", result)
|
||||
self.assertEqual(result["file_info"]["format"], "WEBP")
|
||||
|
||||
def test_extracts_text_encoder_nodes(self):
|
||||
workflow = {
|
||||
"nodes": [
|
||||
|
||||
@@ -233,18 +233,6 @@ class TestBaseSaveAndSearch(NodeTestCase):
|
||||
self.assertIsNone(self.node._parse_tags(" , ,"))
|
||||
self.assertEqual(self.node._parse_tags(" a, b ,,c"), ["a", "b", "c"])
|
||||
|
||||
def test_search_prompts_and_api_wrappers(self):
|
||||
self.node._save_prompt_to_database("a cat on a mat")
|
||||
self.assertEqual(self.node._search_prompts(""), [])
|
||||
self.assertEqual(self.node._search_prompts(" "), [])
|
||||
self.assertEqual(len(self.node._search_prompts("cat")), 1)
|
||||
|
||||
def test_search_and_recent_errors_return_empty_lists(self):
|
||||
self.node.db = mock.Mock()
|
||||
self.node.db.search_prompts.side_effect = RuntimeError("locked")
|
||||
with self.assertLogs("test.node", level="ERROR"):
|
||||
self.assertEqual(self.node._search_prompts("cat"), [])
|
||||
|
||||
def test_gallery_system_start_failure_is_logged(self):
|
||||
self.node.image_monitor.start_monitoring.side_effect = OSError("no inotify")
|
||||
with self.assertLogs("test.node", level="ERROR"):
|
||||
|
||||
@@ -17,8 +17,10 @@ from utils.prompt_pair_resolver import OutputAdapter, resolve_prompt_pair
|
||||
|
||||
try:
|
||||
from tests import inspection_parity as parity
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # discovered with ``-s tests``
|
||||
import inspection_parity as parity
|
||||
import unknown_node_graphs as switch_graphs
|
||||
|
||||
|
||||
def graph(positive: str = "portrait", negative: str = "blurry") -> dict:
|
||||
@@ -1671,6 +1673,201 @@ class TestConditioningSemantics(unittest.TestCase):
|
||||
self.assertIsNone(result["reason_code"])
|
||||
|
||||
|
||||
class TestFirstPresentSelector(unittest.TestCase):
|
||||
"""rgthree Any Switch: the first input proven to hold a value wins (#657).
|
||||
|
||||
Graphs are the sweep shape (``unknown_node_graphs.any_switch_sweep_graph``)
|
||||
with neutral texts: PromptManagerText 12, StringConcatenate 13 (a stacker's
|
||||
trigger text, then 12), Any Switch 14, encoder 15, KSampler 26.
|
||||
"""
|
||||
|
||||
SHAPES = switch_graphs.first_present_shapes()
|
||||
JOINED = f"{switch_graphs.SWEEP_PREFIX}, {switch_graphs.POSITIVE}"
|
||||
|
||||
def shape(self, name, **options):
|
||||
return _inspect(self.SHAPES[name], **options)
|
||||
|
||||
def candidates(self, result):
|
||||
return [
|
||||
(item["state"], _role_text_of(item, "positive"))
|
||||
for item in result["candidates"]
|
||||
]
|
||||
|
||||
def assertResolved(self, result, positive):
|
||||
self.assertEqual(result["state"], "resolved", result["reason"])
|
||||
self.assertEqual(_sides(result), (positive, switch_graphs.NEGATIVE))
|
||||
|
||||
def test_the_sweep_graph_resolves_to_the_prompt_manager_text(self):
|
||||
result = self.shape("sweep")
|
||||
self.assertResolved(result, switch_graphs.POSITIVE)
|
||||
self.assertEqual(result["sampler_id"], "26")
|
||||
path = [step["node_id"] for step in result["positive"]["provenance"]["path"]]
|
||||
self.assertEqual(path, ["15", "14", "12"])
|
||||
|
||||
def test_the_sweep_graph_was_ambiguous_without_the_table_entry(self):
|
||||
table = inspection_semantics.get_semantics()
|
||||
selectors = {
|
||||
name: entry
|
||||
for name, entry in table.selectors.items()
|
||||
if name != "Any Switch (rgthree)"
|
||||
}
|
||||
without = replace(
|
||||
table,
|
||||
selectors=selectors,
|
||||
all_classes=table.all_classes - {"Any Switch (rgthree)"},
|
||||
)
|
||||
with mock.patch.object(resolver, "_inspection_semantics", return_value=without):
|
||||
result = self.shape("sweep")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(result["reason"], resolver.SEVERAL_SOURCES_REASON)
|
||||
|
||||
def test_ingestion_still_cannot_read_the_switch(self):
|
||||
result = resolve_prompt_pair({"prompt": self.SHAPES["sweep"]})
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
|
||||
def test_a_proven_first_input_resolves_to_that_input(self):
|
||||
for name, positive in (
|
||||
("through-reroute", switch_graphs.POSITIVE),
|
||||
("through-primitive", switch_graphs.OTHER),
|
||||
("through-encoder-chain", switch_graphs.OTHER),
|
||||
("literal-text", "literal words"),
|
||||
):
|
||||
with self.subTest(name):
|
||||
self.assertResolved(self.shape(name), positive)
|
||||
|
||||
def test_the_proven_tables_are_the_semantics_constant(self):
|
||||
# #662 (N1): proves_value follows PROVEN_VALUE_CATEGORIES, so a table
|
||||
# left out of it no longer proves that a switch input held a value.
|
||||
self.assertEqual(self.shape("through-encoder-chain")["state"], "resolved")
|
||||
with mock.patch.object(
|
||||
inspection_semantics, "PROVEN_VALUE_CATEGORIES", frozenset()
|
||||
):
|
||||
result = self.shape("through-encoder-chain")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(result["reason"], resolver.SELECTOR_BRANCHES_REASON)
|
||||
|
||||
def test_an_unproven_first_input_offers_each_input(self):
|
||||
result = self.shape("through-unknown")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(result["reason"], resolver.SELECTOR_BRANCHES_REASON)
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("resolved", switch_graphs.POSITIVE), ("resolved", self.JOINED)],
|
||||
)
|
||||
|
||||
def test_a_run_time_first_input_is_never_replaced_by_prompt_manager(self):
|
||||
# rgthree outputs the generated text, not the PromptManager text.
|
||||
result = self.shape("runtime-first")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("unresolved", None), ("resolved", switch_graphs.POSITIVE)],
|
||||
)
|
||||
self.assertEqual(result["candidates"][0]["reason_code"], "runtime-value")
|
||||
|
||||
def test_inputs_with_one_outcome_are_one_candidate(self):
|
||||
# Three inputs, two with one text: two candidates, not three, so one
|
||||
# text never reads as a choice between two.
|
||||
result = self.shape("repeated-text")
|
||||
self.assertEqual(result["reason"], resolver.SELECTOR_BRANCHES_REASON)
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("resolved", switch_graphs.POSITIVE), ("resolved", self.JOINED)],
|
||||
)
|
||||
result = self.shape("repeated-text-failed-middle")
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("resolved", switch_graphs.POSITIVE), ("unresolved", None)],
|
||||
)
|
||||
|
||||
def test_inputs_with_one_text_need_no_choice(self):
|
||||
self.assertResolved(self.shape("same-text"), switch_graphs.OTHER)
|
||||
|
||||
def test_a_literal_for_conditioning_is_malformed(self):
|
||||
result = self.shape("literal-conditioning")
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
self.assertEqual(result["reason_code"], "malformed")
|
||||
|
||||
def test_one_participating_input_is_traced_as_usual(self):
|
||||
self.assertResolved(self.shape("one-input-unknown"), switch_graphs.POSITIVE)
|
||||
# An input set to null is not passed on (rgthree skips None).
|
||||
self.assertResolved(self.shape("null-first"), self.JOINED)
|
||||
|
||||
def test_no_participating_input_is_malformed(self):
|
||||
result = self.shape("no-input")
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
self.assertEqual(result["reason_code"], "malformed")
|
||||
|
||||
def test_a_selector_upstream_gives_one_result_per_choice(self):
|
||||
result = self.shape("selector-upstream")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
[text for _, text in self.candidates(result)],
|
||||
# Each selector choice applies the switch rule; the joined text
|
||||
# both choices reach is listed once.
|
||||
[switch_graphs.OTHER, self.JOINED, switch_graphs.POSITIVE],
|
||||
)
|
||||
|
||||
def test_a_switch_never_proves_a_value(self):
|
||||
result = self.shape("nested-switch")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
[text for _, text in self.candidates(result)],
|
||||
[switch_graphs.POSITIVE, switch_graphs.OTHER],
|
||||
)
|
||||
|
||||
def test_a_limit_on_the_first_input_is_that_limit(self):
|
||||
result = self.shape("depth-limit")
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "depth-limit")
|
||||
)
|
||||
long = switch_graphs.switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": {"class_type": "VendorPassText", "inputs": {"src": ["31", 0]}},
|
||||
"31": _primitive("x" * 50),
|
||||
"32": _primitive("short"),
|
||||
},
|
||||
)
|
||||
result = _inspect(long, max_text_length=20)
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "text-limit")
|
||||
)
|
||||
chain = switch_graphs.switched(
|
||||
{"any_01": ["r0", 0], "any_02": ["32", 0]},
|
||||
**switch_graphs._reroutes(30, 0, ["12", 0]),
|
||||
**{"32": _primitive("short")},
|
||||
)
|
||||
result = _inspect(chain, max_visits=20)
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "work-limit")
|
||||
)
|
||||
|
||||
def test_a_pair_record_check_through_a_diverging_switch_is_unverifiable(self):
|
||||
# While a pair's execution record is checked, a switch choice cannot be
|
||||
# read statically: that input is skipped, and the record still applies.
|
||||
source = switch_graphs.switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": {"class_type": "VendorPassText", "inputs": {"src": ["31", 0]}},
|
||||
"31": _primitive(switch_graphs.OTHER),
|
||||
"32": _primitive(switch_graphs.POSITIVE),
|
||||
"60": switch_graphs.pair(text=["14", 0]),
|
||||
},
|
||||
)
|
||||
source["26"]["inputs"]["positive"] = ["60", 0]
|
||||
source["26"]["inputs"]["negative"] = ["60", 1]
|
||||
metadata = {
|
||||
"prompt": source,
|
||||
"comfyassets_prompt_pairs": switch_graphs.execution(
|
||||
"60", switch_graphs.GENERATED
|
||||
),
|
||||
}
|
||||
result = resolve_prompt_pair(metadata, profile=resolver.INSPECTION_PROFILE)
|
||||
self.assertEqual(result["state"], "resolved", result["reason"])
|
||||
self.assertEqual(_sides(result), (switch_graphs.GENERATED, ""))
|
||||
|
||||
|
||||
def _primitive(value: str) -> dict:
|
||||
return {"class_type": "PrimitiveString", "inputs": {"value": value}}
|
||||
|
||||
@@ -2255,12 +2452,14 @@ class TestDetailerStages(unittest.TestCase):
|
||||
],
|
||||
)
|
||||
self.assertEqual(_inspect(_detailed(), output_node_id="9"), result)
|
||||
# Neither the upstream prompt nor the detailer prompt is shown as the answer.
|
||||
# Neither the upstream prompt nor the detailer prompt is shown as the
|
||||
# answer; the negative both stages share is (#658).
|
||||
prompts = inspect_prompt_evidence({"prompt": _detailed()})["prompts"]
|
||||
self.assertEqual(
|
||||
[prompts[role]["status"] for role in ("positive", "negative")],
|
||||
["ambiguous", "ambiguous"],
|
||||
["ambiguous", "resolved"],
|
||||
)
|
||||
self.assertEqual(prompts["negative"]["text"], parity.NEG)
|
||||
self.assertNotIn(parity.POS, str(prompts))
|
||||
|
||||
def test_detailer_of_a_loaded_image_is_a_single_stage(self):
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""The browser resolver proves values from the same categories as the server.
|
||||
|
||||
#662 (N1): ``PROVEN_VALUE_CATEGORIES`` (utils/inspection_semantics.py) names
|
||||
the semantics tables whose outputs always hold a value (#657). The Python
|
||||
resolver reads it through ``Semantics.proves_value``; the browser resolver
|
||||
(web/js/workspace/local-resolver.mjs) reads its copy in
|
||||
local-resolver-support.mjs. This fails when the two copies drift apart.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess # nosec B404 - fixed local Node command, no shell
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from utils import inspection_semantics # noqa: E402
|
||||
|
||||
SUPPORT = ROOT / "web" / "js" / "workspace" / "local-resolver-support.mjs"
|
||||
PRINT_CONSTANTS = (
|
||||
"const m = await import(process.argv[1]);"
|
||||
"console.log(JSON.stringify({categories: [...m.PROVEN_VALUE_CATEGORIES],"
|
||||
" byClass: [...m.PROVEN_BY_CLASS]}));"
|
||||
)
|
||||
|
||||
|
||||
class TestProvenValueParity(unittest.TestCase):
|
||||
def browser_constants(self):
|
||||
node = shutil.which("node")
|
||||
if node is None: # pragma: no cover - CI runners and dev hosts ship Node
|
||||
if os.environ.get("CI"):
|
||||
self.fail("Node.js is required in CI for the resolver parity test")
|
||||
self.skipTest("Node.js is not installed")
|
||||
completed = subprocess.run( # nosec B603
|
||||
[node, "--input-type=module", "-e", PRINT_CONSTANTS, SUPPORT.as_uri()],
|
||||
capture_output=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr.decode("utf-8"))
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
def test_the_browser_proves_the_same_categories_keyed_the_same_way(self):
|
||||
found = self.browser_constants()
|
||||
proven = inspection_semantics.PROVEN_VALUE_CATEGORIES
|
||||
self.assertEqual(set(found["categories"]), set(proven))
|
||||
self.assertEqual(len(found["categories"]), len(proven))
|
||||
by_class = proven & set(inspection_semantics._CLASS_CATEGORIES)
|
||||
self.assertEqual(set(found["byClass"]), by_class)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -23,7 +23,7 @@ except ImportError: # discovered with ``-s tests``
|
||||
import unknown_node_graphs as graphs
|
||||
|
||||
POSITIVE, OTHER, NEGATIVE = graphs.POSITIVE, graphs.OTHER, graphs.NEGATIVE
|
||||
any_switch_graph = graphs.any_switch_graph
|
||||
unknown_multi_graph = graphs.unknown_multi_graph
|
||||
_encode, _pair, _with = graphs.encode, graphs.pair, graphs.with_nodes
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ def _texts(result):
|
||||
|
||||
|
||||
class TestTheReportedGraph(unittest.TestCase):
|
||||
def test_prompt_manager_pair_through_any_switch_resolves(self):
|
||||
result = _inspect(any_switch_graph())
|
||||
def test_prompt_manager_pair_through_an_unknown_node_resolves(self):
|
||||
result = _inspect(unknown_multi_graph())
|
||||
self.assertEqual(result["state"], "resolved", result["reason"])
|
||||
self.assertEqual(_texts(result), (POSITIVE, ""))
|
||||
self.assertEqual(result["sampler_id"], "17")
|
||||
@@ -51,13 +51,15 @@ class TestTheReportedGraph(unittest.TestCase):
|
||||
self.assertEqual(path, ["15", "10"])
|
||||
|
||||
def test_the_inspector_shows_the_prompt(self):
|
||||
evidence = inspect_prompt_evidence({"prompt": json.dumps(any_switch_graph())})
|
||||
evidence = inspect_prompt_evidence(
|
||||
{"prompt": json.dumps(unknown_multi_graph())}
|
||||
)
|
||||
self.assertEqual(evidence["resolution"]["state"], "resolved")
|
||||
self.assertEqual(evidence["prompts"]["positive"]["status"], "resolved")
|
||||
self.assertEqual(evidence["prompts"]["positive"]["text"], POSITIVE)
|
||||
|
||||
def test_ingestion_is_unchanged(self):
|
||||
result = resolve_prompt_pair({"prompt": any_switch_graph()})
|
||||
result = resolve_prompt_pair({"prompt": unknown_multi_graph()})
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
# Its first failure is the custom latent node, as before this change.
|
||||
self.assertEqual(result["reason"], "Unsupported latent ancestry")
|
||||
@@ -69,12 +71,12 @@ class TestTheReportedGraph(unittest.TestCase):
|
||||
|
||||
class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
def test_several_inputs_with_one_text_resolve(self):
|
||||
graph = any_switch_graph(any_01=["10", 0], any_02=["10", 0])
|
||||
graph = unknown_multi_graph(any_01=["10", 0], any_02=["10", 0])
|
||||
self.assertEqual(_texts(_inspect(graph)), (POSITIVE, ""))
|
||||
|
||||
def test_equal_texts_from_different_nodes_resolve(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
**{"20": _encode(OTHER), "21": _encode(OTHER)},
|
||||
)
|
||||
result = _inspect(graph)
|
||||
@@ -83,7 +85,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
|
||||
def test_different_texts_are_candidates_not_a_refusal(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
**{"20": _encode(POSITIVE), "21": _encode(OTHER)},
|
||||
)
|
||||
result = _inspect(graph)
|
||||
@@ -99,7 +101,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
|
||||
def test_prompt_manager_is_authoritative(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
**{"20": _encode(OTHER)},
|
||||
)
|
||||
result = _inspect(graph)
|
||||
@@ -108,7 +110,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
|
||||
def test_prompt_manager_wins_over_an_unreadable_branch(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
@@ -121,7 +123,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
|
||||
def test_an_unreadable_branch_blocks_without_prompt_manager(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["22", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["22", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
@@ -137,7 +139,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
|
||||
def test_chained_unknown_nodes(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "Router Node (vendor)",
|
||||
@@ -148,16 +150,16 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
self.assertEqual(_texts(_inspect(graph)), (POSITIVE, ""))
|
||||
|
||||
def test_no_text_names_the_unknown_node(self):
|
||||
graph = any_switch_graph(any_01=["7", 0])
|
||||
graph = unknown_multi_graph(any_01=["7", 0])
|
||||
result = _inspect(graph)
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
self.assertEqual(result["reason_code"], "unsupported-node")
|
||||
self.assertEqual(
|
||||
result["node"], {"id": "15", "class_type": "Any Switch (rgthree)"}
|
||||
result["node"], {"id": "15", "class_type": "PMTest Unknown Multi"}
|
||||
)
|
||||
|
||||
def test_another_sampler_is_never_entered(self):
|
||||
graph = any_switch_graph(any_01=["17", 0], any_02=["10", 0])
|
||||
graph = unknown_multi_graph(any_01=["17", 0], any_02=["10", 0])
|
||||
graph["30"] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {**graph["17"]["inputs"], "positive": ["31", 0]},
|
||||
@@ -172,7 +174,7 @@ class TestSourcesThroughUnknownNodes(unittest.TestCase):
|
||||
class TestLegacyShapedRules(unittest.TestCase):
|
||||
def test_a_text_input_is_the_text(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorTextEncode",
|
||||
@@ -183,7 +185,7 @@ class TestLegacyShapedRules(unittest.TestCase):
|
||||
self.assertEqual(_texts(_inspect(graph))[0], OTHER)
|
||||
|
||||
def test_role_inputs_route_by_output_slot(self):
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["20"] = {
|
||||
"class_type": "VendorControlApply",
|
||||
"inputs": {
|
||||
@@ -201,7 +203,7 @@ class TestLegacyShapedRules(unittest.TestCase):
|
||||
|
||||
def test_a_conditioning_input_is_followed_alone(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorStyleApply",
|
||||
@@ -216,7 +218,7 @@ class TestLegacyShapedRules(unittest.TestCase):
|
||||
# The vendor encoder's ``clip`` reaches a loader with its own ``text``:
|
||||
# that text is a lora tag, never the prompt.
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorPromptEncode",
|
||||
@@ -236,7 +238,7 @@ class TestLegacyShapedRules(unittest.TestCase):
|
||||
|
||||
class TestBounds(unittest.TestCase):
|
||||
def test_a_long_unknown_chain_reaches_the_depth_limit(self):
|
||||
graph = any_switch_graph(any_01=["100", 0])
|
||||
graph = unknown_multi_graph(any_01=["100", 0])
|
||||
for index in range(100, 100 + resolver.INSPECTION_PROFILE.max_depth + 2):
|
||||
graph[str(index)] = {
|
||||
"class_type": "Router Node (vendor)",
|
||||
@@ -249,7 +251,7 @@ class TestBounds(unittest.TestCase):
|
||||
|
||||
def test_many_different_sources_hit_the_candidate_cap(self):
|
||||
inputs = {}
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
for index in range(resolver._MAX_BRANCH_CANDIDATES + 1):
|
||||
graph[str(200 + index)] = _encode(f"{OTHER} {index}")
|
||||
inputs[f"any_{index:02}"] = [str(200 + index), 0]
|
||||
@@ -292,7 +294,7 @@ class TestGeneratedAndTransformedText(unittest.TestCase):
|
||||
|
||||
def test_a_seeded_conditioning_node_still_passes_through(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorConditioningNoise",
|
||||
@@ -307,7 +309,7 @@ class TestReviewFindings(unittest.TestCase):
|
||||
"""Shapes from the independent review of the first #381 commit."""
|
||||
|
||||
def _recorded(self, text_source: dict) -> dict:
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["10"]["inputs"]["text"] = ["30", 0]
|
||||
graph.update(text_source)
|
||||
metadata = {
|
||||
@@ -349,7 +351,7 @@ class TestReviewFindings(unittest.TestCase):
|
||||
|
||||
def test_the_seed_rule_reads_only_string_outputs(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {"class_type": "XNoise", "inputs": {"conditioning": ["21", 0]}},
|
||||
"21": {
|
||||
@@ -361,7 +363,7 @@ class TestReviewFindings(unittest.TestCase):
|
||||
self.assertEqual(_texts(_inspect(graph))[0], OTHER)
|
||||
|
||||
def test_an_unlinked_role_input_adds_nothing(self):
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["20"] = {
|
||||
"class_type": "XApply",
|
||||
"inputs": {"positive": ["21", 0], "negative_opt": ""},
|
||||
@@ -376,7 +378,7 @@ class TestReviewFindings(unittest.TestCase):
|
||||
|
||||
def test_one_text_offered_twice_is_one_candidate(self):
|
||||
graph = _with(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["23", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["23", 0]),
|
||||
**{
|
||||
"20": {"class_type": "XB", "inputs": {"p": ["21", 0], "q": ["22", 0]}},
|
||||
"21": _encode(POSITIVE),
|
||||
|
||||
+300
-36
@@ -117,6 +117,57 @@ def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
# Ceiling of every wait for the review worker (TESTING.md: 30 s)
|
||||
WAIT_SECONDS = 30
|
||||
|
||||
|
||||
class Recorded:
|
||||
"""Wrap ``api.record_review_file`` (called by the review worker, #659)
|
||||
and let a test wait for its calls without sleeping."""
|
||||
|
||||
def __init__(self, testcase, api, side_effect=None):
|
||||
import threading
|
||||
|
||||
self._real = api.record_review_file
|
||||
self._side_effect = side_effect
|
||||
self._changed = threading.Condition()
|
||||
self.paths, self.outcomes = [], []
|
||||
patcher = patch.object(api, "record_review_file", self)
|
||||
patcher.start()
|
||||
testcase.addCleanup(patcher.stop)
|
||||
|
||||
def __call__(self, image_path):
|
||||
try:
|
||||
if self._side_effect is not None:
|
||||
outcome = self._side_effect(image_path)
|
||||
else:
|
||||
outcome = self._real(image_path)
|
||||
except Exception:
|
||||
outcome = "raised"
|
||||
raise
|
||||
finally:
|
||||
with self._changed:
|
||||
self.paths.append(os.path.basename(str(image_path)))
|
||||
self.outcomes.append(outcome)
|
||||
self._changed.notify_all()
|
||||
return outcome
|
||||
|
||||
def reset(self):
|
||||
with self._changed:
|
||||
self.paths, self.outcomes = [], []
|
||||
|
||||
def wait_blocking(self, count):
|
||||
with self._changed:
|
||||
return self._changed.wait_for(
|
||||
lambda: len(self.outcomes) >= count, WAIT_SECONDS
|
||||
)
|
||||
|
||||
async def wait_for(self, count):
|
||||
reached = await asyncio.to_thread(self.wait_blocking, count)
|
||||
if not reached:
|
||||
raise AssertionError(f"the review worker made {self.outcomes}")
|
||||
|
||||
|
||||
class ReviewTestCase(AdminAPITestCase):
|
||||
"""Scan helpers over a capture store kept inside the test directory."""
|
||||
|
||||
@@ -127,6 +178,8 @@ class ReviewTestCase(AdminAPITestCase):
|
||||
return app
|
||||
|
||||
async def tearDownAsync(self):
|
||||
# The review worker (#659) ends before its store and folder go.
|
||||
self.assertTrue(self.api.stop_review_worker(30), "review worker running")
|
||||
self.api.close_annotation_captures()
|
||||
await super().tearDownAsync()
|
||||
|
||||
@@ -158,6 +211,10 @@ class ReviewTestCase(AdminAPITestCase):
|
||||
)
|
||||
]
|
||||
|
||||
def _items_at(self, path):
|
||||
locator = os.path.normcase(os.path.realpath(str(path)))
|
||||
return [item for item in self._items() if item["locator"] == locator]
|
||||
|
||||
def _review_revision(self):
|
||||
conn = self.api.db.model.get_connection()
|
||||
return conn.execute(
|
||||
@@ -210,12 +267,16 @@ class TestScanRecording(ReviewTestCase):
|
||||
self.assertEqual(
|
||||
(item["state"], item["revision"], item["limited"]), ("pending", 0, 0)
|
||||
)
|
||||
self.assertEqual(item["resolver_version"], 1)
|
||||
self.assertEqual(
|
||||
item["resolver_version"], review_capture.default_item_version()
|
||||
)
|
||||
self.assertEqual(item["candidate_count"], 3)
|
||||
self.assertEqual(item["evidence_hash"], evidence_digest(item["evidence"]))
|
||||
evidence = json.loads(item["evidence"])
|
||||
self.assertEqual(canonical_evidence(evidence), item["evidence"])
|
||||
self.assertEqual(evidence["resolver_version"], 1)
|
||||
self.assertEqual(
|
||||
evidence["resolver_version"], review_capture.default_item_version()
|
||||
)
|
||||
self.assertEqual(resolved_texts(evidence), ["cat", "dog"])
|
||||
for candidate in evidence["candidates"]:
|
||||
self.assertEqual(
|
||||
@@ -417,9 +478,11 @@ class TestScanRecording(ReviewTestCase):
|
||||
self.assertEqual(items[0]["locator"], items[1]["locator"])
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
|
||||
async def test_many_candidates_are_limited_without_candidates(self):
|
||||
async def test_many_candidates_are_collapsed(self):
|
||||
"""Only ``many.png`` is queued: the A1111 delimiter ambiguity offers
|
||||
no candidate to choose (``tests/test_review_choosable.py``)."""
|
||||
no candidate to choose (``tests/test_review_choosable.py``). Its 17
|
||||
prompts are more than 16: the 16 most used are kept (#657 D3,
|
||||
``tests/test_review_collapsed.py``)."""
|
||||
self._require_module()
|
||||
self._roots()
|
||||
write_png(
|
||||
@@ -433,15 +496,14 @@ class TestScanRecording(ReviewTestCase):
|
||||
|
||||
items = {Path(item["locator"]).name: item for item in self._items()}
|
||||
self.assertEqual(set(items), {"many.png"})
|
||||
for item in items.values():
|
||||
self.assertEqual((item["limited"], item["candidate_count"]), (1, 0))
|
||||
evidence = json.loads(item["evidence"])
|
||||
self.assertEqual(evidence["candidates"], [])
|
||||
self.assertIs(evidence["limited"], True)
|
||||
item = items["many.png"]
|
||||
self.assertEqual((item["limited"], item["candidate_count"]), (0, 16))
|
||||
evidence = json.loads(item["evidence"])
|
||||
self.assertNotIn("limited", evidence)
|
||||
self.assertEqual(
|
||||
# 17 samplers and the parser's unresolved one.
|
||||
json.loads(items["many.png"]["evidence"])["candidate_total"],
|
||||
18,
|
||||
evidence["collapsed"],
|
||||
{"shown": 16, "total": 17, "paths": 18},
|
||||
)
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
|
||||
@@ -548,7 +610,7 @@ class TestRecordAmbiguousFile(ReviewTestCase):
|
||||
self.assertEqual(self._record("delims.png"), "untraced")
|
||||
many = [f"prompt {n}" for n in range(17)]
|
||||
write_png(self.output_dir / "many.png", prompt=unlinkable_graph(*many))
|
||||
self.assertEqual(self._record("many.png"), "limited")
|
||||
self.assertEqual(self._record("many.png"), "recorded") # collapsed (D3)
|
||||
self.assertEqual(self._record("many.png"), "duplicate")
|
||||
self.assertEqual(self._review_revision(), 2)
|
||||
|
||||
@@ -691,7 +753,7 @@ class TestReviewEdges(ReviewTestCase):
|
||||
review_capture.review_evidence({"state": "ambiguous", "candidates": None}),
|
||||
(
|
||||
{
|
||||
"resolver_version": 1,
|
||||
"resolver_version": review_capture.default_item_version(),
|
||||
"reason": "",
|
||||
"limited": True,
|
||||
"candidate_total": 0,
|
||||
@@ -866,39 +928,49 @@ class TestMonitorRecording(ReviewTestCase):
|
||||
"""S1 admission: a ``records`` recording waits for no job; it is refused.
|
||||
|
||||
While a ``records`` or ``guarded`` job runs, the monitor's pass
|
||||
writes nothing and answers ``deferred`` (its fallback link stands and
|
||||
a later scan reads the ambiguous file again); a ``read`` job does not
|
||||
refuse it. Thumbnail work (the job and the gallery's holds) is
|
||||
``guarded`` but writes only previews, never records, so it does not
|
||||
defer the pass either (S5 M7). Not deferred, the pass still records
|
||||
nothing: only scans add items, so an unlinked output is ``skipped``.
|
||||
writes nothing and answers ``deferred``; the review worker keeps the
|
||||
file and queues it once the job ends, with no other output (#659). A
|
||||
``read`` job does not refuse it. Thumbnail work (the job and the
|
||||
gallery's holds) is ``guarded`` but writes only previews, never
|
||||
records, so it does not defer the pass either (S5 M7).
|
||||
"""
|
||||
self._require_module()
|
||||
from py.api import review_recording
|
||||
from py.api.jobs import RESTORE_JOB_KIND, THUMBNAILS_JOB_KIND
|
||||
|
||||
self._roots()
|
||||
path = self.output_dir / "held.png"
|
||||
write_png(path, prompt=unlinkable_graph("cat", "dog"))
|
||||
|
||||
calls = Recorded(self, self.api)
|
||||
for kind, admission in (
|
||||
(RESTORE_JOB_KIND, "records"),
|
||||
("backup", "guarded"),
|
||||
):
|
||||
with self.subTest(admission=admission):
|
||||
async with self.api._jobs.hold(
|
||||
kind, f"{kind} (admin page)", admission=admission
|
||||
):
|
||||
with self.assertLogs("prompt_manager", logging.INFO) as logs:
|
||||
outcome = await asyncio.to_thread(
|
||||
self.api.record_review_file, str(path)
|
||||
)
|
||||
self.assertEqual(outcome, "deferred")
|
||||
self.assertEqual(self._items(), [])
|
||||
path = self.output_dir / f"held_{admission}.png"
|
||||
write_png(path, prompt=unlinkable_graph("cat", "dog"))
|
||||
calls.reset()
|
||||
with patch.object(review_recording, "REVIEW_RETRY_SECONDS", 0.05):
|
||||
async with self.api._jobs.hold(
|
||||
kind, f"{kind} (admin page)", admission=admission
|
||||
):
|
||||
with self.assertLogs("prompt_manager", logging.INFO) as logs:
|
||||
self.assertEqual(
|
||||
self.api.queue_review_file(str(path)), "queued"
|
||||
)
|
||||
await calls.wait_for(1)
|
||||
self.assertEqual(calls.outcomes, ["deferred"])
|
||||
self.assertEqual(self._items_at(path), [])
|
||||
# The job ended: the deferred file is queued, once
|
||||
await calls.wait_for(2)
|
||||
self.assertEqual(calls.outcomes, ["deferred", "recorded"])
|
||||
self.assertEqual(len(self._items_at(path)), 1)
|
||||
self.assertTrue(
|
||||
any(f"{kind} (admin page)" in line for line in logs.output),
|
||||
logs.output,
|
||||
)
|
||||
self.assertEqual(self.api._review_worker().deferred_count(), 0)
|
||||
|
||||
path = self.output_dir / "beside_reads.png"
|
||||
write_png(path, prompt=unlinkable_graph("cat", "dog"))
|
||||
async with self.api._jobs.hold("probe-read", "Read probe", admission="read"):
|
||||
async with self.api._jobs.hold(
|
||||
THUMBNAILS_JOB_KIND,
|
||||
@@ -908,8 +980,8 @@ class TestMonitorRecording(ReviewTestCase):
|
||||
outcome = await asyncio.to_thread(
|
||||
self.api.record_review_file, str(path)
|
||||
)
|
||||
self.assertEqual(outcome, "skipped")
|
||||
self.assertEqual(self._items(), [])
|
||||
self.assertEqual(outcome, "recorded")
|
||||
self.assertEqual(len(self._items_at(path)), 1)
|
||||
|
||||
async def test_a_running_thumbnail_job_does_not_defer_monitor_recording(self):
|
||||
"""S5 M7: a long rebuild never defers the monitor's pass (no records)."""
|
||||
@@ -937,9 +1009,9 @@ class TestMonitorRecording(ReviewTestCase):
|
||||
finally:
|
||||
gate.set()
|
||||
await asyncio.wait_for(job.task, 5)
|
||||
# Not deferred (thumbnail work writes no records); only scans add items.
|
||||
self.assertEqual(outcome, "skipped")
|
||||
self.assertEqual(self._items(), [])
|
||||
# Not deferred (thumbnail work writes no records): queued (#659).
|
||||
self.assertEqual(outcome, "recorded")
|
||||
self.assertEqual(len(self._items()), 1)
|
||||
|
||||
async def test_monitor_wiring_reaches_new_and_existing_handlers(self):
|
||||
self._require_module()
|
||||
@@ -1079,6 +1151,198 @@ class TestRecordedSpelling(ReviewTestCase):
|
||||
db.refresh_review_spelling(locator, os.path.join(root, "other.png"))
|
||||
|
||||
|
||||
class TestReviewWorker(ReviewTestCase):
|
||||
"""#659 C5: one daemon thread records monitor outputs, off the image
|
||||
worker, one path at a time."""
|
||||
|
||||
def _worker_thread(self):
|
||||
return self.api._review_worker()._thread
|
||||
|
||||
async def test_a_queued_output_is_recorded_on_the_worker_thread(self):
|
||||
self._roots()
|
||||
path = self.output_dir / "two.png"
|
||||
write_png(path, prompt=unlinkable_graph("cat", "dog"))
|
||||
calls = Recorded(self, self.api)
|
||||
|
||||
self.assertEqual(self.api.queue_review_file(str(path)), "queued")
|
||||
await calls.wait_for(1)
|
||||
|
||||
self.assertEqual(calls.outcomes, ["recorded"])
|
||||
self.assertEqual(len(self._items()), 1)
|
||||
thread = self._worker_thread()
|
||||
self.assertEqual(thread.name, "pm-review-recorder")
|
||||
self.assertTrue(thread.daemon)
|
||||
self.assertTrue(self.api.review_worker_started())
|
||||
|
||||
async def test_a_worker_that_dies_is_started_again_by_the_next_output(self):
|
||||
"""An unexpected error outside one recording ends the thread with a
|
||||
log line, and the next queued output starts a new one (never a dead
|
||||
worker that keeps answering ``queued``)."""
|
||||
from unittest.mock import patch
|
||||
|
||||
self._roots()
|
||||
worker = self.api._review_worker()
|
||||
real = type(worker)._next_locked
|
||||
broken = []
|
||||
|
||||
def next_once_broken(self_):
|
||||
if not broken:
|
||||
broken.append(True)
|
||||
raise ValueError("boom")
|
||||
return real(self_)
|
||||
|
||||
first = self.output_dir / "one.png"
|
||||
write_png(first, prompt=unlinkable_graph("cat", "dog"))
|
||||
with patch.object(type(worker), "_next_locked", next_once_broken):
|
||||
with self.assertLogs(worker._logger, level="ERROR") as logs:
|
||||
self.assertEqual(self.api.queue_review_file(str(first)), "queued")
|
||||
dead = worker._thread
|
||||
await asyncio.to_thread(dead.join, 5)
|
||||
self.assertFalse(dead.is_alive())
|
||||
self.assertIn("review worker stopped", "\n".join(logs.output))
|
||||
self.assertIsNone(worker._thread)
|
||||
self.assertTrue(self.api.review_worker_started())
|
||||
|
||||
calls = Recorded(self, self.api)
|
||||
second = self.output_dir / "two.png"
|
||||
write_png(second, prompt=unlinkable_graph("bird", "fish"))
|
||||
self.assertEqual(self.api.queue_review_file(str(second)), "queued")
|
||||
await calls.wait_for(2)
|
||||
self.assertEqual(sorted(calls.outcomes), ["recorded", "recorded"])
|
||||
|
||||
async def test_a_path_queued_while_it_runs_runs_once_more_never_at_once(self):
|
||||
import threading
|
||||
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
running, overlaps = [], []
|
||||
|
||||
def held(image_path):
|
||||
if image_path in running:
|
||||
overlaps.append(image_path)
|
||||
running.append(image_path)
|
||||
try:
|
||||
if not entered.is_set():
|
||||
entered.set()
|
||||
release.wait(WAIT_SECONDS)
|
||||
return "skipped"
|
||||
finally:
|
||||
running.remove(image_path)
|
||||
|
||||
calls = Recorded(self, self.api, side_effect=held)
|
||||
self.addCleanup(release.set)
|
||||
first, other = str(self.output_dir / "a.png"), str(self.output_dir / "b.png")
|
||||
self.api.queue_review_file(first)
|
||||
self.assertTrue(await asyncio.to_thread(entered.wait, WAIT_SECONDS))
|
||||
for path in (first, first, other): # coalesced: "a" once more
|
||||
self.assertEqual(self.api.queue_review_file(path), "queued")
|
||||
release.set()
|
||||
await calls.wait_for(3)
|
||||
|
||||
self.assertEqual(calls.paths, ["a.png", "a.png", "b.png"])
|
||||
self.assertEqual(overlaps, [])
|
||||
|
||||
async def test_a_full_queue_drops_its_oldest_path_and_never_blocks(self):
|
||||
import threading
|
||||
|
||||
from py.api import review_recording
|
||||
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def held(image_path):
|
||||
if not entered.is_set():
|
||||
entered.set()
|
||||
release.wait(WAIT_SECONDS)
|
||||
return "skipped"
|
||||
|
||||
calls = Recorded(self, self.api, side_effect=held)
|
||||
self.addCleanup(release.set)
|
||||
with patch.object(review_recording, "REVIEW_QUEUE_LIMIT", 2):
|
||||
self.api.queue_review_file(str(self.output_dir / "x.png"))
|
||||
self.assertTrue(await asyncio.to_thread(entered.wait, WAIT_SECONDS))
|
||||
with self.assertLogs("prompt_manager.api", logging.INFO) as logs:
|
||||
for name in ("a.png", "b.png", "c.png"):
|
||||
self.assertEqual(
|
||||
self.api.queue_review_file(str(self.output_dir / name)),
|
||||
"queued",
|
||||
)
|
||||
release.set()
|
||||
await calls.wait_for(3)
|
||||
self.assertEqual(calls.paths, ["x.png", "b.png", "c.png"])
|
||||
self.assertTrue(any("a.png" in line for line in logs.output), logs.output)
|
||||
|
||||
async def test_the_deferred_set_keeps_its_newest_paths(self):
|
||||
from py.api import review_recording
|
||||
|
||||
calls = Recorded(self, self.api, side_effect=lambda path: "deferred")
|
||||
blocked = patch.object(
|
||||
self.api._jobs, "blocker", return_value=object()
|
||||
) # a job stays running: no replay
|
||||
blocked.start()
|
||||
self.addCleanup(blocked.stop)
|
||||
with (
|
||||
patch.object(review_recording, "REVIEW_DEFERRED_LIMIT", 2),
|
||||
self.assertLogs("prompt_manager.api", logging.INFO) as logs,
|
||||
):
|
||||
for name in ("a.png", "b.png", "c.png"):
|
||||
self.api.queue_review_file(str(self.output_dir / name))
|
||||
await calls.wait_for(3)
|
||||
worker = self.api._review_worker()
|
||||
self.assertTrue(await asyncio.to_thread(worker.wait_idle, WAIT_SECONDS))
|
||||
self.assertEqual(worker.deferred_count(), 2)
|
||||
self.assertEqual(
|
||||
[os.path.basename(p) for p in worker.deferred_paths()],
|
||||
["b.png", "c.png"],
|
||||
)
|
||||
self.assertTrue(any("a.png" in line for line in logs.output), logs.output)
|
||||
|
||||
async def test_a_recorder_failure_is_logged_and_the_worker_goes_on(self):
|
||||
def flaky(image_path):
|
||||
if image_path.endswith("bad.png"):
|
||||
raise sqlite3.OperationalError("database is locked")
|
||||
return "skipped"
|
||||
|
||||
calls = Recorded(self, self.api, side_effect=flaky)
|
||||
with self.assertLogs("prompt_manager.api", logging.WARNING) as logs:
|
||||
self.api.queue_review_file(str(self.output_dir / "bad.png"))
|
||||
self.api.queue_review_file(str(self.output_dir / "good.png"))
|
||||
await calls.wait_for(2)
|
||||
self.assertEqual(calls.outcomes, ["raised", "skipped"])
|
||||
self.assertTrue(any("bad.png" in line for line in logs.output))
|
||||
self.assertTrue(self._worker_thread().is_alive())
|
||||
|
||||
async def test_stop_drops_waiting_paths_joins_and_refuses_new_ones(self):
|
||||
import threading
|
||||
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
|
||||
def held(image_path):
|
||||
entered.set()
|
||||
release.wait(WAIT_SECONDS)
|
||||
return "skipped"
|
||||
|
||||
Recorded(self, self.api, side_effect=held)
|
||||
self.addCleanup(release.set)
|
||||
self.api.queue_review_file(str(self.output_dir / "a.png"))
|
||||
self.assertTrue(await asyncio.to_thread(entered.wait, WAIT_SECONDS))
|
||||
self.api.queue_review_file(str(self.output_dir / "b.png"))
|
||||
thread = self._worker_thread()
|
||||
|
||||
with self.assertLogs("prompt_manager.api", logging.WARNING):
|
||||
self.assertFalse(self.api.stop_review_worker(0.05)) # "a" in hand
|
||||
release.set()
|
||||
self.assertTrue(self.api.stop_review_worker(WAIT_SECONDS))
|
||||
self.assertFalse(thread.is_alive())
|
||||
self.assertEqual(
|
||||
self.api.queue_review_file(str(self.output_dir / "c.png")), "stopped"
|
||||
)
|
||||
self.assertEqual(self.api._review_worker().pending_count(), 0)
|
||||
|
||||
def test_a_worker_never_started_stops_at_once(self):
|
||||
self.assertFalse(self.api.review_worker_started())
|
||||
self.assertTrue(self.api.stop_review_worker(0))
|
||||
self.assertFalse(self.api.review_worker_started())
|
||||
|
||||
|
||||
class TestCaptureStoreShutdown(ReviewTestCase):
|
||||
async def test_recording_after_close_creates_no_store(self):
|
||||
"""A scan recording still in flight at shutdown leaks nothing (M2),
|
||||
|
||||
@@ -3,22 +3,25 @@
|
||||
The maintainer's live queue (#284 / #288) held 39 items whose 11 candidates
|
||||
all read "unresolved", "No positive / No negative": the ingestion resolver
|
||||
found several sampler branches but could trace no prompt on any of them.
|
||||
An ambiguous result is reviewable only when at least two candidates carry a
|
||||
resolved prompt text. With none, the file could not be traced; with exactly
|
||||
one, the other branches may still have made the file, so the one text is
|
||||
not certain either (the resolver never flattens unknown semantics). Both
|
||||
stay unresolved and are never queued, and a rescan removes the pending,
|
||||
An ambiguous result is reviewable when at least one candidate carries a
|
||||
resolved prompt text (#657 addendum D1, 2026-11-20: one readable choice is
|
||||
enough; the other branches stay listed, disabled, so the user sees them and
|
||||
can still Leave unresolved). With none, the file could not be traced: it
|
||||
stays unresolved and is never queued, and a rescan removes the pending,
|
||||
undecided items such files already have.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
try:
|
||||
from tests.sweep_graphs import ENHANCED_TEXT, enhanced_sweep_graph
|
||||
from tests.test_review import DELIMITERS, write_png
|
||||
from tests.test_review_outcome import OutcomeTestCase
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from sweep_graphs import ENHANCED_TEXT, enhanced_sweep_graph
|
||||
from test_review import DELIMITERS, write_png
|
||||
from test_review_outcome import OutcomeTestCase
|
||||
|
||||
@@ -67,6 +70,11 @@ class ChoosableTestCase(OutcomeTestCase):
|
||||
write_png(self.output_dir / name, prompt=graph)
|
||||
return self.output_dir / name
|
||||
|
||||
@staticmethod
|
||||
def _evidence(item):
|
||||
evidence = item["evidence"]
|
||||
return json.loads(evidence) if isinstance(evidence, str) else evidence
|
||||
|
||||
|
||||
class TestChoosableCandidates(unittest.TestCase):
|
||||
def _resolution(self, *states):
|
||||
@@ -78,18 +86,24 @@ class TestChoosableCandidates(unittest.TestCase):
|
||||
)
|
||||
return {"state": "ambiguous", "candidates": candidates}
|
||||
|
||||
def test_two_resolved_candidates_are_reviewable(self):
|
||||
resolution = self._resolution("resolved", "resolved", "unresolved")
|
||||
self.assertTrue(review_capture.reviewable(resolution))
|
||||
def test_one_or_more_resolved_candidates_are_reviewable(self):
|
||||
for states in (
|
||||
("resolved", "resolved", "unresolved"),
|
||||
("resolved", "unresolved"),
|
||||
("unresolved", "resolved"),
|
||||
):
|
||||
with self.subTest(states=states):
|
||||
resolution = self._resolution(*states)
|
||||
self.assertTrue(review_capture.reviewable(resolution))
|
||||
|
||||
def test_none_or_one_resolved_candidate_is_not_reviewable(self):
|
||||
for states in ((), ("unresolved",) * 11, ("resolved", "unresolved")):
|
||||
def test_no_resolved_candidate_is_not_reviewable(self):
|
||||
for states in ((), ("unresolved",) * 11):
|
||||
with self.subTest(states=states):
|
||||
resolution = self._resolution(*states)
|
||||
self.assertFalse(review_capture.reviewable(resolution))
|
||||
|
||||
def test_blank_or_missing_text_does_not_count(self):
|
||||
resolution = self._resolution("resolved", "resolved")
|
||||
resolution = self._resolution("resolved", "unresolved")
|
||||
resolution["candidates"][0]["positive"] = {"text": " "}
|
||||
self.assertFalse(review_capture.reviewable(resolution))
|
||||
resolution["candidates"][0]["positive"] = None
|
||||
@@ -110,18 +124,21 @@ class TestChoosableCandidates(unittest.TestCase):
|
||||
|
||||
|
||||
class TestStoredEvidenceOffersChoice(unittest.TestCase):
|
||||
def test_unlimited_evidence_needs_two_choosable_candidates(self):
|
||||
def test_unlimited_evidence_needs_one_choosable_candidate(self):
|
||||
side = {"text": "cat"}
|
||||
two = [{"state": "resolved", "positive": side}] * 2
|
||||
self.assertTrue(evidence_offers_choice({"candidates": two}))
|
||||
one = two[:1] + [{"state": "unresolved", "positive": None}]
|
||||
self.assertFalse(evidence_offers_choice({"candidates": one}))
|
||||
self.assertTrue(evidence_offers_choice({"candidates": one}))
|
||||
none = [{"state": "unresolved", "positive": None}] * 2
|
||||
self.assertFalse(evidence_offers_choice({"candidates": none}))
|
||||
|
||||
def test_limited_evidence_offers_a_choice_only_with_two_candidates(self):
|
||||
self.assertTrue(
|
||||
evidence_offers_choice({"limited": True, "candidate_total": 18})
|
||||
)
|
||||
for total in (0, 1, None, "18", True):
|
||||
def test_limited_evidence_offers_a_choice_with_one_candidate(self):
|
||||
for total in (1, 18):
|
||||
with self.subTest(total=total):
|
||||
evidence = {"limited": True, "candidate_total": total}
|
||||
self.assertTrue(evidence_offers_choice(evidence))
|
||||
for total in (0, None, "18", True):
|
||||
with self.subTest(total=total):
|
||||
evidence = {"limited": True, "candidate_total": total}
|
||||
self.assertFalse(evidence_offers_choice(evidence))
|
||||
@@ -148,16 +165,19 @@ class TestNothingToChooseIsNotQueued(ChoosableTestCase):
|
||||
self.assertEqual(job["counters"]["review"], 1, job["counters"])
|
||||
self.assertEqual(self._capture_files(), [])
|
||||
|
||||
async def test_exactly_one_candidate_with_text_stays_unresolved(self):
|
||||
"""One traced branch beside untraced ones is not certain: no link."""
|
||||
async def test_exactly_one_candidate_with_text_is_queued_not_linked(self):
|
||||
"""One traced branch beside untraced ones is not certain: no link,
|
||||
but it is a choice to confirm (D1), with the other branch listed."""
|
||||
self._roots()
|
||||
self._write("one.png", opaque_graph("cat", traced=("dog",)))
|
||||
|
||||
job = await self._scan()
|
||||
|
||||
self.assertEqual(self._items(), [])
|
||||
(item,) = self._items()
|
||||
states = sorted(c["state"] for c in self._evidence(item)["candidates"])
|
||||
self.assertEqual(states, ["resolved", "unresolved"])
|
||||
(row,) = job["outcomes"]["review"]
|
||||
self.assertIn("could not be traced", row["detail"])
|
||||
self.assertIn("more than one prompt could match", row["detail"])
|
||||
self.assertEqual(job["counters"].get("added", 0), 0, job["counters"])
|
||||
self.assertEqual(job["counters"].get("known", 0), 0, job["counters"])
|
||||
|
||||
@@ -188,8 +208,7 @@ class TestNothingToChooseIsNotQueued(ChoosableTestCase):
|
||||
def test_recorder_reports_untraced_and_stores_nothing(self):
|
||||
self._roots()
|
||||
self._write("none.png", opaque_graph("cat", "dog"))
|
||||
self._write("one.png", opaque_graph("cat", traced=("dog",)))
|
||||
for name in ("none.png", "one.png"):
|
||||
for name in ("none.png",):
|
||||
with self.subTest(name=name):
|
||||
outcome = review_capture.record_ambiguous_file(
|
||||
self.api.db, self.api._captures, self.output_dir, 0, name
|
||||
@@ -202,10 +221,50 @@ class TestNothingToChooseIsNotQueued(ChoosableTestCase):
|
||||
self._roots()
|
||||
path = self._write("none.png", opaque_graph("cat", "dog"))
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "untraced")
|
||||
self.assertEqual(self._items(), [])
|
||||
|
||||
|
||||
class TestOneReadableChoiceIsQueued(ChoosableTestCase):
|
||||
"""#657 addendum D1: the sweep with an LLM enhancer on ``any_01``.
|
||||
|
||||
The inspection profile finds two candidates, one decided at run time
|
||||
and one readable; the file is queued with both listed, by the scan and
|
||||
by the monitor, and is never linked.
|
||||
"""
|
||||
|
||||
def _assert_one_choice(self, item):
|
||||
evidence = self._evidence(item)
|
||||
self.assertEqual(evidence["profile"], "inspection")
|
||||
by_state = {}
|
||||
for candidate in evidence["candidates"]:
|
||||
by_state.setdefault(candidate["state"], []).append(candidate)
|
||||
(readable,) = by_state["resolved"]
|
||||
self.assertEqual(readable["positive"]["text"], ENHANCED_TEXT)
|
||||
(runtime,) = by_state["unresolved"]
|
||||
self.assertEqual(runtime["reason"], "Text is decided at run time")
|
||||
|
||||
async def test_the_scan_queues_it(self):
|
||||
self._roots()
|
||||
self._write("sweep.png", enhanced_sweep_graph())
|
||||
|
||||
job = await self._scan()
|
||||
|
||||
(item,) = self._items()
|
||||
self._assert_one_choice(item)
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
self.assertFalse(self.api.db.review_file_linked((str(self.output_dir),)))
|
||||
|
||||
def test_the_monitor_queues_it(self):
|
||||
self._roots()
|
||||
path = self._write("sweep.png", enhanced_sweep_graph())
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "recorded")
|
||||
(item,) = self._items()
|
||||
self._assert_one_choice(item)
|
||||
self.assertFalse(self.api.db.review_file_linked((str(path),)))
|
||||
|
||||
|
||||
class TestUntracedItemsLeaveTheQueue(ChoosableTestCase):
|
||||
async def test_rescan_removes_pending_items_without_a_choice(self):
|
||||
"""The maintainer's 39 items: queued before the rule, gone on rescan."""
|
||||
@@ -220,14 +279,14 @@ class TestUntracedItemsLeaveTheQueue(ChoosableTestCase):
|
||||
|
||||
job = await self._scan("all")
|
||||
|
||||
(item,) = self._items()
|
||||
self.assertEqual(os.path.basename(item["locator"]), "two.png")
|
||||
self.assertEqual(self._pending(), 1)
|
||||
names = sorted(os.path.basename(i["locator"]) for i in self._items())
|
||||
self.assertEqual(names, ["one.png", "two.png"])
|
||||
self.assertEqual(self._pending(), 2)
|
||||
self.assertGreater(self._review_revision(), revision)
|
||||
self.assertEqual(job["scope"]["review_untraced"], 2)
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
self.assertEqual(job["scope"]["review_untraced"], 1)
|
||||
self.assertEqual(job["scope"]["review_items"], 2)
|
||||
self.assertIn(
|
||||
"= 2 images left Needs review · nothing to choose", "\n".join(job["log"])
|
||||
"= 1 image left Needs review · nothing to choose", "\n".join(job["log"])
|
||||
)
|
||||
|
||||
async def test_decided_items_of_untraced_files_are_never_touched(self):
|
||||
@@ -320,19 +379,21 @@ class TestUntracedItemsLeaveTheQueue(ChoosableTestCase):
|
||||
await self._scan("all")
|
||||
self.assertEqual(self._pending(), 0)
|
||||
|
||||
async def test_the_scan_not_the_monitor_removes_an_untraced_outputs_item(self):
|
||||
"""The monitor only clears items of outputs it links; the next scan
|
||||
removes the item of an output that offers nothing to choose."""
|
||||
async def test_the_monitor_removes_an_untraced_outputs_item_as_the_scan(self):
|
||||
"""#659: the monitor's pass runs the scan's per-file steps, so it
|
||||
removes the item of an output that offers nothing to choose, as the
|
||||
next scan would."""
|
||||
self._roots()
|
||||
path = self._write("none.png", opaque_graph("cat", "dog"))
|
||||
self._record_pre_fix("none.png")
|
||||
# A pre-fix item of other bytes keeps the stat shortcut out of the way.
|
||||
self._write("none.png", opaque_graph("a cow", "dog"))
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual(len(self._items()), 1)
|
||||
await self._scan("all")
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "untraced")
|
||||
self.assertEqual(self._items(), [])
|
||||
job = await self._scan("all")
|
||||
self.assertEqual(self._items(), [])
|
||||
self.assertEqual(job["scope"]["review_untraced"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Too many candidates are collapsed, not dropped (#657 addendum D3).
|
||||
|
||||
The maintainer's ConsistentFace batch: 83 samplers, 81 distinct prompts, above
|
||||
``MAX_CANDIDATES`` (16), stored a ``limited`` item without candidates, so the
|
||||
card offered nothing to choose. Now the choosable candidates are grouped by
|
||||
their (positive, negative) texts, the groups ordered by size (descending) then
|
||||
first appearance, and the first 16 kept, one representative each (its first
|
||||
occurrence, so its sampler and hash are real). The evidence is ordinary and
|
||||
unlimited, with ``collapsed: {shown, total, paths}``. ``limited`` remains only
|
||||
for evidence that cannot be projected or canonicalized. Apply is unchanged.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import unittest
|
||||
|
||||
try:
|
||||
from tests.test_api_review import ReviewRoutesTestCase
|
||||
from tests.test_review import unlinkable_graph, write_png
|
||||
except ImportError: # discovered with tests/ as the top-level directory
|
||||
from test_api_review import ReviewRoutesTestCase
|
||||
from test_review import unlinkable_graph, write_png
|
||||
|
||||
from database.review_schema import MAX_CANDIDATES
|
||||
from py.api.review import _candidate_still_offered
|
||||
from utils import review_capture
|
||||
|
||||
POPULAR = "a popular prompt"
|
||||
SECOND = "a second prompt"
|
||||
|
||||
|
||||
def _candidate(sampler, text, negative="bad"):
|
||||
if text is None:
|
||||
return {"sampler_id": sampler, "state": "unresolved", "positive": None}
|
||||
return {
|
||||
"sampler_id": sampler,
|
||||
"state": "resolved",
|
||||
"positive": {"text": text},
|
||||
"negative": {"text": negative} if negative is not None else None,
|
||||
}
|
||||
|
||||
|
||||
def _resolution(texts):
|
||||
return {
|
||||
"state": "ambiguous",
|
||||
"reason": "Several samplers",
|
||||
"candidates": [_candidate(str(i), t) for i, t in enumerate(texts)],
|
||||
}
|
||||
|
||||
|
||||
def batch_texts():
|
||||
"""Twenty singles, one text five times, another three times, one
|
||||
unresolved branch: 29 distinct candidates, 22 distinct prompts."""
|
||||
singles = [f"prompt {n}" for n in range(20)]
|
||||
texts = [None, singles[0], POPULAR, singles[1], SECOND]
|
||||
texts += [POPULAR] * 4 + [SECOND] * 2 + singles[2:]
|
||||
return texts
|
||||
|
||||
|
||||
class TestCollapsedEvidence(unittest.TestCase):
|
||||
def test_groups_by_frequency_then_first_appearance(self):
|
||||
texts = batch_texts()
|
||||
|
||||
evidence, count, limited = review_capture.review_evidence(_resolution(texts))
|
||||
|
||||
self.assertFalse(limited)
|
||||
self.assertNotIn("limited", evidence)
|
||||
self.assertEqual(count, MAX_CANDIDATES)
|
||||
shown = [c["positive"]["text"] for c in evidence["candidates"]]
|
||||
singles = [f"prompt {n}" for n in range(14)]
|
||||
self.assertEqual(shown, [POPULAR, SECOND, *singles])
|
||||
self.assertEqual(
|
||||
evidence["collapsed"],
|
||||
{"shown": MAX_CANDIDATES, "total": 22, "paths": len(texts)},
|
||||
)
|
||||
|
||||
def test_each_group_keeps_its_first_occurrence(self):
|
||||
evidence, _count, _limited = review_capture.review_evidence(
|
||||
_resolution(batch_texts())
|
||||
)
|
||||
by_text = {c["positive"]["text"]: c for c in evidence["candidates"]}
|
||||
self.assertEqual(by_text[POPULAR]["sampler_id"], "2")
|
||||
self.assertEqual(by_text[SECOND]["sampler_id"], "4")
|
||||
for candidate in evidence["candidates"]:
|
||||
projected = {k: v for k, v in candidate.items() if k != "hash"}
|
||||
text = json.dumps(projected, sort_keys=True, separators=(",", ":"))
|
||||
self.assertEqual(
|
||||
candidate["hash"], hashlib.sha256(text.encode("ascii")).hexdigest()
|
||||
)
|
||||
|
||||
def test_negative_text_separates_groups(self):
|
||||
texts = [f"p{n}" for n in range(17)]
|
||||
resolution = _resolution(texts)
|
||||
resolution["candidates"].append(_candidate("x", "p0", negative="other"))
|
||||
resolution["candidates"].append(_candidate("y", "p0", negative=None))
|
||||
|
||||
evidence, _count, _limited = review_capture.review_evidence(resolution)
|
||||
|
||||
self.assertEqual(evidence["collapsed"]["total"], 19)
|
||||
pairs = [
|
||||
(c["positive"]["text"], (c["negative"] or {}).get("text"))
|
||||
for c in evidence["candidates"][:3]
|
||||
]
|
||||
self.assertEqual(pairs, [("p0", "bad"), ("p1", "bad"), ("p2", "bad")])
|
||||
|
||||
def test_sixteen_or_fewer_candidates_are_not_collapsed(self):
|
||||
texts = [f"p{n}" for n in range(MAX_CANDIDATES)]
|
||||
evidence, count, limited = review_capture.review_evidence(_resolution(texts))
|
||||
self.assertFalse(limited)
|
||||
self.assertEqual(count, MAX_CANDIDATES)
|
||||
self.assertNotIn("collapsed", evidence)
|
||||
|
||||
def test_many_paths_to_few_prompts_are_not_collapsed(self):
|
||||
"""Distinct samplers, three texts and unresolved branches (#657
|
||||
review): three groups fit, so the item stays ordinary. One candidate
|
||||
per text, and the run-time branches stay listed."""
|
||||
texts = [None, POPULAR, SECOND, "third"] * 5
|
||||
evidence, count, limited = review_capture.review_evidence(_resolution(texts))
|
||||
self.assertFalse(limited)
|
||||
self.assertNotIn("collapsed", evidence)
|
||||
shown = [
|
||||
(c["state"], (c["positive"] or {}).get("text"))
|
||||
for c in evidence["candidates"]
|
||||
]
|
||||
self.assertEqual(
|
||||
shown[:4],
|
||||
[
|
||||
("unresolved", None),
|
||||
("resolved", POPULAR),
|
||||
("resolved", SECOND),
|
||||
("resolved", "third"),
|
||||
],
|
||||
)
|
||||
self.assertEqual(count, 8)
|
||||
self.assertEqual(sum(1 for state, _ in shown if state == "resolved"), 3)
|
||||
|
||||
def test_unresolved_branches_fill_up_to_the_bound_after_every_text(self):
|
||||
texts = [None] * 20 + [POPULAR, SECOND, "third"] * 2
|
||||
evidence, count, limited = review_capture.review_evidence(_resolution(texts))
|
||||
self.assertFalse(limited)
|
||||
self.assertNotIn("collapsed", evidence)
|
||||
self.assertEqual(count, MAX_CANDIDATES)
|
||||
resolved = [
|
||||
c["positive"]["text"] for c in evidence["candidates"] if c["positive"]
|
||||
]
|
||||
self.assertEqual(resolved, [POPULAR, SECOND, "third"])
|
||||
sampler_ids = [c["sampler_id"] for c in evidence["candidates"]]
|
||||
self.assertEqual(sampler_ids, sorted(sampler_ids, key=int))
|
||||
|
||||
def test_nothing_choosable_is_still_limited(self):
|
||||
texts = [None] * (MAX_CANDIDATES + 1)
|
||||
evidence, count, limited = review_capture.review_evidence(_resolution(texts))
|
||||
self.assertTrue(limited)
|
||||
self.assertEqual((count, evidence["candidates"]), (0, []))
|
||||
|
||||
def test_unprojectable_evidence_is_still_limited(self):
|
||||
resolution = _resolution(batch_texts())
|
||||
resolution["candidates"][3]["positive"] = {"no": "text"}
|
||||
evidence, count, limited = review_capture.review_evidence(resolution)
|
||||
self.assertTrue(limited)
|
||||
self.assertNotIn("collapsed", evidence)
|
||||
|
||||
def test_apply_accepts_any_offered_candidate_after_a_reorder(self):
|
||||
"""Apply checks the chosen hash against every candidate the bytes
|
||||
offer, not against a fresh collapse (#657 review): a reorder that
|
||||
changes the representatives, or a text past the first 16, is still
|
||||
offered."""
|
||||
resolution = _resolution(batch_texts())
|
||||
evidence, _count, _limited = review_capture.review_evidence(resolution)
|
||||
chosen = {c["positive"]["text"]: c["hash"] for c in evidence["candidates"]}
|
||||
reordered = dict(resolution, candidates=resolution["candidates"][::-1])
|
||||
self.assertTrue(_candidate_still_offered(reordered, chosen[POPULAR]))
|
||||
tail = _resolution(batch_texts())["candidates"][-1]
|
||||
tail_hash = review_capture.candidate_hashes({"candidates": [tail]})
|
||||
(only,) = tail_hash
|
||||
self.assertTrue(_candidate_still_offered(resolution, only))
|
||||
self.assertFalse(_candidate_still_offered(resolution, "0" * 64))
|
||||
|
||||
def test_apply_still_finds_a_representative(self):
|
||||
resolution = _resolution(batch_texts())
|
||||
evidence, _count, _limited = review_capture.review_evidence(resolution)
|
||||
for candidate in evidence["candidates"]:
|
||||
self.assertTrue(_candidate_still_offered(resolution, candidate["hash"]))
|
||||
|
||||
|
||||
def many_prompts():
|
||||
"""Unlinkable: the parser's sampler is unresolved, three samplers share
|
||||
``POPULAR`` and seventeen have a prompt each (18 prompts, 21 paths)."""
|
||||
return unlinkable_graph(*([POPULAR] * 3 + [f"prompt {n}" for n in range(17)]))
|
||||
|
||||
|
||||
class TestCollapsedItems(ReviewRoutesTestCase):
|
||||
def _write_many(self, name="many.png"):
|
||||
path = self.output_dir / name
|
||||
write_png(path, prompt=many_prompts())
|
||||
return path
|
||||
|
||||
async def test_scan_records_collapsed_choices_and_apply_links(self):
|
||||
self._require_routes()
|
||||
self._roots()
|
||||
path = self._write_many()
|
||||
|
||||
job = await self._scan()
|
||||
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
(stored,) = self._items()
|
||||
self.assertFalse(stored["limited"])
|
||||
self.assertEqual(stored["candidate_count"], MAX_CANDIDATES)
|
||||
item, detail, observed = await self._open()
|
||||
self.assertFalse(detail["limited"])
|
||||
self.assertEqual(
|
||||
detail["collapsed"], {"shown": MAX_CANDIDATES, "total": 18, "paths": 21}
|
||||
)
|
||||
self.assertEqual(detail["candidates"][0]["positive"]["text"], POPULAR)
|
||||
popular = detail["candidates"][0]
|
||||
|
||||
status, data = await self._decide(
|
||||
item["id"], self._body(detail, observed, popular["hash"])
|
||||
)
|
||||
|
||||
self.assertEqual(status, 200, data)
|
||||
conn = self.api.db.model.get_connection()
|
||||
linked = conn.execute(
|
||||
"SELECT p.text FROM generated_images gi "
|
||||
"JOIN prompts p ON p.id=gi.prompt_id WHERE gi.image_path=?",
|
||||
(str(path),),
|
||||
).fetchone()
|
||||
self.assertEqual(linked[0], POPULAR)
|
||||
|
||||
async def test_detail_of_an_ordinary_item_has_no_collapsed(self):
|
||||
self._require_routes()
|
||||
self._record(self._ambiguous("two.png"))
|
||||
_item, detail, _observed = await self._open()
|
||||
self.assertIsNone(detail["collapsed"])
|
||||
|
||||
async def test_an_old_limited_item_is_replaced_on_the_next_scan(self):
|
||||
"""Items recorded before D3 carry the previous item version: the
|
||||
next scan records the collapsed item and it supersedes the pending,
|
||||
undecided limited one."""
|
||||
self._roots()
|
||||
path = self._write_many()
|
||||
old = self._old_limited_item(path)
|
||||
|
||||
job = await self._scan("all")
|
||||
|
||||
(item,) = self._items()
|
||||
self.assertNotEqual(item["id"], old)
|
||||
self.assertFalse(item["limited"])
|
||||
self.assertIn("collapsed", json.loads(item["evidence"]))
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
|
||||
async def test_a_decided_old_limited_item_is_kept_and_not_requeued(self):
|
||||
self._roots()
|
||||
path = self._write_many()
|
||||
old = self._old_limited_item(path)
|
||||
conn = self.api.db.model.get_connection()
|
||||
with conn:
|
||||
conn.execute(
|
||||
"UPDATE media_review_items SET state='unresolved', revision=1 "
|
||||
"WHERE id=?",
|
||||
(old,),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO media_review_decisions(id,item_id,decision_revision,"
|
||||
"created_at,outcome,candidate_hash,evidence) VALUES(?,?,?,?,?,?,?)",
|
||||
(
|
||||
"00000000-0000-4000-8000-0000000000d3",
|
||||
old,
|
||||
1,
|
||||
"2026-11-20T00:00:00+00:00",
|
||||
"unresolved",
|
||||
None,
|
||||
'{"kind":"user-selection"}',
|
||||
),
|
||||
)
|
||||
|
||||
await self._scan("all")
|
||||
|
||||
self.assertEqual([i["id"] for i in self._items()], [old])
|
||||
|
||||
def _old_limited_item(self, path):
|
||||
"""A limited item as the recorder stored it before D3 (version 1)."""
|
||||
facts = path.stat()
|
||||
locator, spelled = self._locator(path)
|
||||
evidence = {
|
||||
"resolver_version": 1,
|
||||
"reason": "Several samplers",
|
||||
"limited": True,
|
||||
"candidate_total": 21,
|
||||
"candidates": [],
|
||||
}
|
||||
stored = self.api.db.record_review_item(
|
||||
locator=locator,
|
||||
spelled_path=spelled,
|
||||
sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
size=facts.st_size,
|
||||
mtime_ns=facts.st_mtime_ns,
|
||||
epoch=self.api.db.get_execution_epoch(),
|
||||
resolver_version=1,
|
||||
evidence=evidence,
|
||||
candidate_count=0,
|
||||
limited=True,
|
||||
)
|
||||
self.assertTrue(stored)
|
||||
(item,) = self._items()
|
||||
return item["id"]
|
||||
|
||||
def _locator(self, path):
|
||||
import os
|
||||
|
||||
relative = path.relative_to(self.output_dir).parts
|
||||
spelled = os.path.join(os.path.realpath(self.output_dir), *relative)
|
||||
return os.path.normcase(spelled), spelled
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+285
-38
@@ -10,7 +10,9 @@ choices. Ruling (option a): when the default profile is ambiguous with fewer
|
||||
than two candidates that carry text, the scan asks the inspection profile;
|
||||
with at least two choosable candidates it records the item from that
|
||||
profile, and Apply re-resolves with the same profile. Nothing links
|
||||
automatically from the inspection profile, and the live monitor never queues.
|
||||
automatically from the inspection profile. Since #659 the live monitor queues
|
||||
what the scan would, at a file's final unlinked outcome, and a file the
|
||||
default profile calls unresolved is offered its inspection choices too.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
@@ -29,6 +31,7 @@ except ImportError: # discovered with tests/ as the top-level directory
|
||||
from test_review import unlinkable_graph, write_png
|
||||
|
||||
from tests.background_stops import close_handler
|
||||
from tests.sweep_graphs import SWEEP_TEXTS, ambiguous_sweep_graph
|
||||
from utils import inspection_semantics, review_capture
|
||||
from utils.hashing import generate_prompt_hash
|
||||
from utils.image_monitor import ImageGenerationHandler
|
||||
@@ -164,6 +167,18 @@ def _unrelated_encoder(doc):
|
||||
)
|
||||
|
||||
|
||||
ANY_SWITCH = {"strategy": "first-present", "input_prefix": "any_"}
|
||||
|
||||
|
||||
def _without_any_switch(doc):
|
||||
"""The table before #657 listed rgthree's Any Switch."""
|
||||
del doc["selectors"]["Any Switch (rgthree)"]
|
||||
|
||||
|
||||
def _with_any_switch(doc):
|
||||
doc["selectors"]["Any Switch (rgthree)"] = dict(ANY_SWITCH)
|
||||
|
||||
|
||||
def _texts(evidence):
|
||||
return sorted(
|
||||
c["positive"]["text"]
|
||||
@@ -221,6 +236,99 @@ class InspectionTestCase(ReviewRoutesTestCase):
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
MIXED_NAME = "zzz_00001_.png"
|
||||
|
||||
|
||||
def mixed_edit_graph():
|
||||
"""One Qwen image-edit sampler ("alpha", which only the inspection profile
|
||||
reads) and one CLIPTextEncode sampler ("beta"): the default profile
|
||||
offers one choice beside an unresolved branch, the inspection profile
|
||||
both (#657 review)."""
|
||||
graph = qwen_edit_graph("alpha")
|
||||
graph["900"] = {
|
||||
"class_type": "CheckpointLoaderSimple",
|
||||
"inputs": {"ckpt_name": "m.safetensors"},
|
||||
}
|
||||
graph["901"] = {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"clip": ["900", 1], "text": "beta"},
|
||||
}
|
||||
graph["902"] = {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"clip": ["900", 1], "text": "neg"},
|
||||
}
|
||||
graph["903"] = {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"model": ["900", 0],
|
||||
"positive": ["901", 0],
|
||||
"negative": ["902", 0],
|
||||
"latent_image": ["6", 0],
|
||||
"seed": 9,
|
||||
},
|
||||
}
|
||||
graph["904"] = {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {"samples": ["903", 0], "vae": ["900", 2]},
|
||||
}
|
||||
graph["905"] = {
|
||||
"class_type": "SaveImage",
|
||||
"inputs": {"images": ["904", 0], "filename_prefix": "x"},
|
||||
}
|
||||
return graph
|
||||
|
||||
|
||||
class TestPartialDefaultAsksInspection(InspectionTestCase):
|
||||
"""A default result with one choice beside unresolved branches still asks
|
||||
the inspection profile, which may read those branches (#657 review). The
|
||||
file's name anchors on no saver, so both branches are offered."""
|
||||
|
||||
def _write(self, name=MIXED_NAME, graph=None, color=(255, 0, 0)):
|
||||
return super()._write(name, graph, color)
|
||||
|
||||
def _assert_inspection_item(self, item):
|
||||
evidence = self._evidence(item)
|
||||
self.assertEqual(evidence["profile"], "inspection")
|
||||
self.assertEqual(_texts(evidence), ["alpha", "beta"])
|
||||
|
||||
async def test_the_scan_records_the_inspection_choices(self):
|
||||
self._roots()
|
||||
self._write(graph=mixed_edit_graph())
|
||||
|
||||
await self._scan()
|
||||
|
||||
(item,) = self._items()
|
||||
self._assert_inspection_item(item)
|
||||
|
||||
def test_the_monitor_records_the_inspection_choices(self):
|
||||
self._roots()
|
||||
path = self._write(graph=mixed_edit_graph())
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "recorded")
|
||||
(item,) = self._items()
|
||||
self._assert_inspection_item(item)
|
||||
|
||||
async def test_a_rescan_keeps_an_older_inspection_item_inspection(self):
|
||||
"""An item recorded before D1 and D3 (two choices needed, the old
|
||||
evidence version) is recorded again from the inspection profile,
|
||||
never replaced by the poorer default choices."""
|
||||
self._roots()
|
||||
self._write(graph=mixed_edit_graph())
|
||||
with (
|
||||
patch.object(review_capture, "MIN_CHOOSABLE", 2),
|
||||
patch.object(review_capture, "REVIEW_EVIDENCE_VERSION", 0),
|
||||
):
|
||||
await self._scan()
|
||||
(old,) = self._items()
|
||||
self._assert_inspection_item(old)
|
||||
|
||||
await self._scan("all")
|
||||
|
||||
(item,) = self._items()
|
||||
self.assertNotEqual(item["id"], old["id"])
|
||||
self._assert_inspection_item(item)
|
||||
|
||||
|
||||
class TestQwenEditBatchIsQueued(InspectionTestCase):
|
||||
async def test_qwen_edit_batch_is_queued_with_its_texts(self):
|
||||
self._roots()
|
||||
@@ -264,7 +372,8 @@ class TestQwenEditBatchIsQueued(InspectionTestCase):
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
self.assertEqual(job["scope"]["review_untraced"], 0)
|
||||
|
||||
async def test_more_than_sixteen_qwen_samplers_make_a_limited_item(self):
|
||||
async def test_more_than_sixteen_qwen_samplers_are_collapsed(self):
|
||||
"""#657 addendum D3: the 16 most used prompts, not a limited item."""
|
||||
self._roots()
|
||||
self._write(graph=qwen_edit_graph(*(f"edit {n}" for n in range(17))))
|
||||
|
||||
@@ -272,9 +381,9 @@ class TestQwenEditBatchIsQueued(InspectionTestCase):
|
||||
|
||||
(item,) = self._items()
|
||||
evidence = self._evidence(item)
|
||||
self.assertTrue(item["limited"])
|
||||
self.assertEqual(item["candidate_count"], 0)
|
||||
self.assertEqual(evidence["candidate_total"], 17)
|
||||
self.assertFalse(item["limited"])
|
||||
self.assertEqual(item["candidate_count"], 16)
|
||||
self.assertEqual(evidence["collapsed"], {"shown": 16, "total": 17, "paths": 17})
|
||||
self.assertEqual(evidence["profile"], "inspection")
|
||||
|
||||
async def test_evidence_over_the_cap_makes_a_limited_item(self):
|
||||
@@ -297,10 +406,11 @@ class TestQwenEditBatchIsQueued(InspectionTestCase):
|
||||
|
||||
|
||||
class TestDefaultProfileStillDecides(InspectionTestCase):
|
||||
async def test_ambiguous_file_with_texts_keeps_the_default_profile(self):
|
||||
"""A default-ambiguous file with a choice is recorded from the
|
||||
default profile, even when the inspection profile would offer more
|
||||
candidates. That profile only checks the saver anchor (#390): no
|
||||
async def test_a_partial_default_choice_yields_to_a_fuller_inspection(self):
|
||||
"""A default-ambiguous file whose choice sits beside unresolved
|
||||
branches is recorded from the inspection profile when that offers
|
||||
more choices (#657 review; before, the default profile kept it and
|
||||
the inspection profile only checked the saver anchor, #390). No
|
||||
saver names this file, so it anchors nothing."""
|
||||
self._roots()
|
||||
graph = {
|
||||
@@ -309,19 +419,12 @@ class TestDefaultProfileStillDecides(InspectionTestCase):
|
||||
}
|
||||
self._write("unsaved_00001_.png", graph=graph)
|
||||
|
||||
with patch.object(
|
||||
review_capture,
|
||||
"inspection_choice",
|
||||
side_effect=AssertionError("inspection choices were asked"),
|
||||
):
|
||||
await self._scan()
|
||||
await self._scan()
|
||||
|
||||
(item,) = self._items()
|
||||
evidence = self._evidence(item)
|
||||
self.assertNotIn("profile", evidence)
|
||||
self.assertNotIn("semantics", evidence)
|
||||
self.assertEqual(item["resolver_version"], review_capture.RESOLVER_VERSION)
|
||||
self.assertEqual(_texts(evidence), ["cat", "dog"])
|
||||
self.assertEqual(evidence["profile"], "inspection")
|
||||
self.assertEqual(_texts(evidence), ["cat", "dog", "make it night"])
|
||||
|
||||
async def test_apply_of_a_default_item_inspects_only_for_the_anchor(
|
||||
self,
|
||||
@@ -445,28 +548,32 @@ class TestApplyInspectionCandidate(InspectionTestCase):
|
||||
self.assertEqual(job["scope"]["review_untraced"], 1)
|
||||
|
||||
|
||||
class TestMonitorNeverQueues(InspectionTestCase):
|
||||
class TestMonitorQueues(InspectionTestCase):
|
||||
def _handler(self):
|
||||
handler = ImageGenerationHandler(self.api.db, PromptTracker(self.api.db))
|
||||
self.addCleanup(close_handler, self, handler)
|
||||
handler.review_recorder = self.api.record_review_file
|
||||
return handler
|
||||
|
||||
async def test_monitor_pass_never_queues_but_the_next_scan_does(self):
|
||||
async def test_monitor_pass_queues_and_the_next_scan_reports_a_duplicate(self):
|
||||
"""#659: the monitor queues at the final outcome what the scan
|
||||
would; the next scan finds the item already there."""
|
||||
self._roots()
|
||||
path = self._write()
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual(self._items(), [])
|
||||
self.assertEqual(self._capture_files(), [])
|
||||
|
||||
await self._scan()
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "recorded")
|
||||
(item,) = self._items()
|
||||
self.assertEqual(self._evidence(item)["profile"], "inspection")
|
||||
self.assertEqual(self._capture_files(), [])
|
||||
|
||||
job = await self._scan()
|
||||
self.assertEqual([i["id"] for i in self._items()], [item["id"]])
|
||||
self.assertEqual(job["scope"]["review_items"], 1)
|
||||
self.assertEqual(job["scope"]["review_added"], 0)
|
||||
|
||||
async def test_monitor_keeps_the_inspection_item_of_an_unlinked_output(self):
|
||||
"""The monitor's untraced settle judges each item by its own
|
||||
evidence: an inspection item offers a choice and stays."""
|
||||
"""The monitor judges each item by its own evidence: the old bytes'
|
||||
inspection item offers a choice and stays beside the new bytes'."""
|
||||
self._roots()
|
||||
path = self._write()
|
||||
await self._scan()
|
||||
@@ -474,8 +581,9 @@ class TestMonitorNeverQueues(InspectionTestCase):
|
||||
# Other bytes, so the stat shortcut does not answer for the file.
|
||||
self._write(color=(0, 0, 255))
|
||||
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual([i["id"] for i in self._items()], [item["id"]])
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "recorded")
|
||||
self.assertIn(item["id"], [i["id"] for i in self._items()])
|
||||
self.assertEqual(len(self._items()), 2)
|
||||
|
||||
async def test_monitor_link_removes_the_inspection_item(self):
|
||||
self._roots()
|
||||
@@ -570,6 +678,35 @@ class TestVersionChanges(InspectionTestCase):
|
||||
self.assertEqual(status, 200, data)
|
||||
self.assertEqual(self._linked_text(path), "make it night")
|
||||
|
||||
async def test_the_any_switch_entry_moves_only_items_of_graphs_with_one(self):
|
||||
# #657: adding ``Any Switch (rgthree)`` to the table changes the class
|
||||
# projection of a graph that holds that class, and of no other graph.
|
||||
self._roots()
|
||||
self._table(_without_any_switch)
|
||||
plain = qwen_edit_graph(*PROMPTS)
|
||||
switched = {**plain, "90": {"class_type": "Any Switch (rgthree)", "inputs": {}}}
|
||||
self._write(graph=plain)
|
||||
self._write("switched_00001_.png", graph=switched)
|
||||
await self._scan()
|
||||
old = {item["locator"]: item for item in self._items()}
|
||||
self.assertEqual(len(old), 2)
|
||||
|
||||
# ``_table`` edits the table in effect: put the entry back.
|
||||
self._table(_with_any_switch)
|
||||
await self._scan("all")
|
||||
|
||||
new = {item["locator"]: item for item in self._items()}
|
||||
self.assertEqual(set(new), set(old))
|
||||
(moved,) = [locator for locator in new if "switched" in locator]
|
||||
(kept,) = [locator for locator in new if "switched" not in locator]
|
||||
self.assertEqual(new[kept]["id"], old[kept]["id"])
|
||||
self.assertEqual(new[kept]["resolver_version"], old[kept]["resolver_version"])
|
||||
self.assertNotEqual(
|
||||
new[moved]["resolver_version"], old[moved]["resolver_version"]
|
||||
)
|
||||
self.assertEqual(new[moved]["resolver_version"], _version(switched))
|
||||
self.assertEqual(self._pending(), 2)
|
||||
|
||||
async def test_unrelated_table_edit_keeps_the_item_and_does_no_work(self):
|
||||
self._roots()
|
||||
self._write()
|
||||
@@ -598,14 +735,16 @@ class TestVersionChanges(InspectionTestCase):
|
||||
write_png(self.output_dir / "two.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
await self._scan()
|
||||
(old,) = self._items()
|
||||
self.assertEqual(old["resolver_version"], 1)
|
||||
self.assertEqual(old["resolver_version"], review_capture.default_item_version())
|
||||
|
||||
with patch.object(review_capture, "RESOLVER_VERSION", 2):
|
||||
await self._scan("all")
|
||||
current = review_capture.default_item_version()
|
||||
|
||||
(item,) = self._items()
|
||||
self.assertNotEqual(item["id"], old["id"])
|
||||
self.assertEqual(item["resolver_version"], 2)
|
||||
self.assertNotEqual(current, old["resolver_version"])
|
||||
self.assertEqual(item["resolver_version"], current)
|
||||
self.assertEqual(self._pending(), 1)
|
||||
|
||||
async def test_decided_old_item_is_kept_and_no_duplicate_is_made(self):
|
||||
@@ -946,22 +1085,130 @@ class TestUntracedMemoryKeys(InspectionTestCase):
|
||||
self.assertEqual(len(key), 16)
|
||||
|
||||
|
||||
class TestMonitorNeverRecords(InspectionTestCase):
|
||||
async def test_monitor_never_records_an_unlinked_ambiguous_output(self):
|
||||
"""Only scans add items (maintainer ruling); the monitor only clears
|
||||
the items of outputs it links."""
|
||||
class TestMonitorRecords(InspectionTestCase):
|
||||
async def test_monitor_records_an_unlinked_ambiguous_output(self):
|
||||
"""#659 (2026-11-19): the monitor's pass queues an unlinked ambiguous
|
||||
output with a choice, once; the next scan reports a duplicate."""
|
||||
self._roots()
|
||||
path = self.output_dir / "two.png"
|
||||
write_png(path, prompt=unlinkable_graph("cat", "dog"))
|
||||
|
||||
with _counted(self.api._captures, "capture") as copies:
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "recorded")
|
||||
|
||||
self.assertEqual(len(copies), 1)
|
||||
(item,) = self._items()
|
||||
job = await self._scan()
|
||||
self.assertEqual([i["id"] for i in self._items()], [item["id"]])
|
||||
self.assertEqual(job["scope"]["review_added"], 0)
|
||||
|
||||
async def test_a_file_without_a_prompt_graph_is_never_captured(self):
|
||||
self._roots()
|
||||
path = self.output_dir / "plain.png"
|
||||
write_png(path)
|
||||
with _counted(self.api._captures, "capture") as copies:
|
||||
self.assertEqual(self.api.record_review_file(str(path)), "skipped")
|
||||
self.assertEqual(copies, [])
|
||||
self.assertEqual(self._items(), [])
|
||||
await self._scan()
|
||||
|
||||
|
||||
SWEEP = "sweep_00001_.png"
|
||||
|
||||
|
||||
class TestDefaultUnresolvedFiles(InspectionTestCase):
|
||||
"""#659 C1: a file the default profile calls unresolved is queued from
|
||||
the inspection profile when that finds a choice. The sweep graph with its
|
||||
switch replaced by a class no table lists is the example (the real Any
|
||||
Switch resolves since #657)."""
|
||||
|
||||
def _sweep(self):
|
||||
path = self._write(SWEEP, graph=ambiguous_sweep_graph())
|
||||
return path
|
||||
|
||||
def test_the_sweep_graph_is_recorded_from_the_inspection_profile(self):
|
||||
self._roots()
|
||||
self._sweep()
|
||||
outcome = review_capture.record_ambiguous_file(
|
||||
self.api.db, self.api._captures, self.output_dir, 0, SWEEP
|
||||
)
|
||||
self.assertEqual(outcome, "skipped") # the default profile alone
|
||||
self.assertEqual(self._items(), [])
|
||||
|
||||
outcome = review_capture.record_ambiguous_file(
|
||||
self.api.db,
|
||||
self.api._captures,
|
||||
self.output_dir,
|
||||
0,
|
||||
SWEEP,
|
||||
inspection=True,
|
||||
)
|
||||
|
||||
self.assertEqual(outcome, "recorded")
|
||||
(item,) = self._items()
|
||||
evidence = self._evidence(item)
|
||||
self.assertEqual(evidence["profile"], "inspection")
|
||||
self.assertEqual(_texts(evidence), SWEEP_TEXTS)
|
||||
self.assertEqual(item["resolver_version"], _version(ambiguous_sweep_graph()))
|
||||
self.assertEqual(self._capture_files(), [])
|
||||
|
||||
def test_a_default_unresolved_file_without_a_choice_is_untraced(self):
|
||||
self._roots()
|
||||
graph = ambiguous_sweep_graph()
|
||||
graph["14"]["inputs"].pop("any_02") # one input: nothing to choose
|
||||
graph["15"]["class_type"] = "PMTest Opaque Encode"
|
||||
self._write(SWEEP, graph=graph)
|
||||
outcome = review_capture.record_ambiguous_file(
|
||||
self.api.db,
|
||||
self.api._captures,
|
||||
self.output_dir,
|
||||
0,
|
||||
SWEEP,
|
||||
inspection=True,
|
||||
)
|
||||
self.assertEqual(outcome, "untraced")
|
||||
self.assertEqual(self._items(), [])
|
||||
|
||||
async def test_the_scan_queues_the_sweep_image(self):
|
||||
self._roots()
|
||||
path = self._sweep()
|
||||
|
||||
job = await self._scan()
|
||||
|
||||
(item,) = self._items()
|
||||
self.assertEqual(self._evidence(item)["profile"], "inspection")
|
||||
self.assertEqual(_texts(self._evidence(item)), SWEEP_TEXTS)
|
||||
(row,) = job["outcomes"]["review"]
|
||||
self.assertEqual(row["path"], SWEEP)
|
||||
self.assertIn("more than one prompt could match", row["detail"])
|
||||
self.assertIsNone(self._linked_text(path))
|
||||
# The rescan reads the queued bytes from the stat shortcut
|
||||
with _counted(review_capture, "resolve_inspection") as calls:
|
||||
await self._scan("all")
|
||||
self.assertEqual(calls, [])
|
||||
self.assertEqual(len(self._items()), 1)
|
||||
|
||||
async def test_the_monitor_queues_the_sweep_image(self):
|
||||
"""Outside ComfyUI's output folder (no run is ever sealed for it),
|
||||
the monitor's ladder leaves it unlinked and its recorder queues it."""
|
||||
self._roots()
|
||||
path = self._sweep()
|
||||
handler = ImageGenerationHandler(self.api.db, PromptTracker(self.api.db))
|
||||
self.addCleanup(close_handler, self, handler)
|
||||
outcomes = []
|
||||
|
||||
def recorder(image_path):
|
||||
outcomes.append(self.api.record_review_file(image_path))
|
||||
return outcomes[-1]
|
||||
|
||||
handler.review_recorder = recorder
|
||||
with patch("utils.image_monitor.host_output_directory", return_value=None):
|
||||
handler.process_new_image(str(path))
|
||||
|
||||
self.assertEqual(outcomes, ["recorded"])
|
||||
(item,) = self._items()
|
||||
self.assertEqual(_texts(self._evidence(item)), SWEEP_TEXTS)
|
||||
self.assertIsNone(self._linked_text(path))
|
||||
|
||||
|
||||
class TestStaleSettleContainment(InspectionTestCase):
|
||||
async def test_a_failed_stale_settle_is_logged_and_counted(self):
|
||||
|
||||
@@ -357,21 +357,25 @@ class TestMonitorRule(OutcomeTestCase):
|
||||
self.assertEqual((self._items(), self._decisions()), before)
|
||||
self.assertEqual(self._pending(), 0)
|
||||
|
||||
async def test_record_review_file_only_clears_what_it_links(self):
|
||||
"""Only scans add items: the monitor's pass skips every unlinked file
|
||||
and settles the items of a linked one."""
|
||||
async def test_record_review_file_queues_what_the_scan_would(self):
|
||||
"""#659: the monitor's pass queues an unlinked file the scan would
|
||||
queue, skips one the scan's fallback would link (linking nothing
|
||||
itself) and settles the items of a linked one."""
|
||||
self._roots()
|
||||
write_png(self.output_dir / "fallback.png", prompt=ambiguous_graph("a", "b"))
|
||||
fallback = self.output_dir / "fallback.png"
|
||||
write_png(fallback, prompt=ambiguous_graph("a", "b"))
|
||||
write_png(self.output_dir / "two.png", prompt=unlinkable_graph("cat", "dog"))
|
||||
linked = self.output_dir / "linked.png"
|
||||
write_png(linked, prompt=unlinkable_graph("cat", "dog"))
|
||||
self._link(linked)
|
||||
|
||||
record = self.api.record_review_file
|
||||
self.assertEqual(record(str(self.output_dir / "fallback.png")), "skipped")
|
||||
self.assertEqual(record(str(fallback)), "skipped")
|
||||
self.assertEqual(self.api.db.review_file_linked((str(fallback),)), False)
|
||||
self.assertEqual(record(str(linked)), "linked")
|
||||
self.assertEqual(record(str(self.output_dir / "two.png")), "skipped")
|
||||
self.assertEqual(self._items(), [])
|
||||
self.assertEqual(record(str(self.output_dir / "two.png")), "recorded")
|
||||
(item,) = self._items()
|
||||
self.assertEqual(os.path.basename(item["locator"]), "two.png")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -233,7 +233,9 @@ class TestDefaultItemsAnchor(InspectionTestCase):
|
||||
evidence = json.loads(item["evidence"])
|
||||
self.assertNotIn("profile", evidence)
|
||||
self.assertNotIn("anchor", evidence)
|
||||
self.assertEqual(item["resolver_version"], review_capture.RESOLVER_VERSION)
|
||||
self.assertEqual(
|
||||
item["resolver_version"], review_capture.default_item_version()
|
||||
)
|
||||
|
||||
async def test_file_the_parser_floor_links_is_not_queued(self):
|
||||
"""Already linked by the default path: unchanged by the anchor."""
|
||||
@@ -276,7 +278,7 @@ class TestDefaultItemsAnchor(InspectionTestCase):
|
||||
with patch.object(review_capture, "_captured_inspection", return_value=None):
|
||||
await self._scan() # queued from the default profile, as before #390
|
||||
(old,) = self._items()
|
||||
self.assertEqual(old["resolver_version"], review_capture.RESOLVER_VERSION)
|
||||
self.assertEqual(old["resolver_version"], review_capture.default_item_version())
|
||||
|
||||
await self._scan("all")
|
||||
|
||||
|
||||
@@ -25,12 +25,14 @@ class TestReadonlyUri(unittest.TestCase):
|
||||
|
||||
def test_no_reader_builds_its_own_uri(self):
|
||||
offenders = []
|
||||
for folder in ("database", "py", "utils"):
|
||||
# #662: the repair and review tools open libraries too.
|
||||
for folder in ("database", "py", "utils", "tools"):
|
||||
for path in (ROOT / folder).rglob("*.py"):
|
||||
if path.name == "sqlite_uri.py":
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8")
|
||||
if re.search(r"as_uri\(\)\s*\+\s*[\"']\?mode=ro", text):
|
||||
# Also ``as_uri() + ("?mode=ro" if ... else "")``.
|
||||
if re.search(r"as_uri\(\)\s*\+\s*\(?\s*[\"']\?mode=ro", text):
|
||||
offenders.append(path.relative_to(ROOT).as_posix())
|
||||
self.assertEqual(offenders, [])
|
||||
|
||||
|
||||
@@ -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.
|
||||
"""
|
||||
|
||||
@@ -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.
|
||||
"""
|
||||
|
||||
+242
-29
@@ -1,9 +1,11 @@
|
||||
"""Synthetic graphs with unknown nodes between the prompt and the sampler (#381).
|
||||
|
||||
``any_switch_graph`` reproduces the shape of the maintainer's krea2 run
|
||||
(PromptManagerPair -> Any Switch (rgthree) -> KSampler, a LoraManager loader
|
||||
with its own lora ``text``, custom latent, filename and saver nodes) with
|
||||
neutral texts. ``shapes()`` names one graph per pass-through rule; the resolver
|
||||
``unknown_multi_graph`` reproduces the shape of the maintainer's krea2 run
|
||||
(PromptManagerPair -> an unknown multi-input node -> KSampler, a LoraManager
|
||||
loader with its own lora ``text``, custom latent, filename and saver nodes) with
|
||||
neutral texts. The krea2 run had rgthree's Any Switch there; the table now
|
||||
describes that class (#657), so the stand-in is ``PMTest Unknown Multi``, a
|
||||
class no table lists. ``shapes()`` names one graph per pass-through rule; the resolver
|
||||
tests and the browser-port parity vectors share them. No user file is involved.
|
||||
"""
|
||||
|
||||
@@ -34,8 +36,8 @@ def pair(text=POSITIVE, negative=""):
|
||||
}
|
||||
|
||||
|
||||
def any_switch_graph(**switch_inputs):
|
||||
"""The shape of #381: PromptManagerPair -> Any Switch (rgthree) -> KSampler.
|
||||
def unknown_multi_graph(**switch_inputs):
|
||||
"""The shape of #381: PromptManagerPair -> an unknown node -> KSampler.
|
||||
|
||||
Classes and links reproduce the maintainer's krea2 run (a LoraManager
|
||||
loader with its own lora ``text``, a project-path filename node, a custom
|
||||
@@ -61,7 +63,7 @@ def any_switch_graph(**switch_inputs):
|
||||
},
|
||||
},
|
||||
"10": pair(),
|
||||
"15": {"class_type": "Any Switch (rgthree)", "inputs": inputs},
|
||||
"15": {"class_type": "PMTest Unknown Multi", "inputs": inputs},
|
||||
"16": {
|
||||
"class_type": "EmptyLatentBatch",
|
||||
"inputs": {"width": 1024, "height": 1536, "batch_size": 1},
|
||||
@@ -105,7 +107,7 @@ def generated_text_graph():
|
||||
The generator (``sampling_mode.seed``, ``prompt``, ``system_prompt``)
|
||||
writes new text at run time: its inputs are not the prompt.
|
||||
"""
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["10"]["inputs"]["text"] = ["30", 0]
|
||||
graph["30"] = {
|
||||
"class_type": "VendorTextGenerate",
|
||||
@@ -123,7 +125,7 @@ def generated_text_graph():
|
||||
|
||||
def transformed_text_graph():
|
||||
"""PromptManagerPair whose ``text`` passes an unknown string transform."""
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["10"]["inputs"]["text"] = ["30", 0]
|
||||
graph["30"] = {
|
||||
"class_type": "VendorRegexReplace",
|
||||
@@ -181,22 +183,24 @@ def shapes():
|
||||
},
|
||||
}
|
||||
return {
|
||||
"any-switch-pair": any_switch_graph(),
|
||||
"any-switch-same-pair": any_switch_graph(any_01=["10", 0], any_02=["10", 0]),
|
||||
"any-switch-equal-texts": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
"unknown-multi-pair": unknown_multi_graph(),
|
||||
"unknown-multi-same-pair": unknown_multi_graph(
|
||||
any_01=["10", 0], any_02=["10", 0]
|
||||
),
|
||||
"unknown-multi-equal-texts": with_nodes(
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
**{"20": encode(OTHER), "21": encode(OTHER)},
|
||||
),
|
||||
"any-switch-candidates": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
"unknown-multi-candidates": with_nodes(
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["21", 0]),
|
||||
**{"20": encode(POSITIVE), "21": encode(OTHER)},
|
||||
),
|
||||
"any-switch-prompt-manager-wins": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
"unknown-multi-prompt-manager-wins": with_nodes(
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["10", 0]),
|
||||
**{"20": encode(OTHER)},
|
||||
),
|
||||
"any-switch-runtime-blocks": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["22", 0]),
|
||||
"unknown-multi-runtime-blocks": with_nodes(
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["22", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
@@ -206,9 +210,9 @@ def shapes():
|
||||
"22": encode(OTHER),
|
||||
},
|
||||
),
|
||||
"any-switch-no-text": any_switch_graph(any_01=["7", 0]),
|
||||
"unknown-multi-no-text": unknown_multi_graph(any_01=["7", 0]),
|
||||
"unknown-chain": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "Router Node (vendor)",
|
||||
@@ -217,7 +221,7 @@ def shapes():
|
||||
},
|
||||
),
|
||||
"unknown-text-input": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorTextEncode",
|
||||
@@ -227,14 +231,14 @@ def shapes():
|
||||
),
|
||||
"unknown-role-inputs": _sampler_inputs(
|
||||
with_nodes(
|
||||
any_switch_graph(),
|
||||
unknown_multi_graph(),
|
||||
**{"20": control, "21": encode(POSITIVE), "22": encode(NEGATIVE)},
|
||||
),
|
||||
["20", 0],
|
||||
["20", 1],
|
||||
),
|
||||
"unknown-conditioning-input": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {
|
||||
"class_type": "VendorStyleApply",
|
||||
@@ -246,7 +250,7 @@ def shapes():
|
||||
"generated-text-runtime": generated_text_graph(),
|
||||
"transformed-text": transformed_text_graph(),
|
||||
"unknown-skips-clip": with_nodes(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": vendor_encode,
|
||||
"21": {"class_type": "PrimitiveString", "inputs": {"value": OTHER}},
|
||||
@@ -263,7 +267,7 @@ def review_shapes():
|
||||
"""Record sets for the review findings on the first #381 commit."""
|
||||
|
||||
def recorded(source):
|
||||
graph = any_switch_graph()
|
||||
graph = unknown_multi_graph()
|
||||
graph["10"]["inputs"]["text"] = ["30", 0]
|
||||
graph.update(source)
|
||||
return {
|
||||
@@ -272,7 +276,7 @@ def review_shapes():
|
||||
}
|
||||
|
||||
seeded = with_nodes(
|
||||
any_switch_graph(any_01=["20", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0]),
|
||||
**{
|
||||
"20": {"class_type": "XNoise", "inputs": {"conditioning": ["21", 0]}},
|
||||
"21": {
|
||||
@@ -281,7 +285,7 @@ def review_shapes():
|
||||
},
|
||||
},
|
||||
)
|
||||
unlinked = any_switch_graph()
|
||||
unlinked = unknown_multi_graph()
|
||||
unlinked["20"] = {
|
||||
"class_type": "XApply",
|
||||
"inputs": {"positive": ["21", 0], "negative_opt": ""},
|
||||
@@ -290,7 +294,7 @@ def review_shapes():
|
||||
unlinked["17"]["inputs"]["positive"] = ["20", 0]
|
||||
unlinked["17"]["inputs"]["negative"] = ["20", 1]
|
||||
twice = with_nodes(
|
||||
any_switch_graph(any_01=["20", 0], any_02=["23", 0]),
|
||||
unknown_multi_graph(any_01=["20", 0], any_02=["23", 0]),
|
||||
**{
|
||||
"20": {"class_type": "XB", "inputs": {"p": ["21", 0], "q": ["22", 0]}},
|
||||
"21": encode(POSITIVE),
|
||||
@@ -319,3 +323,212 @@ def review_shapes():
|
||||
"unlinked-role-input": {"prompt": json.dumps(unlinked)},
|
||||
"one-text-twice": {"prompt": json.dumps(twice)},
|
||||
}
|
||||
|
||||
|
||||
# #657: rgthree Any Switch outputs the first ``any_*`` input that is not None.
|
||||
SWEEP_PREFIX = "<lora:style-demo:1>"
|
||||
|
||||
|
||||
def any_switch_sweep_graph():
|
||||
"""The maintainer's model-compare sweep (2026-11-19), with neutral texts.
|
||||
|
||||
PromptManagerText (12) feeds the switch's ``any_01`` directly and, joined
|
||||
after a LoraManager stacker's trigger text, its ``any_02`` (13). The switch
|
||||
(14) feeds the positive encoder (15) of KSampler 26; the negative is a plain
|
||||
CLIPTextEncode. A checkpoint iterator, a LoRA text loader and a
|
||||
model-compare sheet (all unknown classes) surround it, as in the file.
|
||||
"""
|
||||
return {
|
||||
"4": {"class_type": "SeedHistory", "inputs": {"seed": 1000}},
|
||||
"8": {"class_type": "CLIPLoader", "inputs": {"clip_name": "clip.safetensors"}},
|
||||
"9": {"class_type": "VAELoader", "inputs": {"vae_name": "vae.safetensors"}},
|
||||
"10": {
|
||||
"class_type": "EmptyLatentImage",
|
||||
"inputs": {"width": 1088, "height": 1920, "batch_size": 1},
|
||||
},
|
||||
"11": {
|
||||
"class_type": "Lora Stacker (LoraManager)",
|
||||
"inputs": {
|
||||
"text": SWEEP_PREFIX,
|
||||
"loras": [{"name": "style-demo", "strength": "1.00", "active": True}],
|
||||
},
|
||||
},
|
||||
"12": {
|
||||
"class_type": "PromptManagerText",
|
||||
"inputs": {
|
||||
"text": POSITIVE,
|
||||
"category": "",
|
||||
"tags": "",
|
||||
"search_text": "",
|
||||
"prepend_text": "",
|
||||
"append_text": "",
|
||||
"save_to_library": True,
|
||||
},
|
||||
},
|
||||
"13": {
|
||||
"class_type": "StringConcatenate",
|
||||
"inputs": {"string_a": ["11", 1], "string_b": ["12", 0], "delimiter": ", "},
|
||||
},
|
||||
"14": {
|
||||
"class_type": "Any Switch (rgthree)",
|
||||
"inputs": {"any_01": ["12", 0], "any_02": ["13", 0]},
|
||||
},
|
||||
"15": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": ["14", 0], "clip": ["8", 0]},
|
||||
},
|
||||
"16": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": NEGATIVE, "clip": ["8", 0]},
|
||||
},
|
||||
"21": {
|
||||
"class_type": "CheckpointFolderIterator",
|
||||
"inputs": {"folder": "demo", "index": 1, "model_type": "checkpoint"},
|
||||
},
|
||||
"23": {
|
||||
"class_type": "LoRA Text Loader (LoraManager)",
|
||||
"inputs": {"model": ["21", 0], "lora_syntax": ["11", 2]},
|
||||
},
|
||||
"26": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"seed": ["4", 0],
|
||||
"steps": 25,
|
||||
"cfg": 2.5,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "normal",
|
||||
"denoise": 1.0,
|
||||
"model": ["23", 0],
|
||||
"positive": ["15", 0],
|
||||
"negative": ["16", 0],
|
||||
"latent_image": ["10", 0],
|
||||
},
|
||||
},
|
||||
"27": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {"samples": ["26", 0], "vae": ["9", 0]},
|
||||
},
|
||||
"28": {
|
||||
"class_type": "ModelCompareSheet",
|
||||
"inputs": {"run_name": "sweep", "columns": 3, "images": ["27", 0]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def switched(switch_inputs, **nodes):
|
||||
"""The sweep graph with the switch's inputs replaced and nodes added."""
|
||||
graph = with_nodes(any_switch_sweep_graph(), **nodes)
|
||||
graph["14"] = {"class_type": "Any Switch (rgthree)", "inputs": dict(switch_inputs)}
|
||||
return graph
|
||||
|
||||
|
||||
def _string(text):
|
||||
return {"class_type": "PrimitiveString", "inputs": {"value": text}}
|
||||
|
||||
|
||||
def _vendor(**inputs):
|
||||
"""An unknown node that passes its one linked input through."""
|
||||
return {"class_type": "VendorPassText", "inputs": inputs}
|
||||
|
||||
|
||||
def _reroutes(count, start, target):
|
||||
"""``count`` chained Reroutes ``r{start}..``, the last reading ``target``."""
|
||||
nodes = {}
|
||||
for index in range(count):
|
||||
upstream = target if index == count - 1 else [f"r{start + index + 1}", 0]
|
||||
nodes[f"r{start + index}"] = {
|
||||
"class_type": "Reroute",
|
||||
"inputs": {"input": upstream},
|
||||
}
|
||||
return nodes
|
||||
|
||||
|
||||
def _conditioning_switch(**switch_inputs):
|
||||
"""A switch in the sampler's positive conditioning input (any_* conditioning)."""
|
||||
graph = switched(
|
||||
switch_inputs,
|
||||
**{
|
||||
"40": encode(OTHER),
|
||||
"41": {"class_type": "FluxGuidance", "inputs": {"conditioning": ["40", 0]}},
|
||||
"42": encode(POSITIVE),
|
||||
},
|
||||
)
|
||||
graph["26"]["inputs"]["positive"] = ["14", 0]
|
||||
return graph
|
||||
|
||||
|
||||
def first_present_shapes():
|
||||
"""One named graph per ``first-present`` rule (#657); limits are built in tests."""
|
||||
inner = {
|
||||
"class_type": "Any Switch (rgthree)",
|
||||
"inputs": {"any_01": ["12", 0], "any_02": ["13", 0]},
|
||||
}
|
||||
upstream_selector = {
|
||||
"class_type": "easy ifElse",
|
||||
"inputs": {"boolean": ["81", 0], "on_true": ["31", 0], "on_false": ["12", 0]},
|
||||
}
|
||||
return {
|
||||
"sweep": any_switch_sweep_graph(),
|
||||
"through-reroute": switched(
|
||||
{"any_01": ["30", 0], "any_02": ["13", 0]},
|
||||
**{"30": {"class_type": "Reroute", "inputs": {"input": ["12", 0]}}},
|
||||
),
|
||||
"through-primitive": switched(
|
||||
{"any_01": ["31", 0], "any_02": ["13", 0]}, **{"31": _string(OTHER)}
|
||||
),
|
||||
"through-encoder-chain": _conditioning_switch(
|
||||
any_01=["41", 0], any_02=["42", 0]
|
||||
),
|
||||
"through-unknown": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["13", 0]}, **{"50": _vendor(src=["12", 0])}
|
||||
),
|
||||
"runtime-first": switched(
|
||||
{"any_01": ["60", 0], "any_02": ["12", 0]},
|
||||
**{
|
||||
"60": {
|
||||
"class_type": "VendorTextGenerate",
|
||||
"inputs": {"prompt": "x", "seed": 3},
|
||||
}
|
||||
},
|
||||
),
|
||||
"same-text": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": _vendor(src=["31", 0]),
|
||||
"31": _string(OTHER),
|
||||
"32": _string(OTHER),
|
||||
},
|
||||
),
|
||||
"literal-text": switched({"any_01": "literal words", "any_02": ["12", 0]}),
|
||||
"literal-conditioning": _conditioning_switch(
|
||||
any_01="literal words", any_02=["42", 0]
|
||||
),
|
||||
"one-input-unknown": switched(
|
||||
{"any_01": ["50", 0], "other": ["13", 0]}, **{"50": _vendor(src=["12", 0])}
|
||||
),
|
||||
"no-input": switched({}),
|
||||
"null-first": switched({"any_01": None, "any_02": ["13", 0]}),
|
||||
"selector-upstream": switched(
|
||||
{"any_01": ["80", 0], "any_02": ["13", 0]},
|
||||
**{
|
||||
"80": upstream_selector,
|
||||
"81": {"class_type": "PrimitiveBoolean", "inputs": {"value": True}},
|
||||
"31": _string(OTHER),
|
||||
},
|
||||
),
|
||||
"nested-switch": switched(
|
||||
{"any_01": ["90", 0], "any_02": ["31", 0]},
|
||||
**{"90": inner, "31": _string(OTHER)},
|
||||
),
|
||||
"repeated-text": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["13", 0], "any_03": ["12", 0]},
|
||||
**{"50": _vendor(src=["12", 0])},
|
||||
),
|
||||
"repeated-text-failed-middle": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["missing", 0], "any_03": ["12", 0]},
|
||||
**{"50": _vendor(src=["12", 0])},
|
||||
),
|
||||
"depth-limit": switched(
|
||||
{"any_01": ["r0", 0], "any_02": ["13", 0]}, **_reroutes(70, 0, ["12", 0])
|
||||
),
|
||||
}
|
||||
|
||||
Vendored
+7
-4
@@ -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
@@ -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' }]);
|
||||
});
|
||||
|
||||
|
||||
Vendored
+290
-275
@@ -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,111 @@ 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.
|
||||
// #662: viewerjs-update.yml too, so every workflow is bounded.
|
||||
const BOUNDED_WORKFLOWS = ['ci.yml', 'nightly.yml', 'publish.yml', 'viewerjs-update.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);
|
||||
});
|
||||
|
||||
Vendored
+1
-1
@@ -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\//);
|
||||
|
||||
Vendored
+77
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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())
|
||||
@@ -83,6 +83,7 @@ from database.pair_ingestion import ( # noqa: E402
|
||||
mark_created,
|
||||
)
|
||||
from database.run_attribution import recorded_output # noqa: E402
|
||||
from database.sqlite_uri import readonly_uri # noqa: E402
|
||||
from py.api import PromptManagerAPI # noqa: E402
|
||||
from tools.comfyui_stopped import ( # noqa: E402
|
||||
NO_PROC,
|
||||
@@ -452,8 +453,10 @@ def counts(path, readonly=True):
|
||||
Read-only for a library; the tool's own backup is opened read-write so
|
||||
a WAL file leaves no side files behind once it closes.
|
||||
"""
|
||||
uri = Path(os.path.abspath(path)).as_uri() + ("?mode=ro" if readonly else "")
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
if readonly:
|
||||
conn = sqlite3.connect(readonly_uri(path), uri=True)
|
||||
else:
|
||||
conn = sqlite3.connect(path)
|
||||
try:
|
||||
found = {
|
||||
table: conn.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()[0]
|
||||
@@ -628,8 +631,7 @@ def _stamp():
|
||||
|
||||
def schema_of(path):
|
||||
"""``sqlite_master`` and ``user_version`` from a read-only connection."""
|
||||
uri = Path(os.path.abspath(path)).as_uri() + "?mode=ro"
|
||||
conn = sqlite3.connect(uri, uri=True)
|
||||
conn = sqlite3.connect(readonly_uri(path), uri=True)
|
||||
try:
|
||||
master = conn.execute(
|
||||
"SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name"
|
||||
|
||||
@@ -64,6 +64,7 @@ from database.maintenance import _delete_ids # noqa: E402
|
||||
from database.operations import PromptDatabase # noqa: E402
|
||||
from database.pair_ingestion import blank_positive # noqa: E402
|
||||
from database.run_attribution import stored_run_prompt # noqa: E402
|
||||
from database.sqlite_uri import readonly_uri # noqa: E402
|
||||
from utils.generation_params import ( # noqa: E402
|
||||
PLACEHOLDERS,
|
||||
GenerationParamsError,
|
||||
@@ -253,9 +254,8 @@ def apply(db, verdicts, ids):
|
||||
|
||||
def backup_database(source, target):
|
||||
"""SQLite online backup of ``source`` (opened read-only) into ``target``."""
|
||||
uri = Path(os.path.abspath(source)).as_uri() + "?mode=ro"
|
||||
with (
|
||||
closing(sqlite3.connect(uri, uri=True)) as src,
|
||||
closing(sqlite3.connect(readonly_uri(source), uri=True)) as src,
|
||||
closing(sqlite3.connect(target)) as dst,
|
||||
):
|
||||
src.backup(dst)
|
||||
|
||||
+44
@@ -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`);
|
||||
}
|
||||
}
|
||||
+12
@@ -742,5 +742,17 @@
|
||||
"branches": 60,
|
||||
"functions": 80,
|
||||
"statements": 80
|
||||
},
|
||||
"workspace/inspect-choice.mjs": {
|
||||
"lines": 98,
|
||||
"branches": 92,
|
||||
"functions": 89,
|
||||
"statements": 98
|
||||
},
|
||||
"workspace/review-options.mjs": {
|
||||
"lines": 98,
|
||||
"branches": 98,
|
||||
"functions": 98,
|
||||
"statements": 98
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+9
-2
@@ -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,
|
||||
|
||||
Vendored
+2
-1
@@ -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: [
|
||||
|
||||
@@ -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',
|
||||
|
||||
Vendored
+5
-2
@@ -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}` }]];
|
||||
}
|
||||
|
||||
@@ -33,19 +33,25 @@ from pathlib import Path
|
||||
_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load_documents():
|
||||
"""``database/workflow_documents.py`` alone, without the ``database`` package."""
|
||||
path = _ROOT / "database" / "workflow_documents.py"
|
||||
spec = importlib.util.spec_from_file_location("_pm_workflow_documents", path)
|
||||
def _load_database_module(name):
|
||||
"""``database/<name>.py`` alone, without the ``database`` package."""
|
||||
path = _ROOT / "database" / f"{name}.py"
|
||||
spec = importlib.util.spec_from_file_location(f"_pm_{name}", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _load_documents():
|
||||
"""``database/workflow_documents.py`` alone, without the ``database`` package."""
|
||||
return _load_database_module("workflow_documents")
|
||||
|
||||
|
||||
def database_uri(db_path):
|
||||
"""``mode=ro``, plus ``immutable=1`` when nothing has the database open."""
|
||||
path = os.path.abspath(db_path)
|
||||
uri = Path(path).as_uri() + "?mode=ro"
|
||||
# #662: the one read-only URI helper, so a library on a network share opens.
|
||||
uri = _load_database_module("sqlite_uri").readonly_uri(path)
|
||||
if not any(os.path.exists(path + suffix) for suffix in ("-wal", "-shm")):
|
||||
uri += "&immutable=1"
|
||||
return uri
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""ComfyUI's EXIF metadata records (WebP, AVIF, JPEG).
|
||||
|
||||
PNG keeps the workflow and the prompt in text chunks (``utils.png_text``).
|
||||
The formats without text chunks carry the same records as EXIF strings:
|
||||
``SaveAnimatedWEBP`` writes ``prompt:{json}`` to tag 0x0110, then
|
||||
``workflow:{json}`` and every other ``extra_pnginfo`` key to 0x010F and down,
|
||||
and the AVIF writer uses that layout too. Pillow answers those tags only
|
||||
through ``getexif()``; ``image.info`` holds the raw EXIF blob, so reading it
|
||||
as text found no metadata at all.
|
||||
|
||||
``exif_text`` returns the ``{key: json}`` shape of ``utils.png_text`` so a
|
||||
caller reads either source the same way. Only a value shaped like a ComfyUI
|
||||
record counts, a key and a colon followed by a JSON object, array or string;
|
||||
a camera's ``Make`` or a ``DateTime`` is not metadata.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# A record's key: ``workflow``, ``prompt`` or an extra_pnginfo key.
|
||||
_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
||||
# What a record holds: the workflow and the prompt are objects, the pair
|
||||
# records a list, a custom extra_pnginfo value may be a string. Numbers,
|
||||
# dates and camera names start with anything else.
|
||||
_STARTS = ("{", "[", '"')
|
||||
|
||||
|
||||
def exif_text(image) -> dict:
|
||||
"""ComfyUI's EXIF records of an opened image, or ``{}``.
|
||||
|
||||
The image stays usable and nothing is decoded but the EXIF block. Formats
|
||||
whose records are text chunks (PNG) answer ``{}``; read those with
|
||||
``utils.png_text.png_text`` first.
|
||||
"""
|
||||
try:
|
||||
exif = image.getexif()
|
||||
except Exception: # a broken EXIF block never fails a scan
|
||||
return {}
|
||||
records = {}
|
||||
for value in exif.values():
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8", errors="replace")
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
key, separator, payload = value.partition(":")
|
||||
if separator and _KEY.match(key) and payload.lstrip()[:1] in _STARTS:
|
||||
records[key] = payload
|
||||
return records
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user