Files
Vito a1f744708e fix: resolve rgthree Any Switch, show shared roles, choose ambiguous prompts in Inspect (#660)
* 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.
2026-11-21 03:07:38 +00:00

603 lines
21 KiB
Python

"""Exact inspection-only graph projection and bounded JSON wire encoding."""
import json
import math
import re
from decimal import Decimal, InvalidOperation
from typing import TYPE_CHECKING, Any, Literal, Optional
from .inspection_outcomes import MESSAGE_LENGTH, project_resolution
from .validators import validate_tags
if TYPE_CHECKING:
from .prompt_inspector import InspectionRead
MAX_RESPONSE_BYTES = 8 * 1024 * 1024
MAX_LIBRARY_BYTES = 32 * 1024
# The image tag set cap (database/annotations.py MAX_IMAGE_TAGS; pinned equal
# by tests/test_config.py).
MAX_IMAGE_TAGS = 100
_IMAGE_TAG_STATES = frozenset({"current", "none", "unavailable"})
_MAX_SAFE_INTEGER = 2**53 - 1
_RECORD_KEYS = frozenset(
{"prompt", "workflow", "parameters", "comfyassets_prompt_pairs"}
)
_FORMATS = frozenset({"original-text", "reserialized-json", "invalid", "limited"})
_PROMPT_NODE_KEYS = frozenset({"class_type", "inputs"})
MAX_PROJECTION_DEPTH = 64
# Backstop, not an expected outcome: executable API nodes for a prompt; UI nodes
# including subgraph definitions for a workflow.
GRAPH_NODE_CEILING = 20_000
ProjectionKind = Literal["prompt", "workflow", "carrier"]
class _ProjectionLimit(ValueError):
"""A present graph cannot be projected within inspection limits."""
def _pairs(items: list[tuple]) -> dict:
result = {}
for key, value in items:
if key in result:
raise ValueError("Duplicate JSON key")
result[key] = value
return result
class _Nonfinite:
"""A parsed ``NaN``/``Infinity`` literal: never a fact, projected as null."""
_NONFINITE = _Nonfinite()
def _nonfinite(value: str) -> _Nonfinite:
return _NONFINITE
def _normalize(value: object, depth: int = 1, *, retain: bool = True) -> object:
"""Walk bounded source once; unretained values are only validated as JSON."""
if isinstance(value, (dict, list)):
if depth > MAX_PROJECTION_DEPTH:
raise _ProjectionLimit()
if isinstance(value, dict):
result = {} if retain else None
for key, child in value.items():
normalized = _normalize(child, depth + 1, retain=retain)
if retain:
result[key] = normalized
else:
result = [] if retain else None
for child in value:
normalized = _normalize(child, depth + 1, retain=retain)
if retain:
result.append(normalized)
return result
if not retain or value is _NONFINITE:
return None
if isinstance(value, Decimal):
if not value.is_finite():
raise ValueError("Nonfinite JSON number")
# str keeps large exponents compact and never rounds through a float.
return str(value)
if type(value) is int and abs(value) > _MAX_SAFE_INTEGER:
return str(value)
return value
def _project_prompt(tree: object, depth: int = 1) -> dict:
"""Each API node keeps exactly ``class_type`` and ``inputs``.
Other node keys (``_meta``, ``is_changed``, future keys) are validated and
dropped, so a nonfinite value there never reaches the projection.
"""
if not isinstance(tree, dict):
raise ValueError("Prompt graph must be an object of nodes")
if depth + 1 > MAX_PROJECTION_DEPTH: # the root and its node objects
raise _ProjectionLimit()
result = {}
for node_id, node in tree.items():
if not isinstance(node, dict):
result[node_id] = _normalize(node, depth + 1)
continue
projected = {}
for key, child in node.items():
keep = key in _PROMPT_NODE_KEYS
normalized = _normalize(child, depth + 2, retain=keep)
if keep:
projected[key] = normalized
result[node_id] = projected
return result
def _project(tree: object, kind: str, depth: int = 1) -> object:
if kind == "prompt":
return _project_prompt(tree, depth)
if kind == "workflow":
return _normalize(tree, depth)
if not isinstance(tree, dict):
raise ValueError("Malformed carrier")
result = {}
for key, member in tree.items():
if key not in ("prompt", "workflow"):
_normalize(member, depth + 1, retain=False)
elif isinstance(member, str):
result[key] = member # projected by its own kind when read
elif key == "prompt" and not isinstance(member, dict):
result[key] = _normalize(member, depth + 1)
else:
result[key] = _project(member, key, depth + 1)
return result
def _strict_projection(text: str, *, kind: ProjectionKind) -> object:
"""Parse exactly (Decimal, no duplicate keys) and project by record kind."""
try:
tree = json.loads(
text,
parse_float=Decimal,
object_pairs_hook=_pairs,
parse_constant=_nonfinite,
)
return _project(tree, kind)
except RecursionError:
raise _ProjectionLimit() from None
except InvalidOperation:
raise ValueError("JSON decimal exceeds supported range") from None
def _node_count(value: dict, *, workflow: bool) -> int:
if not workflow:
return len(value)
nodes = value.get("nodes")
count = len(nodes) if isinstance(nodes, list) else 0
definitions = value.get("definitions")
subgraphs = definitions.get("subgraphs") if isinstance(definitions, dict) else None
for subgraph in subgraphs if isinstance(subgraphs, list) else ():
inner = subgraph.get("nodes") if isinstance(subgraph, dict) else None
count += len(inner) if isinstance(inner, list) else 0
return count
def _graph(value: object, *, workflow: bool = False) -> dict:
if not isinstance(value, dict):
return {"status": "malformed", "value": None}
if _node_count(value, workflow=workflow) > GRAPH_NODE_CEILING:
return {"status": "limited", "value": None}
return {"status": "parsed", "value": value}
def project_graph(text: str, kind: Literal["prompt", "workflow"]) -> dict:
"""One record's graph as the inspector projects it: ``{status, value}``.
``status`` is ``parsed`` (``value`` is the projected graph the browser
parser receives), ``limited`` (past the depth or node bound) or
``malformed``. Shared with the workspace card so both read one bound.
"""
try:
return _graph(_strict_projection(text, kind=kind), workflow=kind == "workflow")
except _ProjectionLimit:
return {"status": "limited", "value": None}
except (ValueError, TypeError, KeyError, OverflowError):
return {"status": "malformed", "value": None}
def _metadata(inspection: "InspectionRead | None") -> dict:
formats = (
{}
if inspection is None
else {
key: value
for key, value in inspection.record_formats.items()
if key in _RECORD_KEYS and value in _FORMATS
}
)
if inspection is not None:
# A record over its read budget has no text: like ``invalid``, raw omits
# it, and its graph is ``limited`` rather than parsed from nothing.
for key in inspection.limited_records & _RECORD_KEYS:
formats[key] = "limited"
raw = (
{}
if inspection is None
else {
key: value
for key, value in inspection.metadata.items()
if key in _RECORD_KEYS
and isinstance(value, str)
and formats.get(key) != "limited"
}
)
result = {
"status": (
"unreadable"
if inspection is None
else ("available" if raw or formats else "absent")
),
"omitted_reason": None,
"raw": raw,
"record_formats": formats,
"parameters": raw.get("parameters"),
}
carrier, failed = None, None
if inspection is not None and inspection.video_carrier_text is not None:
try:
carrier = _strict_projection(inspection.video_carrier_text, kind="carrier")
except _ProjectionLimit:
failed = "limited"
except (ValueError, TypeError, OverflowError):
failed = "malformed"
for key, field in (("prompt", "prompt_graph"), ("workflow", "workflow_graph")):
graph = {"status": "absent", "value": None}
if key in raw or key in formats:
if failed or formats.get(key) == "limited":
graph["status"] = failed or "limited"
elif formats.get(key) == "invalid":
graph["status"] = "malformed"
elif carrier is None and formats.get(key) == "reserialized-json":
graph["status"] = "limited"
elif carrier is None:
graph = project_graph(raw.get(key), key)
else:
try:
value = carrier.get(key)
if isinstance(value, str):
value = _strict_projection(value, kind=key)
graph = _graph(value, workflow=key == "workflow")
except _ProjectionLimit:
graph["status"] = "limited"
except (ValueError, TypeError, KeyError, OverflowError):
graph["status"] = "malformed"
result[field] = graph
return result
def _bytes(value: dict) -> bytes:
# JSON preserves isolated surrogate evidence through escaped code units.
return json.dumps(
value, ensure_ascii=False, allow_nan=False, separators=(",", ":")
).encode("utf-8", "backslashreplace")
def _finite(value: object, *, positive: bool = False) -> bool:
try:
return (
type(value) in (int, float)
and math.isfinite(value)
and (value > 0 if positive else value >= 0)
)
except OverflowError:
return False
def _file_projection(file: dict, inspection: "InspectionRead | None") -> dict:
source = dict(file)
if inspection is not None:
source.update(
format=inspection.format, width=inspection.width, height=inspection.height
)
result = {"observation": "current-file"}
for key in ("source_label", "extension", "format"):
value = source.get(key)
if value is None and key == "format":
result[key] = None
elif isinstance(value, str):
result[key] = value
if source.get("media_type") in ("image", "video"):
result["media_type"] = source["media_type"]
for key in ("size", "modified_time", "width", "height"):
if key not in source:
continue
value = source[key]
if value is None or _finite(value, positive=key in ("width", "height")):
if key not in ("width", "height") or value is None or type(value) is int:
result[key] = value
return result
def _blank(value: str | bytes | None) -> bool:
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value is None or not value.strip()
def inherited_category(
positive_category: str | bytes | None,
recipe_category: str | bytes | None,
has_recipe: bool,
) -> tuple:
"""``(value, scope)`` of the category an image's link supplies (#332 MC4).
The one rule for the inspector chip, the Images category filter and
History (D39): a linked recipe's own category when it is not blank,
``(recipe category, "pair")``; otherwise the positive's value unchanged,
blank or not, ``(positive category, "positive")``.
"""
if has_recipe and not _blank(recipe_category):
return recipe_category, "pair"
return positive_category, "positive"
class _OwnCategoryUnread:
"""The own-category read failed: hide the category (#332 DC5)."""
def __repr__(self) -> str:
return "OWN_CATEGORY_UNREAD"
OWN_CATEGORY_UNREAD = _OwnCategoryUnread()
def apply_own_category(library: dict, own) -> dict:
"""*library* with an image's own category applied (#332 §5).
``own`` is the own category (a string, shown with scope ``"image"``
whatever the link status), None (the inherited values stay) or
OWN_CATEGORY_UNREAD (category and scope hidden rather than possibly
wrong). Returns a new dict.
"""
result = dict(library)
if own is OWN_CATEGORY_UNREAD:
result.update(category=None, category_scope=None)
elif isinstance(own, str):
result.update(category=own, category_scope="image")
return result
def library_metadata(
positive_category: str | bytes | None,
positive_tags: list,
recipe: tuple | None = None,
) -> dict:
"""The panel's saved category and tags, each with the scope it came from.
D39 (maintainer ruling, 2026-10-21): a recipe-linked image shows the recipe's
own category and tags when set; otherwise each field separately falls back to
the linked positive prompt's, the values Set category writes and the Images
filters match. Tag sets are never merged. ``recipe`` is (category, tags).
"""
category, category_scope = inherited_category(
positive_category,
recipe[0] if recipe is not None else None,
recipe is not None,
)
tags, tags_scope = positive_tags, "positive"
if recipe is not None and recipe[1]:
tags, tags_scope = recipe[1], "pair"
return {
"category": category,
"category_scope": category_scope,
"tags": tags,
"tags_scope": tags_scope,
}
def _library_projection(library: dict) -> dict:
status = library.get("status")
result = {
"status": (
status
if status in ("linked", "none", "ambiguous", "unavailable", "limited")
else "unavailable"
),
"scope": "saved-library",
}
for key in ("positive_id", "pair_id"):
value = library.get(key)
if value is None or type(value) is int and 0 < value <= _MAX_SAFE_INTEGER:
result[key] = value
for key in ("title", "category"):
value = library.get(key)
if value is None or isinstance(value, str):
result[key] = value
# An image's own category (#332) has the scope "image"; tags never do.
for key, scopes in (
("category_scope", ("pair", "positive", "image", None)),
("tags_scope", ("pair", "positive", None)),
):
scope = library.get(key)
if scope in scopes:
result[key] = scope
tags = library.get("tags")
result["tags"] = (
[tag for tag in tags if isinstance(tag, str)] if isinstance(tags, list) else []
)
if len(_bytes(result)) > MAX_LIBRARY_BYTES:
return {
"status": "limited",
"scope": "saved-library",
"positive_id": None,
"pair_id": None,
"title": None,
"category": None,
"tags": [],
"category_scope": None,
"tags_scope": None,
}
return result
def _image_tag_name(value: object) -> bool:
if not isinstance(value, str) or value != value.strip() or "," in value:
return False
try:
return validate_tags([value])
except ValueError:
return False
def project_image_tags(facet: object) -> dict:
"""The ``image_tags`` facet as the client accepts it, else unavailable.
``current`` carries the byte record's names (at most 100 valid vocabulary
names); ``none`` and ``unavailable`` carry no names. Anything else, extra
keys included, is reported as ``unavailable`` rather than passed on.
"""
unavailable = {"state": "unavailable", "tags": []}
if not isinstance(facet, dict) or set(facet) != {"state", "tags"}:
return unavailable
state, tags = facet["state"], facet["tags"]
if state not in _IMAGE_TAG_STATES or not isinstance(tags, list):
return unavailable
if state != "current" and tags:
return unavailable
if len(tags) > MAX_IMAGE_TAGS or not all(_image_tag_name(tag) for tag in tags):
return unavailable
return {"state": state, "tags": list(tags)}
_REVIEW_ITEM_ID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}")
def project_review(value: Any) -> Optional[dict]:
"""The ``review`` facet as the client accepts it (#659), else None.
``{"state": "pending", "item_id": <item id>}`` or ``{"state": "decided"}``;
any other value is null, so a malformed answer never offers a choice.
"""
if not isinstance(value, dict):
return None
if value == {"state": "decided"}:
return {"state": "decided"}
item_id = value.get("item_id")
if (
set(value) == {"state", "item_id"}
and value["state"] == "pending"
and isinstance(item_id, str)
and _REVIEW_ITEM_ID.fullmatch(item_id)
):
return {"state": "pending", "item_id": item_id}
return None
def _bounded_message(value: Any) -> Optional[str]:
"""A role line as the client accepts it: 1 to 512 UTF-16 code units."""
if not isinstance(value, str) or not value:
return None
value = value[:MESSAGE_LENGTH]
while len(value.encode("utf-16-le", "surrogatepass")) > 2 * MESSAGE_LENGTH:
value = value[:-1]
return value
def _bounded_messages(prompts: dict) -> dict:
"""Keep a role ``message`` only as bounded text on a non-resolved role."""
bounded = {}
for role, side in prompts.items():
if isinstance(side, dict) and "message" in side:
side = {key: item for key, item in side.items() if key != "message"}
message = _bounded_message(prompts[role]["message"])
if message is not None and side.get("status") != "resolved":
side["message"] = message
bounded[role] = side
return bounded
def _encode_inspection(
*,
identity: dict,
file: dict,
prompts: dict,
resolution: dict,
inspection: "InspectionRead | None",
library: dict,
image_tags: dict | None = None,
review: dict | None = None,
) -> bytes:
"""Serialize exactly once per budget step, preserving identity and roles."""
metadata = _metadata(inspection)
response = {
"success": True,
"inspection_version": 1,
**identity,
"file": _file_projection(file, inspection),
"prompts": _bounded_messages(prompts),
"resolution": project_resolution(resolution),
"metadata": metadata,
"library": _library_projection(library),
"review": project_review(review),
}
if image_tags is not None:
response["image_tags"] = project_image_tags(image_tags)
body = _bytes(response)
# Omission order keeps prompt evidence longest: the workflow graph first,
# then the prompt graph, then all raw records atomically.
for field in ("workflow_graph", "prompt_graph"):
if len(body) <= MAX_RESPONSE_BYTES:
break
if metadata[field]["status"] != "absent":
metadata[field] = {"status": "limited", "value": None}
body = _bytes(response)
if len(body) > MAX_RESPONSE_BYTES:
metadata.update(
raw={},
parameters=None,
status="limited",
omitted_reason="response-size-limit",
)
body = _bytes(response)
if len(body) > MAX_RESPONSE_BYTES:
raise ValueError("Inspection response exceeds limits")
return body
def encode_inspection_response(
*,
image: dict,
root_scope: str,
file: dict,
prompts: dict,
resolution: dict,
inspection: "InspectionRead | None",
library: dict,
image_tags: dict | None = None,
review: dict | None = None,
) -> bytes:
"""Preserve the existing rooted wire and its bounded metadata projection.
*image_tags*, when given, adds the validated ``image_tags`` facet (B3).
*review* is the file's Needs review facet (#659); null when not given.
"""
return _encode_inspection(
identity={"root_scope": root_scope, "image": image},
file=file,
prompts=prompts,
resolution=resolution,
inspection=inspection,
library=library,
image_tags=image_tags,
review=review,
)
def encode_history_inspection_response(
*,
current_output: dict,
file: dict,
prompts: dict,
resolution: dict,
inspection: "InspectionRead | None",
library: dict,
image_tags: dict | None = None,
review: dict | None = None,
) -> bytes:
"""Use occurrence identity with the same current-file evidence projection.
*image_tags*, when given, adds the validated ``image_tags`` facet (#457).
*review* is the file's Needs review facet (#659); null when not given.
"""
return _encode_inspection(
identity={
"history_version": 1,
"history_epoch": current_output["history_epoch"],
"current_output": current_output,
},
file=file,
prompts=prompts,
resolution=resolution,
inspection=inspection,
library=library,
image_tags=image_tags,
review=review,
)