Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions comfy_api/latest/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -1334,8 +1334,8 @@ def __init__(self, input_name: str, message: str):


@comfytype(io_type="COMFY_DYNAMICGROUP_V3")
class DynamicGroup(ComfyTypeI):
"""Repeat a widget template and pass its values to execute as a list of row dicts.
class _DynamicGroup(ComfyTypeI):
"""Internal, unstable widget template repeated as a list of row dicts.

Template fields must be widget inputs without force_input or nested dynamic inputs.
Submit fields as '<group>.<index>.<field>', using indices below max without leading zeros.
Expand Down Expand Up @@ -1379,8 +1379,8 @@ def __init__(self, id: str, template: list[WidgetInput], min: int=0, max: int=20
raise ValueError(f"DynamicGroup id must be nonempty and must not contain '.'. Got: '{id}'")
if isinstance(min, bool) or not isinstance(min, int) or isinstance(max, bool) or not isinstance(max, int):
raise TypeError("DynamicGroup min and max must be integers.")
if not 1 <= max <= DynamicGroup._MaxRows:
raise ValueError(f"DynamicGroup max must be between 1 and {DynamicGroup._MaxRows}.")
if not 1 <= max <= _DynamicGroup._MaxRows:
raise ValueError(f"DynamicGroup max must be between 1 and {_DynamicGroup._MaxRows}.")
if not 0 <= min <= max:
raise ValueError("DynamicGroup min must be between 0 and max.")
self.template = template
Expand All @@ -1407,7 +1407,7 @@ def validate(self):
def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None):
info = value[1]
min_rows = info.get("min", 0)
max_rows = info.get("max", DynamicGroup._MaxRows)
max_rows = info.get("max", _DynamicGroup._MaxRows)
template = info.get("template", {})
field_specs = {
field_id: (field_value, category)
Expand Down Expand Up @@ -1659,8 +1659,8 @@ def setup_dynamic_input_funcs():
register_dynamic_input_func(DynamicCombo.io_type, DynamicCombo._expand_schema_for_dynamic)
# DynamicSlot.Input
register_dynamic_input_func(DynamicSlot.io_type, DynamicSlot._expand_schema_for_dynamic)
# DynamicGroup.Input
register_dynamic_input_func(DynamicGroup.io_type, DynamicGroup._expand_schema_for_dynamic)
# _DynamicGroup.Input
register_dynamic_input_func(_DynamicGroup.io_type, _DynamicGroup._expand_schema_for_dynamic)

if len(DYNAMIC_INPUT_LOOKUP) == 0:
setup_dynamic_input_funcs()
Expand Down Expand Up @@ -1791,7 +1791,7 @@ def collect_inputs(inputs: list[Input], prefix: str = "") -> None:
for inp in inputs:
name = prefix + inp.id
input_types[name] = inp.get_io_type()
if isinstance(inp, DynamicGroup.Input):
if isinstance(inp, _DynamicGroup.Input):
for row in range(inp.max):
collect_inputs(inp.template, f"{name}.{row}.")
else:
Expand Down Expand Up @@ -2063,7 +2063,7 @@ def parse_class_inputs(out_dict: dict[str, Any], live_inputs: dict[str, Any], cu

def _dynamic_group_prefixes(inputs: list[Input]) -> Iterable[str]:
for inp in inputs:
if isinstance(inp, DynamicGroup.Input):
if isinstance(inp, _DynamicGroup.Input):
yield inp.id + "."
elif isinstance(inp, DynamicInput):
for prefix in _dynamic_group_prefixes(inp.get_all()[1:]):
Expand Down Expand Up @@ -2705,7 +2705,6 @@ def as_dict(self):
"MatchType",
"DynamicCombo",
"Autogrow",
"DynamicGroup",
# Other classes
"HiddenHolder",
"Hidden",
Expand Down
55 changes: 31 additions & 24 deletions tests-unit/comfy_api_test/io_dynamic_group_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import pytest

from comfy_api.latest import io
from comfy_api.latest._io import DynamicSlot, build_nested_inputs, create_input_dict_v1, get_finalized_class_inputs
from comfy_api.latest._io import DynamicSlot, _DynamicGroup, build_nested_inputs, create_input_dict_v1, get_finalized_class_inputs
from comfy_api.v0_0_2 import IO as versioned_io


@pytest.mark.parametrize("public_io", [io, versioned_io], ids=["latest", "v0_0_2"])
def test_dynamic_group_is_not_exported_for_node_authors(public_io):
assert not hasattr(public_io, "DynamicGroup")
assert not hasattr(public_io, "_DynamicGroup")


def _reconstruct(group, values, *, lazy=False):
Expand All @@ -11,7 +18,7 @@ def _reconstruct(group, values, *, lazy=False):


def test_serializes_one_template_with_field_requirements():
group = io.DynamicGroup.Input(
group = _DynamicGroup.Input(
"rows",
template=[io.String.Input("name"), io.Float.Input("weight", default=1.0, optional=True)],
min=0, max=5, group_name="Item",
Expand All @@ -34,33 +41,33 @@ def test_serializes_one_template_with_field_requirements():
("", [io.Float.Input("x")], {}),
("rows", [io.Float.Input("")], {}),
("rows", [io.Float.Input("x", force_input=True)], {}),
("rows", [io.DynamicGroup.Input("nested", template=[io.Float.Input("x")])], {}),
("rows", [_DynamicGroup.Input("nested", template=[io.Float.Input("x")])], {}),
("rows", [io.Float.Input("x")], {"min": -1}),
("rows", [io.Float.Input("x")], {"min": 2, "max": 1}),
("rows", [io.Float.Input("x")], {"max": 0}),
("rows", [io.Float.Input("x")], {"max": 21}),
])
def test_rejects_invalid_template_or_limits(group_id, template, limits):
with pytest.raises(ValueError):
io.DynamicGroup.Input(group_id, template=template, **limits)
_DynamicGroup.Input(group_id, template=template, **limits)


def test_rejects_socket_template():
with pytest.raises(TypeError, match="WidgetInputs"):
io.DynamicGroup.Input("rows", template=[io.Image.Input("image")])
_DynamicGroup.Input("rows", template=[io.Image.Input("image")])


@pytest.mark.parametrize("limit", ["min", "max"])
@pytest.mark.parametrize("value", [1.5, True, False])
def test_rejects_non_integer_limits(limit, value):
with pytest.raises(TypeError, match="min and max must be integers"):
io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], **{limit: value})
_DynamicGroup.Input("rows", template=[io.Float.Input("x")], **{limit: value})


