diff --git a/README.md b/README.md index 9ab67ff..d88e92d 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ def make_cube(size: Float["Size"] = 2.0) -> Geometry: ``` 5. Return to the NodeForge sidebar and select the new text in **Text Script**. -6. Click **Compile Script**. NodeForge places a `make_cube` Group Node in the existing base Geometry Nodes tree; its implementation lives in a nested node group. +6. Click **Compile Script**. NodeForge creates a `make_cube` node-group datablock. 7. Connect the Group Node's **Value** output to the existing **Group Output** geometry input. See the [Get Started guide](https://denikryt.github.io/NodeForge/docs/latest/GET_STARTED/) for the complete beginner workflow. diff --git a/__init__.py b/__init__.py index 4d1d82e..8d958c1 100644 --- a/__init__.py +++ b/__init__.py @@ -1,13 +1,13 @@ """NodeForge Blender addon package.""" -NODEFORGE_VERSION = (0, 93, 3) +NODEFORGE_VERSION = (0, 94, 2) bl_info = { "name": "NodeForge", "author": "nachitima", "version": NODEFORGE_VERSION, "blender": (5, 2, 0), - "location": "Geometry Nodes Editor > Sidebar > NodeForge > Compile/Update Script; Add Menu > Script > Compile Group", + "location": "Geometry Nodes Editor > Sidebar > NodeForge > Compile Script; Add Menu > Script > Compile Group", "description": "Compile a Python-like DSL into Geometry Nodes node groups. Catalog library: reusable functions, bundled examples, and user-owned local DSL scripts.", "category": "Node", } diff --git a/blender/direct_composition.py b/blender/direct_composition.py index 7b02446..81e8bb6 100644 --- a/blender/direct_composition.py +++ b/blender/direct_composition.py @@ -1,15 +1,10 @@ -"""Initial NodeForge composition into a caller-owned base GeometryNodeTree. - -This is an internal target-specific lowering primitive. It does not replace or -manage nodes inserted during an earlier successful composition operation. -""" +"""Lower prepared physical root IR using an externally managed build attempt.""" from __future__ import annotations from ..errors import CompileError from ..function_instances import FunctionCompilationTrace from .function_materializer import FunctionMaterializationContext, FunctionMaterializer -from .group_backend import BlenderGroupBuildTransaction from .ir_lowering import BlenderIRLoweringContext, lower_body @@ -27,83 +22,57 @@ def validate_prepared_direct(prepared, target): 'direct base-tree installation is unavailable') -def compose_prepared_initial(prepared, target, backend, session, *, source_module, - transaction=None): - """Lower prepared source in place; a supplied nested transaction remains caller-owned. +def compose_prepared_initial(prepared, target, backend, session, *, + transaction, root_input_endpoint): + """Lower root IR; the calling root updater owns commit, cleanup and rollback. - Every attempt cleans up only its own newly inserted root nodes. An - internally created transaction is committed or rolled back here; an - externally supplied one is neither committed nor rolled back here. + The transaction and canonical input endpoint belong to the same outer root + attempt, including all nested inline expansions targeting this tree. """ - validate_prepared_direct(prepared, target) - preexisting_nodes = {node.as_pointer() for node in target.nodes} - own_transaction = transaction is None - if transaction is None: - transaction = BlenderGroupBuildTransaction() - cache = {} - trace = FunctionCompilationTrace() + if not prepared.body.statements: + raise CompileError( + 'Root lowering requires a physical top-level body; ' + 'definition-only sources use GROUPS_ONLY publication' + ) context = BlenderIRLoweringContext( group=target, runtime_bindings={}, source_callable_session=session, function_materializer=FunctionMaterializer(group_backend=backend), function_materialization_context=FunctionMaterializationContext( - function_group_cache=cache, + function_group_cache={}, function_group_transaction=transaction, - function_compilation_trace=trace, + function_compilation_trace=FunctionCompilationTrace(), source_callable_session=session, ), helper_namespace=target.name, extension_registry=session.resolved_environment.extension_registry, + root_input_endpoint=root_input_endpoint, ) - try: - if prepared.body.statements: - lower_body(context, prepared.body, {}, base_depth=1) - else: - _place_definition_entries(prepared, context, source_module) - if own_transaction: - transaction.commit() - except Exception as error: - cleanup_failure = None - for node in tuple(target.nodes): - if node.as_pointer() not in preexisting_nodes: - try: - target.nodes.remove(node) - except Exception as exc: - if cleanup_failure is None: - cleanup_failure = exc - if own_transaction: - try: - transaction.rollback() - except Exception as exc: - if cleanup_failure is None: - cleanup_failure = exc - if cleanup_failure is not None: - error.add_note(f"Direct-composition node cleanup or rollback also failed: {cleanup_failure}") - raise error from cleanup_failure - raise + # NODEFORGE-TEMP-ISSUE61-ROOT-STAGING: Root-producing Compile still lowers in the authoritative tree while physical Extension API v2 is rejected in root. Issue #61 PR 2 must replace this call with native-copy private staging and strict subgraph transfer; delete this marker when no backend can receive the authoritative root. + lower_body(context, prepared.body, {}, base_depth=1) return target -def _place_definition_entries(prepared, context, snapshot): - """Place zero-incoming source functions without treating them as DSL calls. +def materialize_definition_entries(prepared, materializer, materialization_context, snapshot): + """Publish only zero-incoming source definitions, without root node placement. - Required inputs deliberately remain unconnected. Input types come only - from validated annotations; defaults do not supply missing types. + The caller owns the shared group transaction and its commit/rollback. The + same source-function IDs and materializer are used by direct compilation. """ from ..compiler_identities import GroupCompilationIdentity, module_definition_function_id from ..function_instances import function_materialization_owner_scope from ..semantic.function_signatures import compile_function_signature from ..semantic.source_callables import serialize_local_signature from ..semantic.ir import IRFunctionMaterialization, IRFunctionMaterializationMode - from .library_groups import apply_function_node_display_name graph = prepared.source_call_graph if graph is None: - raise CompileError('Definition-only initial placement lacks a resolved call graph') - session = context.source_callable_session + raise CompileError('Definition-only compilation lacks a resolved call graph') + session = materialization_context.source_callable_session env, compile_time_values = session.callable_environment_for_module(snapshot) - for index, reference in enumerate(graph.entries): + groups = [] + for reference in graph.entries: fn = snapshot.definitions[reference.name] signature = compile_function_signature( fn, owner_scope=reference.stable_key(), @@ -123,10 +92,7 @@ def _place_definition_entries(prepared, context, snapshot): compile_time_values=compile_time_values, source_module=snapshot, helper_namespace=fn.name, ) - nested = context.function_materializer.materialize_module( - prepared_callable, materialization, context.function_materialization_context, - ) - node = context.group.nodes.new('GeometryNodeGroup') - node.node_tree = nested.group - node.location = (index * 260, 0) - apply_function_node_display_name(node, nested.group) + groups.append(materializer.materialize_module( + prepared_callable, materialization, materialization_context, + ).group) + return tuple(groups) diff --git a/blender/ir_lowering.py b/blender/ir_lowering.py index 2d81926..2ba4fbd 100644 --- a/blender/ir_lowering.py +++ b/blender/ir_lowering.py @@ -34,7 +34,7 @@ from .nodes import _id as _field_id, _index as _field_index, _normal as _field_normal, _position as _field_position from .bundle import build_bundle, build_bundle_get, build_bundle_set from .object_info import resolve_object_property_explicit -from .raw_nodes import build_materialized_raw_node +from .raw_nodes import build_materialized_raw_node, read_existing_raw_group_input from .extension_backend import lower_extension_call from ..semantic.ir import ( IRBinary, @@ -127,6 +127,14 @@ def _create_repeat_zone(group, state_specs, index_name, x=0, y=0): return ri, ro +@dataclass +class RootInputEndpoint: + """One mutable root-only Group Input selection for a compilation attempt.""" + + node: object | None = None + created_by_attempt: bool = False + + @dataclass(frozen=True) class BlenderIRLoweringContext: """Explicit Blender backend inputs for one Semantic IR lowering operation. @@ -147,6 +155,7 @@ class BlenderIRLoweringContext: extension_registry: object | None = None generated_resource_transaction: object | None = None layout_origin: tuple[float, float] = (0.0, 0.0) + root_input_endpoint: RootInputEndpoint | None = None def __post_init__(self): """Freeze value bindings while retaining explicit mutable backend-owned maps.""" @@ -527,6 +536,27 @@ def _lower_builtin_call(context, operation, operands, x, y): raise CompileError(f"Internal error: unknown raw-node input mode {mode!r}") raw_inputs.append((selector, value_spec)) outputs = options["outputs"] + endpoint = getattr(context, 'root_input_endpoint', None) + if options["bl_idname"] == 'NodeGroupInput' and endpoint is not None: + if endpoint.node is None: + node = next((item for item in group.nodes if item.bl_idname == 'NodeGroupInput'), None) + if node is None: + result = build_materialized_raw_node( + group, bl_idname='NodeGroupInput', props=dict(options['props']), + inputs=raw_inputs, output=options['output'], typ=options['typ'], + outputs=list(outputs) if outputs is not None else None, + x=x, y=y, context='node()', + ) + endpoint.node = result[0].socket.node if isinstance(result, tuple) else result.socket.node + endpoint.created_by_attempt = True + return result + endpoint.node = node + return read_existing_raw_group_input( + endpoint.node, props=dict(options['props']), inputs=raw_inputs, + output=options['output'], typ=options['typ'], + outputs=list(outputs) if outputs is not None else None, + context='node()', + ) return build_materialized_raw_node( group, bl_idname=options["bl_idname"], @@ -662,6 +692,7 @@ def _lower_inline_source_call(context, operation, operands, prepared, x, y): extension_registry=context.extension_registry, generated_resource_transaction=context.generated_resource_transaction, layout_origin=child_origin, + root_input_endpoint=context.root_input_endpoint, ) result = lower_body(bound_context, prepared.group.body, inputs, base_depth=0) outputs = result.explicit_outputs if result.explicit_outputs else ( diff --git a/blender/raw_nodes.py b/blender/raw_nodes.py index 3232e92..7aeb0ec 100644 --- a/blender/raw_nodes.py +++ b/blender/raw_nodes.py @@ -232,6 +232,60 @@ def build_materialized_raw_node( return make_value(socket, out_typ) +def read_existing_raw_group_input(node, *, props, inputs, output, typ, outputs, + context="node()"): + """Read one retained Group Input without changing its RNA, links or metadata. + + The root compositor has selected the canonical physical node. This uses + the same selector/physical-type checks as new raw-node construction, but + treats any requested properties as assertions about current RNA state. + """ + if getattr(node, 'bl_idname', None) != 'NodeGroupInput': + raise CompileError(f"{context}: expected a canonical NodeGroupInput") + if not isinstance(props, dict) or not isinstance(inputs, (list, tuple)): + raise CompileError(f"{context}: invalid raw-node props or inputs") + if inputs: + raise CompileError(f"{context}: NodeGroupInput has no assignable input sockets") + for name, requested in props.items(): + if not isinstance(name, str) or not name or name.startswith('['): + raise CompileError(f"{context}: invalid raw node property {name!r}") + prop = node.bl_rna.properties.get(name) + if prop is None or getattr(prop, 'is_readonly', False): + raise CompileError(f"{context}: invalid or read-only property {name!r} on NodeGroupInput") + actual = _normalize_json_value(getattr(node, name), f"{context}: property {name!r}") + expected = _normalize_json_value(requested, f"{context}: property {name!r}") + if not _normalized_equal(actual, expected): + raise CompileError(f"{context}: existing NodeGroupInput property {name!r} differs from requested value") + + if outputs is None: + if output is None or typ is None: + raise CompileError(f"{context}: raw node requires an output and type") + _validate_public_type(typ, f"{context}: typ") + declarations = [(None, output, typ)] + else: + if not isinstance(outputs, (list, tuple)) or not outputs: + raise CompileError(f"{context}: outputs cannot be empty") + declarations = outputs + selected = [] + for item in declarations: + if not isinstance(item, (list, tuple)) or len(item) != 3: + raise CompileError(f"{context}: outputs must contain (alias, selector, type) triples") + alias, selector, out_typ = item + if outputs is not None and (not isinstance(alias, str) or not alias): + raise CompileError(f"{context}: output aliases must be non-empty strings") + _validate_public_type(out_typ, f"{context}: output type") + label = _selector_label(selector) + socket = resolve_socket(node.outputs, selector, direction='output', context=context) + _validate_runtime_socket_type(socket, out_typ, direction='output', context=context, socket_name=label) + _capture_physical_socket_ref(socket, direction='output', context=f"{context}: output {label}") + _reject_duplicate_physical_socket( + selected, socket, context=f"{context}: two output selectors resolve to the same physical socket", + ) + selected.append(socket) + values = tuple(make_value(socket, item[2]) for socket, item in zip(selected, declarations)) + return values if outputs is not None else values[0] + + def _selector_label(selector) -> str: """Return a user-facing diagnostic label for one normalized source selector.""" if isinstance(selector, str): diff --git a/blender/root_update.py b/blender/root_update.py index 23295f2..dc63491 100644 --- a/blender/root_update.py +++ b/blender/root_update.py @@ -328,9 +328,10 @@ def _fail(error, failures, *, possible_change): raise RootUpdateError(summary, may_have_mutated=possible_change or bool(failures)) from error -def replace_prepared_root(prepared, target, backend, session, *, source_module): +def replace_prepared_root(prepared, target, backend, session): """Stage exactly once into `target`, cut over and commit nested groups last.""" from .direct_composition import compose_prepared_initial, validate_prepared_direct + from .ir_lowering import RootInputEndpoint validate_base_target(target) reject_node_local_animation(target) @@ -349,6 +350,7 @@ def replace_prepared_root(prepared, target, backend, session, *, source_module): if node.parent is not None and node.parent.as_pointer() in old_ptrs} boundary = _boundary(target) transaction = BlenderGroupBuildTransaction() + endpoint = RootInputEndpoint() backup = None cutover_started = False io_detach_started = False @@ -356,11 +358,17 @@ def replace_prepared_root(prepared, target, backend, session, *, source_module): backup = target.copy() mark_transaction_private(backup) compose_prepared_initial(prepared, target, backend, session, - source_module=source_module, transaction=transaction) + transaction=transaction, root_input_endpoint=endpoint) created = tuple(node for node in target.nodes if node.as_pointer() not in preexisting_ptrs) - if any(node.bl_idname in _IO_TYPES for node in created): - raise CompileError('Direct Update cannot insert new structural Group Input/Output nodes') - new = created + allowed_input = (endpoint.node.as_pointer() if endpoint.created_by_attempt + and endpoint.node is not None else None) + if any(node.bl_idname == 'NodeGroupOutput' + or (node.bl_idname == 'NodeGroupInput' and node.as_pointer() != allowed_input) + for node in created): + raise CompileError('Compile cannot insert unapproved structural Group Input/Output nodes') + if _interface_signature(target) != interface_before: + raise CompileError('Compile changed the root interface during staging') + new = tuple(node for node in created if node.bl_idname not in _IO_TYPES) matched = _matches(old, new) for node in io_nodes: if node.parent is not None and node.parent.as_pointer() in old_ptrs: diff --git a/blender_manifest.toml b/blender_manifest.toml index fa2e7db..5a2a355 100644 --- a/blender_manifest.toml +++ b/blender_manifest.toml @@ -1,6 +1,6 @@ schema_version = "1.0.0" id = "nodeforge" -version = "0.93.3" +version = "0.94.2" name = "NodeForge" tagline = "Compile a procedural DSL into Blender Geometry Nodes" maintainer = "nachitima" diff --git a/compiler.py b/compiler.py index c79ac23..13bf8b0 100644 --- a/compiler.py +++ b/compiler.py @@ -1,5 +1,7 @@ """Public compiler facade and root build orchestration.""" +from dataclasses import dataclass + from .errors import CompileError from .blender.library_groups import ( materialize_library_entry_group_for_record, @@ -121,7 +123,7 @@ def create_expression_group(source: str, name: str = "NodeForge Group"): """Materialize exactly one standalone unified `.nf` definition. This API no longer accepts a generated-root script or implicit root I/O. - Use ``compose_source_initial`` for executable top-level composition. + Use ``compile_source_in_tree`` for executable top-level composition. """ from uuid import uuid4 from .compiler_identities import ModuleId @@ -152,8 +154,14 @@ def _prepare_direct_source(source: str, target, *, resolved_environment=None, raise CompileError("Direct composition requires an existing base GeometryNodeTree") backend = _new_group_backend(resolved_environment) session = backend.new_source_callable_session() - module_id = ModuleId("ROOT_TEXT", module_context or f"base-tree:{target.name}") + module_id = ModuleId("ROOT_TEXT", module_context if isinstance(module_context, str) and module_context.strip() else f"base-tree:{target.name}") snapshot = parse_source_module(source, module_id) + if snapshot.definitions and ( + not isinstance(module_context, str) + or not module_context.strip() + or module_context != module_context.strip() + ): + raise CompileError("Source definitions require a stable module_context") owner_scope = function_group_owner_scope("COMPOSITION", module_id.stable_key()) identity = GroupCompilationIdentity(None, owner_scope, owner_scope, owner_scope) prepared = analyze_group_source( @@ -166,39 +174,70 @@ def _prepare_direct_source(source: str, target, *, resolved_environment=None, return prepared, backend, session, snapshot -def compose_source_initial(source: str, target, *, resolved_environment=None, - module_context: str | None = None): - """Append one typed `.nf` composition directly to an existing base tree.""" - from .blender.direct_composition import compose_prepared_initial +@dataclass(frozen=True) +class RootCompileResult: + """One unified root compilation outcome and its boundary-link losses.""" - prepared, backend, session, snapshot = _prepare_direct_source( - source, target, resolved_environment=resolved_environment, - module_context=module_context, - ) - return compose_prepared_initial(prepared, target, backend, session, source_module=snapshot) + target: object + outcome: str + skipped_boundary_links: int = 0 -def update_source_in_tree(source: str, target, *, module_context: str | None = None): - """Replace ordinary nodes of an eligible base GeometryNodeTree in place. +def compile_source_in_tree(source: str, target, *, module_context: str | None = None, + resolved_environment=None) -> RootCompileResult: + """Replace root nodes for physical statements or publish definition groups only. - Returns ``RootUpdateResult`` with the number of skipped old boundary links. - A ``RootUpdateError.may_have_mutated`` flag distinguishes errors that require - an Undo step from preflight or fully cleaned staging failures. + The semantic body is the sole mode selector; no source text or historical + root state decides which physical graph owns this invocation. """ - from .blender.root_update import ( - validate_base_target, reject_node_local_animation, replace_prepared_root, - ) + from .blender.root_update import validate_base_target, reject_node_local_animation, replace_prepared_root + from .blender.direct_composition import materialize_definition_entries + from .blender.function_materializer import FunctionMaterializationContext, FunctionMaterializer + from .blender.group_backend import BlenderGroupBuildTransaction + from .function_instances import FunctionCompilationTrace validate_base_target(target) if not isinstance(source, str) or not source.strip(): - raise CompileError('Update Script requires a nonblank selected Text source') - reject_node_local_animation(target) + raise CompileError('Compile Script requires a nonblank selected Text source') prepared, backend, session, snapshot = _prepare_direct_source( - source, target, module_context=module_context, + source, target, resolved_environment=resolved_environment, + module_context=module_context, ) - return replace_prepared_root( - prepared, target, backend, session, source_module=snapshot, + if prepared.body.statements: + reject_node_local_animation(target) + updated = replace_prepared_root(prepared, target, backend, session) + return RootCompileResult(target, 'ROOT_REPLACEMENT', updated.skipped_boundary_links) + + transaction = BlenderGroupBuildTransaction() + context = FunctionMaterializationContext( + function_group_cache={}, function_group_transaction=transaction, + function_compilation_trace=FunctionCompilationTrace(), + source_callable_session=session, ) + try: + materialize_definition_entries( + prepared, FunctionMaterializer(group_backend=backend), context, snapshot, + ) + transaction.commit() + except Exception as original_error: + if transaction._closed: + # Commit has crossed the point of no return. A cleanup warning + # promoted to an exception cannot be repaired by rollback. + from .blender.root_update import RootUpdateError + raise RootUpdateError( + f"Function groups were committed, but postcommit cleanup failed: {original_error}", + may_have_mutated=True, + ) from original_error + try: + transaction.rollback() + except Exception as rollback_error: + from .blender.root_update import RootUpdateError + raise RootUpdateError( + f"Function-group rollback failed after {original_error}: {rollback_error}", + may_have_mutated=True, + ) from rollback_error + raise + return RootCompileResult(target, 'GROUPS_ONLY', 0) def _requires_mesh_compute(prepared) -> bool: @@ -207,7 +246,8 @@ def _requires_mesh_compute(prepared) -> bool: for owner, _ in prepared.extension_dependencies) -def compile_script_auto(source: str, owner=None, name: str = "NodeForge Group"): +def compile_script_auto(source: str, owner=None, name: str = "NodeForge Group", + *, module_context: str | None = None): """Compile top-level `.nf` only into the explicitly supplied base node tree. ``name`` is retained for callers, not used to create a generated root. @@ -219,7 +259,7 @@ def compile_script_auto(source: str, owner=None, name: str = "NodeForge Group"): 'Unified Compile Script requires an existing base GeometryNodeTree; ' 'generated-root and modifier compilation are unsupported' ) - compose_source_initial(source, owner) + compile_source_in_tree(source, owner, module_context=module_context) return owner, False diff --git a/dev/CHANGELOG.md b/dev/CHANGELOG.md index e9959c2..8edef2a 100644 --- a/dev/CHANGELOG.md +++ b/dev/CHANGELOG.md @@ -758,3 +758,23 @@ lifecycle. - Materialize omitted or explicit static Rotation arguments in inline source calls using Blender's native Input Rotation node, preserving canonical XYZ angles and typed socket connections. - Added inline Rotation regression coverage for argument binding, nested calls, grouped callers, and native geometry evaluation. - Keep the inline Rotation implementation plan local under the ignored `plans/` directory. + +## 0.94.0 + +- Unified root compilation under one `Compile Script`: a physical top-level body replaces ordinary root nodes, while a definition-only or compile-time-only source updates eligible function group datablocks without modifying root topology. +- Made stable `module_context` mandatory for local source definitions and kept their authoritative Node Group identities across root renames and selected Text Reload. +- Reused one canonical root `NodeGroupInput` for raw reads in nested inline calls, preserving physical socket identifiers and existing user properties; rejected new Group Outputs during root replacement. +- Preserved Undo signaling for incomplete function-group rollback and removed the separate Update operator and append-only root API. +- Added Blender 5.2 regression coverage for both Compile outcomes, Group Input reuse, error recovery, and updated characterization baselines. + +## 0.94.1 + +- Preserve the Undo-required error signal when GROUPS_ONLY postcommit cleanup raises after authoritative function groups have been published. +- Reject definition-only IR in the internal root-lowering helper instead of placing obsolete group-instance nodes in the root tree. +- Add Blender regressions for postcommit warning escalation, non-escalated cleanup warnings, and direct internal-helper rejection. + +## 0.94.2 + +- Simplified root-producing compilation so the root updater alone owns its group transaction, staged-node cleanup, rollback, and Undo uncertainty. The internal lowering helper now requires its caller-provided transaction and canonical Group Input endpoint. +- Removed unused source-module forwarding through root lowering and added Blender regression coverage for delegated error cleanup and one transaction owner. +- Updated the user documentation for unified Compile Script modes, manual placement and refresh of function groups, mode transitions, and base-tree Group Input reuse. diff --git a/docs/BUILTINS.md b/docs/BUILTINS.md index 4de2504..63e434e 100644 --- a/docs/BUILTINS.md +++ b/docs/BUILTINS.md @@ -783,7 +783,7 @@ def example(): Creates a Blender node directly. Use this for Blender node types that are not exposed through a dedicated NodeForge built-in. The dictionary expressions shown here are special compile-time syntax accepted only in arguments to `node(...)`; general DSL dictionaries remain unsupported. -`bl_idname`, node properties, socket selectors, output aliases, and type tokens are compile-time declarations. Runtime values are allowed inside `inputs={...}` and are linked to the selected Blender input sockets. `props=` is applied before socket selectors are resolved, so selectors see the node configuration produced by those properties. +`bl_idname`, node properties, socket selectors, output aliases, and type tokens are compile-time declarations. Runtime values are allowed inside `inputs={...}` and are linked to the selected Blender input sockets. `props=` is applied before socket selectors are resolved, so selectors see the node configuration produced by those properties. Reusing a [base-tree Group Input](#base-tree-group-input) checks its existing properties instead. Supported type tokens are `Float`, `Int`, `Bool`, `Vector`, `Color`, `Geometry`, `Material`, `Object`, `String`, and `Bundle`. A `Color`-typed result maps exactly to Blender `NodeSocketColor`; `typ=Color` is a strict output type assertion. Color input sockets accept four-component RGBA tuple literals as defaults. @@ -877,6 +877,21 @@ def example(): Raw-node declarations are validated before defaults, links, or result bindings are applied. Newly generated raw-node metadata stores Blender socket identifiers so later updates can fail closed if the physical node schema no longer matches the declaration. +### Base-tree Group Input + +During **Compile Script** root replacement, `node("NodeGroupInput", ...)` reads the base tree's existing interface inputs. Create the interface sockets in Blender first. For a Float input named **Radius**: + +```python +radius = node("NodeGroupInput", output="Radius", typ=Float) +shape = cube(radius) +``` + +All such reads use the first existing Group Input in the tree's node order, including reads inside inline functions and control-flow bodies. If the tree has no Group Input, the first read creates one. Further reads and later compiles reuse it. Other existing Group Input nodes remain in place. A script that never requests a Group Input creates none. + +Reusing the selected node preserves its position, label, and properties. Links to replaced nodes follow the [base-tree compilation rules](GET_STARTED.md#update-a-script). On reuse, each supplied `props` value must already match the node's current property; a conflicting, unknown, or read-only property raises an error. The first call that creates a Group Input can set its properties normally. Each read validates its socket selectors and types against the existing sockets. Single-output and named `outputs=` forms use the selectors described above. + +This reuse applies to reads targeting the base tree. Separately compiled function groups construct their own raw nodes. Creating a new Group Output through `node()` during root replacement is unsupported; connect generated results to the base tree's existing Group Output in Blender. + ## Runtime loops `repeat_range(...)` creates a Blender Repeat Zone. For the compile-time and runtime forms of `range(...)`, see [`range` Loops](#range-loops). diff --git a/docs/CORE_CONCEPTS.md b/docs/CORE_CONCEPTS.md index ae60a40..4295e22 100644 --- a/docs/CORE_CONCEPTS.md +++ b/docs/CORE_CONCEPTS.md @@ -36,7 +36,7 @@ Each Group Node instance can have different input values or incoming links. Chan ## Modules and functions -A `.nf` file is a module. It can declare several functions, create nodes directly with top-level statements, or combine both. Calls to its functions create Group Nodes; functions can call other functions. A module with no executable top-level statements places its entry functions as Group Nodes when compiled. See [`.nf` Modules](MODULES.md) for the placement rules and examples. +A `.nf` file is a module. It can declare several functions, create nodes directly with top-level statements, or combine both. Grouped function calls create Group Nodes; functions can call other functions. A module without top-level node-building code creates or updates entry function groups for manual placement. See [`.nf` Modules](MODULES.md#compose-the-base-tree) for compilation modes and examples. ## Imports diff --git a/docs/EXTENSION_API.md b/docs/EXTENSION_API.md index ea9f0f7..5fa3429 100644 --- a/docs/EXTENSION_API.md +++ b/docs/EXTENSION_API.md @@ -431,7 +431,7 @@ Semantic and backend modules are loaded lazily for the phase that uses them. Do A new root compilation resolves a new package environment snapshot and uses it consistently for nested calls. -Call Python-backed extensions that create Blender nodes inside a typed `.nf` function. **Compile Script** and **Update Script** reject those calls directly at module level in the existing base tree. The function supplies a separate node group for the extension's nodes. Mesh Compute callbacks use the dedicated entry-function and modifier workflow described in [Mesh Compute](MESH_COMPUTE.md). +Call Python-backed extensions that create Blender nodes inside a grouped typed `.nf` function. **Compile Script** rejects those calls directly in the base tree, including calls inside inline functions expanded there. The grouped function supplies a separate node group for the extension's nodes. Mesh Compute callbacks use the dedicated entry-function and modifier workflow described in [Mesh Compute](MESH_COMPUTE.md). ## Validation diff --git a/docs/GET_STARTED.md b/docs/GET_STARTED.md index f8a2df1..5996748 100644 --- a/docs/GET_STARTED.md +++ b/docs/GET_STARTED.md @@ -36,7 +36,7 @@ def make_cube(size: Float["Size"] = 2.0) -> Geometry: 5. Select that Text in **Text Script** and click **Compile Script**. -The function becomes a Group Node in the open base tree. Connect its output to the base tree's **Group Output** Geometry input to display the cube. Change **Size** on the Group Node to see Blender reevaluate it. +Compilation creates the `make_cube` node-group datablock. In the Geometry Node Editor, use **Add → Group** to place an instance of that group. Connect its output to the base tree's **Group Output** Geometry input to display the cube. Change **Size** on the Group Node to see Blender reevaluate it. A script can also build ordinary nodes directly: @@ -44,24 +44,23 @@ A script can also build ordinary nodes directly: geometry = cube(2.0) ``` -**Compile Script** adds these nodes to the open base tree. It keeps existing nodes and does not connect the base tree's Group Input/Output automatically. +**Compile Script** replaces all ordinary nodes in the open base tree with this script's nodes, including the manually placed Group Node from the previous example. Connect the Cube output to **Group Output** to display it. ## Update a script -Edit the source in a Text datablock, select it under **Text Script**, open the base Geometry Nodes tree, and click **Update Script**. Each update uses the currently selected Text. The action recompiles its root graph and called functions, including nested function groups. It replaces the tree's ordinary nodes, including Group Nodes, while keeping the physical tree, its interface, and its Group Input/Output nodes. +Edit the source in a Text datablock, select it under **Text Script**, open the base Geometry Nodes tree, and click **Compile Script** again. With top-level node-building code, compilation replaces every ordinary node, including manually created nodes and Group Nodes. It keeps the base tree, its interface sockets and defaults, its Group Input/Output nodes, and references from modifiers or other groups. -Compatible unambiguous links between the root interface nodes and rebuilt nodes can be restored; other manual connections between ordinary nodes are replaced by the script's graph. Inspect boundary links after updating, especially if node types or counts changed. Repeated **Update Script** calls replace rather than accumulate nodes. **Compile Script** adds to the existing graph. A module containing only compile-time constants clears the ordinary nodes when used with **Update Script**; a module containing only declarations places its entry functions. An empty or invalid source is rejected. +Compatible unambiguous links between the base tree's Group Input/Output nodes and rebuilt nodes can be restored; manual connections between replaced nodes are replaced by the script's graph. Inspect interface links after compiling, especially if node types or counts changed. A warning reports links that could not be restored. -Update does not migrate animation or drivers on ordinary root nodes; a tree containing them cannot be updated with this action. +With only function declarations or compile-time statements, compilation preserves the base graph and updates eligible function groups. See [Compose the base tree](MODULES.md#compose-the-base-tree) for mode selection, manual group instances, and switching between the two workflows. Empty or invalid source is rejected. -Both script actions require an editable base tree in the Geometry Nodes editor. Linked read-only trees and NodeForge-managed function or Mesh Compute trees are unsupported targets. Return from any nested group before using them. +Root replacement rejects animation or drivers on ordinary base-tree nodes. **Compile Script** requires an editable base tree in the Geometry Nodes editor for both modes. Linked read-only trees and NodeForge-managed function or Mesh Compute trees are unsupported targets. Return from any nested group before compiling. ## Main actions | Button | What it does | | --- | --- | -| **Compile Script** | Adds the selected Text's nodes or entry functions to the open base tree. | -| **Update Script** | Replaces ordinary nodes in the open base tree from the selected Text. | +| **Compile Script** | Replaces ordinary base-tree nodes for top-level node-building code; otherwise creates or updates function groups. | | **Reload Function from Source** | Rebuilds a selected source-backed Function Group from its current source. | | **Load Script From Selected NodeGroup** | Copies the selected function's stored module source into the selected Text, replacing its contents. | | **Install Mesh Compute** / **Reload Compute** | Install or reload an experimental [Mesh Compute](MESH_COMPUTE.md) modifier on a Mesh object. | diff --git a/docs/MODULES.md b/docs/MODULES.md index c2b675b..8d03665 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -56,12 +56,20 @@ moved = transform(shape, translation=vector(0, 0, 1)) **Compile Script** uses the module in one of two ways: -- With top-level node-building code, it adds those nodes to the base tree. A function called there appears as a Group Node; functions it calls appear inside that group. Unused declarations add no node. -- Without top-level node-building code, it places the module's entry functions as Group Nodes in the base tree, even without calls. An entry is a function that no other function in the module calls. The declaration-only example places a Group Node for `small_cube` and one for `large_cube`. Required inputs on these nodes remain unlinked. +- With top-level node-building code, it replaces all ordinary nodes in the base tree, including manually created nodes and Group Nodes. Group Input and Group Output nodes remain in place. A grouped function call creates a Group Node; functions it calls appear inside that group. Unused declarations add no node. +- Without top-level node-building code, it creates or updates the module's entry function node-group datablocks and their required dependencies. An entry is a function that no other function in the module calls. The declaration-only example creates groups for `small_cube` and `large_cube`. Place instances manually through Blender's **Add → Group** menu and connect their sockets as needed. -Function names beginning with `_` follow the same entry-placement and import rules as other function names. +Function names beginning with `_` follow the same entry and import rules as other function names. -Existing base-tree nodes remain in place. Connect the new nodes to **Group Input** and **Group Output** as needed; **Compile Script** does not create or connect the base tree's interface sockets. +The mode follows the node-building operations remaining after compile-time evaluation. A call inside a function declaration does not select root replacement. Neither do imports, constants, or calls in a branch discarded at compile time. For example, compiling `FLAG = False` leaves the base tree and previously compiled function groups in place. + +Compiling without top-level node-building code preserves the base tree's nodes, layout, and connections. Recompiling a function with the same name and parameter signature from the same Text updates its existing group in place. Manually placed instances keep using that group; with an unchanged interface, their sockets and links remain connected. Interface changes can cause Blender to remove incompatible links, so inspect affected instances. Removing a declaration leaves its previously compiled group available while nodes still reference it. + +Switching from node-building code to declarations or constants leaves the existing base graph in place. Switching back to node-building code replaces all ordinary base-tree nodes. Repeated node-building compiles replace nodes rather than accumulate them. See [Update a script](GET_STARTED.md#update-a-script) for interface-link preservation and target requirements. + +The selected Text identifies its source functions across compiles, base-tree renames, and saving and reopening the `.blend` file. Keep using the same Text when updating those functions. Copied Texts with duplicate source identities are rejected. + +Create base-tree interface sockets in Blender and connect generated nodes as needed. To read an existing interface input from source, use [`node("NodeGroupInput", ...)`](BUILTINS.md#base-tree-group-input). ## Import functions diff --git a/docs/SYNTAX.md b/docs/SYNTAX.md index 278a5ae..016e328 100644 --- a/docs/SYNTAX.md +++ b/docs/SYNTAX.md @@ -389,7 +389,7 @@ results = measure(2.0) tripled = results[1] ``` -See [Writing Functions](WRITING_FUNCTIONS.md) for function interfaces and [Modules](MODULES.md#compose-the-base-tree) for automatic placement of functions when compiling a module containing only declarations. +See [Writing Functions](WRITING_FUNCTIONS.md) for function interfaces and [Modules](MODULES.md#compose-the-base-tree) for creating function groups from a module containing only declarations. ### Shared and Unique Groups @@ -440,7 +440,7 @@ An effective `__inline__=True` with `__unique__=True` is an error. `__inline__` An inline call emits nodes directly into its immediate caller's tree. A grouped caller contains its inline callee's native nodes inside the caller's group; nested calls independently select their own inline or grouped mode. Inputs and flat-tuple returns retain the normal typed function contract. -**Compile Script** and **Update Script** compile inline calls in a base tree. **Reload Function from Source** recompiles inline callees embedded in a selected grouped function. Explicit **Add Node Group** and standalone function creation continue to create editable groups, even for definitions declaring `__inline__=True`. +**Compile Script** compiles inline calls in a base tree. **Reload Function from Source** recompiles inline callees embedded in a selected grouped function. Explicit **Add Node Group** and standalone function creation continue to create editable groups, even for definitions declaring `__inline__=True`. ## Imports diff --git a/docs/WRITING_FUNCTIONS.md b/docs/WRITING_FUNCTIONS.md index fa5ce8b..4339483 100644 --- a/docs/WRITING_FUNCTIONS.md +++ b/docs/WRITING_FUNCTIONS.md @@ -1,6 +1,6 @@ # Writing Functions -Declare reusable functions with top-level `def` in a `.nf` module. Each parameter has a type annotation, and each function ends with a `return`. A file can declare several functions; [`.nf` Modules](MODULES.md#compose-the-base-tree) explains when their Group Nodes are placed in the base tree. +Declare reusable functions with top-level `def` in a `.nf` module. Each parameter has a type annotation, and each function ends with a `return`. A file can declare several functions; [`.nf` Modules](MODULES.md#compose-the-base-tree) explains how to compile them for use in the base tree. ## Parameters and sockets @@ -112,9 +112,9 @@ The original Text must still exist and have a unique source binding. Selecting a Reload rebuilds the selected function group in place. All Group Nodes using that shared group receive the change; a `__unique__` group retains its separate instance. Compatible links and user-edited input values are preserved. -Reload also updates inline bodies embedded in the selected grouped function. Inline calls in a base tree are refreshed by **Compile Script** or **Update Script** on their calling script. Explicit standalone creation and Library **Add Node Group** produce editable groups from definitions with `__inline__=True`. +Reload also updates inline bodies embedded in the selected grouped function. Inline calls in a base tree are refreshed by **Compile Script** on their calling script. Explicit standalone creation and Library **Add Node Group** produce editable groups from definitions with `__inline__=True`. -The function name, parameter names, order, and types must match the compiled definition. Removing or renaming the definition, changing those parameters, or losing its source prevents Reload. To compile a changed signature, update the calling script and use **Compile Script** or **Update Script**. For replacement of the base graph, see [Update a script](GET_STARTED.md#update-a-script). +The function name, parameter names, order, and types must match the compiled definition. Removing or renaming the definition, changing those parameters, or losing its source prevents Reload. To compile a changed signature, update the calling script and use **Compile Script**. For replacement of the base graph, see [Update a script](GET_STARTED.md#update-a-script). Blender's **Make Single User** copies the group's source binding along with its nodes. Duplicate bindings prevent NodeForge from choosing an owner when compiling or reloading that function. To keep a manually created copy independent, select that copy in a Geometry Nodes editor. In a Python Console in the same window, run the operator with that editor as its context: diff --git a/tests/blender/expression_characterization/cases/expected/local_call_mixed_array_index.json b/tests/blender/expression_characterization/cases/expected/local_call_mixed_array_index.json index 7b1c0f2..e2e8b41 100644 --- a/tests/blender/expression_characterization/cases/expected/local_call_mixed_array_index.json +++ b/tests/blender/expression_characterization/cases/expected/local_call_mixed_array_index.json @@ -1,148 +1,185 @@ { - "graph": { - "interface": [], - "links": [], - "nodes": [ - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Result", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "A", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "B", - "socket_type": "NodeSocketFloat" - } + "definitions": [ + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "value", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ - "n0", - "Socket_1" - ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n2", - "Socket_1" - ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n1", - "Socket_2" - ] - } + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + } + ] + }, + "name": "identity" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Result", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "A", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "B", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "value", - "socket_type": "NodeSocketFloat" - } - ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n1", - "Socket_1" - ] - } + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n0", + "Socket_1" + ], + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n2", + "Socket_1" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_2" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "value", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - } + "to": [ + "n1", + "Socket_1" ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} }, - "id": "g2", - "unique": false - }, - "id": "n2", - "properties": {} + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + } + ] }, - { - "bl_idname": "ShaderNodeMath", - "id": "n3", - "properties": { - "operation": "ADD" - } - } - ] + "id": "g1", + "unique": false + }, + "id": "n2", + "properties": {} }, - "id": "g1", - "unique": false - }, - "id": "n0", - "properties": {} - } - ] + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } + ] + }, + "name": "nf_fixture" + } + ], + "graph": { + "interface": [], + "links": [], + "nodes": [] }, "kind": "graph" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json b/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json index 12b2d1f..2b96803 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json @@ -1,326 +1,562 @@ { - "graph": { - "interface": [], - "links": [], - "nodes": [ - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "definitions": [ + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ - "n2", - "Socket_1" - ], - "to": [ - "n1", - "Socket_1" - ] - } + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n2", + "Socket_1" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ - "n2", - "Socket_1" - ], - "to": [ - "n4", - "Value" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", - "Value_001" - ] - }, - { - "from": [ - "n4", - "Value" - ], - "to": [ - "n1", - "Socket_1" - ] - } + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n2", + "Socket_1" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "to": [ + "n4", + "Value" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n4", + "Value_001" + ] + }, + { + "from": [ + "n4", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n2", - "Value" - ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n1", - "Socket_1" - ] - } + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n3", - "properties": { - "operation": "ADD" - } - } + "to": [ + "n3", + "Value_001" ] }, - "id": "g3", - "unique": false - }, - "id": "n2", - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } + ] }, - { - "bl_idname": "ShaderNodeMath", - "id": "n4", - "properties": { - "operation": "MULTIPLY" - } - } - ] + "id": "g2", + "unique": false + }, + "id": "n2", + "properties": {} }, - "id": "g2", - "unique": false - }, - "id": "n2", - "properties": {} - } + { + "bl_idname": "ShaderNodeValue", + "id": "n3", + "payload": { + "value": 2.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n4", + "properties": { + "operation": "MULTIPLY" + } + } + ] + }, + "id": "g1", + "unique": false + }, + "id": "n2", + "properties": {} + } + ] + }, + "name": "entry" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" + ], + "to": [ + "n3", + "Value_001" ] }, - "id": "g1", - "unique": false - }, - "id": "n0", - "properties": {} + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "SUBTRACT" + } + } + ] }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "name": "independent" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n2", - "Value" + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" + ], + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } + ] + }, + "name": "leaf" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n2", + "Socket_1" + ], + "to": [ + "n4", + "Value" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n4", + "Value_001" + ] + }, + { + "from": [ + "n4", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" + ], + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } ], - "to": [ - "n1", - "Socket_1" + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } ] - } - ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n3", - "properties": { - "operation": "SUBTRACT" - } - } - ] + "id": "g1", + "unique": false + }, + "id": "n2", + "properties": {} }, - "id": "g4", - "unique": false - }, - "id": "n1", - "properties": {} - } - ] + { + "bl_idname": "ShaderNodeValue", + "id": "n3", + "payload": { + "value": 2.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n4", + "properties": { + "operation": "MULTIPLY" + } + } + ] + }, + "name": "middle" + } + ], + "graph": { + "interface": [], + "links": [], + "nodes": [] }, "kind": "graph" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json b/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json index 03f1208..0640ff9 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json @@ -1,125 +1,120 @@ { - "graph": { - "interface": [], - "links": [], - "nodes": [ - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 3.0, - "in_out": "INPUT", - "name": "Bias", - "socket_type": "NodeSocketFloat" - }, - { - "default": 2.0, - "in_out": "INPUT", - "name": "Amount", - "socket_type": "NodeSocketFloat" - } + "definitions": [ + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 3.0, + "in_out": "INPUT", + "name": "Bias", + "socket_type": "NodeSocketFloat" + }, + { + "default": 2.0, + "in_out": "INPUT", + "name": "Amount", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n0", + "Socket_1" + ], + "to": [ + "n4", + "Value_001" + ] + }, + { + "from": [ + "n2", + "Value" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n0", - "Socket_1" - ], - "to": [ - "n4", - "Value_001" - ] - }, - { - "from": [ - "n2", - "Value" - ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", - "Value" - ] - }, - { - "from": [ - "n4", - "Value" - ], - "to": [ - "n1", - "Socket_3" - ] - } + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n4", + "Value" + ] + }, + { + "from": [ + "n4", + "Value" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 2.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n3", - "properties": { - "operation": "MULTIPLY" - } - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n4", - "properties": { - "operation": "ADD" - } - } + "to": [ + "n1", + "Socket_3" ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} }, - "id": "g1", - "unique": false - }, - "id": "n0", - "properties": {} - } - ] + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 2.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "MULTIPLY" + } + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n4", + "properties": { + "operation": "ADD" + } + } + ] + }, + "name": "offset" + } + ], + "graph": { + "interface": [], + "links": [], + "nodes": [] }, "kind": "graph" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_preserve_user_link.json b/tests/blender/expression_characterization/cases/expected/top_level_preserve_user_link.json index 08435c4..b81f9a0 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_preserve_user_link.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_preserve_user_link.json @@ -1,36 +1,11 @@ { "graph": { "interface": [], - "links": [ - { - "from": [ - "n0", - "Value" - ], - "to": [ - "n1", - "Value" - ] - } - ], + "links": [], "nodes": [ - { - "bl_idname": "ShaderNodeMath", - "id": "n0", - "properties": { - "operation": "ADD" - } - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n1", - "properties": { - "operation": "ADD" - } - }, { "bl_idname": "GeometryNodeMeshCube", - "id": "n2", + "id": "n0", "properties": {} } ] diff --git a/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json b/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json index 2e2989e..916c613 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json @@ -1,252 +1,392 @@ { - "graph": { - "interface": [], - "links": [], - "nodes": [ - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "definitions": [ + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ - "n2", - "Socket_1" - ], - "to": [ - "n1", - "Socket_1" - ] - } + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } - ], - "links": [ - { - "from": [ - "n0", - "Socket_0" - ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n2", - "Value" - ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n1", - "Socket_1" - ] - } - ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n3", - "properties": { - "operation": "ADD" - } - } - ] - }, - "id": "g2", - "unique": false - }, - "id": "n2", - "properties": {} - } + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} }, - "id": "g1", - "unique": false - }, - "id": "n0", - "properties": {} + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } + ] }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "graph": { - "interface": [ - { - "in_out": "OUTPUT", - "name": "Value", - "socket_type": "NodeSocketFloat" - }, - { - "default": 0.0, - "in_out": "INPUT", - "name": "x", - "socket_type": "NodeSocketFloat" - } + "name": "_common" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" ], - "links": [ - { - "from": [ - "n0", - "Socket_0" + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n2", + "Socket_1" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } ], - "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ - "n2", - "Socket_1" + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" + ], + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } ], - "to": [ - "n4", - "Value" + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } ] }, - { - "from": [ - "n3", - "Value" + "id": "g1", + "unique": false + }, + "id": "n2", + "properties": {} + } + ] + }, + "name": "first" + }, + { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } + ], + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n2", + "Socket_0" + ] + }, + { + "from": [ + "n2", + "Socket_1" + ], + "to": [ + "n4", + "Value" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n4", + "Value_001" + ] + }, + { + "from": [ + "n4", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } + ], + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "GeometryNodeGroup", + "group": { + "graph": { + "interface": [ + { + "in_out": "OUTPUT", + "name": "Value", + "socket_type": "NodeSocketFloat" + }, + { + "default": 0.0, + "in_out": "INPUT", + "name": "x", + "socket_type": "NodeSocketFloat" + } ], - "to": [ - "n4", - "Value_001" - ] - }, - { - "from": [ - "n4", - "Value" + "links": [ + { + "from": [ + "n0", + "Socket_0" + ], + "to": [ + "n3", + "Value" + ] + }, + { + "from": [ + "n2", + "Value" + ], + "to": [ + "n3", + "Value_001" + ] + }, + { + "from": [ + "n3", + "Value" + ], + "to": [ + "n1", + "Socket_1" + ] + } ], - "to": [ - "n1", - "Socket_1" + "nodes": [ + { + "bl_idname": "NodeGroupInput", + "id": "n0", + "properties": {} + }, + { + "bl_idname": "NodeGroupOutput", + "id": "n1", + "properties": {} + }, + { + "bl_idname": "ShaderNodeValue", + "id": "n2", + "payload": { + "value": 1.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n3", + "properties": { + "operation": "ADD" + } + } ] - } - ], - "nodes": [ - { - "bl_idname": "NodeGroupInput", - "id": "n0", - "properties": {} - }, - { - "bl_idname": "NodeGroupOutput", - "id": "n1", - "properties": {} - }, - { - "bl_idname": "GeometryNodeGroup", - "group": { - "id": "g2", - "unique": false - }, - "id": "n2", - "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeMath", - "id": "n4", - "properties": { - "operation": "MULTIPLY" - } - } - ] + "id": "g1", + "unique": false + }, + "id": "n2", + "properties": {} }, - "id": "g3", - "unique": false - }, - "id": "n1", - "properties": {} - } - ] + { + "bl_idname": "ShaderNodeValue", + "id": "n3", + "payload": { + "value": 2.0 + }, + "properties": {} + }, + { + "bl_idname": "ShaderNodeMath", + "id": "n4", + "properties": { + "operation": "MULTIPLY" + } + } + ] + }, + "name": "second" + } + ], + "graph": { + "interface": [], + "links": [], + "nodes": [] }, "kind": "graph" } diff --git a/tests/blender/expression_characterization/harness.py b/tests/blender/expression_characterization/harness.py index 8accf78..153e556 100644 --- a/tests/blender/expression_characterization/harness.py +++ b/tests/blender/expression_characterization/harness.py @@ -21,7 +21,7 @@ import bpy from NodeForge import compiler, local_sources, packages -from NodeForge.function_instances import FUNCTION_INSTANCE_KEY_PROP +from NodeForge.function_instances import FUNCTION_INSTANCE_KEY_PROP, FUNCTION_DEFINITION_OWNER_PROP from NodeForge.errors import CompileError HERE = Path(__file__).resolve().parent @@ -226,10 +226,17 @@ def _validate_baseline_document(baseline, case_id): raise ValueError(f"baseline for case {case_id} must be a JSON object") kind = baseline.get("kind") if kind == "graph": - if set(baseline) != {"kind", "graph"}: + if set(baseline) not in ({"kind", "graph"}, {"kind", "graph", "definitions"}): raise ValueError( f"graph baseline for case {case_id} must contain exactly kind and graph" ) + if "definitions" in baseline: + if not isinstance(baseline["definitions"], list) or any( + not isinstance(item, dict) or set(item) != {"name", "graph"} + or not isinstance(item["name"], str) or not isinstance(item["graph"], dict) + for item in baseline["definitions"] + ): + raise ValueError(f"invalid published definitions for case {case_id}") graph = baseline["graph"] if not isinstance(graph, dict) or set(graph) != {"interface", "nodes", "links"}: raise ValueError( @@ -448,7 +455,9 @@ def run_case(case): first = group.nodes.new("ShaderNodeMath") second = group.nodes.new("ShaderNodeMath") group.links.new(first.outputs[0], second.inputs[0]) - compiler.compose_source_initial(source, group) + outcome = compiler.compile_source_in_tree( + source, group, module_context=f"test:characterization:{case_id}", + ) else: group = compiler.create_expression_group(source, f"NFChar_{case_id}") except CompileError as exc: @@ -466,6 +475,18 @@ def run_case(case): group, include_dependencies=has_local or "top-level" in case["tags"], ), } + if "top-level" in case["tags"] and outcome.outcome == "GROUPS_ONLY": + published = [ + candidate for candidate in bpy.data.node_groups + if candidate.as_pointer() not in before + and candidate.get(FUNCTION_DEFINITION_OWNER_PROP) + ] + if published: + result["definitions"] = [ + {"name": str(g.get("nodeforge_module_name") or g.name), + "graph": group_snapshot(g, include_dependencies=True)} + for g in sorted(published, key=lambda g: str(g.get("nodeforge_module_name") or g.name)) + ] _assert_json_native(result) if actual_outcome != expected_outcome: raise AssertionError( diff --git a/tests/blender/expression_characterization/test_cases.py b/tests/blender/expression_characterization/test_cases.py index 6d6ff8a..57eb1d7 100644 --- a/tests/blender/expression_characterization/test_cases.py +++ b/tests/blender/expression_characterization/test_cases.py @@ -164,9 +164,11 @@ def test_top_level_baselines_pin_sharing_and_import_side_effects(): def test_top_level_baselines_pin_nesting_and_absent_unused_functions(): """A definition chain materializes three levels; shadowed defs remain unused.""" - definitions = load_case_baseline("top_level_definition_chain")["graph"] - assert len(definitions["nodes"]) == 2 - entry_graph = definitions["nodes"][0]["group"]["graph"] + definitions = load_case_baseline("top_level_definition_chain") + assert definitions["graph"]["nodes"] == [] # groups-only does not place root instances + published = {item["name"]: item["graph"] for item in definitions["definitions"]} + assert {"entry", "independent", "leaf", "middle"} == set(published) + entry_graph = published["entry"] middle = next(node["group"]["graph"] for node in entry_graph["nodes"] if "group" in node) leaf = next(node["group"]["graph"] for node in middle["nodes"] if "group" in node) assert any(node["bl_idname"] == "ShaderNodeMath" for node in leaf["nodes"]) @@ -179,8 +181,9 @@ def test_top_level_baselines_pin_nesting_and_absent_unused_functions(): def test_top_level_baselines_pin_interface_outputs_and_existing_links(): """Check semantic details that can be lost by blindly regenerating JSON baselines.""" - panel = load_case_baseline("top_level_panel_defaults")["graph"] - interface = panel["nodes"][0]["group"]["graph"]["interface"] + panel = load_case_baseline("top_level_panel_defaults") + assert panel["graph"]["nodes"] == [] + interface = panel["definitions"][0]["graph"]["interface"] assert [(item["name"], item["default"]) for item in interface if item["in_out"] == "INPUT"] == [ ("Bias", 3.0), ("Amount", 2.0), ] @@ -193,10 +196,20 @@ def test_top_level_baselines_pin_interface_outputs_and_existing_links(): assert len(outputs["links"]) == 2 preserved = load_case_baseline("top_level_preserve_user_link")["graph"] - assert [node["bl_idname"] for node in preserved["nodes"]] == [ - "ShaderNodeMath", "ShaderNodeMath", "GeometryNodeMeshCube", - ] - assert preserved["links"] == [{"from": ["n0", "Value"], "to": ["n1", "Value"]}] + assert [node["bl_idname"] for node in preserved["nodes"]] == ["GeometryNodeMeshCube"] + assert preserved["links"] == [] # root-producing Compile replaces all ordinary nodes + + +def test_groups_only_baselines_pin_shared_helper_without_root_instances(): + """Entry groups share a helper, while the selected root remains physically unchanged.""" + baseline = load_case_baseline("top_level_shared_entries") + assert baseline["graph"]["nodes"] == [] + groups = {row["name"]: row["graph"] for row in baseline["definitions"]} + assert set(groups) == {"_common", "first", "second"} + helper_graph = groups["_common"] + assert any(node["bl_idname"] == "ShaderNodeMath" for node in helper_graph["nodes"]) + for name in ("first", "second"): + assert any(node["bl_idname"] == "GeometryNodeGroup" for node in groups[name]["nodes"]) def test_top_level_baseline_pins_only_reachable_function_groups(): diff --git a/tests/blender/helpers.py b/tests/blender/helpers.py index 367b619..36bcfac 100644 --- a/tests/blender/helpers.py +++ b/tests/blender/helpers.py @@ -57,19 +57,21 @@ def compile_group(source, name): return group def compile_entry_group(source, name, entry_name): - """Compose a definition-only module and return its named entry's function tree. + """Publish zero-incoming definitions and return the selected authoritative group. - This exercises level-0 automatic entry placement instead of treating a - multi-definition source as one legacy standalone function. + The single Compile contract never inserts definition-only instances into + the root tree; tests select the canonical materialized datablock instead. """ target = bpy.data.node_groups.new(name + "_base", "GeometryNodeTree") - compiler.compose_source_initial(source, target) + result = compile_root(source, target) + check(result.outcome == 'GROUPS_ONLY', f"expected group-only source for {name}") + origin = f"test:root:{target.as_pointer()}" entries = [ - node.node_tree for node in target.nodes - if node.bl_idname == "GeometryNodeGroup" and node.node_tree is not None - and node.node_tree.get("nodeforge_module_name") == entry_name + group for group in bpy.data.node_groups + if group.get('nodeforge_module_name') == entry_name + and origin in str(group.get('nodeforge_module_origin', '')) ] - check(len(entries) == 1, f"expected exactly one {entry_name!r} entry in {name}") + check(len(entries) == 1, f"expected exactly one authoritative {entry_name!r} group in {name}") return entries[0] @@ -434,4 +436,37 @@ def _named_attribute_node_name(node): return None + + +def compile_root(source, target, *, module_context=None, resolved_environment=None): + """Exercise the public Compile API with an explicit test-owned source origin. + + Tests covering a missing origin call the compiler directly. Here the test + invocation owns an origin derived from the physical test target pointer, + which remains stable across root renames and repeated calls. + """ + if module_context is None: + module_context = f"test:root:{target.as_pointer()}" if target is not None else None + return compiler.compile_source_in_tree( + source, target, module_context=module_context, + resolved_environment=resolved_environment, + ) + + +def published_groups_for_root(root): + """Return source-function datablocks for this test-owned root origin.""" + origin = f"test:root:{root.as_pointer()}" + return tuple(group for group in bpy.data.node_groups + if origin in str(group.get('nodeforge_module_origin', '')) + and group.get('nodeforge_module_definition')) + + +def published_entry(root, name): + """Retrieve the one group bearing a named authoritative source definition.""" + found = [group for group in published_groups_for_root(root) + if group.get('nodeforge_module_name') == name] + check(len(found) == 1, f"expected exactly one published {name!r} group, got {len(found)}") + return found[0] + + __all__ = [name for name in globals() if not name.startswith("__")] diff --git a/tests/blender/root_update_save_reopen.py b/tests/blender/root_update_save_reopen.py index aa97217..9b95344 100644 --- a/tests/blender/root_update_save_reopen.py +++ b/tests/blender/root_update_save_reopen.py @@ -14,7 +14,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[3])) -from NodeForge.compiler import update_source_in_tree +from NodeForge.compiler import compile_source_in_tree FILE = Path(os.environ['NODEFORGE_ROOT_ROUNDTRIP_FILE']) @@ -59,7 +59,7 @@ def _create(): external = outer.nodes.new('GeometryNodeGroup') external.node_tree = group before = _interface(group) - result = update_source_in_tree('a = cube(4)\n', group) + result = compile_source_in_tree('a = cube(4)\n', group) assert result.skipped_boundary_links == 0 assert _interface(group) == before assert mod.node_group.as_pointer() == group.as_pointer() diff --git a/tests/blender/test_color_extension_api_v2.py b/tests/blender/test_color_extension_api_v2.py index 0a54f09..41b78e2 100644 --- a/tests/blender/test_color_extension_api_v2.py +++ b/tests/blender/test_color_extension_api_v2.py @@ -2,6 +2,8 @@ from __future__ import annotations +from helpers import compile_root + import json import tempfile from pathlib import Path @@ -252,7 +254,7 @@ def test_package_source_color_roundtrips_through_python_and_raw_nodes(tmp_path): _write_color_extension(root, source_functions=True) packages.install_package_directory(root) wrapper=bpy.data.node_groups.new('NFTest_ColorExt_Root','GeometryNodeTree') - compiler.compose_source_initial('''from packages import color_runtime + compile_root('''from packages import color_runtime first = color_runtime.extension_to_raw(0.2) second = color_runtime.extension_to_raw(0.3, __unique__=True) diff --git a/tests/blender/test_compile_fixtures.py b/tests/blender/test_compile_fixtures.py index 32cdaf7..547be89 100644 --- a/tests/blender/test_compile_fixtures.py +++ b/tests/blender/test_compile_fixtures.py @@ -13,7 +13,7 @@ def test_representative_compile_fixtures(): for name, source in fixtures.items(): if name == 'local_function': tree = bpy.data.node_groups.new('NFTest_' + name, 'GeometryNodeTree') - compiler.compose_source_initial(source + '\nresult = nf_fixture(2.0)\n', tree) + compile_root(source + '\nresult = nf_fixture(2.0)\n', tree) else: compile_group(source, 'NFTest_' + name) print('COMPILE_FIXTURES_OK') diff --git a/tests/blender/test_function_output_labels.py b/tests/blender/test_function_output_labels.py index c4d6bb8..70c9e08 100644 --- a/tests/blender/test_function_output_labels.py +++ b/tests/blender/test_function_output_labels.py @@ -39,7 +39,7 @@ def unnamed(geo: Geometry) -> Geometry: def test_nested_function_calls_preserve_both_output_naming_styles(): root = bpy.data.node_groups.new('NFTest_ReturnNamesRoot', 'GeometryNodeTree') - compiler.compose_source_initial(''' + compile_root(''' def move_x(geometry: Geometry, x_shift: Float["X Shift"] = 0.0) -> Geometry["Geometry"]: return transform(geometry, translation=vector(x_shift, 0, 0)) @@ -49,12 +49,10 @@ def move(): combined = join([left, right]) return combined ''', root) - top_calls = [node for node in root.nodes if node.bl_idname == 'GeometryNodeGroup'] - check(len(top_calls) == 1, f'expected one Move entry, got {len(top_calls)}') - move = top_calls[0] - check([socket.name for socket in move.outputs] == ['Combined'], - f'outer group outputs: {[socket.name for socket in move.outputs]}') - shift_calls = [node for node in move.node_tree.nodes if node.bl_idname == 'GeometryNodeGroup'] + check(not list(root.nodes), 'group-only Compile inserted root instances') + move = published_entry(root, 'move') + check(_output_names(move) == ['Combined'], f'outer group outputs: {_output_names(move)}') + shift_calls = [node for node in move.nodes if node.bl_idname == 'GeometryNodeGroup'] check(len(shift_calls) == 2, 'expected two nested move_x calls') check(all([socket.name for socket in node.outputs] == ['Geometry'] for node in shift_calls), f'nested outputs: {[[socket.name for socket in node.outputs] for node in shift_calls]}') diff --git a/tests/blender/test_inline_source_calls.py b/tests/blender/test_inline_source_calls.py index 635b927..400d26f 100644 --- a/tests/blender/test_inline_source_calls.py +++ b/tests/blender/test_inline_source_calls.py @@ -12,7 +12,7 @@ def _compose(source, title): """Compile a source module into a fresh Geometry Nodes base tree.""" tree = bpy.data.node_groups.new(title, 'GeometryNodeTree') - compiler.compose_source_initial(source, tree) + compile_root(source, tree) return tree @@ -184,13 +184,13 @@ def test_inline_rotation_default_invalid_or_vector_runtime_rejected(): for bad in ('(0, 1)', '(0, True, 1)', '(0, 1e50, 1)'): tree = bpy.data.node_groups.new('NFTest_Inline_Bad_Rotation', 'GeometryNodeTree') with pytest.raises(CompileError): - compiler.compose_source_initial( + compile_root( 'def identity(rotation: Rotation = ' + bad + ', __inline__=True) -> Rotation:\n' ' return rotation\nresult = identity()\n', tree, ) wrong = bpy.data.node_groups.new('NFTest_Inline_Bad_Runtime', 'GeometryNodeTree') with pytest.raises(CompileError): - compiler.compose_source_initial('''def identity(rotation: Rotation, __inline__=True) -> Rotation: + compile_root('''def identity(rotation: Rotation, __inline__=True) -> Rotation: return rotation result = identity(vector(0, 0, 0)) ''', wrong) @@ -383,13 +383,13 @@ def test_direct_root_update_replaces_inline_expansion_and_staging_failure_rolls_ from NodeForge.blender import ir_lowering tree = bpy.data.node_groups.new('NFTest_Inline_Root_Update', 'GeometryNodeTree') - compiler.update_source_in_tree('a = cube(1.0)\n', tree) + compile_root('a = cube(1.0)\n', tree) before = {node.as_pointer() for node in tree.nodes} source = '''def inline_leaf(value: Float, __inline__=True) -> Float: return value + 1.0 result = inline_leaf(index()) ''' - compiler.update_source_in_tree(source, tree) + compile_root(source, tree) assert len(_nodes(tree, 'ShaderNodeMath')) == 2 # Int-to-Float adapter and inline addition. assert not _nodes(tree, 'GeometryNodeGroup') assert not before.intersection(node.as_pointer() for node in tree.nodes) @@ -405,7 +405,7 @@ def injected(*args, **kwargs): monkeypatch.setattr(ir_lowering, '_math', injected) from NodeForge.blender.root_update import RootUpdateError with pytest.raises(RootUpdateError, match='injected inline lowering failure'): - compiler.update_source_in_tree(source.replace('1.0', '2.0'), tree) + compile_root(source.replace('1.0', '2.0'), tree) assert pointers == {node.as_pointer() for node in tree.nodes} assert group_pointers == {g.as_pointer() for g in bpy.data.node_groups} @@ -425,10 +425,11 @@ def test_standalone_and_declaration_only_materialization_ignore_compiler_paramet assert len(_nodes(standalone, 'ShaderNodeMath')) == 1 root = _compose(source, 'NFTest_Inline_Definition_Only') - group_node, = _nodes(root, 'GeometryNodeGroup') - assert group_node.node_tree.get('nodeforge_module_name') == 'inline_standalone' - assert len(group_node.inputs) == 1 - assert len(_nodes(group_node.node_tree, 'ShaderNodeMath')) == 1 + assert _nodes(root, 'GeometryNodeGroup') == [] + group = published_entry(root, 'inline_standalone') + assert len([item for item in group.interface.items_tree + if item.item_type == 'SOCKET' and item.in_out == 'INPUT']) == 1 + assert len(_nodes(group, 'ShaderNodeMath')) == 1 @pytest.mark.parametrize('marker', ('__inline__=True', '__inline__: Bool=True')) diff --git a/tests/blender/test_local_function_multi_return.py b/tests/blender/test_local_function_multi_return.py index e7a2b7b..502dee1 100644 --- a/tests/blender/test_local_function_multi_return.py +++ b/tests/blender/test_local_function_multi_return.py @@ -1,5 +1,7 @@ """Blender integration coverage for local-function multiple returns.""" +from helpers import compile_root + import bpy import pytest @@ -15,7 +17,7 @@ def _compile_direct_module(source: str, name: str): """Place mixed new-DSL declarations and operations in a test-owned base tree.""" group = bpy.data.node_groups.new(name, 'GeometryNodeTree') try: - compiler.compose_source_initial(source, group) + compile_root(source, group) except Exception: bpy.data.node_groups.remove(group, do_unlink=True) raise diff --git a/tests/blender/test_mesh_compute_ui.py b/tests/blender/test_mesh_compute_ui.py index 63c9d25..54d6e5e 100644 --- a/tests/blender/test_mesh_compute_ui.py +++ b/tests/blender/test_mesh_compute_ui.py @@ -2,6 +2,8 @@ from __future__ import annotations +from helpers import compile_root + import bpy import pytest @@ -79,7 +81,7 @@ def test_local_python_source_uses_registered_owner_not_permission(registered_ui, def test_explicit_modifier_install_rejects_occupied_modifier_without_affecting_direct_composition( registered_ui, configured_local, mesh_object): """Mesh Compute needs an exclusive private modifier; regular direct composition does not.""" - from NodeForge.compiler import create_mesh_compute_modifier, compose_source_initial + from NodeForge.compiler import create_mesh_compute_modifier from NodeForge.errors import CompileError _select(mesh_object) @@ -89,7 +91,7 @@ def test_explicit_modifier_install_rejects_occupied_modifier_without_affecting_d with pytest.raises(CompileError, match='without previous modifiers'): create_mesh_compute_modifier(SOURCE, mesh_object) assert mesh_object.modifiers[0].as_pointer() == modifier.as_pointer() - assert compose_source_initial('geometry = cube(1)\n', tree) is tree + assert compile_root('geometry = cube(1)\n', tree).target is tree assert any(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) assert len(mesh_object.modifiers) == 1 finally: diff --git a/tests/blender/test_module_compile_time_fingerprints.py b/tests/blender/test_module_compile_time_fingerprints.py index 060686e..474c1a6 100644 --- a/tests/blender/test_module_compile_time_fingerprints.py +++ b/tests/blender/test_module_compile_time_fingerprints.py @@ -36,7 +36,7 @@ def test_reload_tracks_used_module_constant_without_replacing_shared_datablock() context = "test:fingerprint-module-constant" source = "K=2\ndef f(x: Float=1):\n return x+K\na=f()\n" base = bpy.data.node_groups.new("NF-fingerprint-constant-base", "GeometryNodeTree") - compiler.compose_source_initial(source, base, module_context=context) + compile_root(source, base, module_context=context) call, = (node for node in base.nodes if node.bl_idname == "GeometryNodeGroup") group = call.node_tree pointer = group.as_pointer() @@ -59,7 +59,7 @@ def test_reload_ignores_unrelated_sibling_and_module_constant(): "def other(x: Float):\n return x+3\na=f()\n" ) base = bpy.data.node_groups.new("NF-fingerprint-sibling-base", "GeometryNodeTree") - compiler.compose_source_initial(source, base, module_context=context) + compile_root(source, base, module_context=context) call, = (node for node in base.nodes if node.bl_idname == "GeometryNodeGroup") group = call.node_tree before_fingerprint = stored_fingerprint(group) @@ -76,14 +76,14 @@ def test_new_compilation_updates_reusable_group_when_constant_changes(): context = "test:fingerprint-automatic-reuse" source = "K=2\ndef f(x: Float=1):\n return x+K\na=f()\n" first = bpy.data.node_groups.new("NF-fingerprint-automatic-first", "GeometryNodeTree") - compiler.compose_source_initial(source, first, module_context=context) + compile_root(source, first, module_context=context) original, = (node for node in first.nodes if node.bl_idname == "GeometryNodeGroup") pointer = original.node_tree.as_pointer() old_fingerprint = stored_fingerprint(original.node_tree) assert round(_evaluate_float_output(first, original.outputs[0]), 5) == 3 second = bpy.data.node_groups.new("NF-fingerprint-automatic-second", "GeometryNodeTree") - compiler.compose_source_initial(source.replace("K=2", "K=8"), second, module_context=context) + compile_root(source.replace("K=2", "K=8"), second, module_context=context) new, = (node for node in second.nodes if node.bl_idname == "GeometryNodeGroup") assert new.node_tree.as_pointer() == original.node_tree.as_pointer() == pointer assert stored_fingerprint(original.node_tree) != old_fingerprint diff --git a/tests/blender/test_numeric_semantics.py b/tests/blender/test_numeric_semantics.py index 008e967..39b7553 100644 --- a/tests/blender/test_numeric_semantics.py +++ b/tests/blender/test_numeric_semantics.py @@ -279,11 +279,8 @@ def move(geometry: Geometry, x: Float, y: Float) -> Geometry: ''' root = bpy.data.node_groups.new("NFTest_negative_literal_root", "GeometryNodeTree") try: - compiler.compose_source_initial(source, root) - move_node = next(node for node in root.nodes - if node.bl_idname == "GeometryNodeGroup" and node.node_tree - and node.node_tree.get("nodeforge_module_name") == "move") - move = move_node.node_tree + compile_root(source, root) + move = published_entry(root, 'move') calls = [node for node in move.nodes if node.bl_idname == "GeometryNodeGroup"] check(len(calls) == 2, "expected two move_x calls") check(not _nodes(move, "ShaderNodeMath", "SUBTRACT"), "literal -2 created Subtract") diff --git a/tests/blender/test_rev2_module_snapshot_reload.py b/tests/blender/test_rev2_module_snapshot_reload.py index e41be0c..b95235d 100644 --- a/tests/blender/test_rev2_module_snapshot_reload.py +++ b/tests/blender/test_rev2_module_snapshot_reload.py @@ -31,7 +31,7 @@ def grow(value: Float = K) -> Float: shared = values.grow() unique = values.grow(__unique__=True) ''' - compiler.compose_source_initial(caller, base, module_context='test:rev2-local-caller') + compile_root(caller, base, module_context='test:rev2-local-caller') shared, unique = [n for n in base.nodes if n.bl_idname == 'GeometryNodeGroup'] assert shared.inputs[0].default_value == unique.inputs[0].default_value == 9.0 assert not shared.inputs[0].is_linked and not unique.inputs[0].is_linked @@ -68,7 +68,7 @@ def broken(x): before_links = {(l.from_node.as_pointer(), l.to_node.as_pointer()) for l in base.links} before_groups = {group.as_pointer() for group in bpy.data.node_groups} with pytest.raises(CompileError, match='explicit type annotation'): - compiler.compose_source_initial( + compile_root( 'from local import values\nresult=values.good(2.0)\n', base, module_context='test:rev2-imported-invalid', ) diff --git a/tests/blender/test_rotation_runtime.py b/tests/blender/test_rotation_runtime.py index 5181030..4746691 100644 --- a/tests/blender/test_rotation_runtime.py +++ b/tests/blender/test_rotation_runtime.py @@ -2,6 +2,8 @@ from __future__ import annotations +from helpers import compile_root + import json import bpy @@ -57,7 +59,7 @@ def test_rotation_default_required_and_euler_readback(): assert _inputs(required, 'INPUT')[0].socket_type == 'NodeSocketRotation' missing_call = bpy.data.node_groups.new('NFTest_RotationMissingRequired', 'GeometryNodeTree') with pytest.raises(CompileError): - compiler.compose_source_initial('''def need_rotation(value: Rotation) -> Rotation: + compile_root('''def need_rotation(value: Rotation) -> Rotation: return value result = need_rotation() diff --git a/tests/blender/test_runtime_loop_index_shadowing.py b/tests/blender/test_runtime_loop_index_shadowing.py index 71895c7..667ce07 100644 --- a/tests/blender/test_runtime_loop_index_shadowing.py +++ b/tests/blender/test_runtime_loop_index_shadowing.py @@ -23,7 +23,7 @@ def b(x: Float): result = a(3) ''' base = bpy.data.node_groups.new('NF-shadow-index-' + iterator[:5], 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:runtime-index-' + iterator) + compile_root(source, base, module_context='test:runtime-index-' + iterator) call, = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] assert call.node_tree.get('nodeforge_module_name') == 'a' nested = [node for node in call.node_tree.nodes if node.bl_idname == 'GeometryNodeGroup'] @@ -47,7 +47,7 @@ def a(count: Int): result = a(3) ''' base = bpy.data.node_groups.new('NF-shadow-index-scope', 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:runtime-index-scope') + compile_root(source, base, module_context='test:runtime-index-scope') call, = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] assert round(_evaluate_float_output(base, call.outputs[0]), 5) == 14.0 @@ -71,7 +71,7 @@ def b(x: Float): result = a(2) ''' base = bpy.data.node_groups.new('NF-shadow-index-nested', 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:runtime-index-nested') + compile_root(source, base, module_context='test:runtime-index-nested') call, = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] assert round(_evaluate_float_output(base, call.outputs[0]), 5) == 23.0 @@ -93,7 +93,7 @@ def b(x: Float): result = a() ''' base = bpy.data.node_groups.new('NF-shadow-static-index', 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:static-index-scope') + compile_root(source, base, module_context='test:static-index-scope') call, = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] assert round(_evaluate_float_output(base, call.outputs[0]), 5) == 11.0 nested = [node for node in call.node_tree.nodes if node.bl_idname == 'GeometryNodeGroup'] @@ -117,12 +117,15 @@ def b(x: Float): return x + 10 ''' base = bpy.data.node_groups.new('NF-static-loop-CT-state', 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:static-loop-ct') - calls = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert [node.node_tree.get('nodeforge_module_name') for node in calls] == ['a'] - nested = [node for node in calls[0].node_tree.nodes if node.bl_idname == 'GeometryNodeGroup'] + compile_root(source, base, module_context='test:static-loop-ct') + assert not list(base.nodes) + group = next(g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'a' + and 'test:static-loop-ct' in str(g.get('nodeforge_module_origin', ''))) + nested = [node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] assert [node.node_tree.get('nodeforge_module_name') for node in nested] == ['b'] - assert round(_evaluate_float_output(base, calls[0].outputs[0]), 5) == 11.0 + node = base.nodes.new('GeometryNodeGroup') # Manually instanced after group-only publication. + node.node_tree = group + assert round(_evaluate_float_output(base, node.outputs[0]), 5) == 11.0 def test_static_loop_false_state_does_not_materialize_unreachable_callee(): @@ -140,8 +143,12 @@ def b(x: Float): return x + 10 ''' base = bpy.data.node_groups.new('NF-static-loop-CT-false', 'GeometryNodeTree') - compiler.compose_source_initial(source, base, module_context='test:static-loop-ct-false') - calls = [node for node in base.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert [node.node_tree.get('nodeforge_module_name') for node in calls] == ['a', 'b'] - assert not [node for node in calls[0].node_tree.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert round(_evaluate_float_output(base, calls[0].outputs[0]), 5) == 1.0 + compile_root(source, base, module_context='test:static-loop-ct-false') + assert not list(base.nodes) + groups = {g.get('nodeforge_module_name'): g for g in bpy.data.node_groups + if 'test:static-loop-ct-false' in str(g.get('nodeforge_module_origin', ''))} + assert set(groups) == {'a', 'b'} + assert not [node for node in groups['a'].nodes if node.bl_idname == 'GeometryNodeGroup'] + node = base.nodes.new('GeometryNodeGroup') + node.node_tree = groups['a'] + assert round(_evaluate_float_output(base, node.outputs[0]), 5) == 1.0 diff --git a/tests/blender/test_string_inputs.py b/tests/blender/test_string_inputs.py index 132ca9b..3e1a87f 100644 --- a/tests/blender/test_string_inputs.py +++ b/tests/blender/test_string_inputs.py @@ -111,7 +111,7 @@ def nf_fixture(geo: Geometry['Geometry'], name: String['Attribute'] = 'Weight_A' def test_top_level_store_accepts_runtime_string_name(): group = bpy.data.node_groups.new("NFTest_string_statement_store", "GeometryNodeTree") - compiler.compose_source_initial(''' + compile_root(''' name = node("FunctionNodeInputString", props={"string": "Weight_A"}, output="String", typ=String) geometry = store_named_attribute(cube(1.0), name, position().x, domain="POINT", type="FLOAT") ''', group) diff --git a/tests/blender/test_third_party_package_lifecycle.py b/tests/blender/test_third_party_package_lifecycle.py index 0c5a042..7299548 100644 --- a/tests/blender/test_third_party_package_lifecycle.py +++ b/tests/blender/test_third_party_package_lifecycle.py @@ -1,5 +1,7 @@ """Blender integration coverage for third-party package lifecycle operations.""" +from helpers import compile_root + from helpers import compile_group, expect_compile_error, has_package_function from NodeForge import compiler import bpy @@ -48,7 +50,7 @@ def test_directory_zip_replace_uninstall_and_reinstall_lifecycle(): assert installed.package_id == "vendor.lifecycle" assert has_package_function("vendor_value") tree = bpy.data.node_groups.new("NFTest_vendor_lifecycle_directory", "GeometryNodeTree") - compiler.compose_source_initial('from packages import lifecycle\nx = lifecycle.vendor_value(2.0)\n', tree) + compile_root('from packages import lifecycle\nx = lifecycle.vendor_value(2.0)\n', tree) assert any(node.bl_idname == "GeometryNodeGroup" for node in tree.nodes) source_v2 = tmp / "source_v2" diff --git a/tests/blender/test_unified_compile_modes.py b/tests/blender/test_unified_compile_modes.py new file mode 100644 index 0000000..a3a5e22 --- /dev/null +++ b/tests/blender/test_unified_compile_modes.py @@ -0,0 +1,454 @@ +"""Blender acceptance for a single Compile action and definition publication.""" + +from helpers import * + +from NodeForge.blender.direct_composition import materialize_definition_entries +from NodeForge.blender.function_materializer import FunctionMaterializationContext, FunctionMaterializer +from NodeForge.blender.group_backend import BlenderGroupBuildTransaction +from NodeForge.function_instances import FunctionCompilationTrace + + +def _base(name): + """Return a fresh editable Geometry Nodes root.""" + return bpy.data.node_groups.new(name, 'GeometryNodeTree') + + +def _publish(source, root, *, origin): + """Call the extracted publication mechanism without root node placement.""" + prepared, backend, session, snapshot = compiler._prepare_direct_source( + source, root, module_context=origin, + ) + tx = BlenderGroupBuildTransaction() + context = FunctionMaterializationContext( + function_group_cache={}, function_group_transaction=tx, + function_compilation_trace=FunctionCompilationTrace(), + source_callable_session=session, + ) + try: + groups = materialize_definition_entries(prepared, FunctionMaterializer(group_backend=backend), context, snapshot) + tx.commit() + return groups + except Exception: + tx.rollback() + raise + + +def test_definition_entries_publish_without_root_nodes_and_reuse_on_rename(): + """A stable source context owns an updated authoritative group despite root renames.""" + root = _base('PR1_entries') + cube = root.nodes.new('GeometryNodeMeshCube') + before = cube.as_pointer() + source = 'def calc(v: Float) -> Float:\n return v + 1.0\n' + first, = _publish(source, root, origin='text:pr1-entries') + assert len(root.nodes) == 1 and root.nodes[0].as_pointer() == before + root.name = 'PR1_entries_renamed' + second, = _publish('def calc(v: Float) -> Float:\n return v * 2.0\n', root, + origin='text:pr1-entries') + assert second.as_pointer() == first.as_pointer() + assert any(node.bl_idname == 'ShaderNodeMath' and node.operation == 'MULTIPLY' + for node in second.nodes) + assert root.nodes[0].as_pointer() == before + + +@pytest.mark.parametrize('origin', [None, '', ' ', 'text: trailing ', 123]) +def test_definition_without_stable_origin_rejected_before_build(origin): + """Unanchored definitions cannot silently publish groups under a mutable name.""" + root = _base('PR1_unanchored') + before_groups = {item.as_pointer() for item in bpy.data.node_groups} + with pytest.raises(CompileError, match='stable module_context'): + compiler._prepare_direct_source( + 'def calc(v: Float) -> Float:\n return v + 1.0\n', root, + module_context=origin, + ) + assert {item.as_pointer() for item in bpy.data.node_groups} == before_groups + + +def test_unanchored_definition_free_source_is_allowed(): + """Pure root expressions and compile-time-only sources need no definition owner.""" + root = _base('PR1_definition_free') + for source in ('FLAG = False', 'x = cube(1)'): + prepared, *_ = compiler._prepare_direct_source(source, root) + assert prepared is not None + + +def test_unified_modes_replace_only_for_semantically_physical_top_level(): + """Group-only leaves manual ordinary nodes in place; root output replaces them.""" + root = _base('PR1_two_modes') + manual = root.nodes.new('GeometryNodeMeshCube') + manual_pointer = manual.as_pointer() + group_only = compiler.compile_source_in_tree('FLAG = False', root) + assert group_only.outcome == 'GROUPS_ONLY' + assert group_only.target is root and group_only.skipped_boundary_links == 0 + assert {node.as_pointer() for node in root.nodes} == {manual_pointer} + physical = compiler.compile_source_in_tree('a = cube(1)', root) + assert physical.outcome == 'ROOT_REPLACEMENT' + assert len(root.nodes) == 1 and root.nodes[0].bl_idname == 'GeometryNodeMeshCube' + assert root.nodes[0].as_pointer() != manual_pointer + new_pointer = root.nodes[0].as_pointer() + compiler.compile_source_in_tree('FLAG = False', root) + assert root.nodes[0].as_pointer() == new_pointer + compiler.compile_source_in_tree('a = cube(2)', root) + assert sum(n.bl_idname == 'GeometryNodeMeshCube' for n in root.nodes) == 1 + + +def test_unified_groups_only_publishes_no_root_instances_and_reuses_authority(): + """Definition compilation updates manual group references through their datablock.""" + root = _base('PR1_group_only') + manual = root.nodes.new('GeometryNodeMeshCube') + saved = (manual.as_pointer(), tuple(manual.location)) + source = 'def calc(v: Float) -> Float:\n return v + 1.0\n' + result = compiler.compile_source_in_tree(source, root, module_context='text:PR1-source') + assert result.outcome == 'GROUPS_ONLY' and len(root.nodes) == 1 + from NodeForge.function_instances import FUNCTION_DEFINITION_OWNER_PROP + fn_group, = [g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'calc' + and g.get(FUNCTION_DEFINITION_OWNER_PROP) + and 'text:PR1-source' in g.get('nodeforge_module_origin', '')] + group_node = root.nodes.new('GeometryNodeGroup') + group_node.node_tree = fn_group + manual_math = root.nodes.new('ShaderNodeMath') + root.links.new(group_node.outputs[0], manual_math.inputs[0]) + link_pointers = [(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in root.links] + root.name = 'PR1_group_only_renamed' + compiler.compile_source_in_tree('def calc(v: Float) -> Float:\n return v * 2.0\n', root, + module_context='text:PR1-source') + assert group_node.node_tree is fn_group + assert [(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in root.links] == link_pointers + assert manual_math.inputs[0].is_linked + assert (manual.as_pointer(), tuple(manual.location)) == saved + assert sum(n.bl_idname == 'GeometryNodeGroup' for n in root.nodes) == 1 + assert any(n.bl_idname == 'ShaderNodeMath' and n.operation == 'MULTIPLY' + for n in fn_group.nodes) + result = compiler.compile_source_in_tree('FLAG = False', root) + assert result.outcome == 'GROUPS_ONLY' and group_node.node_tree is fn_group + + +def test_unified_definitions_require_stable_origin_even_with_root_statements(): + """A source owner must be anchored before any root or group publication.""" + root = _base('PR1_anchored_physical') + manual = root.nodes.new('GeometryNodeMeshCube') + source = 'def calc() -> Geometry:\n return cube(1)\na = calc()\n' + with pytest.raises(CompileError, match='stable module_context'): + compiler.compile_source_in_tree(source, root) + assert len(root.nodes) == 1 and root.nodes[0].as_pointer() == manual.as_pointer() + + +def _radius_root(name, *, with_input): + """Make a base interface whose Radius native socket identifier is not zero.""" + tree = _base(name) + unused = tree.interface.new_socket(name='Unused', in_out='INPUT', socket_type='NodeSocketFloat') + item = tree.interface.new_socket(name='Radius', in_out='INPUT', socket_type='NodeSocketFloat') + assert item.identifier != unused.identifier + tree.interface.remove(unused) + inlet = tree.nodes.new('NodeGroupInput') if with_input else None + return tree, inlet, item.identifier + + +def test_canonical_root_input_reuses_manual_node_and_properties(): + """Repeated raw reads never edit an existing user's Group Input node.""" + root, inlet, identifier = _radius_root('PR1_existing_group_input', with_input=True) + inlet.label = 'Keep label' + inlet.location = (312, 450) + pointer = inlet.as_pointer() + code = '''a = node("NodeGroupInput", output="Radius", typ=Float) +b = node("NodeGroupInput", output="Radius", typ=Float) +c = a + b +''' + for _ in range(2): + compiler.compile_source_in_tree(code, root) + inputs = [node for node in root.nodes if node.bl_idname == 'NodeGroupInput'] + assert len(inputs) == 1 and inputs[0].as_pointer() == pointer + assert inputs[0].label == 'Keep label' and tuple(inputs[0].location) == (312, 450) + assert inputs[0].outputs['Radius'].identifier == identifier + math = [node for node in root.nodes if node.bl_idname == 'ShaderNodeMath'] + assert math and all(node.inputs[0].is_linked for node in math if node.operation == 'ADD') + with pytest.raises(CompileError, match='differs'): + compiler.compile_source_in_tree( + 'a = node("NodeGroupInput", props={"label":"Wrong"}, output="Radius", typ=Float)', root, + ) + assert inlet.label == 'Keep label' and inlet.as_pointer() == pointer + + +def test_canonical_root_input_creates_one_and_remains_across_recompiles(): + """A missing physical Input is created lazily then reused by subsequent Compile.""" + root, _, identifier = _radius_root('PR1_missing_group_input', with_input=False) + source = 'a = node("NodeGroupInput", props={"label": "Created"}, output="Radius", typ=Float)' + compiler.compile_source_in_tree(source, root) + inlet, = [node for node in root.nodes if node.bl_idname == 'NodeGroupInput'] + pointer = inlet.as_pointer() + assert inlet.label == 'Created' and inlet.outputs['Radius'].identifier == identifier + compiler.compile_source_in_tree(source, root) + assert [n.as_pointer() for n in root.nodes if n.bl_idname == 'NodeGroupInput'] == [pointer] + with pytest.raises(CompileError): + compiler.compile_source_in_tree('a = node("NodeGroupInput", output="NO_SUCH_SOCKET", typ=Float)', root) + assert [n.as_pointer() for n in root.nodes if n.bl_idname == 'NodeGroupInput'] == [pointer] + + +def test_nested_inline_raw_input_shares_root_endpoint(): + """Inline source expansion references the caller's one physical input.""" + root, inlet, identifier = _radius_root('PR1_inline_group_input', with_input=True) + code = '''def read_radius(__inline__=True) -> Float: + return node("NodeGroupInput", output="Radius", typ=Float) +a = read_radius() +b = read_radius() +c = a + b +''' + compiler.compile_source_in_tree(code, root, module_context='text:pr1-inline') + assert [n.as_pointer() for n in root.nodes if n.bl_idname == 'NodeGroupInput'] == [inlet.as_pointer()] + assert inlet.outputs['Radius'].identifier == identifier + + +def test_canonical_root_input_chooses_first_manual_and_validates_named_outputs(): + """Named multi-socket reads reuse the first manual Input and leave other Inputs alone.""" + root, first, radius_id = _radius_root('PR1_two_manual_inputs', with_input=True) + amount = root.interface.new_socket(name='Amount', in_out='INPUT', socket_type='NodeSocketFloat') + second = root.nodes.new('NodeGroupInput') + first.label = 'First remains' + second.label = 'Second remains' + second.location = (333, -444) + stable = ((first.as_pointer(), first.label), (second.as_pointer(), second.label, tuple(second.location))) + source = 'pair = node("NodeGroupInput", outputs={"Radius": Float, "Amount": Float})\nresult = pair.Radius + pair.Amount\n' + for _ in range(2): + compiler.compile_source_in_tree(source, root) + inputs = [n for n in root.nodes if n.bl_idname == 'NodeGroupInput'] + assert len(inputs) == 2 + assert (inputs[0].as_pointer(), inputs[0].label) == stable[0] + assert (inputs[1].as_pointer(), inputs[1].label, tuple(inputs[1].location)) == stable[1] + assert first.outputs['Radius'].identifier == radius_id + assert first.outputs['Amount'].identifier == amount.identifier + math, = [n for n in root.nodes if n.bl_idname == 'ShaderNodeMath' and n.operation == 'ADD'] + assert {link.from_node.as_pointer() for link in root.links if link.to_node == math} == {first.as_pointer()} + before = {n.as_pointer() for n in root.nodes} + with pytest.raises(CompileError): + compiler.compile_source_in_tree('pair = node("NodeGroupInput", outputs={"Radius": Vector})', root) + assert {n.as_pointer() for n in root.nodes} == before + assert first.label == 'First remains' and second.label == 'Second remains' + + +def test_unapproved_group_output_is_rejected_and_rolled_back(monkeypatch): + """A structural Group Output cannot be smuggled into root cutover.""" + from NodeForge.blender import ir_lowering + root, inlet, _ = _radius_root('PR1_rogue_output', with_input=True) + ptrs = {node.as_pointer() for node in root.nodes} + old = ir_lowering._cube_geometry + + def rogue(*args, **kwargs): + """Inject a forbidden structural output after an otherwise valid geometry call.""" + result = old(*args, **kwargs) + args[0].nodes.new('NodeGroupOutput') + return result + + monkeypatch.setattr(ir_lowering, '_cube_geometry', rogue) + with pytest.raises(CompileError, match='unapproved structural'): + compiler.compile_source_in_tree('a = cube(1)', root) + assert {node.as_pointer() for node in root.nodes} == ptrs + + +def test_groups_only_failed_transaction_rollback_requires_undo(monkeypatch): + """An incomplete group rollback is surfaced through the root UI error type.""" + from NodeForge.blender.root_update import RootUpdateError + root = _base('PR1_group_rollback_failure') + origin = 'text:PR1-rollback' + compiler.compile_source_in_tree('def a(x: Float) -> Float:\n return x + 1\n', + root, module_context=origin) + original = FunctionMaterializer.materialize_module + seen = [] + + def fail_after_update(self, prepared, materialization, context, **kwargs): + """Fail the second entry after the first one updated its authority.""" + seen.append(prepared.contract.function_id.name) + if seen[-1] == 'b': + raise RuntimeError('second function failed') + return original(self, prepared, materialization, context, **kwargs) + + def broken_rollback(self): + """Expose the existing group transaction's uncertain rollback boundary.""" + raise RuntimeError('group restoration failed') + + monkeypatch.setattr(FunctionMaterializer, 'materialize_module', fail_after_update) + monkeypatch.setattr(BlenderGroupBuildTransaction, 'rollback', broken_rollback) + with pytest.raises(RootUpdateError, match='group restoration failed') as raised: + compiler.compile_source_in_tree('''def a(x: Float) -> Float: + return x * 2 + +def b(x: Float) -> Float: + return x + 1 +''', root, module_context=origin) + assert seen == ['a', 'b'] and raised.value.may_have_mutated + assert 'second function failed' in str(raised.value) + assert isinstance(raised.value.__cause__, RuntimeError) + assert not list(root.nodes) + + +def test_single_compile_operator_preserves_undo_and_selected_text_origin(monkeypatch): + """The retained Compile operator uses the Text origin and retains uncertain Undo.""" + from types import SimpleNamespace + from NodeForge import ui + from NodeForge.blender.root_update import RootUpdateError + from NodeForge.compiler_identities import TEXT_MODULE_CONTEXT_PROP + root = _base('PR1_operator') + text = bpy.data.texts.new('PR1_operator_text') + text.write('def make() -> Geometry:\n return cube(1)\n') + reports = [] + operator = SimpleNamespace(expression='', report=lambda kind, msg: reports.append((kind, msg))) + ctx = SimpleNamespace(scene=SimpleNamespace(gn_script_mvp=SimpleNamespace(text_block=text))) + monkeypatch.setattr(ui, '_eligible_base_gn_tree', lambda context: root) + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, ctx) == {'FINISHED'} + origin = text.get(TEXT_MODULE_CONTEXT_PROP) + assert isinstance(origin, str) and origin + assert not list(root.nodes) + assert not hasattr(ui, 'GNSCRIPT_MVP_OT_update_expression') + + def uncertain(*args, **kwargs): + """Simulate a group rollback that could not restore authoritative data.""" + raise RootUpdateError('group cleanup incomplete', may_have_mutated=True) + + monkeypatch.setattr(ui, 'compile_source_in_tree', uncertain) + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, ctx) == {'FINISHED'} + assert text.get(TEXT_MODULE_CONTEXT_PROP) == origin + assert any('group cleanup incomplete' in msg for _, msg in reports) + + +def test_public_root_compiler_exposes_only_unified_route(): + """Neither legacy append nor Update remains available as an API escape hatch.""" + assert callable(compiler.compile_source_in_tree) + assert not hasattr(compiler, 'compose_source_initial') + assert not hasattr(compiler, 'update_source_in_tree') + root = _base('PR1_single_root_api') + assert compiler.compile_script_auto('FLAG = False', root) == (root, False) + with pytest.raises(CompileError, match='stable module_context'): + compiler.compile_script_auto('def calc() -> Float:\n return 1.0\n', root) + + +def test_groups_only_postcommit_cleanup_exception_preserves_undo(monkeypatch): + """A warning promoted to an exception after commit retains the Undo signal.""" + import warnings + from NodeForge.blender import group_backend + from NodeForge.blender.root_update import RootUpdateError + from NodeForge.function_instances import FUNCTION_DEFINITION_OWNER_PROP + + root = _base('PR1_postcommit_uncertain') + origin = 'text:pr1-postcommit' + source_v1 = 'def calc(v: Float) -> Float:\n return v + 1.0\n' + source_v2 = 'def calc(v: Float) -> Float:\n return v * 2.0\n' + compiler.compile_source_in_tree(source_v1, root, module_context=origin) + published, = [g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'calc' + and g.get(FUNCTION_DEFINITION_OWNER_PROP) + and origin in g.get('nodeforge_module_origin', '')] + manual = root.nodes.new('GeometryNodeGroup') + manual.node_tree = published + manual_pointer = manual.as_pointer() + original_pointer = published.as_pointer() + removal = group_backend._remove_node_group_if_live + + def cleanup_with_warning(group, *, failures=None): + """Inject one failed postcommit retirement after removing the backup.""" + result = removal(group, failures=failures) + if failures is not None: + failures.append(RuntimeError('injected postcommit backup cleanup failure')) + return result + + monkeypatch.setattr(group_backend, '_remove_node_group_if_live', cleanup_with_warning) + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + with pytest.raises(RootUpdateError, match='postcommit backup cleanup failure') as exc: + compiler.compile_source_in_tree(source_v2, root, module_context=origin) + assert exc.value.may_have_mutated is True + assert isinstance(exc.value.__cause__, RuntimeWarning) + assert 'injected postcommit backup cleanup failure' in str(exc.value.__cause__) + assert manual.as_pointer() == manual_pointer + assert manual.node_tree.as_pointer() == original_pointer + assert any(n.bl_idname == 'ShaderNodeMath' and n.operation == 'MULTIPLY' + for n in published.nodes) + + +def test_groups_only_postcommit_warning_without_escalation_keeps_success(monkeypatch): + """Ordinary best-effort retirement warnings remain successful commits.""" + import warnings + from NodeForge.blender import group_backend + + root = _base('PR1_postcommit_warning') + origin = 'text:pr1-postcommit-default' + compiler.compile_source_in_tree('def calc(v: Float) -> Float:\n return v + 1.0\n', + root, module_context=origin) + removal = group_backend._remove_node_group_if_live + + def cleanup_with_warning(group, *, failures=None): + """Record a postcommit cleanup warning without aborting publication.""" + result = removal(group, failures=failures) + if failures is not None: + failures.append(RuntimeError('injected benign retirement failure')) + return result + + monkeypatch.setattr(group_backend, '_remove_node_group_if_live', cleanup_with_warning) + with warnings.catch_warnings(record=True) as emitted: + warnings.simplefilter('always', RuntimeWarning) + result = compiler.compile_source_in_tree( + 'def calc(v: Float) -> Float:\n return v * 2.0\n', + root, module_context=origin, + ) + assert result.outcome == 'GROUPS_ONLY' + assert any('injected benign retirement failure' in str(w.message) for w in emitted) + + +def test_internal_root_lowering_rejects_definitions_without_mutating_root(): + """The internal root helper cannot revive obsolete definition-only placement.""" + from NodeForge.blender.direct_composition import compose_prepared_initial + + root = _base('PR1_internal_definition_only_rejected') + manual = root.nodes.new('GeometryNodeMeshCube') + original_ptr = manual.as_pointer() + source = 'def calc(v: Float) -> Float:\n return v + 1.0\n' + prepared, backend, session, snapshot = compiler._prepare_direct_source( + source, root, module_context='text:pr1-internal-guard', + ) + from NodeForge.blender.ir_lowering import RootInputEndpoint + group_ptrs = {group.as_pointer() for group in bpy.data.node_groups} + tx = BlenderGroupBuildTransaction() + with pytest.raises(CompileError, match='physical top-level body'): + compose_prepared_initial( + prepared, root, backend, session, + transaction=tx, root_input_endpoint=RootInputEndpoint(), + ) + tx.rollback() + assert {group.as_pointer() for group in bpy.data.node_groups} == group_ptrs + assert [node.as_pointer() for node in root.nodes] == [original_ptr] + assert compiler.compile_source_in_tree( + source, root, module_context='text:pr1-internal-guard', + ).outcome == 'GROUPS_ONLY' + assert [node.as_pointer() for node in root.nodes] == [original_ptr] + + +def test_compile_operator_retains_undo_on_real_postcommit_cleanup_exception(monkeypatch): + """The real group publication error travels through the UI's Undo-aware path.""" + import warnings + from types import SimpleNamespace + from NodeForge import ui + from NodeForge.blender import group_backend + + root = _base('PR1_operator_postcommit') + text = bpy.data.texts.new('PR1_operator_postcommit_source') + text.write('def calc(v: Float) -> Float:\n return v + 1.0\n') + reports = [] + operator = SimpleNamespace(expression='', report=lambda kind, msg: reports.append((kind, msg))) + context = SimpleNamespace(scene=SimpleNamespace(gn_script_mvp=SimpleNamespace(text_block=text))) + monkeypatch.setattr(ui, '_eligible_base_gn_tree', lambda _context: root) + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, context) == {'FINISHED'} + + text.clear() + text.write('def calc(v: Float) -> Float:\n return v * 2.0\n') + cleanup = group_backend._remove_node_group_if_live + + def fail_postcommit(group, *, failures=None): + """Force a retirement warning after authoritative publication.""" + removed = cleanup(group, failures=failures) + if failures is not None: + failures.append(RuntimeError('UI postcommit warning-as-error')) + return removed + + monkeypatch.setattr(group_backend, '_remove_node_group_if_live', fail_postcommit) + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, context) == {'FINISHED'} + assert any('postcommit cleanup failed' in msg and 'UI postcommit warning-as-error' in msg + for _, msg in reports) + assert not list(root.nodes) diff --git a/tests/blender/test_unified_definition_only_entries.py b/tests/blender/test_unified_definition_only_entries.py index 3a155e6..0896239 100644 --- a/tests/blender/test_unified_definition_only_entries.py +++ b/tests/blender/test_unified_definition_only_entries.py @@ -12,7 +12,7 @@ def test_definition_only_entries_have_correct_nested_levels_and_required_inputs( """A→B→C with D places only A and D on the base node tree.""" group = bpy.data.node_groups.new('NFTest_definition_only_entries', 'GeometryNodeTree') original = group.nodes.new('GeometryNodeMeshCube') - compiler.compose_source_initial('''def leaf(x: Float) -> Float: + compile_root('''def leaf(x: Float) -> Float: return x + 1 def middle(x: Float) -> Float: @@ -24,12 +24,11 @@ def entry_a(x: Float) -> Float: def entry_d(x: Float) -> Float: return x + 2 ''', group) - entries = _group_nodes(group) + assert _group_nodes(group) == [] + entries = [published_entry(group, name) for name in ('entry_a', 'entry_d')] assert len(entries) == 2 - assert {node.node_tree.get('nodeforge_module_name') for node in entries} == {'entry_a', 'entry_d'} - entry_a = next(node for node in entries if node.node_tree.get('nodeforge_module_name') == 'entry_a') - assert entry_a.inputs[0].is_linked is False - child = _group_nodes(entry_a.node_tree) + entry_a = entries[0] + child = _group_nodes(entry_a) assert len(child) == 1 and child[0].node_tree.get('nodeforge_module_name') == 'middle' grandchild = _group_nodes(child[0].node_tree) assert len(grandchild) == 1 and grandchild[0].node_tree.get('nodeforge_module_name') == 'leaf' @@ -40,7 +39,7 @@ def entry_d(x: Float) -> Float: def test_definition_only_entry_graph_does_not_insert_unused_mixed_definitions(): """One effective executable expression disables automatic entry placement.""" group = bpy.data.node_groups.new('NFTest_mixed_no_auto_entries', 'GeometryNodeTree') - compiler.compose_source_initial('''a = cube(1) + compile_root('''a = cube(1) def unused(x: Float) -> Float: return x + 1 @@ -52,19 +51,20 @@ def unused(x: Float) -> Float: def test_definition_only_constant_declarations_do_not_disable_entries(): """Compile-time-only source declarations do not count as executable composition.""" group = bpy.data.node_groups.new('NFTest_compile_time_entries', 'GeometryNodeTree') - compiler.compose_source_initial('''FACTOR = 2 + compile_root('''FACTOR = 2 def constant_entry(x: Float) -> Float: return x + FACTOR ''', group) - assert len(_group_nodes(group)) == 1 + assert _group_nodes(group) == [] + assert published_entry(group, 'constant_entry') def test_ambiguous_untyped_definition_only_entry_is_rejected(): """An entry requiring unspecified type inference must not become arbitrary Float.""" group = bpy.data.node_groups.new('NFTest_untyped_entry', 'GeometryNodeTree') with pytest.raises(CompileError, match='requires an explicit type annotation'): - compiler.compose_source_initial('''def ambiguous(x): + compile_root('''def ambiguous(x): return x ''', group) assert len(group.nodes) == 0 @@ -74,7 +74,7 @@ def test_definition_only_recursion_rejected_before_group_creation(): """A recursive graph has no valid zero-incoming entry and must be diagnosed.""" group = bpy.data.node_groups.new('NFTest_recursive_definition_entries', 'GeometryNodeTree') with pytest.raises(CompileError, match='Recursive'): - compiler.compose_source_initial('''def recur(x: Float) -> Float: + compile_root('''def recur(x: Float) -> Float: return recur(x) ''', group) assert len(group.nodes) == 0 @@ -83,7 +83,7 @@ def test_definition_only_recursion_rejected_before_group_creation(): def test_two_entries_share_the_same_nested_callee(): """Multiple roots reuse a common nested definition without duplicate backing owners.""" group = bpy.data.node_groups.new('NFTest_shared_entries', 'GeometryNodeTree') - compiler.compose_source_initial('''def _common(x: Float) -> Float: + compile_root('''def _common(x: Float) -> Float: return x + 1 def a(x: Float) -> Float: @@ -92,9 +92,9 @@ def a(x: Float) -> Float: def b(x: Float) -> Float: return _common(x) ''', group) - roots = _group_nodes(group) - assert len(roots) == 2 - shared = [_group_nodes(node.node_tree)[0].node_tree for node in roots] + assert _group_nodes(group) == [] + roots = [published_entry(group, name) for name in ('a', 'b')] + shared = [_group_nodes(group)[0].node_tree for group in roots] assert shared[0].as_pointer() == shared[1].as_pointer() assert shared[0].get('nodeforge_module_name') == '_common' @@ -102,7 +102,7 @@ def b(x: Float) -> Float: def test_top_level_function_call_does_not_create_automatic_entries(): """Executable top-level invocation suppresses entries for untouched definitions.""" group = bpy.data.node_groups.new('NFTest_called_entry_only', 'GeometryNodeTree') - compiler.compose_source_initial('''def a(x: Float) -> Float: + compile_root('''def a(x: Float) -> Float: return x + 2 def uncalled(x: Float) -> Float: @@ -118,7 +118,7 @@ def uncalled(x: Float) -> Float: def test_nested_compile_time_branch_places_only_reachable_entry(): """Nested CT writes must produce the same edges as actual group materialization.""" tree = bpy.data.node_groups.new('NFTest_nested_ct_true_entry', 'GeometryNodeTree') - compiler.compose_source_initial('''FLAG = False + compile_root('''FLAG = False def a(): if True: @@ -130,16 +130,16 @@ def a(): def b(): return 2 ''', tree) - entries = _group_nodes(tree) - assert [node.node_tree.get('nodeforge_module_name') for node in entries] == ['a'] - children = _group_nodes(entries[0].node_tree) + assert _group_nodes(tree) == [] + entries = [published_entry(tree, 'a')] + children = _group_nodes(entries[0]) assert [node.node_tree.get('nodeforge_module_name') for node in children] == ['b'] def test_nested_compile_time_dead_call_does_not_hide_independent_entry(): """Nested CT reassignment prunes a dead call in both graph and Blender body.""" tree = bpy.data.node_groups.new('NFTest_nested_ct_false_entry', 'GeometryNodeTree') - compiler.compose_source_initial('''FLAG = True + compile_root('''FLAG = True def a(): if True: @@ -151,7 +151,7 @@ def a(): def b(): return 2 ''', tree) - entries = _group_nodes(tree) - assert {node.node_tree.get('nodeforge_module_name') for node in entries} == {'a', 'b'} - a = next(node for node in entries if node.node_tree.get('nodeforge_module_name') == 'a') - assert _group_nodes(a.node_tree) == [] + assert _group_nodes(tree) == [] + entries = [published_entry(tree, name) for name in ('a', 'b')] + assert {group.get('nodeforge_module_name') for group in entries} == {'a', 'b'} + assert _group_nodes(entries[0]) == [] diff --git a/tests/blender/test_unified_direct_composition.py b/tests/blender/test_unified_direct_composition.py index bee7a4b..31519ea 100644 --- a/tests/blender/test_unified_direct_composition.py +++ b/tests/blender/test_unified_direct_composition.py @@ -8,18 +8,19 @@ def test_direct_compose_mixed_forward_decl_into_existing_base_group(): target = bpy.data.node_groups.new('NFTest_direct_mixed', 'GeometryNodeTree') user = target.nodes.new('GeometryNodeMeshCube') before_groups = {group.as_pointer() for group in bpy.data.node_groups} - assert compiler.compose_source_initial('''a = cube(1) + result = compile_root('''a = cube(1) b = raise_level(a) def raise_level(geometry: Geometry) -> Geometry: return transform(geometry, translation=vector(0, 0, 1)) extra = cube(2) -''', target) is target - assert any(node.as_pointer() == user.as_pointer() for node in target.nodes) +''', target) + assert result.outcome == 'ROOT_REPLACEMENT' and result.target is target + assert all(node.as_pointer() != user.as_pointer() for node in target.nodes) assert not any(node.bl_idname in {'NodeGroupInput', 'NodeGroupOutput'} for node in target.nodes) groups = [node for node in target.nodes if node.bl_idname == 'GeometryNodeGroup'] assert len(groups) == 1 assert groups[0].node_tree.get('nodeforge_module_name') == 'raise_level' - assert len([node for node in target.nodes if node.bl_idname == 'GeometryNodeMeshCube']) >= 3 + assert len([node for node in target.nodes if node.bl_idname == 'GeometryNodeMeshCube']) == 2 assert {group.as_pointer() for group in bpy.data.node_groups} - before_groups == {groups[0].node_tree.as_pointer()} @@ -30,11 +31,11 @@ def test_direct_compose_preserves_preexisting_base_links_and_interface(): sink = group.nodes.new('GeometryNodeTransform') group.links.new(source.outputs['Mesh'], sink.inputs['Geometry']) interface_before = tuple((socket.name, socket.in_out) for socket in group.interface.items_tree) - compiler.compose_source_initial('a = cube(1)\nb = cube(2)\n', group) + compile_root('a = cube(1)\nb = cube(2)\n', group) assert tuple((socket.name, socket.in_out) for socket in group.interface.items_tree) == interface_before - assert len(group.links) == 1 - assert group.links[0].from_node.as_pointer() == source.as_pointer() - assert group.links[0].to_node.as_pointer() == sink.as_pointer() + assert len(group.links) == 0 + assert all(node.as_pointer() not in (source.as_pointer(), sink.as_pointer()) + for node in group.nodes) @pytest.mark.parametrize('source', ['output(value=1)', 'x = input_float("X")', 'x = ghost_variable']) @@ -43,20 +44,20 @@ def test_direct_compose_rejects_old_root_contract_and_implicit_bindings(source): group = bpy.data.node_groups.new('NFTest_direct_invalid', 'GeometryNodeTree') user = group.nodes.new('GeometryNodeMeshCube') with pytest.raises(CompileError): - compiler.compose_source_initial(source, group) + compile_root(source, group) assert tuple(group.nodes) == (user,) def test_direct_compose_requires_geometry_node_tree(): """Invalid targets cannot produce a new generated root group.""" - with pytest.raises(CompileError, match='existing base GeometryNodeTree'): - compiler.compose_source_initial('a = cube(1)', None) + with pytest.raises(CompileError, match='base Geometry Nodes tree'): + compile_root('a = cube(1)', None) def test_definition_only_entries_respect_module_compile_time_condition(): """A compile-time-disabled reverse call does not prevent nested materialization.""" target = bpy.data.node_groups.new('NFTest_module_ct_entry', 'GeometryNodeTree') - compiler.compose_source_initial('''FLAG = False + compile_root('''FLAG = False def a() -> Geometry: if FLAG: @@ -66,25 +67,24 @@ def a() -> Geometry: def b() -> Geometry: return a() ''', target) - entries = [node for node in target.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert len(entries) == 1 - assert entries[0].node_tree.get('nodeforge_module_name') == 'b' + assert not any(node.bl_idname == 'GeometryNodeGroup' for node in target.nodes) + assert published_entry(target, 'b').get('nodeforge_module_name') == 'b' def test_explicit_int_runtime_range_count_entry_uses_int_socket(): """A definition-only range(count) materializes as an Int Repeat input.""" target = bpy.data.node_groups.new('NFTest_typed_range', 'GeometryNodeTree') - compiler.compose_source_initial('''def make_count(count: Int): + compile_root('''def make_count(count: Int): x = 1.0 for i in range(count): x = x + 1.0 return x ''', target) - entry, = [node for node in target.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert entry.node_tree is not None - assert entry.inputs[0].name == 'count' - assert entry.inputs[0].bl_idname == 'NodeSocketInt' - assert any(node.bl_idname == 'GeometryNodeRepeatInput' for node in entry.node_tree.nodes) + assert not list(target.nodes) + entry = published_entry(target, 'make_count') + assert any(item.name == 'count' and item.socket_type == 'NodeSocketInt' + for item in entry.interface.items_tree if item.item_type == 'SOCKET') + assert any(node.bl_idname == 'GeometryNodeRepeatInput' for node in entry.nodes) def test_explicit_int_runtime_range_count_standalone_add(): diff --git a/tests/blender/test_unified_final_regressions.py b/tests/blender/test_unified_final_regressions.py index cd48ffa..9dcd526 100644 --- a/tests/blender/test_unified_final_regressions.py +++ b/tests/blender/test_unified_final_regressions.py @@ -1,5 +1,7 @@ """Last-stage negative and positive regressions for the breaking .nf frontend.""" +from helpers import compile_root + import bpy import pytest @@ -19,14 +21,14 @@ def test_obsolete_function_io_is_rejected_without_publishing(source): user = tree.nodes.new('GeometryNodeMeshCube') before = user.as_pointer() with pytest.raises(CompileError): - compiler.compose_source_initial(source, tree) + compile_root(source, tree) assert [node.as_pointer() for node in tree.nodes] == [before] def test_forward_function_alias_can_be_composed_without_duplicate_binding(): """An alias declaration is not a second runtime assignment to a reserved name.""" tree = bpy.data.node_groups.new('NFTest_alias_compose', 'GeometryNodeTree') - compiler.compose_source_initial('''shortcut = later + compile_root('''shortcut = later result = shortcut(2.0) def later(x: Float) -> Float: return x + 1 @@ -39,7 +41,7 @@ def test_reassigning_a_definition_alias_fails_before_node_mutation(): tree = bpy.data.node_groups.new('NFTest_alias_reassignment', 'GeometryNodeTree') user = tree.nodes.new('GeometryNodeMeshCube') with pytest.raises(CompileError): - compiler.compose_source_initial('''def f(x: Float) -> Float: + compile_root('''def f(x: Float) -> Float: return x alias = f alias = other_name diff --git a/tests/blender/test_unified_group_authority.py b/tests/blender/test_unified_group_authority.py index b5cb675..19da734 100644 --- a/tests/blender/test_unified_group_authority.py +++ b/tests/blender/test_unified_group_authority.py @@ -15,7 +15,7 @@ def test_automatic_module_owner_lookup_rejects_copied_group_without_mutation(): v = v ''' root = bpy.data.node_groups.new('NFTest_module_authority', 'GeometryNodeTree') - compiler.compose_source_initial(original, root) + compile_root(original, root) owned = next(g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'authority_module_leaf') copy = owned.copy() root_pointer = root.as_pointer() @@ -85,7 +85,7 @@ def test_duplicate_owner_id_properties_remain_ambiguous_after_save_reopen(tmp_pa v = v ''' root = bpy.data.node_groups.new('NFTest_authority_reopen', 'GeometryNodeTree') - compiler.compose_source_initial(source, root) + compile_root(source, root) owned = next(g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'persistent_authority_leaf') copy = owned.copy() root.use_fake_user = True diff --git a/tests/blender/test_unified_initial_composition_rollback.py b/tests/blender/test_unified_initial_composition_rollback.py index fec0f05..d7a69ce 100644 --- a/tests/blender/test_unified_initial_composition_rollback.py +++ b/tests/blender/test_unified_initial_composition_rollback.py @@ -42,31 +42,30 @@ def fail_second_cube(*args, **kwargs): return result monkeypatch.setattr(ir_lowering, '_cube_geometry', fail_second_cube) - with pytest.raises(RuntimeError, match='second cube failure'): - compiler.compose_source_initial('a = cube(1)\nb = cube(2)\n', tree) + from NodeForge.blender.root_update import RootUpdateError + with pytest.raises(RootUpdateError, match='second cube failure') as error: + compile_root('a = cube(1)\nb = cube(2)\n', tree) + assert not error.value.may_have_mutated _assert_user_graph(tree, before, endpoints) assert {group.as_pointer() for group in bpy.data.node_groups} == old_groups def test_late_second_definition_entry_failure_cleans_nodes_and_nested_groups(monkeypatch): """Both already-placed Group Nodes and newly materialized callees roll back.""" - from NodeForge.blender import library_groups + from NodeForge.blender.function_materializer import FunctionMaterializer tree, before, endpoints = _user_graph('NFTest_entry_initial_rollback') old_groups = {group.as_pointer() for group in bpy.data.node_groups} - original = library_groups.apply_function_node_display_name - count = 0 + original = FunctionMaterializer.materialize_module - def fail_after_second_placement(node, function_group): - nonlocal count - result = original(node, function_group) - count += 1 - if count == 2: + def fail_after_first_entry(self, prepared, materialization, context, **kwargs): + """Fail the second entry after earlier candidate group publication.""" + if prepared.contract.function_id.name == 'root_b': raise RuntimeError('injected second entry failure') - return result + return original(self, prepared, materialization, context, **kwargs) - monkeypatch.setattr(library_groups, 'apply_function_node_display_name', fail_after_second_placement) + monkeypatch.setattr(FunctionMaterializer, 'materialize_module', fail_after_first_entry) with pytest.raises(RuntimeError, match='second entry failure'): - compiler.compose_source_initial('''def root_a(x: Float) -> Float: + compile_root('''def root_a(x: Float) -> Float: return child(x) def root_b(x: Float) -> Float: @@ -81,31 +80,29 @@ def child(x: Float) -> Float: def test_failed_initial_composition_restores_previously_existing_nested_group(monkeypatch): """Nested in-place group updates roll back after level-zero node cleanup.""" - from NodeForge.blender import library_groups + from NodeForge.blender.function_materializer import FunctionMaterializer context = 'NFTest_persisted_function_owner' old_target = bpy.data.node_groups.new('NFTest_existing_owner_target', 'GeometryNodeTree') initial = '''def ref(x: Float) -> Float: return x + 1 ''' - compiler.compose_source_initial(initial, old_target, module_context=context) - existing = next(node.node_tree for node in old_target.nodes if node.bl_idname == 'GeometryNodeGroup') + compile_root(initial, old_target, module_context=context) + existing = next(g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'ref' + and context in str(g.get('nodeforge_module_origin', ''))) pointer = existing.as_pointer() previous = tuple((node.bl_idname, getattr(node, 'operation', '')) for node in existing.nodes) tree, before, endpoints = _user_graph('NFTest_failing_initial_new_target') - original = library_groups.apply_function_node_display_name - count = 0 + original = FunctionMaterializer.materialize_module - def fail_after_second(node, function_group): - nonlocal count - result = original(node, function_group) - count += 1 - if count == 2: + def fail_after_first(self, prepared, materialization, context, **kwargs): + """Reject second group entry after mutating an existing authoritative group.""" + if prepared.contract.function_id.name == 'independent': raise RuntimeError('second entry failed after nested update') - return result + return original(self, prepared, materialization, context, **kwargs) - monkeypatch.setattr(library_groups, 'apply_function_node_display_name', fail_after_second) + monkeypatch.setattr(FunctionMaterializer, 'materialize_module', fail_after_first) with pytest.raises(RuntimeError, match='second entry failed'): - compiler.compose_source_initial('''def ref(x: Float) -> Float: + compile_root('''def ref(x: Float) -> Float: return x * 4 def independent(x: Float) -> Float: diff --git a/tests/blender/test_unified_legacy_source_entrypoints.py b/tests/blender/test_unified_legacy_source_entrypoints.py index 294770a..92d30bb 100644 --- a/tests/blender/test_unified_legacy_source_entrypoints.py +++ b/tests/blender/test_unified_legacy_source_entrypoints.py @@ -13,7 +13,7 @@ def test_legacy_root_interface_is_rejected_before_any_blender_mutation(): before = tuple(x.as_pointer() for x in tree.nodes) existing = {group.as_pointer() for group in bpy.data.node_groups} with pytest.raises(CompileError, match='legacy .nf interface'): - compiler.compose_source_initial(_OLD, tree) + compile_root(_OLD, tree) with pytest.raises(CompileError, match='legacy .nf interface'): compiler.create_expression_group(_OLD) with pytest.raises(CompileError, match='legacy .nf interface'): diff --git a/tests/blender/test_unified_module_materialization.py b/tests/blender/test_unified_module_materialization.py index 13d85a2..22155dd 100644 --- a/tests/blender/test_unified_module_materialization.py +++ b/tests/blender/test_unified_module_materialization.py @@ -16,7 +16,7 @@ def _nested_groups(tree): def _compose_module(source, name, *, environment=None): """Compile unified top-level statements into a pre-existing base node tree.""" root = bpy.data.node_groups.new(name, 'GeometryNodeTree') - compiler.compose_source_initial(source, root, resolved_environment=environment) + compile_root(source, root, resolved_environment=environment) return root diff --git a/tests/blender/test_unified_module_selected_reload.py b/tests/blender/test_unified_module_selected_reload.py index 618ff64..a3987ab 100644 --- a/tests/blender/test_unified_module_selected_reload.py +++ b/tests/blender/test_unified_module_selected_reload.py @@ -22,7 +22,7 @@ def _materialized(source=_SOURCE): """Return one shared and two unique instances in one existing target tree.""" target = bpy.data.node_groups.new('NFTest-selected-module-root', 'GeometryNodeTree') - compiler.compose_source_initial(source, target, module_context=_CONTEXT) + compile_root(source, target, module_context=_CONTEXT) nodes = [node for node in target.nodes if node.bl_idname == 'GeometryNodeGroup'] groups = [node.node_tree for node in nodes] assert len(groups) == 3 and len({group.as_pointer() for group in groups}) == 3 diff --git a/tests/blender/test_unified_root_update.py b/tests/blender/test_unified_root_update.py index 3646d20..c760d2d 100644 --- a/tests/blender/test_unified_root_update.py +++ b/tests/blender/test_unified_root_update.py @@ -56,7 +56,7 @@ def test_update_preserves_root_interface_io_custom_props_and_replaces_manual_gro outer = bpy.data.node_groups.new('NFR5_outer', 'GeometryNodeTree') external = outer.nodes.new('GeometryNodeGroup') external.node_tree = tree - result = compiler.update_source_in_tree('a = cube(2)\n', tree) + result = compile_root('a = cube(2)\n', tree) assert result.target is tree assert tree.as_pointer() == ptr and tree['user_marker'] == 'keep me' assert _interface(tree) == signature @@ -81,7 +81,7 @@ def test_update_keeps_direct_io_link_and_frame_parented_io_absolute_position(): outlet.location = (350, -100) before = tuple(root_update._point(node) for node in (inlet, outlet)) tree.links.new(inlet.outputs['Geometry'], outlet.inputs['Geometry']) - result = compiler.update_source_in_tree('a = cube(1)\n', tree) + result = compile_root('a = cube(1)\n', tree) assert result.skipped_boundary_links == 0 assert outlet.parent is None assert tuple(root_update._point(node) for node in (inlet, outlet)) == before @@ -95,7 +95,7 @@ def test_update_reconnects_unique_compatible_boundary_and_reuses_position(): old = tree.nodes.new('GeometryNodeMeshCube') old.location = (333, 177) tree.links.new(old.outputs['Mesh'], outlet.inputs['Geometry']) - result = compiler.update_source_in_tree('a = cube(3)\n', tree) + result = compile_root('a = cube(3)\n', tree) cube, = [node for node in tree.nodes if node.bl_idname == 'GeometryNodeMeshCube'] assert cube.as_pointer() != old.as_pointer() assert root_update._point(cube) == (333, 177) @@ -108,29 +108,31 @@ def test_update_skips_ambiguous_old_boundary_without_guessing(): tree, inlet, outlet = _root('NFR5_skip_ambiguous') old = tree.nodes.new('GeometryNodeMeshCube') tree.links.new(old.outputs['Mesh'], outlet.inputs['Geometry']) - result = compiler.update_source_in_tree('a = cube(1)\nb = cube(2)\n', tree) + result = compile_root('a = cube(1)\nb = cube(2)\n', tree) assert result.skipped_boundary_links == 1 assert not outlet.inputs['Geometry'].is_linked assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) == 2 -def test_update_twice_no_accumulation_and_compile_still_appends(): +def test_compile_twice_no_accumulation(): """Two Updates overwrite ordinary nodes; Compile alone remains append-only.""" tree, _, _ = _root('NFR5_repeat_update') - compiler.update_source_in_tree('a = cube(1)\nb = cube(2)', tree) - compiler.update_source_in_tree('a = cube(7)\nb = cube(8)', tree) + compile_root('a = cube(1)\nb = cube(2)', tree) + compile_root('a = cube(7)\nb = cube(8)', tree) assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) == 2 - compiler.compose_source_initial('a = cube(1)', tree) - assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) == 3 + compile_root('a = cube(1)', tree) + assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) == 1 -def test_update_definition_only_and_zero_node_source(): - """Entry placement shares Compile while a nonblank compile-time-only script clears nodes.""" +def test_compile_definition_only_and_zero_node_source_preserves_manual_root(): + """Group-only Compile publishes definitions without clearing ordinary root nodes.""" tree, inlet, outlet = _root('NFR5_definitions') - compiler.update_source_in_tree('def make_cube() -> Geometry:\n return cube(1)\n', tree) - assert sum(node.bl_idname == 'GeometryNodeGroup' for node in tree.nodes) == 1 - compiler.update_source_in_tree('FLAG = False\n', tree) - assert {node.as_pointer() for node in tree.nodes} == {inlet.as_pointer(), outlet.as_pointer()} + old = tree.nodes.new('GeometryNodeMeshCube') + compile_root('def make_cube() -> Geometry:\n return cube(1)\n', tree) + assert sum(node.bl_idname == 'GeometryNodeGroup' for node in tree.nodes) == 0 + assert published_entry(tree, 'make_cube') + compile_root('FLAG = False\n', tree) + assert {node.as_pointer() for node in tree.nodes} == {inlet.as_pointer(), outlet.as_pointer(), old.as_pointer()} @pytest.mark.parametrize('source', ['', ' \n ', 'x = unknown(1)', 'output(value=1)', 'x = input_float("x")']) @@ -140,7 +142,7 @@ def test_update_rejects_invalid_source_before_root_mutation(source): old = tree.nodes.new('GeometryNodeMeshCube') ids = {node.as_pointer() for node in tree.nodes} with pytest.raises(CompileError): - compiler.update_source_in_tree(source, tree) + compile_root(source, tree) assert ids == {node.as_pointer() for node in tree.nodes} assert len(bpy.data.node_groups.get(tree.name).nodes) == 3 @@ -155,12 +157,12 @@ def test_update_rejects_function_private_and_mesh_compute_root_before_mutation() tree, inlet, outlet = _root(name) tree[key] = value with pytest.raises(CompileError): - compiler.update_source_in_tree('a = cube(1)', tree) + compile_root('a = cube(1)', tree) assert {node.as_pointer() for node in tree.nodes} == {inlet.as_pointer(), outlet.as_pointer()} tree, inlet, outlet = _root('NFR5_private') mark_transaction_private(tree) with pytest.raises(CompileError): - compiler.update_source_in_tree('a = cube(1)', tree) + compile_root('a = cube(1)', tree) assert len(tree.nodes) == 2 @@ -186,7 +188,7 @@ def injected(*args, **kwargs): monkeypatch.setattr(ir_lowering, '_cube_geometry', injected) with pytest.raises(root_update.RootUpdateError, match='NFR5 stage failure') as info: - compiler.update_source_in_tree('a = cube(1)\nb = cube(2)\n', tree) + compile_root('a = cube(1)\nb = cube(2)\n', tree) assert not info.value.may_have_mutated assert pointers == {node.as_pointer() for node in tree.nodes} assert len(tree.links) == 1 and tree.links[0].from_node.as_pointer() == old.as_pointer() @@ -206,7 +208,7 @@ def injected(*args, **kwargs): monkeypatch.setattr(root_update, '_reconnect_boundary', injected) with pytest.raises(root_update.RootUpdateError, match='NFR5 late failure') as info: - compiler.update_source_in_tree('a = cube(4)\n', tree) + compile_root('a = cube(4)\n', tree) assert info.value.may_have_mutated assert len([n for n in tree.nodes if n.bl_idname == 'GeometryNodeMeshCube']) == 1 assert len(tree.links) == 1 @@ -220,7 +222,7 @@ def test_update_frame_and_distinct_type_layout_without_guessing(): first.location = (901, 901) second = tree.nodes.new('GeometryNodeTransform') second.location = (432, 211) - compiler.update_source_in_tree('a = cube(1)\nb = cube(2)\nc = transform(a)', tree) + compile_root('a = cube(1)\nb = cube(2)\nc = transform(a)', tree) transforms = [node for node in tree.nodes if node.bl_idname == 'GeometryNodeTransform'] assert len(transforms) == 1 and root_update._point(transforms[0]) == (432, 211) assert all(root_update._point(node) != (901, 901) @@ -236,12 +238,12 @@ def test_node_driver_is_rejected_while_root_interface_driver_is_allowed(): assert any('nodes[' in fcurve.data_path for fcurve in tree.animation_data.drivers) before = {n.as_pointer() for n in tree.nodes} with pytest.raises(CompileError, match='animation/driver'): - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert {n.as_pointer() for n in tree.nodes} == before tree.animation_data_clear() # Structural node animation does not target an ordinary node. inlet.driver_add('location', 0) - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert len([n for n in tree.nodes if n.bl_idname == 'GeometryNodeMeshCube']) == 1 @@ -259,7 +261,7 @@ def test_node_driver_guard_uses_blender_escaped_paths(node_name): assert node.path_from_id() in tree.animation_data.drivers[0].data_path before = {item.as_pointer() for item in tree.nodes} with pytest.raises(CompileError, match='animation/driver'): - compiler.update_source_in_tree('a = cube(2)', tree) + compile_root('a = cube(2)', tree) assert {item.as_pointer() for item in tree.nodes} == before assert tree.animation_data.drivers[0].data_path.startswith(node.path_from_id() + '.') @@ -272,7 +274,7 @@ def test_structural_driver_does_not_match_similar_ordinary_node_prefix(): inlet.name = 'Node.001' inlet.driver_add('location', 0) assert inlet.path_from_id().startswith('nodes[') - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in tree.nodes) == 1 @@ -282,7 +284,7 @@ def test_directed_boundary_preserves_output_and_skips_occupied_input(): old = tree.nodes.new('GeometryNodeTransform') tree.links.new(inlet.outputs['Geometry'], old.inputs['Geometry']) tree.links.new(old.outputs['Geometry'], outlet.inputs['Geometry']) - result = compiler.update_source_in_tree('a = cube(1)\nb = transform(a)', tree) + result = compile_root('a = cube(1)\nb = transform(a)', tree) transform, = (n for n in tree.nodes if n.bl_idname == 'GeometryNodeTransform') assert result.skipped_boundary_links == 1 assert any(link.from_node.bl_idname == 'GeometryNodeMeshCube' @@ -298,7 +300,7 @@ def test_layout_identical_shapes_reuses_ordered_duplicate_positions(): tree, _, _ = _root('NFR5_ordered_duplicate') a, b = (tree.nodes.new('GeometryNodeMeshCube') for _ in range(2)) a.location, b.location = (25, 55), (625, -75) - compiler.update_source_in_tree('a = cube(1)\nb = cube(2)', tree) + compile_root('a = cube(1)\nb = cube(2)', tree) positions = [root_update._point(n) for n in tree.nodes if n.bl_idname == 'GeometryNodeMeshCube'] assert positions == [(25, 55), (625, -75)] @@ -313,13 +315,13 @@ def source(scalar_type, body): f' return {body}\n' 'y = change(2)\n') - compiler.update_source_in_tree(source('Float', 'value + 1'), tree, module_context=context) + compile_root(source('Float', 'value + 1'), tree, module_context=context) old_group = next(n.node_tree for n in tree.nodes if n.bl_idname == 'GeometryNodeGroup') group_pointer = old_group.as_pointer() - compiler.update_source_in_tree(source('Float', 'value * 3'), tree, module_context=context) + compile_root(source('Float', 'value * 3'), tree, module_context=context) new_group = next(n.node_tree for n in tree.nodes if n.bl_idname == 'GeometryNodeGroup') assert new_group.as_pointer() == group_pointer - compiler.update_source_in_tree(source('Int', 'value + 5'), tree, module_context=context) + compile_root(source('Int', 'value + 5'), tree, module_context=context) new_group = next(n.node_tree for n in tree.nodes if n.bl_idname == 'GeometryNodeGroup') assert new_group is not None and len([n for n in tree.nodes if n.bl_idname == 'GeometryNodeGroup']) == 1 assert any(item.item_type == "SOCKET" and item.in_out == "INPUT" @@ -332,12 +334,12 @@ def test_raw_math_staged_once_and_retained_without_copying(): tree.nodes.new('GeometryNodeMeshCube') src = ('x = node("ShaderNodeMath", props={"operation": "ADD"}, ' 'inputs={ID("Value_001"): 2.0}, output=ID("Value"), typ=Float)\n') - compiler.update_source_in_tree(src, tree) + compile_root(src, tree) math_nodes = [n for n in tree.nodes if n.bl_idname == 'ShaderNodeMath'] assert len(math_nodes) == 1 assert math_nodes[0].operation == 'ADD' first_pointer = math_nodes[0].as_pointer() - compiler.update_source_in_tree(src, tree) + compile_root(src, tree) math_nodes = [n for n in tree.nodes if n.bl_idname == 'ShaderNodeMath'] assert len(math_nodes) == 1 and math_nodes[0].as_pointer() != first_pointer @@ -370,7 +372,7 @@ def observe(*args, **kwargs): return result monkeypatch.setattr(direct_composition, 'compose_prepared_initial', observe) - compiler.update_source_in_tree('a = cube(9)\n', tree) + compile_root('a = cube(9)\n', tree) assert seen assert not old_ptrs.intersection(node.as_pointer() for node in tree.nodes) @@ -389,7 +391,7 @@ def observe(self): return transaction_commit(self) monkeypatch.setattr(group_backend.BlenderGroupBuildTransaction, 'commit', observe) - compiler.update_source_in_tree('a = cube(1)', root) + compile_root('a = cube(1)', root) assert counts == [set()] @@ -397,11 +399,12 @@ def test_direct_lowering_with_caller_transaction_does_not_commit(monkeypatch): """An externally owned transaction remains open after successful direct lowering.""" from NodeForge.blender.group_backend import BlenderGroupBuildTransaction from NodeForge.blender.direct_composition import compose_prepared_initial + from NodeForge.blender.ir_lowering import RootInputEndpoint target, _, _ = _root('NFR5_owned_lowering') - prepared, backend, session, snapshot = compiler._prepare_direct_source('a = cube(4)', target) + prepared, backend, session, _snapshot = compiler._prepare_direct_source('a = cube(4)', target) tx = BlenderGroupBuildTransaction() compose_prepared_initial(prepared, target, backend, session, - source_module=snapshot, transaction=tx) + transaction=tx, root_input_endpoint=RootInputEndpoint()) assert not tx._closed assert sum(n.bl_idname == 'GeometryNodeMeshCube' for n in target.nodes) == 1 tx.rollback() @@ -415,14 +418,14 @@ def test_repeat_pair_stages_and_survives_physical_cutover_twice(): source = ('x = 0\n' 'for i in repeat_range(3):\n' ' x = x + 1\n') - compiler.update_source_in_tree(source, tree) + compile_root(source, tree) pair = [node for node in tree.nodes if node.bl_idname in {'GeometryNodeRepeatInput', 'GeometryNodeRepeatOutput'}] assert len(pair) == 2 start, = (n for n in pair if n.bl_idname == 'GeometryNodeRepeatInput') end, = (n for n in pair if n.bl_idname == 'GeometryNodeRepeatOutput') assert start.paired_output.as_pointer() == end.as_pointer() - compiler.update_source_in_tree(source, tree) + compile_root(source, tree) pair = [node for node in tree.nodes if node.bl_idname in {'GeometryNodeRepeatInput', 'GeometryNodeRepeatOutput'}] assert len(pair) == 2 @@ -438,48 +441,45 @@ def test_update_accepts_import_and_rejects_missing_import_without_root_change(tm monkeypatch.setattr(local_sources, '_local_sources_registry_path', lambda: tmp_path / 'registry.json') (tmp_path / 'shapes.nf').write_text('def model() -> Geometry:\n return cube(2)\n') tree, _, _ = _root('NFR5_import_source') - compiler.update_source_in_tree('from local import shapes\nx = shapes.model()\n', tree) + compile_root('from local import shapes\nx = shapes.model()\n', tree) assert sum(n.bl_idname == 'GeometryNodeGroup' for n in tree.nodes) == 1 before = {n.as_pointer() for n in tree.nodes} with pytest.raises(CompileError): - compiler.update_source_in_tree('from local import missing_module\nx = missing_module.model()', tree) + compile_root('from local import missing_module\nx = missing_module.model()', tree) assert before == {n.as_pointer() for n in tree.nodes} def test_staging_failure_after_nested_update_preserves_old_root_but_marks_possible_change(monkeypatch): """A shared nested rollback cannot be promised globally atomic on stage errors.""" - from NodeForge.blender import library_groups + from NodeForge.blender.function_materializer import FunctionMaterializer tree, _, _ = _root('NFR5_nested_stage_rollback') context = 'NFR5_nested_rollback_owner' - compiler.update_source_in_tree('''def shared() -> Geometry: + compile_root('''def shared() -> Geometry: return cube(1) ''', tree, module_context=context) old_root = {node.as_pointer() for node in tree.nodes} - old_group = next(n.node_tree for n in tree.nodes if n.bl_idname == 'GeometryNodeGroup') + old_group = next(g for g in bpy.data.node_groups if g.get('nodeforge_module_name') == 'shared' + and context in str(g.get('nodeforge_module_origin', ''))) pointer = old_group.as_pointer() - original = library_groups.apply_function_node_display_name - counter = 0 - - def failing_second(node, group): - """Stop after updating one shared nested function and staging two entries.""" - nonlocal counter - result = original(node, group) - counter += 1 - if counter == 2: + nodes_before = tuple((n.bl_idname, n.name) for n in old_group.nodes) + original = FunctionMaterializer.materialize_module + + def failing_second(self, prepared, materialization, scope, **kwargs): + """Fail before second entry after a candidate group was already updated.""" + if prepared.contract.function_id.name == 'extra': raise RuntimeError('NFR5 nested stage failure') - return result + return original(self, prepared, materialization, scope, **kwargs) - monkeypatch.setattr(library_groups, 'apply_function_node_display_name', failing_second) - with pytest.raises(root_update.RootUpdateError, match='NFR5 nested stage failure') as info: - compiler.update_source_in_tree('''def shared() -> Geometry: + monkeypatch.setattr(FunctionMaterializer, 'materialize_module', failing_second) + with pytest.raises(RuntimeError, match='NFR5 nested stage failure'): + compile_root('''def shared() -> Geometry: return cube(5) def extra() -> Geometry: return cube(6) ''', tree, module_context=context) - assert info.value.may_have_mutated # A canonical nested group was updated. assert {node.as_pointer() for node in tree.nodes} == old_root assert old_group.as_pointer() == pointer - # Existing shared-group rollback limitations are deliberately not reimplemented here. + assert tuple((n.bl_idname, n.name) for n in old_group.nodes) == nodes_before def test_linked_root_rejected_before_materialization(tmp_path): @@ -493,7 +493,7 @@ def test_linked_root_rejected_before_materialization(tmp_path): linked = dst.node_groups[0] assert linked is not None and linked.library is not None with pytest.raises(CompileError, match='linked or read-only'): - compiler.update_source_in_tree('a = cube(1)', linked) + compile_root('a = cube(1)', linked) assert len(linked.nodes) == 2 @@ -509,7 +509,7 @@ def failed_remove(_backup): monkeypatch.setattr(root_update, '_remove_backup', failed_remove) with pytest.raises(root_update.RootUpdateError, match='backup cleanup') as info: - compiler.update_source_in_tree('a = cube(7)', tree) + compile_root('a = cube(7)', tree) assert info.value.may_have_mutated assert all(n.bl_idname != 'ShaderNodeMath' for n in tree.nodes) @@ -528,8 +528,8 @@ def insert_unexpected_io(*args, **kwargs): return result monkeypatch.setattr(direct_composition, 'compose_prepared_initial', insert_unexpected_io) - with pytest.raises(root_update.RootUpdateError, match='cannot insert new structural') as info: - compiler.update_source_in_tree('a = cube(1)', root) + with pytest.raises(root_update.RootUpdateError, match='unapproved structural') as info: + compile_root('a = cube(1)', root) assert not info.value.may_have_mutated assert {n.as_pointer() for n in root.nodes} == before @@ -558,7 +558,7 @@ def test_update_rejects_ordinary_node_nla_animation_without_active_action(): before = {n.as_pointer() for n in tree.nodes} links = tuple((link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links) with pytest.raises(CompileError, match='animation/driver'): - compiler.update_source_in_tree('a = cube(2)', tree) + compile_root('a = cube(2)', tree) assert before == {n.as_pointer() for n in tree.nodes} assert links == tuple((link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links) assert strip.action is action and tree.animation_data.action is None @@ -569,7 +569,7 @@ def test_update_accepts_structural_io_nla_animation_without_active_action(): tree, inlet, outlet = _root('NFR5_nla_io') action, strip = _nla_strip_for_node(tree, inlet) old_io = (inlet.as_pointer(), outlet.as_pointer()) - compiler.update_source_in_tree('a = cube(2)', tree) + compile_root('a = cube(2)', tree) assert old_io == (inlet.as_pointer(), outlet.as_pointer()) assert strip.action is action @@ -608,7 +608,7 @@ def fail_once(node, position): monkeypatch.setattr(root_update, '_place_absolute', fail_once) with pytest.raises(root_update.RootUpdateError, match='NFR5 detach once') as info: - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert not info.value.may_have_mutated assert before == {node.as_pointer() for node in tree.nodes} assert inlet.parent.as_pointer() == frame.as_pointer() and outlet.parent.as_pointer() == frame.as_pointer() @@ -626,7 +626,7 @@ def fail_position(*args): monkeypatch.setattr(root_update, '_place_absolute', fail_position) with pytest.raises(root_update.RootUpdateError, match='structural I/O restoration') as info: - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert info.value.may_have_mutated assert inlet.parent.as_pointer() == frame.as_pointer() # The restore attempt reattaches before placement. assert outlet.parent.as_pointer() == frame.as_pointer() @@ -645,7 +645,7 @@ def fail_boundary(*args): monkeypatch.setattr(root_update, '_reconnect_boundary', fail_boundary) with pytest.raises(root_update.RootUpdateError, match='NFR5 late frame restore') as info: - compiler.update_source_in_tree('a = cube(4)', tree) + compile_root('a = cube(4)', tree) assert info.value.may_have_mutated restored_frame = tree.nodes.get('Old Frame') assert restored_frame is not None and restored_frame.bl_idname == 'NodeFrame' @@ -671,5 +671,87 @@ def fail_io_restore(*args): monkeypatch.setattr(root_update, '_reconnect_boundary', fail_boundary) monkeypatch.setattr(root_update, '_restore_structural_io', fail_io_restore) with pytest.raises(root_update.RootUpdateError, match='root restoration: parent Frame unavailable') as info: - compiler.update_source_in_tree('a = cube(3)', tree) + compile_root('a = cube(3)', tree) assert info.value.may_have_mutated + + +def test_root_update_owns_one_transaction_and_cleans_failed_lowering(monkeypatch): + """A lowering failure is cleaned and rolled back once by the outer root owner.""" + from NodeForge.blender import direct_composition + from NodeForge.blender.group_backend import BlenderGroupBuildTransaction + + tree, _, outlet = _root('NFR5_single_attempt_owner') + old = tree.nodes.new('GeometryNodeMeshCube') + tree.links.new(old.outputs['Mesh'], outlet.inputs['Geometry']) + old_pointers = {node.as_pointer() for node in tree.nodes} + old_groups = {group.as_pointer() for group in bpy.data.node_groups} + transactions = [] + rollbacks = [] + commits = [] + + class ObservedTransaction(BlenderGroupBuildTransaction): + """Count the transaction transitions for one root-producing attempt.""" + + def __init__(self): + super().__init__() + transactions.append(self) + + def rollback(self): + rollbacks.append(self) + return super().rollback() + + def commit(self): + commits.append(self) + return super().commit() + + original_lower = direct_composition.lower_body + + def fail_after_lowering(*args, **kwargs): + """Raise only after the real lowerer has inserted its ordinary node.""" + original_lower(*args, **kwargs) + raise RuntimeError('single-owner staged failure') + + monkeypatch.setattr(root_update, 'BlenderGroupBuildTransaction', ObservedTransaction) + monkeypatch.setattr(direct_composition, 'lower_body', fail_after_lowering) + with pytest.raises(root_update.RootUpdateError, match='single-owner staged failure') as info: + compile_root('a = cube(2)\n', tree) + assert info.value.may_have_mutated is False + assert len(transactions) == 1 + assert rollbacks == transactions and commits == [] + assert transactions[0]._closed + assert {node.as_pointer() for node in tree.nodes} == old_pointers + assert len(tree.links) == 1 and tree.links[0].from_node.as_pointer() == old.as_pointer() + assert {group.as_pointer() for group in bpy.data.node_groups} == old_groups + + +def test_root_lowerer_propagates_without_owning_node_or_transaction_cleanup(monkeypatch): + """Direct lowering leaves both failure cleanup and transaction closure to its caller.""" + from NodeForge.blender import direct_composition + from NodeForge.blender.group_backend import BlenderGroupBuildTransaction + from NodeForge.blender.ir_lowering import RootInputEndpoint + + tree, _, _ = _root('NFR5_lowering_delegates_failures') + prepared, backend, session, _snapshot = compiler._prepare_direct_source('a = cube(3)', tree) + tx = BlenderGroupBuildTransaction() + old_pointers = {node.as_pointer() for node in tree.nodes} + + def fail_with_created_node(context, *_args, **_kwargs): + """Simulate a backend failure after inserting a physical node.""" + context.group.nodes.new('GeometryNodeMeshCube') + raise RuntimeError('caller must clean this node') + + monkeypatch.setattr(direct_composition, 'lower_body', fail_with_created_node) + with pytest.raises(RuntimeError, match='caller must clean this node'): + direct_composition.compose_prepared_initial( + prepared, tree, backend, session, + transaction=tx, root_input_endpoint=RootInputEndpoint(), + ) + assert tx._closed is False + assert len([node for node in tree.nodes if node.as_pointer() not in old_pointers]) == 1 + # Explicitly emulate the only supported caller's cleanup policy in this test. + for node in tuple(tree.nodes): + if node.as_pointer() not in old_pointers: + tree.nodes.remove(node) + tx.rollback() + assert tx._closed + assert {node.as_pointer() for node in tree.nodes} == old_pointers diff --git a/tests/blender/test_unified_root_update_ui.py b/tests/blender/test_unified_root_update_ui.py index ea7d1e3..f39a67d 100644 --- a/tests/blender/test_unified_root_update_ui.py +++ b/tests/blender/test_unified_root_update_ui.py @@ -52,16 +52,16 @@ def test_operator_switches_selected_text_and_preserves_pinned_root(root_editor): pointer = root.as_pointer() area.spaces.active.pin = True with bpy.context.temp_override(area=area): - assert bpy.ops.gn_script_mvp.update_expression() == {'FINISHED'} + assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} assert sum(n.bl_idname == 'GeometryNodeMeshCube' for n in root.nodes) == 1 bpy.context.scene.gn_script_mvp.text_block = text_b text_b.write('a = cube(3)\nb = cube(4)\n') with bpy.context.temp_override(area=area): - assert bpy.ops.gn_script_mvp.update_expression() == {'FINISHED'} + assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} assert root.as_pointer() == pointer assert sum(n.bl_idname == 'GeometryNodeMeshCube' for n in root.nodes) == 2 - assert 'REGISTER' in ui.GNSCRIPT_MVP_OT_update_expression.bl_options - assert 'UNDO' in ui.GNSCRIPT_MVP_OT_update_expression.bl_options + assert 'REGISTER' in ui.GNSCRIPT_MVP_OT_compile_expression.bl_options + assert 'UNDO' in ui.GNSCRIPT_MVP_OT_compile_expression.bl_options assert not any(key.startswith('nodeforge_root_text') for key in root.keys()) finally: area.spaces.active.pin = False @@ -76,8 +76,8 @@ def test_operator_rejects_missing_or_blank_text_without_editing_root(root_editor for selected in (None, text): bpy.context.scene.gn_script_mvp.text_block = selected with bpy.context.temp_override(area=area): - with pytest.raises(RuntimeError, match='Update Script' if selected is text else 'Text datablock'): - bpy.ops.gn_script_mvp.update_expression() + with pytest.raises(RuntimeError, match='Compile Script requires a nonblank selected Text source'): + bpy.ops.gn_script_mvp.compile_expression() assert {node.as_pointer() for node in root.nodes} == {pointer} @@ -111,6 +111,7 @@ class OperatorReport: def __init__(self): """Prepare an in-memory operator report ledger.""" self.messages = [] + self.expression = '' def report(self, levels, message): """Record Blender-style error levels and messages.""" @@ -118,7 +119,7 @@ def report(self, levels, message): operator = OperatorReport() with bpy.context.temp_override(area=area): - assert ui.GNSCRIPT_MVP_OT_update_expression.execute(operator, bpy.context) == {'FINISHED'} + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, bpy.context) == {'FINISHED'} assert any('NFR5 UI late failure' in msg for levels, msg in operator.messages) assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in root.nodes) == 1 @@ -130,7 +131,6 @@ def test_operator_compile_is_append_only_and_updated_root_replaces(root_editor): with bpy.context.temp_override(area=area): assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} - assert bpy.ops.gn_script_mvp.update_expression() == {'FINISHED'} assert sum(n.bl_idname == 'GeometryNodeMeshCube' for n in root.nodes) == 1 assert ui.NODEFORGE_OT_detach_selected_source_owner in ui.classes assert ui.NODEFORGE_OT_reload_selected_library_group in ui.classes @@ -156,7 +156,8 @@ def test_panel_does_not_show_detach_but_recovery_and_reload_are_registered(): draw = inspect.getsource(ui.GNSCRIPT_MVP_PT_panel.draw) assert 'NODEFORGE_OT_detach_selected_source_owner.bl_idname' not in draw - assert 'GNSCRIPT_MVP_OT_update_expression.bl_idname' in draw + assert 'GNSCRIPT_MVP_OT_update_expression.bl_idname' not in draw + assert 'GNSCRIPT_MVP_OT_compile_expression.bl_idname' in draw assert 'NODEFORGE_OT_reload_selected_library_group.bl_idname' in draw assert ui.NODEFORGE_OT_detach_selected_source_owner in ui.classes @@ -171,7 +172,7 @@ def test_operator_invalid_semantics_does_not_leave_new_text_identity(root_editor assert TEXT_MODULE_CONTEXT_PROP not in text with bpy.context.temp_override(area=area): with pytest.raises(RuntimeError, match='not_defined'): - bpy.ops.gn_script_mvp.update_expression() + bpy.ops.gn_script_mvp.compile_expression() assert TEXT_MODULE_CONTEXT_PROP not in text assert len(tree.nodes) == 1 and tree.nodes[0].as_pointer() == old.as_pointer() @@ -197,6 +198,7 @@ class OperatorReport: def __init__(self): """Initialize report capture.""" self.messages = [] + self.expression = '' def report(self, levels, message): """Record diagnostic and classification.""" @@ -204,6 +206,6 @@ def report(self, levels, message): operator = OperatorReport() with bpy.context.temp_override(area=area): - assert ui.GNSCRIPT_MVP_OT_update_expression.execute(operator, bpy.context) == {'FINISHED'} + assert ui.GNSCRIPT_MVP_OT_compile_expression.execute(operator, bpy.context) == {'FINISHED'} assert output.parent.as_pointer() == frame.as_pointer() assert any('structural I/O restoration:' in message for _, message in operator.messages) diff --git a/tests/blender/test_unified_runtime_capability_preflight.py b/tests/blender/test_unified_runtime_capability_preflight.py index e5db625..d5fa262 100644 --- a/tests/blender/test_unified_runtime_capability_preflight.py +++ b/tests/blender/test_unified_runtime_capability_preflight.py @@ -56,7 +56,7 @@ def test_direct_physical_extension_never_invokes_destructive_backend(tmp_path): group.links.new(a.outputs['Mesh'], b.inputs['Geometry']) before = {node.as_pointer() for node in group.nodes} with pytest.raises(CompileError, match='unsupported directly'): - compiler.compose_source_initial('''from packages import danger + compile_root('''from packages import danger first = cube(1) result = unsafe_wipe(1.0) ''', group) @@ -73,13 +73,34 @@ def test_physical_extension_inside_nested_function_uses_own_group_transaction(tm builtins._nodeforge_nested_safe_hits = 0 group = bpy.data.node_groups.new('NFTest_nested_extension_supported', 'GeometryNodeTree') previous = group.nodes.new('GeometryNodeMeshCube') - compiler.compose_source_initial('''from packages import danger + compile_root('''from packages import danger def nested_safe(x: Float) -> Float: return safe_add(x) value = nested_safe(1.0) ''', group) assert builtins._nodeforge_nested_safe_hits == 1 - assert any(node.as_pointer() == previous.as_pointer() for node in group.nodes) + assert all(node.as_pointer() != previous.as_pointer() for node in group.nodes) nested = [node.node_tree for node in group.nodes if node.bl_idname == 'GeometryNodeGroup'] assert len(nested) == 1 assert any(node.bl_idname == 'ShaderNodeMath' for node in nested[0].nodes) + + +def test_physical_extension_in_transitively_inline_root_is_rejected_before_backend(tmp_path): + """PR1 must not pass the authoritative root into nested physical Python backends.""" + _install_capability_fixture(tmp_path) + if hasattr(builtins, '_nodeforge_direct_danger_hits'): + delattr(builtins, '_nodeforge_direct_danger_hits') + root = bpy.data.node_groups.new('NFTest_inline_extension_root_forbidden', 'GeometryNodeTree') + manual = root.nodes.new('GeometryNodeMeshCube') + before = {node.as_pointer() for node in root.nodes} + with pytest.raises(CompileError): + compile_root('''from packages import danger + +def inline_unsafe(value: Float, __inline__=True) -> Float: + return unsafe_wipe(value) + +result = inline_unsafe(1.0) +''', root) + assert not hasattr(builtins, '_nodeforge_direct_danger_hits') + assert {node.as_pointer() for node in root.nodes} == before + assert manual.as_pointer() in before diff --git a/tests/blender/test_unified_selected_unique_reload.py b/tests/blender/test_unified_selected_unique_reload.py index 226165a..f6931bd 100644 --- a/tests/blender/test_unified_selected_unique_reload.py +++ b/tests/blender/test_unified_selected_unique_reload.py @@ -1,5 +1,7 @@ """Selected source Reload keeps shared/unique identity for real .nf module owners.""" +from helpers import compile_root + import json import bpy @@ -56,7 +58,7 @@ def _source_owner(namespace, tmp_path, monkeypatch): def _materialize(prefix, callee): """Make three level-0 calls with one shared and two distinct unique owners.""" target = bpy.data.node_groups.new('NFTest_unique_reload_base', 'GeometryNodeTree') - compiler.compose_source_initial( + compile_root( prefix + f'a = {callee}(1.0)\nb = {callee}(2.0, __unique__=True)\n' f'c = {callee}(3.0, __unique__=True)\n', target, module_context='unique-reload-fixture', @@ -147,7 +149,7 @@ def test_rotation_shared_and_unique_package_reload_keeps_overrides(tmp_path): }), encoding='utf-8') installed = packages.install_package_directory(root) target = bpy.data.node_groups.new('NFTest_RotationSharedUnique', 'GeometryNodeTree') - compiler.compose_source_initial('''from packages import rot_reload + compile_root('''from packages import rot_reload a = rot_reload.rotate() b = rot_reload.rotate(__unique__=True) diff --git a/tests/blender/test_unified_semantic_scope.py b/tests/blender/test_unified_semantic_scope.py index a42d031..7484b82 100644 --- a/tests/blender/test_unified_semantic_scope.py +++ b/tests/blender/test_unified_semantic_scope.py @@ -6,7 +6,7 @@ def _compose(source, suffix): tree = bpy.data.node_groups.new('NF-Rev2-sem-' + suffix, 'GeometryNodeTree') - compiler.compose_source_initial(source, tree, module_context='test:rev2-' + suffix) + compile_root(source, tree, module_context='test:rev2-' + suffix) return tree, [node for node in tree.nodes if node.bl_idname == 'GeometryNodeGroup'] @@ -39,7 +39,7 @@ def reuse() -> Geometry: user_node = tree.nodes.new('GeometryNodeMeshCube') groups_before = {group.as_pointer() for group in bpy.data.node_groups} with pytest.raises(CompileError, match='Unknown name: root_geo'): - compiler.compose_source_initial(source, tree, module_context='test:no-implicit-capture') + compile_root(source, tree, module_context='test:no-implicit-capture') assert [node.as_pointer() for node in tree.nodes] == [user_node.as_pointer()] assert {group.as_pointer() for group in bpy.data.node_groups} == groups_before @@ -142,7 +142,7 @@ def unused(value): connections = {(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links} groups = {group.as_pointer() for group in bpy.data.node_groups} with pytest.raises(CompileError, match='explicit type annotation'): - compiler.compose_source_initial(source, tree, module_context='test:rev2-preflight-error') + compile_root(source, tree, module_context='test:rev2-preflight-error') assert {node.as_pointer() for node in tree.nodes} == initial assert {(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links} == connections assert {group.as_pointer() for group in bpy.data.node_groups} == groups @@ -162,7 +162,7 @@ def f(x: Float): tree = bpy.data.node_groups.new('NF-Rev2-before-assignment', 'GeometryNodeTree') user = tree.nodes.new('GeometryNodeMeshCube') with pytest.raises(CompileError, match='used before assignment'): - compiler.compose_source_initial(source, tree, module_context='test:rev2-before-assignment') + compile_root(source, tree, module_context='test:rev2-before-assignment') assert len(tree.nodes) == 1 assert tree.nodes[0].as_pointer() == user.as_pointer() @@ -226,7 +226,7 @@ def outer({parameter}) -> Float: initial_links = {(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links} original_groups = {group.as_pointer() for group in bpy.data.node_groups} with pytest.raises(CompileError, match="Cannot call 'copied'"): - compiler.compose_source_initial(source, tree, module_context='test:rev2-invalid-copied-numeric') + compile_root(source, tree, module_context='test:rev2-invalid-copied-numeric') assert {node.as_pointer() for node in tree.nodes} == initial_nodes assert {(link.from_node.as_pointer(), link.to_node.as_pointer()) for link in tree.links} == initial_links assert {group.as_pointer() for group in bpy.data.node_groups} == original_groups diff --git a/tests/blender/test_unified_source_detachment.py b/tests/blender/test_unified_source_detachment.py index 4ec134e..0eca6ad 100644 --- a/tests/blender/test_unified_source_detachment.py +++ b/tests/blender/test_unified_source_detachment.py @@ -22,7 +22,7 @@ def test_module_single_user_detachment_restores_canonical_updates(): v = v ''' root = bpy.data.node_groups.new('NFTest_module_detachment', 'GeometryNodeTree') - compiler.compose_source_initial(initial, root) + compile_root(initial, root) original = _group('detachable_function') from NodeForge.compiler_identities import parse_module_definition_function_id module_context = parse_module_definition_function_id(original['nodeforge_module_definition']).module.origin @@ -79,7 +79,7 @@ def test_detachment_requires_a_selected_source_owned_copy(): finally: bpy.data.node_groups.remove(plain) original = bpy.data.node_groups.new('NFTest_cannot_detach_canonical_without_copy', 'GeometryNodeTree') - compiler.compose_source_initial('''def sole_owned_leaf(x: Float): + compile_root('''def sole_owned_leaf(x: Float): return x v = sole_owned_leaf(1) @@ -98,7 +98,7 @@ def test_source_detachment_is_persistent_after_save_and_reopen(tmp_path): v = v ''' root = bpy.data.node_groups.new('NFTest_persistent_detachment', 'GeometryNodeTree') - compiler.compose_source_initial(original_source, root) + compile_root(original_source, root) owned = _group('persistent_detachment') copy = owned.copy() detached_name = copy.name diff --git a/tests/blender/test_unified_typed_boundaries.py b/tests/blender/test_unified_typed_boundaries.py index 1c3de90..b7e6fa1 100644 --- a/tests/blender/test_unified_typed_boundaries.py +++ b/tests/blender/test_unified_typed_boundaries.py @@ -1,5 +1,9 @@ """Physical type-interface regressions for independent .nf function definitions.""" +from helpers import compile_root, published_entry + +import ast + import bpy import pytest @@ -12,10 +16,16 @@ def _compose(source: str): """Compile a definition-only module into a fresh existing user tree.""" tree = bpy.data.node_groups.new('NFTest_unified_typed_interface', 'GeometryNodeTree') - compiler.compose_source_initial(source, tree) - calls = [node for node in tree.nodes if node.bl_idname == 'GeometryNodeGroup'] - assert len(calls) == 1 - return tree, calls[0].node_tree + compile_root(source, tree) + assert not list(tree.nodes) + # Root pointer addresses can be recycled after a previous test removes its tree. + # Filter by the declaration's canonical public name, not just the test origin. + fn_name = next(node.name for node in ast.parse(source).body if isinstance(node, ast.FunctionDef)) + groups = [g for g in bpy.data.node_groups + if g.get('nodeforge_module_name') == fn_name + and f"test:root:{tree.as_pointer()}" in str(g.get('nodeforge_module_origin', ''))] + assert len(groups) == 1 + return tree, groups[0] @pytest.mark.parametrize('source,input_type,output_type', [ @@ -49,7 +59,7 @@ def test_typed_argument_mismatch_leaves_existing_tree_untouched(): root = bpy.data.node_groups.new('NFTest_unified_typed_mismatch', 'GeometryNodeTree') existing = root.nodes.new('GeometryNodeMeshCube') with pytest.raises(CompileError): - compiler.compose_source_initial('''def echo(value: String) -> String: + compile_root('''def echo(value: String) -> String: return value result = echo(cube(1.0)) @@ -70,7 +80,7 @@ def test_definition_bundle_parameter_and_return_use_native_bundle_socket(): def test_explicit_float_defaults_and_int_calls_share_one_physical_group(): """An Int runtime argument does not specialize a declared Float input.""" tree = bpy.data.node_groups.new('NFTest_explicit_float_identity', 'GeometryNodeTree') - compiler.compose_source_initial('def scale(value: Float = 2.0) -> Float:\n return value\n\na = scale()\nb = scale(3)\nc = scale(3.5)\n', tree) + compile_root('def scale(value: Float = 2.0) -> Float:\n return value\n\na = scale()\nb = scale(3)\nc = scale(3.5)\n', tree) calls = [node for node in tree.nodes if node.bl_idname == 'GeometryNodeGroup'] assert len(calls) == 3 assert len({node.node_tree.as_pointer() for node in calls}) == 1 @@ -86,7 +96,7 @@ def test_definition_only_invalid_unused_parameter_does_not_mutate_user_tree(): tree = bpy.data.node_groups.new('NFTest_explicit_unused_rollback', 'GeometryNodeTree') original = tree.nodes.new('GeometryNodeMeshCube') with pytest.raises(CompileError, match='requires an explicit type annotation'): - compiler.compose_source_initial('cube(1)\ndef unused(x=3):\n return x\n', tree) + compile_root('cube(1)\ndef unused(x=3):\n return x\n', tree) assert tuple(tree.nodes) == (original,) @@ -108,7 +118,7 @@ def imported_echo(value: Float = RATE) -> Float: for name in ('functions', 'examples', 'local') }) root = bpy.data.node_groups.new('NFTest_imported_explicit_default', 'GeometryNodeTree') - compiler.compose_source_initial('''RATE = 99.0 + compile_root('''RATE = 99.0 from local import defaults result = defaults.imported_echo() ''', root, resolved_environment=environment) diff --git a/tests/blender/test_unified_ui_integration.py b/tests/blender/test_unified_ui_integration.py index c90d2ff..e0669e6 100644 --- a/tests/blender/test_unified_ui_integration.py +++ b/tests/blender/test_unified_ui_integration.py @@ -1,5 +1,7 @@ """Exercise unified source composition and copy detachment through Blender operators.""" +from helpers import compile_root, published_entry + import bpy import pytest @@ -60,11 +62,9 @@ def shift(g: Geometry) -> Geometry: with bpy.context.temp_override(area=area): assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} assert group.as_pointer() == group_pointer - assert len(group.links) >= 1 - assert any(node.as_pointer() == a.as_pointer() for node in group.nodes) - assert any(node.as_pointer() == b.as_pointer() for node in group.nodes) + assert all(node.as_pointer() not in (a.as_pointer(), b.as_pointer()) for node in group.nodes) assert sum(node.bl_idname == 'GeometryNodeGroup' for node in group.nodes) == 1 - assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in group.nodes) >= 3 + assert sum(node.bl_idname == 'GeometryNodeMeshCube' for node in group.nodes) == 2 def test_compile_operator_rejects_invalid_target_without_publication(editor_context): @@ -83,11 +83,12 @@ def test_compile_operator_rejects_invalid_target_without_publication(editor_cont def test_detach_selected_copy_operator_preserves_canonical_group(editor_context): """Detachment is explicit, copy-directed and does not touch the original.""" area, tree, text = editor_context - compiler.compose_source_initial('''def shape(size: Float = 1.0) -> Geometry: + compile_root('''def shape(size: Float = 1.0) -> Geometry: return cube(size) ''', tree) - original_node = next(node for node in tree.nodes if node.bl_idname == 'GeometryNodeGroup') - canonical = original_node.node_tree + canonical = published_entry(tree, 'shape') + original_node = tree.nodes.new('GeometryNodeGroup') + original_node.node_tree = canonical duplicate = canonical.copy() other = tree.nodes.new('GeometryNodeGroup') other.node_tree = duplicate @@ -111,7 +112,12 @@ def test_selected_module_reload_operator_from_bound_text(editor_context): ''') with bpy.context.temp_override(area=area): assert bpy.ops.gn_script_mvp.compile_expression() == {'FINISHED'} - node = next(node for node in group.nodes if node.bl_idname == 'GeometryNodeGroup') + assert not list(group.nodes) # Group-only Compile leaves the root's composition manual. + canonical = next(item for item in bpy.data.node_groups + if item.get('nodeforge_module_name') == 'bump' + and 'nodeforge_module_definition' in item) + node = group.nodes.new('GeometryNodeGroup') + node.node_tree = canonical for candidate in group.nodes: candidate.select = False node.select = True diff --git a/tests/unit/test_semantic_ir.py b/tests/unit/test_semantic_ir.py index 8d2182c..4f734f5 100644 --- a/tests/unit/test_semantic_ir.py +++ b/tests/unit/test_semantic_ir.py @@ -703,6 +703,7 @@ def test_blender_lowering_context_is_minimal_immutable_and_compiler_independent( "extension_registry", "generated_resource_transaction", "layout_origin", + "root_input_endpoint", ) assert context.runtime_bindings[_test_binding_id("a")] is value source_bindings[_test_binding_id("a")] = Value(object(), TYPE_VECTOR) diff --git a/ui.py b/ui.py index 9cf9339..7e98249 100644 --- a/ui.py +++ b/ui.py @@ -7,8 +7,7 @@ from bpy.props import StringProperty, PointerProperty, CollectionProperty, IntProperty, BoolProperty from .compiler import ( - compose_source_initial, - update_source_in_tree, + compile_source_in_tree, create_selected_library_group_auto, update_mesh_compute_modifier, create_library_catalog_group, @@ -383,53 +382,21 @@ class GNSCRIPT_MVP_Properties(PropertyGroup): local_overwrite: BoolProperty(name="Overwrite", default=False) class GNSCRIPT_MVP_OT_compile_expression(Operator): - """Compose unified NF source once in the existing base Geometry Nodes tree.""" + """Compile a selected Text into the current base using one semantic route.""" bl_idname = "gn_script_mvp.compile_expression" bl_label = "Compile Script" - bl_description = "Insert NF statements or definition entries into the existing base node tree" + bl_description = "Replace the root graph or update function groups from the selected script" bl_options = {'REGISTER', 'UNDO'} expression: StringProperty(default="") @classmethod def poll(cls, context): - """Keep the action available so execute can provide a useful target diagnostic.""" - return getattr(context, "scene", None) is not None - - def execute(self, context): - """Compile into space.node_tree and let the compiler own rollback on error.""" - props = getattr(getattr(context, "scene", None), "gn_script_mvp", None) - source = self.expression or _source_from_props(props) - try: - target = _eligible_base_gn_tree(context) - from .compiler import ensure_source_text_context - text = None if self.expression else getattr(props, 'text_block', None) - module_context = ensure_source_text_context(text) if text is not None else None - compose_source_initial(source, target, module_context=module_context) - except Exception as exc: - traceback.print_exc() - self.report({'ERROR'}, str(exc)) - return {'CANCELLED'} - self.report({'INFO'}, f"Compiled script into: {target.name}") - return {'FINISHED'} - - - -class GNSCRIPT_MVP_OT_update_expression(Operator): - """Replace all ordinary nodes in the current base tree using selected Text.""" - - bl_idname = 'gn_script_mvp.update_expression' - bl_label = 'Update Script' - bl_description = 'Replace all ordinary root nodes (including manual Group Nodes) using selected Text' - bl_options = {'REGISTER', 'UNDO'} - - @classmethod - def poll(cls, context): - """Leave the action available for precise eligibility diagnostics.""" + """Provide a precise target diagnostic during execute.""" return getattr(context, 'scene', None) is not None def execute(self, context): - """Update current base root and retain Undo for possibly partial failures.""" + """Use one Compile route, retaining Undo when cleanup may be incomplete.""" from .compiler import ensure_source_text_context from .compiler_identities import TEXT_MODULE_CONTEXT_PROP from .blender.root_update import RootUpdateError @@ -440,22 +407,18 @@ def execute(self, context): try: target = _eligible_base_gn_tree(context) props = getattr(context.scene, 'gn_script_mvp', None) - text = getattr(props, 'text_block', None) - if text is None: - raise ValueError('Select a Text datablock for Update Script') - source = _source_from_props(props) - if not source.strip(): - raise ValueError('Update Script requires a nonblank selected Text source') - context_added = TEXT_MODULE_CONTEXT_PROP not in text - module_context = ensure_source_text_context(text) - result = update_source_in_tree(source, target, module_context=module_context) + text = None if self.expression else getattr(props, 'text_block', None) + source = self.expression or _source_from_props(props) + if not isinstance(source, str) or not source.strip(): + raise ValueError('Compile Script requires a nonblank selected Text source') + if text is not None: + context_added = TEXT_MODULE_CONTEXT_PROP not in text + module_context = ensure_source_text_context(text) + result = compile_source_in_tree(source, target, module_context=module_context) except Exception as exc: traceback.print_exc() might_have_changed = isinstance(exc, RootUpdateError) and exc.may_have_mutated message = str(exc) - # The existing nested-function identity helper stamps Text IDs. On - # a fully rejected attempt, undo that otherwise unnecessary change - # before returning CANCELLED without an Undo history entry. if not might_have_changed and context_added and text is not None: try: if module_context is None or text.get(TEXT_MODULE_CONTEXT_PROP) == module_context: @@ -467,11 +430,15 @@ def execute(self, context): return {'FINISHED'} if might_have_changed else {'CANCELLED'} if result.skipped_boundary_links: - self.report({'WARNING'}, f'Updated {target.name}; skipped {result.skipped_boundary_links} incompatible or ambiguous boundary link(s)') + self.report({'WARNING'}, + f'Compiled {target.name}; skipped {result.skipped_boundary_links} incompatible or ambiguous boundary link(s)') + elif result.outcome == 'GROUPS_ONLY': + self.report({'INFO'}, f'Updated function groups from: {target.name}') else: - self.report({'INFO'}, f'Updated script in: {target.name}') + self.report({'INFO'}, f'Compiled root graph in: {target.name}') return {'FINISHED'} + def _report_mesh_compute_evaluation(operator, context, group): """Evaluate a committed runtime modifier and report nonfatal callback failure.""" from .blender.mesh_compute_runtime import evaluate_modifier_binding @@ -1214,7 +1181,6 @@ def draw(self, context): row = layout.row(align=True) op = row.operator(GNSCRIPT_MVP_OT_compile_expression.bl_idname, text="Compile Script") op.expression = "" - row.operator(GNSCRIPT_MVP_OT_update_expression.bl_idname, text="Update Script") owner = getattr(context, "active_object", None) if owner is not None and getattr(owner, "type", None) == "MESH": row = layout.row() @@ -1393,7 +1359,6 @@ def menu_func(self, context): NODEFORGE_UL_function_library, NODEFORGE_UL_packages, GNSCRIPT_MVP_OT_compile_expression, - GNSCRIPT_MVP_OT_update_expression, NODEFORGE_OT_install_mesh_compute_modifier, NODEFORGE_OT_reload_mesh_compute_modifier, NODEFORGE_OT_detach_selected_source_owner,