* 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.
179 lines
6.6 KiB
Python
179 lines
6.6 KiB
Python
"""The monitor's ladder path: foreign outputs (#247) and PromptManager runs (#659).
|
|
|
|
A foreign output (no positive PromptManager node in its graph) is decided by
|
|
the ladder the output scan uses (``utils.file_prompt.decide_file_prompt``)
|
|
with the ``MONITOR`` policy: certain files are stored at once, files only
|
|
recorded history can decide wait for their run's outputs to be sealed, and
|
|
everything else stays unlinked. A PromptManager run the image's metadata and
|
|
its tracked run cannot link takes the same path (#659 Part 3); its entries
|
|
carry the run kind ``PROMPTMANAGER``, which selects the settings gate and the
|
|
marks of a created prompt (``ladder_gate``). This module holds the parts that
|
|
do not need the monitor's waiting sets: the settings, the decision call and
|
|
the store. The waiting and the re-check stay on ``ImageGenerationHandler``.
|
|
"""
|
|
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import Any, Callable, Mapping, Optional, Tuple
|
|
|
|
from .file_prompt import (
|
|
NOT_SAVED,
|
|
NOT_SAVED_WIRED,
|
|
PAIR,
|
|
POSITIVE,
|
|
Decision,
|
|
Policy,
|
|
decide_file_prompt,
|
|
)
|
|
from .hashing import generate_prompt_hash
|
|
from .usage_tracking import survive_switch
|
|
|
|
try:
|
|
from ..database.pair_ingestion import RUN_MARKS, SCAN_MARKS, ingest_resolved_pair
|
|
from ..database.run_attribution import recorded_output_lookup
|
|
from ..database.scanned_prompts import store_scanned_prompt_or_raise
|
|
except ImportError:
|
|
from database.pair_ingestion import RUN_MARKS, SCAN_MARKS, ingest_resolved_pair
|
|
from database.run_attribution import recorded_output_lookup
|
|
from database.scanned_prompts import store_scanned_prompt_or_raise
|
|
|
|
# Decisions that name a prompt to store
|
|
CERTAIN = (PAIR, POSITIVE)
|
|
# Decisions of a run whose prompt has Save to library off, or wired from a
|
|
# node the file cannot show (#90): final, nothing is stored, nothing waits
|
|
NOT_SAVED_KINDS = (NOT_SAVED, NOT_SAVED_WIRED)
|
|
# Sources certain without a recorded run: the graph alone, or its recorded saver
|
|
ANCHORED_SOURCES = ("inspector", "recorded-run")
|
|
# The run kinds of a ladder entry: an output of another workflow, or a
|
|
# PromptManager run its metadata and tracked run could not link (#659)
|
|
FOREIGN = "foreign"
|
|
PROMPTMANAGER = "promptmanager"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ForeignRecheck:
|
|
"""``schedule`` snapshot: the one ladder re-check of an output after its
|
|
run's outputs were sealed. ``reference`` is the sealed output reference,
|
|
the spelling history recorded (``recorded_output_lookup(reference=)``);
|
|
``kind`` is the entry's run kind (``FOREIGN`` or ``PROMPTMANAGER``)."""
|
|
|
|
reference: Mapping[str, Any]
|
|
kind: str = FOREIGN
|
|
|
|
|
|
def _gallery_config():
|
|
"""``GalleryConfig``, or None when the configuration cannot be imported."""
|
|
try:
|
|
from ..py.config import GalleryConfig
|
|
except ImportError:
|
|
try:
|
|
from py.config import GalleryConfig
|
|
except ImportError:
|
|
return None
|
|
return GalleryConfig
|
|
|
|
|
|
def monitoring_enabled() -> bool:
|
|
"""``GalleryConfig.MONITORING_ENABLED``, read for every file: saved off,
|
|
it stops the monitor's ladder writes at once, although the running
|
|
observer watches until a restart. True without the configuration."""
|
|
config = _gallery_config()
|
|
return config is None or config.MONITORING_ENABLED is not False
|
|
|
|
|
|
def ladder_gate(kind: str) -> Tuple[bool, Any]:
|
|
"""``(enabled, marks)`` of a ladder entry of run ``kind``, read now.
|
|
|
|
``FOREIGN``: ``save_foreign_runs()`` and ``RUN_MARKS`` (a prompt created
|
|
from another workflow). ``PROMPTMANAGER``: ``monitoring_enabled()`` and
|
|
the scan's ``SCAN_MARKS`` (the prompt belongs to a PromptManager run and
|
|
usually exists already); the node's own Save to library switch applies
|
|
through the ladder's opt-out steps.
|
|
"""
|
|
if kind == FOREIGN:
|
|
return save_foreign_runs(), RUN_MARKS
|
|
return monitoring_enabled(), SCAN_MARKS
|
|
|
|
|
|
def save_foreign_runs() -> bool:
|
|
"""Whether a foreign output may be stored now, read for every file.
|
|
|
|
``GalleryConfig.SAVE_FOREIGN_RUNS`` and ``MONITORING_ENABLED``: a
|
|
monitoring switch saved off stops foreign writes at once, although the
|
|
running observer watches until a restart. True when the configuration
|
|
cannot be imported (the defaults).
|
|
"""
|
|
config = _gallery_config()
|
|
if config is None:
|
|
return True
|
|
return config.SAVE_FOREIGN_RUNS is not False and monitoring_enabled()
|
|
|
|
|
|
def history_lookup(
|
|
db: Any, image_path: str, reference: Optional[Mapping[str, Any]] = None
|
|
) -> Callable[[], Any]:
|
|
"""The ladder's ``lookup`` for one file: its ``RecordedOutput`` or None.
|
|
|
|
With ``reference`` the file is spelled as history recorded it. Failures
|
|
are logged by ``recorded_output_lookup`` and name nothing.
|
|
"""
|
|
lookup = recorded_output_lookup(
|
|
db, reference=dict(reference) if reference is not None else None
|
|
)
|
|
return lambda: lookup(image_path)
|
|
|
|
|
|
def decide_foreign(
|
|
image_path: str,
|
|
metadata: Any,
|
|
*,
|
|
in_output: bool,
|
|
lookup: Optional[Callable[[], Any]],
|
|
) -> Decision:
|
|
"""The ``MONITOR`` ladder for one foreign output (the size is read only
|
|
when the ladder needs it)."""
|
|
|
|
def file_size() -> Optional[int]:
|
|
try:
|
|
return os.path.getsize(image_path)
|
|
except OSError:
|
|
return None
|
|
|
|
return decide_file_prompt(
|
|
metadata,
|
|
file_name=os.path.basename(image_path),
|
|
file_size=file_size,
|
|
in_output=in_output,
|
|
lookup=lookup,
|
|
policy=Policy.MONITOR,
|
|
)
|
|
|
|
|
|
def store_foreign(
|
|
db: Any, image_path: str, decision: Decision, marks: Any = RUN_MARKS
|
|
) -> Tuple[str, Optional[int]]:
|
|
"""Store a certain decision: ``(status, prompt id)``.
|
|
|
|
One write through ``survive_switch``, so it runs again on the moved
|
|
library when a Move library switched while it waited (#249 S6b). Created
|
|
prompts carry ``marks`` (``ladder_gate``). A file linked to another prompt is a
|
|
``conflict`` and nothing is written. Database errors are raised.
|
|
"""
|
|
|
|
def store():
|
|
if decision.kind == PAIR:
|
|
result = ingest_resolved_pair(
|
|
db, image_path, decision.canonical, decision.resolution, marks=marks
|
|
)
|
|
return result["status"], result.get("image_id")
|
|
return store_scanned_prompt_or_raise(
|
|
db, image_path, decision.canonical, decision.text, marks
|
|
)
|
|
|
|
status, linked = survive_switch(db, store)
|
|
if decision.kind != PAIR or linked is None:
|
|
return status, linked
|
|
# The pair ingester reports the image row; its prompt is the positive's.
|
|
prompt = db.get_prompt_by_hash(generate_prompt_hash(decision.text))
|
|
return status, prompt["id"] if prompt else None
|