@pytest.mark.parametrize("lazy", [False, True])
@pytest.mark.parametrize("values", [{}, {"rows": 0}, {"rows": 7}, {"rows": [1, 2, 3]}, {"rows": {"bad": "data"}}])
def test_empty_group_is_an_empty_list(lazy, values):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x", default=1.0)], min=0)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x", default=1.0)], min=0)
assert _reconstruct(group, values, lazy=lazy) == {"rows": []}


Expand All @@ -69,7 +76,7 @@ def test_empty_group_is_an_empty_list(lazy, values):
def test_rejects_sibling_input_in_group_namespace(sibling_id, nested):
inputs = [
io.Float.Input(sibling_id, optional=True),
io.DynamicGroup.Input("rows", template=[io.Float.Input("x")]),
_DynamicGroup.Input("rows", template=[io.Float.Input("x")]),
]
if nested:
inputs = [io.DynamicCombo.Input("mode", options=[io.DynamicCombo.Option("on", inputs)])]
Expand All @@ -78,7 +85,7 @@ def test_rejects_sibling_input_in_group_namespace(sibling_id, nested):


def test_other_dotted_input_ids_are_unchanged():
inputs = [io.DynamicGroup.Input("rows", template=[io.Float.Input("x")]), io.Float.Input("rows_summary.value")]
inputs = [_DynamicGroup.Input("rows", template=[io.Float.Input("x")]), io.Float.Input("rows_summary.value")]
schema = create_input_dict_v1(inputs)
assert schema["required"]["rows_summary.value"] == ("FLOAT", {})

