Compare commits

...
Author SHA1 Message Date
Vito d4101f64cb Merge branch 'main' into fix/662-small-cleanup 2026-11-21 09:34:51 -08:00
Vito Sansevero 693b030d5d Merge origin/main into fix/662-small-cleanup (#662)
Takes main's CI rebuild (#667): publish.yml was already bounded, so only
the viewerjs-update.yml limit remains from this branch, written as an
estimate line in the new style and checked by the new guard.
2026-11-21 08:37:32 -08:00
Vito Sansevero df1b93c01f docs: correct the redesign plan's CI and PR rules, renumber the second D205 (#662)
docs/application-redesign.md named a Python 3.10-3.13 matrix with macOS,
asked for PR screenshots and said Overview links the legacy metadata
page. It now names the 3.12 floor and the current Linux/Windows split,
asks for visual changes in words, and says the metadata page is reached
by address or from the legacy admin page. TESTING.md used D205 for both
#431 (saved instructions) and #620 (Library sorts); #620's entry is
D206 now.
2026-11-21 05:20:53 -08:00
Vito Sansevero 11e363352b ci: bound the publish and Viewer.js update jobs by measured limits (#662)
publish.yml and viewerjs-update.yml had no timeout-minutes, and the
workflow guard listed only four workflows. The guard now reads every
workflow and recomputes both new limits from their comments: publish
5 min from its last three green runs; the Viewer.js update 18 min, from
an estimate of its never-run update path (the three measured nightly
runs found no release and give the 5-minute floor).
2026-11-21 05:19:53 -08:00
Vito Sansevero 88fa7cc473 fix(tools): open libraries through the shared read-only URI helper (#662)
review_image_links, repair_foreign_links (twice) and workflow_text_digests
built their own file: URIs, which SQLite refuses for a library on a
Windows network share (file://server/share/...). They now use
database/sqlite_uri.readonly_uri; repair_foreign_links opens its own
read-write backup by path. The guard in tests/test_sqlite_uri.py scans
tools/ too and also catches a conditional ?mode=ro suffix.
2026-11-21 05:16:49 -08:00
Vito Sansevero 9b44c56264 refactor: remove the write-only preview batch count and the test-only node search (#662)
AutoThumbnailWorker set self._batch in four places and never read it.
PromptManagerBase._search_prompts had no caller but its own tests: the
node UIs search through GET /prompt_manager/search. Prompt search itself
stays covered by the database and route tests.
2026-11-21 05:15:53 -08:00
Vito Sansevero a28923b9c6 refactor(inspect): both resolvers read PROVEN_VALUE_CATEGORIES (#662)
proves_value hard-coded the four tables in Python and in the browser.
Semantics.proves_value now reads the constant (class-keyed categories by
class, the rest by output slot), the browser resolver loops over its
mirrored copy in local-resolver-support.mjs, and
tests/test_proven_value_parity.py fails when that copy drifts. A test
patches the constant to show the resolver follows it.
2026-11-21 05:15:20 -08:00
Vito Sansevero 9677400f32 fix(api): refuse malformed bodies on the legacy prompt routes with a 400 (#662)
PUT /prompts/{id}, PUT /prompts/{id}/rating, POST and DELETE
/prompts/{id}/tags, POST /prompts/tags, PUT /tags/{tag}, POST /tags/merge
and POST /bulk/delete|tags|category read the body with the bounded JSON
reader /save uses and check field types, so a body that is not a JSON
object, or a field such as {"text": 123}, is a 400 instead of a 500.
A prompt id may still be a number or its text, as the legacy page sends
it; a boolean is refused (prompt_ids [true] deleted prompt 1).
POST /jobs/image-tags refuses a mode that is no text instead of a 500.
2026-11-21 05:12:32 -08:00
Vito Sansevero 3d2c449361 refactor(api): one bounded JSON body reader for the API and images.py (#662)
images.py kept its own copy of the chunked, capped JSON object reader.
Both now use py/api/json_body.py; images.py keeps its 1 MiB cap and its
raising form for the thumbnail job.
2026-11-21 05:10:32 -08:00
26 changed files with 416 additions and 197 deletions
+9
View File
@@ -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
+4 -3
View File
@@ -297,7 +297,8 @@ 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 `ci.yml`, `nightly.yml` and `publish.yml` has `timeout-minutes`.
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
@@ -1022,7 +1023,7 @@ 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. 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
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`
@@ -4794,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
+8 -6
View File
@@ -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.
+1 -35
View File
@@ -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:
+5 -39
View File
@@ -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
@@ -214,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 ────────────────────────────────────────
+2 -1
View File
@@ -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"}
+7 -26
View File
@@ -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,
@@ -549,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).
@@ -718,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):
+60
View 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
View File
@@ -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:
-4
View File
@@ -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
View 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.
+96
View File
@@ -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):
+3
View File
@@ -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": {}},
+26
View File
@@ -618,6 +618,32 @@ class ValidationTest(_TableCase):
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()
-12
View File
@@ -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"):
+11
View File
@@ -1735,6 +1735,17 @@ class TestFirstPresentSelector(unittest.TestCase):
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")
+57
View File
@@ -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()
+4 -2
View File
@@ -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, [])
+2 -1
View File
@@ -458,7 +458,8 @@ test('nightly reports by issue after every other job, with the only write permis
// runs and times written above jobs: as "<job id>: 7m26s / 7m22s / 7m54s -> 15 min". A job without
// three green runs yet has "estimate <job id>: <why> -> N min" instead. That the runs were green is
// the author's word; that every job has one line and uses its limit is checked here.
const BOUNDED_WORKFLOWS = ['ci.yml', 'nightly.yml', 'publish.yml'];
// #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) {
+6 -4
View File
@@ -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"
+2 -2
View File
@@ -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)
+11 -5
View File
@@ -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
+12
View File
@@ -156,6 +156,18 @@ class Semantics:
# The canonical table JSON itself, for ``class_version``.
source: str = ""
def proves_value(self, name: str, slot: int) -> bool:
"""Whether a ``PROVEN_VALUE_CATEGORIES`` table lists this output (#657).
Class-keyed categories match by class, slot-keyed ones by
``(class, slot)``.
"""
return any(
(name if category in _CLASS_CATEGORIES else (name, slot))
in getattr(self, category)
for category in PROVEN_VALUE_CATEGORIES
)
def _freeze(value: Any) -> Frozen:
if isinstance(value, dict):
+4 -15
View File
@@ -1063,28 +1063,17 @@ class _GraphResolver:
"""Whether every node on a followed path always outputs a value (#657).
PromptManager and code-traced classes, the default adapters and the
table's ``PROVEN_VALUE_CATEGORIES``; class-keyed sets by class, slot-keyed
ones by ``(class, output slot)``.
table's ``PROVEN_VALUE_CATEGORIES`` (``Semantics.proves_value``).
"""
self.scan(len(path))
semantics = self.semantics
for step in path:
name, slot = self.node(step["node_id"])[0], step["output_slot"]
if name in _OWN_CLASSES or name in _CODED_CLASSES:
continue
if name in semantics.composites:
if (name, slot) in _DEFAULT_ADAPTERS:
continue
output = (name, slot)
if output in _DEFAULT_ADAPTERS or any(
output in table
for table in (
semantics.encoders,
semantics.strings,
semantics.conditioning,
)
):
continue
return False
if not self.semantics.proves_value(name, slot):
return False
return True
def owned(self, path: list) -> bool:
@@ -38,6 +38,10 @@ export const PASS_THROUGH = 'pass-through';
// #657: the divergence tag of a `first-present` switch (rgthree Any Switch), apart from selector and pass-through keys.
export const FIRST_PRESENT = 'first-present';
export const NO_SWITCH_INPUT = 'Switch has no connected input';
// `PROVEN_VALUE_CATEGORIES` (inspection_semantics.py): tables whose outputs always hold a value (#657); class-keyed ones
// match by class, the rest by output slot. tests/test_proven_value_parity.py checks both against the server (#662).
export const PROVEN_VALUE_CATEGORIES = Object.freeze(['composites', 'conditioning', 'encoders', 'strings']);
export const PROVEN_BY_CLASS = new Set(['composites']);
export const SWITCH_UNVERIFIABLE = 'Switch output is not verifiable';
// `_NAME_LENGTH` (inspection_semantics.py), in code points.
export const NAME_LENGTH = 128;
+5 -3
View File
@@ -36,6 +36,8 @@ import {
PASSED_UNVERIFIABLE,
OVERWRITTEN_PROMPT_REASON,
PROFILE,
PROVEN_BY_CLASS,
PROVEN_VALUE_CATEGORIES,
ROLE_METADATA_KEYS,
RUNTIME_REASON,
SAMPLER_LIKE_INPUTS,
@@ -475,15 +477,15 @@ class GraphResolver {
/**
* `proves_value` (#657): every node on the path always outputs a value: own, coded and adapter classes, and the
* table's `PROVEN_VALUE_CATEGORIES` (inspection_semantics.py: composites by class, the rest by output slot).
* table's `PROVEN_VALUE_CATEGORIES` (`Semantics.proves_value`: `PROVEN_BY_CLASS` by class, the rest by output slot).
*/
provesValue(path) {
this.scan(path.length);
const semantics = this.semantics;
return path.every(step => {
const name = this.node(step.node_id)[0], key = slotKey(name, step.output_slot);
if (OWN_CLASSES.has(name) || CODED_CLASSES.includes(name) || semantics.composites.has(name)) return true;
return ADAPTERS.has(key) || semantics.encoders.has(key) || semantics.strings.has(key) || semantics.conditioning.has(key);
if (OWN_CLASSES.has(name) || CODED_CLASSES.includes(name) || ADAPTERS.has(key)) return true;
return PROVEN_VALUE_CATEGORIES.some(category => semantics[category].has(PROVEN_BY_CLASS.has(category) ? name : key));
});
}