diff --git a/comfy_cli/command/workflow.py b/comfy_cli/command/workflow.py index 8be9dce9f..125c7b7f2 100644 --- a/comfy_cli/command/workflow.py +++ b/comfy_cli/command/workflow.py @@ -2213,6 +2213,9 @@ def validate_cmd( from comfy_cli.command import workflow_edit as _wedit # noqa: E402 +app.command("define-subgraph", help="Create a subgraph definition; emits one define_subgraph op.")( + _wedit.define_subgraph_cmd +) app.command("insert-workflow", help="Insert a complete workflow; emits one insert_workflow op.")( _wedit.insert_workflow_cmd ) diff --git a/comfy_cli/command/workflow_edit.py b/comfy_cli/command/workflow_edit.py index 0f4acb7cb..de24f0e8b 100644 --- a/comfy_cli/command/workflow_edit.py +++ b/comfy_cli/command/workflow_edit.py @@ -14,6 +14,7 @@ from __future__ import annotations import json +import stat from pathlib import Path from typing import Annotated, Any @@ -48,6 +49,7 @@ HostOpt = Annotated[str | None, typer.Option(show_default=False)] PortOpt = Annotated[int | None, typer.Option(show_default=False)] WhereOpt = Annotated[str | None, typer.Option("--where", show_default=False, help="Catalog target: local | cloud.")] +_MAX_DEFINITION_BYTES = 16 * 1024 * 1024 def _emit_edit_error(renderer, e: ValueError, *, hint: str) -> None: @@ -148,6 +150,56 @@ def _graph_or_exit(input_path, host, port, renderer, where=None): return _get_graph(input_path, host, port, where=where) +# --------------------------------------------------------------------------- +# define-subgraph +# --------------------------------------------------------------------------- + + +def _read_subgraph_definition(path: Path): + """Read a bounded regular JSON file without blocking on devices or FIFOs.""" + file_stat = path.stat() + if not stat.S_ISREG(file_stat.st_mode): + raise ValueError("subgraph definition must be a regular file") + if file_stat.st_size > _MAX_DEFINITION_BYTES: + raise ValueError(f"subgraph definition is too large (maximum {_MAX_DEFINITION_BYTES} bytes)") + try: + with path.open("rb") as definition_file: + raw = definition_file.read(_MAX_DEFINITION_BYTES + 1) + if len(raw) > _MAX_DEFINITION_BYTES: + raise ValueError(f"subgraph definition is too large (maximum {_MAX_DEFINITION_BYTES} bytes)") + return json.loads(raw.decode("utf-8")) + except (RecursionError, MemoryError) as error: + raise ValueError("subgraph definition is too deeply nested or too large") from error + + +@tracking.track_command("workflow") +def define_subgraph_cmd( + file: Annotated[str, typer.Argument(help="Source frontend-format workflow JSON; emit-only, file is not modified.")], + definition_file: Annotated[str, typer.Argument(help="Serializable subgraph definition JSON.")], + subgraph_id: Annotated[str | None, typer.Option("--id", show_default=False)] = None, + actor: ActorOpt = "cli", + base_version: BaseVersionOpt = 0, +): + """Create one subgraph definition and emit one ``define_subgraph`` op.""" + renderer = get_renderer() + renderer.command = "workflow define-subgraph" + p, workflow = _load_workflow_or_fail(renderer, file) + try: + definition_path = Path(definition_file).expanduser() + definition = _read_subgraph_definition(definition_path) + _, op = workflow_ops.define_subgraph( + workflow, + definition, + subgraph_id=subgraph_id, + actor=actor, + base_version=base_version, + ) + except (OSError, json.JSONDecodeError, UnicodeDecodeError, ValueError, RecursionError, MemoryError) as e: + _emit_edit_error(renderer, e, hint="provide a serializable subgraph definition JSON object") + raise typer.Exit(code=1) from e + _emit_op(renderer, p, op, base_version, "workflow define-subgraph") + + # --------------------------------------------------------------------------- # add-node # --------------------------------------------------------------------------- @@ -955,6 +1007,18 @@ def apply_cmd( raise typer.Exit(code=1) from e try: + # Batchable-but-deferred kinds (define_subgraph) cannot be persisted by + # a local apply. Standalone-only deferred kinds (insert_workflow) fall + # through to apply_specs so they surface their own not-batchable code. + deferred = [ + spec.get("op") + for spec in specs + if isinstance(spec, dict) + and spec.get("op") in workflow_ops.DEFERRED_OPS + and spec.get("op") in workflow_ops.BATCHABLE_OPS + ] + if deferred: + raise ValueError(f"local apply cannot persist deferred operation(s): {', '.join(deferred)}") workflow, ops, aliases = workflow_ops.apply_specs( workflow, graph, specs, actor=actor, base_version=base_version ) @@ -1079,6 +1143,15 @@ def _load_param_sets(raw: str, renderer) -> list[dict]: return sets +def _reject_deferred_specs(specs: list) -> None: + """Refuse to persist a batch locally when any spec is a deferred op kind.""" + deferred = [ + spec.get("op") for spec in specs if isinstance(spec, dict) and spec.get("op") in workflow_ops.DEFERRED_OPS + ] + if deferred: + raise ValueError(f"local foreach cannot persist deferred operation(s): {', '.join(deferred)}") + + @tracking.track_command("workflow") def foreach_cmd( recipe_file: Annotated[str, typer.Argument(help="Recipe file: {params, ops}.")], @@ -1124,11 +1197,15 @@ def foreach_cmd( out.mkdir(parents=True, exist_ok=True) written: list[str] = [] try: + _reject_deferred_specs(specs_template) for i, pset in enumerate(param_sets): if not isinstance(pset, dict): raise workflow_ops.RecipeError(f"param-set #{i} must be a JSON object") params = workflow_ops.resolve_params(params_decl, {k: str(v) for k, v in pset.items()}) specs = workflow_ops.substitute_params(specs_template, params) + # The op kind itself may be a `${param}`, so the template check above + # cannot see a kind that only becomes deferred for this param-set. + _reject_deferred_specs(specs) wf: dict = {"nodes": [], "links": [], "last_node_id": 0, "last_link_id": 0} wf, _ops, _aliases = workflow_ops.apply_specs(wf, graph, specs, actor=actor, base_version=base_version) workflow_ops.strip_internal(wf) diff --git a/comfy_cli/discovery.py b/comfy_cli/discovery.py index 811547dc5..38d4c9396 100644 --- a/comfy_cli/discovery.py +++ b/comfy_cli/discovery.py @@ -112,6 +112,7 @@ "comfy workflow delete-node": "workflow", "comfy workflow delete-nodes": "workflow", "comfy workflow ls-nodes": "workflow", + "comfy workflow define-subgraph": "workflow", # Whole-document edits: same `_finish` op envelope as the primitives above. "comfy workflow clear": "workflow", "comfy workflow reset-doc": "workflow", diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index 5b7dd3231..36fd7b1df 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -72,6 +72,7 @@ # New ids live in [2**40, 2**53): always large (never collides with small # frontend counter ids), always inside JS Number.MAX_SAFE_INTEGER. _ID_FLOOR = 1 << 40 +_SUBGRAPH_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I) def mint_id() -> int: @@ -110,6 +111,7 @@ def _new_op(kind: str, actor: str, base_version: int, **fields: Any) -> dict[str "delete_node", "clear", "reset_doc", + "define_subgraph", "insert_workflow", ) @@ -122,9 +124,10 @@ def _new_op(kind: str, actor: str, base_version: int, **fields: Any) -> dict[str WRITABLE_NODE_FIELDS: tuple[str, ...] = ("title", "mode", "flags.collapsed", "flags.pinned") #: Kinds frozen in the contract whose replay is not implemented in the CLI. -#: ``insert_workflow`` is emitted for cmp to validate and apply; the CLI must -#: keep rejecting local replay to preserve that ownership boundary. -DEFERRED_OPS: tuple[str, ...] = ("insert_workflow",) +#: ``define_subgraph`` and ``insert_workflow`` are emitted for cmp to validate +#: and apply; the CLI must keep rejecting local replay to preserve that +#: ownership boundary. +DEFERRED_OPS: tuple[str, ...] = ("define_subgraph", "insert_workflow") #: Kinds a batch (``apply_specs``) dispatches. ``clear`` and ``reset_doc`` are #: standalone-only: they rewrite the whole document, so they never ride inside @@ -136,6 +139,7 @@ def _new_op(kind: str, actor: str, base_version: int, **fields: Any) -> dict[str "set_widget", "set_node_field", "delete_node", + "define_subgraph", ) #: Per-kind rendering for :class:`NotBatchableError` — the registered error code @@ -2155,20 +2159,21 @@ class NotExpressibleError(ValueError): def _inexpressible_reason(workflow: dict) -> str | None: """Why ``workflow`` cannot be rebuilt from add_node/connect ops, or None. - The frozen vocabulary has four batchable kinds and none of them can create a - subgraph definition, a canvas group, or a reroute point — so a graph that - carries any of those is not reconstructible from ops, full stop. Enumerated + The frozen vocabulary cannot create a canvas group or a reroute point, so a + graph that carries either is not reconstructible from ops. Enumerated positively (a closed list of things we know we CAN'T do) rather than by trying and checking, so an unexpressible template fails before it has written anything. """ if not isinstance(workflow, dict) or not isinstance(workflow.get("nodes"), list): return "not a frontend-format workflow (no `nodes` list) — only the save/UI format can be op-ified" - definitions = workflow.get("definitions") - if isinstance(definitions, dict) and definitions.get("subgraphs"): - return "the workflow contains a subgraph definition, which no frozen op kind can create" if workflow.get("groups"): return "the workflow contains canvas groups, which no frozen op kind can create" + definitions = workflow.get("definitions") + if definitions is not None and not isinstance(definitions, dict): + return "the workflow's `definitions` is not an object, so it is not a frontend-format workflow" + if definitions and definitions.get("subgraphs"): + return "the workflow contains subgraph definitions, which only cmp can project into ops" extra = workflow.get("extra") if isinstance(extra, dict) and (extra.get("reroutes") or extra.get("linkExtensions")): return "the workflow contains reroute points, which no frozen op kind can create" @@ -2941,6 +2946,14 @@ def apply_specs( workflow, op = delete_node( workflow, graph, resolve_ref(spec["node"], aliases), actor=actor, base_version=base_version ) + elif kind == "define_subgraph": + workflow, op = define_subgraph( + workflow, + spec["subgraph_definition"], + subgraph_id=spec.get("subgraph_id"), + actor=actor, + base_version=base_version, + ) elif kind in _NOT_BATCHABLE: # In the frozen vocabulary but standalone-only — surfaced with # its own registered code so the caller learns the standalone @@ -3002,7 +3015,9 @@ def apply_op(workflow: dict, op: dict, graph) -> dict: if op["op_id"] in applied: return workflow kind = op["op"] - if kind != "insert_workflow" and "definitions" in op: + if kind != "define_subgraph" and any(key in op for key in ("subgraph_id", "subgraph_definition")): + raise ValueError(f"malformed_op: {kind} cannot carry a subgraph definition") + if kind not in ("define_subgraph", "insert_workflow") and "definitions" in op: raise ValueError(f"malformed_op: {kind} does not accept definitions") # Snapshot the LWW bookkeeping so an exception escaping a handler cannot # leave a stamp committed WITHOUT its op_id recorded below. That pairing is @@ -3069,6 +3084,45 @@ def apply_op(workflow: dict, op: dict, graph) -> dict: return workflow +def define_subgraph( + workflow: dict, + definition: dict, + *, + subgraph_id: str | None = None, + actor: str = "cli", + base_version: int = 0, +) -> tuple[dict, dict]: + """Emit a definition op; cmp owns semantic validation and application.""" + if not isinstance(definition, dict): + raise ValueError("subgraph definition must be a JSON object") + definition = copy.deepcopy(definition) + if subgraph_id is not None: + definition_id = subgraph_id + elif "id" in definition: + definition_id = definition["id"] + else: + definition_id = str(uuid.uuid4()) + if not isinstance(definition_id, str) or not definition_id: + raise ValueError("subgraph definition requires a non-empty string id") + if not _SUBGRAPH_UUID_RE.fullmatch(definition_id): + raise ValueError("subgraph definition id must be a valid UUID") + if "id" in definition and definition["id"] != definition_id: + raise ValueError("subgraph definition id must match --id") + definition["id"] = definition_id + try: + json.dumps(definition, allow_nan=False) + except (TypeError, ValueError, RecursionError) as error: + raise ValueError("subgraph definition must be JSON-serializable") from error + op = _new_op( + "define_subgraph", + actor, + base_version, + subgraph_id=definition_id, + subgraph_definition=definition, + ) + return workflow, op + + def _retry_deferred_widget_ops(workflow: dict, graph) -> None: """Apply queued hidden-widget writes after a selector reveals their targets.""" while isinstance(pending := workflow.get("_deferred_widget_ops"), dict) and pending: @@ -3853,6 +3907,8 @@ def _write_target(op: dict) -> tuple: # top-level node 2011. return ("input", tuple(str(seg) for seg in op["path"]), str(op["to_node"]), op["to_slot"]) return ("input", str(op["to_node"]), op["to_slot"]) + if kind == "define_subgraph": + return ("subgraph", str(op["subgraph_id"])) return (kind,) diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index cb2793aeb..6dc5608ca 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -19,11 +19,11 @@ contains the contract version a consumer implements. ## 1. Frozen op kinds -Nine kinds as of amendment v1.8 — `disconnect` is the ninth and arrives with +Ten kinds as of amendment v1.8 — `disconnect` is the ninth and arrives with that amendment; see §1.2.1. `set_node_field` is the eighth and is **PROPOSED**, -not yet ratified; see §1.8 and §15. No other kind is valid in v1: `apply_op` -rejects an unknown kind with `ValueError("unknown op ...")` — it never ignores -one. +not yet ratified; see §1.8 and §15. `define_subgraph` is the tenth; see §1.9. +No other kind is valid in v1: `apply_op` rejects an unknown kind with +`ValueError("unknown op ...")` — it never ignores one. | Kind | Batchable | Standalone command | Summary | |------|-----------|--------------------|---------| @@ -35,6 +35,7 @@ one. | `delete_node` | yes | `comfy workflow delete` | Remove one node and its incident links | | `clear` | no | `comfy workflow clear` | Remove every node, link, and group | | `reset_doc` | no | `comfy workflow reset-doc --confirm` | Reset the whole document to an empty baseline | +| `define_subgraph` | yes | `comfy workflow define-subgraph` | Create one subgraph definition | | `insert_workflow` | no | `comfy workflow insert-workflow` | Merge a complete workflow template in one transaction | Batchable = the kind is accepted by `apply_specs` (the `workflow apply` / @@ -336,6 +337,33 @@ ratified) should confirm comfy-multi-player's applier accepts an op that omits `node_incarnation` rather than requiring one only because its own local model can need it. +### 1.9 `define_subgraph` + +Command: `comfy workflow define-subgraph [--id ]`. +The command performs envelope shape and JSON-serialization checks, assigns its +id from `--id`, the definition's `id`, or a new UUID, and emits exactly one +stamped op without modifying the local workflow: + +```json +{ + "op": "define_subgraph", + "op_id": "", + "actor": "cli", + "base_version": 0, + "stamp": [0, "cli"], + "subgraph_id": "", + "subgraph_definition": {"id": "", "nodes": [], "links": []} +} +``` + +Only this op may carry `subgraph_id` or `subgraph_definition`; `definitions` +is accepted only here and on `insert_workflow`. The CLI does not +semantically validate, apply, replay, project, or resolve conflicts for the +definition. cmp owns those operations: reusing an id with different content +returns `definition_conflict`, and references to unknown ids follow cmp's +unknown-node failure path. The CLI surfaces server errors verbatim. Subsequent +interior edits use the existing id-addressed op scopes. + ## 2. Idempotency and identity * Every op carries `op_id`: uuid4 hex, minted by the **creator, before diff --git a/tests/comfy_cli/command/test_workflow_edit.py b/tests/comfy_cli/command/test_workflow_edit.py index 7dc605e25..13dc7821b 100644 --- a/tests/comfy_cli/command/test_workflow_edit.py +++ b/tests/comfy_cli/command/test_workflow_edit.py @@ -1595,6 +1595,22 @@ def test_batch_is_atomic_on_failure(self, patched_graph, tmp_path, capsys): assert env["error"]["code"] == "workflow_edit_invalid" assert path.read_text() == before, "failed batch must not write a partial graph" + def test_deferred_op_batch_is_not_persisted_locally(self, patched_graph, tmp_path, capsys): + path = self._empty(tmp_path) + before = path.read_text() + ops_path = tmp_path / "ops.json" + ops_path.write_text( + json.dumps( + [{"op": "define_subgraph", "subgraph_definition": {"id": "12345678-1234-4123-8123-123456789abc"}}] + ) + ) + + env = _run(["apply", str(path), "--ops", str(ops_path)], capsys) + + assert env["ok"] is False + assert "deferred operation" in env["error"]["message"] + assert path.read_text() == before + def test_duplicate_alias_is_rejected(self, patched_graph, tmp_path, capsys): """A repeated `as` name would silently clobber the earlier node — reject it.""" path = self._empty(tmp_path) @@ -1814,6 +1830,58 @@ def test_foreach_bad_param_set_fails(self, patched_graph, tmp_path, capsys): assert env["ok"] is False assert "positive" in env["error"]["message"] + def test_foreach_rejects_deferred_ops_before_writing(self, patched_graph, tmp_path, capsys): + rp = tmp_path / "deferred.json" + rp.write_text( + json.dumps( + { + "ops": [ + {"op": "define_subgraph", "subgraph_definition": {"id": "12345678-1234-4123-8123-123456789abc"}} + ] + } + ) + ) + params = tmp_path / "sets.json" + params.write_text("[{}]") + out = tmp_path / "out" + + env = _run(["foreach", str(rp), "--params", str(params), "--out-dir", str(out)], capsys) + + assert env["ok"] is False + assert "deferred operation" in env["error"]["message"] + assert not list(out.glob("*.json")) + + def test_foreach_rejects_deferred_op_kind_that_only_appears_after_substitution( + self, patched_graph, tmp_path, capsys + ): + """The op kind itself may be a `${param}`. The up-front deferred check sees + only the template, so a param-set that resolves the kind to a deferred op + must still be refused as a deferred operation (not fall through to the + generic `unknown op` failure), and the earlier, valid set stays reported.""" + rp = tmp_path / "kind.json" + rp.write_text( + json.dumps( + { + "params": {"kind": {"type": "string"}}, + "ops": [ + {"op": "${kind}", "class_type": "KSampler", "as": "ks"}, + ], + } + ) + ) + params = tmp_path / "sets.jsonl" + params.write_text('{"kind":"add_node"}\n{"kind":"define_subgraph"}\n', encoding="utf-8") + out = tmp_path / "out" + + env = _run(["foreach", str(rp), "--params", str(params), "--out-dir", str(out)], capsys) + + assert env["ok"] is False + assert "deferred operation" in env["error"]["message"] + assert "define_subgraph" in env["error"]["message"] + assert "unknown op" not in env["error"]["message"] + written = env["error"]["details"]["written"] + assert len(written) == 1 and written[0].endswith("_000.json") + def test_foreach_surfaces_partial_writes_on_mid_batch_failure(self, patched_graph, tmp_path, capsys): """foreach writes per param-set; a mid-batch failure leaves earlier files on disk, so the error must surface them (not leave the caller blind).""" diff --git a/tests/comfy_cli/test_define_subgraph_op.py b/tests/comfy_cli/test_define_subgraph_op.py new file mode 100644 index 000000000..f156929e1 --- /dev/null +++ b/tests/comfy_cli/test_define_subgraph_op.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import copy +import json +import math +from pathlib import Path + +import pytest +import typer + +from comfy_cli import workflow_ops +from comfy_cli.command import workflow as workflow_cmd # noqa: F401 -- initializes the edit command cycle +from comfy_cli.command import workflow_edit + +SUBGRAPH_ID = "12345678-1234-4123-8123-123456789abc" + + +def _definition() -> dict: + return { + "id": SUBGRAPH_ID, + "name": "One", + "inputs": [], + "outputs": [], + "nodes": [{"id": 10, "type": "Inner"}], + "links": [], + } + + +def test_define_subgraph_emits_cmp_payload_without_mutating_workflow(): + workflow = {"nodes": [{"id": 1, "type": "Existing"}], "links": []} + before = copy.deepcopy(workflow) + definition = _definition() + + result, op = workflow_ops.define_subgraph(workflow, definition, actor="agent", base_version=4) + + assert result is workflow + assert workflow == before + assert op == { + "op": "define_subgraph", + "op_id": op["op_id"], + "actor": "agent", + "base_version": 4, + "stamp": [4, "agent"], + "subgraph_id": SUBGRAPH_ID, + "subgraph_definition": definition, + } + + +def test_define_subgraph_emits_semantically_odd_definition_for_cmp_validation(): + definition = {"id": SUBGRAPH_ID, "nodes": "future-cmp-shape", "links": {"also": "future"}} + + _, op = workflow_ops.define_subgraph({"nodes": [], "links": []}, definition) + + assert op["subgraph_definition"] == definition + + +def test_define_subgraph_rejects_local_replay(): + _, op = workflow_ops.define_subgraph({"nodes": [], "links": []}, _definition()) + + with pytest.raises(ValueError, match="unknown op 'define_subgraph'"): + workflow_ops.apply_op({"nodes": [], "links": []}, op, None) + + +def test_define_subgraph_can_assign_an_explicit_new_id(): + definition = _definition() + definition.pop("id") + + _, op = workflow_ops.define_subgraph({"nodes": [], "links": []}, definition, subgraph_id=SUBGRAPH_ID) + + assert op["subgraph_id"] == SUBGRAPH_ID + assert op["subgraph_definition"]["id"] == SUBGRAPH_ID + + +@pytest.mark.parametrize( + "subgraph_id", ["12345678-1234-0123-8123-123456789abc", "12345678-1234-4123-7123-123456789abc"] +) +def test_define_subgraph_rejects_invalid_uuid_version_or_variant(subgraph_id): + with pytest.raises(ValueError, match="valid UUID"): + workflow_ops.define_subgraph({"nodes": [], "links": []}, _definition(), subgraph_id=subgraph_id) + + +@pytest.mark.parametrize("non_finite", [math.nan, math.inf, -math.inf]) +def test_define_subgraph_rejects_non_finite_values(non_finite): + definition = _definition() + definition["nodes"][0]["value"] = non_finite + + with pytest.raises(ValueError, match="JSON-serializable"): + workflow_ops.define_subgraph({"nodes": [], "links": []}, definition) + + +def test_define_subgraph_command_emits_without_writing_workflow(tmp_path, monkeypatch): + workflow = tmp_path / "workflow.json" + original = {"nodes": [], "links": []} + workflow.write_text(json.dumps(original)) + definition_file = tmp_path / "definition.json" + definition_file.write_text(json.dumps(_definition())) + emitted = [] + + class Renderer: + command = "" + + def is_pretty(self): + return False + + def emit(self, payload, **kwargs): + emitted.append((payload, kwargs)) + + monkeypatch.setattr(workflow_edit, "get_renderer", Renderer) + + workflow_edit.define_subgraph_cmd(str(workflow), str(definition_file)) + + assert json.loads(workflow.read_text()) == original + assert emitted[0][0]["op"]["op"] == "define_subgraph" + assert emitted[0][0]["wrote"] is None + assert emitted[0][1]["changed"] is False + + +def test_define_subgraph_command_rejects_non_regular_definition_file(tmp_path, monkeypatch): + workflow = tmp_path / "workflow.json" + workflow.write_text(json.dumps({"nodes": [], "links": []})) + definition_dir = tmp_path / "definition" + definition_dir.mkdir() + errors = [] + + class Renderer: + command = "" + + def error(self, **kwargs): + errors.append(kwargs) + + monkeypatch.setattr(workflow_edit, "get_renderer", Renderer) + with pytest.raises(typer.Exit): + workflow_edit.define_subgraph_cmd(str(workflow), str(definition_dir)) + + assert "regular file" in errors[0]["message"] + + +def test_definition_reader_rejects_oversized_files(tmp_path): + path = tmp_path / "large.json" + path.write_bytes(b" " * (workflow_edit._MAX_DEFINITION_BYTES + 1)) + + with pytest.raises(ValueError, match="too large"): + workflow_edit._read_subgraph_definition(Path(path)) + + +def test_define_subgraph_command_is_emit_only_in_its_own_contract(): + """The command never writes the workflow, so it must not advertise otherwise: + no ``--stdout/--in-place`` switch (there is nothing to write in place) and a + file help text that says emit-only, matching ``insert-workflow``.""" + import inspect + import typing + + signature = inspect.signature(workflow_edit.define_subgraph_cmd) + assert "stdout" not in signature.parameters + + hints = typing.get_type_hints(workflow_edit.define_subgraph_cmd, include_extras=True) + (_, typer_arg) = typing.get_args(hints["file"]) + assert "not modified" in typer_arg.help + assert "to update" not in typer_arg.help + + +def test_replace_ops_refuses_non_object_definitions_instead_of_crashing(): + """``definitions`` that is truthy but not an object must be a clean refusal, + not an AttributeError from ``.get`` on a list or string.""" + for definitions in (["not", "a", "dict"], "subgraphs", 7): + new = {"nodes": [], "links": [], "definitions": definitions} + with pytest.raises(workflow_ops.NotExpressibleError, match="definitions"): + workflow_ops.replace_ops({"nodes": [], "links": []}, new)