Expand All @@ -88,7 +95,7 @@ def test_other_dotted_input_ids_are_unchanged():
def test_rejects_outer_input_in_nested_group_namespace(sibling_id, sibling_first):
inputs = [
io.DynamicCombo.Input("mode", options=[io.DynamicCombo.Option("on", [
io.DynamicGroup.Input("rows", template=[io.Float.Input("x")]),
_DynamicGroup.Input("rows", template=[io.Float.Input("x")]),
])]),
io.Float.Input(sibling_id),
]
Expand All @@ -100,7 +107,7 @@ def test_rejects_outer_input_in_nested_group_namespace(sibling_id, sibling_first

def test_group_namespace_is_scoped_to_its_combo_option():
combo = io.DynamicCombo.Input("mode", options=[
io.DynamicCombo.Option("on", [io.DynamicGroup.Input("rows", template=[io.Float.Input("x")])]),
io.DynamicCombo.Option("on", [_DynamicGroup.Input("rows", template=[io.Float.Input("x")])]),
io.DynamicCombo.Option("off", [io.Float.Input("rows.summary")]),
])
assert _reconstruct(combo, {"mode": "off", "mode.rows.summary": 0.5}) == {
Expand All @@ -110,7 +117,7 @@ def test_group_namespace_is_scoped_to_its_combo_option():

@pytest.mark.parametrize("nested", [False, True])
def test_price_badge_resolves_indexed_group_fields(nested):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("weight"), io.String.Input("name")], max=2)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("weight"), io.String.Input("name")], max=2)
inputs = [group, io.Float.Input("fixed")]
prefix = "rows"
if nested:
Expand All @@ -131,7 +138,7 @@ def test_price_badge_resolves_indexed_group_fields(nested):
@pytest.mark.parametrize("minimum", [0, 1, 2])
@pytest.mark.parametrize("optional_group", [False, True])
def test_every_submitted_row_keeps_template_requirements(minimum, optional_group):
group = io.DynamicGroup.Input("rows", template=[
group = _DynamicGroup.Input("rows", template=[
io.String.Input("name"),
io.Float.Input("weight", default=1.0),
io.Boolean.Input("enabled", optional=True),
Expand All @@ -147,13 +154,13 @@ def test_every_submitted_row_keeps_template_requirements(minimum, optional_group
@pytest.mark.parametrize("optional_group", [False, True])
@pytest.mark.parametrize("values", [{}, {"rows.0.x": 1.0}, {"rows.2.x": 1.0}])
def test_min_counts_submitted_rows_without_padding(optional_group, values):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x", optional=True)], min=2, optional=optional_group)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x", optional=True)], min=2, optional=optional_group)
with pytest.raises(ValueError, match="expected between 2 and"):
_reconstruct(group, values)


def test_sparse_rows_preserve_positions_without_defaults():
group = io.DynamicGroup.Input("rows", template=[
group = _DynamicGroup.Input("rows", template=[
io.String.Input("name"), io.Float.Input("weight", default=1.0, optional=True),
], min=2, max=3)
values = {"rows.2.name": "C", "rows.2.weight": 0.5, "rows.0.name": "A"}
Expand All @@ -166,7 +173,7 @@ def test_sparse_rows_preserve_positions_without_defaults():


def test_max_counts_rows_not_fields():
group = io.DynamicGroup.Input("rows", template=[io.String.Input("name"), io.Float.Input("weight")], max=1)
group = _DynamicGroup.Input("rows", template=[io.String.Input("name"), io.Float.Input("weight")], max=1)
assert _reconstruct(group, {"rows.0.name": "A", "rows.0.weight": 0.8}) == {
"rows": [{"name": "A", "weight": 0.8}],
}
Expand All @@ -179,38 +186,38 @@ def test_max_counts_rows_not_fields():
"rows.0", "rows..x", "rows.0.unknown", "rows.0.x.extra",
])
def test_rejects_malformed_row_keys(key):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")])
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")])
with pytest.raises(ValueError) as error:
_reconstruct(group, {key: 1.0})
assert key in str(error.value)


def test_default_max_is_exposed_and_enforced():
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")])
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")])
assert create_input_dict_v1([group])["required"]["rows"][1]["max"] == 20
with pytest.raises(ValueError, match="exceeds the index limit of 19"):
_reconstruct(group, {"rows.20.x": 0.5})


def test_largest_supported_index_preserves_position():
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=20)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=20)
rows = _reconstruct(group, {"rows.19.x": 0.5})["rows"]
assert rows == [{"x": None}] * 19 + [{"x": 0.5}]


