From c7b5bf61eb2016140bbd1041c4095e0aee544d06 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:39:08 +0900 Subject: [PATCH 1/7] feat(workflow): replace DynamicGroup rows in one batch spec Add a `set_dynamic_group_rows` batch spec that replaces a group's rows with the complete desired list. It emits only existing `set_widget` ops: the row count, then every field of each written row. Rows with a connected field keep their index and values; supplied rows fill the other positions, and the spec refuses when a connected row would have to move. Co-Authored-By: Claude Opus 5.5 --- comfy_cli/skills/comfy/SKILL.md | 11 +++ comfy_cli/workflow_ops.py | 86 ++++++++++++++++++++ docs/op-vocabulary-v1.md | 6 ++ tests/comfy_cli/test_dynamic_group.py | 110 ++++++++++++++++++++++++++ 4 files changed, 213 insertions(+) diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index 412c5c862..fe06d96db 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -426,6 +426,17 @@ 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 complete 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 row with a connected field keeps its index and values; your rows fill the +other positions in order, so the batch fails if a connected row would have to move. + +```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 f173e8cb1..ee9a1af3d 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -761,6 +761,80 @@ 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 field of each written + row. Omitted fields take the template default. + + A row with a connected field (including a subgraph promotion) keeps its + index and values; ``rows`` fill the other positions in order. Links are + never moved, so ``rows`` must cover every free position before the last + connected row. + """ + from comfy_cli.cql import engine as _engine + from comfy_cli.cql import promoted as _promoted + + target = _resolve_widget_write(workflow, graph, node_id, group) + if target.kind == "top" and target.redirected_from is None: + node = target.node + elif target.kind == "interior" and target.redirected_from is None: + node = _promoted._navigate(workflow, target.segments, _promoted.defs_by_id(workflow)) + 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") + fields = _engine._dynamic_group_fields(port) + names = [field.name for field in fields] + for i, row in enumerate(rows): + unknown = [key for key in row if key not in names] + if unknown: + raise ValueError(f"{group}: row {i} has unknown field(s) {unknown}; row fields: {', '.join(names)}") + + entries = _engine._validate_dynamic_group_layout(node, m) or [] + width = len(_engine._dynamic_group_widgets(port, f"{group}.0")) + current = sum(1 for e in entries if e.owner == group) // width + linked = { + inp.get("name") for inp in node.get("inputs") or [] if isinstance(inp, dict) and inp.get("link") is not None + } + pinned = [r for r in range(current) if any(f"{group}.{r}.{name}" in linked for name in names)] + free_before_last = pinned[-1] + 1 - len(pinned) if pinned else 0 + if len(rows) < free_before_last: + raise ValueError( + f"{group}.{pinned[-1]} is connected and keeps its position; supply at least " + f"{free_before_last} row(s) or disconnect it first" + ) + supplied = iter(rows) + plan = [None if index in pinned else next(supplied) for index in range(len(rows) + len(pinned))] + + workflow, op = set_widget(workflow, graph, node_id, group, len(plan), actor=actor, base_version=base_version) + ops = [op] + for index, row in enumerate(plan): + if row is None: + continue + for field in fields: + value = row[field.name] if field.name in row else _engine._widget_default(field) + workflow, op = set_widget( + workflow, graph, node_id, f"{group}.{index}.{field.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. @@ -2489,6 +2563,18 @@ 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) + continue elif kind == "set_node_field": workflow, op = set_node_field( workflow, diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index 9b01506b6..e38d4dffe 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -39,6 +39,12 @@ 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 field of each written row. Rows with a connected field keep their index and +are not rewritten. + 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 a668ef740..5ba1d7809 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1070,3 +1070,113 @@ def test_dynamic_group_prompt_validation_checks_only_submitted_rows(inputs, mini else: assert not result["valid"] 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"): + _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, "between 0 and 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) From ec85826a68e453ab03444589b54dcfcb6523f093 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:33:50 +0900 Subject: [PATCH 2/7] fix(workflow): make group row replacement atomic and pin promoted rows Run the writes on a copy, resolve template ids and binding names like set_widget, rewrite seed control modes with their rows, pin rows whose field is promoted (including legacy proxyWidgets) or linked by widget name, and require fields that have no default. --- comfy_cli/skills/comfy/SKILL.md | 6 +- comfy_cli/workflow_ops.py | 62 +++++++++++++----- docs/op-vocabulary-v1.md | 4 +- tests/comfy_cli/test_dynamic_group.py | 91 +++++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 21 deletions(-) diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index fe06d96db..544bfdf52 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -429,8 +429,10 @@ comfy --json workflow apply wf.json --ops ops.json $CAT # or --ops - to read s **Adding, removing or reordering DynamicGroup rows** (e.g. a LoRA stack's `loras`): send the complete 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 row with a connected field keeps its index and values; your rows fill the -other positions in order, so the batch fails if a connected row would have to move. +default (a field with no default 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; your rows fill the other positions in order, so the batch fails if that row +would have to move. ```json {"op":"set_dynamic_group_rows","node":12,"group":"loras", diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index ee9a1af3d..5b52389d8 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -772,22 +772,28 @@ def set_dynamic_group_rows( 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 field of each written - row. Omitted fields take the template default. + ``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 field (including a subgraph promotion) keeps its - index and values; ``rows`` fill the other positions in order. Links are - never moved, so ``rows`` must cover every free position before the last - connected row. + A row with a connected or promoted field keeps its index and values; + ``rows`` 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. """ 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" @@ -798,20 +804,36 @@ def set_dynamic_group_rows( 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") - fields = _engine._dynamic_group_fields(port) - names = [field.name for field in fields] + 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}: row {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 row {i}") entries = _engine._validate_dynamic_group_layout(node, m) or [] - width = len(_engine._dynamic_group_widgets(port, f"{group}.0")) - current = sum(1 for e in entries if e.owner == group) // width - linked = { - inp.get("name") for inp in node.get("inputs") or [] if isinstance(inp, dict) and inp.get("link") is not None - } - pinned = [r for r in range(current) if any(f"{group}.{r}.{name}" in linked for name in names)] + 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: + linked.add(inp.get("name")) + if isinstance(inp.get("widget"), dict): + linked.add(inp["widget"].get("name")) + fields = [field.name for field in _engine._dynamic_group_fields(port)] + + def is_pinned(row: int) -> bool: + # 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}" + if address in linked or _promoted.resolve_write(workflow, graph, segments, address).redirected_from: + return True + return False + + pinned = [r for r in range(current) if is_pinned(r)] free_before_last = pinned[-1] + 1 - len(pinned) if pinned else 0 if len(rows) < free_before_last: raise ValueError( @@ -826,10 +848,16 @@ def set_dynamic_group_rows( for index, row in enumerate(plan): if row is None: continue - for field in fields: - value = row[field.name] if field.name in row else _engine._widget_default(field) + for widget in widgets: + value = row[widget.name] if widget.name in row else _engine._widget_default(widget) workflow, op = set_widget( - workflow, graph, node_id, f"{group}.{index}.{field.name}", value, actor=actor, base_version=base_version + workflow, + graph, + node_id, + f"{group}.{index}.{widget.name}", + value, + actor=actor, + base_version=base_version, ) ops.append(op) return workflow, ops diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index e38d4dffe..08ec76b50 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -42,8 +42,8 @@ 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 field of each written row. Rows with a connected field keep their index and -are not rewritten. +every widget of each written row, including a field's `.0` control mode. +Rows with a connected or promoted field keep their index and are not rewritten. Every op carries the common envelope stamped by `_new_op`: diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index 5ba1d7809..a935a237f 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1180,3 +1180,94 @@ def test_group_row_replacement_edits_an_interior_node(): 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"} + + +def test_group_row_replacement_pins_a_row_connected_by_widget_name_only(): + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + workflow["nodes"][0]["inputs"][4].update(name="LoRA #2 strength", 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 connected"): + _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}] + ) From 698cf9b7d6d63c34af7b0d6d30d33bc004257835 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:56:37 +0900 Subject: [PATCH 3/7] fix(workflow): refuse same-batch group writes before row replacement An earlier write to the group at the same stamp would be settled by the random op_id tiebreak, so the count could be dropped. Also count pinned rows against the maximum, say whether a pinned row is linked or promoted, and skip non-string input names. --- comfy_cli/skills/comfy/SKILL.md | 6 +-- comfy_cli/workflow_ops.py | 56 ++++++++++++++++++++------- docs/op-vocabulary-v1.md | 4 +- tests/comfy_cli/test_dynamic_group.py | 37 +++++++++++++++--- 4 files changed, 80 insertions(+), 23 deletions(-) diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index 544bfdf52..2c84e3783 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -427,12 +427,12 @@ comfy --json workflow apply wf.json --ops ops.json $CAT # or --ops - to read s ``` **Adding, removing or reordering DynamicGroup rows** (e.g. a LoRA stack's `loras`): -send the complete desired row list in one `set_dynamic_group_rows` spec instead of +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 field with no default 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; your rows fill the other positions in order, so the batch fails if that row -would have to move. +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. ```json {"op":"set_dynamic_group_rows","node":12,"group":"loras", diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index 5b52389d8..e0d25ded2 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -776,11 +776,15 @@ def set_dynamic_group_rows( 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; - ``rows`` fill the other positions in order. Links are never moved, so - ``rows`` must cover every free position before the last pinned row. + 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, and replay + must apply them in order: the row writes address rows the count creates. """ from comfy_cli.cql import engine as _engine from comfy_cli.cql import promoted as _promoted @@ -819,27 +823,51 @@ def set_dynamic_group_rows( linked = set() for inp in node.get("inputs") or []: if isinstance(inp, dict) and inp.get("link") is not None: - linked.add(inp.get("name")) - if isinstance(inp.get("widget"), dict): - linked.add(inp["widget"].get("name")) + 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 is_pinned(row: int) -> bool: + 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}" - if address in linked or _promoted.resolve_write(workflow, graph, segments, address).redirected_from: - return True - return False + if address in linked: + return "is connected; disconnect it first" + if _promoted.resolve_write(workflow, graph, segments, address).redirected_from: + return "is promoted to the parent subgraph; unpromote it first" + return None - pinned = [r for r in range(current) if is_pinned(r)] - free_before_last = pinned[-1] + 1 - len(pinned) if pinned else 0 + 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}.{pinned[-1]} is connected and keeps its position; supply at least " - f"{free_before_last} row(s) or disconnect it first" + 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}" ) + register = segments if len(segments) > 1 else str(node_id) + for key, stamp in (workflow.get("_widget_stamps") or {}).items(): + kind, where, written = json.loads(key)[:3] + if ( + kind == "widget" + and where == register + and isinstance(written, str) + and (written == group or written.startswith(f"{group}.")) + and list(stamp[:2]) >= [base_version, actor] + ): + raise ValueError( + f"{group}: this batch already writes {written}; replace the rows without other writes to {group}" + ) supplied = iter(rows) plan = [None if index in pinned else next(supplied) for index in range(len(rows) + len(pinned))] diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index 08ec76b50..8c5e7e28c 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -43,7 +43,9 @@ naming the standalone command. Nothing from such a batch is applied. 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 and are not rewritten. +Rows with a connected or promoted field keep their index, are not rewritten, and +are left out of `rows`. The ops must replay in order, since the row writes address +rows the count creates; an earlier write to the group in the same batch is refused. Every op carries the common envelope stamped by `_new_op`: diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index a935a237f..31d37286c 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1142,7 +1142,7 @@ def test_group_row_replacement_refuses_to_move_a_connected_row(): workflow["nodes"][0]["inputs"][4]["link"] = 10 original = copy.deepcopy(workflow) - with pytest.raises(ValueError, match=r"loras\.1 is connected"): + with pytest.raises(ValueError, match=r"loras\.1 is connected; disconnect it first"): _replace_rows(workflow, []) assert workflow == original @@ -1152,7 +1152,7 @@ def test_group_row_replacement_refuses_to_move_a_connected_row(): [ ([{"lora": "A.safetensors"}], "unknown field"), ({"lora_name": "A.safetensors"}, "list of objects"), - ([{"lora_name": "A.safetensors"}] * 4, "between 0 and 3"), + ([{"lora_name": "A.safetensors"}] * 4, "exceed the maximum of 3"), ([{"lora_name": "A.safetensors", "strength": 5}], "strength"), ], ) @@ -1239,9 +1239,10 @@ def test_group_row_replacement_accepts_the_template_id_of_an_inserted_node(): assert {op["node_id"] for op in ops} == {"insert:op1:root:node:1"} -def test_group_row_replacement_pins_a_row_connected_by_widget_name_only(): +@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="LoRA #2 strength", link=10) + workflow["nodes"][0]["inputs"][4].update(name=name, link=10) with pytest.raises(ValueError, match=r"loras\.1 is connected"): _replace_rows(workflow, []) @@ -1250,7 +1251,7 @@ def test_group_row_replacement_pins_a_row_connected_by_widget_name_only(): 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 connected"): + 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") @@ -1271,3 +1272,29 @@ def test_group_row_replacement_requires_a_field_without_a_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="this batch already writes loras"): + 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) From 78ae266efdbd242e1a4605203c9b7b62e24ed942 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:22:02 +0900 Subject: [PATCH 4/7] fix(workflow): refuse later same-batch writes to a replaced group Check only the registers the replacement claims, so unrelated or stale stamps cannot break it, and write through the resolved owner path. --- comfy_cli/workflow_ops.py | 41 +++++++++++++++++---------- tests/comfy_cli/test_dynamic_group.py | 31 +++++++++++++++++++- 2 files changed, 56 insertions(+), 16 deletions(-) diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index e0d25ded2..8a8afb4fc 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -855,23 +855,21 @@ def pin_reason(row: int) -> str | None: raise ValueError( f"{group}: {len(rows)} row(s) plus {len(pinned)} connected or promoted row(s) exceed the maximum of {maximum}" ) - register = segments if len(segments) > 1 else str(node_id) - for key, stamp in (workflow.get("_widget_stamps") or {}).items(): - kind, where, written = json.loads(key)[:3] - if ( - kind == "widget" - and where == register - and isinstance(written, str) - and (written == group or written.startswith(f"{group}.")) - and list(stamp[:2]) >= [base_version, actor] - ): - raise ValueError( - f"{group}: this batch already writes {written}; replace the rows without other writes to {group}" - ) supplied = iter(rows) plan = [None if index in pinned else next(supplied) for index in range(len(rows) + len(pinned))] + 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, row in enumerate(plan) if row 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 base_version {base_version} by {actor}; " + f"write the group once per batch, or apply with a higher base_version" + ) - workflow, op = set_widget(workflow, graph, node_id, group, len(plan), actor=actor, base_version=base_version) + workflow, op = set_widget(workflow, graph, address, group, len(plan), actor=actor, base_version=base_version) ops = [op] for index, row in enumerate(plan): if row is None: @@ -881,7 +879,7 @@ def pin_reason(row: int) -> str | None: workflow, op = set_widget( workflow, graph, - node_id, + address, f"{group}.{index}.{widget.name}", value, actor=actor, @@ -2576,6 +2574,7 @@ def apply_specs( pre_batch_hint = _available_nodes_hint(workflow) aliases: dict[str, Any] = {} ops: list[dict] = [] + replaced: list[tuple] = [] try: for i, spec in enumerate(specs): if not isinstance(spec, dict) or "op" not in spec: @@ -2630,6 +2629,7 @@ def apply_specs( base_version=base_version, ) ops.extend(row_ops) + replaced.append(_write_target(row_ops[0])) continue elif kind == "set_node_field": workflow, op = set_node_field( @@ -2653,6 +2653,17 @@ 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. + target = _write_target(op) if op.get("op") == "set_widget" else None + if target and any( + target[1] == where and (target[2] == group or target[2].startswith(f"{group}.")) + for _, where, group in replaced + ): + raise ValueError( + f"spec #{i}: {target[2]} was replaced earlier in this batch by set_dynamic_group_rows; " + f"put the value in its rows instead" + ) ops.append(op) except (NotBatchableError, DeprecatedNodeType): # Already carries a registered code and a hint that says what to do diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index 31d37286c..61b03a5a4 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 @@ -1288,7 +1289,7 @@ def test_group_row_replacement_refuses_an_earlier_write_to_the_group_in_its_batc {"op": "set_dynamic_group_rows", "node": 1, "group": "loras", "rows": [{"lora_name": "B.safetensors"}]}, ] - with pytest.raises(ValueError, match="this batch already writes loras"): + with pytest.raises(ValueError, match=r"loras(\.0\.strength)? is already written at base_version 0 by cli"): workflow_ops.apply_specs(copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]), graph, specs) @@ -1298,3 +1299,31 @@ def test_group_row_replacement_counts_pinned_rows_against_the_maximum(): 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"), [("loras", 1), ("loras.0.strength", 0.2)]) +def test_group_row_replacement_refuses_a_later_write_to_the_group_in_its_batch(widget, value): + 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"): + 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"] == [] From ea6ae83f8ac6b5c71643a7d6a6e46748c6f1ace3 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:49:37 +0900 Subject: [PATCH 5/7] fix(workflow): match only claimed registers in group replacement guards Refuse a later write only to a register the replacement wrote, report the stamp that holds the group, give the count its own hint, and name subgraph-input promotions as promoted. --- comfy_cli/workflow_ops.py | 28 +++++++++------ tests/comfy_cli/test_dynamic_group.py | 51 ++++++++++++++++++++++++--- 2 files changed, 64 insertions(+), 15 deletions(-) diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index 8a8afb4fc..b39ce1172 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -836,10 +836,14 @@ def pin_reason(row: int) -> str | None: # input or a legacy proxyWidgets entry), owns the row's value. for name in fields: address = f"{group}.{row}.{name}" + try: + redirected = _promoted.resolve_write(workflow, graph, segments, address).redirected_from + except ValueError: # fed by another interior node: a plain link + redirected = None + if redirected: + return "is promoted to the parent subgraph; unpromote it first" if address in linked: return "is connected; disconnect it first" - if _promoted.resolve_write(workflow, graph, segments, address).redirected_from: - return "is promoted to the parent subgraph; unpromote it first" return None pinned = {r: reason for r in range(current) if (reason := pin_reason(r))} @@ -865,8 +869,8 @@ def pin_reason(row: int) -> str | None: 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 base_version {base_version} by {actor}; " - f"write the group once per batch, or apply with a higher base_version" + 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)" ) workflow, op = set_widget(workflow, graph, address, group, len(plan), actor=actor, base_version=base_version) @@ -2574,7 +2578,7 @@ def apply_specs( pre_batch_hint = _available_nodes_hint(workflow) aliases: dict[str, Any] = {} ops: list[dict] = [] - replaced: list[tuple] = [] + replaced: set[tuple] = set() try: for i, spec in enumerate(specs): if not isinstance(spec, dict) or "op" not in spec: @@ -2629,7 +2633,7 @@ def apply_specs( base_version=base_version, ) ops.extend(row_ops) - replaced.append(_write_target(row_ops[0])) + replaced.update(_write_target(row_op) for row_op in row_ops) continue elif kind == "set_node_field": workflow, op = set_node_field( @@ -2656,13 +2660,15 @@ def apply_specs( # A later write at the batch's stamp would tie with the replacement # and be settled by the random op_id. target = _write_target(op) if op.get("op") == "set_widget" else None - if target and any( - target[1] == where and (target[2] == group or target[2].startswith(f"{group}.")) - for _, where, group in replaced - ): + if target in replaced: + count = "." not in target[2] raise ValueError( f"spec #{i}: {target[2]} was replaced earlier in this batch by set_dynamic_group_rows; " - f"put the value in its rows instead" + + ( + "change the number of rows in that spec instead" + if count + else "put the value in its rows instead" + ) ) ops.append(op) except (NotBatchableError, DeprecatedNodeType): diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index 61b03a5a4..fe81f3850 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1289,7 +1289,7 @@ def test_group_row_replacement_refuses_an_earlier_write_to_the_group_in_its_batc {"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 base_version 0 by cli"): + 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) @@ -1301,8 +1301,11 @@ def test_group_row_replacement_counts_pinned_rows_against_the_maximum(): _replace_rows(workflow, [{"lora_name": "A.safetensors"}] * 3) -@pytest.mark.parametrize(("widget", "value"), [("loras", 1), ("loras.0.strength", 0.2)]) -def test_group_row_replacement_refuses_a_later_write_to_the_group_in_its_batch(widget, value): +@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"}]}, @@ -1310,7 +1313,7 @@ def test_group_row_replacement_refuses_a_later_write_to_the_group_in_its_batch(w {"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"): + 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) @@ -1327,3 +1330,43 @@ def test_group_row_replacement_writes_a_recreated_row_on_the_interior_despite_a_ 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") From 1ec1f068901042e9a9240264ac54206025bd1eb3 Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:28:41 +0900 Subject: [PATCH 6/7] fix(workflow): write group rows without the inserted-node retry Refuse a recreated row that still carries a link, guard earlier writes to dropped rows, pin rows whose write is not a plain owner write, and record which replaced register is the count. --- comfy_cli/skills/comfy/SKILL.md | 2 +- comfy_cli/workflow_ops.py | 33 ++++++++++++++-------- tests/comfy_cli/test_dynamic_group.py | 40 +++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 13 deletions(-) diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index 2c84e3783..c095b7f88 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -429,7 +429,7 @@ comfy --json workflow apply wf.json --ops ops.json $CAT # or --ops - to read s **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 field with no default must be supplied); a seed field's control mode is +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. diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index b39ce1172..15b1d5738 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -813,10 +813,10 @@ def set_dynamic_group_rows( for i, row in enumerate(rows): unknown = [key for key in row if key not in names] if unknown: - raise ValueError(f"{group}: row {i} has unknown field(s) {unknown}; row fields: {', '.join(names)}") + 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 row {i}") + 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) @@ -837,10 +837,10 @@ def pin_reason(row: int) -> str | None: for name in fields: address = f"{group}.{row}.{name}" try: - redirected = _promoted.resolve_write(workflow, graph, segments, address).redirected_from + target = _promoted.resolve_write(workflow, graph, segments, address) except ValueError: # fed by another interior node: a plain link - redirected = None - if redirected: + 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" @@ -861,10 +861,19 @@ def pin_reason(row: int) -> str | None: ) 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, row in enumerate(plan) if row is not None for w in widgets] + 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]: @@ -873,14 +882,15 @@ def pin_reason(row: int) -> str | None: f"per batch (a stamp left by an earlier apply needs a higher base_version)" ) - workflow, op = set_widget(workflow, graph, address, group, len(plan), actor=actor, base_version=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( + workflow, op = _set_widget_impl( workflow, graph, address, @@ -2578,7 +2588,7 @@ def apply_specs( pre_batch_hint = _available_nodes_hint(workflow) aliases: dict[str, Any] = {} ops: list[dict] = [] - replaced: set[tuple] = set() + replaced: dict[tuple, bool] = {} try: for i, spec in enumerate(specs): if not isinstance(spec, dict) or "op" not in spec: @@ -2633,7 +2643,7 @@ def apply_specs( base_version=base_version, ) ops.extend(row_ops) - replaced.update(_write_target(row_op) for row_op in 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( @@ -2661,12 +2671,11 @@ def apply_specs( # and be settled by the random op_id. target = _write_target(op) if op.get("op") == "set_widget" else None if target in replaced: - count = "." not in target[2] 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 count + if replaced[target] else "put the value in its rows instead" ) ) diff --git a/tests/comfy_cli/test_dynamic_group.py b/tests/comfy_cli/test_dynamic_group.py index fe81f3850..02a6a70ac 100644 --- a/tests/comfy_cli/test_dynamic_group.py +++ b/tests/comfy_cli/test_dynamic_group.py @@ -1370,3 +1370,43 @@ def test_group_row_replacement_names_a_subgraph_input_promotion(): 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) From 57481ed7873df859a6ba420ee09681807b62e72b Mon Sep 17 00:00:00 2001 From: jaeone94 <89377375+jaeone94@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:37:40 +0900 Subject: [PATCH 7/7] docs(workflow): scope DynamicGroup replay order to comfy-cli The shared document accepts row writes in any order, so the vocabulary no longer states a universal ordering. The same-batch guards name #1007 as their retirement condition, and SKILL.md states the read-to-write link race. --- comfy_cli/skills/comfy/SKILL.md | 2 ++ comfy_cli/workflow_ops.py | 8 +++++--- docs/op-vocabulary-v1.md | 5 +++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/comfy_cli/skills/comfy/SKILL.md b/comfy_cli/skills/comfy/SKILL.md index 91d4f68ae..32899d01d 100644 --- a/comfy_cli/skills/comfy/SKILL.md +++ b/comfy_cli/skills/comfy/SKILL.md @@ -434,6 +434,8 @@ default (a combo without one takes its first option, so name the LoRA explicitly `".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", diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index eb7df37d0..9c1e33c05 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -837,8 +837,9 @@ def set_dynamic_group_rows( 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, and replay - must apply them in order: the row writes address rows the count creates. + 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 @@ -2994,7 +2995,8 @@ def apply_specs( 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. + # 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( diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index 074b77ff0..eb4e265c9 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -47,8 +47,9 @@ 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`. The ops must replay in order, since the row writes address -rows the count creates; an earlier write to the group in the same batch is refused. +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`: