diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index cb40d28cd..32899d01d 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -427,6 +427,21 @@ comfy --json workflow apply wf.json --ops ops.json $CAT # or --ops - to read s # → data.ops[] (all minted ids), data.aliases{ckpt,ks}. Atomic: nothing writes if any spec fails. ``` +**Adding, removing or reordering DynamicGroup rows** (e.g. a LoRA stack's `loras`): +send the desired row list in one `set_dynamic_group_rows` spec instead of +editing the count and numbered fields separately. Omitted fields take the template +default (a combo without one takes its first option, so name the LoRA explicitly; a field with no default at all must be supplied); a seed field's control mode is +`".0"` in the row. A row with a connected or promoted field keeps its index and +values; leave it out of `rows`, which fill the other positions in order, so the batch +fails if that row would have to move. Do not write the same group elsewhere in the batch. +Links are checked when the workflow is read: a link added to a row after that read is +not rechecked, so the spec can rewrite that row under its link. + +```json +{"op":"set_dynamic_group_rows","node":12,"group":"loras", + "rows":[{"lora_name":"style.safetensors","strength":0.8},{"lora_name":"detail.safetensors"}]} +``` + **Reusable recipes (the reuse path — prefer this over fragments/compose).** A recipe is an ops file with a `params` header and `${param}` holes: diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index 08da921fd..9c1e33c05 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -815,6 +815,149 @@ def set_widget( raise _enrich_resolution_error(e, workflow, graph, widget=widget) from e +def set_dynamic_group_rows( + workflow: dict, + graph, + node_id: Any, + group: str, + rows: Any, + *, + actor: str = "cli", + base_version: int = 0, +) -> tuple[dict, list[dict]]: + """Replace a DynamicGroup's rows with ``rows``, expressed as ordinary + ``set_widget`` ops: the row count first, then every widget of each written + row, including a field's ``.0`` control mode. Omitted widgets take + the template default. + + A row with a connected or promoted field keeps its index and values and + is left out of ``rows``, which fill the other positions in order. Links + are never moved, so ``rows`` must cover every free position before the + last pinned row. + + The writes run on a copy, so ``workflow`` is unchanged when any is refused. + The ops share one stamp, so an earlier write to the group at the same + stamp is refused rather than left to the ``op_id`` tiebreak (revisit once + #1007 makes the later write in a batch win). ``apply_op`` must replay them + in order, because this workflow model materializes rows from the count. + """ + from comfy_cli.cql import engine as _engine + from comfy_cli.cql import promoted as _promoted + + workflow = copy.deepcopy(workflow) + node_id = _template_id(workflow, node_id, graph) + target = _resolve_widget_write(workflow, graph, node_id, group) + if target.kind == "top" and target.redirected_from is None: + node = target.node + segments = [str(node.get("id"))] + elif target.kind == "interior" and target.redirected_from is None: + node = _promoted._navigate(workflow, target.segments, _promoted.defs_by_id(workflow)) + segments = target.segments + else: + raise ValueError( + f"{group}: replace rows on the node that owns the DynamicGroup, not a promoted or linked address" + ) + m = graph.node(node.get("type", "")) + port = next((p for p in m.inputs if p.name == group and p.is_dynamic_group), None) if m else None + if port is None: + raise ValueError(f"{group!r} is not a DynamicGroup on node {node_id}") + if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows): + raise ValueError(f"{group}: rows must be a list of objects keyed by row field") + widgets = _engine._dynamic_group_widgets(port) + names = [widget.name for widget in widgets] + for i, row in enumerate(rows): + unknown = [key for key in row if key not in names] + if unknown: + raise ValueError(f"{group}: rows[{i}] has unknown field(s) {unknown}; row fields: {', '.join(names)}") + for widget in widgets: + if widget.name not in row and _engine._widget_default(widget) is None: + raise ValueError(f"{group}: field {widget.name!r} has no default; supply it in rows[{i}]") + + entries = _engine._validate_dynamic_group_layout(node, m) or [] + current = sum(1 for e in entries if e.owner == group) // len(widgets) + linked = set() + for inp in node.get("inputs") or []: + if isinstance(inp, dict) and inp.get("link") is not None: + widget = inp.get("widget") + linked.update( + name + for name in (inp.get("name"), widget.get("name") if isinstance(widget, dict) else None) + if isinstance(name, str) + ) + fields = [field.name for field in _engine._dynamic_group_fields(port)] + + def pin_reason(row: int) -> str | None: + # A link, or a promotion whose write lands on the host (a subgraph + # input or a legacy proxyWidgets entry), owns the row's value. + for name in fields: + address = f"{group}.{row}.{name}" + try: + target = _promoted.resolve_write(workflow, graph, segments, address) + except ValueError: # fed by another interior node: a plain link + target = None + if target is not None and (target.redirected_from or target.kind not in ("top", "interior")): + return "is promoted to the parent subgraph; unpromote it first" + if address in linked: + return "is connected; disconnect it first" + return None + + pinned = {r: reason for r in range(current) if (reason := pin_reason(r))} + last = max(pinned, default=None) + free_before_last = last + 1 - len(pinned) if pinned else 0 + if len(rows) < free_before_last: + raise ValueError( + f"{group}.{last} keeps its position and is left out of rows; supply at least " + f"{free_before_last} row(s), or {group}.{last} {pinned[last]}" + ) + maximum = port.options.max if port.options.max is not None else 20 + if len(rows) + len(pinned) > maximum: + raise ValueError( + f"{group}: {len(rows)} row(s) plus {len(pinned)} connected or promoted row(s) exceed the maximum of {maximum}" + ) + supplied = iter(rows) + plan = [None if index in pinned else next(supplied) for index in range(len(rows) + len(pinned))] + for index in range(current, len(plan)): + # A shrink can leave a link on an input it did not match by name. + if any(f"{group}.{index}.{name}" in linked for name in fields): + raise ValueError(f"{group}.{index} still has a link from an earlier row; disconnect it first") + address = "/".join(segments) if len(segments) > 1 else node_id + where = segments if len(segments) > 1 else str(node_id) + stamps = workflow.get("_widget_stamps") or {} + claimed = [group] + [ + f"{group}.{i}.{w.name}" + for i in range(max(len(plan), current)) + if i >= len(plan) or plan[i] is not None + for w in widgets + ] + for written in claimed: + prior = stamps.get(json.dumps(["widget", where, written])) + if prior is not None and list(prior[:2]) >= [base_version, actor]: + raise ValueError( + f"{group}: {written} is already written at stamp [{prior[0]}, {prior[1]}]; write the group once " + f"per batch (a stamp left by an earlier apply needs a higher base_version)" + ) + + # The address is resolved, so skip set_widget's retry on another node. + workflow, op = _set_widget_impl(workflow, graph, address, group, len(plan), actor=actor, base_version=base_version) + ops = [op] + for index, row in enumerate(plan): + if row is None: + continue + for widget in widgets: + value = row[widget.name] if widget.name in row else _engine._widget_default(widget) + workflow, op = _set_widget_impl( + workflow, + graph, + address, + f"{group}.{index}.{widget.name}", + value, + actor=actor, + base_version=base_version, + ) + ops.append(op) + return workflow, ops + + def _inserted_node_id(workflow: dict, node_id: Any) -> str | None: """The top-level ``insert::root:node:`` node a bare template id means. @@ -2752,6 +2895,7 @@ def apply_specs( pre_batch_hint = _available_nodes_hint(workflow) aliases: dict[str, Any] = {} ops: list[dict] = [] + replaced: dict[tuple, bool] = {} input_targets: set[str] = set() try: for i, spec in enumerate(specs): @@ -2815,6 +2959,19 @@ def apply_specs( actor=actor, base_version=base_version, ) + elif kind == "set_dynamic_group_rows": + workflow, row_ops = set_dynamic_group_rows( + workflow, + graph, + resolve_ref(spec["node"], aliases), + spec["group"], + spec["rows"], + actor=actor, + base_version=base_version, + ) + ops.extend(row_ops) + replaced.update({_write_target(row_op): row_op is row_ops[0] for row_op in row_ops}) + continue elif kind == "set_node_field": workflow, op = set_node_field( workflow, @@ -2837,6 +2994,19 @@ def apply_specs( raise ValueError(f"spec #{i}: unknown op {kind!r}") except KeyError as e: raise ValueError(f"spec #{i} ({kind}) is missing required field {e}") from e + # A later write at the batch's stamp would tie with the replacement + # and be settled by the random op_id. Revisit once #1007 makes the + # later write in a batch win. + target = _write_target(op) if op.get("op") == "set_widget" else None + if target in replaced: + raise ValueError( + f"spec #{i}: {target[2]} was replaced earlier in this batch by set_dynamic_group_rows; " + + ( + "change the number of rows in that spec instead" + if replaced[target] + else "put the value in its rows instead" + ) + ) if kind in {"connect", "disconnect"}: grow = op.get("grow") if grow is not None and not grow.get("promoted"): diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index 776be39ec..eb4e265c9 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -42,6 +42,15 @@ atomically with its own registered error code — `workflow_clear_not_batchable` / `workflow_reset_doc_not_batchable` — and a hint naming the standalone command. Nothing from such a batch is applied. +`set_dynamic_group_rows` is a batch spec, not an op kind. It replaces a +DynamicGroup's rows (`{"op": "set_dynamic_group_rows", "node": ..., "group": +"loras", "rows": [{...}]}`) and emits only `set_widget` ops: the row count, then +every widget of each written row, including a field's `.0` control mode. +Rows with a connected or promoted field keep their index, are not rewritten, and +are left out of `rows`. comfy-cli's `apply_op` replays these in order because its +workflow model materializes rows from the count; the shared document accepts them +in any order. An earlier write to the group in the same batch is refused. + Every op carries the common envelope stamped by `_new_op`: ```json diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index 908ca9166..a124f1f88 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1,5 +1,6 @@ import copy import json +import re from pathlib import Path import pytest @@ -1072,6 +1073,345 @@ def test_dynamic_group_prompt_validation_checks_only_submitted_rows(inputs, mini assert error_field in {error["field"] for error in result["errors"]} +def _replace_rows(workflow, rows, node=1): + graph = Graph.from_object_info(FIXTURE["object_info"]) + return workflow_ops.apply_specs( + workflow, graph, [{"op": "set_dynamic_group_rows", "node": node, "group": "loras", "rows": rows}] + ) + + +def _replay(ops): + graph = Graph.from_object_info(FIXTURE["object_info"]) + replayed = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + for op in ops: + workflow_ops.apply_op(replayed, op, graph) + return replayed + + +def test_group_row_replacement_rewrites_every_row_as_set_widget_ops(): + rows = [ + {"lora_name": "B.safetensors", "strength": 0.3}, + {"lora_name": "A.safetensors"}, + {"lora_name": "C.safetensors", "enabled": False}, + ] + edited, ops, _ = _replace_rows(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), rows) + + assert {op["op"] for op in ops} == {"set_widget"} + assert (ops[0]["widget"], ops[0]["value"]) == ("loras", 3) + assert [op["widget"] for op in ops[1:]] == [ + f"loras.{r}.{f}" for r in range(3) for f in ("lora_name", "strength", "enabled") + ] + assert workflow_to_api.convert_ui_to_api(edited, FIXTURE["object_info"])["1"]["inputs"] == { + "before": "head", + "loras.0.lora_name": "B.safetensors", + "loras.0.strength": 0.3, + "loras.0.enabled": True, + "loras.1.lora_name": "A.safetensors", + "loras.1.strength": 1.0, + "loras.1.enabled": True, + "loras.2.lora_name": "C.safetensors", + "loras.2.strength": 1.0, + "loras.2.enabled": False, + "after": "tail", + } + assert workflow_ops.canonical(_replay(ops)) == workflow_ops.canonical(edited) + + +def test_group_row_replacement_removes_a_middle_row_without_index_ops(): + rows = [{"lora_name": "C.safetensors", "strength": 0.5, "enabled": False}] + edited, ops, _ = _replace_rows(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), rows) + + assert edited["nodes"][0]["widgets_values"] == ["head", 1, "C.safetensors", 0.5, False, "tail"] + assert workflow_ops.canonical(_replay(ops)) == workflow_ops.canonical(edited) + + +def test_group_row_replacement_keeps_a_connected_row_in_place(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4]["link"] = 10 + + edited, ops, _ = _replace_rows(workflow, [{"lora_name": "B.safetensors"}, {"lora_name": "A.safetensors"}]) + + assert edited["nodes"][0]["widgets_values"] == [ + "head", 3, "B.safetensors", 1.0, True, "C.safetensors", 0.5, False, "A.safetensors", 1.0, True, "tail", + ] # fmt: skip + assert not any(op["widget"].startswith("loras.1.") for op in ops) + assert edited["nodes"][0]["inputs"][4] == {**workflow["nodes"][0]["inputs"][4], "link": 10} + + +def test_group_row_replacement_refuses_to_move_a_connected_row(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4]["link"] = 10 + original = copy.deepcopy(workflow) + + with pytest.raises(ValueError, match=r"loras\.1 is connected; disconnect it first"): + _replace_rows(workflow, []) + assert workflow == original + + +@pytest.mark.parametrize( + ("rows", "match"), + [ + ([{"lora": "A.safetensors"}], "unknown field"), + ({"lora_name": "A.safetensors"}, "list of objects"), + ([{"lora_name": "A.safetensors"}] * 4, "exceed the maximum of 3"), + ([{"lora_name": "A.safetensors", "strength": 5}], "strength"), + ], +) +def test_group_row_replacement_refuses_invalid_rows(rows, match): + with pytest.raises(ValueError, match=match): + _replace_rows(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), rows) + + +def test_group_row_replacement_edits_an_interior_node(): + node = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]["nodes"][0]) + workflow = { + "last_node_id": 9, + "last_link_id": 0, + "nodes": [{"id": 9, "type": "group-def", "pos": [0, 0], "inputs": [], "outputs": []}], + "links": [], + "definitions": { + "subgraphs": [ + {"id": "group-def", "name": "Group", "inputs": [], "outputs": [], "nodes": [node], "links": []} + ] + }, + } + + edited, ops, _ = _replace_rows(workflow, [{"lora_name": "B.safetensors"}], node="9/1") + + interior = edited["definitions"]["subgraphs"][0]["nodes"][0] + assert interior["widgets_values"] == ["head", 1, "B.safetensors", 1.0, True, "tail"] + assert all(op.get("path") == ["9", "1"] for op in ops) + + +def _group_in_subgraph(properties=None): + node = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]["nodes"][0]) + return { + "last_node_id": 9, + "last_link_id": 0, + "nodes": [ + {"id": 9, "type": "group-def", "pos": [0, 0], "inputs": [], "outputs": [], "properties": properties or {}} + ], + "links": [], + "definitions": { + "subgraphs": [ + {"id": "group-def", "name": "Group", "inputs": [], "outputs": [], "nodes": [node], "links": []} + ] + }, + } + + +def test_group_row_replacement_leaves_a_direct_caller_unchanged_on_a_refused_value(): + graph = Graph.from_object_info(FIXTURE["object_info"]) + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + original = copy.deepcopy(workflow) + + with pytest.raises(ValueError, match="strength"): + workflow_ops.set_dynamic_group_rows( + workflow, graph, 1, "loras", [{"lora_name": "B.safetensors"}, {"lora_name": "A.safetensors", "strength": 5}] + ) + assert workflow == original + + +def test_group_row_replacement_rewrites_seed_control_modes_with_their_rows(): + info = copy.deepcopy(FIXTURE["object_info"]) + info["DevToolsNodeWithDynamicGroup"]["input"]["required"]["loras"][1]["template"] = { + "required": {"seed": ["INT", {"default": 5, "control_after_generate": True}]} + } + graph = Graph.from_object_info(info) + workflow = copy.deepcopy(FIXTURE["cases"]["empty"]["workflow"]) + workflow, _ = workflow_ops.set_widget(workflow, graph, 1, "loras", 2) + workflow, _ = workflow_ops.set_widget(workflow, graph, 1, "loras.0.seed.0", "randomize") + + edited, ops = workflow_ops.set_dynamic_group_rows( + workflow, graph, 1, "loras", [{"seed": 7}, {"seed": 9, "seed.0": "increment"}], base_version=1 + ) + + assert edited["nodes"][0]["widgets_values"] == ["first", 2, 7, "fixed", 9, "increment", "last"] + assert [op["widget"] for op in ops] == ["loras", "loras.0.seed", "loras.0.seed.0", "loras.1.seed", "loras.1.seed.0"] + + +def test_group_row_replacement_accepts_the_template_id_of_an_inserted_node(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["id"] = "insert:op1:root:node:1" + + edited, ops, _ = _replace_rows(workflow, [{"lora_name": "B.safetensors"}]) + + assert edited["nodes"][0]["widgets_values"] == ["head", 1, "B.safetensors", 1.0, True, "tail"] + assert {op["node_id"] for op in ops} == {"insert:op1:root:node:1"} + + +@pytest.mark.parametrize("name", ["LoRA #2 strength", ["loras.1.strength"]]) +def test_group_row_replacement_pins_a_row_connected_by_widget_name_only(name): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4].update(name=name, link=10) + + with pytest.raises(ValueError, match=r"loras\.1 is connected"): + _replace_rows(workflow, []) + + +def test_group_row_replacement_pins_a_row_promoted_by_legacy_proxy_widgets(): + workflow = _group_in_subgraph({"proxyWidgets": [["1", "loras.1.strength"]]}) + + with pytest.raises(ValueError, match=r"loras\.1 is promoted to the parent subgraph; unpromote it first"): + _replace_rows(workflow, [], node="9/1") + edited, ops, _ = _replace_rows(workflow, [{"lora_name": "B.safetensors"}], node="9/1") + + interior = edited["definitions"]["subgraphs"][0]["nodes"][0] + assert interior["widgets_values"][1:8] == [2, "B.safetensors", 1.0, True, "C.safetensors", 0.5, False] + assert not any(op["widget"].startswith("loras.1.") for op in ops) + + +def test_group_row_replacement_requires_a_field_without_a_default(): + info = copy.deepcopy(FIXTURE["object_info"]) + info["DevToolsNodeWithDynamicGroup"]["input"]["required"]["loras"][1]["template"]["required"]["lora_name"] = [ + "COMBO", + {"options": []}, + ] + graph = Graph.from_object_info(info) + + with pytest.raises(ValueError, match="'lora_name' has no default"): + workflow_ops.set_dynamic_group_rows( + copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, 1, "loras", [{"strength": 0.5}] + ) + + +@pytest.mark.parametrize( + "earlier", + [ + {"op": "set_widget", "node": 1, "widget": "loras.0.strength", "value": 0.2}, + {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": []}, + ], +) +def test_group_row_replacement_refuses_an_earlier_write_to_the_group_in_its_batch(earlier): + graph = Graph.from_object_info(FIXTURE["object_info"]) + specs = [ + earlier, + {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": [{"lora_name": "B.safetensors"}]}, + ] + + with pytest.raises(ValueError, match=r"loras(\.0\.strength)? is already written at stamp \[0, cli\]"): + workflow_ops.apply_specs(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, specs) + + +def test_group_row_replacement_counts_pinned_rows_against_the_maximum(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4]["link"] = 10 + + with pytest.raises(ValueError, match=r"3 row\(s\) plus 1 connected or promoted row\(s\) exceed the maximum of 3"): + _replace_rows(workflow, [{"lora_name": "A.safetensors"}] * 3) + + +@pytest.mark.parametrize( + ("widget", "value", "hint"), + [("loras", 1, "change the number of rows"), ("loras.0.strength", 0.2, "put the value in its rows")], +) +def test_group_row_replacement_refuses_a_later_write_to_the_group_in_its_batch(widget, value, hint): + graph = Graph.from_object_info(FIXTURE["object_info"]) + specs = [ + {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": [{"lora_name": "B.safetensors"}]}, + {"op": "set_widget", "node": 1, "widget": "before", "value": "kept"}, + {"op": "set_widget", "node": 1, "widget": widget, "value": value}, + ] + + with pytest.raises(ValueError, match=rf"spec #2: {re.escape(widget)} was replaced earlier in this batch.*{hint}"): + workflow_ops.apply_specs(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, specs) + + +def test_group_row_replacement_writes_a_recreated_row_on_the_interior_despite_a_stale_promotion(): + workflow = _group_in_subgraph({"proxyWidgets": [["1", "loras.2.strength"]]}) + rows = [ + {"lora_name": "A.safetensors"}, + {"lora_name": "B.safetensors"}, + {"lora_name": "C.safetensors", "strength": 0.4}, + ] + + edited, ops, _ = _replace_rows(workflow, rows, node="9/1") + + assert all(op.get("path") == ["9", "1"] and "promoted" not in op for op in ops) + assert edited["definitions"]["subgraphs"][0]["nodes"][0]["widgets_values"][8:10] == ["C.safetensors", 0.4] + assert edited["nodes"][0]["inputs"] == [] + + +def test_group_row_replacement_reports_the_stamp_that_holds_the_group(): + graph = Graph.from_object_info(FIXTURE["object_info"]) + workflow, _ = workflow_ops.set_widget( + copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, 1, "loras", 1, actor="doc", base_version=5 + ) + + with pytest.raises(ValueError, match=r"loras is already written at stamp \[5, doc\]"): + workflow_ops.set_dynamic_group_rows(workflow, graph, 1, "loras", [], base_version=2) + + +def test_group_row_replacement_accepts_a_later_write_to_a_pinned_row(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4]["link"] = 10 + graph = Graph.from_object_info(FIXTURE["object_info"]) + specs = [ + {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": [{"lora_name": "B.safetensors"}]}, + {"op": "set_widget", "node": 1, "widget": "loras.1.lora_name", "value": "A.safetensors"}, + ] + + edited, _, _ = workflow_ops.apply_specs(workflow, graph, specs) + + assert edited["nodes"][0]["widgets_values"][5] == "A.safetensors" + + +def test_group_row_replacement_names_a_subgraph_input_promotion(): + workflow = _group_in_subgraph() + definition = workflow["definitions"]["subgraphs"][0] + definition["inputs"] = [{"id": "in-1", "name": "strength", "type": "FLOAT", "linkIds": [1]}] + definition["links"] = [ + {"id": 1, "origin_id": -10, "origin_slot": 0, "target_id": 1, "target_slot": 4, "type": "FLOAT"} + ] + definition["nodes"][0]["inputs"][4]["link"] = 1 + workflow["nodes"][0]["inputs"] = [ + {"name": "strength", "type": "FLOAT", "link": None, "widget": {"name": "strength"}} + ] + + with pytest.raises(ValueError, match=r"loras\.1 is promoted to the parent subgraph; unpromote it first"): + _replace_rows(workflow, [], node="9/1") + + +def test_group_row_replacement_does_not_retry_a_refused_write_on_an_inserted_copy(monkeypatch): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + copy_node = copy.deepcopy(workflow["nodes"][0]) + copy_node["id"] = "insert:op1:root:node:1" + workflow["nodes"].append(copy_node) + monkeypatch.setattr(workflow_ops, "_inserted_node_id", lambda *_: pytest.fail("retried on the inserted copy")) + + with pytest.raises(ValueError, match="strength"): + _replace_rows(workflow, [{"lora_name": "B.safetensors", "strength": 5}]) + + +def test_group_row_replacement_refuses_a_recreated_row_that_still_has_a_link(): + graph = Graph.from_object_info(FIXTURE["object_info"]) + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][3].update(name="LoRA #2 lora_name", link=10) + workflow, _ = workflow_ops.set_widget(workflow, graph, 1, "loras", 1) + assert workflow["nodes"][0]["inputs"][-1]["link"] == 10 + + with pytest.raises(ValueError, match=r"loras\.1 still has a link from an earlier row"): + workflow_ops.set_dynamic_group_rows( + workflow, + graph, + 1, + "loras", + [{"lora_name": "A.safetensors"}, {"lora_name": "B.safetensors"}], + base_version=1, + ) + + +def test_group_row_replacement_refuses_an_earlier_write_to_a_dropped_row(): + graph = Graph.from_object_info(FIXTURE["object_info"]) + specs = [ + {"op": "set_widget", "node": 1, "widget": "loras.1.strength", "value": 0.3}, + {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": [{"lora_name": "B.safetensors"}]}, + ] + + with pytest.raises(ValueError, match=r"loras\.1\.strength is already written"): + workflow_ops.apply_specs(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, specs) + + def test_pruned_dynamic_group_range_finding_stays_advisory(): info = copy.deepcopy(FIXTURE["object_info"]) info["Sink"] = {