@pytest.mark.parametrize("maximum,index", [(1, 1), (1, 99), (2, 2), (20, 20), (20, 100), (1, 1_000_000)])
def test_rejects_out_of_range_index_before_registering_padding(maximum, index):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=maximum)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=maximum)
expanded = {"required": {}, "optional": {}, "dynamic_paths": {}, "dynamic_paths_default_value": {}, "list_paths": set()}
with pytest.raises(ValueError, match=f"exceeds the index limit of {maximum - 1}"):
io.DynamicGroup._expand_schema_for_dynamic(
_DynamicGroup._expand_schema_for_dynamic(
expanded, {f"rows.{index}.x": 0.5}, (group.io_type, group.as_dict()), "required", ["rows"],
)
assert expanded["dynamic_paths"] == {}


def test_lazy_rows_keep_original_field_keys_and_positions():
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=3)
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=3)
assert _reconstruct(group, {"rows.2.x": 0.5, "rows.0.x": 0.8}, lazy=True) == {"rows": [
{"x": (0.8, "rows.0.x")},
{"x": (None, "rows.1.x")},
Expand All @@ -220,7 +227,7 @@ def test_lazy_rows_keep_original_field_keys_and_positions():

@pytest.mark.parametrize("lazy", [False, True])
def test_group_inside_dynamic_combo_preserves_other_inputs(lazy):
group = io.DynamicGroup.Input("rows", template=[io.Float.Input("x")])
group = _DynamicGroup.Input("rows", template=[io.Float.Input("x")])
combo = io.DynamicCombo.Input("mode", options=[io.DynamicCombo.Option("on", [group])])
values = {"mode": "on", "mode.rows.0.x": 0.8, "fixed": "untouched"}
assert _reconstruct(combo, values, lazy=lazy) == {
Expand All @@ -237,7 +244,7 @@ def test_group_inside_dynamic_combo_preserves_other_inputs(lazy):
def test_list_mode_padding_is_limited_to_group_fields(kind, lazy):
inputs = [
io.Float.Input("optional", optional=True),
io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=2),
_DynamicGroup.Input("rows", template=[io.Float.Input("x")], max=2),
]
if kind == "combo":
container = io.DynamicCombo.Input("mode", options=[io.DynamicCombo.Option("on", inputs)])
Expand Down
5 changes: 3 additions & 2 deletions tests-unit/execution_test/dynamic_group_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import execution
import nodes
from comfy_api.latest import io
from comfy_api.latest._io import _DynamicGroup


pytestmark = pytest.mark.asyncio
Expand All @@ -24,7 +25,7 @@ class Group(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id=cls.__name__, is_input_list=is_input_list, inputs=[
io.DynamicGroup.Input("rows", template=[
_DynamicGroup.Input("rows", template=[
io.Float.Input("x"), io.Float.Input("optional", optional=True, default=1.0),
], max=3),
], outputs=[])
Expand Down Expand Up @@ -66,7 +67,7 @@ class Group(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id=cls.__name__, inputs=[
io.DynamicGroup.Input("rows", template=[io.Float.Input("x")], min=1, max=3),
_DynamicGroup.Input("rows", template=[io.Float.Input("x")], min=1, max=3),
], outputs=[io.Float.Output()], is_output_node=not downstream)

@classmethod
Expand Down
Loading