diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a9207ffe..e13b636e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,5 +1,5 @@ # Architecture @@ -9,24 +9,37 @@ Contributor commands and contribution rules live in [CONTRIBUTING.md](CONTRIBUTI ## Public entry points -Graphon is an embeddable Python workflow engine. The host application supplies -workflow configuration, inputs, integration adapters, and any persistence. -The top-level `graphon` package does not re-export its primary classes; import -them from the packages below. +Graphon is an embeddable Python engine for executing Graphs. The host supplies +the Graph definition, inputs, integration adapters, and any persistence. Import +the primary classes from the packages below. | Surface | Entry point | Evidence | | --- | --- | --- | | YAML import and inspection | `graphon.dsl.inspect`, `graphon.dsl.loads` | [Importer](src/graphon/dsl/importer.py), [DSL tests](tests/dsl/) | -| Graph construction | `graphon.graph.Graph`, `GraphBuilder`, `NodeFactory` | [Graph implementation](src/graphon/graph/graph.py), [graph tests](tests/graph/test_graph.py) | -| Execution | `graphon.engine.Engine` | [Engine](src/graphon/engine/engine.py), [workflow tests](tests/workflows/test_full_engine_events.py) | +| Python graph building | `graphon.graph_builder.GraphBuilder` | [Builder](src/graphon/graph_builder/builder.py), [builder tests](tests/graph_builder/test_graph_builder.py) | +| Shared graph definition | `graphon.graph.Graph`, `NodeDefinition`, `EdgeDefinition`, `GraphReference` | [Graph](src/graphon/graph/graph.py), [definition and execution tests](tests/graph/test_graph_definition.py) | +| Execution | `graphon.dsl.load_graph`, `graphon.engine.Engine` | [Importer](src/graphon/dsl/importer.py), [engine](src/graphon/engine/engine.py) | +| Host-supplied nodes | `graphon.engine.FrameGraph`, `graphon.protocols.NodeFactory` | [Frame graph](src/graphon/engine/frame_graph.py), [frame construction tests](tests/engine/test_frame_graph_validation.py) | | Execution setup and state | `graphon.runtime.RuntimeState`, `VariablePool`, `InitParams` | [Runtime exports](src/graphon/runtime/__init__.py), [runtime tests](tests/runtime/) | | Integration contracts | `graphon.protocols` | [Protocol exports](src/graphon/protocols/__init__.py), [export tests](tests/test_protocols_exports.py) | -The [Python example](examples/slim_llm/code.py) constructs nodes and an engine -directly. The [DSL example](examples/slim_llm/dsl.py) uses `loads()`, which builds -the variable pool, runtime state, node factory, graph, and engine. Built-in node -availability and default DSL support are separate concerns: inspect the -[DSL factory](src/graphon/dsl/node_factory.py) for its supported node types. +For an executable DSL document, `inspect(text).document.graph` exposes its +reusable definition. The reader groups nodes from flat Dify workflows into a +root Graph and its embedded bodies. `loads(text, ...)` creates an engine with +the document's variables and plugin dependencies. See the [DSL example](examples/slim_llm/dsl.py). + +In Python, create a `GraphBuilder` and register each node with +`add_node(node_id, node_type)`. Pass the returned IDs to `connect(source, target)` +for each directed edge. `build()` returns an immutable `Graph`. +Pass a definition from either source to `load_graph(graph, ...)` to create a +fresh engine with the built-in node factory. +See the [Python example](examples/slim_llm/code.py) and [supported node types](src/graphon/dsl/node_factory.py). + +With a host factory, `Engine(graph, runtime_state, node_factory=...)` creates +the root frame's executable nodes. A host that already owns those nodes can +pass their node, edge, and adjacency maps and the selected root to `FrameGraph`, +then call `Engine(frame_graph, runtime_state)`. For raw node and edge +configuration, use `FrameGraph.init(graph_config=..., node_factory=..., root_node_id=...)`. ## Import boundaries @@ -34,6 +47,12 @@ The [Import Linter configuration](pyproject.toml) is the source of truth for allowed package dependencies. [Layer regression tests](tests/test_import_layers.py) exercise enforcement in CI. +The DSL reader and Python builder are independent packages at the same layer. +Both use `graphon.graph`. Hosts can construct a `Graph` with `GraphBuilder` +before loading the engine or executable node classes. `graphon.engine` exports +`FrameGraph` and its mutable `Edge` type. See the +[frame graph import tests](tests/engine/test_frame_graph_imports.py). + The public runtime package can restore snapshots without importing the engine. Importing `graphon.protocols` does not register built-in nodes; importing a concrete node implementation registers its type and version. These guarantees are enforced by @@ -45,8 +64,10 @@ runtime paths for new integrations; engine queue aliases exist for compatibility ```mermaid flowchart LR - Config[Graph config and NodeFactory] --> Graph[Scoped Graph] - Graph --> Engine[Engine and root frame] + DSL["YAML · graphon.dsl"] --> Graph["graphon.graph.Graph"] + Python["Python · graphon.graph_builder"] --> Graph + Graph --> Engine[Engine and root FrameGraph] + Host[NodeFactory and runtime state] --> Engine Engine --> Ready[Shared ready queue] Ready --> Workers[Worker pool] Workers --> Dispatch[Dispatch queue] @@ -58,9 +79,12 @@ flowchart LR Stream --> Consumer[Engine.run consumer] ``` -1. [Graph.init](src/graphon/graph/graph.py) turns input configuration into a - scoped executable graph. `Graph.new()` supplies the builder for directly - instantiated nodes; see the [Python example](examples/slim_llm/code.py). +1. For a shared definition, the engine selects the sole entry automatically. + Supply `root_node_id` when there are several. The engine binds fresh node + instances and edges to the root frame. Each container call gets a child frame + for its body. For referenced bodies, the host supplies a `graph_resolver` + that maps a reference to a Graph. See [frame graph factory](src/graphon/engine/frame_graph_factory.py) and + [child frames](src/graphon/engine/frame.py). 2. [Engine](src/graphon/engine/engine.py) binds a root frame, command processor, event stream, fixed worker pool, and dispatcher. Calling `run()` starts or resumes execution and yields graph and frame lifecycle events, committed @@ -139,10 +163,13 @@ Keep frame events enabled so the filter receives its initial root baseline. The filter consumes baselines and committed replacements without forwarding them. Its detached view stays usable after the engine removes the frame. -Root templates come from the graph's response nodes. Child Answer and End -templates come from [retained graph definitions](src/graphon/engine/filter/builtin/response_stream/frame_graph.py) -without reconstructing nodes. Frames without sufficient definitions have no -response session. Response eligibility follows [reachability](src/graphon/engine/filter/builtin/response_stream/reachability.py) +Root templates come from the root graph's response nodes. For child Answer +and End templates, the filter reads the called Graph in its parent's frame or +the retained configuration for a directly built frame. Bodies can use the same +node ID for different replies. See [child templates](src/graphon/engine/filter/builtin/response_stream/frame_graph.py) +and [response tests for called graphs](tests/graph/test_graph_definition.py). +Frames without sufficient definitions have no response session. +Response eligibility follows [reachability](src/graphon/engine/filter/builtin/response_stream/reachability.py) through nonblocking edges and consumed traversal events. A blocking edge opens only if its first consumed decision is a take. The engine may be ahead of the consumer, so activation uses the events already consumed in that frame. See @@ -195,14 +222,24 @@ for that extension. ## State and execution invariants -Execution state is owned by frames; shared queues and workflow execution connect -those frames without requiring nested worker pools. File adapters are host -resources owned by the engine, while snapshots contain portable state. These -boundaries let the host rebuild an execution with its own integrations. +All frames in one run share a [GraphExecution](src/graphon/runtime/execution.py) +and the engine's queues and worker pool. Each frame owns its executable nodes +and edges. `Engine.graph` exposes the root frame's `FrameGraph`. +`Engine.definition` exposes the shared `Graph` when the host supplied one. +The engine keeps host file adapters while snapshots carry portable state. +See the [domain model](docs/domain-model.md#definition-and-execution) for the +boundary between a graph and a run. -[Variable pools](src/graphon/runtime/variable_pool.py) preserve node ownership through copies and serialization for both configured graphs and `Graph.new()` graphs. +[Variable pools](src/graphon/runtime/variable_pool.py) preserve node ownership through copies and serialization for both configured graphs and frames built from host-supplied nodes. Iteration writes host variables already present in the parent pool back to that parent, while keeping inherited node variables private to each round. -Independent workflows with fresh pools have separate ownership even when ancestor or sibling graphs reuse the same node IDs. +Each Graph execution with a fresh pool tracks its own variables, even when ancestor or sibling Graphs reuse node IDs. + +A stored variable has a two-string address `(scope, name)`. `VariablePool.add()` +and `remove()` require this pair. Reads can follow a longer path to an object +field or a file attribute, as in `pool.get(("start", "profile", "name"))`. +`pool.clear_scope("start")` removes every variable in that scope and preserves +its node ownership. See the [address definition](src/graphon/variables/address.py) +and [variable pool tests](tests/runtime/test_variable_pool.py). The executable contracts below are authoritative for validation, lifecycle, and compatibility details: @@ -211,7 +248,7 @@ compatibility details: | --- | --- | --- | | Frame state and queue ownership | [Frame](src/graphon/engine/frame.py), [runtime state](src/graphon/runtime/runtime_state/state.py) | [Dispatch](tests/engine/test_dispatch_patterns.py) | | File adapter binding and isolation | [File runtime](src/graphon/file/runtime.py), [engine](src/graphon/engine/engine.py) | [Execution file isolation](tests/engine/test_file_runtime.py), [file scopes](tests/file/test_runtime.py) | -| Container ownership and factory preflight | [Graph and NodeFactory](src/graphon/graph/graph.py), [scoping](src/graphon/graph/scoping.py), [validation](src/graphon/graph/validation.py) | [Graph scoping and validation](tests/graph/test_graph_scoping.py) | +| Container ownership and factory preflight | [Frame graph factory](src/graphon/engine/frame_graph_factory.py), [node factory contract](src/graphon/nodes/factory.py), [scoping](src/graphon/graph/scoping.py), [validation](src/graphon/graph/validation.py) | [Frame scoping and preflight](tests/engine/test_frame_graph_scoping.py) | | Branch joins and readiness | [Scheduler](src/graphon/engine/scheduler.py) | [Scheduling](tests/engine/test_scheduler.py) | | Container suspension and variable propagation | [Container effects](src/graphon/nodes/container_effects.py), [handlers](src/graphon/engine/container_handler/builtin/) | [Container values](tests/nodes/test_container_effects.py), [cooperative execution](tests/engine/test_cooperative_container_execution.py), [container variable scoping](tests/workflows/test_full_engine_events.py), [Iteration variable ownership](tests/engine/test_iteration_variable_scopes.py) | | Pause, resume, and snapshot quiescence | [Dispatcher](src/graphon/engine/dispatcher.py), [execution guard](src/graphon/runtime/execution.py) | [Serialization](tests/engine/test_runtime_state_serialization.py) | @@ -266,7 +303,7 @@ snapshot guard tracks engine activity, so it cannot protect arbitrary host write | Change | Start here | Existing check | | --- | --- | --- | -| Add a node | [Node base class](src/graphon/nodes/base/node.py), [NodeFactory](src/graphon/graph/graph.py); import the subclass to register its type/version | [Node execution binding](tests/nodes/base/test_node_execution_binding.py), [factory tests](tests/dsl/test_node_factory.py) | +| Add a node | Import the subclass to register its type/version. See the [node base class](src/graphon/nodes/base/node.py) and [NodeFactory](src/graphon/nodes/factory.py) | [Node execution binding](tests/nodes/base/test_node_execution_binding.py), [factory tests](tests/dsl/test_node_factory.py) | | Add lifecycle observation or limits | [Layer API and usage](src/graphon/engine/layer/README.md); runtime access is read-only, controls use commands | [Layer context tests](tests/engine/test_layer_node_run_context.py) | | Pause, abort, or update variables externally | [Command API and channels](src/graphon/engine/command/README.md) | [Dispatch tests](tests/engine/test_dispatch_patterns.py) | | Adapt the consumer event stream | [Filter protocol](src/graphon/engine/filter/protocol.py) | [Filter tests](tests/engine/test_event_filters.py) | diff --git a/README.md b/README.md index c9ff2665..6169eb62 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Graphon @@ -12,7 +12,7 @@ protocols, and a runnable end-to-end example. ## Highlights - Queue-based `Engine` orchestration with event-driven execution -- Graph parsing, validation, and fluent graph building +- Graph definitions from YAML or Python, with node and edge validation - Frame-owned runtime state and variables with shared workflow execution state - Built-in node implementations for common workflow patterns - DSL import support with Slim-backed LLM nodes diff --git a/docs/README.md b/docs/README.md index b1050761..5f5208bb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,17 +1,18 @@ # Repository knowledge -Start with the question you need to answer, then follow the links to code and -tests. These documents describe this checkout; they do not substitute for the -implementation or establish new public contracts. +Start with the question you need to answer. The domain model describes the +intended design. Follow the links to code and tests for current behavior and +public contracts. ## Map | Question | Start here | | --- | --- | | What is Graphon and how do I run it? | [Project README](../README.md), [Slim example](../examples/slim_llm/README.md) | +| What do the five subdomains own, and where do the DSL and engine share a model? | [Graph domain model](domain-model.md) | | Where does execution happen, and who owns state? | [Architecture](../ARCHITECTURE.md) | | How should runtime dependencies and mutable state be owned? | [Explicit state ownership](../CONTRIBUTING.md#explicit-state-ownership) | | Which files and tests should I change? | [Development guide](development.md) | diff --git a/docs/development.md b/docs/development.md index 81244202..8dc31c6a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,5 @@ # Development navigation @@ -23,8 +23,10 @@ when changing runtime types, state transfers, or presentation values. | --- | --- | --- | | Update runtime, development, build, or CI dependencies | [Package metadata](../pyproject.toml), [lockfile](../uv.lock), [CI workflows](../.github/workflows/) | [Repository validation](../CONTRIBUTING.md#testing-and-validation), [package build](../justfile), [extractor tests](../tests/nodes/document_extractor/) | | Change import boundaries or queue ownership | [Import boundaries](../ARCHITECTURE.md#import-boundaries), [runtime queues](../src/graphon/runtime/ready_queue/) | `just imports`, [runtime isolation](../tests/runtime/test_runtime_imports.py), [public contract imports](../tests/test_protocols_exports.py) | -| Parse or validate a graph | [graph](../src/graphon/graph/), [graph config](../src/graphon/entities/graph_config.py) | [graph tests](../tests/graph/), especially validation and scoping | -| Import Dify DSL or wire node dependencies | [importer](../src/graphon/dsl/importer.py), [node factory](../src/graphon/dsl/node_factory.py) | [DSL tests](../tests/dsl/), especially importer, node factory, and app bootstrap | +| Define or validate a Graph | [Graph](../src/graphon/graph/graph.py), [validation](../src/graphon/graph/validation.py) | [Graph definitions](../tests/graph/test_graph_definition.py) | +| Build a Graph in Python | [GraphBuilder](../src/graphon/graph_builder/builder.py), [Python example](../examples/slim_llm/code.py) | [Builder tests](../tests/graph_builder/test_graph_builder.py) | +| Build a `FrameGraph` for execution | [Bind a Graph definition to a frame](../src/graphon/engine/frame_graph_factory.py), [build a frame from configuration or node instances](../src/graphon/engine/frame_graph.py) | [Inactive entry branches](../tests/engine/test_frame_graph.py), [frame scoping](../tests/engine/test_frame_graph_scoping.py), [frame validation](../tests/engine/test_frame_graph_validation.py) | +| Import Dify DSL or wire node dependencies | [Importer](../src/graphon/dsl/importer.py), [flat DSL to Graph](../src/graphon/dsl/graph.py), [node factory](../src/graphon/dsl/node_factory.py) | [DSL tests](../tests/dsl/), especially importer, node factory, and app bootstrap | | Change a built-in node | [nodes](../src/graphon/nodes/), [base node](../src/graphon/nodes/base/node.py) | Matching [node tests](../tests/nodes/); [workflow events](../tests/workflows/test_full_engine_events.py) for graph-visible changes | | Change dispatch, scheduling, or containers | [engine](../src/graphon/engine/), [container effects](../src/graphon/nodes/container_effects.py) | [engine tests](../tests/engine/), [container values](../tests/nodes/test_container_effects.py), [container dispatch](../tests/nodes/test_container_dispatch.py), [workflow events](../tests/workflows/test_full_engine_events.py) | | Change event payloads or response streaming | [raw frame observations](../ARCHITECTURE.md#raw-frame-observations), [response sessions](../ARCHITECTURE.md#response-sessions), [node events](../src/graphon/node_events/), [engine events](../src/graphon/engine_events/), [filters](../src/graphon/engine/filter/) | [frame observation tests](../tests/engine/test_frame_observations.py), [frame failure tests](../tests/engine/test_frame_failures.py), [node event tests](../tests/node_events/), [engine event tests](../tests/engine_events/), [response filter tests](../tests/engine/test_response_stream_filter.py), [response traversal regressions](../tests/engine/test_response_stream_filter_performance.py), [gating regressions](#response-gating-regressions), [container response tests](../tests/engine/test_container_response_streaming.py), [reply ordering tests](../tests/engine/test_response_reply_ordering.py) | @@ -47,6 +49,8 @@ when changing runtime types, state transfers, or presentation values. when extending import support. 4. For a custom host factory, use the [factory validation and isolation contract](../ARCHITECTURE.md#state-and-execution-invariants). + When the engine builds a frame, `with_runtime_state()` receives its + read-only state view. Pass that view to the nodes the factory creates. Bind scoped configuration before construction because `post_init()` runs in the constructor. 5. Complete [validation](#validate-the-behavior-you-changed). @@ -58,10 +62,10 @@ and the node's constructor instead of importing host infrastructure into the engine. [Protocol export tests](../tests/test_protocols_exports.py) protect that public surface. -- **Models:** inject a prepared `LLMProtocol` as `LLMNode.model_instance`. - [SlimLLM](../src/graphon/dsl/slim/llm.py) is the provided graph-facing adapter; - [code.py](../examples/slim_llm/code.py) shows direct wiring. Provider discovery - and capability wrappers have separate protocols; see the +- **Model adapters** implement `LLMProtocol`. Pass the adapter to `LLMNode` as + `model_instance`, as the [DSL factory](../src/graphon/dsl/node_factory.py) does + with [SlimLLM](../src/graphon/dsl/slim/llm.py). For provider discovery and + capability wrappers, see the [model runtime guide](../src/graphon/model_runtime/README.md). For polling, subclass [`graphon.protocols.LLMPollingCapableProtocol`](../src/graphon/nodes/llm/runtime_protocols.py). A successful polling run emits the completed text in its final text chunk. diff --git a/docs/domain-model.md b/docs/domain-model.md new file mode 100644 index 00000000..1dd48d91 --- /dev/null +++ b/docs/domain-model.md @@ -0,0 +1,72 @@ + +# Graph domain model + +Graphon's design has five **subdomains**, each with a different job. Graph DSL +and Graph Engine share the **Graph bounded context**. Within it, a node means +a step, its type says what it does, and an edge is a possible path between +steps. Both use the same Graph definition and rules for calling it. + +```mermaid +flowchart TB + subgraph graphContext["Graph bounded context"] + dsl["Graph DSL
Write and check a Graph"] -->|Graph definition| engine["Graph Engine
Execute a Graph"] + runningNode(["Node"]) -->|"yields events, including write requests"| engine + end + runningNode -->|reads frame variables| variable["Variable
Typed values visible
to each node"] + engine -->|writes to VariablePool| variable + modelRuntime["Model Runtime
Send requests to providers
and read their replies"] -->|model replies| runningNode + engine -->|publishes events to callers| response["Response
Choose, order, and stream
replies to users"] +``` + +Every node reports what happens as it runs by yielding events to the Graph +Engine. The engine defines those events and uses them to update execution state, +decide whether to retry a failed node, and schedule nodes as they become ready. +Response interprets the events the engine exposes to callers and assembles the +reply users see. See [Execution flow](../ARCHITECTURE.md#execution-flow) and +[Response sessions](../ARCHITECTURE.md#response-sessions). + +Nodes in a frame share a read-only view of its variable pool. Each read returns +a copy of the current value. A node yields `VariableUpdatedEvent` to write a +variable or supplies named outputs in its result. The engine copies these +values when it receives them and commits the writes in dispatch order. +See the [frame observation tests](../tests/engine/test_frame_observations.py). + +## Definition and execution + +A `Graph` is an immutable **value object**, whether read from YAML or built in +Python. It defines where execution can start, each node's type, version and +settings, and the Graph a node can call. +Edges connect nodes within the same Graph. Two definitions are equal when this +content matches, including node and edge IDs and the order of each node's +outgoing edges. + +The Graph Engine creates a `FrameGraph` for the root and another each time a +container calls its body. Each holds the selected entry, executable nodes and +the traversal state of each edge. + +`GraphExecution` is the **aggregate root** for one run. It controls when the +run can start, pause or finish. Two runs of the same Graph can choose different +entries. Each keeps its own variables, branch decisions, active calls, loop +progress and outputs. An Iteration body can read its current item as a Variable. + +## Calling a Graph + +A `Container` calls a Graph with inputs and returns its outputs, like a +function. The calling node determines how often the body runs. + +```mermaid +flowchart LR + callOnce["Call once"] --> container["Container"] + iteration["Iteration
Once per item"] --> container + loopNode["Loop
Once per round"] --> container + container --> embeddedBody["Embedded body
The caller includes the Graph"] + container --> referencedBody["Referenced body
The host looks up the Graph"] +``` + +Iteration and Loop accept either form. An Iteration over a list of names can +call the same greeting Graph once per name, whether the caller embeds the body +or references it by ID and optional version. Node and edge IDs are local to +each Graph, so two bodies can use the same IDs. +[Graph definition and execution tests](../tests/graph/test_graph_definition.py) diff --git a/docs/maintenance.md b/docs/maintenance.md index d56539fd..3f776497 100644 --- a/docs/maintenance.md +++ b/docs/maintenance.md @@ -1,5 +1,5 @@ # Maintaining repository knowledge @@ -78,6 +78,11 @@ normal change's [knowledge review](#review-for-drift): | A complex task's progress and unresolved decisions | A linked plan under `docs/plans/`, created when needed | | Completed plans retained as history | [Archived plans](archive/plans/), excluded from routine knowledge checks | +Write knowledge pages for someone using the current version. When existing +users need to change their code, configuration, or data to upgrade, draft the +migration steps in a temporary local file outside repository knowledge. Include +those steps in the pull request description when you open the PR. + ## Validation The [documentation check](../tests/test_repository_docs.py) is the source of truth diff --git a/docs/technical-debt.md b/docs/technical-debt.md index 92230fc5..5a490f14 100644 --- a/docs/technical-debt.md +++ b/docs/technical-debt.md @@ -1,5 +1,5 @@ # Technical debt @@ -17,6 +17,7 @@ item is resolved. | TD-08 | [Offline execution example](#td-08--offline-execution-example) | P2 | Examples | | TD-09 | [Performance feedback](#td-09--performance-feedback) | P2 | Filters/performance | | TD-10 | [Decision records](#td-10--decision-records) | P3 | Maintainers/docs | +| TD-11 | [Legacy Start input form](#td-11--legacy-start-input-form) | P2 | Start node and host | P2 denotes targeted API, architecture, or developer-feedback work; P3 can follow more consequential changes. Priorities are suggestions, not delivery commitments. @@ -104,3 +105,15 @@ Promote approved lasting rules to stable guides and executable checks. **Completion:** accepted decisions have repository-local links and explicit status, and the knowledge index and maintenance guidance agree with merged policy. + +## TD-11 — Legacy Start input form + +Saved Start configurations still use the deprecated `VariableEntity`. Its +schema is frozen so those graphs continue to load. New controls such as +multi-select belong in the host, along with their validation. See the +[form model](../src/graphon/variables/input_entities.py), +[schema compatibility test](../tests/variables/test_input_entities.py), and +[multi-select proposal](https://github.com/langgenius/graphon/pull/259). + +Close this item when the host owns the form and saved Start nodes still run +with their existing inputs. diff --git a/examples/slim_llm/README.md b/examples/slim_llm/README.md index 4c2020ba..5ad35600 100644 --- a/examples/slim_llm/README.md +++ b/examples/slim_llm/README.md @@ -1,9 +1,9 @@ # Slim LLM Example -This directory has two versions of the same LLM workflow: +The YAML and Python examples run the same three steps. ```text start -> llm -> answer @@ -11,9 +11,11 @@ start -> llm -> answer ## Source and setup -[graph.yml](graph.yml) defines the workflow; [dsl.py](dsl.py) imports it and -[code.py](code.py) constructs it directly. [settings.py](settings.py) handles -example configuration; the [Slim client](../../src/graphon/dsl/slim/client.py) +The YAML example passes its document to `loads()`. The Python example connects +the nodes with `GraphBuilder` and passes the result of `build()` to `load_graph()`. +See [graph.yml](graph.yml), [dsl.py](dsl.py), and [code.py](code.py). + +[settings.py](settings.py) handles example configuration. The [Slim client](../../src/graphon/dsl/slim/client.py) defines daemon configuration and binary lookup. Use [credentials.example.json](credentials.example.json) as the credential schema. Complete [repository setup](../../CONTRIBUTING.md#development-setup) first. @@ -49,5 +51,5 @@ uv run python code.py uv run python code.py "Reply with only the word Graphon." ``` -Running either workflow invokes a real model. Use `--help` to check command +Both examples invoke a real model. Use `--help` to check command usage without credentials or a Slim executable. diff --git a/examples/slim_llm/code.py b/examples/slim_llm/code.py index 08944d63..44e00c46 100644 --- a/examples/slim_llm/code.py +++ b/examples/slim_llm/code.py @@ -2,8 +2,6 @@ import argparse import sys -import time -from collections.abc import Sequence from pathlib import Path if __package__ in {None, ""}: @@ -15,152 +13,60 @@ OPENAI_PLUGIN_ID, OPENAI_PROVIDER, load_credentials, - openai_credentials, - slim_client_config, use_local_slim_binary, ) -from graphon.dsl.slim import SlimLLM -from graphon.engine import Engine -from graphon.file.enums import FileType -from graphon.file.models import File -from graphon.graph.graph import Graph -from graphon.model_runtime.entities.llm_entities import LLMMode -from graphon.model_runtime.entities.message_entities import ( - PromptMessage, - PromptMessageRole, -) -from graphon.nodes.answer.answer_node import AnswerNode -from graphon.nodes.answer.entities import AnswerNodeData -from graphon.nodes.llm import ( - LLMNode, - LLMNodeChatModelMessage, - LLMNodeData, - ModelConfig, -) -from graphon.nodes.llm.entities import ContextConfig -from graphon.nodes.start import StartNode -from graphon.nodes.start.entities import StartNodeData -from graphon.runtime.init_params import InitParams -from graphon.runtime.runtime_state import RuntimeState -from graphon.runtime.variable_pool import VariablePool - - -class PromptSerializer: - def serialize( - self, - *, - model_mode: LLMMode, - prompt_messages: Sequence[PromptMessage], - ) -> object: - _ = model_mode - return list(prompt_messages) - - -class TextOnlyFileSaver: - def save_binary_string( - self, - data: bytes, - mime_type: str, - file_type: FileType, - extension_override: str | None = None, - ) -> File: - _ = data, mime_type, file_type, extension_override - msg = "This example only supports text responses." - raise RuntimeError(msg) - - def save_remote_url(self, url: str, file_type: FileType) -> File: - _ = url, file_type - msg = "This example only supports text responses." - raise RuntimeError(msg) +from graphon.dsl import DslDependency, PluginDependencyType, load_graph +from graphon.graph import Graph +from graphon.graph_builder import GraphBuilder + + +def build_graph() -> Graph: + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + llm_id = builder.add_node( + "llm", + "llm", + config={ + "title": "LLM", + "model": { + "provider": OPENAI_PROVIDER, + "name": OPENAI_MODEL, + "mode": "chat", + }, + "prompt_template": [{"role": "user", "text": "{{#start.query#}}"}], + "context": {"enabled": False}, + }, + ) + answer_id = builder.add_node( + "answer", "answer", config={"answer": "{{#llm.text#}}"} + ) + builder.connect(start_id, llm_id) + builder.connect(llm_id, answer_id) + return builder.build() def run(query: str) -> str: use_local_slim_binary() - credentials = load_credentials() - workflow_id = "slim-llm-code-example" - runtime_state = RuntimeState( - workflow_id=workflow_id, - variable_pool=VariablePool(), - start_at=time.time(), - ) - runtime_state.variable_pool.add(("start", "query"), query) - init_params = InitParams( - workflow_id=workflow_id, - graph_config={"nodes": [], "edges": []}, - run_context={}, - call_depth=0, + engine = load_graph( + build_graph(), + graph_id="slim-llm-code-example", + start_inputs={"query": query}, + credentials=load_credentials(), + dependencies=[ + DslDependency( + type=PluginDependencyType.MARKETPLACE, + plugin_unique_identifier=OPENAI_PLUGIN_ID, + ) + ], ) - - graph = build_graph( - init_params=init_params, - runtime_state=runtime_state, - llm=SlimLLM( - config=slim_client_config(credentials), - plugin_id=OPENAI_PLUGIN_ID, - provider=OPENAI_PROVIDER, - model_name=OPENAI_MODEL, - credentials=openai_credentials(credentials), - parameters={}, - ), - ) - engine = Engine( - graph=graph, - runtime_state=runtime_state, - ) - list(engine.run()) - answer = runtime_state.get_output("answer") + answer = engine.runtime_state.get_output("answer") if not isinstance(answer, str): - msg = "Workflow finished without a string answer." + msg = "Graph finished without a string answer." raise TypeError(msg) return answer -def build_graph( - *, - init_params: InitParams, - runtime_state: RuntimeState, - llm: SlimLLM, -) -> Graph: - start = StartNode( - node_id="start", - data=StartNodeData(title="Start"), - init_params=init_params, - runtime_state=runtime_state, - ) - llm_node = LLMNode( - node_id="llm", - data=LLMNodeData( - title="LLM", - model=ModelConfig( - provider=OPENAI_PROVIDER, - name=OPENAI_MODEL, - mode=LLMMode.CHAT, - ), - prompt_template=[ - LLMNodeChatModelMessage( - role=PromptMessageRole.USER, - text="{{#start.query#}}", - ), - ], - context=ContextConfig(enabled=False), - ), - init_params=init_params, - runtime_state=runtime_state, - model_instance=llm, - llm_file_saver=TextOnlyFileSaver(), - prompt_message_serializer=PromptSerializer(), - ) - answer = AnswerNode( - node_id="answer", - data=AnswerNodeData(title="Answer", answer="{{#llm.text#}}"), - init_params=init_params, - runtime_state=runtime_state, - ) - - return Graph.new().add_root(start).add_node(llm_node).add_node(answer).build() - - def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("query", nargs="?", default=DEFAULT_QUERY) diff --git a/pyproject.toml b/pyproject.toml index 31fef2c1..4e676076 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,7 +108,7 @@ type = 'layers' containers = ['graphon'] exhaustive = true layers = [ - 'dsl', + 'dsl | graph_builder', 'engine', 'protocols : errors', 'graph : nodes : runtime : utils : variable_loader', diff --git a/src/graphon/dsl/__init__.py b/src/graphon/dsl/__init__.py index 2e50a161..769f3bde 100644 --- a/src/graphon/dsl/__init__.py +++ b/src/graphon/dsl/__init__.py @@ -11,7 +11,7 @@ PluginDependencyType, ) from .errors import DslError -from .importer import inspect, loads +from .importer import inspect, load_graph, loads from .node_factory import SlimDslNodeFactory from .slim import SlimClient, SlimClientError @@ -32,5 +32,6 @@ "SlimClientError", "SlimDslNodeFactory", "inspect", + "load_graph", "loads", ] diff --git a/src/graphon/dsl/entities.py b/src/graphon/dsl/entities.py index 5aa98bde..8c449170 100644 --- a/src/graphon/dsl/entities.py +++ b/src/graphon/dsl/entities.py @@ -6,6 +6,10 @@ from pydantic import BaseModel, ConfigDict, Field +from graphon.graph import Graph + +from .graph import read_graph + class DslKind(StrEnum): APP = auto() @@ -47,6 +51,14 @@ class DslDocument(BaseModel): graph_config: Mapping[str, Any] | None = None runtime_variables: DslRuntimeVariables = Field(default_factory=DslRuntimeVariables) + @property + def graph(self) -> Graph | None: + """Build an immutable snapshot of the document's current graph configuration.""" + if self.graph_config is None: + return None + graph, _ = read_graph(self.graph_config) + return graph + class DslDependency(BaseModel): model_config = ConfigDict(extra="forbid") diff --git a/src/graphon/dsl/graph.py b/src/graphon/dsl/graph.py new file mode 100644 index 00000000..b53613dd --- /dev/null +++ b/src/graphon/dsl/graph.py @@ -0,0 +1,120 @@ +"""Read scoped node definitions from the flat layout used by existing DSL files.""" + +from collections import defaultdict +from collections.abc import Mapping +from typing import Any + +from graphon.enums import BuiltinNodeTypes +from graphon.graph import EdgeDefinition, Graph, GraphReference, NodeDefinition +from graphon.graph.config import normalize_nodes, prepare_edge_configs +from graphon.graph.validation import GraphValidationError, GraphValidationIssue + +# The canvas stores these beside the executable settings in older documents. +_NODE_METADATA = frozenset(( + "type", + "version", + "container_id", + "iteration_id", + "loop_id", + "isInIteration", + "isInLoop", + "selected", + "width", + "height", + "position", + "_connectedSourceHandleIds", + "_connectedTargetHandleIds", + "_targetBranches", + "_children", + "_runningStatus", + "_runningBranchId", + "_singleRunningStatus", + "_iterationIndex", + "_iterationLength", + "_loopIndex", + "_loopLength", + "_waitingRun", + "_retryIndex", +)) + + +def resolve_node_version(data: Mapping[str, Any]) -> str: + # Older Variable Assigner exports select v2 by their items field. + if data.get("type") == BuiltinNodeTypes.VARIABLE_ASSIGNER and "items" in data: + return "2" + return data.get("version", "1") + + +def _read_edges( + config: Mapping[str, Any], + container_ids: Mapping[str, str], +) -> tuple[dict[str, list[EdgeDefinition]], dict[str, str]]: + edges_by_container: defaultdict[str, list[EdgeDefinition]] = defaultdict(list) + legacy_edge_ids: dict[str, str] = {} + for ordinal, edge in enumerate(prepare_edge_configs(config, container_ids)): + source, target = edge["source"], edge["target"] + if source not in container_ids or target not in container_ids: + raise GraphValidationError([ + GraphValidationIssue( + "MISSING_NODE", f"Unknown endpoint in edge {edge['id']!r}." + ) + ]) + if container_ids[source] != container_ids[target]: + msg = f"Edge '{source}->{target}' crosses container scopes" + raise ValueError(msg) + if not container_ids[source]: + legacy_edge_ids[f"edge_{ordinal}"] = edge["id"] + edges_by_container[container_ids[source]].append( + EdgeDefinition( + edge["id"], source, target, edge.get("sourceHandle", "source") + ) + ) + return dict(edges_by_container), legacy_edge_ids + + +def read_graph(config: Mapping[str, Any]) -> tuple[Graph, dict[str, str]]: + """Read a definition and the root edge ordinals used by v1 response snapshots.""" + nodes, container_ids = normalize_nodes(config.get("nodes", [])) + nodes_by_container: defaultdict[str, list[dict[str, Any]]] = defaultdict(list) + for node in nodes: + nodes_by_container[container_ids[node["id"]]].append(node) + edges_by_container, legacy_edge_ids = _read_edges(config, container_ids) + visited_node_ids: set[str] = set() + + def read_container_graph(container_id: str) -> Graph: + node_definitions: list[NodeDefinition] = [] + for node in nodes_by_container[container_id]: + node_id = node["id"] + visited_node_ids.add(node_id) + data = node["data"] + target: Graph | GraphReference | None = None + if node_id in nodes_by_container: + target = read_container_graph(node_id) + elif ( + data["type"] == BuiltinNodeTypes.TOOL + and data.get("provider_type") == "workflow" + and data.get("provider_id") + ): + target = GraphReference(data["provider_id"]) + node_definitions.append( + NodeDefinition( + node_id, + data["type"], + version=resolve_node_version(data), + config={ + key: value + for key, value in data.items() + if key not in _NODE_METADATA + }, + call_target=target, + ) + ) + return Graph( + nodes=node_definitions, edges=edges_by_container.get(container_id, ()) + ) + + graph = read_container_graph("") + if missing := container_ids.keys() - visited_node_ids: + msg = f"Nodes reference unknown or cyclic containers: {sorted(missing)}" + raise ValueError(msg) + return graph, legacy_edge_ids diff --git a/src/graphon/dsl/importer.py b/src/graphon/dsl/importer.py index e13be1cc..baafc6ad 100644 --- a/src/graphon/dsl/importer.py +++ b/src/graphon/dsl/importer.py @@ -14,8 +14,9 @@ from graphon.engine import Engine from graphon.engine.command import CommandChannel from graphon.engine.container_handler import ContainerHandlerFactory +from graphon.engine.frame_graph_factory import GraphResolver from graphon.enums import BuiltinNodeTypes -from graphon.graph.graph import Graph +from graphon.graph import Graph from graphon.graph.scoping import resolve_container_id from graphon.graph.validation import GraphValidationError from graphon.runtime.init_params import InitParams @@ -34,6 +35,7 @@ PluginDependencyType, ) from .errors import DslError +from .graph import read_graph from .node_factory import SUPPORTED_DEFAULT_FACTORY_NODE_TYPES, SlimDslNodeFactory @@ -97,6 +99,7 @@ def loads( command_channel: CommandChannel | None = None, workers: int = 5, container_handler_factories: Sequence[ContainerHandlerFactory] = (), + graph_resolver: GraphResolver | None = None, ) -> Engine: plan = inspect(dsl, source_kind=source_kind) if plan.load_status == LoadStatus.UNSUPPORTED: @@ -112,49 +115,26 @@ def loads( kind=plan.document.kind, ) - graph_config = plan.document.graph_config - if graph_config is None: + if plan.document.graph_config is None: msg = "DSL does not contain an executable graph." - raise _dsl_error( - msg, - code="graph.missing", - kind=plan.document.kind, - ) - - root_id = root_node_id or _select_root_node_id(graph_config) - workflow_id = workflow_id if workflow_id is not None else str(uuid4()) - variable_pool = _build_variable_pool( - runtime_variables=plan.document.runtime_variables, - root_node_id=root_id, - run_context=run_context or {}, - start_inputs=start_inputs or {}, - ) - init_params = InitParams( - workflow_id=workflow_id, - graph_config=graph_config, - run_context=run_context or {}, - call_depth=0, - ) - runtime_state = RuntimeState( - variable_pool=variable_pool, - start_at=time.time(), - workflow_id=workflow_id, - ) - parsed_credentials = _parse_credentials(credentials) - node_factory = SlimDslNodeFactory( - graph_config=graph_config, - init_params=init_params, - runtime_state=runtime_state, - credentials=parsed_credentials, - dependencies=list(plan.dependencies), - ) - + raise _dsl_error(msg, code="graph.missing", kind=plan.document.kind) try: - graph = Graph.init( - graph_config=graph_config, - node_factory=node_factory, - root_node_id=root_id, + graph, legacy_edge_ids = read_graph(plan.document.graph_config) + engine = load_graph( + graph, + credentials=credentials, + graph_id=workflow_id, + root_node_id=root_node_id, + run_context=run_context, + start_inputs=start_inputs, + runtime_variables=plan.document.runtime_variables, + dependencies=plan.dependencies, + command_channel=command_channel, + workers=workers, + container_handler_factories=container_handler_factories, + graph_resolver=graph_resolver, ) + engine.graph.legacy_edge_ids = legacy_edge_ids except DslError: raise except GraphValidationError as error: @@ -170,10 +150,65 @@ def loads( code="graph.build_failed", kind=plan.document.kind, ) from error + return engine + +def load_graph( + graph: Graph, + *, + credentials: dict[str, Any] | str | None = None, + graph_id: str | None = None, + root_node_id: str | None = None, + run_context: Mapping[str, Any] | None = None, + start_inputs: Mapping[str, Any] | None = None, + runtime_variables: DslRuntimeVariables | None = None, + dependencies: Sequence[DslDependency] = (), + command_channel: CommandChannel | None = None, + workers: int = 5, + container_handler_factories: Sequence[ContainerHandlerFactory] = (), + graph_resolver: GraphResolver | None = None, +) -> Engine: + """Create a new execution of a shared graph with the built-in node factory.""" + if root_node_id is None: + candidates = [ + node_id for node_id in graph.nodes if node_id in graph.entry_node_ids + ] + if len(candidates) != 1: + msg = "DSL graph must contain exactly one entry unless root_node_id is set." + raise _dsl_error( + msg, + code="graph.root_ambiguous", + details={"root_node_candidates": candidates}, + ) + root_node_id = candidates[0] + graph_id = graph_id if graph_id is not None else str(uuid4()) + variable_pool = _build_variable_pool( + runtime_variables=runtime_variables or DslRuntimeVariables(), + root_node_id=root_node_id, + run_context=run_context or {}, + start_inputs=start_inputs or {}, + ) + state = RuntimeState( + variable_pool=variable_pool, start_at=time.time(), workflow_id=graph_id + ) + node_factory = SlimDslNodeFactory( + graph_config={}, + init_params=InitParams( + workflow_id=graph_id, + graph_config={}, + run_context=run_context or {}, + call_depth=0, + ), + runtime_state=state, + credentials=_parse_credentials(credentials), + dependencies=list(dependencies), + ) return Engine( graph=graph, - runtime_state=runtime_state, + runtime_state=state, + root_node_id=root_node_id, + node_factory=node_factory, + graph_resolver=graph_resolver, command_channel=command_channel, workers=workers, container_handler_factories=container_handler_factories, @@ -812,30 +847,6 @@ def _dependency_from_mapping( ) -def _root_node_candidates(graph_config: Mapping[str, Any]) -> list[str]: - return [ - str(node["id"]) - for node in graph_config.get("nodes", []) - if isinstance(node, Mapping) - and isinstance(node.get("data"), Mapping) - and node["data"].get("type") == BuiltinNodeTypes.START - ] - - -def _select_root_node_id(graph_config: Mapping[str, Any]) -> str: - candidates = _root_node_candidates(graph_config) - if len(candidates) != 1: - msg = ( - "DSL graph must contain exactly one start node unless root_node_id is set." - ) - raise _dsl_error( - msg, - code="graph.root_ambiguous", - details={"root_node_candidates": candidates}, - ) - return candidates[0] - - def _build_variable_pool( *, runtime_variables: DslRuntimeVariables, diff --git a/src/graphon/dsl/node_factory.py b/src/graphon/dsl/node_factory.py index 5e138b64..b4b15e23 100644 --- a/src/graphon/dsl/node_factory.py +++ b/src/graphon/dsl/node_factory.py @@ -67,6 +67,7 @@ VariableAssignerNode as VariableAssignerNodeV2, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.template_rendering import Jinja2TemplateRenderer, TemplateRenderError @@ -79,6 +80,7 @@ DslToolCredential, ) from .errors import DslError +from .graph import resolve_node_version from .slim import SlimClientConfig, SlimLLM from .tool_runtime import SlimToolNodeRuntime, resolve_dsl_tool_credential @@ -420,12 +422,13 @@ class _NodeBuildRequest: class SlimDslNodeFactory: graph_config: Mapping[str, Any] init_params: InitParams - runtime_state: RuntimeState + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper credentials: DslCredentials dependencies: list[DslDependency] slim_client_config: SlimClientConfig = field(init=False) def __post_init__(self) -> None: + self.runtime_state = self.runtime_state.read_only_view slim = self.credentials.slim self.slim_client_config = SlimClientConfig( folder=_resolve_plugin_folder(self.credentials), @@ -444,7 +447,7 @@ def __post_init__(self) -> None: def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, ) -> SlimDslNodeFactory: """Return a copied factory bound to one execution frame's state. @@ -769,8 +772,7 @@ def _validate_variable_assigner_data( """ data = request.data_payload - version = str(data.get("version") or "") - if "items" in data or version == VariableAssignerNodeV2.version(): + if resolve_node_version(data) == VariableAssignerNodeV2.version(): return VariableAssignerNodeData.model_validate(data) if { "assigned_variable_selector", diff --git a/src/graphon/dsl/tool_runtime.py b/src/graphon/dsl/tool_runtime.py index b03bf60c..988c907b 100644 --- a/src/graphon/dsl/tool_runtime.py +++ b/src/graphon/dsl/tool_runtime.py @@ -16,7 +16,7 @@ ToolRuntimeMessage, ToolRuntimeParameter, ) -from graphon.runtime.variable_pool import VariablePool +from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool from graphon.variables.template_resolution import convert_template from .entities import DslToolCredential @@ -187,7 +187,7 @@ def _require_client(self) -> SlimClient: @dataclass(slots=True) class _SlimToolParameterResolver: - variable_pool: VariablePool | None + variable_pool: ReadOnlyVariablePool | None def resolve_form_values( self, @@ -300,7 +300,7 @@ def get_runtime( *, node_id: str, node_data: ToolNodeData, - variable_pool: VariablePool | None, + variable_pool: ReadOnlyVariablePool | None, node_execution_id: str | None = None, ) -> ToolRuntimeHandle: _ = node_id, node_execution_id diff --git a/src/graphon/engine/__init__.py b/src/graphon/engine/__init__.py index 17243b35..9f919045 100644 --- a/src/graphon/engine/__init__.py +++ b/src/graphon/engine/__init__.py @@ -1,3 +1,4 @@ from .engine import Engine +from .frame_graph import Edge, FrameGraph -__all__ = ["Engine"] +__all__ = ["Edge", "Engine", "FrameGraph"] diff --git a/src/graphon/engine/command/README.md b/src/graphon/engine/command/README.md index 04eb68e1..3e866d05 100644 --- a/src/graphon/engine/command/README.md +++ b/src/graphon/engine/command/README.md @@ -1,39 +1,49 @@ # Commands -Command processing and channels for external workflow control. +Use commands to pause or abort a graph execution or update its variables. Use the [command definitions](entities.py) for payloads and deserialization literals, [CommandProcessor](processor.py) for dispatch, and the channel implementations for [in-memory](builtin/in_memory.py) or [Redis](builtin/redis.py) delivery. The [dispatch tests](../../../../tests/engine/test_dispatch_patterns.py) cover -workflow control behavior. With frame observations enabled, successful variable +command handling. With frame observations enabled, successful variable writes produce [frame commit observations](../../../../ARCHITECTURE.md#raw-frame-observations), including writes completed before a later command update fails. ## Usage -Pass the channel to [Engine](../engine.py) through `command_channel`; each -channel belongs to one workflow execution. For Redis, use a unique `channel_key` -for each execution. Watch for +Pass one `command_channel` per execution to [Engine](../engine.py). For a shared +`Graph` definition, pass the host's `node_factory` and select `root_node_id` if +the graph has multiple entries. For Redis, use a unique `channel_key` for each +execution. Consume `engine.run()` and watch for [`GraphRunPausedEvent` or `GraphRunAbortedEvent`](../../engine_events/graph.py) to see when a queued pause or abort takes effect. ```python from graphon.engine import Engine from graphon.engine.command import AbortCommand, InMemoryChannel, RedisChannel +from graphon.engine_events import GraphRunAbortedEvent # Local execution channel = InMemoryChannel() -engine = Engine(graph=graph, runtime_state=runtime_state, command_channel=channel) +engine = Engine( + graph=graph, + runtime_state=runtime_state, + node_factory=node_factory, + command_channel=channel, +) channel.send_command(AbortCommand(reason="stop")) +for event in engine.run(): + if isinstance(event, GraphRunAbortedEvent): + print(event.reason) # Distributed execution redis_channel = RedisChannel( - redis_client=redis_client, channel_key="workflow:123:commands" + redis_client=redis_client, channel_key=f"graph:{execution_id}:commands" ) ``` diff --git a/src/graphon/engine/container_handler/builtin/loop.py b/src/graphon/engine/container_handler/builtin/loop.py index 3a565d43..edec96c7 100644 --- a/src/graphon/engine/container_handler/builtin/loop.py +++ b/src/graphon/engine/container_handler/builtin/loop.py @@ -6,6 +6,7 @@ from datetime import UTC, datetime from typing import final +from graphon.engine.frame_graph import FrameGraph from graphon.engine_events.base import NodeEvent from graphon.engine_events.node import ( NodeRunFailedEvent, @@ -107,6 +108,26 @@ def handle_request( msg = f"loop handler cannot continue {run_state.kind} run" raise TypeError(msg) parent_frame = self._frame_registry[run_state.frame_id] + graph = parent_frame.graph + if ( + isinstance(graph, FrameGraph) + and graph.definition is not None + and graph.frame_graph_factory is not None + ): + body = graph.frame_graph_factory.resolve_call_target( + graph.definition.node(run_state.node_id) + ) + loop_node_ids = frozenset( + node_id + for scope, _ in graph.frame_graph_factory.walk_graphs( + body, stop_at_node_type=BuiltinNodeTypes.LOOP + ) + for node_id in scope.nodes + ) + request = request.model_copy(update={"loop_node_ids": loop_node_ids}) + run_state = run_state.model_copy(update={"loop_node_ids": loop_node_ids}) + self._root_runtime_state().put_container_run(run_state) + node = parent_frame.graph.nodes[run_state.node_id] if not isinstance(node, LoopNode): msg = f"node {run_state.node_id} cannot handle loop await requests" @@ -343,7 +364,7 @@ def _start_loop_frame( deep=True, ) for node_id in request.loop_node_ids: - variable_pool.remove([node_id]) + variable_pool.clear_scope(node_id) # The parent pool is authoritative: loop assignments are written back as # events, and external commands may update it between completed rounds. # ``run_state.outputs`` is only a reporting snapshot of the prior round. diff --git a/src/graphon/engine/engine.py b/src/graphon/engine/engine.py index fb5079b3..22936230 100644 --- a/src/graphon/engine/engine.py +++ b/src/graphon/engine/engine.py @@ -7,6 +7,8 @@ from collections.abc import Generator, Sequence from typing import final +from graphon.engine.frame_graph import FrameGraph +from graphon.engine.frame_graph_factory import FrameGraphFactory, GraphResolver from graphon.engine_events.base import ( EngineEvent, ) @@ -24,7 +26,8 @@ peek_workflow_file_runtime, use_workflow_file_runtime, ) -from graphon.graph.graph import Graph +from graphon.graph import Graph +from graphon.nodes.factory import NodeFactory from graphon.runtime.execution import ROOT_FRAME_ID from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.ready_queue import ResumeTask, StartTask @@ -61,12 +64,15 @@ class Engine: def __init__( self, - graph: Graph, + graph: Graph | FrameGraph, runtime_state: RuntimeState, command_channel: CommandChannel | None = None, workers: int = 5, container_handler_factories: Sequence[ContainerHandlerFactory] = (), *, + node_factory: NodeFactory | None = None, + root_node_id: str | None = None, + graph_resolver: GraphResolver | None = None, file_runtime: WorkflowFileRuntimeProtocol | None = None, emit_frame_events: bool = True, ) -> None: @@ -84,6 +90,9 @@ def __init__( A process-local in-memory channel is created when omitted. workers: Fixed number of worker threads to create while running. container_handler_factories: Additional container handler factories. + node_factory: Host factory for nodes in a shared graph definition. + root_node_id: Entry to execute. A single entry is selected automatically. + graph_resolver: Host lookup for referenced graph definitions. file_runtime: File adapter for this execution. None captures the current scoped adapter, even if it is unconfigured. Supply it again when rebuilding an engine from a snapshot. @@ -99,7 +108,21 @@ def __init__( msg = "workers must be a positive integer" raise ValueError(msg) - # Bind runtime state to current workflow context + # Create the root frame's graph for this execution. + if isinstance(graph, Graph): + if node_factory is None: + msg = "A Graph definition requires a node_factory" + raise ValueError(msg) + if root_node_id is None: + if len(graph.entry_node_ids) != 1: + msg = "Choose root_node_id when a graph has multiple entries" + raise ValueError(msg) + root_node_id = next(iter(graph.entry_node_ids)) + graph = FrameGraphFactory(graph_resolver).create( + graph, + node_factory.with_runtime_state(runtime_state.read_only_view), + root_node_id, + ) self._graph = graph self._runtime_state = runtime_state self._file_runtime = ( @@ -183,9 +206,8 @@ def __init__( def _validate_runtime_state_consistency(self) -> None: """Validate that all nodes share the same RuntimeState.""" - expected_state_id = id(self._runtime_state) for node in self._graph.nodes.values(): - if id(node.runtime_state) != expected_state_id: + if node.runtime_state is not self._runtime_state.read_only_view: msg = ( "RuntimeState consistency violation: Node " f"'{node.id}' has a different instance" @@ -216,7 +238,7 @@ def run(self) -> Generator[EngineEvent, None, None]: """Execute the graph without leaking its file adapter to event consumers. Yields: - `EngineEvent` instances emitted during workflow execution. + `EngineEvent` instances emitted during graph execution. """ events = self._run() @@ -440,7 +462,12 @@ def file_runtime(self) -> WorkflowFileRuntimeProtocol | None: return self._file_runtime @property - def graph(self) -> Graph: + def definition(self) -> Graph | None: + """The shared definition, when the engine was built from one.""" + return self._graph.definition + + @property + def graph(self) -> FrameGraph: """Get the graph bound to this engine.""" return self._graph diff --git a/src/graphon/engine/event/node_failure.py b/src/graphon/engine/event/node_failure.py index c4fab6f7..1a9a710a 100644 --- a/src/graphon/engine/event/node_failure.py +++ b/src/graphon/engine/event/node_failure.py @@ -4,6 +4,7 @@ import time from typing import assert_never, final +from graphon.engine.frame_graph import FrameGraph from graphon.engine_events.base import NodeEvent from graphon.engine_events.node import ( NodeRunExceptionEvent, @@ -15,7 +16,6 @@ WorkflowNodeExecutionMetadataKey, WorkflowNodeExecutionStatus, ) -from graphon.graph.graph import Graph from graphon.node_events.base import NodeRunResult from graphon.runtime.execution import GraphExecution @@ -32,7 +32,7 @@ class NodeFailureHandler: def __init__( self, - graph: Graph, + graph: FrameGraph, graph_execution: GraphExecution, ) -> None: """Initialize failure handling for one frame's graph. diff --git a/src/graphon/engine/filter/builtin/response_stream/filter.py b/src/graphon/engine/filter/builtin/response_stream/filter.py index e8c64847..a407bd7b 100644 --- a/src/graphon/engine/filter/builtin/response_stream/filter.py +++ b/src/graphon/engine/filter/builtin/response_stream/filter.py @@ -4,6 +4,11 @@ from typing import Any, cast from graphon.engine.filter.protocol import EngineEventFilterContext +from graphon.engine.frame_graph import FrameGraph +from graphon.engine.frame_graph_factory import ( + FrameGraphFactory, + build_local_graph_config, +) from graphon.engine_events.base import EngineEvent, NodeEvent from graphon.engine_events.frame import ( FrameFinishedEvent, @@ -28,8 +33,10 @@ ) from graphon.engine_events.traversal import GraphEdgeSkippedEvent, GraphEdgeTakenEvent from graphon.entities.workflow_start_reason import WorkflowStartReason +from graphon.enums import BuiltinNodeTypes from graphon.file.protocols import WorkflowFileRuntimeProtocol from graphon.file.runtime import use_workflow_file_runtime +from graphon.graph import Graph, NodeDefinition from graphon.runtime.execution import ROOT_FRAME_ID from graphon.runtime.runtime_state import GraphProtocol @@ -56,6 +63,8 @@ def __init__(self, *, pass_unmatched_chunks: bool = False) -> None: self._has_child_progress = False self._reply_order = _ReplyOrder() self._response_container_ids: set[str] = set() + self._frame_graph_factory: FrameGraphFactory | None = None + self._response_containers_by_frame: dict[str, dict[str, NodeDefinition]] = {} def initialize(self, context: EngineEventFilterContext) -> None: with use_workflow_file_runtime(context.file_runtime): @@ -80,9 +89,23 @@ def initialize(self, context: EngineEventFilterContext) -> None: self._root_session = root_session self._frame_sessions[ROOT_FRAME_ID] = root_session self._graph_config = getattr(context.graph, "graph_config", None) - self._response_container_ids = find_response_container_ids( - self._graph_config + self._response_containers_by_frame.clear() + self._frame_graph_factory = ( + context.graph.frame_graph_factory + if isinstance(context.graph, FrameGraph) + else None ) + if ( + self._frame_graph_factory is not None + and context.graph.definition is not None + ): + self._register_response_containers( + ROOT_FRAME_ID, context.graph.definition + ) + else: + self._response_container_ids = find_response_container_ids( + self._graph_config + ) self._pending_state = None def on_event(self, event: EngineEvent) -> Iterable[EngineEvent]: @@ -126,6 +149,7 @@ def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: igno ) if event.frame_id != ROOT_FRAME_ID: self._frame_sessions.pop(event.frame_id, None) + self._response_containers_by_frame.pop(event.frame_id, None) self._reply_order.finish_frame( event.frame_id, succeeded=event.outcome == "succeeded" ) @@ -173,10 +197,32 @@ def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: igno return [] return [event] + def _register_response_containers(self, frame_id: str, graph: Graph) -> None: + frame_graph_factory = self._frame_graph_factory + if frame_graph_factory is None: + return + callers: dict[str, NodeDefinition] = {} + for caller in graph.nodes.values(): + if caller.call_target is None: + continue + body = frame_graph_factory.resolve_call_target(caller) + if any( + node.node_type in {BuiltinNodeTypes.ANSWER, BuiltinNodeTypes.END} + for scope, _ in frame_graph_factory.walk_graphs(body) + for node in scope.nodes.values() + ): + callers[caller.id] = caller + self._response_containers_by_frame[frame_id] = callers + + def _container_has_response(self, frame_id: str, node_id: str) -> bool: + if self._frame_graph_factory is not None: + return node_id in self._response_containers_by_frame.get(frame_id, {}) + return node_id in self._response_container_ids + def _update_container_replies(self, event: EngineEvent) -> None: if not isinstance(event, NodeEvent): return - if event.node_id not in self._response_container_ids: + if not self._container_has_response(event.frame_id, event.node_id): return if isinstance( event, @@ -196,13 +242,26 @@ def _start_frame_session(self, event: FrameStartedEvent) -> list[EngineEvent]: if event.frame_id == ROOT_FRAME_ID: self._awaiting_root_baseline = False return self._initialized_root_session.start(event) - if event.container_id not in self._response_container_ids: + parent_frame_id = event.parent_frame_id or ROOT_FRAME_ID + if not self._container_has_response(parent_frame_id, event.container_id): return [] if event.reason == WorkflowStartReason.RESUMPTION: msg = "Resuming child response progress is not supported yet" raise ValueError(msg) self._reply_order.start_frame(event) - graph = build_child_graph(self._graph_config, event) + config = self._graph_config + configured_start_node_id = None + if self._frame_graph_factory is not None: + caller = self._response_containers_by_frame[parent_frame_id][ + event.container_id + ] + body = self._frame_graph_factory.resolve_call_target(caller) + configured_start_node_id = caller.config.get("start_node_id") + self._register_response_containers(event.frame_id, body) + config = build_local_graph_config(body, event.container_id) + graph = build_child_graph( + config, event, configured_start_node_id=configured_start_node_id + ) if graph is None: return [] session = _FrameSession( diff --git a/src/graphon/engine/filter/builtin/response_stream/frame_graph.py b/src/graphon/engine/filter/builtin/response_stream/frame_graph.py index 4a244145..1424a3cb 100644 --- a/src/graphon/engine/filter/builtin/response_stream/frame_graph.py +++ b/src/graphon/engine/filter/builtin/response_stream/frame_graph.py @@ -135,7 +135,10 @@ def _build_node_definition(node_id: str, data: Mapping[str, Any]) -> _NodeDefini def build_child_graph( - graph_config: Mapping[str, Any] | None, start: FrameStartedEvent + graph_config: Mapping[str, Any] | None, + start: FrameStartedEvent, + *, + configured_start_node_id: str | None = None, ) -> GraphProtocol | None: if not graph_config: return None @@ -152,7 +155,7 @@ def build_child_graph( if isinstance(data, BaseNodeData): data = data.model_dump(mode="python") nodes[node_id] = _build_node_definition(node_id, data) - root_node_id = start.root_node_id + root_node_id = start.root_node_id or configured_start_node_id if root_node_id is None and (container := node_configs.get(start.container_id)): data = container["data"] root_node_id = ( diff --git a/src/graphon/engine/filter/builtin/response_stream/v1.py b/src/graphon/engine/filter/builtin/response_stream/v1.py index 22035be9..bb5fc8f1 100644 --- a/src/graphon/engine/filter/builtin/response_stream/v1.py +++ b/src/graphon/engine/filter/builtin/response_stream/v1.py @@ -87,7 +87,9 @@ def for_graph( for node_id, node in graph.nodes.items() if node.execution_type == NodeExecutionType.RESPONSE } - legacy_edge_ids = _legacy_edge_ids(graph) + legacy_edge_ids = getattr(graph, "legacy_edge_ids", None) + if legacy_edge_ids is None: + legacy_edge_ids = _legacy_edge_ids(graph) try: paths_map = { diff --git a/src/graphon/engine/filter/protocol.py b/src/graphon/engine/filter/protocol.py index 1015f340..af589f18 100644 --- a/src/graphon/engine/filter/protocol.py +++ b/src/graphon/engine/filter/protocol.py @@ -4,10 +4,10 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Protocol +from graphon.engine.frame_graph import FrameGraph from graphon.engine_events.base import EngineEvent from graphon.file.protocols import WorkflowFileRuntimeProtocol from graphon.file.runtime import peek_workflow_file_runtime -from graphon.graph.graph import Graph from graphon.runtime.execution import ROOT_FRAME_ID from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state_protocol import ReadOnlyRuntimeState @@ -20,7 +20,7 @@ class EngineEventFilterContext: """Run-scoped context available to engine event filters.""" - graph: Graph + graph: FrameGraph runtime_state: ReadOnlyRuntimeState file_runtime: WorkflowFileRuntimeProtocol | None = field( default_factory=peek_workflow_file_runtime, diff --git a/src/graphon/engine/frame.py b/src/graphon/engine/frame.py index 8b246f3a..4b1ac03c 100644 --- a/src/graphon/engine/frame.py +++ b/src/graphon/engine/frame.py @@ -6,13 +6,13 @@ from dataclasses import dataclass from typing import Literal, final +from graphon.engine.frame_graph import FrameGraph from graphon.engine_events.frame import ( FrameFinishedEvent, FrameStartedEvent, FrameVariablesUpdatedEvent, ) from graphon.entities.workflow_start_reason import WorkflowStartReason -from graphon.graph.graph import Graph from graphon.runtime.container_state import CustomContainerFrameState, FrameRuntimeData from graphon.runtime.execution import ROOT_FRAME_ID from graphon.runtime.runtime_state import RuntimeState @@ -27,7 +27,7 @@ @dataclass(frozen=True, slots=True) class ExecutionFrame: frame_id: str - graph: Graph + graph: FrameGraph state: RuntimeState scheduler: Scheduler failure_handler: NodeFailureHandler @@ -242,7 +242,7 @@ def create( *, frame_id: str, container_id: str, - graph: Graph, + graph: FrameGraph, state: RuntimeState, ) -> ExecutionFrame: """Create and register a fully wired frame. @@ -255,7 +255,7 @@ def create( Args: frame_id: Unique frame ID used by scheduled tasks. container_id: Direct owning container node ID; root uses ``""``. - graph: Graph structure executable by this frame. + graph: FrameGraph structure executable by this frame. state: Mutable runtime state owned by this graph execution. Returns: @@ -370,11 +370,10 @@ def _create_child_with_state( root_node_id: str, state: RuntimeState, ) -> ExecutionFrame: - """Build a scoped child graph around an already prepared state. + """Build the child frame's graph and bind its nodes to the child's state. - The parent's retained graph config and node factory are the only graph - construction inputs. Rebinding the factory prevents child nodes from - observing the parent's mutable runtime state. + For a shared Graph, resolve the body called by the container. For a + host-supplied graph config, build the body from the parent's subtree. Args: frame_id: Unique ID for the new child frame. @@ -400,13 +399,25 @@ def _create_child_with_state( msg = "Parent graph does not carry node_factory for frame creation." raise RuntimeError(msg) - rebound_factory = node_factory.with_runtime_state(state) - graph = Graph.init( - graph_config=graph_config, - node_factory=rebound_factory, - root_node_id=root_node_id, - container_id=container_id, - ) + rebound_factory = node_factory.with_runtime_state(state.read_only_view) + if ( + isinstance(parent_graph, FrameGraph) + and parent_graph.definition is not None + and parent_graph.frame_graph_factory is not None + ): + child = parent_graph.frame_graph_factory.resolve_call_target( + parent_graph.definition.node(container_id) + ) + graph = parent_graph.frame_graph_factory.create( + child, rebound_factory, root_node_id, container_id + ) + else: + graph = FrameGraph.init( + graph_config=graph_config, + node_factory=rebound_factory, + root_node_id=root_node_id, + container_id=container_id, + ) state.variable_pool.node_ids |= self[ parent_frame_id ].state.variable_pool.node_ids diff --git a/src/graphon/engine/frame_graph.py b/src/graphon/engine/frame_graph.py new file mode 100644 index 00000000..657d596a --- /dev/null +++ b/src/graphon/engine/frame_graph.py @@ -0,0 +1,584 @@ +from __future__ import annotations + +import logging +import uuid +from collections import defaultdict +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, final + +from pydantic import TypeAdapter + +from graphon.entities.graph_config import NodeConfigDict +from graphon.enums import ErrorStrategy, NodeExecutionType, NodeState +from graphon.graph.config import normalize_nodes, prepare_edge_configs +from graphon.graph.validation import ( + GraphValidationError, + get_edge_issues, + get_graph_validator, +) +from graphon.nodes.base.node import Node +from graphon.nodes.factory import NodeFactory + +if TYPE_CHECKING: + from graphon.graph import Graph + + from .frame_graph_factory import FrameGraphFactory + +logger = logging.getLogger(__name__) + +_ListNodeConfigDict = TypeAdapter(list[NodeConfigDict]) +_ListObjectDict = TypeAdapter(list[dict[str, Any]]) + + +@dataclass +class Edge: + """A connection and its traversal state in one execution frame.""" + + id: str = field(default_factory=lambda: str(uuid.uuid4())) + tail: str = "" # tail node id (source) + head: str = "" # head node id (target) + source_handle: str = "source" # source handle for conditional branching + state: NodeState = field(default=NodeState.UNKNOWN) # edge execution state + + @property + def source(self) -> str: + return self.tail + + @property + def target(self) -> str: + return self.head + + +@final +class FrameGraph: + """Executable nodes, edges, and the selected entry for one frame.""" + + nodes: dict[str, Node] + edges: dict[str, Edge] + in_edges: dict[str, list[str]] + out_edges: dict[str, list[str]] + root_node: Node + + def __init__( + self, + *, + nodes: dict[str, Node] | None = None, + edges: dict[str, Edge] | None = None, + in_edges: dict[str, list[str]] | None = None, + out_edges: dict[str, list[str]] | None = None, + root_node: Node, + graph_config: Mapping[str, Any] | None = None, + node_factory: NodeFactory | None = None, + ) -> None: + """Initialize FrameGraph instance. + + :param nodes: graph nodes mapping (node id: node object) + :param edges: graph edges mapping (edge id: edge object) + :param in_edges: incoming edges mapping (node id: list of edge ids) + :param out_edges: outgoing edges mapping (node id: list of edge ids) + :param root_node: root node object + """ + self.nodes = nodes or {} + self.edges = edges or {} + self.in_edges = in_edges or {} + self.out_edges = out_edges or {} + self.root_node = root_node + self.graph_config = graph_config + self.node_factory = node_factory + self.legacy_edge_ids: Mapping[str, str] | None = None + self.definition: Graph | None = None + self.frame_graph_factory: FrameGraphFactory | None = None + + @classmethod + def _parse_node_configs( + cls, + node_configs: list[NodeConfigDict], + ) -> dict[str, NodeConfigDict]: + """Parse node configurations and build a mapping of node IDs to configs. + + :param node_configs: list of node configuration dictionaries + + Returns: + Mapping of node ID to node config. + + """ + node_configs_map: dict[str, NodeConfigDict] = {} + + for node_config in node_configs: + node_configs_map[node_config["id"]] = node_config + + return node_configs_map + + @classmethod + def _build_edges( + cls, + edge_configs: list[dict[str, Any]], + ) -> tuple[dict[str, Edge], dict[str, list[str]], dict[str, list[str]]]: + """Build edge objects and mappings from edge configurations. + + :param edge_configs: list of edge configurations + + Returns: + Tuple of `edges`, `in_edges`, and `out_edges` mappings. + + Raises: + ValueError: If two edges in this graph use the same public ID. + + """ + edges: dict[str, Edge] = {} + edge_ids: set[str] = set() + in_edges: dict[str, list[str]] = defaultdict(list) + out_edges: dict[str, list[str]] = defaultdict(list) + + for edge_config in edge_configs: + source = edge_config["source"] + target = edge_config["target"] + + edge_id = edge_config["id"] + if edge_id in edge_ids: + msg = f"Duplicate graph edge ID: {edge_id}" + raise ValueError(msg) + edge_ids.add(edge_id) + + source_handle = edge_config.get("sourceHandle", "source") + + edge = Edge( + id=edge_id, + tail=source, + head=target, + source_handle=source_handle, + ) + + edges[edge_id] = edge + out_edges[source].append(edge_id) + in_edges[target].append(edge_id) + + return edges, dict(in_edges), dict(out_edges) + + @classmethod + def _create_node_instances( + cls, + node_configs_map: dict[str, NodeConfigDict], + node_factory: NodeFactory, + ) -> dict[str, Node]: + """Create node instances from configurations using the node factory. + + :param node_configs_map: mapping of node ID to node config + :param node_factory: factory for creating node instances + + Returns: + Mapping of node ID to node instance. + + """ + nodes: dict[str, Node] = {} + + for node_id, node_config in node_configs_map.items(): + try: + node_instance = node_factory.create_node(node_config) + except Exception: + logger.exception( + "Failed to create node instance for node_id %s", + node_id, + ) + raise + nodes[node_id] = node_instance + + return nodes + + @classmethod + def _scope_graph_config( + cls, + *, + graph_config: Mapping[str, Any], + node_configs: list[dict[str, Any]], + edge_configs: list[dict[str, Any]], + container_ids: Mapping[str, str], + container_id: str, + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: + """Split a graph configuration into one frame's executable and visible scope. + + The direct node and edge lists contain only objects owned by + ``container_id`` and are used to construct the frame's executable + :class:`FrameGraph`. The returned graph config also retains recursively nested + containers so the frame can later construct its children, while excluding + every parent and sibling scope. Edges between different direct owners are + invalid because they would bypass the owning container node. + + :param graph_config: complete config visible to the parent frame + :param node_configs: copied nodes carrying canonical ``data.container_id`` + :param edge_configs: validated raw edge dictionaries from that config + :param container_ids: direct container ID already resolved for every node + :param container_id: direct owner to materialize, or ``""`` for root + + Returns: + Direct nodes, direct edges, and the container subtree config. + + Raises: + ValueError: If scopes are orphaned, cyclic, or joined by an edge. + + """ + direct_node_ids = { + node_id + for node_id, node_container_id in container_ids.items() + if node_container_id == container_id + } + subtree_node_ids = set(direct_node_ids) + while descendants := { + node_id + for node_id, node_container_id in container_ids.items() + if node_container_id in subtree_node_ids and node_id not in subtree_node_ids + }: + subtree_node_ids.update(descendants) + if not container_id and subtree_node_ids != set(container_ids): + orphan_node_ids = sorted(set(container_ids) - subtree_node_ids) + msg = f"Nodes reference unknown or cyclic containers: {orphan_node_ids}" + raise ValueError(msg) + + direct_edge_configs: list[dict[str, Any]] = [] + subtree_edge_configs: list[dict[str, Any]] = [] + for edge_config in edge_configs: + source = edge_config["source"] + target = edge_config["target"] + + if ( + source in container_ids + and target in container_ids + and container_ids[source] != container_ids[target] + ): + msg = ( + f"Edge '{source}->{target}' crosses container scopes " + f"'{container_ids[source]}' and '{container_ids[target]}'" + ) + raise ValueError(msg) + + has_unknown_endpoint = ( + source not in container_ids or target not in container_ids + ) + if ( + source in direct_node_ids + or target in direct_node_ids + or (not container_id and has_unknown_endpoint) + ): + direct_edge_configs.append(edge_config) + if ( + source in subtree_node_ids + or target in subtree_node_ids + or (not container_id and has_unknown_endpoint) + ): + subtree_edge_configs.append(edge_config) + + scoped_graph_config = dict(graph_config) + scoped_graph_config["nodes"] = [ + node_config + for node_config in node_configs + if node_config.get("id") in subtree_node_ids + ] + scoped_graph_config["edges"] = subtree_edge_configs + direct_node_configs = [ + node_config + for node_config in node_configs + if node_config.get("id") in direct_node_ids + ] + return direct_node_configs, direct_edge_configs, scoped_graph_config + + @classmethod + def _promote_fail_branch_nodes(cls, nodes: dict[str, Node]) -> None: + """Promote nodes configured with FAIL_BRANCH error strategy + to branch execution type. + + :param nodes: mapping of node ID to node instance + """ + for node in nodes.values(): + if node.error_strategy == ErrorStrategy.FAIL_BRANCH: + node.execution_type = NodeExecutionType.BRANCH + + @classmethod + def mark_inactive_root_branches( + cls, + nodes: dict[str, Node], + edges: dict[str, Edge], + in_edges: dict[str, list[str]], + out_edges: dict[str, list[str]], + active_root_id: str, + ) -> None: + """Mark nodes and edges that belong to inactive root branches.""" + cls._mark_inactive_root_branches( + nodes, + edges, + in_edges, + out_edges, + active_root_id, + ) + + @classmethod + def _mark_inactive_root_branches( + cls, + nodes: dict[str, Node], + edges: dict[str, Edge], + in_edges: dict[str, list[str]], + out_edges: dict[str, list[str]], + active_root_id: str, + entry_node_ids: frozenset[str] | None = None, + ) -> None: + """Mark nodes and edges from inactive root branches as skipped. + + Algorithm: + 1. Mark inactive root nodes as skipped + 2. For skipped nodes, mark all their outgoing edges as skipped + 3. For each edge marked as skipped, check its target node: + - If ALL incoming edges are skipped, mark the node as skipped + - Otherwise, leave the node state unchanged + + :param nodes: mapping of node ID to node instance + :param edges: mapping of edge ID to edge instance + :param in_edges: mapping of node ID to incoming edge IDs + :param out_edges: mapping of node ID to outgoing edge IDs + :param active_root_id: ID of the active root node + """ + if entry_node_ids is None: + entry_node_ids = frozenset( + node.id + for node in nodes.values() + if node.execution_type == NodeExecutionType.ROOT + ) + + # If there's only one root or the active root is not a top-level + # root, no marking is needed + if len(entry_node_ids) <= 1 or active_root_id not in entry_node_ids: + return + + # Mark inactive root nodes as skipped + inactive_roots = (entry_node_ids & nodes.keys()) - {active_root_id} + for root_id in inactive_roots: + nodes[root_id].state = NodeState.SKIPPED + + # Unchecked graphs can contain cycles or missing targets. + visited_node_ids: set[str] = set() + + # Recursively mark downstream nodes and edges + def mark_downstream(node_id: str) -> None: + """Recursively mark downstream nodes and edges as skipped.""" + if node_id in visited_node_ids or nodes[node_id].state != NodeState.SKIPPED: + return + visited_node_ids.add(node_id) + # If this node is skipped, mark all its outgoing edges as skipped + out_edge_ids = out_edges.get(node_id, []) + for edge_id in out_edge_ids: + edge = edges[edge_id] + edge.state = NodeState.SKIPPED + + # Check the target node of this edge + target_node = nodes.get(edge.head) + if target_node is None: + continue + in_edge_ids = in_edges.get(target_node.id, []) + in_edge_states = [edges[eid].state for eid in in_edge_ids] + + # If all incoming edges are skipped, mark the node as skipped + if all(state == NodeState.SKIPPED for state in in_edge_states): + target_node.state = NodeState.SKIPPED + # Recursively process downstream nodes + mark_downstream(target_node.id) + + # Process each inactive root and its downstream nodes + for root_id in inactive_roots: + mark_downstream(root_id) + + @staticmethod + def _validate_subtree_edges( + graph_config: Mapping[str, Any], + container_ids: Mapping[str, str], + ) -> None: + """Validate retained subtree edges before any node is constructed.""" + issues = get_edge_issues( + { + node_config["id"]: container_ids[node_config["id"]] + for node_config in graph_config["nodes"] + }, + ( + Edge( + id=edge_config["id"], + tail=edge_config["source"], + head=edge_config["target"], + source_handle=edge_config.get("sourceHandle", "source"), + ) + for edge_config in graph_config["edges"] + ), + ) + if issues: + raise GraphValidationError(issues) + + @classmethod + def init( + cls, + *, + graph_config: Mapping[str, Any], + node_factory: NodeFactory, + root_node_id: str, + container_id: str = "", + skip_validation: bool = False, + ) -> FrameGraph: + """Initialize a graph with an explicit execution entry point. + + :param graph_config: graph config containing nodes and edges + :param node_factory: factory for creating node instances from config data + :param root_node_id: active root node id + :param container_id: direct container scope to materialize; empty for root + :param skip_validation: bypass endpoint existence, root type, and cycle + checks; input fields, IDs, schemas, and ownership are still validated + + Returns: + Initialized graph instance rooted at `root_node_id`. + + Raises: + ValueError: If the graph has no nodes or `root_node_id` does not exist. + + """ + # Parse configs + node_configs, container_ids = normalize_nodes( + _ListObjectDict.validate_python(graph_config.get("nodes", [])), + ) + + direct_node_configs, direct_edge_configs, scoped_graph_config = ( + cls._scope_graph_config( + graph_config=graph_config, + node_configs=node_configs, + edge_configs=prepare_edge_configs( + graph_config, + container_ids, + ), + container_ids=container_ids, + container_id=container_id, + ) + ) + node_factory = node_factory.with_graph_config(scoped_graph_config) + scoped_node_configs = _ListNodeConfigDict.validate_python( + scoped_graph_config["nodes"], + ) + execution_types = { + node_config["id"]: node_factory.validate_node(node_config) + for node_config in scoped_node_configs + } + # Every descendant is prevalidated above, so container ownership can be + # checked before direct-frame nodes run constructors or post-init hooks. + for container_node_id in sorted( + { + container_ids[node_config["id"]] + for node_config in scoped_node_configs + if container_ids[node_config["id"]] + } + & execution_types.keys(), + ): + if execution_types[container_node_id] != NodeExecutionType.CONTAINER: + msg = ( + f"Node '{container_node_id}' owns child nodes " + "but is not a container" + ) + raise ValueError(msg) + node_configs_map = cls._parse_node_configs( + _ListNodeConfigDict.validate_python(direct_node_configs), + ) + + if not node_configs_map: + msg = "Graph must have at least one node" + raise ValueError(msg) + + if root_node_id not in node_configs_map: + msg = f"Root node id {root_node_id} not found in the graph" + raise ValueError(msg) + + if not skip_validation: + cls._validate_subtree_edges( + scoped_graph_config, + container_ids, + ) + + return cls.from_node_configs( + node_configs_map=node_configs_map, + direct_edge_configs=direct_edge_configs, + scoped_graph_config=scoped_graph_config, + node_factory=node_factory, + root_node_id=root_node_id, + skip_validation=skip_validation, + ) + + @classmethod + def from_node_configs( + cls, + *, + node_configs_map: dict[str, NodeConfigDict], + direct_edge_configs: list[dict[str, Any]], + scoped_graph_config: Mapping[str, Any], + node_factory: NodeFactory, + root_node_id: str, + entry_node_ids: frozenset[str] | None = None, + skip_validation: bool = False, + ) -> FrameGraph: + """Construct fresh executable nodes and edges from checked node configs.""" + # Build edges + edges, in_edges, out_edges = cls._build_edges(direct_edge_configs) + + # Create node instances + nodes = cls._create_node_instances(node_configs_map, node_factory) + # Promote fail-branch nodes to branch execution type at graph level + cls._promote_fail_branch_nodes(nodes) + + # Mark inactive root branches as skipped + cls._mark_inactive_root_branches( + nodes, + edges, + in_edges, + out_edges, + root_node_id, + entry_node_ids, + ) + + # Create and return the graph + graph = cls( + nodes=nodes, + edges=edges, + in_edges=in_edges, + out_edges=out_edges, + root_node=nodes[root_node_id], + graph_config=scoped_graph_config, + node_factory=node_factory, + ) + + if not skip_validation: + # Validate the graph structure using built-in validators + get_graph_validator().validate(graph) + + return graph + + @property + def node_ids(self) -> list[str]: + """Get list of node IDs (compatibility property for existing code) + + :return: list of node IDs + """ + return list(self.nodes.keys()) + + def get_outgoing_edges(self, node_id: str) -> list[Edge]: + """Get all outgoing edges from a node (V2 method) + + :param node_id: node id + + Returns: + All edges whose tail is `node_id`. + + """ + edge_ids = self.out_edges.get(node_id, []) + return [self.edges[eid] for eid in edge_ids if eid in self.edges] + + def get_incoming_edges(self, node_id: str) -> list[Edge]: + """Get all incoming edges to a node (V2 method) + + :param node_id: node id + + Returns: + All edges whose head is `node_id`. + + """ + edge_ids = self.in_edges.get(node_id, []) + return [self.edges[eid] for eid in edge_ids if eid in self.edges] diff --git a/src/graphon/engine/frame_graph_factory.py b/src/graphon/engine/frame_graph_factory.py new file mode 100644 index 00000000..697dffc5 --- /dev/null +++ b/src/graphon/engine/frame_graph_factory.py @@ -0,0 +1,152 @@ +"""Build frame graphs from shared definitions.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from typing import Any + +from graphon.entities.graph_config import NodeConfigDict, NodeConfigDictAdapter +from graphon.enums import NodeExecutionType +from graphon.graph import Graph, GraphReference, NodeDefinition +from graphon.graph.validation import GraphValidationError, GraphValidationIssue +from graphon.nodes.factory import NodeFactory + +from .frame_graph import FrameGraph + +type GraphResolver = Callable[[GraphReference], Graph] + + +def _build_node_config(node: NodeDefinition, container_id: str) -> dict[str, Any]: + data = node.copy_config() + data.update(type=node.node_type, version=node.version, container_id=container_id) + return {"id": node.id, "data": data} + + +def _build_edge_configs(graph: Graph) -> list[dict[str, Any]]: + return [ + { + "id": edge.id, + "source": edge.source, + "target": edge.target, + "sourceHandle": edge.source_handle, + } + for edge in graph.edges.values() + ] + + +def build_local_graph_config(graph: Graph, container_id: str) -> dict[str, Any]: + """Build the node and edge configuration for a single graph.""" + return { + "nodes": [ + _build_node_config(node, container_id) for node in graph.nodes.values() + ], + "edges": _build_edge_configs(graph), + } + + +class FrameGraphFactory: + """Create frame graphs for one run and resolve each graph reference once.""" + + def __init__(self, resolver: GraphResolver | None) -> None: + self._resolver = resolver + self._resolved_graphs: dict[GraphReference, Graph] = {} + + def resolve_call_target(self, node: NodeDefinition) -> Graph: + target = node.call_target + if isinstance(target, Graph): + return target + if target is None: + msg = f"Node {node.id!r} has no graph to call" + raise ValueError(msg) + if target not in self._resolved_graphs: + if self._resolver is None: + msg = f"Node {node.id!r} needs a resolver for graph {target.id!r}" + raise ValueError(msg) + graph = self._resolver(target) + if not isinstance(graph, Graph): + msg = f"Expected a Graph for reference {target.id!r}" + raise TypeError(msg) + self._resolved_graphs[target] = graph + return self._resolved_graphs[target] + + def walk_graphs( + self, + graph: Graph, + container_id: str = "", + *, + stop_at_node_type: str | None = None, + ancestor_graph_ids: frozenset[int] = frozenset(), + ) -> Iterator[tuple[Graph, str]]: + yield graph, container_id + ancestor_graph_ids |= {id(graph)} + for node in graph.nodes.values(): + if node.call_target is not None and node.node_type != stop_at_node_type: + child = self.resolve_call_target(node) + # A recursive reference can open another frame when it is invoked. + if id(child) not in ancestor_graph_ids: + yield from self.walk_graphs( + child, + node.id, + stop_at_node_type=stop_at_node_type, + ancestor_graph_ids=ancestor_graph_ids, + ) + + def create( + self, + graph: Graph, + node_factory: NodeFactory, + root_node_id: str, + container_id: str = "", + ) -> FrameGraph: + if root_node_id not in graph.entry_node_ids: + raise GraphValidationError([ + GraphValidationIssue( + "INVALID_ROOT", + f"Node {root_node_id!r} is not an entry of this graph.", + root_node_id, + ) + ]) + # Existing factories and response filters read the flat subtree config. + # Node construction and edge lookup always use the frame's local IDs. + graph_configs = [ + (scope, build_local_graph_config(scope, owner_id)) + for scope, owner_id in self.walk_graphs(graph, container_id) + ] + subtree_config = { + "nodes": [ + node + for _, scope_config in graph_configs + for node in scope_config["nodes"] + ], + "edges": [ + edge + for _, scope_config in graph_configs + for edge in scope_config["edges"] + ], + } + node_factory = node_factory.with_graph_config(subtree_config) + local_node_configs: dict[str, NodeConfigDict] = {} + for scope, scope_config in graph_configs: + for raw_node_config in scope_config["nodes"]: + node_config = NodeConfigDictAdapter.validate_python(raw_node_config) + node = scope.node(node_config["id"]) + execution_type = node_factory.validate_node(node_config) + if ( + node.call_target is not None + and execution_type != NodeExecutionType.CONTAINER + ): + msg = f"Node '{node.id}' owns child nodes but is not a container" + raise ValueError(msg) + if scope is graph: + local_node_configs[node.id] = node_config + frame_graph = FrameGraph.from_node_configs( + node_configs_map=local_node_configs, + direct_edge_configs=graph_configs[0][1]["edges"], + scoped_graph_config=subtree_config, + node_factory=node_factory, + root_node_id=root_node_id, + entry_node_ids=graph.entry_node_ids, + ) + frame_graph.definition = graph + frame_graph.frame_graph_factory = self + return frame_graph diff --git a/src/graphon/engine/scheduler.py b/src/graphon/engine/scheduler.py index 18d9ecb3..99daa678 100644 --- a/src/graphon/engine/scheduler.py +++ b/src/graphon/engine/scheduler.py @@ -3,10 +3,9 @@ from collections.abc import Callable, Sequence from typing import TypedDict, final +from graphon.engine.frame_graph import Edge, FrameGraph from graphon.engine_events.traversal import GraphEdgeSkippedEvent, GraphEdgeTakenEvent from graphon.enums import NodeExecutionType, NodeState -from graphon.graph.edge import Edge -from graphon.graph.graph import Graph from graphon.runtime.ready_queue import ReadyTask, StartTask from graphon.runtime.runtime_state import RuntimeState @@ -25,7 +24,7 @@ class _EdgeStateAnalysis(TypedDict): class Scheduler: def __init__( self, - graph: Graph, + graph: FrameGraph, state: RuntimeState, frame_id: str, ) -> None: diff --git a/src/graphon/engine/worker/worker.py b/src/graphon/engine/worker/worker.py index 5a1562dc..49948489 100644 --- a/src/graphon/engine/worker/worker.py +++ b/src/graphon/engine/worker/worker.py @@ -10,6 +10,7 @@ import threading from collections.abc import Generator, Iterator, Sequence from contextlib import ExitStack, contextmanager, nullcontext +from copy import deepcopy from dataclasses import dataclass from datetime import UTC, datetime from typing import final, override @@ -19,8 +20,11 @@ from graphon.engine.layer import Layer from graphon.engine_events.base import NodeEvent from graphon.engine_events.node import ( + NodeRunExceptionEvent, NodeRunFailedEvent, NodeRunStartedEvent, + NodeRunSucceededEvent, + NodeRunVariableUpdatedEvent, is_node_result_event, ) from graphon.enums import WorkflowNodeExecutionStatus @@ -57,6 +61,21 @@ class ContainerAwaitTask: type DispatchTask = NodeEventTask | ContainerAwaitTask +def _copy_node_writes(event: NodeEvent) -> NodeEvent: + """Capture the write before the node resumes on the worker thread.""" + if isinstance(event, NodeRunVariableUpdatedEvent): + return event.model_copy( + update={"variable": event.variable.model_copy(deep=True)} + ) + if isinstance(event, (NodeRunSucceededEvent, NodeRunExceptionEvent)): + result = event.node_run_result + outputs = deepcopy(dict(result.outputs)) + return event.model_copy( + update={"node_run_result": result.model_copy(update={"outputs": outputs})} + ) + return event + + @final class Worker(threading.Thread): """Worker thread that executes nodes from the ready queue. @@ -309,8 +328,9 @@ def _consume_node_events( node_events: Iterator[NodeEvent | ContainerAwaitRequest], ) -> tuple[NodeEvent | None, bool]: result_event: NodeEvent | None = None - for event in node_events: - if isinstance(event, ContainerAwaitRequest): + for event_or_request in node_events: + if isinstance(event_or_request, ContainerAwaitRequest): + request = event_or_request.model_copy(deep=True) started_at = self._current_node_started_at if started_at is None: msg = "container await request emitted before node start" @@ -324,16 +344,17 @@ def _consume_node_events( frame_id=self._current_frame_id, node_id=node.id, started_at=started_at, - request=event, + request=request, ) ) self._dispatch_queue.put( ContainerAwaitTask( invocation_id=invocation_id, - request=event, + request=request, ) ) return None, True + event = _copy_node_writes(event_or_request) if isinstance(event, NodeRunStartedEvent) and event.id == node.execution_id: self._current_node_started_at = event.start_at self._dispatch_queue.put( diff --git a/src/graphon/graph/__init__.py b/src/graphon/graph/__init__.py index 4830ea83..6de5ff1b 100644 --- a/src/graphon/graph/__init__.py +++ b/src/graphon/graph/__init__.py @@ -1,11 +1,10 @@ -from .edge import Edge -from .graph import Graph, GraphBuilder, NodeFactory +from .graph import EdgeDefinition, Graph, GraphReference, NodeDefinition from .graph_template import GraphTemplate __all__ = [ - "Edge", + "EdgeDefinition", "Graph", - "GraphBuilder", + "GraphReference", "GraphTemplate", - "NodeFactory", + "NodeDefinition", ] diff --git a/src/graphon/graph/config.py b/src/graphon/graph/config.py new file mode 100644 index 00000000..71638439 --- /dev/null +++ b/src/graphon/graph/config.py @@ -0,0 +1,182 @@ +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping, Sequence +from typing import Any + +from pydantic import TypeAdapter + +from graphon.entities.base_node_data import BaseNodeData + +from .scoping import resolve_container_id +from .validation import GraphValidationError, GraphValidationIssue + +_ListObjectDict = TypeAdapter(list[dict[str, Any]]) + + +def normalize_nodes( + node_configs: Sequence[Mapping[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, str]]: + """Copy nodes and normalize their direct container IDs once. + + Resolve canonical, React Flow, and legacy ownership fields against the + complete node hierarchy, remove editor-only note widgets, then write the + result to ``data.container_id`` on copied dictionaries. Filtering happens + before Pydantic node validation because notes intentionally have no executable + ``data.type``. The caller's persisted input is never modified. Prevalidated + :class:`BaseNodeData` values are dumped with ``exclude_unset`` so an unset + canonical default cannot hide an explicitly supplied legacy owner. + + Args: + node_configs: Raw external node configurations. + + Returns: + Copied node configurations with canonical container IDs, followed by + the same IDs indexed by node ID. ``""`` identifies the root graph. + + Raises: + GraphValidationError: If node IDs are invalid or duplicated. + + """ + normalized_nodes = [ + dict(node_config) + for node_config in node_configs + if node_config.get("type", "") != "custom-note" + ] + nodes_by_id: dict[str, dict[str, Any]] = {} + for node_config in normalized_nodes: + node_id = node_config.get("id") + if not isinstance(node_id, str) or not node_id: + raise GraphValidationError([ + GraphValidationIssue( + code="INVALID_NODE_ID", + message=(f"Graph node ID must be a non-empty string: {node_id!r}"), + ) + ]) + if node_id in nodes_by_id: + raise GraphValidationError([ + GraphValidationIssue( + code="DUPLICATE_NODE_ID", + message=f"Duplicate graph node ID: {node_id}", + node_id=node_id, + ) + ]) + nodes_by_id[node_id] = node_config + container_ids = { + node_id: resolve_container_id(node_config, nodes_by_id=nodes_by_id) + for node_id, node_config in nodes_by_id.items() + } + for node_config in normalized_nodes: + node_id = node_config["id"] + data = node_config.get("data") + if isinstance(data, BaseNodeData): + normalized_data = data.model_dump(mode="python", exclude_unset=True) + elif isinstance(data, Mapping): + normalized_data = dict(data) + else: + continue + normalized_data["container_id"] = container_ids[node_id] + node_config["data"] = normalized_data + return normalized_nodes, container_ids + + +def prepare_edge_configs( + graph_config: Mapping[str, Any], + container_ids: Mapping[str, str], +) -> list[dict[str, Any]]: + """Validate edge fields and copy configs with public DSL IDs. + + Missing IDs start with the historical ``edge_N`` ordinal and advance + past IDs supplied or generated elsewhere in the same scope. + Supplied IDs are reserved within their owning graph before + generation, making mixed explicit and fallback IDs independent of + config order without preventing separate graphs from reusing a local + ID. The generated public ID is retained in scoped graph configs, so + child graphs use the same ID when they are materialized later. Supplied + IDs must be non-empty strings. + + Duplicate IDs are rejected within their owning scope, allowing separate + child graphs to reuse the same local edge ID. Each dictionary is copied + before an ID is added, so the caller's config is never mutated. + + Args: + graph_config: Complete or previously scoped graph config. + container_ids: Direct container ID already resolved for every node. + + Returns: + Copied edge dictionaries carrying public DSL edge IDs. + + Raises: + GraphValidationError: If edge fields or scoped edge IDs are invalid. + ValueError: If a supplied edge ID is not a non-empty string. + + """ + edge_configs = [ + dict(edge_config) + for edge_config in _ListObjectDict.validate_python( + graph_config.get("edges", []), + ) + ] + edge_container_ids: list[str | None] = [] + reserved_edge_ids: defaultdict[str | None, set[str]] = defaultdict(set) + for edge_index, edge_config in enumerate(edge_configs): + source = edge_config.get("source") + target = edge_config.get("target") + for field, value in ( + ("source", source), + ("target", target), + ("sourceHandle", edge_config.get("sourceHandle", "source")), + ): + if not isinstance(value, str): + raise GraphValidationError([ + GraphValidationIssue( + code="INVALID_EDGE", + message=( + f"Graph edge at index {edge_index}: " + f"{field} must be a string." + ), + ) + ]) + source_container_id = container_ids.get(source) + target_container_id = container_ids.get(target) + edge_container_id = ( + source_container_id + if source_container_id is not None + and source_container_id == target_container_id + else None + ) + edge_container_ids.append(edge_container_id) + edge_id = edge_config.get("id") + if isinstance(edge_id, str) and edge_id: + if ( + edge_container_id is not None + and edge_id in reserved_edge_ids[edge_container_id] + ): + raise GraphValidationError([ + GraphValidationIssue( + code="DUPLICATE_EDGE_ID", + message=( + f"Duplicate graph edge ID: {edge_id} " + f"in scope {edge_container_id!r}" + ), + ) + ]) + reserved_edge_ids[edge_container_id].add(edge_id) + + for edge_index, (edge_config, edge_container_id) in enumerate( + zip(edge_configs, edge_container_ids, strict=True), + ): + if "id" in edge_config and ( + not isinstance(edge_config["id"], str) or not edge_config["id"] + ): + msg = "Graph edge ID must be a non-empty string" + raise ValueError(msg) + if "id" not in edge_config: + fallback_index = edge_index + edge_id = f"edge_{fallback_index}" + while edge_id in reserved_edge_ids[edge_container_id]: + fallback_index += 1 + edge_id = f"edge_{fallback_index}" + edge_config["id"] = edge_id + reserved_edge_ids[edge_container_id].add(edge_id) + return edge_configs diff --git a/src/graphon/graph/edge.py b/src/graphon/graph/edge.py deleted file mode 100644 index 1f8a2884..00000000 --- a/src/graphon/graph/edge.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid -from dataclasses import dataclass, field - -from graphon.enums import NodeState - - -@dataclass -class Edge: - """Edge connecting two nodes in a workflow graph.""" - - id: str = field(default_factory=lambda: str(uuid.uuid4())) - tail: str = "" # tail node id (source) - head: str = "" # head node id (target) - source_handle: str = "source" # source handle for conditional branching - state: NodeState = field(default=NodeState.UNKNOWN) # edge execution state diff --git a/src/graphon/graph/graph.py b/src/graphon/graph/graph.py index 9329fd45..15fafcc4 100644 --- a/src/graphon/graph/graph.py +++ b/src/graphon/graph/graph.py @@ -1,919 +1,217 @@ +"""The graph definition shared by Python authors, the DSL, and the engine.""" + from __future__ import annotations -import logging -from abc import abstractmethod +import json from collections import defaultdict -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Protocol, final - -from pydantic import TypeAdapter +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, final -from graphon.entities.base_node_data import BaseNodeData -from graphon.entities.graph_config import NodeConfigDict -from graphon.enums import ErrorStrategy, NodeExecutionType, NodeState -from graphon.nodes.base.node import Node +from graphon.enums import BuiltinNodeTypes -from .edge import Edge -from .scoping import resolve_container_id from .validation import ( GraphValidationError, GraphValidationIssue, + check_unique_node_id, get_edge_issues, - get_graph_validator, ) -if TYPE_CHECKING: - from graphon.runtime.runtime_state import RuntimeState - -logger = logging.getLogger(__name__) - -_ListNodeConfigDict = TypeAdapter(list[NodeConfigDict]) -_ListObjectDict = TypeAdapter(list[dict[str, Any]]) - - -class NodeFactory(Protocol): - """Protocol for creating Node instances from node data dictionaries. - - This protocol decouples the Graph class from specific node mapping implementations, - allowing for different node creation strategies while maintaining type safety. - """ - - @abstractmethod - def with_runtime_state( - self, - runtime_state: RuntimeState, - ) -> NodeFactory: - """Return a factory bound to one execution frame's runtime state. - - Container execution creates a separate :class:`RuntimeState` for every - child frame before constructing its scoped graph. Implementations must - ensure every node created by the returned factory uses ``runtime_state`` - instead of the parent frame's state. Stateful factories should return an - independent copy; factories that do not retain runtime state may return - themselves. - - Args: - runtime_state: Runtime state owned by the frame being constructed. - - Returns: - A factory ready to construct nodes for exactly that execution frame. - - """ - ... - - @abstractmethod - def with_graph_config( - self, - graph_config: Mapping[str, Any], - ) -> NodeFactory: - """Return a factory whose nodes receive one frame's scoped graph config. - - Graph scopes are established before node construction because - :meth:`Node.post_init` runs inside the node constructor. Implementations - must copy any factory-owned :class:`InitParams` and replace its - ``graph_config`` rather than mutating configuration shared with parent or - sibling frames. - - Args: - graph_config: Container-subtree configuration visible to the frame. - - Returns: - A factory ready to construct nodes for exactly that graph scope. - - """ - ... - - @abstractmethod - def validate_node(self, node_config: NodeConfigDict) -> NodeExecutionType: - """Validate one node against the concrete schema selected by this factory. - - Validation must resolve the same implementation and version as - :meth:`create_node`, but it must not construct a node, initialize runtime - dependencies, invoke ``post_init()``, or mutate execution state. Graph - calls this method for every node in the visible container subtree before - constructing any direct-frame node, which makes malformed descendants - fail before workflow execution can produce side effects. +__all__ = [ + "EdgeDefinition", + "Graph", + "GraphReference", + "NodeDefinition", +] + + +def _require_nonempty_string(value: str, label: str) -> None: + if not isinstance(value, str) or not value: + msg = f"{label} must be a non-empty string" + raise ValueError(msg) + + +def _freeze_config(value: Any) -> Any: + if isinstance(value, Mapping): + if not all(isinstance(key, str) for key in value): + msg = "Node configuration keys must be strings" + raise TypeError(msg) + return MappingProxyType({ + key: _freeze_config(item) for key, item in value.items() + }) + if isinstance(value, list | tuple): + return tuple(_freeze_config(item) for item in value) + if value is None or isinstance(value, str | bool | int | float): + return value + msg = f"Unsupported node configuration value: {type(value).__name__}" + raise TypeError(msg) + + +@dataclass(frozen=True, slots=True) +class GraphReference: + """The host's key for another graph, optionally pinned to a version.""" + + id: str + version: str | None = None + + def __post_init__(self) -> None: + _require_nonempty_string(self.id, "Graph reference") + if self.version is not None: + _require_nonempty_string(self.version, "Graph reference version") + + +@dataclass(frozen=True, slots=True) +class NodeDefinition: + id: str + node_type: str + version: str = "1" + config: Mapping[str, Any] = field(default_factory=dict, compare=False) + call_target: Graph | GraphReference | None = None + _config_json: str = field(init=False, repr=False) + + def __post_init__(self) -> None: + _require_nonempty_string(self.id, "Node ID") + _require_nonempty_string(self.node_type, "Node type") + _require_nonempty_string(self.version, "Node version") + if not isinstance(self.config, Mapping): + msg = "Node configuration must be a mapping" + raise TypeError(msg) + if self.call_target is not None and not isinstance( + self.call_target, Graph | GraphReference + ): + msg = "A call target must be a Graph or GraphReference" + raise TypeError(msg) + frozen_config = _freeze_config(self.config) + # JSON also distinguishes true from 1 in node settings. + config_json = json.dumps( + frozen_config, + default=dict, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ) + object.__setattr__(self, "config", frozen_config) + object.__setattr__(self, "_config_json", config_json) - Args: - node_config: Base-validated node configuration to resolve and validate. + def copy_config(self) -> dict[str, Any]: + """Give a node factory its own mutable copy of these settings.""" + return json.loads(self._config_json) - Returns: - The execution type declared by the resolved node implementation. - Raises: - ValueError: If the node implementation is unknown or its concrete data - schema is invalid. +@dataclass(frozen=True, slots=True) +class EdgeDefinition: + id: str + source: str + target: str + source_handle: str = "source" - """ - ... + def __post_init__(self) -> None: + _require_nonempty_string(self.id, "Edge ID") + _require_nonempty_string(self.source, "Edge source") + _require_nonempty_string(self.target, "Edge target") + if not isinstance(self.source_handle, str): + msg = "Edge source handle must be a string" + raise TypeError(msg) - @abstractmethod - def create_node(self, node_config: NodeConfigDict) -> Node: - """Create a Node instance from node configuration data. - :param node_config: node configuration dictionary containing type and other data - :return: initialized Node instance - :raises ValueError: if node type is unknown or no - implementation exists for the resolved version - :raises ValidationError: if node_config does not satisfy - NodeConfigDict/BaseNodeData validation - """ - ... +_BUILTIN_ENTRY_TYPES = frozenset(( + BuiltinNodeTypes.START, + BuiltinNodeTypes.ITERATION_START, + BuiltinNodeTypes.LOOP_START, +)) @final +@dataclass(frozen=True, slots=True, init=False) class Graph: - """Graph representation with nodes and edges for workflow execution.""" + """One immutable graph with local IDs and ordered outgoing edges. - nodes: dict[str, Node] - edges: dict[str, Edge] - in_edges: dict[str, list[str]] - out_edges: dict[str, list[str]] - root_node: Node + Hosts can declare additional entry node types by (type, version). + Each execution chooses one of the resulting entry IDs. + """ + + nodes: Mapping[str, NodeDefinition] + edges: Mapping[str, EdgeDefinition] + entry_node_ids: frozenset[str] + _incoming_edges: Mapping[str, tuple[EdgeDefinition, ...]] = field( + repr=False, compare=False + ) + _outgoing_edges: Mapping[str, tuple[EdgeDefinition, ...]] = field(repr=False) def __init__( self, *, - nodes: dict[str, Node] | None = None, - edges: dict[str, Edge] | None = None, - in_edges: dict[str, list[str]] | None = None, - out_edges: dict[str, list[str]] | None = None, - root_node: Node, - graph_config: Mapping[str, Any] | None = None, - node_factory: NodeFactory | None = None, + nodes: Iterable[NodeDefinition], + edges: Iterable[EdgeDefinition] = (), + entry_types: Iterable[tuple[str, str]] = (), ) -> None: - """Initialize Graph instance. - - :param nodes: graph nodes mapping (node id: node object) - :param edges: graph edges mapping (edge id: edge object) - :param in_edges: incoming edges mapping (node id: list of edge ids) - :param out_edges: outgoing edges mapping (node id: list of edge ids) - :param root_node: root node object - """ - self.nodes = nodes or {} - self.edges = edges or {} - self.in_edges = in_edges or {} - self.out_edges = out_edges or {} - self.root_node = root_node - self.graph_config = graph_config - self.node_factory = node_factory - - @classmethod - def _parse_node_configs( - cls, - node_configs: list[NodeConfigDict], - ) -> dict[str, NodeConfigDict]: - """Parse node configurations and build a mapping of node IDs to configs. - - :param node_configs: list of node configuration dictionaries - - Returns: - Mapping of node ID to node config. - - """ - node_configs_map: dict[str, NodeConfigDict] = {} - - for node_config in node_configs: - node_configs_map[node_config["id"]] = node_config - - return node_configs_map - - @classmethod - def _build_edges( - cls, - edge_configs: list[dict[str, Any]], - ) -> tuple[dict[str, Edge], dict[str, list[str]], dict[str, list[str]]]: - """Build edge objects and mappings from edge configurations. - - :param edge_configs: list of edge configurations - - Returns: - Tuple of `edges`, `in_edges`, and `out_edges` mappings. - - Raises: - ValueError: If two edges in this graph use the same public ID. - - """ - edges: dict[str, Edge] = {} - edge_ids: set[str] = set() - in_edges: dict[str, list[str]] = defaultdict(list) - out_edges: dict[str, list[str]] = defaultdict(list) - - for edge_config in edge_configs: - source = edge_config["source"] - target = edge_config["target"] - - edge_id = edge_config["id"] - if edge_id in edge_ids: - msg = f"Duplicate graph edge ID: {edge_id}" - raise ValueError(msg) - edge_ids.add(edge_id) - - source_handle = edge_config.get("sourceHandle", "source") - - edge = Edge( - id=edge_id, - tail=source, - head=target, - source_handle=source_handle, - ) - - edges[edge_id] = edge - out_edges[source].append(edge_id) - in_edges[target].append(edge_id) - - return edges, dict(in_edges), dict(out_edges) - - @staticmethod - def _prepare_edge_configs( - graph_config: Mapping[str, Any], - container_ids: Mapping[str, str], - ) -> list[dict[str, Any]]: - """Validate edge fields and copy configs with public DSL IDs. - - Missing IDs start with the historical ``edge_N`` ordinal and advance - past IDs supplied or generated elsewhere in the same scope. - Supplied IDs are reserved within their owning graph before - generation, making mixed explicit and fallback IDs independent of - config order without preventing separate graphs from reusing a local - ID. The generated public ID is retained in scoped graph configs, so - child graphs use the same ID when they are materialized later. Supplied - IDs must be non-empty strings. - - Duplicate IDs are rejected within their owning scope, allowing separate - child graphs to reuse the same local edge ID. Each dictionary is copied - before an ID is added, so the caller's config is never mutated. - - Args: - graph_config: Complete or previously scoped workflow graph config. - container_ids: Direct container ID already resolved for every node. - - Returns: - Copied edge dictionaries carrying public DSL edge IDs. - - Raises: - GraphValidationError: If edge fields or scoped edge IDs are invalid. - ValueError: If a supplied edge ID is not a non-empty string. - - """ - edge_configs = [ - dict(edge_config) - for edge_config in _ListObjectDict.validate_python( - graph_config.get("edges", []), - ) - ] - edge_container_ids: list[str | None] = [] - reserved_edge_ids: defaultdict[str | None, set[str]] = defaultdict(set) - for edge_index, edge_config in enumerate(edge_configs): - source = edge_config.get("source") - target = edge_config.get("target") - for field, value in ( - ("source", source), - ("target", target), - ("sourceHandle", edge_config.get("sourceHandle", "source")), - ): - if not isinstance(value, str): - raise GraphValidationError([ - GraphValidationIssue( - code="INVALID_EDGE", - message=( - f"Graph edge at index {edge_index}: " - f"{field} must be a string." - ), - ) - ]) - source_container_id = container_ids.get(source) - target_container_id = container_ids.get(target) - edge_container_id = ( - source_container_id - if source_container_id is not None - and source_container_id == target_container_id - else None - ) - edge_container_ids.append(edge_container_id) - edge_id = edge_config.get("id") - if isinstance(edge_id, str) and edge_id: - if ( - edge_container_id is not None - and edge_id in reserved_edge_ids[edge_container_id] - ): - raise GraphValidationError([ - GraphValidationIssue( - code="DUPLICATE_EDGE_ID", - message=( - f"Duplicate graph edge ID: {edge_id} " - f"in scope {edge_container_id!r}" - ), - ) - ]) - reserved_edge_ids[edge_container_id].add(edge_id) - - for edge_index, (edge_config, edge_container_id) in enumerate( - zip(edge_configs, edge_container_ids, strict=True), - ): - if "id" in edge_config and ( - not isinstance(edge_config["id"], str) or not edge_config["id"] - ): - msg = "Graph edge ID must be a non-empty string" - raise ValueError(msg) - if "id" not in edge_config: - fallback_index = edge_index - edge_id = f"edge_{fallback_index}" - while edge_id in reserved_edge_ids[edge_container_id]: - fallback_index += 1 - edge_id = f"edge_{fallback_index}" - edge_config["id"] = edge_id - reserved_edge_ids[edge_container_id].add(edge_id) - return edge_configs - - @classmethod - def _create_node_instances( - cls, - node_configs_map: dict[str, NodeConfigDict], - node_factory: NodeFactory, - ) -> dict[str, Node]: - """Create node instances from configurations using the node factory. - - :param node_configs_map: mapping of node ID to node config - :param node_factory: factory for creating node instances - - Returns: - Mapping of node ID to node instance. - - """ - nodes: dict[str, Node] = {} - - for node_id, node_config in node_configs_map.items(): - try: - node_instance = node_factory.create_node(node_config) - except Exception: - logger.exception( - "Failed to create node instance for node_id %s", - node_id, + nodes_by_id: dict[str, NodeDefinition] = {} + for node in nodes: + if not isinstance(node, NodeDefinition): + msg = "Graph nodes must be node definitions" + raise TypeError(msg) + check_unique_node_id(node.id, nodes_by_id) + nodes_by_id[node.id] = node + entry_types = frozenset(entry_types) + entry_node_ids = frozenset( + node.id + for node in nodes_by_id.values() + if node.node_type in _BUILTIN_ENTRY_TYPES + or (node.node_type, node.version) in entry_types + ) + if not entry_node_ids: + raise GraphValidationError([ + GraphValidationIssue( + "INVALID_ROOT", "Graph must have at least one entry node." ) - raise - nodes[node_id] = node_instance - - return nodes - - @classmethod - def new(cls) -> GraphBuilder: - """Create a fluent builder for assembling a graph programmatically.""" - return GraphBuilder(graph_cls=cls) - - @staticmethod - def _normalize_nodes( - node_configs: Sequence[Mapping[str, Any]], - ) -> tuple[list[dict[str, Any]], dict[str, str]]: - """Copy nodes and normalize their direct container IDs once. - - This is the compatibility boundary used by :meth:`Graph.init`. It resolves - canonical, React Flow, and legacy ownership fields against the complete node - hierarchy, removes editor-only note widgets, then writes the result to - ``data.container_id`` on copied dictionaries. Filtering happens before - Pydantic node validation because notes intentionally have no executable - ``data.type``. The caller's persisted input is never modified. Prevalidated - :class:`BaseNodeData` values are dumped with ``exclude_unset`` so an unset - canonical default cannot hide an explicitly supplied legacy owner. - - Args: - node_configs: Raw external node configurations. - - Returns: - Copied node configurations with canonical container IDs, followed by - the same IDs indexed by node ID. ``""`` identifies the root graph. - - Raises: - GraphValidationError: If node IDs are invalid or duplicated. - - """ - normalized_nodes = [ - dict(node_config) - for node_config in node_configs - if node_config.get("type", "") != "custom-note" - ] - nodes_by_id: dict[str, dict[str, Any]] = {} - for node_config in normalized_nodes: - node_id = node_config.get("id") - if not isinstance(node_id, str) or not node_id: + ]) + + edges_by_id: dict[str, EdgeDefinition] = {} + incoming: defaultdict[str, list[EdgeDefinition]] = defaultdict(list) + outgoing: defaultdict[str, list[EdgeDefinition]] = defaultdict(list) + for edge in edges: + if not isinstance(edge, EdgeDefinition): + msg = "Graph edges must be edge definitions" + raise TypeError(msg) + if edge.id in edges_by_id: raise GraphValidationError([ GraphValidationIssue( - code="INVALID_NODE_ID", - message=( - f"Graph node ID must be a non-empty string: {node_id!r}" - ), + "DUPLICATE_EDGE_ID", f"Duplicate edge ID: {edge.id}" ) ]) - if node_id in nodes_by_id: - raise GraphValidationError([ - GraphValidationIssue( - code="DUPLICATE_NODE_ID", - message=f"Duplicate graph node ID: {node_id}", - node_id=node_id, - ) - ]) - nodes_by_id[node_id] = node_config - container_ids = { - node_id: resolve_container_id(node_config, nodes_by_id=nodes_by_id) - for node_id, node_config in nodes_by_id.items() - } - for node_config in normalized_nodes: - node_id = node_config["id"] - data = node_config.get("data") - if isinstance(data, BaseNodeData): - normalized_data = data.model_dump(mode="python", exclude_unset=True) - elif isinstance(data, Mapping): - normalized_data = dict(data) - else: - continue - normalized_data["container_id"] = container_ids[node_id] - node_config["data"] = normalized_data - return normalized_nodes, container_ids - - @classmethod - def _scope_graph_config( - cls, - *, - graph_config: Mapping[str, Any], - node_configs: list[dict[str, Any]], - edge_configs: list[dict[str, Any]], - container_ids: Mapping[str, str], - container_id: str, - ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: - """Split a workflow graph into one frame's executable and visible scope. - - The direct node and edge lists contain only objects owned by - ``container_id`` and are used to construct the frame's executable - :class:`Graph`. The returned graph config also retains recursively nested - containers so the frame can later construct its children, while excluding - every parent and sibling scope. Edges between different direct owners are - invalid because they would bypass the owning container node. - - :param graph_config: complete config visible to the parent frame - :param node_configs: copied nodes carrying canonical ``data.container_id`` - :param edge_configs: validated raw edge dictionaries from that config - :param container_ids: direct container ID already resolved for every node - :param container_id: direct owner to materialize, or ``""`` for root - - Returns: - Direct nodes, direct edges, and the container subtree config. - - Raises: - ValueError: If scopes are orphaned, cyclic, or joined by an edge. - - """ - direct_node_ids = { - node_id - for node_id, node_container_id in container_ids.items() - if node_container_id == container_id - } - subtree_node_ids = set(direct_node_ids) - while descendants := { - node_id - for node_id, node_container_id in container_ids.items() - if node_container_id in subtree_node_ids and node_id not in subtree_node_ids - }: - subtree_node_ids.update(descendants) - if not container_id and subtree_node_ids != set(container_ids): - orphan_node_ids = sorted(set(container_ids) - subtree_node_ids) - msg = f"Nodes reference unknown or cyclic containers: {orphan_node_ids}" - raise ValueError(msg) - - direct_edge_configs: list[dict[str, Any]] = [] - subtree_edge_configs: list[dict[str, Any]] = [] - for edge_config in edge_configs: - source = edge_config["source"] - target = edge_config["target"] - - if ( - source in container_ids - and target in container_ids - and container_ids[source] != container_ids[target] - ): - msg = ( - f"Edge '{source}->{target}' crosses container scopes " - f"'{container_ids[source]}' and '{container_ids[target]}'" - ) - raise ValueError(msg) - - has_unknown_endpoint = ( - source not in container_ids or target not in container_ids - ) - if ( - source in direct_node_ids - or target in direct_node_ids - or (not container_id and has_unknown_endpoint) - ): - direct_edge_configs.append(edge_config) - if ( - source in subtree_node_ids - or target in subtree_node_ids - or (not container_id and has_unknown_endpoint) - ): - subtree_edge_configs.append(edge_config) - - scoped_graph_config = dict(graph_config) - scoped_graph_config["nodes"] = [ - node_config - for node_config in node_configs - if node_config.get("id") in subtree_node_ids - ] - scoped_graph_config["edges"] = subtree_edge_configs - direct_node_configs = [ - node_config - for node_config in node_configs - if node_config.get("id") in direct_node_ids - ] - return direct_node_configs, direct_edge_configs, scoped_graph_config - - @classmethod - def _promote_fail_branch_nodes(cls, nodes: dict[str, Node]) -> None: - """Promote nodes configured with FAIL_BRANCH error strategy - to branch execution type. - - :param nodes: mapping of node ID to node instance - """ - for node in nodes.values(): - if node.error_strategy == ErrorStrategy.FAIL_BRANCH: - node.execution_type = NodeExecutionType.BRANCH - - @classmethod - def mark_inactive_root_branches( - cls, - nodes: dict[str, Node], - edges: dict[str, Edge], - in_edges: dict[str, list[str]], - out_edges: dict[str, list[str]], - active_root_id: str, - ) -> None: - """Mark nodes and edges that belong to inactive root branches.""" - cls._mark_inactive_root_branches( - nodes, - edges, - in_edges, - out_edges, - active_root_id, - ) - - @classmethod - def _mark_inactive_root_branches( - cls, - nodes: dict[str, Node], - edges: dict[str, Edge], - in_edges: dict[str, list[str]], - out_edges: dict[str, list[str]], - active_root_id: str, - ) -> None: - """Mark nodes and edges from inactive root branches as skipped. - - Algorithm: - 1. Mark inactive root nodes as skipped - 2. For skipped nodes, mark all their outgoing edges as skipped - 3. For each edge marked as skipped, check its target node: - - If ALL incoming edges are skipped, mark the node as skipped - - Otherwise, leave the node state unchanged - - :param nodes: mapping of node ID to node instance - :param edges: mapping of edge ID to edge instance - :param in_edges: mapping of node ID to incoming edge IDs - :param out_edges: mapping of node ID to outgoing edge IDs - :param active_root_id: ID of the active root node - """ - # Find all top-level root nodes - top_level_roots: list[str] = [ - node.id - for node in nodes.values() - if node.execution_type == NodeExecutionType.ROOT - ] - - # If there's only one root or the active root is not a top-level - # root, no marking is needed - if len(top_level_roots) <= 1 or active_root_id not in top_level_roots: - return - - # Mark inactive root nodes as skipped - inactive_roots: list[str] = [ - root_id for root_id in top_level_roots if root_id != active_root_id - ] - for root_id in inactive_roots: - if root_id in nodes: - nodes[root_id].state = NodeState.SKIPPED - - # Unchecked graphs can contain cycles or missing targets. - visited_node_ids: set[str] = set() - - # Recursively mark downstream nodes and edges - def mark_downstream(node_id: str) -> None: - """Recursively mark downstream nodes and edges as skipped.""" - if node_id in visited_node_ids or nodes[node_id].state != NodeState.SKIPPED: - return - visited_node_ids.add(node_id) - # If this node is skipped, mark all its outgoing edges as skipped - out_edge_ids = out_edges.get(node_id, []) - for edge_id in out_edge_ids: - edge = edges[edge_id] - edge.state = NodeState.SKIPPED - - # Check the target node of this edge - target_node = nodes.get(edge.head) - if target_node is None: - continue - in_edge_ids = in_edges.get(target_node.id, []) - in_edge_states = [edges[eid].state for eid in in_edge_ids] - - # If all incoming edges are skipped, mark the node as skipped - if all(state == NodeState.SKIPPED for state in in_edge_states): - target_node.state = NodeState.SKIPPED - # Recursively process downstream nodes - mark_downstream(target_node.id) - - # Process each inactive root and its downstream nodes - for root_id in inactive_roots: - mark_downstream(root_id) - - @staticmethod - def _validate_subtree_edges( - graph_config: Mapping[str, Any], - container_ids: Mapping[str, str], - ) -> None: - """Validate retained subtree edges before any node is constructed.""" - issues = get_edge_issues( - { - node_config["id"]: container_ids[node_config["id"]] - for node_config in graph_config["nodes"] - }, - ( - Edge( - id=edge_config["id"], - tail=edge_config["source"], - head=edge_config["target"], - source_handle=edge_config.get("sourceHandle", "source"), - ) - for edge_config in graph_config["edges"] - ), - ) + edges_by_id[edge.id] = edge + incoming[edge.target].append(edge) + outgoing[edge.source].append(edge) + issues = get_edge_issues(dict.fromkeys(nodes_by_id, ""), edges_by_id.values()) if issues: raise GraphValidationError(issues) - - @classmethod - def init( - cls, - *, - graph_config: Mapping[str, Any], - node_factory: NodeFactory, - root_node_id: str, - container_id: str = "", - skip_validation: bool = False, - ) -> Graph: - """Initialize a graph with an explicit execution entry point. - - :param graph_config: graph config containing nodes and edges - :param node_factory: factory for creating node instances from config data - :param root_node_id: active root node id - :param container_id: direct container scope to materialize; empty for root - :param skip_validation: bypass endpoint existence, root type, and cycle - checks; input fields, IDs, schemas, and ownership are still validated - - Returns: - Initialized graph instance rooted at `root_node_id`. - - Raises: - ValueError: If the graph has no nodes or `root_node_id` does not exist. - - """ - # Parse configs - node_configs, container_ids = cls._normalize_nodes( - _ListObjectDict.validate_python(graph_config.get("nodes", [])), - ) - - direct_node_configs, direct_edge_configs, scoped_graph_config = ( - cls._scope_graph_config( - graph_config=graph_config, - node_configs=node_configs, - edge_configs=cls._prepare_edge_configs( - graph_config, - container_ids, - ), - container_ids=container_ids, - container_id=container_id, - ) - ) - node_factory = node_factory.with_graph_config(scoped_graph_config) - scoped_node_configs = _ListNodeConfigDict.validate_python( - scoped_graph_config["nodes"], + object.__setattr__(self, "nodes", MappingProxyType(nodes_by_id)) + object.__setattr__(self, "edges", MappingProxyType(edges_by_id)) + object.__setattr__(self, "entry_node_ids", entry_node_ids) + object.__setattr__( + self, + "_incoming_edges", + MappingProxyType({key: tuple(items) for key, items in incoming.items()}), ) - execution_types = { - node_config["id"]: node_factory.validate_node(node_config) - for node_config in scoped_node_configs - } - # Every descendant is prevalidated above, so container ownership can be - # checked before direct-frame nodes run constructors or post-init hooks. - for container_node_id in sorted( - { - container_ids[node_config["id"]] - for node_config in scoped_node_configs - if container_ids[node_config["id"]] - } - & execution_types.keys(), - ): - if execution_types[container_node_id] != NodeExecutionType.CONTAINER: - msg = ( - f"Node '{container_node_id}' owns child nodes " - "but is not a container" - ) - raise ValueError(msg) - node_configs_map = cls._parse_node_configs( - _ListNodeConfigDict.validate_python(direct_node_configs), - ) - - if not node_configs_map: - msg = "Graph must have at least one node" - raise ValueError(msg) - - if root_node_id not in node_configs_map: - msg = f"Root node id {root_node_id} not found in the graph" - raise ValueError(msg) - - if not skip_validation: - cls._validate_subtree_edges( - scoped_graph_config, - container_ids, - ) - - # Build edges - edges, in_edges, out_edges = cls._build_edges(direct_edge_configs) - - # Create node instances - nodes = cls._create_node_instances(node_configs_map, node_factory) - # Promote fail-branch nodes to branch execution type at graph level - cls._promote_fail_branch_nodes(nodes) - - # Mark inactive root branches as skipped - cls._mark_inactive_root_branches( - nodes, - edges, - in_edges, - out_edges, - root_node_id, - ) - - # Create and return the graph - graph = cls( - nodes=nodes, - edges=edges, - in_edges=in_edges, - out_edges=out_edges, - root_node=nodes[root_node_id], - graph_config=scoped_graph_config, - node_factory=node_factory, - ) - - if not skip_validation: - # Validate the graph structure using built-in validators - get_graph_validator().validate(graph) - - return graph - - @property - def node_ids(self) -> list[str]: - """Get list of node IDs (compatibility property for existing code) - - :return: list of node IDs - """ - return list(self.nodes.keys()) - - def get_outgoing_edges(self, node_id: str) -> list[Edge]: - """Get all outgoing edges from a node (V2 method) - - :param node_id: node id - - Returns: - All edges whose tail is `node_id`. - - """ - edge_ids = self.out_edges.get(node_id, []) - return [self.edges[eid] for eid in edge_ids if eid in self.edges] - - def get_incoming_edges(self, node_id: str) -> list[Edge]: - """Get all incoming edges to a node (V2 method) - - :param node_id: node id - - Returns: - All edges whose head is `node_id`. - - """ - edge_ids = self.in_edges.get(node_id, []) - return [self.edges[eid] for eid in edge_ids if eid in self.edges] - - -@final -class GraphBuilder: - """Fluent helper for constructing simple graphs, primarily for tests.""" - - def __init__(self, *, graph_cls: type[Graph]) -> None: - self._graph_cls = graph_cls - self._nodes: list[Node] = [] - self._nodes_by_id: dict[str, Node] = {} - self._edges: list[Edge] = [] - self._edge_counter = 0 - - def add_root(self, node: Node) -> GraphBuilder: - """Register the root node. Must be called exactly once.""" - if self._nodes: - msg = "Root node has already been added" - raise ValueError(msg) - self._register_node(node) - self._nodes.append(node) - return self - - def add_node( - self, - node: Node, - *, - from_node_id: str | None = None, - source_handle: str = "source", - ) -> GraphBuilder: - """Append a node and connect it from the specified predecessor.""" - if not self._nodes: - msg = "Root node must be added before adding other nodes" - raise ValueError(msg) - - predecessor_id = from_node_id or self._nodes[-1].id - if predecessor_id not in self._nodes_by_id: - msg = f"Predecessor node '{predecessor_id}' not found" - raise ValueError(msg) - - predecessor = self._nodes_by_id[predecessor_id] - self._register_node(node) - self._nodes.append(node) - - edge_id = f"edge_{self._edge_counter}" - self._edge_counter += 1 - edge = Edge( - id=edge_id, - tail=predecessor.id, - head=node.id, - source_handle=source_handle, + object.__setattr__( + self, + "_outgoing_edges", + MappingProxyType({key: tuple(items) for key, items in outgoing.items()}), ) - self._edges.append(edge) - return self - - def connect( - self, - *, - tail: str, - head: str, - source_handle: str = "source", - ) -> GraphBuilder: - """Connect two existing nodes without adding a new node.""" - if tail not in self._nodes_by_id: - msg = f"Tail node '{tail}' not found" - raise ValueError(msg) - if head not in self._nodes_by_id: - msg = f"Head node '{head}' not found" - raise ValueError(msg) - - edge_id = f"edge_{self._edge_counter}" - self._edge_counter += 1 - edge = Edge(id=edge_id, tail=tail, head=head, source_handle=source_handle) - self._edges.append(edge) - - return self - - def build(self) -> Graph: - """Materialize the graph instance from the accumulated nodes and edges.""" - if not self._nodes: - msg = "Cannot build an empty graph" - raise ValueError(msg) - - nodes = {node.id: node for node in self._nodes} - edges = {edge.id: edge for edge in self._edges} - in_edges: dict[str, list[str]] = defaultdict(list) - out_edges: dict[str, list[str]] = defaultdict(list) - - for edge in self._edges: - out_edges[edge.tail].append(edge.id) - in_edges[edge.head].append(edge.id) - - graph = self._graph_cls( - nodes=nodes, - edges=edges, - in_edges=dict(in_edges), - out_edges=dict(out_edges), - root_node=self._nodes[0], - ) + def __hash__(self) -> int: + return hash(( + frozenset(self.nodes.items()), + frozenset(self._outgoing_edges.items()), + self.entry_node_ids, + )) - get_graph_validator().validate(graph) + def node(self, node_id: str) -> NodeDefinition: + return self.nodes[node_id] - return graph + def incoming(self, node_id: str) -> tuple[EdgeDefinition, ...]: + return self._incoming_edges.get(node_id, ()) - def _register_node(self, node: Node) -> None: - if not isinstance(node.id, str) or not node.id: - msg = "Node must have a non-empty string id" - raise ValueError(msg) - if node.id in self._nodes_by_id: - msg = f"Duplicate node id detected: {node.id}" - raise ValueError(msg) - self._nodes_by_id[node.id] = node + def outgoing(self, node_id: str) -> tuple[EdgeDefinition, ...]: + return self._outgoing_edges.get(node_id, ()) diff --git a/src/graphon/graph/validation.py b/src/graphon/graph/validation.py index 8c4146cd..ae9feeab 100644 --- a/src/graphon/graph/validation.py +++ b/src/graphon/graph/validation.py @@ -1,7 +1,7 @@ from __future__ import annotations from abc import abstractmethod -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Container, Iterable, Mapping, Sequence from dataclasses import dataclass from graphlib import CycleError, TopologicalSorter from typing import TYPE_CHECKING, Protocol @@ -9,8 +9,9 @@ from graphon.enums import BuiltinNodeTypes, NodeExecutionType, NodeType if TYPE_CHECKING: - from .edge import Edge - from .graph import Graph + from graphon.runtime.runtime_state.protocol import EdgeProtocol, GraphProtocol + + from .graph import EdgeDefinition @dataclass(frozen=True, slots=True) @@ -34,18 +35,27 @@ def __init__(self, issues: Sequence[GraphValidationIssue]) -> None: super().__init__(message) +def check_unique_node_id(node_id: str, existing_ids: Container[str]) -> None: + if node_id in existing_ids: + raise GraphValidationError([ + GraphValidationIssue( + "DUPLICATE_NODE_ID", f"Duplicate node ID: {node_id}", node_id + ) + ]) + + class GraphValidationRule(Protocol): """Protocol that individual validation rules must satisfy.""" @abstractmethod - def validate(self, graph: Graph) -> Sequence[GraphValidationIssue]: + def validate(self, graph: GraphProtocol) -> Sequence[GraphValidationIssue]: """Validate the provided graph and return any discovered issues.""" ... def get_edge_issues( node_scopes: Mapping[str, str], - edges: Iterable[Edge], + edges: Iterable[EdgeDefinition | EdgeProtocol], ) -> list[GraphValidationIssue]: """Check edge fields, endpoints, and cycles without constructing nodes. @@ -59,18 +69,24 @@ def get_edge_issues( Returns: Issues for invalid edges or a cycle; empty for a valid graph. """ + from .graph import EdgeDefinition # ruff: ignore[import-outside-top-level] + issues: list[GraphValidationIssue] = [] predecessors: dict[str, list[str]] = {node_id: [] for node_id in node_scopes} for edge in edges: + if isinstance(edge, EdgeDefinition): + source, target = edge.source, edge.target + else: + source, target = edge.tail, edge.head if not isinstance(edge.source_handle, str): issues.append( GraphValidationIssue( code="INVALID_EDGE", message=f"Edge {edge.id!r} sourceHandle must be a string.", - node_id=edge.tail, + node_id=source, ) ) - for field, node_id in (("source", edge.tail), ("target", edge.head)): + for field, node_id in (("source", source), ("target", target)): if node_id not in node_scopes: issues.append( GraphValidationIssue( @@ -82,8 +98,8 @@ def get_edge_issues( node_id=node_id, ), ) - if edge.tail in node_scopes and edge.head in node_scopes: - predecessors[edge.head].append(edge.tail) + if source in node_scopes and target in node_scopes: + predecessors[target].append(source) if not issues: try: TopologicalSorter(predecessors).prepare() @@ -103,7 +119,7 @@ def get_edge_issues( class _EdgeValidator: - def validate(self, graph: Graph) -> Sequence[GraphValidationIssue]: + def validate(self, graph: GraphProtocol) -> Sequence[GraphValidationIssue]: return get_edge_issues( dict.fromkeys(graph.nodes, ""), graph.edges.values(), @@ -120,7 +136,7 @@ class _RootNodeValidator: BuiltinNodeTypes.LOOP_START, ) - def validate(self, graph: Graph) -> Sequence[GraphValidationIssue]: + def validate(self, graph: GraphProtocol) -> Sequence[GraphValidationIssue]: root_node = graph.root_node issues: list[GraphValidationIssue] = [] if root_node.id not in graph.nodes: @@ -159,7 +175,7 @@ class GraphValidator: rules: tuple[GraphValidationRule, ...] - def validate(self, graph: Graph) -> None: + def validate(self, graph: GraphProtocol) -> None: """Validate the graph against all configured rules.""" issues: list[GraphValidationIssue] = [] for rule in self.rules: diff --git a/src/graphon/graph_builder/__init__.py b/src/graphon/graph_builder/__init__.py new file mode 100644 index 00000000..49ad8f44 --- /dev/null +++ b/src/graphon/graph_builder/__init__.py @@ -0,0 +1,3 @@ +from .builder import GraphBuilder + +__all__ = ["GraphBuilder"] diff --git a/src/graphon/graph_builder/builder.py b/src/graphon/graph_builder/builder.py new file mode 100644 index 00000000..09009746 --- /dev/null +++ b/src/graphon/graph_builder/builder.py @@ -0,0 +1,60 @@ +"""Build Graph definitions in Python.""" + +from collections.abc import Iterable, Mapping +from typing import Any, final + +from graphon.graph import EdgeDefinition, Graph, GraphReference, NodeDefinition +from graphon.graph.validation import check_unique_node_id + + +@final +class GraphBuilder: + """Register nodes and connect their local IDs in the desired edge order.""" + + def __init__(self, *, entry_types: Iterable[tuple[str, str]] = ()) -> None: + self._entry_types = frozenset(entry_types) + self._nodes_by_id: dict[str, NodeDefinition] = {} + self._edges: list[EdgeDefinition] = [] + + def add_node( + self, + node_id: str, + node_type: str, + *, + version: str = "1", + config: Mapping[str, Any] | None = None, + call_target: Graph | GraphReference | None = None, + ) -> str: + """Register a node and return the ID that connects it to other nodes.""" + node = NodeDefinition( + node_id, + node_type, + version=version, + config={} if config is None else config, + call_target=call_target, + ) + check_unique_node_id(node.id, self._nodes_by_id) + self._nodes_by_id[node.id] = node + return node.id + + def connect( + self, source: str, target: str, *, source_handle: str = "source" + ) -> None: + """Add a directed edge between two registered nodes.""" + if source not in self._nodes_by_id: + msg = f"Unknown source node: {source!r}" + raise ValueError(msg) + if target not in self._nodes_by_id: + msg = f"Unknown target node: {target!r}" + raise ValueError(msg) + self._edges.append( + EdgeDefinition(f"edge_{len(self._edges)}", source, target, source_handle) + ) + + def build(self) -> Graph: + """Return an immutable snapshot of the current nodes and edges.""" + return Graph( + nodes=self._nodes_by_id.values(), + edges=self._edges, + entry_types=self._entry_types, + ) diff --git a/src/graphon/nodes/base/node.py b/src/graphon/nodes/base/node.py index b641b6e1..46dbcfc8 100644 --- a/src/graphon/nodes/base/node.py +++ b/src/graphon/nodes/base/node.py @@ -75,6 +75,7 @@ ) from graphon.nodes.container_effects import ContainerAwaitRequest, ContainerRunResult from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState _MISSING_RUN_CONTEXT_VALUE = object() @@ -595,7 +596,7 @@ def __init__( data: NodeDataT, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, ) -> None: if not node_id: msg = "node_id is required" @@ -607,7 +608,7 @@ def __init__( self.workflow_id = init_params.workflow_id self.graph_config = init_params.graph_config self.workflow_call_depth = init_params.call_depth - self.runtime_state = runtime_state + self.runtime_state = runtime_state.read_only_view self.state: NodeState = NodeState.UNKNOWN # node execution state self._node_id = node_id diff --git a/src/graphon/nodes/code/code_node.py b/src/graphon/nodes/code/code_node.py index 12b6f4a1..baedc793 100644 --- a/src/graphon/nodes/code/code_node.py +++ b/src/graphon/nodes/code/code_node.py @@ -12,6 +12,7 @@ from graphon.nodes.code.limits import CodeNodeLimits from graphon.nodes.code.protocols import CodeExecutorProtocol from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.segments import ArrayFileSegment from graphon.variables.types import SegmentType @@ -73,7 +74,7 @@ def __init__( data: CodeNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, code_executor: CodeExecutorProtocol, code_limits: CodeNodeLimits, ) -> None: diff --git a/src/graphon/nodes/document_extractor/node.py b/src/graphon/nodes/document_extractor/node.py index 19832a9c..8b4ce6e7 100644 --- a/src/graphon/nodes/document_extractor/node.py +++ b/src/graphon/nodes/document_extractor/node.py @@ -41,6 +41,7 @@ from graphon.node_events.base import NodeRunResult from graphon.nodes.base.node import Node from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.segments import ArrayFileSegment, ArrayStringSegment, FileSegment @@ -293,7 +294,7 @@ def __init__( data: DocumentExtractorNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, unstructured_api_config: UnstructuredApiConfig | None = None, http_client: HttpClientProtocol | None = None, ) -> None: diff --git a/src/graphon/nodes/factory.py b/src/graphon/nodes/factory.py new file mode 100644 index 00000000..b84a0f57 --- /dev/null +++ b/src/graphon/nodes/factory.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Mapping +from typing import Any, Protocol + +from graphon.entities.graph_config import NodeConfigDict +from graphon.enums import NodeExecutionType +from graphon.nodes.base.node import Node +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper + + +class NodeFactory(Protocol): + """Protocol for creating Node instances from node data dictionaries. + + A host supplies the node implementations and dependencies for each frame. + """ + + @abstractmethod + def with_runtime_state( + self, + runtime_state: ReadOnlyRuntimeStateWrapper, + ) -> NodeFactory: + """Return a factory bound to one execution frame's runtime state. + + Container execution creates a separate :class:`RuntimeState` for every + child frame before constructing its scoped graph. Implementations must + ensure every node created by the returned factory uses ``runtime_state`` + instead of the parent frame's state. Stateful factories should return an + independent copy; factories that do not retain runtime state may return + themselves. + + Args: + runtime_state: Read-only view of the frame being constructed. + + Returns: + A factory ready to construct nodes for exactly that execution frame. + + """ + ... + + @abstractmethod + def with_graph_config( + self, + graph_config: Mapping[str, Any], + ) -> NodeFactory: + """Return a factory whose nodes receive one frame's scoped graph config. + + FrameGraph scopes are established before node construction because + :meth:`Node.post_init` runs inside the node constructor. Implementations + must copy any factory-owned :class:`InitParams` and replace its + ``graph_config`` rather than mutating configuration shared with parent or + sibling frames. + + Args: + graph_config: Container-subtree configuration visible to the frame. + + Returns: + A factory ready to construct nodes for exactly that graph scope. + + """ + ... + + @abstractmethod + def validate_node(self, node_config: NodeConfigDict) -> NodeExecutionType: + """Validate one node against the concrete schema selected by this factory. + + Validation must resolve the same implementation and version as + :meth:`create_node`, but it must not construct a node, initialize runtime + dependencies, invoke ``post_init()``, or mutate execution state. FrameGraph + calls this method for every node in the visible container subtree before + constructing any direct-frame node, which makes malformed descendants + fail before graph execution can produce side effects. + + Args: + node_config: Base-validated node configuration to resolve and validate. + + Returns: + The execution type declared by the resolved node implementation. + + Raises: + ValueError: If the node implementation is unknown or its concrete data + schema is invalid. + + """ + ... + + @abstractmethod + def create_node(self, node_config: NodeConfigDict) -> Node: + """Create a Node instance from node configuration data. + + :param node_config: node configuration dictionary containing type and other data + :return: initialized Node instance + :raises ValueError: if node type is unknown or no + implementation exists for the resolved version + :raises ValidationError: if node_config does not satisfy + NodeConfigDict/BaseNodeData validation + """ + ... diff --git a/src/graphon/nodes/http_request/executor.py b/src/graphon/nodes/http_request/executor.py index 6a2c71d9..86a5b356 100644 --- a/src/graphon/nodes/http_request/executor.py +++ b/src/graphon/nodes/http_request/executor.py @@ -11,7 +11,7 @@ from graphon.file.enums import FileTransferMethod from graphon.http import HttpClientProtocol, HttpResponse -from graphon.runtime.variable_pool import VariablePool +from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool from graphon.variables.segments import ArrayFileSegment, FileSegment from graphon.variables.template_resolution import convert_template @@ -91,7 +91,7 @@ def __init__( *, node_data: HttpRequestNodeData, timeout: HttpRequestNodeTimeout, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, http_request_config: HttpRequestNodeConfig, max_retries: int | None = None, ssl_verify: bool | None = None, @@ -289,8 +289,8 @@ def _init_json_body(self, data: Sequence[BodyData]) -> None: def _init_binary_body(self, data: Sequence[BodyData]) -> None: item = self._require_single_body_item(data, body_type="binary") file_selector = item.file - file_variable = self.variable_pool.get_file(file_selector) - if file_variable is None: + file_variable = self.variable_pool.get(file_selector) + if not isinstance(file_variable, FileSegment): msg = f"cannot fetch file with selector {file_selector}" raise FileFetchError(msg) self.content = self._file_manager.download(file_variable.value) diff --git a/src/graphon/nodes/http_request/node.py b/src/graphon/nodes/http_request/node.py index bca6efc7..d0e12e51 100644 --- a/src/graphon/nodes/http_request/node.py +++ b/src/graphon/nodes/http_request/node.py @@ -21,6 +21,7 @@ ToolFileManagerProtocol, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.segments import ArrayFileSegment @@ -57,7 +58,7 @@ def __init__( data: HttpRequestNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, http_request_config: HttpRequestNodeConfig, dependencies: HttpRequestNodeDependencies | None = None, http_client: HttpClientProtocol | None = None, diff --git a/src/graphon/nodes/human_input/human_input_node.py b/src/graphon/nodes/human_input/human_input_node.py index 486750df..a99a64f4 100644 --- a/src/graphon/nodes/human_input/human_input_node.py +++ b/src/graphon/nodes/human_input/human_input_node.py @@ -13,6 +13,7 @@ from graphon.node_events.node import PauseRequestedEvent, StreamCompletedEvent from graphon.nodes.base.node import Node from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.segments import Segment @@ -42,7 +43,7 @@ def __init__( data: HumanInputNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, hitl_callback: HITLCallback, ) -> None: super().__init__( diff --git a/src/graphon/nodes/llm/llm_utils.py b/src/graphon/nodes/llm/llm_utils.py index a853c90a..284e473a 100644 --- a/src/graphon/nodes/llm/llm_utils.py +++ b/src/graphon/nodes/llm/llm_utils.py @@ -27,7 +27,7 @@ from graphon.model_runtime.memory.prompt_message_memory import PromptMessageMemory from graphon.nodes.base.entities import VariableSelector from graphon.prompt_entities import MemoryConfig -from graphon.runtime.variable_pool import VariablePool +from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool from graphon.template_rendering import Jinja2TemplateRenderer, TemplateRenderError from graphon.variables.segments import ( ArrayAnySegment, @@ -79,7 +79,9 @@ def build_model_identity_inputs( } -def fetch_files(variable_pool: VariablePool, selector: Sequence[str]) -> Sequence[File]: +def fetch_files( + variable_pool: ReadOnlyVariablePool, selector: Sequence[str] +) -> Sequence[File]: variable = variable_pool.get(selector) if variable is None: return [] @@ -247,7 +249,7 @@ def fetch_prompt_messages( memory_config: MemoryConfig | None = None, vision_enabled: bool = False, vision_detail: ImagePromptMessageContent.DETAIL, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, jinja2_variables: Sequence[VariableSelector], context_files: Sequence[File] | None = None, jinja2_template_renderer: Jinja2TemplateRenderer | None = None, @@ -342,7 +344,7 @@ def handle_list_messages( messages: Sequence[LLMNodeChatModelMessage], context: str, jinja2_variables: Sequence[VariableSelector], - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, vision_detail_config: ImagePromptMessageContent.DETAIL, jinja2_template_renderer: Jinja2TemplateRenderer | None = None, ) -> Sequence[PromptMessage]: @@ -419,7 +421,7 @@ def render_jinja2_message( *, template: str, jinja2_variables: Sequence[VariableSelector], - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, jinja2_template_renderer: Jinja2TemplateRenderer | None = None, ) -> str: if not template: @@ -442,7 +444,7 @@ def handle_completion_template( template: LLMNodeCompletionModelPromptTemplate, context: str, jinja2_variables: Sequence[VariableSelector], - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, jinja2_template_renderer: Jinja2TemplateRenderer | None = None, ) -> Sequence[PromptMessage]: if template.edition_type == "jinja2": @@ -619,7 +621,7 @@ def _coerce_resolved_value(raw: str) -> int | float | bool | str: def resolve_completion_params_variables( completion_params: Mapping[str, Any], - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, ) -> dict[str, Any]: """Resolve variable references (``{{#node_id.var#}}``) in string-typed completion params. diff --git a/src/graphon/nodes/llm/node.py b/src/graphon/nodes/llm/node.py index 772e8274..cd2640eb 100644 --- a/src/graphon/nodes/llm/node.py +++ b/src/graphon/nodes/llm/node.py @@ -74,6 +74,7 @@ ) from graphon.prompt_entities import MemoryConfig from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.template_rendering import Jinja2TemplateRenderer from graphon.variables.segments import ( @@ -155,7 +156,7 @@ def __init__( data: LLMNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, credentials_provider: object | None = None, model_factory: object | None = None, model_instance: LLMProtocol, @@ -675,7 +676,7 @@ def _raise_if_polling_deadline_exceeded(deadline: float) -> None: raise LLMNodeError(msg) def _raise_if_polling_aborted(self) -> None: - if self.runtime_state.graph_execution.aborted: + if self.runtime_state.aborted: msg = "workflow execution was aborted" raise LLMNodeError(msg) diff --git a/src/graphon/nodes/loop/loop_node.py b/src/graphon/nodes/loop/loop_node.py index 2afde8a1..bcc46f72 100644 --- a/src/graphon/nodes/loop/loop_node.py +++ b/src/graphon/nodes/loop/loop_node.py @@ -232,7 +232,7 @@ def _extract_loop_node_ids_from_config( """Return nodes governed by the nearest enclosing Loop. Resolve canonical and legacy ownership before walking the hierarchy so - callers can inspect persisted configs before ``Graph.init``. A Loop End + callers can inspect persisted configs before building a frame. A Loop End nested in an Iteration can still stop its surrounding Loop. The walk stops at a different Loop so an inner Loop End never breaks an outer Loop. diff --git a/src/graphon/nodes/parameter_extractor/parameter_extractor_node.py b/src/graphon/nodes/parameter_extractor/parameter_extractor_node.py index e6f44fe1..c1249498 100644 --- a/src/graphon/nodes/parameter_extractor/parameter_extractor_node.py +++ b/src/graphon/nodes/parameter_extractor/parameter_extractor_node.py @@ -44,8 +44,9 @@ PromptMessageSerializerProtocol, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState -from graphon.runtime.variable_pool import VariablePool +from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool from graphon.variables.factory import build_segment_with_type from graphon.variables.template_resolution import convert_template from graphon.variables.types import ArrayValidation, SegmentType @@ -146,7 +147,7 @@ def __init__( data: ParameterExtractorNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, dependencies: _ParameterExtractorNodeDependencies, credentials_provider: object | None = None, model_factory: object | None = None, @@ -162,7 +163,7 @@ def __init__( data: ParameterExtractorNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, dependencies: None = None, credentials_provider: object | None = None, model_factory: object | None = None, @@ -177,7 +178,7 @@ def __init__( data: ParameterExtractorNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, dependencies: _ParameterExtractorNodeDependencies | None = None, credentials_provider: object | None = None, model_factory: object | None = None, @@ -403,7 +404,7 @@ def _prepare_run_context(self) -> _ParameterExtractorRunContext: def _prepare_model_instance( self, *, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, ) -> LLMProtocol: model_instance = self._model_instance model_instance.parameters = llm_utils.resolve_completion_params_variables( @@ -431,7 +432,7 @@ def _build_run_prompt( self, *, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, files: Sequence[File], model_schema_features: Sequence[ModelFeature], @@ -498,7 +499,7 @@ def _generate_function_call_prompt( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, memory: PromptMessageMemory | None, files: Sequence[File], @@ -590,7 +591,7 @@ def _generate_prompt_engineering_prompt( self, data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, memory: PromptMessageMemory | None, files: Sequence[File], @@ -624,7 +625,7 @@ def _generate_prompt_engineering_completion_prompt( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, memory: PromptMessageMemory | None, files: Sequence[File], @@ -657,7 +658,7 @@ def _generate_prompt_engineering_chat_prompt( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, memory: PromptMessageMemory | None, files: Sequence[File], @@ -968,7 +969,7 @@ def _get_function_calling_prompt_template( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, memory: PromptMessageMemory | None, max_token_limit: int = 2000, ) -> list[LLMNodeChatModelMessage]: @@ -1006,7 +1007,7 @@ def get_function_calling_prompt_template( *, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, memory: PromptMessageMemory | None, max_token_limit: int = 2000, ) -> list[LLMNodeChatModelMessage]: @@ -1023,7 +1024,7 @@ def _get_prompt_engineering_prompt_template( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, memory: PromptMessageMemory | None, max_token_limit: int = 2000, ) -> list[LLMNodeChatModelMessage] | LLMNodeCompletionModelPromptTemplate: @@ -1071,7 +1072,7 @@ def _calculate_rest_token( self, node_data: ParameterExtractorNodeData, query: str, - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, model_instance: LLMProtocol, context: str | None, ) -> int: diff --git a/src/graphon/nodes/question_classifier/question_classifier_node.py b/src/graphon/nodes/question_classifier/question_classifier_node.py index 1d1215a8..bb652963 100644 --- a/src/graphon/nodes/question_classifier/question_classifier_node.py +++ b/src/graphon/nodes/question_classifier/question_classifier_node.py @@ -42,6 +42,7 @@ PromptMessageSerializerProtocol, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.template_rendering import Jinja2TemplateRenderer from graphon.utils.json_in_md_parser import parse_and_check_json_markdown @@ -109,7 +110,7 @@ def __init__( data: QuestionClassifierNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, dependencies: QuestionClassifierNodeDependencies | None = None, credentials_provider: object | None = None, model_factory: object | None = None, diff --git a/src/graphon/nodes/runtime.py b/src/graphon/nodes/runtime.py index 5b21c777..3971cc71 100644 --- a/src/graphon/nodes/runtime.py +++ b/src/graphon/nodes/runtime.py @@ -13,7 +13,7 @@ if TYPE_CHECKING: from graphon.nodes.tool.entities import ToolNodeData - from graphon.runtime.variable_pool import VariablePool + from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool class ToolNodeRuntimeProtocol(Protocol): @@ -29,7 +29,7 @@ def get_runtime( *, node_id: str, node_data: ToolNodeData, - variable_pool: VariablePool | None, + variable_pool: ReadOnlyVariablePool | None, node_execution_id: str | None = None, ) -> ToolRuntimeHandle: ... diff --git a/src/graphon/nodes/start/entities.py b/src/graphon/nodes/start/entities.py index 9d207ec2..68a0d89d 100644 --- a/src/graphon/nodes/start/entities.py +++ b/src/graphon/nodes/start/entities.py @@ -4,11 +4,11 @@ from graphon.entities.base_node_data import BaseNodeData from graphon.enums import BuiltinNodeTypes, NodeType -from graphon.variables.input_entities import VariableEntity +from graphon.variables.input_entities import VariableEntity # ty: ignore[deprecated] class StartNodeData(BaseNodeData): """Start Node Data""" type: NodeType = BuiltinNodeTypes.START - variables: Sequence[VariableEntity] = Field(default_factory=list) + variables: Sequence[VariableEntity] = Field(default_factory=list) # ty: ignore[deprecated] diff --git a/src/graphon/nodes/template_transform/template_transform_node.py b/src/graphon/nodes/template_transform/template_transform_node.py index c6daa19c..f13a46ea 100644 --- a/src/graphon/nodes/template_transform/template_transform_node.py +++ b/src/graphon/nodes/template_transform/template_transform_node.py @@ -11,6 +11,7 @@ from graphon.nodes.base.node import Node from graphon.nodes.template_transform.entities import TemplateTransformNodeData from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.template_rendering import ( Jinja2TemplateRenderer, @@ -39,7 +40,7 @@ def __init__( data: TemplateTransformNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, jinja2_template_renderer: Jinja2TemplateRenderer, max_output_length: int | None = None, ) -> None: diff --git a/src/graphon/nodes/tool/tool_node.py b/src/graphon/nodes/tool/tool_node.py index 8950efae..d72226ea 100644 --- a/src/graphon/nodes/tool/tool_node.py +++ b/src/graphon/nodes/tool/tool_node.py @@ -31,8 +31,9 @@ ToolRuntimeParameter, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState -from graphon.runtime.variable_pool import VariablePool +from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool from graphon.variables.segments import ArrayFileSegment from graphon.variables.template_resolution import convert_template @@ -80,7 +81,7 @@ def __init__( data: ToolNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, tool_file_manager: ToolFileManagerProtocol, # TODO @-LAN: See https://github.com/langgenius/graphon/issues/new/choose. # ruff:ignore[line-contains-todo] # Make `runtime` optional once Graphon provides a default tool runtime @@ -122,7 +123,7 @@ def _run(self) -> Generator[NodeEventPayload, None, None]: # Logically, we shouldn't use the node_data.version field for judgment # But for backward compatibility with historical data # this version field judgment is still preserved here. - variable_pool: VariablePool | None = None + variable_pool: ReadOnlyVariablePool | None = None if ( self.node_data.version != "1" or self.node_data.tool_node_version is not None @@ -202,7 +203,7 @@ def _generate_parameters( self, *, tool_parameters: Sequence[ToolRuntimeParameter], - variable_pool: VariablePool, + variable_pool: ReadOnlyVariablePool, node_data: ToolNodeData, for_log: bool = False, ) -> dict[str, Any]: @@ -212,7 +213,7 @@ def _generate_parameters( Args: tool_parameters (Sequence[ToolRuntimeParameter]): The list of tool parameters. - variable_pool (VariablePool): The variable pool containing the variables. + variable_pool: Variables visible to this node. node_data (ToolNodeData): The data associated with the tool node. for_log (bool): Whether to produce log-friendly parameter values. @@ -259,7 +260,7 @@ def _generate_parameters( def _get_tool_runtime( self, *, - variable_pool: VariablePool | None, + variable_pool: ReadOnlyVariablePool | None, node_execution_id: str, ) -> ToolRuntimeHandle: return self._runtime.get_runtime( diff --git a/src/graphon/nodes/variable_assigner/v1/node.py b/src/graphon/nodes/variable_assigner/v1/node.py index 49202fdb..5ac652b6 100644 --- a/src/graphon/nodes/variable_assigner/v1/node.py +++ b/src/graphon/nodes/variable_assigner/v1/node.py @@ -16,6 +16,7 @@ from graphon.nodes.variable_assigner.common import helpers as common_helpers from graphon.nodes.variable_assigner.common.exc import VariableOperatorNodeError from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.types import SegmentType from graphon.variables.variables import ( @@ -40,7 +41,7 @@ def __init__( data: VariableAssignerData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, ) -> None: super().__init__( node_id=node_id, diff --git a/src/graphon/nodes/variable_assigner/v2/node.py b/src/graphon/nodes/variable_assigner/v2/node.py index 2326857a..2bdb5cf6 100644 --- a/src/graphon/nodes/variable_assigner/v2/node.py +++ b/src/graphon/nodes/variable_assigner/v2/node.py @@ -17,6 +17,7 @@ from graphon.nodes.variable_assigner.common import helpers as common_helpers from graphon.nodes.variable_assigner.common.exc import VariableOperatorNodeError from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.variables.consts import SELECTORS_LENGTH from graphon.variables.types import SegmentType @@ -82,7 +83,7 @@ def __init__( data: VariableAssignerNodeData, *, init_params: InitParams, - runtime_state: RuntimeState, + runtime_state: RuntimeState | ReadOnlyRuntimeStateWrapper, ) -> None: super().__init__( node_id=node_id, @@ -141,9 +142,7 @@ def _run(self) -> Generator[NodeEventPayload, None, None]: updated_variable_selectors: list[Sequence[str]] = [] # Preserve intra-node read-after-write behavior without mutating the shared pool # until the engine processes the emitted VariableUpdatedEvent instances. - working_variable_pool = self.runtime_state.variable_pool.model_copy( - deep=True, - ) + working_variable_pool = self.runtime_state.variable_pool.mutable_copy() try: for item in self.node_data.items: diff --git a/src/graphon/protocols/__init__.py b/src/graphon/protocols/__init__.py index cead931f..798024df 100644 --- a/src/graphon/protocols/__init__.py +++ b/src/graphon/protocols/__init__.py @@ -1,5 +1,4 @@ from graphon.file.protocols import WorkflowFileRuntimeProtocol -from graphon.graph.graph import NodeFactory from graphon.graph.validation import GraphValidationRule from graphon.http.protocols import HttpClientProtocol, HttpResponseProtocol from graphon.model_runtime.memory.prompt_message_memory import PromptMessageMemory @@ -18,6 +17,7 @@ ) from graphon.model_runtime.protocols.tts_runtime import TTSModelRuntime from graphon.nodes.code.protocols import CodeExecutorProtocol +from graphon.nodes.factory import NodeFactory from graphon.nodes.llm.protocols import CredentialsProvider, ModelFactory from graphon.nodes.llm.runtime_protocols import ( LLMPollingCapableProtocol, diff --git a/src/graphon/runtime/read_only_wrappers.py b/src/graphon/runtime/read_only_wrappers.py index 1f49c2df..09fb58cd 100644 --- a/src/graphon/runtime/read_only_wrappers.py +++ b/src/graphon/runtime/read_only_wrappers.py @@ -2,14 +2,18 @@ from collections.abc import Mapping, Sequence from copy import deepcopy +from typing import TYPE_CHECKING from graphon.model_runtime.entities.llm_entities import LLMUsage -from graphon.variables.segments import Segment +from graphon.variables.segments import FileSegment, Segment +from graphon.variables.variables import Variable -from .runtime_state import RuntimeState from .runtime_state_protocol import ReadOnlyVariablePool from .variable_pool import VariablePool +if TYPE_CHECKING: + from .runtime_state import RuntimeState + class ReadOnlyVariablePoolWrapper(ReadOnlyVariablePool): """Provide defensive, read-only access to ``VariablePool``.""" @@ -26,6 +30,19 @@ def get_by_prefix(self, prefix: str, /) -> Mapping[str, object]: """Return a copy of all variables stored under the given prefix.""" return self._variable_pool.get_by_prefix(prefix) + def get_variable(self, selector: Sequence[str], /) -> Variable | None: + return deepcopy(self._variable_pool.get_variable(selector)) + + def get_file(self, selector: Sequence[str], /) -> FileSegment | None: + return deepcopy(self._variable_pool.get_file(selector)) + + def flatten(self, *, unprefixed_node_id: str | None = None) -> Mapping[str, object]: + return self._variable_pool.flatten(unprefixed_node_id=unprefixed_node_id) + + def mutable_copy(self) -> VariablePool: + """Create a private pool for several assignments within one node.""" + return self._variable_pool.model_copy(deep=True) + class ReadOnlyRuntimeStateWrapper: """Expose a defensive, read-only view of ``RuntimeState``.""" @@ -34,10 +51,19 @@ def __init__(self, state: RuntimeState) -> None: self._state = state self._variable_pool_wrapper = ReadOnlyVariablePoolWrapper(state.variable_pool) + @property + def read_only_view(self) -> ReadOnlyRuntimeStateWrapper: + """Return the owning frame's shared view.""" + return self._state.read_only_view + @property def variable_pool(self) -> ReadOnlyVariablePoolWrapper: return self._variable_pool_wrapper + @property + def aborted(self) -> bool: + return self._state.graph_execution.aborted + @property def start_at(self) -> float: return self._state.start_at diff --git a/src/graphon/runtime/runtime_state/state.py b/src/graphon/runtime/runtime_state/state.py index 16bcd3fd..87559089 100644 --- a/src/graphon/runtime/runtime_state/state.py +++ b/src/graphon/runtime/runtime_state/state.py @@ -12,6 +12,7 @@ ContainerRunState, FrameRuntimeData, ) +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.ready_queue import InMemoryReadyQueue, ReadyQueue, ReadyTask from graphon.runtime.variable_pool import VariablePool @@ -104,6 +105,12 @@ def __init__( self._has_pending_graph_state = False self._graph_state_migration: GraphStateMigration | None = None self._container_state_lock = threading.Lock() + self._read_only_view = ReadOnlyRuntimeStateWrapper(self) + + @property + def read_only_view(self) -> ReadOnlyRuntimeStateWrapper: + """The live read-only view shared by this frame's nodes.""" + return self._read_only_view @property def variable_pool(self) -> VariablePool: diff --git a/src/graphon/runtime/variable_pool.py b/src/graphon/runtime/variable_pool.py index 81a98d56..3e9a6a94 100644 --- a/src/graphon/runtime/variable_pool.py +++ b/src/graphon/runtime/variable_pool.py @@ -10,6 +10,7 @@ from graphon.file import file_manager from graphon.file.enums import FileAttribute from graphon.file.models import File +from graphon.variables.address import VariableAddress from graphon.variables.consts import SELECTORS_LENGTH from graphon.variables.factory import ( build_segment, @@ -35,14 +36,7 @@ class VariablePool(BaseModel): # Node namespaces retain their ownership across pool copies and snapshots. node_ids: frozenset[str] = Field(default_factory=frozenset) - # Variable dictionary is a dictionary for looking up variables by their selector. - # The first element of the selector is the node id. - # It's the first-level key in the dictionary. - # Other elements of the selector are keys in the second-level dictionary. - # To get the key, we hash the elements of the selector except the first one. - # - # The `variable_dictionary` is the source of truth for the runtime - # value of variables. + # Stored variables are indexed by scope, then by name. variable_dictionary: defaultdict[ str, Annotated[dict[str, Variable], Field(default_factory=dict)], @@ -144,53 +138,10 @@ def _ingest_legacy_rag_variables( self.add((self._RAG_PIPELINE_VARIABLE_NODE_ID, node_id), value) def add(self, selector: Sequence[str], value: Any, /) -> None: - """Add a variable to the variable pool. - - This method accepts a selector path and a value, converting the value - to a Variable object if necessary before storing it in the pool. - - Args: - selector: A two-element sequence containing [node_id, variable_name]. - The selector must have exactly 2 elements to be valid. - value: The value to store. Can be a Variable, Segment, or any value - that can be converted to a Segment (str, int, float, - dict, list, File). - - Raises: - ValueError: If selector length is not exactly 2 elements. - - Note: - While non-Segment values are currently accepted and automatically - converted, it's recommended to pass Segment or Variable objects directly. - - """ - if len(selector) != SELECTORS_LENGTH: - msg = ( - f"Invalid selector: expected {SELECTORS_LENGTH} elements " - f"(node_id, variable_name), got {len(selector)} elements" - ) - raise ValueError(msg) - - match value: - case Segment(): - variable = segment_to_variable(segment=value, selector=selector) - case _: - segment = build_segment(value) - variable = segment_to_variable(segment=segment, selector=selector) - - node_id, name = self._selector_to_keys(selector) - self.variable_dictionary[node_id][name] = variable - - @classmethod - def _selector_to_keys(cls, selector: Sequence[str]) -> tuple[str, str]: - return selector[0], selector[1] - - def _has(self, selector: Sequence[str]) -> bool: - node_id, name = self._selector_to_keys(selector) - return ( - node_id in self.variable_dictionary - and name in self.variable_dictionary[node_id] - ) + """Bind a variable, segment or Python value at the address (scope, name).""" + address = VariableAddress.from_selector(selector) + variable = segment_to_variable(segment=build_segment(value), selector=address) + self.variable_dictionary[address.scope][address.name] = variable def get(self, selector: Sequence[str], /) -> Segment | None: """Retrieve a variable's value from the pool as a Segment. @@ -211,12 +162,7 @@ def get(self, selector: Sequence[str], /) -> Segment | None: file attribute is requested. """ - if len(selector) < SELECTORS_LENGTH: - return None - - node_id, name = self._selector_to_keys(selector) - node_map = self.variable_dictionary.get(node_id) - segment = node_map.get(name) if node_map is not None else None + segment = self.get_variable(selector[:SELECTORS_LENGTH]) if segment is None or len(selector) == SELECTORS_LENGTH: return segment @@ -235,11 +181,11 @@ def get(self, selector: Sequence[str], /) -> Segment | None: def get_variable(self, selector: Sequence[str], /) -> Variable | None: """Retrieve a stored top-level variable without attribute traversal.""" - if len(selector) != SELECTORS_LENGTH: - return None - node_id, name = self._selector_to_keys(selector) - node_map = self.variable_dictionary.get(node_id) - return node_map.get(name) if node_map is not None else None + match selector: + case [str(scope), str(name)]: + return self.variable_dictionary.get(scope, {}).get(name) + case _: + return None def _get_file_attribute_segment( self, @@ -306,19 +252,13 @@ def _get_nested_attribute( return result def remove(self, selector: Sequence[str], /) -> None: - """Remove variables from the variable pool based on the given selector. + """Remove the single variable at this address, if present.""" + scope, name = VariableAddress.from_selector(selector) + self.variable_dictionary.get(scope, {}).pop(name, None) - Args: - selector (Sequence[str]): A sequence of strings representing the selector. - - """ - if not selector: - return - if len(selector) == 1: - self.variable_dictionary[selector[0]] = {} - return - key, hash_key = self._selector_to_keys(selector) - self.variable_dictionary[key].pop(hash_key, None) + def clear_scope(self, scope: str, /) -> None: + """Remove all variables in this scope, retaining its node ownership.""" + self.variable_dictionary.pop(scope, None) def get_file(self, selector: Sequence[str], /) -> FileSegment | None: segment = self.get(selector) diff --git a/src/graphon/variables/__init__.py b/src/graphon/variables/__init__.py index 82a72fbb..c4cabee2 100644 --- a/src/graphon/variables/__init__.py +++ b/src/graphon/variables/__init__.py @@ -1,3 +1,4 @@ +from .address import VariableAddress from .factory import ( TypeMismatchError, UnsupportedSegmentTypeError, @@ -5,7 +6,7 @@ build_segment_with_type, segment_to_variable, ) -from .input_entities import VariableEntity, VariableEntityType +from .input_entities import VariableEntity, VariableEntityType # ty: ignore[deprecated] from .segment_group import SegmentGroup from .segments import ( ArrayAnySegment, @@ -76,6 +77,7 @@ "TypeMismatchError", "UnsupportedSegmentTypeError", "Variable", + "VariableAddress", "VariableBase", "VariableEntity", "VariableEntityType", diff --git a/src/graphon/variables/address.py b/src/graphon/variables/address.py new file mode 100644 index 00000000..1c0d8a9e --- /dev/null +++ b/src/graphon/variables/address.py @@ -0,0 +1,18 @@ +from collections.abc import Sequence +from typing import NamedTuple, Self + + +class VariableAddress(NamedTuple): + """The scope and name of one stored variable.""" + + scope: str + name: str + + @classmethod + def from_selector(cls, selector: Sequence[str], /) -> Self: + match selector: + case [str(scope), str(name)]: + return cls(scope, name) + case _: + msg = "A variable address requires two strings: scope and name." + raise ValueError(msg) diff --git a/src/graphon/variables/input_entities.py b/src/graphon/variables/input_entities.py index 055fc7d7..22c9a468 100644 --- a/src/graphon/variables/input_entities.py +++ b/src/graphon/variables/input_entities.py @@ -1,10 +1,11 @@ import json from collections.abc import Sequence from enum import StrEnum -from typing import Any +from typing import Any, final from jsonschema import Draft7Validator, SchemaError from pydantic import BaseModel, Field, field_validator +from typing_extensions import deprecated from graphon.file.enums import ( FileTransferMethod, @@ -29,8 +30,13 @@ class VariableEntityType(StrEnum): JSON_OBJECT = "json_object" +@final +@deprecated( + "Legacy Start input form. Define new input fields and controls in the host.", + category=None, +) class VariableEntity(BaseModel): - """Shared variable entity used by workflow runtime and app configuration.""" + """Input form stored in existing Start configurations. Its schema is frozen.""" # `variable` records the name of the variable in user inputs. variable: str diff --git a/tests/dsl/test_importer.py b/tests/dsl/test_importer.py index 70c10acc..1fa0dd39 100644 --- a/tests/dsl/test_importer.py +++ b/tests/dsl/test_importer.py @@ -408,3 +408,16 @@ def test_sibling_graphs_may_reuse_edge_ids(owner_field: str) -> None: plan = inspect_dsl(dsl) assert plan.load_status == LoadStatus.LOADABLE + + +def test_legacy_assigner_with_items_has_the_version_selected_by_the_node_factory() -> ( + None +): + data = _assigner_data() + graph = inspect_dsl(_graph_dsl_for_node(data)).document.graph + del data["version"] + legacy = inspect_dsl(_graph_dsl_for_node(data)).document.graph + assert graph is not None + assert legacy is not None + assert legacy.node("node").version == "2" + assert legacy == graph diff --git a/tests/dsl/test_node_factory.py b/tests/dsl/test_node_factory.py index 074da5b5..304bb9cf 100644 --- a/tests/dsl/test_node_factory.py +++ b/tests/dsl/test_node_factory.py @@ -559,9 +559,21 @@ def test_slim_dsl_node_factory_rebinds_runtime_state() -> None: assert rebound_factory.init_params is init_params assert rebound_factory.credentials is credentials assert rebound_factory.dependencies is dependencies - assert rebound_factory.runtime_state is rebound_runtime_state + assert rebound_factory.runtime_state is rebound_runtime_state.read_only_view assert rebound_factory.slim_client_config == factory.slim_client_config - assert node.runtime_state is rebound_runtime_state + pool = node.runtime_state.variable_pool + assert pool.get_by_prefix("start") == {"query": "after"} + rebound_runtime_state.variable_pool.add(("start", "profile"), {"tags": ["old"]}) + profile = pool.get(("start", "profile")) + assert profile is not None + profile.value["tags"].append("new") + assert rebound_runtime_state.variable_pool.get_by_prefix("start")["profile"] == { + "tags": ["old"] + } + assert not hasattr(pool, "add") + assert not hasattr(pool, "remove") + assert not hasattr(pool, "clear_scope") + assert not hasattr(pool, "variable_dictionary") @pytest.mark.parametrize( diff --git a/tests/engine/test_cooperative_container_execution.py b/tests/engine/test_cooperative_container_execution.py index 66a1d463..a18fe6d4 100644 --- a/tests/engine/test_cooperative_container_execution.py +++ b/tests/engine/test_cooperative_container_execution.py @@ -11,6 +11,7 @@ from graphon.engine.event.node_failure import NodeFailureHandler from graphon.engine.frame import ExecutionFrame, FrameRegistry +from graphon.engine.frame_graph import FrameGraph from graphon.engine.layer import Layer from graphon.engine.ready_queue.entities import ( ResumeTask, @@ -35,7 +36,6 @@ NodeExecutionType, WorkflowNodeExecutionStatus, ) -from graphon.graph.graph import Graph from graphon.node_events.base import NodeRunResult from graphon.nodes.base.node import Node from graphon.nodes.container_effects import ( @@ -54,7 +54,7 @@ def _execution_frame( *, frame_id: str, - graph: Graph, + graph: FrameGraph, runtime_state: RuntimeState, ) -> ExecutionFrame: scheduler = Scheduler(graph, runtime_state, frame_id) @@ -303,7 +303,7 @@ def resume_container( ) container_node = ContainerNode() - graph = Graph( + graph = FrameGraph( nodes={"loop": cast(Node, container_node)}, root_node=cast(Node, container_node), ) @@ -443,7 +443,7 @@ def resume_container( frame_registry = FrameRegistry() container_node = ContainerNode() graph_node = cast(Node, container_node) - parent_graph = Graph( + parent_graph = FrameGraph( nodes={"loop": graph_node}, root_node=graph_node, ) diff --git a/tests/engine/test_dispatch_patterns.py b/tests/engine/test_dispatch_patterns.py index 47ef1823..7492107f 100644 --- a/tests/engine/test_dispatch_patterns.py +++ b/tests/engine/test_dispatch_patterns.py @@ -30,6 +30,7 @@ from graphon.engine.event.processor import NodeEventProcessor from graphon.engine.event.stream import EventStream from graphon.engine.frame import ExecutionFrame, FrameRegistry +from graphon.engine.frame_graph import FrameGraph from graphon.engine.layer import ExecutionLimitsLayer, Layer from graphon.engine.ready_queue.entities import ( ReadyTask, @@ -61,6 +62,7 @@ GraphEdgeSkippedEvent, GraphEdgeTakenEvent, ) +from graphon.entities.graph_config import NodeConfigDict from graphon.entities.pause_reason import HitlRequired, SchedulingPause from graphon.enums import ( BuiltinNodeTypes, @@ -68,9 +70,7 @@ ErrorStrategy, NodeExecutionType, NodeState, - NodeType, ) -from graphon.graph.graph import Graph, NodeFactory from graphon.model_runtime.entities.llm_entities import LLMUsage from graphon.node_events.base import NodeRunResult from graphon.nodes.container_effects import ( @@ -79,9 +79,11 @@ IterationFrameRequest, build_container_value, ) +from graphon.nodes.factory import NodeFactory from graphon.nodes.human_input.entities import PauseRequested from graphon.nodes.human_input.human_input_node import HumanInputNode from graphon.nodes.iteration.iteration_node import IterationNode +from graphon.nodes.start.start_node import StartNode from graphon.runtime.container_state import ( CustomContainerFrameState, CustomContainerRunState, @@ -94,9 +96,11 @@ ) from graphon.runtime.execution import GraphExecution from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.runtime.variable_pool import VariablePool from graphon.variables.variables import IntegerVariable, StringVariable +from tests.helpers import build_init_params def _variable_value( @@ -111,7 +115,7 @@ def _variable_value( def _execution_frame( *, frame_id: str, - graph: Graph, + graph: FrameGraph, runtime_state: object | None = None, scheduler: object | None = None, failure_handler: object | None = None, @@ -309,7 +313,7 @@ def validate_node( def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> "_FrameFactory": _ = runtime_state return self @@ -493,21 +497,21 @@ def test_command_processor_directly_handles_builtin_commands() -> None: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, MagicMock()), + graph=cast(FrameGraph, MagicMock()), runtime_state=SimpleNamespace(variable_pool=variable_pool), ), ) frame_registry.register( _execution_frame( frame_id="nested", - graph=cast(Graph, MagicMock()), + graph=cast(FrameGraph, MagicMock()), runtime_state=SimpleNamespace(variable_pool=nested_variable_pool), ), ) frame_registry.register( _execution_frame( frame_id="isolated", - graph=cast(Graph, MagicMock()), + graph=cast(FrameGraph, MagicMock()), runtime_state=SimpleNamespace(variable_pool=isolated_variable_pool), ), ) @@ -602,7 +606,7 @@ def test_scheduler_enqueues_ready_task_for_frame() -> None: nodes={"start": SimpleNamespace(state=NodeState.UNKNOWN)}, ) scheduler = Scheduler( - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), state=runtime_state, frame_id="root", ) @@ -631,7 +635,7 @@ def test_scheduler_defers_ready_task_when_paused() -> None: nodes={"start": SimpleNamespace(state=NodeState.UNKNOWN)}, ) scheduler = Scheduler( - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), state=runtime_state, frame_id="root", ) @@ -657,7 +661,7 @@ def test_scheduler_completion_ignores_other_frame_queue_items() -> None: ) graph = SimpleNamespace(nodes={}) scheduler = Scheduler( - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), state=runtime_state, frame_id="root", ) @@ -682,7 +686,7 @@ def test_pause_defers_queued_tasks_without_losing_frame_progress() -> None: } ) scheduler = Scheduler( - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), state=runtime_state, frame_id="root", ) @@ -889,7 +893,7 @@ def run(self) -> Generator[NodeRunSucceededEvent, None, None]: _execution_frame( frame_id="root", graph=cast( - Graph, + FrameGraph, SimpleNamespace(nodes={"node": BlockingNode()}, graph_config=None), ), runtime_state=runtime_state, @@ -986,7 +990,7 @@ def run(self) -> Generator[NodeRunSucceededEvent, None, None]: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) @@ -1052,7 +1056,7 @@ def test_pause_requested_event_defers_current_task_for_resume() -> None: init_params=init_params, runtime_state=root_runtime_state, ) - root_graph = Graph( + root_graph = FrameGraph( root_node=iteration_node, nodes={"iteration": iteration_node}, ) @@ -1066,7 +1070,7 @@ def test_pause_requested_event_defers_current_task_for_resume() -> None: runtime_state=child_runtime_state, hitl_callback=lambda _context: PauseRequested(session_id="unused"), ) - child_graph = Graph( + child_graph = FrameGraph( root_node=human_node, nodes={"human": human_node}, ) @@ -1179,23 +1183,13 @@ def test_graph_execution_tracks_node_executions_by_frame() -> None: def test_frame_registry_creates_child_frame_with_rebound_runtime() -> None: - @dataclass - class RuntimeBoundNode: - id: str - runtime_state: RuntimeState - - node_type: ClassVar[NodeType] = BuiltinNodeTypes.START - execution_type: ClassVar[NodeExecutionType] = NodeExecutionType.ROOT - error_strategy: ClassVar[None] = None - state: ClassVar[NodeState] = NodeState.UNKNOWN - class RuntimeBoundFactory: - def __init__(self, runtime_state: RuntimeState) -> None: + def __init__(self, runtime_state: ReadOnlyRuntimeStateWrapper) -> None: self.runtime_state = runtime_state def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> "RuntimeBoundFactory": return RuntimeBoundFactory(runtime_state) @@ -1213,10 +1207,15 @@ def validate_node( ) -> NodeExecutionType: """Accept the minimal config and report its root execution type.""" _ = node_config - return RuntimeBoundNode.execution_type - - def create_node(self, node_config: dict[str, object]) -> RuntimeBoundNode: - return RuntimeBoundNode(str(node_config["id"]), self.runtime_state) + return StartNode.execution_type + + def create_node(self, node_config: NodeConfigDict) -> StartNode: + return StartNode( + node_id=node_config["id"], + data=StartNode.validate_node_data(node_config["data"]), + init_params=build_init_params(), + runtime_state=self.runtime_state, + ) graph_config = { "nodes": [{"id": "start", "data": {"type": BuiltinNodeTypes.START}}], @@ -1231,9 +1230,9 @@ def create_node(self, node_config: dict[str, object]) -> RuntimeBoundNode: ready_queue=ready_queue, graph_execution=graph_execution, ) - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, - node_factory=cast(Any, RuntimeBoundFactory(root_runtime_state)), + node_factory=cast(Any, RuntimeBoundFactory(root_runtime_state.read_only_view)), root_node_id="start", ) frame_registry = FrameRegistry() @@ -1252,9 +1251,16 @@ def create_node(self, node_config: dict[str, object]) -> RuntimeBoundNode: variable_pool=VariablePool(), ) + assert type(child_frame.graph).__module__.startswith("graphon.engine.") assert child_frame.graph is not root_graph assert child_frame.graph.nodes["start"] is not root_graph.nodes["start"] - assert child_frame.graph.nodes["start"].runtime_state is child_frame.state + root_runtime_state.variable_pool.add(("parent", "private"), "root only") + child_frame.state.variable_pool.add(("start", "child"), "visible in this frame") + child_pool = child_frame.graph.nodes["start"].runtime_state.variable_pool + assert child_pool.get_by_prefix("start") == {"child": "visible in this frame"} + assert not hasattr(child_pool, "add") + assert child_pool.get(("parent", "private")) is None + assert root_runtime_state.variable_pool.get(("start", "child")) is None assert child_frame.state.ready_queue is root_runtime_state.ready_queue assert child_frame.state.graph_execution is graph_execution @@ -1275,7 +1281,7 @@ def test_frame_registry_restores_child_frame() -> None: ready_queue=ready_queue, graph_execution=graph_execution, ) - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=cast(Any, _FrameFactory()), root_node_id="start", @@ -1352,7 +1358,7 @@ def test_frame_registry_rejects_frame_state_with_missing_graph_state_ids() -> No ready_queue=ready_queue, graph_execution=graph_execution, ) - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=cast(Any, _FrameFactory()), root_node_id="start", @@ -1416,7 +1422,7 @@ def test_frame_registry_copies_frame_runtime_data_from_state() -> None: ready_queue=ready_queue, graph_execution=graph_execution, ) - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=cast(Any, _FrameFactory()), root_node_id="start", @@ -1504,7 +1510,7 @@ def run(self) -> Generator[NodeRunStartedEvent, None, None]: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) @@ -1570,14 +1576,14 @@ def run(self) -> Generator[NodeRunStartedEvent, None, None]: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, root_graph), + graph=cast(FrameGraph, root_graph), runtime_state=runtime_state, ), ) frame_registry.register( _execution_frame( frame_id="child", - graph=cast(Graph, child_graph), + graph=cast(FrameGraph, child_graph), runtime_state=runtime_state, ), ) @@ -1647,7 +1653,7 @@ def run(self) -> Generator[NodeRunStartedEvent, None, None]: frame_registry.register( _execution_frame( frame_id="child", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) @@ -1983,7 +1989,7 @@ def test_event_processor_dispatches_task_event_payload() -> None: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, MagicMock()), + graph=cast(FrameGraph, MagicMock()), runtime_state=runtime_state, ), ) @@ -2025,7 +2031,7 @@ def test_event_processor_stamps_frame_owner_on_node_and_edge_events() -> None: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, scheduler=scheduler, container_id="owner", @@ -2083,7 +2089,7 @@ def test_loop_exception_preserves_default_outputs() -> None: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) @@ -2146,7 +2152,7 @@ def test_parallel_iteration_preserves_aggregate_and_response_order() -> None: # "is_parallel": True, "parallel_nums": 2, }) - iteration_node.runtime_state = runtime_state + iteration_node.runtime_state = runtime_state.read_only_view iteration_node.graph_config = graph_config graph = SimpleNamespace( nodes={"iteration": iteration_node}, @@ -2157,7 +2163,7 @@ def test_parallel_iteration_preserves_aggregate_and_response_order() -> None: # frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) @@ -2289,7 +2295,7 @@ def test_iteration_in_tool_workflow_passes_only_host_variable_writes() -> None: frame_registry.create( frame_id="root", container_id="", - graph=Graph.init( + graph=FrameGraph.init( graph_config={ "nodes": [_node_config("tool", "workflow-tool")], "edges": [], @@ -2332,7 +2338,7 @@ def test_iteration_in_tool_workflow_passes_only_host_variable_writes() -> None: frame_registry.create( frame_id="tool-workflow", container_id="tool", - graph=Graph.init( + graph=FrameGraph.init( graph_config={ "nodes": [ _node_config("start", BuiltinNodeTypes.START), @@ -2539,7 +2545,7 @@ def test_iteration_frame_completion_requests_next_index() -> None: "is_parallel": True, "parallel_nums": 2, }) - iteration_node.runtime_state = runtime_state + iteration_node.runtime_state = runtime_state.read_only_view iteration_node.graph_config = graph_config graph = SimpleNamespace( nodes={"iteration": iteration_node}, @@ -2550,7 +2556,7 @@ def test_iteration_frame_completion_requests_next_index() -> None: frame_registry.register( _execution_frame( frame_id="root", - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), runtime_state=runtime_state, ), ) diff --git a/tests/engine/test_file_runtime.py b/tests/engine/test_file_runtime.py index 1ab863bb..f91f09b5 100644 --- a/tests/engine/test_file_runtime.py +++ b/tests/engine/test_file_runtime.py @@ -25,7 +25,6 @@ from graphon.file.file_manager import to_prompt_message_content from graphon.file.protocols import WorkflowFileRuntimeProtocol from graphon.file.runtime import use_workflow_file_runtime -from graphon.graph.graph import Graph from graphon.model_runtime.entities.message_entities import DocumentPromptMessageContent from graphon.nodes.base.entities import OutputVariableEntity from graphon.nodes.base.node import Node @@ -46,6 +45,7 @@ _new_runtime_state, _snapshot_after_hitl_pause, ) +from tests.helpers.frame_graph import build_linear_frame_graph from tests.helpers.workflow_events import final_outputs @@ -75,38 +75,29 @@ def _make_file_engine( params = InitParams( workflow_id="workflow", graph_config={}, run_context={}, call_depth=0 ) - graph = ( - Graph - .new() - .add_root( - StartNode("start", StartNodeData(), init_params=params, runtime_state=state) - ) - .add_node( - DocumentExtractorNode( - "extract", - DocumentExtractorNodeData(variable_selector=["sys", "file"]), - init_params=params, - runtime_state=state, - ) - ) - .add_node( - EndNode( - "end", - EndNodeData( - outputs=[ - OutputVariableEntity( - variable="text", value_selector=["extract", "text"] - ), - OutputVariableEntity( - variable="url", value_selector=["sys", "file", "url"] - ), - ] - ), - init_params=params, - runtime_state=state, - ) - ) - .build() + graph = build_linear_frame_graph( + StartNode("start", StartNodeData(), init_params=params, runtime_state=state), + DocumentExtractorNode( + "extract", + DocumentExtractorNodeData(variable_selector=["sys", "file"]), + init_params=params, + runtime_state=state, + ), + EndNode( + "end", + EndNodeData( + outputs=[ + OutputVariableEntity( + variable="text", value_selector=["extract", "text"] + ), + OutputVariableEntity( + variable="url", value_selector=["sys", "file", "url"] + ), + ] + ), + init_params=params, + runtime_state=state, + ), ) return Engine(graph, state, workers=1, file_runtime=file_runtime) diff --git a/tests/graph/test_graph.py b/tests/engine/test_frame_graph.py similarity index 79% rename from tests/graph/test_graph.py rename to tests/engine/test_frame_graph.py index b07386ce..707e3369 100644 --- a/tests/graph/test_graph.py +++ b/tests/engine/test_frame_graph.py @@ -1,12 +1,7 @@ -from typing import cast from unittest.mock import Mock -import pytest - +from graphon.engine import Edge, FrameGraph from graphon.enums import BuiltinNodeTypes, NodeExecutionType, NodeState -from graphon.graph.edge import Edge -from graphon.graph.graph import Graph -from graphon.graph.validation import GraphValidationError from graphon.nodes.base.node import Node @@ -23,85 +18,6 @@ def create_mock_node( return node -class TestGraphBuilder: - def test_build_runs_default_validators(self) -> None: - root = create_mock_node("root", NodeExecutionType.EXECUTABLE) - - with pytest.raises(GraphValidationError) as exc: - Graph.new().add_root(root).build() - - assert any(issue.code == "INVALID_ROOT" for issue in exc.value.issues) - - @pytest.mark.parametrize("head", ["a", "b"]) - def test_build_rejects_cycles(self, head: str) -> None: - builder = ( - Graph - .new() - .add_root(create_mock_node("start", NodeExecutionType.ROOT)) - .add_node(create_mock_node("a", NodeExecutionType.EXECUTABLE)) - .add_node(create_mock_node("b", NodeExecutionType.EXECUTABLE)) - .connect(tail="b", head=head) - ) - - with pytest.raises(GraphValidationError): - builder.build() - - @pytest.mark.parametrize("node_id", ["", None, 1]) - def test_build_rejects_invalid_node_ids(self, node_id: object) -> None: - builder = Graph.new().add_root( - create_mock_node("start", NodeExecutionType.ROOT), - ) - - with pytest.raises(ValueError, match=r"(?i)node.*id"): - builder.add_node( - create_mock_node(cast(str, node_id), NodeExecutionType.EXECUTABLE), - ).build() - - @pytest.mark.parametrize("source_handle", [None, 1]) - @pytest.mark.parametrize("builder_method", ["add_node", "connect"]) - def test_build_rejects_non_string_handles( - self, - source_handle: object, - builder_method: str, - ) -> None: - builder = Graph.new().add_root( - create_mock_node("start", NodeExecutionType.ROOT), - ) - node = create_mock_node("a", NodeExecutionType.EXECUTABLE) - - if builder_method == "add_node": - with pytest.raises(GraphValidationError): - builder.add_node( - node, - source_handle=cast(str, source_handle), - ).build() - else: - with pytest.raises(GraphValidationError): - builder.add_node(node).connect( - tail="start", - head="a", - source_handle=cast(str, source_handle), - ).build() - - def test_build_accepts_a_dag(self) -> None: - graph = ( - Graph - .new() - .add_root(create_mock_node("start", NodeExecutionType.ROOT)) - .add_node(create_mock_node("a", NodeExecutionType.EXECUTABLE)) - .add_node(create_mock_node("b", NodeExecutionType.EXECUTABLE)) - .connect(tail="start", head="b") - .build() - ) - - assert set(graph.nodes) == {"start", "a", "b"} - assert {(edge.tail, edge.head) for edge in graph.edges.values()} == { - ("start", "a"), - ("a", "b"), - ("start", "b"), - } - - class TestMarkInactiveRootBranches: def test_single_root_no_marking(self) -> None: nodes = { @@ -121,7 +37,7 @@ def test_single_root_no_marking(self) -> None: in_edges = {"child1": ["edge1"]} out_edges = {"root1": ["edge1"]} - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -159,7 +75,7 @@ def test_multiple_roots_mark_inactive(self) -> None: in_edges = {"child1": ["edge1"], "child2": ["edge2"]} out_edges = {"root1": ["edge1"], "root2": ["edge2"]} - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -222,7 +138,7 @@ def test_shared_downstream_node(self) -> None: "child2": ["edge4"], } - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -299,7 +215,7 @@ def test_deep_branch_marking(self) -> None: "level2_b": ["edge5"], } - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -346,7 +262,7 @@ def test_non_root_execution_type(self) -> None: in_edges = {"child1": ["edge1"], "child2": ["edge2"]} out_edges = {"root1": ["edge1"], "non_root": ["edge2"]} - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -362,7 +278,7 @@ def test_non_root_execution_type(self) -> None: assert edges["edge2"].state == NodeState.UNKNOWN def test_empty_graph(self) -> None: - Graph.mark_inactive_root_branches({}, {}, {}, {}, "non_existent") + FrameGraph.mark_inactive_root_branches({}, {}, {}, {}, "non_existent") def test_three_roots_mark_two_inactive(self) -> None: nodes = { @@ -406,7 +322,7 @@ def test_three_roots_mark_two_inactive(self) -> None: "root3": ["edge3"], } - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, @@ -480,7 +396,7 @@ def test_convergent_paths(self) -> None: "mid2": ["edge5"], } - Graph.mark_inactive_root_branches( + FrameGraph.mark_inactive_root_branches( nodes, edges, in_edges, diff --git a/tests/engine/test_frame_graph_imports.py b/tests/engine/test_frame_graph_imports.py new file mode 100644 index 00000000..71e7c318 --- /dev/null +++ b/tests/engine/test_frame_graph_imports.py @@ -0,0 +1,92 @@ +import subprocess # ruff: ignore[suspicious-subprocess-import] +import sys +from importlib.util import find_spec +from pkgutil import resolve_name +from textwrap import dedent + +import pytest + +from graphon import dsl +from graphon.engine import FrameGraph +from graphon.graph import Graph + + +def test_loading_dsl_builds_an_engine_frame_graph() -> None: + engine = dsl.loads(""" +kind: graph +graph: + nodes: + - {id: start, data: {type: start, variables: []}} + edges: [] +""") + + assert isinstance(engine.definition, Graph) + assert isinstance(engine.graph, FrameGraph) + assert type(engine.graph).__module__.startswith("graphon.engine.") + assert engine.graph.root_node.id == "start" + + +@pytest.mark.parametrize( + "qualified_name", + [ + "graphon.graph:Graph.init", + "graphon.graph:Graph.new", + "graphon.graph:Edge", + "graphon.graph:GraphBuilder", + "graphon.graph:NodeFactory", + "graphon.graph.graph:Edge", + "graphon.graph.graph:GraphBuilder", + "graphon.graph.graph:NodeFactory", + ], +) +def test_graph_package_omits_builder_and_execution_apis(qualified_name: str) -> None: + with pytest.raises(AttributeError): + resolve_name(qualified_name) + + +def test_old_graph_edge_module_is_removed() -> None: + assert find_spec("graphon.graph.edge") is None + + +@pytest.mark.parametrize( + "name", + [ + "graphon.engine:FrameGraph.new", + "graphon.engine:GraphBuilder", + "graphon.engine.frame_graph:GraphBuilder", + ], +) +def test_engine_omits_graph_authoring_apis(name: str) -> None: + with pytest.raises(AttributeError): + resolve_name(name) + + +def test_graph_and_builder_import_independently_of_dsl_and_execution() -> None: + script = dedent( + """ + import sys + + from graphon.graph import Graph, NodeDefinition + + start = NodeDefinition("start", "start") + assert Graph(nodes=[start]).node("start") == start + assert "graphon.graph_builder" not in sys.modules + + from graphon.graph_builder import GraphBuilder + + assert GraphBuilder.__module__.split(".")[:2] == ["graphon", "graph_builder"] + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + reply_id = builder.add_node("reply", "answer") + builder.connect(start_id, reply_id) + definition = builder.build() + assert isinstance(definition, Graph) + assert definition.node("reply").node_type == "answer" + assert not any( + name in {"graphon.dsl", "graphon.engine", "graphon.nodes"} + or name.startswith(("graphon.dsl.", "graphon.engine.", "graphon.nodes.")) + for name in sys.modules + ) + """ + ) + subprocess.run([sys.executable, "-c", script], check=True) # ruff: ignore[subprocess-without-shell-equals-true] diff --git a/tests/graph/test_graph_scoping.py b/tests/engine/test_frame_graph_scoping.py similarity index 91% rename from tests/graph/test_graph_scoping.py rename to tests/engine/test_frame_graph_scoping.py index a0222806..923fc80d 100644 --- a/tests/graph/test_graph_scoping.py +++ b/tests/engine/test_frame_graph_scoping.py @@ -8,14 +8,14 @@ import pytest +from graphon.engine import Edge, FrameGraph from graphon.entities.base_node_data import BaseNodeData from graphon.entities.graph_config import NodeConfigDict, NodeConfigDictAdapter from graphon.enums import NodeExecutionType, NodeState -from graphon.graph.edge import Edge -from graphon.graph.graph import Graph from graphon.graph.validation import GraphValidationError from graphon.nodes.base.node import Node from graphon.nodes.loop.loop_start_node import LoopStartNode +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from tests.helpers import build_init_params, build_variable_pool @@ -33,7 +33,7 @@ class _RecordingNodeFactory: def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> _RecordingNodeFactory: """Accept frame state rebinding for this stateless test factory.""" _ = runtime_state @@ -136,7 +136,7 @@ def _config_edges(graph_config: Mapping[str, Any]) -> set[tuple[str, str]]: return {(edge["source"], edge["target"]) for edge in graph_config["edges"]} -def _graph_edges(graph: Graph) -> set[tuple[str, str]]: +def _graph_edges(graph: FrameGraph) -> set[tuple[str, str]]: return {(edge.tail, edge.head) for edge in graph.edges.values()} @@ -147,7 +147,7 @@ def test_invalid_node_ids_fail_before_construction(node_id: object) -> None: node_factory = _RecordingNodeFactory() with pytest.raises(GraphValidationError): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -177,7 +177,7 @@ def test_invalid_edges_fail_before_construction( node_factory = _RecordingNodeFactory() with pytest.raises(GraphValidationError): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -202,7 +202,7 @@ def test_cycles_fail_before_construction( node_factory = _RecordingNodeFactory() with pytest.raises(GraphValidationError, match=r"(?i)cycle") as error: - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -226,7 +226,7 @@ def test_cycles_outside_the_active_path_are_rejected(has_inactive_root: bool) -> node_factory = _RecordingNodeFactory() with pytest.raises(GraphValidationError, match=r"(?i)cycle"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -239,7 +239,7 @@ def test_child_validation_does_not_include_sibling_cycles() -> None: graph_config = _scoped_graph_config() graph_config["edges"].append(_edge("b-end", "b-start")) - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="a-start", @@ -249,14 +249,14 @@ def test_child_validation_does_not_include_sibling_cycles() -> None: assert set(graph.nodes) == {"a-start", "nested-container", "a-end"} -def test_graph_init_preserves_input_and_handles() -> None: +def test_frame_graph_init_preserves_config_and_edge_handles() -> None: graph_config = _scoped_graph_config() graph_config["nodes"].append({"id": "start", "type": "custom-note", "data": {}}) graph_config["edges"][1]["sourceHandle"] = "" graph_config["edges"][2]["sourceHandle"] = "custom" original_graph_config = deepcopy(graph_config) - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -277,7 +277,7 @@ def test_skip_validation_allows_cycle_and_missing_target() -> None: _edge("end", "missing"), ]) - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="end", @@ -298,7 +298,7 @@ def test_skip_validation_still_rejects_invalid_input(invalid_input: str) -> None graph_config["edges"][0]["sourceHandle"] = None with pytest.raises(GraphValidationError): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -310,7 +310,7 @@ def test_invalid_root_is_rejected() -> None: node_factory = _RecordingNodeFactory() with pytest.raises(GraphValidationError) as error: - Graph.init( + FrameGraph.init( graph_config=_scoped_graph_config(), node_factory=node_factory, root_node_id="end", @@ -337,7 +337,7 @@ def create_node(self, node_config: NodeConfigDict) -> Node: ), ) - graph = Graph.init( + graph = FrameGraph.init( graph_config={ "nodes": [_node("entry", node_type="entry-alias")], "edges": [], @@ -351,7 +351,7 @@ def create_node(self, node_config: NodeConfigDict) -> Node: @pytest.mark.parametrize("target", ["missing", "other-start"]) def test_skip_validation_allows_invalid_inactive_branches(target: str) -> None: - graph = Graph.init( + graph = FrameGraph.init( graph_config={ "nodes": [ _node("start", node_type="start"), @@ -376,7 +376,7 @@ def test_duplicate_child_edge_ids_fail_before_construction() -> None: node_factory = _RecordingNodeFactory() with pytest.raises(ValueError, match="Duplicate graph edge ID: duplicate"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -391,7 +391,7 @@ def test_skip_validation_still_rejects_cross_scope_edges() -> None: node_factory = _RecordingNodeFactory() with pytest.raises(ValueError, match="crosses container scopes"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -401,21 +401,21 @@ def test_skip_validation_still_rejects_cross_scope_edges() -> None: assert node_factory.created_node_ids == [] -def test_graph_constructor_accepts_cycle() -> None: +def test_frame_graph_constructor_accepts_cycle() -> None: root = cast(Node, Mock(spec=Node, id="node")) edge = Edge(id="cycle", tail="node", head="node") - graph = Graph(root_node=root, nodes={"node": root}, edges={"cycle": edge}) + graph = FrameGraph(root_node=root, nodes={"node": root}, edges={"cycle": edge}) assert graph.root_node is root assert graph.edges["cycle"] is edge -def test_graph_init_materializes_only_root_scope_by_default() -> None: +def test_frame_graph_init_builds_only_root_scope_by_default() -> None: graph_config = _scoped_graph_config() node_factory = _RecordingNodeFactory() - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -435,7 +435,7 @@ def test_graph_init_materializes_only_root_scope_by_default() -> None: assert graph.graph_config["viewport"] == graph_config["viewport"] -def test_graph_init_preserves_typed_node_container_ownership() -> None: +def test_frame_graph_init_preserves_typed_node_container_ownership() -> None: """Keep ownership when callers provide already validated node configs. ``NodeConfigDictAdapter`` stores ``data`` as ``BaseNodeData`` rather than a @@ -454,7 +454,7 @@ def test_graph_init_preserves_typed_node_container_ownership() -> None: "edges": [_edge("start", "owner")], } - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -492,7 +492,7 @@ def test_typed_node_default_does_not_hide_explicit_legacy_ownership() -> None: "edges": [_edge("start", "owner")], } - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -509,11 +509,11 @@ def test_typed_node_default_does_not_hide_explicit_legacy_ownership() -> None: assert "container_id" not in original_data.model_fields_set -def test_graph_init_scopes_execution_and_retains_only_its_subtree_config() -> None: +def test_child_frame_graph_keeps_local_nodes_and_subtree_config() -> None: graph_config = _scoped_graph_config() node_factory = _RecordingNodeFactory() - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="a-start", @@ -543,14 +543,14 @@ def test_graph_init_scopes_execution_and_retains_only_its_subtree_config() -> No def test_scoped_graphs_preserve_full_config_edge_ids() -> None: """Expose legacy fallback IDs and retain them in every scoped config. - Missing DSL IDs use their original full-config ordinal. Graph initialization + Missing DSL IDs use their original full-config ordinal. Frame construction writes those IDs only to copied configs so callers are not mutated, while later child and nested materializations reuse the public ``id`` field. """ graph_config = _scoped_graph_config() node_factory = _RecordingNodeFactory() - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -577,7 +577,7 @@ def test_scoped_graphs_preserve_full_config_edge_ids() -> None: "__graphon_edge_id" not in edge for edge in root_graph.graph_config["edges"] ) - child_graph = Graph.init( + child_graph = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=node_factory, root_node_id="a-start", @@ -596,7 +596,7 @@ def test_scoped_graphs_preserve_full_config_edge_ids() -> None: ("nested-start", "nested-end"), } - nested_graph = Graph.init( + nested_graph = FrameGraph.init( graph_config=child_graph.graph_config, node_factory=node_factory, root_node_id="nested-start", @@ -611,12 +611,12 @@ def test_scoped_graphs_preserve_full_config_edge_ids() -> None: } -def test_graph_init_preserves_public_edge_ids() -> None: +def test_frame_graph_init_preserves_public_edge_ids() -> None: graph_config = _scoped_graph_config() graph_config["edges"][0]["id"] = "start-to-container" graph_config["edges"][3]["id"] = "child-edge" - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -624,7 +624,7 @@ def test_graph_init_preserves_public_edge_ids() -> None: assert "start-to-container" in root_graph.edges assert root_graph.graph_config is not None - child_graph = Graph.init( + child_graph = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=_RecordingNodeFactory(), root_node_id="a-start", @@ -647,14 +647,14 @@ def test_generated_edge_ids_reserve_explicit_ids( ) -> None: """Keep fallback IDs distinct from every supplied public edge ID. - Mixed DSLs may give stable IDs to only some edges. Graph initialization + Mixed DSLs may give stable IDs to only some edges. Frame construction must reserve all supplied IDs before filling omissions so both an explicit ID before an unnamed edge and one later in the config remain loadable. """ graph_config = _scoped_graph_config() graph_config["edges"][explicit_index]["id"] = explicit_id - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -673,7 +673,7 @@ def test_generated_edge_ids_reserve_explicit_ids_only_in_their_graph() -> None: graph_config = _scoped_graph_config() graph_config["edges"][3]["id"] = "edge_0" - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -681,7 +681,7 @@ def test_generated_edge_ids_reserve_explicit_ids_only_in_their_graph() -> None: assert root_graph.edges["edge_0"].tail == "start" assert root_graph.graph_config is not None - child_graph = Graph.init( + child_graph = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=_RecordingNodeFactory(), root_node_id="a-start", @@ -691,13 +691,13 @@ def test_generated_edge_ids_reserve_explicit_ids_only_in_their_graph() -> None: assert child_graph.edges["edge_0"].tail == "a-start" -def test_graph_init_rejects_duplicate_edge_ids_in_one_scope() -> None: +def test_frame_graph_init_rejects_duplicate_edge_ids_in_one_scope() -> None: graph_config = _scoped_graph_config() graph_config["edges"][0]["id"] = "edge-duplicate" graph_config["edges"][1]["id"] = "edge-duplicate" with pytest.raises(ValueError, match="Duplicate graph edge ID: edge-duplicate"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -709,20 +709,20 @@ def test_child_graphs_may_reuse_edge_ids() -> None: graph_config["edges"][3]["id"] = "local-edge" graph_config["edges"][6]["id"] = "local-edge" - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", ) assert root_graph.graph_config is not None - child_a = Graph.init( + child_a = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=_RecordingNodeFactory(), root_node_id="a-start", container_id="container-a", ) - child_b = Graph.init( + child_b = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=_RecordingNodeFactory(), root_node_id="b-start", @@ -734,19 +734,19 @@ def test_child_graphs_may_reuse_edge_ids() -> None: @pytest.mark.parametrize("edge_id", ["", None, 1]) -def test_graph_init_rejects_invalid_public_edge_ids(edge_id: object) -> None: +def test_frame_graph_init_rejects_invalid_public_edge_ids(edge_id: object) -> None: graph_config = _scoped_graph_config() graph_config["edges"][0]["id"] = edge_id with pytest.raises(ValueError, match="must be a non-empty string"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", ) -def test_graph_init_rejects_edges_crossing_container_scopes() -> None: +def test_frame_graph_init_rejects_edges_crossing_container_scopes() -> None: graph_config = _scoped_graph_config() graph_config["edges"].append(_edge("container-a", "a-start")) @@ -757,18 +757,18 @@ def test_graph_init_rejects_edges_crossing_container_scopes() -> None: r"'' and 'container-a'" ), ): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", ) -def test_graph_init_rejects_orphan_scopes_and_unknown_edges() -> None: +def test_frame_graph_init_rejects_missing_owners_and_edge_endpoints() -> None: graph_config = _scoped_graph_config() graph_config["nodes"].append(_node("orphan", container_id="missing")) with pytest.raises(ValueError, match="orphan"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -777,7 +777,7 @@ def test_graph_init_rejects_orphan_scopes_and_unknown_edges() -> None: graph_config = _scoped_graph_config() graph_config["edges"].append(_edge("ghost-a", "ghost-b")) with pytest.raises(GraphValidationError): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -791,7 +791,7 @@ def test_graph_init_rejects_orphan_scopes_and_unknown_edges() -> None: ("loop", "loop_id"), ], ) -def test_graph_init_accepts_container_scope_owners( +def test_frame_graph_init_accepts_container_scope_owners( owner_type: str, ownership_field: str, ) -> None: @@ -813,7 +813,7 @@ def test_graph_init_accepts_container_scope_owners( "edges": [_edge("start", "owner")], } - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -829,12 +829,12 @@ def test_graph_init_accepts_container_scope_owners( assert "container_id" not in graph_config["nodes"][2]["data"] -def test_graph_init_rejects_non_container_scope_owner() -> None: +def test_frame_graph_init_rejects_non_container_scope_owner() -> None: """Reject a child scope whose direct owner cannot create a child frame. Scoping removes child nodes from the parent's executable graph. Allowing an ordinary node to own that scope would therefore make execution succeed while - silently skipping the child, so Graph initialization must fail first. + silently skipping the child, so frame construction must fail first. """ graph_config = { "nodes": [ @@ -852,7 +852,7 @@ def test_graph_init_rejects_non_container_scope_owner() -> None: ValueError, match="Node 'ordinary' owns child nodes but is not a container", ): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="start", @@ -882,7 +882,7 @@ def test_nested_non_container_owner_is_rejected_before_construction() -> None: ValueError, match="Node 'ordinary' owns child nodes but is not a container", ): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=factory, root_node_id="start", @@ -898,7 +898,7 @@ def test_nested_non_container_owner_is_rejected_before_construction() -> None: ("iteration", "iteration", "loop", "loop", "iteration_id"), ], ) -def test_graph_init_accepts_nested_legacy_fields_without_container_id( +def test_frame_graph_init_accepts_nested_legacy_fields_without_container_id( outer_id: str, outer_type: str, inner_id: str, @@ -935,7 +935,7 @@ def test_graph_init_accepts_nested_legacy_fields_without_container_id( ], } - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id=inner_start_id, @@ -955,7 +955,7 @@ def test_graph_init_accepts_nested_legacy_fields_without_container_id( ) -def test_graph_init_rejects_unrelated_legacy_container_owners() -> None: +def test_frame_graph_init_rejects_unrelated_legacy_container_owners() -> None: """Reject two legacy owners when neither container encloses the other.""" graph_config = { "nodes": [ @@ -974,7 +974,7 @@ def test_graph_init_rejects_unrelated_legacy_container_owners() -> None: } with pytest.raises(ValueError, match="ambiguous legacy container owners"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=_RecordingNodeFactory(), root_node_id="nested", diff --git a/tests/graph/test_graph_validation.py b/tests/engine/test_frame_graph_validation.py similarity index 86% rename from tests/graph/test_graph_validation.py rename to tests/engine/test_frame_graph_validation.py index b27141c4..6074f767 100644 --- a/tests/graph/test_graph_validation.py +++ b/tests/engine/test_frame_graph_validation.py @@ -7,14 +7,15 @@ import pytest +from graphon.engine import FrameGraph from graphon.entities.base_node_data import BaseNodeData from graphon.entities.graph_config import NodeConfigDict from graphon.enums import BuiltinNodeTypes, ErrorStrategy, NodeExecutionType, NodeType -from graphon.graph.graph import Graph from graphon.graph.validation import GraphValidationError from graphon.node_events.base import NodeEventPayload, NodeRunResult from graphon.nodes.base.node import Node from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState from graphon.runtime.variable_pool import VariablePool @@ -56,11 +57,11 @@ def _maybe_override_execution_type(self) -> None: @dataclass(slots=True) class _SimpleNodeFactory: init_params: InitParams - runtime_state: RuntimeState + runtime_state: ReadOnlyRuntimeStateWrapper def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> _SimpleNodeFactory: """Copy this test factory with the state owned by a child frame.""" return replace(self, runtime_state=runtime_state) @@ -94,7 +95,7 @@ def create_node(self, node_config: NodeConfigDict) -> _TestNode: @pytest.fixture -def graph_init_dependencies() -> tuple[_SimpleNodeFactory, dict[str, object]]: +def node_factory_and_config() -> tuple[_SimpleNodeFactory, dict[str, object]]: graph_config: dict[str, object] = {"edges": [], "nodes": []} init_params = build_init_params( workflow_id="workflow", @@ -107,15 +108,15 @@ def graph_init_dependencies() -> tuple[_SimpleNodeFactory, dict[str, object]]: ) factory = _SimpleNodeFactory( init_params=init_params, - runtime_state=runtime_state, + runtime_state=runtime_state.read_only_view, ) return factory, graph_config -def test_graph_initialization_runs_default_validators( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], +def test_frame_graph_init_builds_the_configured_nodes( + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "start", @@ -131,7 +132,7 @@ def test_graph_initialization_runs_default_validators( {"source": "start", "target": "answer", "sourceHandle": "success"}, ] - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -142,7 +143,7 @@ def test_graph_initialization_runs_default_validators( def test_child_post_init_sees_only_its_scoped_graph_config( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: """Bind child InitParams before construction invokes the post-init hook. @@ -151,7 +152,7 @@ def test_child_post_init_sees_only_its_scoped_graph_config( before constructing any child node; otherwise custom ``post_init()`` hooks can cache parent and sibling nodes permanently. """ - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "root", @@ -190,14 +191,14 @@ def test_child_post_init_sees_only_its_scoped_graph_config( {"source": "child-start", "target": "child-end"}, ] - root_graph = Graph.init( + root_graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="root", ) assert root_graph.graph_config is not None assert root_graph.node_factory is not None - child_graph = Graph.init( + child_graph = FrameGraph.init( graph_config=root_graph.graph_config, node_factory=root_graph.node_factory, root_node_id="child-start", @@ -225,10 +226,10 @@ def test_node_data_from_mapping_returns_typed_node_data() -> None: assert node_data.execution_type == NodeExecutionType.EXECUTABLE -def test_graph_validation_fails_for_unknown_edge_targets( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], +def test_frame_graph_init_rejects_an_unknown_edge_target( + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "start", @@ -244,7 +245,7 @@ def test_graph_validation_fails_for_unknown_edge_targets( ] with pytest.raises(GraphValidationError) as exc: - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -253,10 +254,10 @@ def test_graph_validation_fails_for_unknown_edge_targets( assert any(issue.code == "MISSING_NODE" for issue in exc.value.issues) -def test_graph_promotes_fail_branch_nodes_to_branch_execution_type( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], +def test_frame_graph_init_promotes_fail_branch_nodes_to_branch_execution_type( + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "start", @@ -279,7 +280,7 @@ def test_graph_promotes_fail_branch_nodes_to_branch_execution_type( {"source": "start", "target": "branch", "sourceHandle": "success"}, ] - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -288,10 +289,10 @@ def test_graph_promotes_fail_branch_nodes_to_branch_execution_type( assert graph.nodes["branch"].execution_type == NodeExecutionType.BRANCH -def test_graph_init_ignores_custom_note_nodes_before_node_data_validation( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], +def test_frame_graph_init_skips_custom_notes_before_validating_node_data( + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "start", @@ -318,7 +319,7 @@ def test_graph_init_ignores_custom_note_nodes_before_node_data_validation( {"source": "start", "target": "answer", "sourceHandle": "success"}, ] - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="start", @@ -329,10 +330,10 @@ def test_graph_init_ignores_custom_note_nodes_before_node_data_validation( assert "note" not in graph.nodes -def test_graph_init_fails_for_unknown_root_node_id( - graph_init_dependencies: tuple[_SimpleNodeFactory, dict[str, object]], +def test_frame_graph_init_rejects_an_unknown_root_node_id( + node_factory_and_config: tuple[_SimpleNodeFactory, dict[str, object]], ) -> None: - node_factory, graph_config = graph_init_dependencies + node_factory, graph_config = node_factory_and_config graph_config["nodes"] = [ { "id": "start", @@ -346,7 +347,7 @@ def test_graph_init_fails_for_unknown_root_node_id( graph_config["edges"] = [] with pytest.raises(ValueError, match="Root node id missing not found in the graph"): - Graph.init( + FrameGraph.init( graph_config=graph_config, node_factory=node_factory, root_node_id="missing", diff --git a/tests/engine/test_frame_observations.py b/tests/engine/test_frame_observations.py index ce94d3a5..93dc2505 100644 --- a/tests/engine/test_frame_observations.py +++ b/tests/engine/test_frame_observations.py @@ -4,7 +4,7 @@ import json from collections import UserDict -from collections.abc import Generator, Sequence +from collections.abc import Generator, Iterator, Sequence from datetime import UTC, datetime from threading import Event, Thread from typing import Any, override @@ -13,7 +13,7 @@ from graphon import engine_events from graphon.dsl import loads -from graphon.engine import Engine +from graphon.engine import Engine, FrameGraph from graphon.engine.command import ( CommandProcessor, UpdateVariablesCommand, @@ -31,9 +31,12 @@ ) from graphon.entities.workflow_start_reason import WorkflowStartReason from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus -from graphon.graph import Graph from graphon.node_events.base import NodeEventPayload, NodeRunResult -from graphon.node_events.node import StreamChunkEvent, StreamCompletedEvent +from graphon.node_events.node import ( + StreamChunkEvent, + StreamCompletedEvent, + VariableUpdatedEvent, +) from graphon.nodes.container_effects import ( ContainerAwaitRequest, ContainerExecutionResult, @@ -112,6 +115,55 @@ def _assert_frame_lifetimes(events: Sequence[EngineEvent]) -> None: assert events.index(finishes[-1]) < len(events) - 1 +def test_node_cannot_change_a_variable_after_yielding_its_write( + monkeypatch: pytest.MonkeyPatch, +) -> None: + engine = loads(_dsl([], [])) + node = engine.graph.nodes["start"] + address = ("conversation", "profile") + engine.runtime_state.variable_pool.add(address, {"tags": []}) + + def update_profile() -> Generator[NodeEventPayload, None, None]: + profile = node.runtime_state.variable_pool.get(address) + assert isinstance(profile, ObjectVariable) + profile.value["tags"].append("requested") + yield VariableUpdatedEvent(variable=profile) + profile.value["tags"].append("after yield") + yield StreamCompletedEvent( + node_run_result=NodeRunResult(status=WorkflowNodeExecutionStatus.SUCCEEDED) + ) + + monkeypatch.setattr(node, "_run", update_profile) + list(engine.run()) + pool = engine.runtime_state.variable_pool + assert pool.get_by_prefix("conversation")["profile"] == {"tags": ["requested"]} + + +@pytest.mark.parametrize("streamed", [False, True]) +def test_node_cannot_change_a_committed_output( + monkeypatch: pytest.MonkeyPatch, streamed: bool +) -> None: + engine = loads(_dsl([], [])) + output = {"tags": ["published"]} + result = NodeRunResult( + status=WorkflowNodeExecutionStatus.SUCCEEDED, outputs={"result": output} + ) + + def stream_result() -> Iterator[StreamCompletedEvent]: + yield StreamCompletedEvent(node_run_result=result) + output["tags"].append("after yield") + + monkeypatch.setattr( + engine.graph.nodes["start"], + "_run", + stream_result if streamed else lambda: result, + ) + list(engine.run()) + output["tags"].append("after completion") + pool = engine.runtime_state.variable_pool + assert pool.get_by_prefix("start")["result"] == {"tags": ["published"]} + + def test_root_baseline_commits_identity_and_detached_values() -> None: engine = loads( _dsl([_node("answer", "answer", answer="ok")], [("start", "answer")]), @@ -242,7 +294,7 @@ def _run(self) -> NodeRunResult: "root", StartNodeData(), init_params=build_init_params(), runtime_state=state ) engine = Engine( - graph=Graph.new().add_root(root).build(), + graph=FrameGraph(root_node=root, nodes={root.id: root}), runtime_state=state, emit_frame_events=False, ) diff --git a/tests/engine/test_iteration_variable_scopes.py b/tests/engine/test_iteration_variable_scopes.py index efc6ca4a..24b59cbb 100644 --- a/tests/engine/test_iteration_variable_scopes.py +++ b/tests/engine/test_iteration_variable_scopes.py @@ -7,14 +7,13 @@ import pytest -from graphon.engine import Engine +from graphon.engine import Engine, FrameGraph from graphon.engine.frame import ExecutionFrame, FrameRegistry from graphon.engine_events.base import NodeEvent from graphon.engine_events.node import NodeRunFailedEvent, NodeRunVariableUpdatedEvent from graphon.entities.base_node_data import BaseNodeData from graphon.entities.graph_config import NodeConfigDict, NodeConfigDictAdapter from graphon.enums import NodeExecutionType, WorkflowNodeExecutionStatus -from graphon.graph import Graph from graphon.node_events.base import NodeRunResult from graphon.node_events.node import StreamCompletedEvent from graphon.nodes.base.node import Node @@ -31,12 +30,18 @@ from graphon.nodes.iteration.iteration_start_node import IterationStartNode from graphon.nodes.start.start_node import StartNode from graphon.nodes.variable_assigner.v2.node import VariableAssignerNode -from graphon.runtime import InitParams, RuntimeState, VariablePool +from graphon.runtime import ( + InitParams, + ReadOnlyRuntimeStateWrapper, + RuntimeState, + VariablePool, +) from graphon.runtime.container_state import ( ContainerFrameState, CustomContainerFrameState, ) from graphon.runtime.ready_queue import ResumeTask +from tests.helpers.frame_graph import build_linear_frame_graph from tests.helpers.workflow_events import final_outputs @@ -80,11 +85,13 @@ def _run(self) -> NodeRunResult: @dataclass(frozen=True) class _NodeFactory: - state: RuntimeState + state: ReadOnlyRuntimeStateWrapper signals: Mapping[str, Event] graph_config: Mapping[str, Any] = field(default_factory=dict) - def with_runtime_state(self, runtime_state: RuntimeState) -> _NodeFactory: + def with_runtime_state( + self, runtime_state: ReadOnlyRuntimeStateWrapper + ) -> _NodeFactory: return replace(self, state=runtime_state) def with_graph_config(self, graph_config: Mapping[str, Any]) -> _NodeFactory: @@ -252,9 +259,9 @@ def handle_request( "edges": [_build_edge_config("start", self.sibling_node_id)], } ) - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, - node_factory=_NodeFactory(state, self.signals), + node_factory=_NodeFactory(state.read_only_view, self.signals), root_node_id="start", ) frame = self.frames.create( @@ -321,7 +328,7 @@ def restore_frame(self, frame_state: ContainerFrameState) -> None: def _run_workflow( *, - root_graph_kind: Literal["builder", "config"] = "config", + root_graph_source: Literal["nodes", "config"] = "config", root_node_id: str = "source", inherit_pool: bool = False, serialize_pool: bool = False, @@ -358,15 +365,15 @@ def _run_workflow( _build_edge_config(root_node_id, "sibling-tool"), _build_edge_config("sibling-tool", "end"), ]) - factory = _NodeFactory(state, signals) - if root_graph_kind == "builder": + factory = _NodeFactory(state.read_only_view, signals) + if root_graph_source == "nodes": start, tool, end = [ factory.create_node(NodeConfigDictAdapter.validate_python(node_config)) for node_config in node_configs ] - graph = Graph.new().add_root(start).add_node(tool).add_node(end).build() + graph = build_linear_frame_graph(start, tool, end) else: - graph = Graph.init( + graph = FrameGraph.init( graph_config={"nodes": node_configs, "edges": edge_configs}, node_factory=factory, root_node_id=root_node_id, @@ -393,13 +400,13 @@ def _run_workflow( return outputs -@pytest.mark.parametrize("root_graph_kind", ["builder", "config"]) +@pytest.mark.parametrize("root_graph_source", ["nodes", "config"]) @pytest.mark.parametrize("serialize_pool", [False, True]) def test_iteration_preserves_inherited_node_variables( - root_graph_kind: Literal["builder", "config"], serialize_pool: bool + root_graph_source: Literal["nodes", "config"], serialize_pool: bool ) -> None: outputs = _run_workflow( - root_graph_kind=root_graph_kind, + root_graph_source=root_graph_source, root_node_id="session", inherit_pool=True, serialize_pool=serialize_pool, diff --git a/tests/engine/test_response_stream_filter.py b/tests/engine/test_response_stream_filter.py index 74312091..2d963744 100644 --- a/tests/engine/test_response_stream_filter.py +++ b/tests/engine/test_response_stream_filter.py @@ -24,7 +24,6 @@ ) from graphon.engine_events.traversal import GraphEdgeSkippedEvent, GraphEdgeTakenEvent from graphon.enums import BuiltinNodeTypes, NodeExecutionType, NodeState, NodeType -from graphon.graph.graph import Graph from graphon.nodes.base.template import ( Template, TemplateSegmentUnion, @@ -41,6 +40,7 @@ ) from graphon.runtime.variable_pool import VariablePool from graphon.variables.segments import StringSegment +from tests.helpers.frame_graph import build_linear_frame_graph _V1_FIXTURE_DIR = Path(__file__).with_name("fixtures") # These snapshots are the exact output of ResponseStreamFilter.dumps() at c3870df. @@ -924,7 +924,7 @@ def test_response_stream_filter_migrates_v1_graph_builder_state() -> None: segments=[VariableSegment(selector=["source", "answer"])], ), ) - graph = Graph.new().add_root(cast(Any, source)).add_node(cast(Any, answer)).build() + graph = build_linear_frame_graph(cast(Any, source), cast(Any, answer)) assert graph.graph_config is None restored_filter = ResponseStreamFilter() @@ -1557,3 +1557,29 @@ def test_response_stream_filter_keeps_current_state_when_load_fails() -> None: chunks = [event for event in output if isinstance(event, NodeRunStreamChunkEvent)] assert [event.chunk for event in chunks] == ["preserved"] + + +def test_loading_nested_dsl_preserves_the_edge_ordinals_of_v1_snapshots() -> None: + engine = loads(""" +kind: graph +graph: + nodes: + - {id: source, data: {type: start, variables: []}} + - {id: answer, data: {type: answer, answer: '{{#source.answer#}}'}} + - id: loop + data: + {type: loop, start_node_id: enter, loop_count: 1, + break_conditions: [], logical_operator: and} + - {id: enter, parentId: loop, data: {type: loop-start}} + - {id: finish, parentId: loop, data: {type: loop-end}} + edges: + - {id: child-edge, source: enter, target: finish} + - {id: root-answer, source: source, target: answer} +""") + restored = ResponseStreamFilter() + restored.loads(_V1_NESTED_SNAPSHOT) + restored.initialize(EngineEventFilterContext.from_engine(engine)) + + assert json.loads(restored.dumps())["legacy_paths_map"] == { + "answer": [["root-answer"]], + } diff --git a/tests/engine/test_runtime_state_serialization.py b/tests/engine/test_runtime_state_serialization.py index 71bc1871..708653c5 100644 --- a/tests/engine/test_runtime_state_serialization.py +++ b/tests/engine/test_runtime_state_serialization.py @@ -21,6 +21,7 @@ from graphon.engine.command.protocol import CommandChannel from graphon.engine.container_handler import LoopContainerHandler from graphon.engine.frame import ExecutionFrame, FrameRegistry +from graphon.engine.frame_graph import FrameGraph from graphon.engine.layer import Layer from graphon.engine.ready_queue.entities import ResumeTask, StartTask from graphon.engine.ready_queue.in_memory import InMemoryReadyQueue @@ -54,7 +55,6 @@ NodeState, WorkflowNodeExecutionMetadataKey, ) -from graphon.graph.graph import Graph from graphon.nodes.base.node import Node from graphon.nodes.container_effects import ( IterationFrameRequest, @@ -78,7 +78,9 @@ create_container_run_state, ) from graphon.runtime.init_params import InitParams +from graphon.runtime.read_only_wrappers import ReadOnlyRuntimeStateWrapper from graphon.runtime.runtime_state import RuntimeState +from graphon.runtime.runtime_state_protocol import ReadOnlyRuntimeState from graphon.runtime.variable_pool import VariablePool from graphon.variables.segments import StringSegment from tests.helpers.workflow_events import final_outputs @@ -235,7 +237,7 @@ def validate_node(self, node_config: NodeConfigDict) -> NodeExecutionType: def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> _HitlNodeFactory: return _HitlNodeFactory( base_factory=self.base_factory.with_runtime_state(runtime_state), @@ -288,7 +290,7 @@ def _hitl_engine( credentials=DslCredentials(), dependencies=list(plan.dependencies), ) - graph = Graph.init( + graph = FrameGraph.init( graph_config=graph_config, node_factory=_HitlNodeFactory( base_factory=base_factory, @@ -397,7 +399,7 @@ def on_graph_end(self, error: Exception | None) -> None: def test_runtime_snapshot_rejects_paused_workers_and_child_frames() -> None: state = _new_runtime_state({"items": ["alpha", "beta"]}) alpha_started = Event() - child_states: list[RuntimeState] = [] + child_states: list[ReadOnlyRuntimeState] = [] snapshots: list[str | Exception] = [] class ChildStateLayer(Layer): @@ -590,7 +592,7 @@ def run_operation() -> None: def _execution_frame( *, frame_id: str, - graph: Graph, + graph: FrameGraph, runtime_state: RuntimeState, ) -> ExecutionFrame: return ExecutionFrame( @@ -618,7 +620,7 @@ def validate_node(self, node_config: NodeConfigDict) -> NodeExecutionType: def with_runtime_state( self, - runtime_state: RuntimeState, + runtime_state: ReadOnlyRuntimeStateWrapper, ) -> _FrameFactory: _ = runtime_state return self @@ -642,7 +644,7 @@ class _GraphNode: state = NodeState.UNKNOWN -def _loop_graph(runtime_state: RuntimeState) -> Graph: +def _loop_graph(runtime_state: RuntimeState) -> FrameGraph: graph_config = { "nodes": [ { @@ -665,10 +667,10 @@ def _loop_graph(runtime_state: RuntimeState) -> Graph: "break_conditions": [], "logical_operator": "and", }) - loop_node.runtime_state = runtime_state + loop_node.runtime_state = runtime_state.read_only_view loop_node.graph_config = graph_config return cast( - Graph, + FrameGraph, SimpleNamespace( nodes={"loop": loop_node}, graph_config=graph_config, diff --git a/tests/engine/test_scheduler.py b/tests/engine/test_scheduler.py index 0af93de4..d4763161 100644 --- a/tests/engine/test_scheduler.py +++ b/tests/engine/test_scheduler.py @@ -1,11 +1,10 @@ from collections.abc import Sequence from typing import cast +from graphon.engine.frame_graph import Edge, FrameGraph from graphon.engine.scheduler import Scheduler from graphon.engine_events.traversal import GraphEdgeSkippedEvent, GraphEdgeTakenEvent from graphon.enums import BuiltinNodeTypes, NodeExecutionType, NodeState -from graphon.graph.edge import Edge -from graphon.graph.graph import Graph from graphon.runtime.runtime_state import RuntimeState from graphon.runtime.variable_pool import VariablePool @@ -60,7 +59,7 @@ def get_incoming_edges(self, node_id: str) -> list[Edge]: def _branch_scheduler() -> Scheduler: graph = _Graph() return Scheduler( - graph=cast(Graph, graph), + graph=cast(FrameGraph, graph), state=RuntimeState( workflow_id="workflow", variable_pool=VariablePool(), start_at=0 ), diff --git a/tests/graph/test_graph_definition.py b/tests/graph/test_graph_definition.py new file mode 100644 index 00000000..3696983d --- /dev/null +++ b/tests/graph/test_graph_definition.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +from itertools import starmap +from typing import Any, cast + +import pytest + +from graphon import dsl +from graphon.engine.filter import ( + EngineEventFilterContext, + ResponseStreamFilter, + filter_engine_events, +) +from graphon.engine_events.frame import FrameStartedEvent +from graphon.engine_events.graph import GraphRunSucceededEvent +from graphon.engine_events.node import NodeRunStreamChunkEvent, NodeRunSucceededEvent +from graphon.enums import NodeState +from graphon.graph import EdgeDefinition, Graph, GraphReference, NodeDefinition + + +@pytest.mark.parametrize("node_id", ["", None, 1]) +def test_node_definition_rejects_an_invalid_id(node_id: object) -> None: + with pytest.raises(ValueError, match="Node ID"): + NodeDefinition(cast(str, node_id), "start") + + +def test_graph_owns_immutable_config_and_compares_by_content() -> None: + selector = ["start", "value"] + config: dict[str, Any] = { + "answer": "ok", + "outputs": [{"variable": "result", "value_selector": selector}], + } + finish = NodeDefinition("end", "end", config=config) + start = NodeDefinition("start", "start") + edge = EdgeDefinition("route", "start", "end") + nodes = [start, finish] + graph = Graph(nodes=nodes, edges=[edge]) + copy = Graph( + nodes=[ + NodeDefinition("end", "end", config=config), + NodeDefinition("start", "start"), + ], + edges=[EdgeDefinition("route", "start", "end")], + ) + + nodes.clear() + selector.clear() + assert graph == copy + assert tuple(graph.node("end").config["outputs"][0]["value_selector"]) == ( + "start", + "value", + ) + assert graph != Graph( + nodes=[ + start, + NodeDefinition("end", "end", version="2", config=finish.config), + ], + edges=[edge], + ) + assert graph != Graph( + nodes=[start, NodeDefinition("end", "end", config={"outputs": []})], + edges=[edge], + ) + assert graph != Graph( + nodes=[start, NodeDefinition("end", "answer", config=finish.config)], + edges=[edge], + ) + with pytest.raises(TypeError): + graph.node("end").config["outputs"][0]["variable"] = "changed" + with pytest.raises(TypeError): + graph.nodes["new"] = start # ty: ignore[invalid-assignment] + with pytest.raises((AttributeError, TypeError)): + graph.node("end").config["outputs"][0]["value_selector"].append("other") + with pytest.raises((AttributeError, TypeError)): + finish.version = "changed" # ty: ignore[invalid-assignment] + with pytest.raises((AttributeError, TypeError)): + graph.nodes = {} # ty: ignore[invalid-assignment] + with pytest.raises((AttributeError, TypeError)): + edge.source_handle = "changed" # ty: ignore[invalid-assignment] + + +def test_only_outgoing_order_affects_graph_equality() -> None: + nodes = [NodeDefinition(name, "start") for name in ("a", "b", "c", "d")] + ab, ac, bd = ( + EdgeDefinition(src + dst, src, dst) for src, dst in ("ab", "ac", "bd") + ) + graph = Graph(nodes=nodes, edges=[ab, ac, bd]) + + assert graph.entry_node_ids == {"a", "b", "c", "d"} + assert graph.outgoing("a") == (ab, ac) + assert graph.incoming("d") == (bd,) + assert graph == Graph(nodes=nodes, edges=[bd, ab, ac]) + assert graph != Graph(nodes=nodes, edges=[ac, ab, bd]) + assert graph != Graph( + nodes=nodes, edges=[EdgeDefinition("ab", "a", "b", "yes"), ac, bd] + ) + + +@pytest.mark.parametrize( + ("kinds", "routes"), + [ + ([("a", "end")], []), + ([("a", "start"), ("a", "start")], []), + ([("a", "start")], [("x", "a", "absent")]), + ([("a", "start")], [("x", "a", "a")]), + ( + [("a", "start"), ("b", "end"), ("c", "end")], + [("x", "a", "b"), ("x", "a", "c")], + ), + ], + ids=["no-entry", "duplicate-node", "unknown-endpoint", "cycle", "duplicate-edge"], +) +def test_invalid_graphs_fail_at_construction( + kinds: list[tuple[str, str]], routes: list[tuple[str, str, str]] +) -> None: + nodes = [ + NodeDefinition(key, kind, config={"outputs": []} if kind == "end" else {}) + for key, kind in kinds + ] + edges = list(starmap(EdgeDefinition, routes)) + with pytest.raises(ValueError): # ruff: ignore[pytest-raises-too-broad] + Graph(nodes=nodes, edges=edges) + + +def test_shared_graph_runs_keep_their_paths_and_outputs() -> None: + graph = dsl.inspect(""" +kind: graph +graph: + nodes: + - {id: a, data: {type: start, variables: []}} + - {id: b, data: {type: start, variables: []}} + - id: left + data: {type: end, outputs: [{variable: name, value_selector: [a, name]}]} + - id: right + data: {type: end, outputs: [{variable: name, value_selector: [b, name]}]} + edges: + - {id: first, source: a, target: left} + - {id: second, source: b, target: right} +""").document.graph + assert graph is not None + left = dsl.load_graph(graph, root_node_id="a", start_inputs={"name": "Ada"}) + right = dsl.load_graph(graph, root_node_id="b", start_inputs={"name": "Lin"}) + + another_left = dsl.load_graph(graph, root_node_id="a", start_inputs={"name": "Jo"}) + assert left.definition is right.definition is another_left.definition is graph + assert graph.entry_node_ids == {"a", "b"} + first_result = list(left.run())[-1] + assert isinstance(first_result, GraphRunSucceededEvent) + assert first_result.outputs == {"name": "Ada"} + assert right.graph.nodes["right"].state == NodeState.UNKNOWN + assert right.graph.edges["second"].state == NodeState.UNKNOWN + assert another_left.graph.nodes["left"].state == NodeState.UNKNOWN + assert another_left.graph.edges["first"].state == NodeState.UNKNOWN + repeated_result = list(another_left.run())[-1] + assert isinstance(repeated_result, GraphRunSucceededEvent) + assert repeated_result.outputs == {"name": "Jo"} + second_result = list(right.run())[-1] + assert isinstance(second_result, GraphRunSucceededEvent) + assert second_result.outputs == {"name": "Lin"} + assert left.runtime_state.outputs == {"name": "Ada"} + + +def test_iteration_can_call_the_same_body_inline_or_by_reference() -> None: + source = """ +kind: graph +graph: + nodes: + - {id: start, data: {type: start, variables: []}} + - id: each + data: + type: iteration + start_node_id: enter + iterator_selector: [start, items] + output_selector: [render, output] + - {id: enter, parentId: each, data: {type: iteration-start}} + - id: render + parentId: each + data: + type: template-transform + variables: [{variable: item, value_selector: [each, item]}] + template: 'hi {{ item }}' + - id: end + data: {type: end, outputs: [{variable: names, value_selector: [each, output]}]} + edges: + - {id: first, source: start, target: each} + - {id: finish, source: each, target: end} + - {id: first, source: enter, target: render} +""" + graph = dsl.inspect(source).document.graph + assert graph is not None + call = graph.node("each") + body = call.call_target + assert isinstance(body, Graph) + assert set(graph.nodes) == {"start", "each", "end"} + assert set(graph.edges) == {"first", "finish"} + assert set(body.edges) == {"first"} + assert set(body.nodes) == {"enter", "render"} + assert ( + graph + == dsl.inspect( + source.replace( + " - id: render\n", + " - id: render\n position: {x: 50, y: 24}\n", + 1, + ) + ).document.graph + ) + assert ( + graph + != dsl.inspect(source.replace("hi {{ item }}", "bye {{ item }}")).document.graph + ) + + def with_reference(target: GraphReference) -> Graph: + referenced_call = NodeDefinition( + call.id, + call.node_type, + version=call.version, + config=call.config, + call_target=target, + ) + return Graph( + nodes=[ + referenced_call if node.id == call.id else node + for node in graph.nodes.values() + ], + edges=graph.edges.values(), + ) + + reference = GraphReference("greeter") + by_reference = with_reference(reference) + assert graph != by_reference + assert by_reference == with_reference(GraphReference("greeter")) + assert by_reference != with_reference(GraphReference("other")) + inputs = {"items": ["Ada", "Lin"]} + for engine in ( + dsl.loads(source, start_inputs=inputs), + dsl.load_graph(graph, start_inputs=inputs), + ): + assert engine.definition == graph + result = list(engine.run())[-1] + assert isinstance(result, GraphRunSucceededEvent) + assert result.outputs == {"names": ["hi Ada", "hi Lin"]} + + updated = dsl.inspect( + source.replace("hi {{ item }}", "bye {{ item }}") + ).document.graph + assert updated is not None + replacement = updated.node("each").call_target + assert isinstance(replacement, Graph) + referenced_engine = dsl.load_graph( + by_reference, + start_inputs=inputs, + graph_resolver={reference: replacement}.__getitem__, + ) + result = list(referenced_engine.run())[-1] + assert isinstance(result, GraphRunSucceededEvent) + assert result.outputs == {"names": ["bye Ada", "bye Lin"]} + + +def _two_loops(first: Graph, second: Graph | GraphReference, count: int) -> Graph: + settings = { + "start_node_id": "enter", + "loop_count": count, + "break_conditions": [], + "logical_operator": "and", + } + return Graph( + nodes=[ + NodeDefinition("start", "start"), + NodeDefinition("first", "loop", config=settings, call_target=first), + NodeDefinition("second", "loop", config=settings, call_target=second), + ], + edges=[ + EdgeDefinition("first-call", "start", "first"), + EdgeDefinition("second-call", "first", "second"), + ], + ) + + +def test_two_loops_can_call_bodies_with_the_same_local_node_ids() -> None: + ref = GraphReference("body") + body = Graph( + nodes=[ + NodeDefinition("enter", "loop-start"), + NodeDefinition("break", "loop-end"), + ], + edges=[EdgeDefinition("next", "enter", "break")], + ) + graph = _two_loops(body, ref, 3) + engine = dsl.load_graph(graph, graph_resolver={ref: body}.__getitem__) + events = list(engine.run()) + assert isinstance(events[-1], GraphRunSucceededEvent) + calls = [ + event.container_id + for event in events + if isinstance(event, FrameStartedEvent) and event.parent_frame_id is not None + ] + assert calls == ["first", "second"] + + +def test_responses_follow_the_called_graph_when_two_bodies_reuse_node_ids() -> None: + def body(reply: str) -> Graph: + return Graph( + nodes=[ + NodeDefinition("enter", "loop-start"), + NodeDefinition("reply", "answer", config={"answer": reply}), + ], + edges=[EdgeDefinition("next", "enter", "reply")], + ) + + graph = _two_loops(body("first reply"), body("second reply"), 1) + engine = dsl.load_graph(graph) + context = EngineEventFilterContext.from_engine(engine) + events = list( + filter_engine_events( + list(engine.run()), filters=[ResponseStreamFilter()], context=context + ) + ) + chunks = [ + event.chunk for event in events if isinstance(event, NodeRunStreamChunkEvent) + ] + assert "".join(chunks) == "first replysecond reply" + + +def test_canvas_layout_and_displayed_run_status_do_not_change_a_graph() -> None: + source = """ +kind: graph +graph: + nodes: + - id: start + data: {type: start, variables: []} + edges: [] +""" + edited = source.replace( + "variables: []", + """ + variables: [], width: 320, height: 220, position: {x: 40, y: 80}, + _runningStatus: succeeded, _connectedSourceHandleIds: [source]""", + ) + original = dsl.inspect(source).document.graph + moved = dsl.inspect(edited).document.graph + assert original is not None + assert moved is not None + assert moved == original + assert moved.node("start").config == original.node("start").config + + +def test_selecting_a_body_entry_skips_other_entries_before_their_paths_join() -> None: + graph = Graph( + nodes=[ + NodeDefinition("first", "loop-start"), + NodeDefinition("second", "loop-start"), + NodeDefinition("join", "end", config={"outputs": []}), + ], + edges=[ + EdgeDefinition("left", "first", "join"), + EdgeDefinition("right", "second", "join"), + ], + ) + engine = dsl.load_graph(graph, root_node_id="first") + assert graph.entry_node_ids == {"first", "second"} + assert engine.graph.nodes["second"].state == NodeState.SKIPPED + assert engine.graph.edges["right"].state == NodeState.SKIPPED + events = list(engine.run()) + assert isinstance(events[-1], GraphRunSucceededEvent) + assert any( + isinstance(event, NodeRunSucceededEvent) and event.node_id == "join" + for event in events + ) diff --git a/tests/graph_builder/__init__.py b/tests/graph_builder/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/graph_builder/test_graph_builder.py b/tests/graph_builder/test_graph_builder.py new file mode 100644 index 00000000..05a6fd26 --- /dev/null +++ b/tests/graph_builder/test_graph_builder.py @@ -0,0 +1,102 @@ +from typing import cast + +import pytest + +from graphon.graph import EdgeDefinition, Graph, GraphReference, NodeDefinition +from graphon.graph.validation import GraphValidationError +from graphon.graph_builder import GraphBuilder + + +def test_build_a_branch_and_join_with_explicit_edges() -> None: + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + start_only = builder.build() + end_id = builder.add_node("end", "end", config={"outputs": []}) + for node_id, handle in [("left", "yes"), ("right", "no")]: + branch_id = builder.add_node(node_id, "answer", config={"answer": node_id}) + builder.connect(start_id, branch_id, source_handle=handle) + builder.connect(branch_id, end_id) + + assert start_only == Graph(nodes=[NodeDefinition("start", "start")]) + assert builder.build() == Graph( + nodes=[ + NodeDefinition("start", "start"), + NodeDefinition("left", "answer", config={"answer": "left"}), + NodeDefinition("right", "answer", config={"answer": "right"}), + NodeDefinition("end", "end", config={"outputs": []}), + ], + edges=[ + EdgeDefinition("edge_0", "start", "left", "yes"), + EdgeDefinition("edge_1", "left", "end"), + EdgeDefinition("edge_2", "start", "right", "no"), + EdgeDefinition("edge_3", "right", "end"), + ], + ) + + +def test_builtin_and_custom_entries_can_share_a_target() -> None: + builder = GraphBuilder(entry_types=[("webhook", "2")]) + end_id = builder.add_node("end", "end") + manual_id = builder.add_node("manual", "start") + trigger_id = builder.add_node("hook", "webhook", version="2") + builder.connect(manual_id, end_id) + builder.connect(trigger_id, end_id) + definition = builder.build() + + assert definition.entry_node_ids == {"manual", "hook"} + assert {edge.source for edge in definition.incoming("end")} == {"manual", "hook"} + assert definition.incoming("hook") == () + + +def test_container_nodes_keep_embedded_and_referenced_graphs() -> None: + body = Graph(nodes=[NodeDefinition("enter", "iteration-start")]) + reference = GraphReference("body", version="v2") + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + for node_id, call_target in [("inline", body), ("external", reference)]: + iteration_id = builder.add_node(node_id, "iteration", call_target=call_target) + builder.connect(start_id, iteration_id) + graph = builder.build() + + assert graph.node("inline").call_target == body + assert graph.node("external").call_target == reference + + +@pytest.mark.parametrize("cycle_target_id", ["a", "b"]) +def test_build_rejects_cycles(cycle_target_id: str) -> None: + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + first_answer_id = builder.add_node("a", "answer") + second_answer_id = builder.add_node("b", "answer") + builder.connect(start_id, first_answer_id) + builder.connect(first_answer_id, second_answer_id) + builder.connect(second_answer_id, cycle_target_id) + with pytest.raises(GraphValidationError): + builder.build() + + +def test_build_requires_an_entry() -> None: + builder = GraphBuilder() + builder.add_node("reply", "answer") + with pytest.raises(GraphValidationError) as exc: + builder.build() + assert any(issue.code == "INVALID_ROOT" for issue in exc.value.issues) + + +def test_rejected_edits_leave_the_builder_available_for_a_retry() -> None: + builder = GraphBuilder() + start_id = builder.add_node("start", "start") + end_id = builder.add_node("end", "end") + + with pytest.raises(GraphValidationError, match="DUPLICATE_NODE_ID"): + builder.add_node("end", "answer") + with pytest.raises(ValueError, match="missing"): + builder.connect(start_id, "missing") + with pytest.raises(TypeError, match="handle"): + builder.connect(start_id, end_id, source_handle=cast(str, None)) + + builder.connect(start_id, end_id) + assert builder.build() == Graph( + nodes=[NodeDefinition("start", "start"), NodeDefinition("end", "end")], + edges=[EdgeDefinition("edge_0", "start", "end")], + ) diff --git a/tests/helpers/frame_graph.py b/tests/helpers/frame_graph.py new file mode 100644 index 00000000..04c71a92 --- /dev/null +++ b/tests/helpers/frame_graph.py @@ -0,0 +1,20 @@ +from itertools import pairwise + +from graphon.engine import Edge, FrameGraph +from graphon.nodes.base.node import Node + + +def build_linear_frame_graph(root: Node, *following: Node) -> FrameGraph: + """Connect test nodes in order with the edge IDs used by saved snapshots.""" + nodes = (root, *following) + edges = [ + Edge(id=f"edge_{index}", tail=source.id, head=target.id) + for index, (source, target) in enumerate(pairwise(nodes)) + ] + return FrameGraph( + root_node=root, + nodes={node.id: node for node in nodes}, + edges={edge.id: edge for edge in edges}, + in_edges={edge.head: [edge.id] for edge in edges}, + out_edges={edge.tail: [edge.id] for edge in edges}, + ) diff --git a/tests/nodes/base/test_node_execution_binding.py b/tests/nodes/base/test_node_execution_binding.py index c61a31c2..a1043e1f 100644 --- a/tests/nodes/base/test_node_execution_binding.py +++ b/tests/nodes/base/test_node_execution_binding.py @@ -2,9 +2,12 @@ from graphon.entities.base_node_data import BaseNodeData from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus +from graphon.file.enums import FileTransferMethod, FileType +from graphon.file.models import File from graphon.node_events.base import NodeRunResult from graphon.nodes.base.node import Node from graphon.runtime.runtime_state import RuntimeState +from graphon.variables.variables import ObjectVariable from tests.helpers import build_init_params, build_variable_pool @@ -33,3 +36,33 @@ def test_node_run_requires_bound_execution_id() -> None: with pytest.raises(RuntimeError, match="execution_id must be bound"): list(node.run()) + + +def test_node_reads_detached_variables_and_files() -> None: + file = File( + file_type=FileType.DOCUMENT, + transfer_method=FileTransferMethod.REMOTE_URL, + remote_url="https://example.org/original.txt", + filename="original.txt", + ) + pool = build_variable_pool( + variables=[(("start", "profile"), {"tags": ["old"]}), (("start", "file"), file)] + ) + node = _RunnableNode( + node_id="reader", + data=BaseNodeData(type=BuiltinNodeTypes.CODE), + init_params=build_init_params(), + runtime_state=RuntimeState(workflow_id="graph", variable_pool=pool, start_at=1), + ) + node_pool = node.runtime_state.variable_pool + profile = node_pool.get_variable(("start", "profile")) + attachment = node_pool.get_file(("start", "file")) + assert isinstance(profile, ObjectVariable) + assert attachment is not None + profile.value["tags"].append("new") + attachment.value.filename = "changed.txt" + + stored_file = pool.get_file(("start", "file")) + assert stored_file is not None + assert stored_file.value.filename == "original.txt" + assert pool.get_by_prefix("start")["profile"] == {"tags": ["old"]} diff --git a/tests/nodes/llm/test_node.py b/tests/nodes/llm/test_node.py index 19f9b683..ba59d08e 100644 --- a/tests/nodes/llm/test_node.py +++ b/tests/nodes/llm/test_node.py @@ -47,6 +47,7 @@ from graphon.nodes.llm.exc import LLMNodeError from graphon.nodes.llm.reasoning import split_reasoning from graphon.nodes.llm.runtime_protocols import LLMPollingCapableProtocol, LLMProtocol +from graphon.runtime.execution import GraphExecution from graphon.runtime.runtime_state import RuntimeState from ...helpers import build_init_params, build_variable_pool @@ -130,6 +131,7 @@ def _build_llm_node( workflow_run_id: str | None = "wr-test", run_context: dict[str, Any] | None = None, llm_file_saver: Any | None = None, + graph_execution: GraphExecution | None = None, ) -> LLMNode: prepared_model = model_instance if prepared_model is None: @@ -170,6 +172,7 @@ def _build_llm_node( workflow_id="workflow", variable_pool=build_variable_pool(variables=prepared_variables), start_at=0.0, + graph_execution=graph_execution, ), model_instance=cast(LLMProtocol, prepared_model), llm_file_saver=MagicMock() if llm_file_saver is None else llm_file_saver, @@ -1010,8 +1013,9 @@ def test_polling_llm_respects_existing_abort_before_start( result=_llm_result(), ), ]) - node = _build_llm_node(model_instance=model) - node.runtime_state.graph_execution.abort("stop") + execution = GraphExecution(workflow_id="workflow") + execution.abort("stop") + node = _build_llm_node(model_instance=model, graph_execution=execution) _stub_simple_prompt(monkeypatch, node) events = list(node._run()) diff --git a/tests/nodes/tool/test_tool_node.py b/tests/nodes/tool/test_tool_node.py index 52cf94f3..3d1e5615 100644 --- a/tests/nodes/tool/test_tool_node.py +++ b/tests/nodes/tool/test_tool_node.py @@ -22,7 +22,6 @@ from graphon.enums import BuiltinNodeTypes from graphon.file.enums import FileTransferMethod, FileType from graphon.file.models import File -from graphon.graph.graph import Graph from graphon.model_runtime.entities.llm_entities import LLMUsage from graphon.node_events.node import StreamChunkEvent, StreamCompletedEvent from graphon.nodes.answer.answer_node import AnswerNode @@ -39,6 +38,7 @@ ) from graphon.runtime.runtime_state import RuntimeState from tests.helpers.builders import build_init_params, build_variable_pool +from tests.helpers.frame_graph import build_linear_frame_graph def _message_stream( @@ -349,14 +349,8 @@ def test_tool_session_id_is_preserved_in_filtered_answer( init_params=init_params, runtime_state=runtime_state, ) - graph = ( - Graph - .new() - .add_root(start_node) - .add_node(session_node) - .add_node(forward_node) - .add_node(answer_node) - .build() + graph = build_linear_frame_graph( + start_node, session_node, forward_node, answer_node ) engine = Engine(graph=graph, runtime_state=runtime_state) events = list( @@ -563,7 +557,7 @@ def test_run_passes_variable_pool_and_bound_execution_id_to_runtime( expects_variable_pool: bool, ) -> None: runtime = _RunStubToolRuntime() - node, variable_pool = _build_run_tool_node( + node, _variable_pool = _build_run_tool_node( runtime=runtime, tool_node_version=tool_node_version, ) @@ -573,7 +567,9 @@ def test_run_passes_variable_pool_and_bound_execution_id_to_runtime( assert runtime.last_get_runtime_kwargs == { "node_id": "node-1", "node_data": node.node_data, - "variable_pool": variable_pool if expects_variable_pool else None, + "variable_pool": node.runtime_state.variable_pool + if expects_variable_pool + else None, "node_execution_id": "bound-execution", } assert node.execution_id == "bound-execution" diff --git a/tests/runtime/test_runtime_state.py b/tests/runtime/test_runtime_state.py index 64878423..a13d570d 100644 --- a/tests/runtime/test_runtime_state.py +++ b/tests/runtime/test_runtime_state.py @@ -19,7 +19,6 @@ NodeState, ) from graphon.file import File, FileTransferMethod, FileType -from graphon.graph.graph import Graph from graphon.model_runtime.entities.llm_entities import LLMUsage from graphon.nodes.container_effects import ( IterationFrameRequest, @@ -37,6 +36,7 @@ from graphon.runtime.variable_pool import VariablePool from graphon.variables.segments import ArrayFileSegment, FileSegment from graphon.variables.variables import StringVariable +from tests.helpers.frame_graph import build_linear_frame_graph CONVERSATION_VARIABLE_NODE_ID = "conversation" @@ -287,7 +287,7 @@ def test_snapshot_before_graph_attachment_accepts_rebuilt_graph( execution_type=NodeExecutionType.EXECUTABLE, state=NodeState.UNKNOWN, ) - graph = Graph.new().add_root(root).add_node(end).build() + graph = build_linear_frame_graph(root, end) restored = RuntimeState.from_snapshot(legacy_snapshot or state.dumps()) restored.attach_graph(graph) @@ -510,7 +510,7 @@ def test_version_2_graph_builder_state_migrates_without_graph_config(self) -> No execution_type=NodeExecutionType.EXECUTABLE, state=NodeState.TAKEN, ) - graph = Graph.new().add_root(root).add_node(end).build() + graph = build_linear_frame_graph(root, end) assert graph.graph_config is None restored = RuntimeState.from_snapshot(_VERSION_2_GRAPH_BUILDER_SNAPSHOT) diff --git a/tests/runtime/test_variable_pool.py b/tests/runtime/test_variable_pool.py index 89ab1166..0d08a3d0 100644 --- a/tests/runtime/test_variable_pool.py +++ b/tests/runtime/test_variable_pool.py @@ -1,3 +1,5 @@ +import pytest + from graphon.runtime.variable_pool import VariablePool from graphon.variables.segments import ( BooleanSegment, @@ -187,6 +189,50 @@ def test_add_binds_copied_outputs_to_the_destination(self) -> None: assert output.id != original.id +@pytest.mark.parametrize( + "selector", + [(), ("start",), ("start", "profile", "name"), "ab", (1, "name"), ("start", 1)], +) +def test_writes_require_a_variable_address(selector: tuple[str, ...] | str) -> None: + pool = VariablePool() + pool.add(("start", "profile"), {"name": "Ada"}) + pool.add(("a", "b"), "two letters") + + with pytest.raises(ValueError, match="address"): + pool.remove(selector) + with pytest.raises(ValueError, match="address"): + pool.add(selector, "new value") + + assert pool.flatten() == {"start.profile": {"name": "Ada"}, "a.b": "two letters"} + + +def test_remove_variable_and_clear_scope() -> None: + pool = VariablePool() + pool.add(("start", "profile"), {"name": "Ada"}) + pool.add(("start", "count"), 1) + pool.add(("start", "language"), "es") + pool.add(("other", "count"), 2) + + pool.remove(["start", "profile"]) + assert pool.flatten() == { + "start.count": 1, + "start.language": "es", + "other.count": 2, + } + pool.clear_scope("start") + assert pool.flatten() == {"other.count": 2} + + +def test_field_path_can_be_read_and_cannot_replace_its_variable() -> None: + pool = VariablePool() + pool.add(("start", "profile"), {"name": "Ada"}) + path = ("start", "profile", "name") + assert pool.get(path) == StringSegment(value="Ada") + with pytest.raises(ValueError, match=r"address|selector"): + pool.add(path, "new name") + assert pool.get_by_prefix("start") == {"profile": {"name": "Ada"}} + + class TestVariablePoolGetNotModifyVariableDictionary: _NODE_ID = "start" _VAR_NAME = "name" diff --git a/tests/test_import_layers.py b/tests/test_import_layers.py index 504fdb07..29dc1232 100644 --- a/tests/test_import_layers.py +++ b/tests/test_import_layers.py @@ -42,23 +42,29 @@ def source_directory(tmp_path: Path) -> Path: @pytest.mark.parametrize( - ("lower_package", "higher_package"), - [("file", "runtime"), ("runtime", "engine")], + ("importer", "imported"), + [ + ("file", "runtime"), + ("runtime", "engine"), + ("graph", "graph_builder"), + ("dsl", "graph_builder"), + ("graph_builder", "dsl"), + ], ) -def test_layers_reject_upward_type_checking_imports( - source_directory: Path, lower_package: str, higher_package: str +def test_layers_reject_disallowed_type_checking_imports( + source_directory: Path, importer: str, imported: str ) -> None: - module_path = source_directory / "graphon" / lower_package / "upward_import.py" + module_path = source_directory / "graphon" / importer / "disallowed_import.py" module_path.write_text( f"from typing import TYPE_CHECKING\n" - f"if TYPE_CHECKING:\n import graphon.{higher_package}\n" + f"if TYPE_CHECKING:\n import graphon.{imported}\n" ) result = run_import_linter(source_directory) assert result.returncode == 1, result.stdout + result.stderr - assert f"graphon.{lower_package}.upward_import" in result.stdout - assert f"graphon.{higher_package}" in result.stdout + assert f"graphon.{importer}.disallowed_import" in result.stdout + assert f"graphon.{imported}" in result.stdout def test_new_top_level_modules_require_a_layer(source_directory: Path) -> None: diff --git a/tests/test_protocols_exports.py b/tests/test_protocols_exports.py index 28f94330..8e1cdde1 100644 --- a/tests/test_protocols_exports.py +++ b/tests/test_protocols_exports.py @@ -4,7 +4,6 @@ from graphon import protocols from graphon.file.protocols import WorkflowFileRuntimeProtocol -from graphon.graph.graph import NodeFactory from graphon.graph.validation import GraphValidationRule from graphon.http.protocols import HttpClientProtocol, HttpResponseProtocol from graphon.model_runtime.memory.prompt_message_memory import PromptMessageMemory @@ -23,6 +22,7 @@ ) from graphon.model_runtime.protocols.tts_runtime import TTSModelRuntime from graphon.nodes.code.code_node import CodeExecutorProtocol +from graphon.nodes.factory import NodeFactory from graphon.nodes.llm.protocols import CredentialsProvider, ModelFactory from graphon.nodes.llm.runtime_protocols import ( LLMPollingCapableProtocol, diff --git a/tests/variables/legacy_start_input_schema.json b/tests/variables/legacy_start_input_schema.json new file mode 100644 index 00000000..8b4af029 --- /dev/null +++ b/tests/variables/legacy_start_input_schema.json @@ -0,0 +1,113 @@ +{ + "deprecated": true, + "fields": { + "allowed_file_extensions": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ] + }, + "allowed_file_types": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/FileType" + }, + "type": "array" + }, + { + "type": "null" + } + ] + }, + "allowed_file_upload_methods": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/FileTransferMethod" + }, + "type": "array" + }, + { + "type": "null" + } + ] + }, + "default": { + "default": null + }, + "description": { + "default": "", + "type": "string" + }, + "hide": { + "default": false, + "type": "boolean" + }, + "json_schema": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null + }, + "label": { + "type": "string" + }, + "max_length": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null + }, + "options": { + "items": { + "type": "string" + }, + "type": "array" + }, + "required": { + "default": false, + "type": "boolean" + }, + "type": { + "$ref": "#/$defs/VariableEntityType" + }, + "variable": { + "type": "string" + } + }, + "input_types": [ + "checkbox", + "external_data_tool", + "file", + "file-list", + "json_object", + "number", + "paragraph", + "select", + "text-input" + ], + "required": [ + "label", + "type", + "variable" + ] +} diff --git a/tests/variables/test_input_entities.py b/tests/variables/test_input_entities.py index 4d966596..729fedab 100644 --- a/tests/variables/test_input_entities.py +++ b/tests/variables/test_input_entities.py @@ -1,9 +1,17 @@ +import json +from pathlib import Path from typing import Any import pytest from pydantic import ValidationError -from graphon.variables.input_entities import VariableEntity, VariableEntityType +from graphon.nodes.start.entities import StartNodeData +from graphon.variables.input_entities import ( + VariableEntity, # ty: ignore[deprecated] + VariableEntityType, +) + +_validate_legacy_input = VariableEntity.model_validate # ty: ignore[deprecated] _VALID_SCHEMA: dict = { "type": "object", @@ -24,9 +32,25 @@ def _make_payload(json_schema: Any) -> dict[str, Any]: } +def test_start_keeps_its_legacy_input_schema() -> None: + definitions = StartNodeData.model_json_schema()["$defs"] + schema = definitions["VariableEntity"] + schema_snapshot = { + "deprecated": schema.get("deprecated", False), + "required": sorted(schema["required"]), + "fields": { + name: {key: value for key, value in field.items() if key != "title"} + for name, field in schema["properties"].items() + }, + "input_types": sorted(definitions["VariableEntityType"]["enum"]), + } + snapshot_path = Path(__file__).with_name("legacy_start_input_schema.json") + assert schema_snapshot == json.loads(snapshot_path.read_text(encoding="utf-8")) + + class TestValidateJsonSchema: def test_accepts_dict_input(self) -> None: - entity = VariableEntity.model_validate(_make_payload(_VALID_SCHEMA)) + entity = _validate_legacy_input(_make_payload(_VALID_SCHEMA)) assert entity.json_schema == _VALID_SCHEMA def test_accepts_json_string_input(self) -> None: @@ -41,49 +65,49 @@ def test_accepts_json_string_input(self) -> None: ' "required": ["name"]\n' "}" ) - entity = VariableEntity.model_validate(_make_payload(raw)) + entity = _validate_legacy_input(_make_payload(raw)) assert entity.json_schema == _VALID_SCHEMA def test_treats_none_as_none(self) -> None: - entity = VariableEntity.model_validate(_make_payload(None)) + entity = _validate_legacy_input(_make_payload(None)) assert entity.json_schema is None def test_treats_empty_string_as_none(self) -> None: # Frontend "clear schema" sends "" rather than removing the field; # treating it as None matches the user's intent of "no constraint". - entity = VariableEntity.model_validate(_make_payload("")) + entity = _validate_legacy_input(_make_payload("")) assert entity.json_schema is None def test_treats_whitespace_string_as_none(self) -> None: - entity = VariableEntity.model_validate(_make_payload(" \n\t ")) + entity = _validate_legacy_input(_make_payload(" \n\t ")) assert entity.json_schema is None def test_rejects_malformed_json_string(self) -> None: with pytest.raises(ValidationError) as exc_info: - VariableEntity.model_validate(_make_payload('{"type": "object"')) + _validate_legacy_input(_make_payload('{"type": "object"')) assert "not valid JSON" in str(exc_info.value) @pytest.mark.parametrize("constant", ["NaN", "Infinity", "-Infinity"]) def test_rejects_non_standard_json_constant(self, constant: str) -> None: with pytest.raises(ValidationError) as exc_info: - VariableEntity.model_validate( + _validate_legacy_input( _make_payload(f'{{"type": "number", "minimum": {constant}}}'), ) assert "invalid constant" in str(exc_info.value) def test_rejects_non_object_non_string_input(self) -> None: with pytest.raises(ValidationError) as exc_info: - VariableEntity.model_validate(_make_payload(123)) + _validate_legacy_input(_make_payload(123)) assert "must be a JSON object" in str(exc_info.value) def test_rejects_semantically_invalid_schema(self) -> None: bad_schema = {"type": "not_a_real_type"} with pytest.raises(ValidationError) as exc_info: - VariableEntity.model_validate(_make_payload(bad_schema)) + _validate_legacy_input(_make_payload(bad_schema)) assert "Invalid JSON schema" in str(exc_info.value) def test_rejects_semantically_invalid_schema_from_string(self) -> None: bad_schema_str = '{"type": "not_a_real_type"}' with pytest.raises(ValidationError) as exc_info: - VariableEntity.model_validate(_make_payload(bad_schema_str)) + _validate_legacy_input(_make_payload(bad_schema_str)) assert "Invalid JSON schema" in str(exc_info.value)