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.
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
@@ -41,3 +41,21 @@ test("without the API client nothing is fetched", async () => {
|
||||
assert.equal(await module.loadInspectionSemantics(), null);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
// #657: a `first-present` selector (rgthree Any Switch) has exactly `strategy` and a non-empty `input_prefix` of at most
|
||||
// 128 characters, as utils/inspection_semantics.py checks; the browser rejected nothing about a selector before.
|
||||
test("the compiler checks a first-present selector as strictly as the server", async () => {
|
||||
const { compileSemantics, SemanticsError } = await import("../../web/js/workspace/local-resolver.mjs");
|
||||
const real = compileSemantics(JSON.parse(TABLE));
|
||||
assert.deepEqual(real.selectors.get("Any Switch (rgthree)"), { strategy: "first-present", input_prefix: "any_" });
|
||||
const valid = { strategy: "first-present", input_prefix: "any_" };
|
||||
for (const entry of [{ ...valid, condition: "boolean" }, { strategy: "first-present" }, { ...valid, input_prefix: "" },
|
||||
{ ...valid, input_prefix: "a".repeat(129) }, { ...valid, input_prefix: 1 }]) {
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = entry;
|
||||
assert.throws(() => compileSemantics(doc), SemanticsError, JSON.stringify(entry));
|
||||
}
|
||||
const doc = JSON.parse(TABLE);
|
||||
doc.selectors["Any Switch (rgthree)"] = { ...valid, input_prefix: "a".repeat(128) };
|
||||
assert.doesNotThrow(() => compileSemantics(doc));
|
||||
});
|
||||
|
||||
@@ -915,6 +915,9 @@ def golden_cases():
|
||||
import unknown_node_graphs
|
||||
for name, graph in unknown_node_graphs.shapes().items():
|
||||
add(f"pass-through-{name}", graph)
|
||||
# #657: rgthree Any Switch, the first input proven to hold a value.
|
||||
for name, graph in unknown_node_graphs.first_present_shapes().items():
|
||||
add(f"first-present-{name}", graph)
|
||||
for name, records in {
|
||||
**unknown_node_graphs.recorded_shapes(),
|
||||
**unknown_node_graphs.review_shapes(),
|
||||
|
||||
@@ -13,9 +13,11 @@ import random
|
||||
|
||||
try:
|
||||
from tests import passthrough_graphs as shapes
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
from tests.local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
import passthrough_graphs as shapes
|
||||
import unknown_node_graphs as switch_graphs
|
||||
from local_resolver_cases import EXECUTION_KEY, SPACES, WORDS, _Builder
|
||||
|
||||
|
||||
@@ -642,10 +644,31 @@ def _passthrough_edges():
|
||||
return {f"edge-{name}": graph for name, graph in cases.items()}
|
||||
|
||||
|
||||
def _first_present():
|
||||
"""rgthree Any Switch (#657) beside a second sampler and in a detailer."""
|
||||
sweep = switch_graphs.any_switch_sweep_graph
|
||||
second = _sampler(["15", 0], ["16", 0], latent=["10", 0])
|
||||
unproven = switch_graphs.first_present_shapes()["through-unknown"]
|
||||
return {
|
||||
"first-present-two-samplers": {**sweep(), "36": second},
|
||||
"first-present-two-samplers-unproven": {**unproven, "36": second},
|
||||
"first-present-detailer": {
|
||||
**sweep(),
|
||||
"36": _detailer(["27", 0], ["15", 0], ["16", 0], wildcard=""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def selection_cases():
|
||||
"""Named record sets for every Task 9 path, each a ``read_inspection_file`` dict."""
|
||||
cases = {}
|
||||
for group in (_samplers(), _previews(), _detailers(), _passthrough()):
|
||||
for group in (
|
||||
_samplers(),
|
||||
_previews(),
|
||||
_detailers(),
|
||||
_passthrough(),
|
||||
_first_present(),
|
||||
):
|
||||
for name, graph in group.items():
|
||||
cases[f"select-{name}"] = {"prompt": json.dumps(graph, ensure_ascii=False)}
|
||||
cases.update(_parameters())
|
||||
|
||||
@@ -20,9 +20,11 @@ from utils.prompt_inspector import InspectionResult
|
||||
try:
|
||||
from tests import inspection_parity as parity
|
||||
from tests import saver_anchor_graphs as shapes
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # pragma: no cover - discover -s tests puts tests/ first
|
||||
import inspection_parity as parity
|
||||
import saver_anchor_graphs as shapes
|
||||
import unknown_node_graphs as switch_graphs
|
||||
|
||||
SHARED_NAME = "IMG_GEN_00371_.png"
|
||||
LORA = "<lora:style:1.00>"
|
||||
@@ -418,6 +420,17 @@ class TestUndecidedGraph(unittest.TestCase):
|
||||
self.assertEqual(decision.text, parity.POS)
|
||||
self.assertEqual(decision.resolution["state"], "unresolved")
|
||||
|
||||
def test_step_8_1_the_inspector_links_the_any_switch_sweep(self):
|
||||
# #657: the default profile cannot read rgthree's Any Switch; the
|
||||
# inspector proves its first input and links it under both policies.
|
||||
graph = switch_graphs.any_switch_sweep_graph()
|
||||
for policy in (Policy.SCAN, Policy.MONITOR):
|
||||
with self.subTest(policy=policy):
|
||||
decision = _decide(_graph(graph), policy=policy, lookup=_Lookup())
|
||||
self.assertEqual(decision.kind, "positive")
|
||||
self.assertEqual(decision.source, "inspector")
|
||||
self.assertEqual(decision.text, switch_graphs.POSITIVE)
|
||||
|
||||
def test_step_8_1_the_recorded_saver_names_its_branch(self):
|
||||
lookup = _Lookup("23")
|
||||
decision = _decide(_graph(shapes.shared_prefix()), lookup=lookup)
|
||||
|
||||
@@ -594,7 +594,7 @@ class ValidationTest(_TableCase):
|
||||
),
|
||||
"guiders": frozenset({"cfg", "basic"}),
|
||||
"conditioning": frozenset({"passthrough", "zeroed"}),
|
||||
"selectors": frozenset({"boolean-select"}),
|
||||
"selectors": frozenset({"boolean-select", "first-present"}),
|
||||
"composites": frozenset({"combine"}),
|
||||
"encoders": frozenset(
|
||||
{"single", "parts-equal", "pm-compose", "flag-parts"}
|
||||
@@ -609,6 +609,32 @@ class ValidationTest(_TableCase):
|
||||
with self.assertRaises(TypeError):
|
||||
semantics.STRATEGIES["samplers"] = frozenset()
|
||||
|
||||
def test_proven_value_categories_are_the_text_returning_ones(self):
|
||||
# #657: a path through only these (plus code-traced classes) proves
|
||||
# that a switch input held a value. Selectors, runtime, facts and
|
||||
# lineage classes may return None or are not text, so never prove one.
|
||||
self.assertEqual(
|
||||
semantics.PROVEN_VALUE_CATEGORIES,
|
||||
frozenset({"encoders", "strings", "conditioning", "composites"}),
|
||||
)
|
||||
|
||||
def test_first_present_entry_shape_is_strict(self):
|
||||
valid = {"strategy": "first-present", "input_prefix": "any_"}
|
||||
doc = _minimal()
|
||||
doc["selectors"]["Any Switch (rgthree)"] = dict(valid)
|
||||
self.assertEqual(self.load_doc(doc).selectors["Any Switch (rgthree)"], valid)
|
||||
for label, entry, fragment in (
|
||||
("extra key", {**valid, "condition": "boolean"}, "unknown field"),
|
||||
("missing prefix", {"strategy": "first-present"}, "missing input"),
|
||||
("empty prefix", {**valid, "input_prefix": ""}, "input prefix"),
|
||||
("long prefix", {**valid, "input_prefix": "a" * 129}, "input prefix"),
|
||||
("prefix not text", {**valid, "input_prefix": 1}, "input prefix"),
|
||||
):
|
||||
with self.subTest(label):
|
||||
doc = _minimal()
|
||||
doc["selectors"]["Any Switch (rgthree)"] = entry
|
||||
self.assertRejected(doc, fragment)
|
||||
|
||||
def test_duplicate_output_key_rejected(self):
|
||||
doc = _minimal()
|
||||
doc["encoders"].append(copy.deepcopy(doc["encoders"][0]))
|
||||
@@ -874,6 +900,11 @@ class SamplerOptionsTest(_TableCase):
|
||||
table.selectors["Switch conditioning [Crystools]"],
|
||||
table.selectors["easy ifElse"],
|
||||
)
|
||||
# rgthree any_switch.py: the first ``any_*`` input that is not None.
|
||||
self.assertEqual(
|
||||
table.selectors["Any Switch (rgthree)"],
|
||||
{"strategy": "first-present", "input_prefix": "any_"},
|
||||
)
|
||||
self.assertEqual(
|
||||
table.encoders[("smZ CLIPTextEncode", 0)],
|
||||
{
|
||||
|
||||
@@ -17,8 +17,10 @@ from utils.prompt_pair_resolver import OutputAdapter, resolve_prompt_pair
|
||||
|
||||
try:
|
||||
from tests import inspection_parity as parity
|
||||
from tests import unknown_node_graphs as switch_graphs
|
||||
except ImportError: # discovered with ``-s tests``
|
||||
import inspection_parity as parity
|
||||
import unknown_node_graphs as switch_graphs
|
||||
|
||||
|
||||
def graph(positive: str = "portrait", negative: str = "blurry") -> dict:
|
||||
@@ -1671,6 +1673,173 @@ class TestConditioningSemantics(unittest.TestCase):
|
||||
self.assertIsNone(result["reason_code"])
|
||||
|
||||
|
||||
class TestFirstPresentSelector(unittest.TestCase):
|
||||
"""rgthree Any Switch: the first input proven to hold a value wins (#657).
|
||||
|
||||
Graphs are the sweep shape (``unknown_node_graphs.any_switch_sweep_graph``)
|
||||
with neutral texts: PromptManagerText 12, StringConcatenate 13 (a stacker's
|
||||
trigger text, then 12), Any Switch 14, encoder 15, KSampler 26.
|
||||
"""
|
||||
|
||||
SHAPES = switch_graphs.first_present_shapes()
|
||||
JOINED = f"{switch_graphs.SWEEP_PREFIX}, {switch_graphs.POSITIVE}"
|
||||
|
||||
def shape(self, name, **options):
|
||||
return _inspect(self.SHAPES[name], **options)
|
||||
|
||||
def candidates(self, result):
|
||||
return [
|
||||
(item["state"], _role_text_of(item, "positive"))
|
||||
for item in result["candidates"]
|
||||
]
|
||||
|
||||
def assertResolved(self, result, positive):
|
||||
self.assertEqual(result["state"], "resolved", result["reason"])
|
||||
self.assertEqual(_sides(result), (positive, switch_graphs.NEGATIVE))
|
||||
|
||||
def test_the_sweep_graph_resolves_to_the_prompt_manager_text(self):
|
||||
result = self.shape("sweep")
|
||||
self.assertResolved(result, switch_graphs.POSITIVE)
|
||||
self.assertEqual(result["sampler_id"], "26")
|
||||
path = [step["node_id"] for step in result["positive"]["provenance"]["path"]]
|
||||
self.assertEqual(path, ["15", "14", "12"])
|
||||
|
||||
def test_the_sweep_graph_was_ambiguous_without_the_table_entry(self):
|
||||
table = inspection_semantics.get_semantics()
|
||||
selectors = {
|
||||
name: entry
|
||||
for name, entry in table.selectors.items()
|
||||
if name != "Any Switch (rgthree)"
|
||||
}
|
||||
without = replace(
|
||||
table,
|
||||
selectors=selectors,
|
||||
all_classes=table.all_classes - {"Any Switch (rgthree)"},
|
||||
)
|
||||
with mock.patch.object(resolver, "_inspection_semantics", return_value=without):
|
||||
result = self.shape("sweep")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(result["reason"], resolver.SEVERAL_SOURCES_REASON)
|
||||
|
||||
def test_ingestion_still_cannot_read_the_switch(self):
|
||||
result = resolve_prompt_pair({"prompt": self.SHAPES["sweep"]})
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
|
||||
def test_a_proven_first_input_resolves_to_that_input(self):
|
||||
for name, positive in (
|
||||
("through-reroute", switch_graphs.POSITIVE),
|
||||
("through-primitive", switch_graphs.OTHER),
|
||||
("through-encoder-chain", switch_graphs.OTHER),
|
||||
("literal-text", "literal words"),
|
||||
):
|
||||
with self.subTest(name):
|
||||
self.assertResolved(self.shape(name), positive)
|
||||
|
||||
def test_an_unproven_first_input_offers_each_input(self):
|
||||
result = self.shape("through-unknown")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(result["reason"], resolver.SELECTOR_BRANCHES_REASON)
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("resolved", switch_graphs.POSITIVE), ("resolved", self.JOINED)],
|
||||
)
|
||||
|
||||
def test_a_run_time_first_input_is_never_replaced_by_prompt_manager(self):
|
||||
# rgthree outputs the generated text, not the PromptManager text.
|
||||
result = self.shape("runtime-first")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
self.candidates(result),
|
||||
[("unresolved", None), ("resolved", switch_graphs.POSITIVE)],
|
||||
)
|
||||
self.assertEqual(result["candidates"][0]["reason_code"], "runtime-value")
|
||||
|
||||
def test_inputs_with_one_text_need_no_choice(self):
|
||||
self.assertResolved(self.shape("same-text"), switch_graphs.OTHER)
|
||||
|
||||
def test_a_literal_for_conditioning_is_malformed(self):
|
||||
result = self.shape("literal-conditioning")
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
self.assertEqual(result["reason_code"], "malformed")
|
||||
|
||||
def test_one_participating_input_is_traced_as_usual(self):
|
||||
self.assertResolved(self.shape("one-input-unknown"), switch_graphs.POSITIVE)
|
||||
# An input set to null is not passed on (rgthree skips None).
|
||||
self.assertResolved(self.shape("null-first"), self.JOINED)
|
||||
|
||||
def test_no_participating_input_is_malformed(self):
|
||||
result = self.shape("no-input")
|
||||
self.assertEqual(result["state"], "unresolved")
|
||||
self.assertEqual(result["reason_code"], "malformed")
|
||||
|
||||
def test_a_selector_upstream_gives_one_result_per_choice(self):
|
||||
result = self.shape("selector-upstream")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
[text for _, text in self.candidates(result)],
|
||||
[switch_graphs.OTHER, self.JOINED, switch_graphs.POSITIVE, self.JOINED],
|
||||
)
|
||||
|
||||
def test_a_switch_never_proves_a_value(self):
|
||||
result = self.shape("nested-switch")
|
||||
self.assertEqual(result["state"], "ambiguous")
|
||||
self.assertEqual(
|
||||
[text for _, text in self.candidates(result)],
|
||||
[switch_graphs.POSITIVE, switch_graphs.OTHER],
|
||||
)
|
||||
|
||||
def test_a_limit_on_the_first_input_is_that_limit(self):
|
||||
result = self.shape("depth-limit")
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "depth-limit")
|
||||
)
|
||||
long = switch_graphs.switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": {"class_type": "VendorPassText", "inputs": {"src": ["31", 0]}},
|
||||
"31": _primitive("x" * 50),
|
||||
"32": _primitive("short"),
|
||||
},
|
||||
)
|
||||
result = _inspect(long, max_text_length=20)
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "text-limit")
|
||||
)
|
||||
chain = switch_graphs.switched(
|
||||
{"any_01": ["r0", 0], "any_02": ["32", 0]},
|
||||
**switch_graphs._reroutes(30, 0, ["12", 0]),
|
||||
**{"32": _primitive("short")},
|
||||
)
|
||||
result = _inspect(chain, max_visits=20)
|
||||
self.assertEqual(
|
||||
(result["state"], result["reason_code"]), ("unresolved", "work-limit")
|
||||
)
|
||||
|
||||
def test_a_pair_record_check_through_a_diverging_switch_is_unverifiable(self):
|
||||
# While a pair's execution record is checked, a switch choice cannot be
|
||||
# read statically: that input is skipped, and the record still applies.
|
||||
source = switch_graphs.switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": {"class_type": "VendorPassText", "inputs": {"src": ["31", 0]}},
|
||||
"31": _primitive(switch_graphs.OTHER),
|
||||
"32": _primitive(switch_graphs.POSITIVE),
|
||||
"60": switch_graphs.pair(text=["14", 0]),
|
||||
},
|
||||
)
|
||||
source["26"]["inputs"]["positive"] = ["60", 0]
|
||||
source["26"]["inputs"]["negative"] = ["60", 1]
|
||||
metadata = {
|
||||
"prompt": source,
|
||||
"comfyassets_prompt_pairs": switch_graphs.execution(
|
||||
"60", switch_graphs.GENERATED
|
||||
),
|
||||
}
|
||||
result = resolve_prompt_pair(metadata, profile=resolver.INSPECTION_PROFILE)
|
||||
self.assertEqual(result["state"], "resolved", result["reason"])
|
||||
self.assertEqual(_sides(result), (switch_graphs.GENERATED, ""))
|
||||
|
||||
|
||||
def _primitive(value: str) -> dict:
|
||||
return {"class_type": "PrimitiveString", "inputs": {"value": value}}
|
||||
|
||||
|
||||
@@ -164,6 +164,18 @@ def _unrelated_encoder(doc):
|
||||
)
|
||||
|
||||
|
||||
ANY_SWITCH = {"strategy": "first-present", "input_prefix": "any_"}
|
||||
|
||||
|
||||
def _without_any_switch(doc):
|
||||
"""The table before #657 listed rgthree's Any Switch."""
|
||||
del doc["selectors"]["Any Switch (rgthree)"]
|
||||
|
||||
|
||||
def _with_any_switch(doc):
|
||||
doc["selectors"]["Any Switch (rgthree)"] = dict(ANY_SWITCH)
|
||||
|
||||
|
||||
def _texts(evidence):
|
||||
return sorted(
|
||||
c["positive"]["text"]
|
||||
@@ -570,6 +582,35 @@ class TestVersionChanges(InspectionTestCase):
|
||||
self.assertEqual(status, 200, data)
|
||||
self.assertEqual(self._linked_text(path), "make it night")
|
||||
|
||||
async def test_the_any_switch_entry_moves_only_items_of_graphs_with_one(self):
|
||||
# #657: adding ``Any Switch (rgthree)`` to the table changes the class
|
||||
# projection of a graph that holds that class, and of no other graph.
|
||||
self._roots()
|
||||
self._table(_without_any_switch)
|
||||
plain = qwen_edit_graph(*PROMPTS)
|
||||
switched = {**plain, "90": {"class_type": "Any Switch (rgthree)", "inputs": {}}}
|
||||
self._write(graph=plain)
|
||||
self._write("switched_00001_.png", graph=switched)
|
||||
await self._scan()
|
||||
old = {item["locator"]: item for item in self._items()}
|
||||
self.assertEqual(len(old), 2)
|
||||
|
||||
# ``_table`` edits the table in effect: put the entry back.
|
||||
self._table(_with_any_switch)
|
||||
await self._scan("all")
|
||||
|
||||
new = {item["locator"]: item for item in self._items()}
|
||||
self.assertEqual(set(new), set(old))
|
||||
(moved,) = [locator for locator in new if "switched" in locator]
|
||||
(kept,) = [locator for locator in new if "switched" not in locator]
|
||||
self.assertEqual(new[kept]["id"], old[kept]["id"])
|
||||
self.assertEqual(new[kept]["resolver_version"], old[kept]["resolver_version"])
|
||||
self.assertNotEqual(
|
||||
new[moved]["resolver_version"], old[moved]["resolver_version"]
|
||||
)
|
||||
self.assertEqual(new[moved]["resolver_version"], _version(switched))
|
||||
self.assertEqual(self._pending(), 2)
|
||||
|
||||
async def test_unrelated_table_edit_keeps_the_item_and_does_no_work(self):
|
||||
self._roots()
|
||||
self._write()
|
||||
|
||||
@@ -323,3 +323,204 @@ def review_shapes():
|
||||
"unlinked-role-input": {"prompt": json.dumps(unlinked)},
|
||||
"one-text-twice": {"prompt": json.dumps(twice)},
|
||||
}
|
||||
|
||||
|
||||
# #657: rgthree Any Switch outputs the first ``any_*`` input that is not None.
|
||||
SWEEP_PREFIX = "<lora:style-demo:1>"
|
||||
|
||||
|
||||
def any_switch_sweep_graph():
|
||||
"""The maintainer's model-compare sweep (2026-11-19), with neutral texts.
|
||||
|
||||
PromptManagerText (12) feeds the switch's ``any_01`` directly and, joined
|
||||
after a LoraManager stacker's trigger text, its ``any_02`` (13). The switch
|
||||
(14) feeds the positive encoder (15) of KSampler 26; the negative is a plain
|
||||
CLIPTextEncode. A checkpoint iterator, a LoRA text loader and a
|
||||
model-compare sheet (all unknown classes) surround it, as in the file.
|
||||
"""
|
||||
return {
|
||||
"4": {"class_type": "SeedHistory", "inputs": {"seed": 1000}},
|
||||
"8": {"class_type": "CLIPLoader", "inputs": {"clip_name": "clip.safetensors"}},
|
||||
"9": {"class_type": "VAELoader", "inputs": {"vae_name": "vae.safetensors"}},
|
||||
"10": {
|
||||
"class_type": "EmptyLatentImage",
|
||||
"inputs": {"width": 1088, "height": 1920, "batch_size": 1},
|
||||
},
|
||||
"11": {
|
||||
"class_type": "Lora Stacker (LoraManager)",
|
||||
"inputs": {
|
||||
"text": SWEEP_PREFIX,
|
||||
"loras": [{"name": "style-demo", "strength": "1.00", "active": True}],
|
||||
},
|
||||
},
|
||||
"12": {
|
||||
"class_type": "PromptManagerText",
|
||||
"inputs": {
|
||||
"text": POSITIVE,
|
||||
"category": "",
|
||||
"tags": "",
|
||||
"search_text": "",
|
||||
"prepend_text": "",
|
||||
"append_text": "",
|
||||
"save_to_library": True,
|
||||
},
|
||||
},
|
||||
"13": {
|
||||
"class_type": "StringConcatenate",
|
||||
"inputs": {"string_a": ["11", 1], "string_b": ["12", 0], "delimiter": ", "},
|
||||
},
|
||||
"14": {
|
||||
"class_type": "Any Switch (rgthree)",
|
||||
"inputs": {"any_01": ["12", 0], "any_02": ["13", 0]},
|
||||
},
|
||||
"15": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": ["14", 0], "clip": ["8", 0]},
|
||||
},
|
||||
"16": {
|
||||
"class_type": "CLIPTextEncode",
|
||||
"inputs": {"text": NEGATIVE, "clip": ["8", 0]},
|
||||
},
|
||||
"21": {
|
||||
"class_type": "CheckpointFolderIterator",
|
||||
"inputs": {"folder": "demo", "index": 1, "model_type": "checkpoint"},
|
||||
},
|
||||
"23": {
|
||||
"class_type": "LoRA Text Loader (LoraManager)",
|
||||
"inputs": {"model": ["21", 0], "lora_syntax": ["11", 2]},
|
||||
},
|
||||
"26": {
|
||||
"class_type": "KSampler",
|
||||
"inputs": {
|
||||
"seed": ["4", 0],
|
||||
"steps": 25,
|
||||
"cfg": 2.5,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "normal",
|
||||
"denoise": 1.0,
|
||||
"model": ["23", 0],
|
||||
"positive": ["15", 0],
|
||||
"negative": ["16", 0],
|
||||
"latent_image": ["10", 0],
|
||||
},
|
||||
},
|
||||
"27": {
|
||||
"class_type": "VAEDecode",
|
||||
"inputs": {"samples": ["26", 0], "vae": ["9", 0]},
|
||||
},
|
||||
"28": {
|
||||
"class_type": "ModelCompareSheet",
|
||||
"inputs": {"run_name": "sweep", "columns": 3, "images": ["27", 0]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def switched(switch_inputs, **nodes):
|
||||
"""The sweep graph with the switch's inputs replaced and nodes added."""
|
||||
graph = with_nodes(any_switch_sweep_graph(), **nodes)
|
||||
graph["14"] = {"class_type": "Any Switch (rgthree)", "inputs": dict(switch_inputs)}
|
||||
return graph
|
||||
|
||||
|
||||
def _string(text):
|
||||
return {"class_type": "PrimitiveString", "inputs": {"value": text}}
|
||||
|
||||
|
||||
def _vendor(**inputs):
|
||||
"""An unknown node that passes its one linked input through."""
|
||||
return {"class_type": "VendorPassText", "inputs": inputs}
|
||||
|
||||
|
||||
def _reroutes(count, start, target):
|
||||
"""``count`` chained Reroutes ``r{start}..``, the last reading ``target``."""
|
||||
nodes = {}
|
||||
for index in range(count):
|
||||
upstream = target if index == count - 1 else [f"r{start + index + 1}", 0]
|
||||
nodes[f"r{start + index}"] = {
|
||||
"class_type": "Reroute",
|
||||
"inputs": {"input": upstream},
|
||||
}
|
||||
return nodes
|
||||
|
||||
|
||||
def _conditioning_switch(**switch_inputs):
|
||||
"""A switch in the sampler's positive conditioning input (any_* conditioning)."""
|
||||
graph = switched(
|
||||
switch_inputs,
|
||||
**{
|
||||
"40": encode(OTHER),
|
||||
"41": {"class_type": "FluxGuidance", "inputs": {"conditioning": ["40", 0]}},
|
||||
"42": encode(POSITIVE),
|
||||
},
|
||||
)
|
||||
graph["26"]["inputs"]["positive"] = ["14", 0]
|
||||
return graph
|
||||
|
||||
|
||||
def first_present_shapes():
|
||||
"""One named graph per ``first-present`` rule (#657); limits are built in tests."""
|
||||
inner = {
|
||||
"class_type": "Any Switch (rgthree)",
|
||||
"inputs": {"any_01": ["12", 0], "any_02": ["13", 0]},
|
||||
}
|
||||
upstream_selector = {
|
||||
"class_type": "easy ifElse",
|
||||
"inputs": {"boolean": ["81", 0], "on_true": ["31", 0], "on_false": ["12", 0]},
|
||||
}
|
||||
return {
|
||||
"sweep": any_switch_sweep_graph(),
|
||||
"through-reroute": switched(
|
||||
{"any_01": ["30", 0], "any_02": ["13", 0]},
|
||||
**{"30": {"class_type": "Reroute", "inputs": {"input": ["12", 0]}}},
|
||||
),
|
||||
"through-primitive": switched(
|
||||
{"any_01": ["31", 0], "any_02": ["13", 0]}, **{"31": _string(OTHER)}
|
||||
),
|
||||
"through-encoder-chain": _conditioning_switch(
|
||||
any_01=["41", 0], any_02=["42", 0]
|
||||
),
|
||||
"through-unknown": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["13", 0]}, **{"50": _vendor(src=["12", 0])}
|
||||
),
|
||||
"runtime-first": switched(
|
||||
{"any_01": ["60", 0], "any_02": ["12", 0]},
|
||||
**{
|
||||
"60": {
|
||||
"class_type": "VendorTextGenerate",
|
||||
"inputs": {"prompt": "x", "seed": 3},
|
||||
}
|
||||
},
|
||||
),
|
||||
"same-text": switched(
|
||||
{"any_01": ["50", 0], "any_02": ["32", 0]},
|
||||
**{
|
||||
"50": _vendor(src=["31", 0]),
|
||||
"31": _string(OTHER),
|
||||
"32": _string(OTHER),
|
||||
},
|
||||
),
|
||||
"literal-text": switched({"any_01": "literal words", "any_02": ["12", 0]}),
|
||||
"literal-conditioning": _conditioning_switch(
|
||||
any_01="literal words", any_02=["42", 0]
|
||||
),
|
||||
"one-input-unknown": switched(
|
||||
{"any_01": ["50", 0], "other": ["13", 0]}, **{"50": _vendor(src=["12", 0])}
|
||||
),
|
||||
"no-input": switched({}),
|
||||
"null-first": switched({"any_01": None, "any_02": ["13", 0]}),
|
||||
"selector-upstream": switched(
|
||||
{"any_01": ["80", 0], "any_02": ["13", 0]},
|
||||
**{
|
||||
"80": upstream_selector,
|
||||
"81": {"class_type": "PrimitiveBoolean", "inputs": {"value": True}},
|
||||
"31": _string(OTHER),
|
||||
},
|
||||
),
|
||||
"nested-switch": switched(
|
||||
{"any_01": ["90", 0], "any_02": ["31", 0]},
|
||||
**{"90": inner, "31": _string(OTHER)},
|
||||
),
|
||||
"depth-limit": switched(
|
||||
{"any_01": ["r0", 0], "any_02": ["13", 0]}, **_reroutes(70, 0, ["12", 0])
|
||||
),
|
||||
}
|
||||
|
||||
@@ -30,6 +30,14 @@ 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
|
||||
@@ -56,7 +64,7 @@ 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"}),
|
||||
"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"}),
|
||||
@@ -64,6 +72,11 @@ STRATEGIES: Mapping[str, FrozenSet[str]] = MappingProxyType(
|
||||
"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(
|
||||
@@ -244,6 +257,11 @@ def _check_guider(entry: dict, strategy: str, where: str) -> None:
|
||||
|
||||
|
||||
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"]
|
||||
|
||||
@@ -221,6 +221,11 @@ _PASSED_UNVERIFIABLE = "Text passed through an unknown node is not verifiable"
|
||||
_CONDITIONING_INPUTS = ("conditioning", "positive", "negative")
|
||||
# The first item of a pass-through divergence's 3-tuple choice key.
|
||||
_PASS_THROUGH = "pass-through"
|
||||
# The divergence tag of a ``first-present`` switch (#657): its key is
|
||||
# ``(_FIRST_PRESENT, node ID, slot)``, apart from selector and pass-through keys.
|
||||
_FIRST_PRESENT = "first-present"
|
||||
_NO_SWITCH_INPUT = "Switch has no connected input"
|
||||
_SWITCH_UNVERIFIABLE = "Switch output is not verifiable"
|
||||
# Uncoded outcomes the inspector explains by their exact reason.
|
||||
EMPTY_POSITIVE_REASON = "Positive prompt is empty"
|
||||
# Several sampler branches, every one resolved to the same pair (#249).
|
||||
@@ -837,7 +842,10 @@ class _GraphResolver:
|
||||
self.inherit_source(node_id, slot, [traced[1]])
|
||||
return traced
|
||||
if name in semantics.selectors:
|
||||
return self.select(node_id, semantics.selectors[name], inputs, kind, depth)
|
||||
entry = semantics.selectors[name]
|
||||
if entry["strategy"] == "first-present":
|
||||
return self.first_present(node_id, entry, inputs, kind, depth)
|
||||
return self.select(node_id, entry, inputs, kind, depth)
|
||||
parts = [
|
||||
self.text(inputs.get(input_name), kind, depth + 1)
|
||||
for input_name in semantics.composites[name]["inputs"]
|
||||
@@ -881,6 +889,66 @@ class _GraphResolver:
|
||||
raise _Diverging((str(condition[0]), condition[1]), (True, False))
|
||||
return self.merged(node_id, 0, parts)
|
||||
|
||||
def first_present(
|
||||
self, node_id: str, entry: Mapping, inputs: dict, kind: str, depth: int
|
||||
) -> Tuple[str, list, str]:
|
||||
"""rgthree Any Switch: the first ``input_prefix`` input that is not None.
|
||||
|
||||
The inputs take part in the order of ``inputs`` (ComfyUI's call order);
|
||||
a missing or null one is not passed on. A file exists, so one of them
|
||||
held a value. The first is the output when it is a literal or its
|
||||
traced path proves a value (``proves_value``). Otherwise every input
|
||||
is a choice, unless all of them trace to one text. Limits and upstream
|
||||
divergences propagate; a failed choice becomes an unresolved candidate.
|
||||
Nothing prefers a PromptManager path: a run-time first input may be
|
||||
what rgthree output.
|
||||
"""
|
||||
prefix = entry["input_prefix"]
|
||||
values = [
|
||||
value
|
||||
for name, value in inputs.items()
|
||||
if name.startswith(prefix) and value is not None
|
||||
]
|
||||
if not values:
|
||||
raise _Unresolved(_NO_SWITCH_INPUT, "malformed")
|
||||
key = (_FIRST_PRESENT, node_id, 0)
|
||||
if len(values) == 1 or not _link(values[0]):
|
||||
chosen = values[0]
|
||||
elif key in self.choices:
|
||||
self.tainted = True
|
||||
chosen = values[self.choices[key]]
|
||||
elif not self.verifying:
|
||||
return self.first_of(node_id, key, values, kind, depth)
|
||||
else:
|
||||
# Checking a pair's execution record: a choice is not readable
|
||||
# statically, as through an unknown node (``passed``).
|
||||
try:
|
||||
return self.first_of(node_id, key, values, kind, depth)
|
||||
except _Diverging:
|
||||
raise self.unsupported(_SWITCH_UNVERIFIABLE, node_id) from None
|
||||
traced = self.text(chosen, kind, depth + 1)
|
||||
self.inherit_source(node_id, 0, [traced[1]])
|
||||
return traced
|
||||
|
||||
def first_of(
|
||||
self, node_id: str, key: tuple, values: list, kind: str, depth: int
|
||||
) -> Tuple[str, list, str]:
|
||||
"""The first linked input when proven, one text, or one choice per input."""
|
||||
found: list = []
|
||||
for value in values:
|
||||
try:
|
||||
found.append(self.text(value, kind, depth + 1))
|
||||
except _Unresolved as error:
|
||||
if error.code in _LIMIT_CODES:
|
||||
raise
|
||||
break
|
||||
if len(found) == 1 and self.proves_value(found[0][1]):
|
||||
self.inherit_source(node_id, 0, [found[0][1]])
|
||||
return found[0]
|
||||
if len(found) == len(values) and len({part[0] for part in found}) == 1:
|
||||
return self.merged(node_id, 0, found)
|
||||
raise _Diverging(key, tuple(range(len(values))))
|
||||
|
||||
def passed(
|
||||
self, node_id: str, slot: int, kind: str, inputs: dict, depth: int
|
||||
) -> Tuple[str, list, str]:
|
||||
@@ -987,6 +1055,34 @@ class _GraphResolver:
|
||||
self.scan(len(path))
|
||||
return any(self.node(step["node_id"])[0] not in self.described for step in path)
|
||||
|
||||
def proves_value(self, path: list) -> bool:
|
||||
"""Whether every node on a followed path always outputs a value (#657).
|
||||
|
||||
PromptManager and code-traced classes, the default adapters and the
|
||||
table's ``PROVEN_VALUE_CATEGORIES``; class-keyed sets by class, slot-keyed
|
||||
ones by ``(class, output slot)``.
|
||||
"""
|
||||
self.scan(len(path))
|
||||
semantics = self.semantics
|
||||
for step in path:
|
||||
name, slot = self.node(step["node_id"])[0], step["output_slot"]
|
||||
if name in _OWN_CLASSES or name in _CODED_CLASSES:
|
||||
continue
|
||||
if name in semantics.composites:
|
||||
continue
|
||||
output = (name, slot)
|
||||
if output in _DEFAULT_ADAPTERS or any(
|
||||
output in table
|
||||
for table in (
|
||||
semantics.encoders,
|
||||
semantics.strings,
|
||||
semantics.conditioning,
|
||||
)
|
||||
):
|
||||
continue
|
||||
return False
|
||||
return True
|
||||
|
||||
def owned(self, path: list) -> bool:
|
||||
"""Whether a followed path passes through one of this repository's nodes."""
|
||||
self.scan(len(path))
|
||||
|
||||
@@ -471,7 +471,7 @@
|
||||
"ControlNetInpaintingAliMamaApply", "LTXVConditioning", "FluxKontextMultiReferenceLatentMethod", "Text to Conditioning",
|
||||
"TextInput", "DisplayText", "ClownsharKSampler_Beta", "KSampler (Efficient)", "ttN KSampler_v2",
|
||||
"SeedVarianceEnhancer", "ApplyInstantIDAdvanced", "Switch conditioning [Crystools]", "smZ CLIPTextEncode", "ttN text",
|
||||
"CR Text", "CR Prompt Text", "TextBoxMira",
|
||||
"CR Text", "CR Prompt Text", "TextBoxMira", "Any Switch (rgthree)",
|
||||
]);
|
||||
// The table's `stage_inputs` (the resolver reads the same lists): inputs that make an
|
||||
// unlisted node a possible stage, and those that do so beside a linked `model`.
|
||||
|
||||
@@ -121,7 +121,8 @@
|
||||
"strategy": "boolean-select",
|
||||
"condition": "boolean",
|
||||
"branches": { "true": "on_true", "false": "on_false" }
|
||||
}
|
||||
},
|
||||
"Any Switch (rgthree)": { "strategy": "first-present", "input_prefix": "any_" }
|
||||
},
|
||||
"composites": {
|
||||
"ConditioningCombine": { "strategy": "combine", "inputs": ["conditioning_1", "conditioning_2"], "additive": true },
|
||||
|
||||
@@ -35,6 +35,14 @@ export const SELECTOR_BRANCHES_REASON = 'Selector branches have different prompt
|
||||
// Failures that bound the work: never skipped by a pass-through walk (`_LIMIT_CODES`).
|
||||
export const PASS_LIMIT_CODES = new Set(['work-limit', 'depth-limit', 'text-limit']);
|
||||
export const PASS_THROUGH = 'pass-through';
|
||||
// #657: the divergence tag of a `first-present` switch (rgthree Any Switch), apart from selector and pass-through keys.
|
||||
export const FIRST_PRESENT = 'first-present';
|
||||
export const NO_SWITCH_INPUT = 'Switch has no connected input';
|
||||
export const SWITCH_UNVERIFIABLE = 'Switch output is not verifiable';
|
||||
// `PROVEN_VALUE_CATEGORIES` (inspection_semantics.py): outputs never None, so a path through them proves a value.
|
||||
export const PROVEN_VALUE_CATEGORIES = Object.freeze(['encoders', 'strings', 'conditioning', 'composites']);
|
||||
// `_NAME_LENGTH` (inspection_semantics.py), in code points.
|
||||
export const NAME_LENGTH = 128;
|
||||
export const PASSED_UNVERIFIABLE = 'Text passed through an unknown node is not verifiable';
|
||||
// Classes traced by code, not by the table (`_CODED_CLASSES`).
|
||||
export const CODED_CLASSES = ['Reroute', 'StringConcatenate', 'Text Concatenate'];
|
||||
@@ -247,6 +255,14 @@ export function compileSemantics(doc) {
|
||||
return set;
|
||||
};
|
||||
const samplers = byClass('samplers'), guiders = byClass('guiders'), selectors = byClass('selectors');
|
||||
// `_check_selector`: a `first-present` entry has exactly `strategy` and a non-empty `input_prefix` (#657).
|
||||
for (const [name, entry] of selectors) {
|
||||
if (entry.strategy !== 'first-present') continue;
|
||||
const keys = Object.keys(entry).sort();
|
||||
if (keys.length !== 2 || keys[0] !== 'input_prefix' || keys[1] !== 'strategy') fail(`selectors[${name}] fields`);
|
||||
const prefix = entry.input_prefix;
|
||||
if (typeof prefix !== 'string' || !prefix || pyLen(prefix) > NAME_LENGTH) fail(`selectors[${name}] input prefix`);
|
||||
}
|
||||
const composites = byClass('composites'), savers = byClass('savers');
|
||||
const conditioning = bySlot('conditioning'), encoders = bySlot('encoders'), strings = bySlot('strings');
|
||||
const runtime = bySet('runtime'), nonFileOutputs = bySet('non_file_outputs');
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Diverging,
|
||||
EMPTY_POSITIVE,
|
||||
EMPTY_POSITIVE_REASON,
|
||||
FIRST_PRESENT,
|
||||
GUIDER_ABSENT_REASON,
|
||||
INCOMPATIBLE_SLOT,
|
||||
MALFORMED_EVIDENCE_REASON,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
MAX_JOIN_INPUTS,
|
||||
MAX_SUBGRAPH_DEPTH,
|
||||
MAX_WORKFLOW_NODES,
|
||||
NO_SWITCH_INPUT,
|
||||
CODED_CLASSES,
|
||||
NO_SAMPLER_NAMES,
|
||||
OWN_CLASSES,
|
||||
@@ -30,6 +32,7 @@ import {
|
||||
PASS_THROUGH,
|
||||
SELECTOR_BRANCHES_REASON,
|
||||
SEVERAL_SOURCES_REASON,
|
||||
SWITCH_UNVERIFIABLE,
|
||||
PASSED_UNVERIFIABLE,
|
||||
OVERWRITTEN_PROMPT_REASON,
|
||||
PROFILE,
|
||||
@@ -294,7 +297,11 @@ class GraphResolver {
|
||||
this.inheritSource(nodeId, slot, [traced[1]]);
|
||||
return traced;
|
||||
}
|
||||
if (semantics.selectors.has(name)) return this.select(nodeId, semantics.selectors.get(name), inputs, kind, depth);
|
||||
if (semantics.selectors.has(name)) {
|
||||
const selector = semantics.selectors.get(name);
|
||||
if (selector.strategy === 'first-present') return this.firstPresent(nodeId, selector, inputs, kind, depth);
|
||||
return this.select(nodeId, selector, inputs, kind, depth);
|
||||
}
|
||||
const parts = semantics.composites.get(name).inputs.map(inputName => this.text(pyGet(inputs, inputName), kind, depth + 1));
|
||||
if (new Set(parts.map(part => part[0])).size !== 1) throw this.named('Combined conditioning has different texts', 'composite', nodeId);
|
||||
return this.merged(nodeId, slot, parts);
|
||||
@@ -319,6 +326,55 @@ class GraphResolver {
|
||||
return this.merged(nodeId, 0, parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* `first_present` (#657, rgthree Any Switch): the first `input_prefix` input that is not null. A literal first input,
|
||||
* or the only one, is the output; a forced choice (re-resolve) takes its input; otherwise `firstOf` decides. While an
|
||||
* execution record is checked, a choice is unverifiable (as `passed`).
|
||||
*/
|
||||
firstPresent(nodeId, entry, inputs, kind, depth) {
|
||||
const prefix = entry.input_prefix;
|
||||
const values = [...inputs].filter(([name, value]) => name.startsWith(prefix) && value !== null).map(([, value]) => value);
|
||||
if (!values.length) throw new Unresolved(NO_SWITCH_INPUT, 'malformed');
|
||||
// JSON escapes U+0000, so this never equals a selector's raw `slotKey` (Python: a 3-tuple vs a 2-tuple).
|
||||
const key = JSON.stringify([FIRST_PRESENT, nodeId, 0]);
|
||||
let chosen;
|
||||
if (values.length === 1 || !isLink(values[0])) chosen = values[0];
|
||||
else if (this.choices.has(key)) {
|
||||
this.tainted = true;
|
||||
chosen = values[this.choices.get(key)];
|
||||
} else if (!this.verifying) return this.firstOf(nodeId, key, values, kind, depth);
|
||||
else {
|
||||
try {
|
||||
return this.firstOf(nodeId, key, values, kind, depth);
|
||||
} catch (error) {
|
||||
if (error instanceof Diverging) throw this.unsupported(SWITCH_UNVERIFIABLE, nodeId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const traced = this.text(chosen, kind, depth + 1);
|
||||
this.inheritSource(nodeId, 0, [traced[1]]);
|
||||
return traced;
|
||||
}
|
||||
|
||||
/** `first_of`: the first linked input when its path proves a value, one shared text, or one choice per input. */
|
||||
firstOf(nodeId, key, values, kind, depth) {
|
||||
const found = [];
|
||||
for (const value of values) {
|
||||
try {
|
||||
found.push(this.text(value, kind, depth + 1));
|
||||
} catch (error) {
|
||||
if (!(error instanceof Unresolved) || PASS_LIMIT_CODES.has(error.code)) throw error;
|
||||
break;
|
||||
}
|
||||
if (found.length === 1 && this.provesValue(found[0][1])) {
|
||||
this.inheritSource(nodeId, 0, [found[0][1]]);
|
||||
return found[0];
|
||||
}
|
||||
}
|
||||
if (found.length === values.length && new Set(found.map(part => part[0])).size === 1) return this.merged(nodeId, 0, found);
|
||||
throw new Diverging(key, values.map((_, index) => index));
|
||||
}
|
||||
|
||||
/** `passed`: `readThrough`, except that while an execution record is checked any outcome but `work-limit` is unverifiable. */
|
||||
passed(nodeId, slot, kind, inputs, depth) {
|
||||
if (!this.verifying) return this.readThrough(nodeId, slot, kind, inputs, depth);
|
||||
@@ -417,6 +473,17 @@ class GraphResolver {
|
||||
return path.some(step => !this.described.has(this.node(step.node_id)[0]));
|
||||
}
|
||||
|
||||
/** `proves_value` (#657): every node on the path always outputs a value (own, coded, adapter or proven-category classes). */
|
||||
provesValue(path) {
|
||||
this.scan(path.length);
|
||||
const semantics = this.semantics;
|
||||
return path.every(step => {
|
||||
const name = this.node(step.node_id)[0], key = slotKey(name, step.output_slot);
|
||||
if (OWN_CLASSES.has(name) || CODED_CLASSES.includes(name) || semantics.composites.has(name)) return true;
|
||||
return ADAPTERS.has(key) || semantics.encoders.has(key) || semantics.strings.has(key) || semantics.conditioning.has(key);
|
||||
});
|
||||
}
|
||||
|
||||
/** `owned`: whether a followed path passes through one of this repository's nodes. */
|
||||
owned(path) {
|
||||
this.scan(path.length);
|
||||
|
||||
Reference in New Issue
Block a user