* test(inspect): use a neutral unknown class in the pass-through fixtures The #381 fixtures used rgthree's Any Switch as their example of an unknown node. The table is about to describe that class (#657), so the stand-in becomes PMTest Unknown Multi and any_switch_graph becomes unknown_multi_graph. Resolver results are unchanged. * feat(inspect): resolve rgthree Any Switch by its first proven input (#657) rgthree's Any Switch outputs the first any_* input that is not None. The inspection resolver treated it as an unknown node, so the model-compare sweep (PromptManagerText into any_01, the same text joined after a LoRA trigger into any_02) was ambiguous in Inspect. The table gains a first-present selector strategy and lists the switch under it. The resolver takes the first participating input when it is a literal or its traced path proves a value (every node is a PromptManager, code-traced, default-adapter or encoders/strings/conditioning/composites class). Otherwise each input is one choice, unless all of them trace to one text; limits and upstream divergences propagate, and no PromptManager path is preferred. A missing or null input does not take part. The browser resolver and its table compiler follow the same rules, with the same strict entry check as the server. Only graphs holding the class change their class projection, so only their pending inspection items move; INSPECTION_RESOLVER_VERSION stays 2. * fix(inspect): list a repeated Any Switch outcome once (#657) A switch with three or more inputs can offer one text through two of them (a, b, a). Each input was its own candidate, so one text read as a choice between two, and two equal resolved candidates beside a failed one would count as reviewable. Like an unknown node passing several texts, a first-present divergence now collapses equal outcomes. The browser resolver does the same. The table compiler test also checks the 128-character prefix bound in code points, as Python counts it. * feat(inspect): show a role every candidate shares (#658) An ambiguous file used to withhold both roles, even when every candidate had the same negative. Inspect now judges each role on its own: a role is shown resolved when every candidate is resolved with the same text, stored recipe and left-out parts for it, using the first candidate's text and source. A role that differs, or any unresolved candidate, keeps the ambiguous line, and resolution.state stays ambiguous, so Send pair, ingestion and Needs review behave as before. The browser-local resolver applies the same rule; the footer Send to ComfyUI still needs both roles. A multistage detailer run whose stages share one negative (fixture f19) now shows that negative. * feat(monitor): ask the ladder for PromptManager runs nothing else links A PromptManager output whose metadata and tracked run cannot name its prompt now takes the ladder path foreign outputs use: decided at settle under the monitor policy, or after its run is sealed through the ladder wait. Wait entries carry their run kind; the kind selects the settings gate (SAVE_FOREIGN_RUNS for foreign entries, MONITORING_ENABLED for PromptManager ones) and the marks of a created prompt. Keyless images, placeholder batch entries and unreadable metadata never enter the wait. Every final unlinked outcome hands the file to the review recorder. Refs #659 * test(monitor): pin the final unlinked outcomes that reach Needs review The sweep, joined-text and shared-prefix graphs move to a shared fixture module. New tests pin when the monitor hands a file to its review recorder: after the sealed re-check, a settle lookup that found the run's record, a file outside ComfyUI's output folder and the keyless re-check; never before the run is sealed, and never for a linked file. A PromptManager output waiting for its run now logs that at INFO. Refs #659 * feat(review): offer inspection choices for default-unresolved files Decision.default_unresolved marks a file the default profile itself calls unresolved (a blank positive does not count). With inspection on, record_ambiguous_file now sends such a captured file with a prompt graph straight to the inspection-profile branch: a reviewable ambiguous or saver-anchored result is recorded, anything else is untraced. Apply is unchanged; it re-resolves with the item's recorded profile. Refs #659 * feat(review): one review dispatch and a review worker for monitor outputs review_dispatch holds the scan's per-file Needs review decision and is now also used by the monitor. The scan replaces its inline dispatch with it (and offers default-unresolved files their inspection choices). record_review_file runs the scan's per-file steps for one file, read only: the scan-policy ladder with the sealed history and the recorded-run check. A file the scan would link is skipped; otherwise the dispatch's record outcome is the answer. The monitor queues paths through queue_review_file onto one daemon worker (pm-review-recorder) with a bounded queue that coalesces by path and a bounded deferred set it replays once no job blocker remains. The package teardown stops it right after the monitor and reports it as part review once started. Refs #659 * docs(testing): the monitor queues what the scan would (#659) Rewrite the Needs review paragraph for the 2026-11-19 decision: the final-outcome points, the review worker and its bounds, the deferred replay and the default-unresolved rule. Document the PromptManager-run ladder path, the review step of the package teardown and the proven-value allowlist every future semantics table entry must keep. Refs #659 * fix(review): lock the untraced memory the scan and review worker share Refs #659 * feat(inspect): name the file's Needs review item in the inspection responses Inspect and the run-history current-file inspection gain a review field: {"state": "pending", "item_id": ...} for the newest pending item at the stat the inspection took, {"state": "decided"} once its item was decided, and null otherwise. It is read only when a role is ambiguous and the file is unlinked, by locator and stat (review_item_at), so Inspect never hashes the file. A LoRA root, a failed read and any malformed value give null. Refs #659 * feat(review): a single-item mode for the review controller and a shared option list createReviewController({api, itemId}) holds one named item: it never reads the queue, loads that item's detail, ends in phase decided (decided: true) after a recorded decision or for an item already decided, and re-reads the detail after a review-conflict, review-missing or restore refusal. The queue mode is unchanged. The Sampler context option list moves into renderReviewOptions (review-options.mjs, re-exported by review.mjs), so Needs review and the Inspect picker render the same options without Inspect importing the Needs review page. Refs #659 * feat(inspect): choose the prompt of an ambiguous file in Inspect When the inspection names the file's pending Needs review item, the inspector shows a Choose prompt section after its prompt blocks (Images panel, viewer details, recorded run current file). It reads the item's detail through the review controller's single-item mode: one Sampler context option per candidate (unusable ones disabled with their reason), the chosen option's prompt blocks with Copy and Send, Use this prompt and Leave unresolved over the Needs review apply flow. A recorded decision shows Needs review's toast and re-reads the inspection, so the file shows its link; an item with nothing to choose offers Open in Needs review. Refs #659 * fix(inspect): read the history review item only when Inspect asks The run-history reader locates the file under the scan roots inside the read, so an unambiguous or linked file costs no realpath of the output folders. The docstring names the linked-subfolder limit, and the newest pending item test pins the rowid tie-break. Refs #659 * fix(inspect): end Choose prompt on another read and on a decision made elsewhere The inspector disposes the section when it reads another file, fails or defers, so a decision in flight never re-reads the next file. A decided item hides the section and re-reads the inspection once, also when it was decided in another tab or in Needs review. Refs #659 * test(inspect): the rooted inspect shape gains the review facet Refs #659 * docs(testing): first-present candidates and per-role results (#657, #658) * test(review): keep the review cases ambiguous now that Any Switch resolves Part 1 resolves rgthree's Any Switch, so the sweep fixture links. The review and monitor tests that need a default-unresolved, inspection-ambiguous file now use ambiguous_sweep_graph(): Part A's any_switch_sweep_graph() with its switch class replaced by the never-listed PMTest Unknown Multi (one sweep graph instead of two). A new test pins that the real sweep links at settle from the inspector. Refs #657 #659 * fix(review): start the review worker again after an unexpected error * fix(inspect): pass the inspection refresh to Choose prompt by reference * feat(review): queue an ambiguous file with one readable choice (#657) An ambiguous result is reviewable when at least one candidate carries a resolved prompt (MIN_CHOOSABLE = 1). The sweep with an LLM enhancer on Any Switch any_01 now records an item, by the scan and the monitor, with the run-time branch listed beside the readable one. A file with no choosable candidate still records nothing. * feat(review): collapse too many candidates into the most used prompts (#657) More than 16 distinct candidates no longer make a limited item without choices. The choosable ones are grouped by their positive and negative texts, ordered by group size then first appearance, and the first 16 are kept, one real candidate each. The evidence names collapsed: {shown, total, paths} and the item detail returns it. Limited stays for evidence that cannot be projected or is over 8 MiB. REVIEW_EVIDENCE_VERSION is folded into every item version (default items now carry RESOLVER_VERSION + 1, inspection items fold it into their seed), so the next scan supersedes pending, undecided items of the old shape; decided items are kept. RESOLVER_VERSION, the ingestion's provenance version, is unchanged. * feat(inspect): record the Needs review item when Inspect finds none (#657) When Inspect asks for the review facet (an ambiguous role, an unlinked file under an output root) and no item exists at the inspected stat, the images and History current-file inspections run record_review_file, the review worker's own per-file path, in the executor and read the item again. A file the scan would link or that offers nothing to choose records nothing; a deferred or failed recording leaves review null and a failure is logged, never failing the response. * docs(testing): one readable choice, collapsed candidates, Inspect records (#657) * feat(review): say when a file's prompts were shortened to the most used (#657) The item detail now passes the stored evidence's optional `collapsed` counts ({shown, total, paths}) through to the page, null when absent, malformed, or when the detail was capped for size. Needs review and Inspect's Choose prompt show one line under Sampler context: "Showing the n most used of t prompts in this file." * feat(review): list the image's own prompts first in Link to a prompt (#657) With an empty search the dialog now lists the item's choosable candidates under "From this image" (positive / negative, one per prompt pair), then the Library's prompts under "Library". Choosing one of the image's prompts and pressing Link image applies that candidate by its hash, the same decision as Apply association (new controller.applyCandidate); no negative is asked for, the candidate carries its own. Typing searches the Library only. Items with no choosable candidate show the dialog as before. A refusal stays in the dialog with the server's sentence. * feat(review): load more of the queue on scroll (#657) The Needs review continuation now works like the Images page: an IntersectionObserver (250 px ahead) loads the next page when the end of the queue scrolls into view, and the line reads "40 of 45 images · more load as you scroll" without a button. Nothing loads behind an open dialog or the viewer; when one closes, focus returning to the page checks again. A failed page shows the failure line and a Retry button. Without IntersectionObserver the Load more images button stays. * fix(review): ask the inspection profile when the default choice is partial (#657) With one readable choice enough, a default result with one choice beside unresolved branches was recorded as is, so the inspection profile, which may read those branches (a Qwen image-edit sampler), was never asked and a rescan replaced older inspection items with the poorer default ones. Such a partial result now yields to the inspection result when that offers more choosable candidates. * fix(review): collapse only too many prompts, and apply any offered one (#657) Collapsing triggered on more than 16 distinct candidates, sampler ids included, so twenty samplers sharing three texts lost their run-time branches behind a collapsed note. Now only more than 16 choosable texts collapse; otherwise one candidate per text is kept and the branches without a prompt fill the remaining places, as an ordinary item. Apply's still-offered check compared the chosen hash with a fresh collapse, so a reorder that changed the representatives refused Apply. It now checks every projected, de-duplicated candidate hash (candidate_hashes). * fix(inspect): keep Inspect's recording quiet, bounded and current (#657) A busy capture store (the worker copying a fresh output) is an expected outcome: Inspect logs it at debug level and reads the item once more, also after a failed recording. A file Inspect found unrecordable (the scan would link it, or it offers nothing to choose) is remembered by its locator, stat and review versions, at most 4,096 files, so a repeated Inspect does not copy it again. A pending item of an older item version is recorded again, so the current record supersedes it. * docs(testing): partial default choices, bounded candidates, Inspect recording (#657) * fix(review): Link to a prompt drops an image choice it no longer shows (#657) Typing in the search box hid the "From this image" list but kept its chosen prompt, so Link image applied a candidate the reviewer could no longer see. Typing now drops that choice; Link image waits for a Library prompt and sends a Library link. Emptying the box lists the image's prompts again, none chosen. When the item's detail is read again while the dialog is open, the list follows what it offers now; a chosen prompt no longer offered is dropped with "This prompt is no longer offered for this file. Choose again." applyCandidate says the same when the hash cannot be chosen, and an unanswered apply from the dialog asks to press Link image again. * fix(review): keep the panel in place when Info brings it into view at one column (#657) At one column, Info scrolls the panel into view past the queue, which could bring the continuation into view and load the next page, pushing the panel away. As on the Images page, loading now waits for the reader's next wheel, touch move or key press. * docs(review): say why the review worker's recorder is a lambda * test(review): open the dialog of the D5 dialog test beside the queue (#657) At one column (touch) the review panel follows the queue just above the continuation, so scrolling Link to a prompt… into view brings the continuation within the observer's 250 px margin. The next page then loads before the dialog opens whenever the observer's callback runs first (CI shard 4/4, touch), and the test found no continuation to scroll to. That load is the page working as designed: the reader has reached the end of the queue. The test is about loading behind an open dialog, so it now runs at two columns, where Link sits in the sticky panel beside the queue, and it checks that the continuation is out of range before the dialog opens.
651 lines
27 KiB
Python
651 lines
27 KiB
Python
"""Load and validate the declarative inspection node semantics table (#240).
|
|
|
|
The table lives once in ``web/js/inspection-semantics.json`` so a browser-local
|
|
resolver can load the same data. It maps node classes (or ``(class, output
|
|
slot)`` pairs) to a named strategy from the closed ``STRATEGIES`` set plus the
|
|
exact input names that strategy reads. Code implements each strategy; adding a
|
|
node that reuses one is a data-only change.
|
|
|
|
Only the inspection resolver profile consumes this table, through
|
|
``get_semantics()``, which reads and validates it on first use and caches only a
|
|
valid result. Importing this module reads nothing, and the default (ingestion)
|
|
profile never imports it, so a missing or bad table can never break ingestion.
|
|
An invalid table raises ``SemanticsError`` so a bad edit fails loudly instead of
|
|
silently changing what the inspector resolves. The file is bounded in size and
|
|
nesting before it is validated. Every class appears in exactly one prompt
|
|
category; an unlisted output of a listed class stays ``unsupported-node``. ``lineage``
|
|
(image and latent pass-through outputs for multi-stage chains) describes no
|
|
prompt, so its classes are not claimed by a category.
|
|
|
|
``Semantics.version`` is the SHA-256 of the table's canonical JSON (sorted
|
|
keys, no whitespace): any change of content, never of layout, moves it.
|
|
``class_version(doc, classes)`` is the narrower fingerprint Needs review
|
|
folds into the version of the items it records from the inspection profile
|
|
(``utils.review_capture``): the SHA-256 of ``class_projection``, the table
|
|
restricted to what it says about ``classes`` (the node classes of one graph)
|
|
plus the class-independent ``schema``, ``stage_inputs`` and ``pass_through``.
|
|
The resolver looks the table up only by the class of a graph node, so an edit
|
|
about other classes cannot change how that graph resolves and leaves the
|
|
version alone. A class the table does not list at all passes text through
|
|
(#381); that rule lives in code, so ``INSPECTION_RESOLVER_VERSION`` moves for it.
|
|
``pass_through.skip_inputs`` names the core type inputs (model, clip, image,
|
|
...) such a node's text is never read through.
|
|
|
|
A ``first-present`` selector (rgthree Any Switch, #657) outputs the first of its
|
|
``input_prefix`` inputs that holds a value. The resolver can only take that
|
|
input when its traced path proves a value: every node on it is a PromptManager
|
|
class, a class traced by code, or listed in one of ``PROVEN_VALUE_CATEGORIES``.
|
|
That makes a rule for every entry added to those categories: its output is
|
|
never None. Selectors (Any Switch returns None when every input is None),
|
|
``runtime``, ``facts`` and ``lineage`` classes do not prove a value.
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
from dataclasses import dataclass, replace
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
from types import MappingProxyType
|
|
from typing import Any, Callable, Dict, FrozenSet, Mapping, Optional, Tuple, Union
|
|
|
|
SEMANTICS_PATH = (
|
|
Path(__file__).resolve().parents[1] / "web" / "js" / "inspection-semantics.json"
|
|
)
|
|
SCHEMA_VERSION = 1
|
|
# The real table is a few KiB and four levels deep; these only reject nonsense.
|
|
MAX_TABLE_BYTES = 1024 * 1024
|
|
MAX_NESTING = 8
|
|
_NAME_LENGTH = 128
|
|
# Comfy output slots are small; this only rejects nonsense, never a real node.
|
|
_MAX_SLOT = 255
|
|
|
|
STRATEGIES: Mapping[str, FrozenSet[str]] = MappingProxyType(
|
|
{
|
|
"samplers": frozenset({"ksampler", "custom-advanced", "detailer-stage"}),
|
|
"guiders": frozenset({"cfg", "basic"}),
|
|
"conditioning": frozenset({"passthrough", "zeroed"}),
|
|
"selectors": frozenset({"boolean-select", "first-present"}),
|
|
"composites": frozenset({"combine"}),
|
|
"encoders": frozenset({"single", "parts-equal", "pm-compose", "flag-parts"}),
|
|
"strings": frozenset({"literal", "strip-newlines", "join-multi", "concat"}),
|
|
"savers": frozenset({"comfy-counter", "vhs-counter"}),
|
|
"lineage": frozenset({"continue"}),
|
|
}
|
|
)
|
|
# Categories whose outputs are never None (#657): a path through only these,
|
|
# PromptManager and code-traced classes proves that a switch input held a value.
|
|
PROVEN_VALUE_CATEGORIES = frozenset(
|
|
{"encoders", "strings", "conditioning", "composites"}
|
|
)
|
|
# Shapes of the facts each sampler class provides (consumed by comfy-metadata.js).
|
|
FACT_SHAPES = frozenset({"ksampler", "custom", "custom-advanced"})
|
|
SAVER_PATTERNS = MappingProxyType(
|
|
{
|
|
"comfy-counter": "{name}_{counter:05}_.{ext}",
|
|
"vhs-counter": "{name}_{counter:05}.{ext}",
|
|
}
|
|
)
|
|
_SAMPLER_OPTIONS = frozenset({"prompt_overrides", "fact_overrides"})
|
|
_CONFIGURATION_KINDS = frozenset({"noise", "sampler", "sigmas", "guider"})
|
|
_SCALAR_KINDS = frozenset({"number", "string"})
|
|
_TYPE_FIELDS = frozenset({"type_fields"})
|
|
_CLASS_CATEGORIES = ("samplers", "guiders", "selectors", "composites", "savers")
|
|
_SLOT_CATEGORIES = ("conditioning", "encoders", "strings")
|
|
_SET_CATEGORIES = ("runtime", "non_file_outputs")
|
|
_FACTS_TABLES = (
|
|
"configuration_outputs",
|
|
"model_outputs",
|
|
"model_passthroughs",
|
|
"scalar_outputs",
|
|
)
|
|
_CATEGORIES = frozenset(
|
|
("schema",)
|
|
+ _CLASS_CATEGORIES
|
|
+ _SLOT_CATEGORIES
|
|
+ _SET_CATEGORIES
|
|
+ ("lineage", "stage_inputs", "pass_through", "facts")
|
|
)
|
|
# Input names that make an unlisted node a possible sampler stage in an ancestry
|
|
# walk (``shaped``: pipes, video embeds and custom-sampler parts carry a prompt
|
|
# without a ``positive`` link), and those that do so beside a linked ``model``
|
|
# (``with_model``: XlabsSampler's ``conditioning``, video samplers' ``samples``).
|
|
# ``model`` alone (ModelSampling*) or with ``clip`` (LoraLoader) is a model patch.
|
|
# The resolver and comfy-metadata.js both read these lists.
|
|
_STAGE_INPUT_LISTS = ("shaped", "with_model")
|
|
# Inputs of core ComfyUI types (model, clip, image, ...) that an unknown node's
|
|
# output is never read through when the resolver passes text through it (#381):
|
|
# a loader's lora tag reached through ``clip`` is not the prompt.
|
|
_PASS_THROUGH_KEYS = ("skip_inputs",)
|
|
_STRING_PARAMS = MappingProxyType(
|
|
{
|
|
"literal": frozenset(),
|
|
"concat": frozenset(),
|
|
"strip-newlines": frozenset({"flag"}),
|
|
"join-multi": frozenset({"count", "delimiter", "list_flag", "input_prefix"}),
|
|
}
|
|
)
|
|
|
|
Frozen = Union[Mapping[str, Any], Tuple[Any, ...], str, int, None]
|
|
|
|
|
|
class SemanticsError(ValueError):
|
|
"""The semantics table is unreadable or violates its schema."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Semantics:
|
|
"""Validated, deeply frozen semantics. Slot categories key by ``(class, slot)``."""
|
|
|
|
samplers: Mapping[str, Mapping[str, Any]]
|
|
guiders: Mapping[str, Mapping[str, Any]]
|
|
conditioning: Mapping[Tuple[str, int], Mapping[str, Any]]
|
|
selectors: Mapping[str, Mapping[str, Any]]
|
|
composites: Mapping[str, Mapping[str, Any]]
|
|
encoders: Mapping[Tuple[str, int], Mapping[str, Any]]
|
|
strings: Mapping[Tuple[str, int], Mapping[str, Any]]
|
|
runtime: FrozenSet[str]
|
|
savers: Mapping[str, Mapping[str, Any]]
|
|
non_file_outputs: FrozenSet[str]
|
|
lineage: Mapping[Tuple[str, int], Mapping[str, Any]]
|
|
stage_inputs: Mapping[str, Tuple[str, ...]]
|
|
pass_through: Mapping[str, Tuple[str, ...]]
|
|
facts: Mapping[str, Any]
|
|
all_classes: FrozenSet[str]
|
|
# SHA-256 of the canonical table JSON (set by ``load_semantics``).
|
|
version: str = ""
|
|
# The canonical table JSON itself, for ``class_version``.
|
|
source: str = ""
|
|
|
|
|
|
def _freeze(value: Any) -> Frozen:
|
|
if isinstance(value, dict):
|
|
return MappingProxyType({key: _freeze(item) for key, item in value.items()})
|
|
if isinstance(value, list):
|
|
return tuple(_freeze(item) for item in value)
|
|
return value
|
|
|
|
|
|
def _reject_duplicate_keys(pairs: list) -> dict:
|
|
result: Dict[str, Any] = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
raise SemanticsError(f"duplicate key {key!r}")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def _reject_constant(name: str) -> None:
|
|
raise SemanticsError(f"non-finite number {name} is not allowed")
|
|
|
|
|
|
def _name(value: Any, where: str, what: str = "input") -> str:
|
|
if not isinstance(value, str) or not value or len(value) > _NAME_LENGTH:
|
|
raise SemanticsError(f"{where}: missing or invalid {what} name {value!r}")
|
|
return value
|
|
|
|
|
|
def _names(value: Any, where: str, minimum: int = 1) -> None:
|
|
if not isinstance(value, list) or len(value) < minimum:
|
|
raise SemanticsError(f"{where}: needs at least {minimum} input name(s)")
|
|
for item in value:
|
|
_name(item, where)
|
|
if len(set(value)) != len(value):
|
|
raise SemanticsError(f"{where}: repeated input name")
|
|
|
|
|
|
def _fields(
|
|
entry: Any, where: str, required: FrozenSet[str], optional: FrozenSet[str]
|
|
) -> None:
|
|
if not isinstance(entry, dict):
|
|
raise SemanticsError(f"{where}: entry must be an object")
|
|
missing = sorted(required - entry.keys())
|
|
if missing:
|
|
raise SemanticsError(f"{where}: missing input field(s) {missing}")
|
|
unknown = sorted(entry.keys() - required - optional)
|
|
if unknown:
|
|
raise SemanticsError(f"{where}: unknown field(s) {unknown}")
|
|
|
|
|
|
def _strategy(entry: Any, category: str, where: str) -> str:
|
|
strategy = entry.get("strategy") if isinstance(entry, dict) else None
|
|
if not isinstance(strategy, str) or strategy not in STRATEGIES[category]:
|
|
raise SemanticsError(f"{where}: unknown strategy {strategy!r}")
|
|
return strategy
|
|
|
|
|
|
def _check_sampler(entry: dict, strategy: str, where: str) -> None:
|
|
stage = "image_stage" if strategy == "detailer-stage" else "latent"
|
|
_fields(
|
|
entry,
|
|
where,
|
|
frozenset({"strategy", "conditioning", stage, "facts"}),
|
|
_SAMPLER_OPTIONS,
|
|
)
|
|
_name(entry[stage], where)
|
|
# Inputs that, when set, replace the prompt the sampler's conditioning
|
|
# inputs carry (a detailer's wildcard); the prompt is then not read.
|
|
# ``fact_overrides`` (read by comfy-metadata.js): inputs that, when set,
|
|
# replace the settings the facts would read (a script or an XY plot).
|
|
for option in sorted(_SAMPLER_OPTIONS & entry.keys()):
|
|
_names(entry[option], f"{where}.{option}")
|
|
keys = {"guider"} if strategy == "custom-advanced" else {"positive", "negative"}
|
|
conditioning = entry["conditioning"]
|
|
_fields(conditioning, where + ".conditioning", frozenset(keys), frozenset())
|
|
for key in keys:
|
|
_name(conditioning[key], where + ".conditioning")
|
|
if entry["facts"] not in FACT_SHAPES:
|
|
raise SemanticsError(f"{where}: unknown facts shape {entry['facts']!r}")
|
|
|
|
|
|
def _check_guider(entry: dict, strategy: str, where: str) -> None:
|
|
if strategy == "cfg":
|
|
_fields(
|
|
entry, where, frozenset({"strategy", "positive", "negative"}), frozenset()
|
|
)
|
|
_name(entry["negative"], where)
|
|
else:
|
|
# Negative absent by design; its reason is fixed text, not an input.
|
|
_fields(
|
|
entry,
|
|
where,
|
|
frozenset({"strategy", "positive"}),
|
|
frozenset({"absent_reason"}),
|
|
)
|
|
if "absent_reason" in entry:
|
|
_name(entry["absent_reason"], where, "absent reason")
|
|
_name(entry["positive"], where)
|
|
|
|
|
|
def _check_selector(entry: dict, strategy: str, where: str) -> None:
|
|
if strategy == "first-present":
|
|
# The inputs whose names start with ``input_prefix``, in input order.
|
|
_fields(entry, where, frozenset({"strategy", "input_prefix"}), frozenset())
|
|
_name(entry["input_prefix"], where, "input prefix")
|
|
return
|
|
_fields(entry, where, frozenset({"strategy", "condition", "branches"}), frozenset())
|
|
_name(entry["condition"], where)
|
|
branches = entry["branches"]
|
|
_fields(branches, where + ".branches", frozenset({"true", "false"}), frozenset())
|
|
_name(branches["true"], where)
|
|
_name(branches["false"], where)
|
|
|
|
|
|
def _check_composite(entry: dict, strategy: str, where: str) -> None:
|
|
# ``additive``: every part stays in effect (combine, concat), so a later
|
|
# stage that adds parts to an earlier stage's prompt keeps that prompt.
|
|
_fields(entry, where, frozenset({"strategy", "inputs"}), frozenset({"additive"}))
|
|
_names(entry["inputs"], where, minimum=2)
|
|
if "additive" in entry and not isinstance(entry["additive"], bool):
|
|
raise SemanticsError(f"{where}: additive must be a boolean")
|
|
|
|
|
|
def _check_saver(entry: dict, strategy: str, where: str) -> None:
|
|
_fields(
|
|
entry,
|
|
where,
|
|
frozenset({"strategy", "prefix_input", "image_input", "pattern"}),
|
|
frozenset(),
|
|
)
|
|
_name(entry["prefix_input"], where)
|
|
_name(entry["image_input"], where)
|
|
if entry["pattern"] != SAVER_PATTERNS[strategy]:
|
|
raise SemanticsError(f"{where}: pattern does not match {strategy}")
|
|
|
|
|
|
def _check_conditioning(entry: dict, strategy: str, where: str) -> None:
|
|
_fields(entry, where, frozenset({"strategy", "input"}), frozenset())
|
|
_name(entry["input"], where)
|
|
|
|
|
|
def _check_encoder(entry: dict, strategy: str, where: str) -> None:
|
|
if strategy == "flag-parts":
|
|
# A literal boolean ``flag`` false reads the first input; true needs
|
|
# every input equal (smZ CLIPTextEncode's with_SDXL).
|
|
_fields(entry, where, frozenset({"strategy", "inputs", "params"}), frozenset())
|
|
params = entry["params"]
|
|
if not isinstance(params, dict) or set(params) != {"flag"}:
|
|
raise SemanticsError(f"{where}: params must be exactly ['flag']")
|
|
_name(params["flag"], where + ".params")
|
|
_names(entry["inputs"], where, minimum=2)
|
|
return
|
|
_fields(entry, where, frozenset({"strategy", "inputs"}), frozenset({"compose"}))
|
|
_names(entry["inputs"], where, minimum=2 if strategy == "parts-equal" else 1)
|
|
if "compose" in entry and not isinstance(entry["compose"], bool):
|
|
raise SemanticsError(f"{where}: compose must be a boolean")
|
|
|
|
|
|
def _check_string(entry: dict, strategy: str, where: str) -> None:
|
|
required = _STRING_PARAMS[strategy]
|
|
if required:
|
|
_fields(entry, where, frozenset({"strategy", "inputs", "params"}), frozenset())
|
|
params = entry["params"]
|
|
if not isinstance(params, dict) or set(params) != required:
|
|
raise SemanticsError(f"{where}: params must be exactly {sorted(required)}")
|
|
for value in params.values():
|
|
_name(value, where + ".params")
|
|
else:
|
|
_fields(entry, where, frozenset({"strategy", "inputs"}), frozenset())
|
|
_names(entry["inputs"], where)
|
|
|
|
|
|
_CHECKS: Mapping[str, Callable[[dict, str, str], None]] = MappingProxyType(
|
|
{
|
|
"samplers": _check_sampler,
|
|
"guiders": _check_guider,
|
|
"selectors": _check_selector,
|
|
"composites": _check_composite,
|
|
"savers": _check_saver,
|
|
"conditioning": _check_conditioning,
|
|
"encoders": _check_encoder,
|
|
"strings": _check_string,
|
|
}
|
|
)
|
|
|
|
|
|
class _Owners:
|
|
"""Each class belongs to one category; each (class, slot) is listed once."""
|
|
|
|
def __init__(self) -> None:
|
|
self._category: Dict[str, str] = {}
|
|
self._outputs: set = set()
|
|
|
|
def claim(self, name: str, category: str, slot: Optional[int] = None) -> None:
|
|
owner = self._category.setdefault(name, category)
|
|
if owner != category:
|
|
raise SemanticsError(f"duplicate class {name!r} in {owner} and {category}")
|
|
key = (name, slot)
|
|
if slot is not None and key in self._outputs:
|
|
raise SemanticsError(f"{category}: duplicate output key {key!r}")
|
|
self._outputs.add(key)
|
|
|
|
def classes(self) -> FrozenSet[str]:
|
|
return frozenset(self._category)
|
|
|
|
|
|
def _class_category(doc: dict, category: str, owners: _Owners) -> Mapping:
|
|
table = doc[category]
|
|
if not isinstance(table, dict):
|
|
raise SemanticsError(f"category {category} must be an object")
|
|
result = {}
|
|
for name, entry in table.items():
|
|
where = f"{category}[{name!r}]"
|
|
_name(name, where, "class")
|
|
strategy = _strategy(entry, category, where)
|
|
_CHECKS[category](entry, strategy, where)
|
|
owners.claim(name, category)
|
|
result[name] = _freeze(entry)
|
|
return MappingProxyType(result)
|
|
|
|
|
|
def _slot(entry: dict, where: str) -> int:
|
|
slot = entry.get("slot")
|
|
# bool is an int subclass; a JSON true is not an output slot.
|
|
if type(slot) is not int or not 0 <= slot <= _MAX_SLOT:
|
|
raise SemanticsError(f"{where}: slot must be a non-negative int, not {slot!r}")
|
|
return slot
|
|
|
|
|
|
def _slot_category(doc: dict, category: str, owners: _Owners) -> Mapping:
|
|
rows = doc[category]
|
|
if not isinstance(rows, list):
|
|
raise SemanticsError(f"category {category} must be a list")
|
|
result = {}
|
|
for index, row in enumerate(rows):
|
|
where = f"{category}[{index}]"
|
|
if not isinstance(row, dict):
|
|
raise SemanticsError(f"{where}: entry must be an object")
|
|
name = _name(row.get("class"), where, "class")
|
|
slot = _slot(row, where)
|
|
entry = {
|
|
key: value for key, value in row.items() if key not in ("class", "slot")
|
|
}
|
|
strategy = _strategy(entry, category, where)
|
|
_CHECKS[category](entry, strategy, where)
|
|
owners.claim(name, category, slot)
|
|
result[(name, slot)] = _freeze(entry)
|
|
return MappingProxyType(result)
|
|
|
|
|
|
def _lineage(doc: dict) -> Mapping:
|
|
"""``(class, slot)`` outputs whose image or latent continues one input's.
|
|
|
|
These describe an output's image or latent, never its prompt, so they are
|
|
not prompt categories: a class listed here is not claimed, and stays
|
|
unsupported (or listed elsewhere) for text. Each output is listed once.
|
|
"""
|
|
rows = doc["lineage"]
|
|
if not isinstance(rows, list):
|
|
raise SemanticsError("category lineage must be a list")
|
|
result = {}
|
|
for index, row in enumerate(rows):
|
|
where = f"lineage[{index}]"
|
|
if not isinstance(row, dict):
|
|
raise SemanticsError(f"{where}: entry must be an object")
|
|
name = _name(row.get("class"), where, "class")
|
|
slot = _slot(row, where)
|
|
entry = {
|
|
key: value for key, value in row.items() if key not in ("class", "slot")
|
|
}
|
|
_strategy(entry, "lineage", where)
|
|
_fields(entry, where, frozenset({"strategy", "input"}), frozenset())
|
|
_name(entry["input"], where)
|
|
if (name, slot) in result:
|
|
raise SemanticsError(f"lineage: duplicate output key {(name, slot)!r}")
|
|
result[(name, slot)] = _freeze(entry)
|
|
return MappingProxyType(result)
|
|
|
|
|
|
def _set_category(doc: dict, category: str, owners: _Owners) -> FrozenSet[str]:
|
|
rows = doc[category]
|
|
if not isinstance(rows, list):
|
|
raise SemanticsError(f"category {category} must be a list")
|
|
seen: set = set()
|
|
for name in rows:
|
|
_name(name, category, "class")
|
|
if name in seen:
|
|
raise SemanticsError(f"{category}: duplicate class {name!r}")
|
|
seen.add(name)
|
|
owners.claim(name, category)
|
|
return frozenset(seen)
|
|
|
|
|
|
def _string_map(table: Any, where: str, allowed: Optional[FrozenSet[str]]) -> None:
|
|
if not isinstance(table, dict):
|
|
raise SemanticsError(f"{where} must be an object")
|
|
for name, value in table.items():
|
|
_name(name, where, "class")
|
|
_name(value, where)
|
|
if allowed is not None and value not in allowed:
|
|
raise SemanticsError(f"{where}[{name!r}]: unknown kind {value!r}")
|
|
|
|
|
|
def _stage_inputs(doc: dict) -> Mapping[str, Tuple[str, ...]]:
|
|
table = doc["stage_inputs"]
|
|
if not isinstance(table, dict) or set(table) != set(_STAGE_INPUT_LISTS):
|
|
raise SemanticsError(
|
|
f"stage_inputs must have exactly {list(_STAGE_INPUT_LISTS)}"
|
|
)
|
|
for key in _STAGE_INPUT_LISTS:
|
|
_names(table[key], f"stage_inputs.{key}")
|
|
if "model" in table[key]:
|
|
raise SemanticsError(f"stage_inputs.{key}: model is a patch input")
|
|
if set(table["shaped"]) & set(table["with_model"]):
|
|
raise SemanticsError("stage_inputs: an input is listed in both lists")
|
|
return _freeze(table)
|
|
|
|
|
|
def _pass_through(doc: dict) -> Mapping[str, Tuple[str, ...]]:
|
|
table = doc["pass_through"]
|
|
if not isinstance(table, dict) or set(table) != set(_PASS_THROUGH_KEYS):
|
|
raise SemanticsError(
|
|
f"pass_through must have exactly {list(_PASS_THROUGH_KEYS)}"
|
|
)
|
|
_names(table["skip_inputs"], "pass_through.skip_inputs")
|
|
for name in ("text", "positive", "negative", "conditioning"):
|
|
if name in table["skip_inputs"]:
|
|
raise SemanticsError(f"pass_through.skip_inputs: {name} carries text")
|
|
return _freeze(table)
|
|
|
|
|
|
def _facts(doc: dict) -> Mapping[str, Any]:
|
|
facts = doc["facts"]
|
|
if not isinstance(facts, dict) or set(facts) != set(_FACTS_TABLES):
|
|
raise SemanticsError(f"facts must have exactly {list(_FACTS_TABLES)}")
|
|
configuration = facts["configuration_outputs"]
|
|
if not isinstance(configuration, dict):
|
|
raise SemanticsError("facts.configuration_outputs must be an object")
|
|
for name, adapter in configuration.items():
|
|
where = f"facts.configuration_outputs[{name!r}]"
|
|
_name(name, where, "class")
|
|
_fields(adapter, where, frozenset({"kind", "fields"}), _TYPE_FIELDS)
|
|
if adapter["kind"] not in _CONFIGURATION_KINDS:
|
|
raise SemanticsError(f"{where}: unknown kind {adapter['kind']!r}")
|
|
_names(adapter["fields"], where)
|
|
if "type_fields" in adapter:
|
|
# A fact whose value is the provider's node type (D8: Flux2Scheduler).
|
|
_names(adapter["type_fields"], where)
|
|
if set(adapter["type_fields"]) & set(adapter["fields"]):
|
|
raise SemanticsError(f"{where}: type_fields repeat an input field")
|
|
_string_map(facts["model_outputs"], "facts.model_outputs", None)
|
|
_string_map(facts["scalar_outputs"], "facts.scalar_outputs", _SCALAR_KINDS)
|
|
passthroughs = facts["model_passthroughs"]
|
|
_names(passthroughs, "facts.model_passthroughs", minimum=0)
|
|
return _freeze(facts)
|
|
|
|
|
|
def _check_nesting(doc: Any) -> None:
|
|
"""Reject containers nested deeper than ``MAX_NESTING`` (iterative walk)."""
|
|
stack = [(doc, 1)]
|
|
while stack:
|
|
value, level = stack.pop()
|
|
if not isinstance(value, (dict, list)):
|
|
continue
|
|
if level > MAX_NESTING:
|
|
raise SemanticsError(f"semantics table nests deeper than {MAX_NESTING}")
|
|
items = value.values() if isinstance(value, dict) else value
|
|
stack.extend((item, level + 1) for item in items)
|
|
|
|
|
|
def _validate(doc: Any) -> Semantics:
|
|
if not isinstance(doc, dict):
|
|
raise SemanticsError("semantics table must be an object")
|
|
if set(doc) != _CATEGORIES:
|
|
missing = sorted(_CATEGORIES - doc.keys())
|
|
unknown = sorted(doc.keys() - _CATEGORIES)
|
|
raise SemanticsError(f"category mismatch: missing {missing}, unknown {unknown}")
|
|
if type(doc["schema"]) is not int or doc["schema"] != SCHEMA_VERSION:
|
|
raise SemanticsError(f"unsupported schema {doc['schema']!r}")
|
|
owners = _Owners()
|
|
tables: Dict[str, Any] = {}
|
|
for category in _CLASS_CATEGORIES:
|
|
tables[category] = _class_category(doc, category, owners)
|
|
for category in _SLOT_CATEGORIES:
|
|
tables[category] = _slot_category(doc, category, owners)
|
|
for category in _SET_CATEGORIES:
|
|
tables[category] = _set_category(doc, category, owners)
|
|
return Semantics(
|
|
lineage=_lineage(doc),
|
|
stage_inputs=_stage_inputs(doc),
|
|
pass_through=_pass_through(doc),
|
|
facts=_facts(doc),
|
|
all_classes=owners.classes(),
|
|
**tables,
|
|
)
|
|
|
|
|
|
def load_semantics(path: Optional[Union[str, Path]] = None) -> Semantics:
|
|
"""Read and validate a semantics table; ``SemanticsError`` on any problem."""
|
|
source = Path(path) if path is not None else SEMANTICS_PATH
|
|
try:
|
|
with source.open("rb") as stream:
|
|
data = stream.read(MAX_TABLE_BYTES + 1)
|
|
if len(data) > MAX_TABLE_BYTES:
|
|
raise SemanticsError(
|
|
f"semantics table {source.name} exceeds {MAX_TABLE_BYTES} bytes"
|
|
)
|
|
doc = json.loads(
|
|
data.decode("utf-8"),
|
|
object_pairs_hook=_reject_duplicate_keys,
|
|
parse_constant=_reject_constant,
|
|
)
|
|
except SemanticsError:
|
|
raise
|
|
except RecursionError:
|
|
raise SemanticsError(
|
|
f"semantics table {source.name} nests deeper than {MAX_NESTING}"
|
|
) from None
|
|
except (OSError, UnicodeDecodeError, ValueError) as error:
|
|
raise SemanticsError(f"cannot read semantics table {source.name}: {error}")
|
|
_check_nesting(doc)
|
|
return replace(
|
|
_validate(doc), version=table_version(doc), source=_canonical_json(doc)
|
|
)
|
|
|
|
|
|
# Table parts that hold no class names: they apply to every graph.
|
|
_CLASS_INDEPENDENT = frozenset({"schema", "stage_inputs", "pass_through"})
|
|
|
|
|
|
def _canonical_json(doc: Any) -> str:
|
|
return json.dumps(doc, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
|
|
|
|
|
def table_version(doc: Any) -> str:
|
|
"""SHA-256 of ``doc`` as canonical JSON: content, not layout."""
|
|
return hashlib.sha256(_canonical_json(doc).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def _about(value: Any, classes: FrozenSet[str]) -> Any:
|
|
"""The part of one category that names a class in ``classes``.
|
|
|
|
Categories are keyed by class (objects), list classes (strings) or list
|
|
entries that carry a ``class``.
|
|
"""
|
|
if isinstance(value, dict):
|
|
return {key: item for key, item in value.items() if key in classes}
|
|
if isinstance(value, list):
|
|
return [
|
|
entry
|
|
for entry in value
|
|
if (isinstance(entry, str) and entry in classes)
|
|
or (isinstance(entry, dict) and entry.get("class") in classes)
|
|
]
|
|
return value
|
|
|
|
|
|
def class_projection(doc: Mapping[str, Any], classes) -> dict:
|
|
"""What ``doc`` says about ``classes``, plus its class-independent parts."""
|
|
classes = frozenset(classes)
|
|
projected = {}
|
|
for category, value in doc.items():
|
|
if category in _CLASS_INDEPENDENT:
|
|
projected[category] = value
|
|
elif category == "facts" and isinstance(value, dict):
|
|
projected[category] = {
|
|
table: _about(entries, classes) for table, entries in value.items()
|
|
}
|
|
else:
|
|
projected[category] = _about(value, classes)
|
|
return projected
|
|
|
|
|
|
def class_version(doc: Mapping[str, Any], classes) -> str:
|
|
"""SHA-256 of ``class_projection(doc, classes)`` as canonical JSON."""
|
|
return table_version(class_projection(doc, classes))
|
|
|
|
|
|
@lru_cache(maxsize=256)
|
|
def _cached_class_version(source: str, classes: FrozenSet[str]) -> str:
|
|
return class_version(json.loads(source), classes)
|
|
|
|
|
|
def semantics_class_version(semantics: Semantics, classes) -> str:
|
|
"""``class_version`` of a loaded table (cached per table and class set)."""
|
|
return _cached_class_version(semantics.source, frozenset(classes))
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def get_semantics() -> Semantics:
|
|
"""The repository table, loaded on first use; failures are not cached."""
|
|
return load_semantics()
|