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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 22 additions & 12 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!-- knowledge
last_checked: "2026-11-09T05:24:03Z"
last_checked: "2026-11-11T05:46:47Z"
-->
# Architecture

Expand Down Expand Up @@ -97,15 +97,17 @@ See [raw-event tests](tests/engine/test_raw_engine_events.py) and

## Raw frame observations

[Frame events](src/graphon/engine_events/frame.py) expose execution state for
consumers that may read events after a child frame has been removed:
By default, [Engine](src/graphon/engine/engine.py) emits [frame events](src/graphon/engine_events/frame.py) that expose execution state for consumers that may read events after a child frame has been removed:

| Event | Meaning |
| --- | --- |
| `FrameStartedEvent` | A detached, typed variable baseline and reserved node execution IDs, published after setup and before body scheduling. Child frames also identify their parent and owning container invocation. |
| `FrameVariablesUpdatedEvent` | Detached replacements at the written selectors, published after successful commits. Empty and `None` values are retained; partial failures report only writes that succeeded. |
| `FrameFinishedEvent` | The frame has emitted its last node, traversal, and variable observations, with a succeeded, failed, or aborted outcome. Child completion is published before registry removal. |

Set `Engine(..., emit_frame_events=False)` to skip these events and their detached value copies for both event consumers and layers while execution and variable commits continue.
This engine option is not persisted; supply it again when rebuilding from a snapshot.

[FrameRegistry](src/graphon/engine/frame.py) publishes commits for node outputs
and handled-failure defaults, variable requests, Loop initialization, Loop and
Iteration ancestor write-back, and external commands. Every frame sharing an
Expand All @@ -123,9 +125,8 @@ pause/restore and distinguishes separate runs with the same `workflow_id`.

Pause leaves unfinished frames open. Resume publishes new baselines with the
resumption reason and existing execution IDs before resumed body events.
[Persisted container state](src/graphon/runtime/container_state.py) preserves
pending frame failures across pause and snapshot restore. Terminal failure or
abort closes each remaining frame once, before the graph's terminal event.
[Persisted container state](src/graphon/runtime/container_state.py) preserves pending frame failures across pause and snapshot restore even when frame events are disabled.
Terminal failure or abort closes each remaining frame once, before the graph's terminal event.
An `Exception` thrown into `Engine.run()` during execution or at the paused event
follows the same failure ordering; continued consumption re-raises the exception.

Expand All @@ -136,10 +137,9 @@ commits, detached values, and raw chunk delivery, and the
[frame failure tests](tests/engine/test_frame_failures.py) for pause/restore and
consumer exceptions.

Baselines and commits contain full variable values. `ResponseStreamFilter`
suppresses those events from its output; this compatibility guard does not add
child response assembly. Response buffers and presentation state remain in the
filter, separate from runtime snapshots.
Baselines and commits contain full variable values.
`ResponseStreamFilter` suppresses those events from its output after the engine has constructed and copied them; this compatibility guard does not add child response assembly.
Response buffers and presentation state remain in the filter, separate from runtime snapshots.

## State and execution invariants

Expand Down Expand Up @@ -168,11 +168,21 @@ compatibility details:
[Concrete segment models](src/graphon/variables/segments.py) own fixed `value_type` tags and value validation; serialized values select their model by that tag.
[Factories](src/graphon/variables/factory.py) infer types for raw values or validate explicit declarations, preserving declared empty arrays and `array[any]` values.
See [factory tests](tests/variables/test_factory.py) for declared types and serialized tag selection.
`array[any]` restores serialized [marked file values](src/graphon/file/constants.py) recursively inside arrays and objects using [File validation](src/graphon/file/models.py), preserving file values in container task and variable pool snapshots.
Unmarked objects retain their data, and invalid marked files fail validation; see [container tests](tests/nodes/test_container_effects.py) and [workflow tests](tests/workflows/test_full_engine_events.py).
`array[any]` keeps ordinary JSON dictionaries as data, including dictionaries with a file identity marker or the full set of file fields.
Complete snapshots produced without `include` or `exclude` use [file snapshot serialization](src/graphon/variables/file_snapshot.py) to record actual [File](src/graphon/file/models.py) locations in `file_paths`.
Paths follow Pydantic's Python serialization of nested values, honoring declared model fields, aliases, field exclusions, and caller context.
Nested models become plain data; sequences, sets, and iterators become arrays, while recorded files restore as `File` objects through variable pool and container task restoration.
[File serialization markers](src/graphon/file/serialization.py) are scoped to this projection and reset on exit, including serialization errors.
These snapshots require string keys on dictionaries containing files; dictionaries without files follow ordinary JSON serialization.
Exports using `include` or `exclude` omit file restoration metadata, as does [dumps_with_segments](src/graphon/variables/utils.py), which exports plain values without log redaction.
Historical `array[any]` snapshots without `file_paths` retain dictionaries as data.
Invalid declared paths or file payloads fail validation; see [snapshot tests](tests/variables/test_file_snapshots.py), [plain value export tests](tests/utils/test_variable_utils.py), and [container tests](tests/nodes/test_container_effects.py).
[VariableBase.copy_with_value](src/graphon/variables/variables.py) validates replacements for assignment nodes, retaining identity and metadata and promoting integer variables when the new value is a float.
The [v1 assignment tests](tests/nodes/variable_assigner/test_v1_node.py) and [v2 assignment tests](tests/nodes/variable_assigner/test_v2_node.py) cover invalid updates, fractional results, and clearing arrays while preserving their declared type, including `array[file]`.

In [template interpolation](src/graphon/variables/template_resolution.py), nonempty object arrays render as JSON, including nested `File` and segment model data.
Empty object arrays render as an empty string; see [template resolution tests](tests/variables/test_template_resolution.py).

[Container values](src/graphon/nodes/container_effects.py) preserve declared segment types through construction, snapshots, and completion, including secret tags.
Explicit `to_segment()` conversion removes source variable identity so the parent pool binds completed outputs to the container's selectors.
Snapshot restoration uses the `SerializableSegment` discriminated union directly.
Expand Down
4 changes: 2 additions & 2 deletions docs/development.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!-- knowledge
last_checked: "2026-11-09T05:24:03Z"
last_checked: "2026-11-11T07:11:10Z"
-->
# Development navigation

Expand Down Expand Up @@ -30,7 +30,7 @@ Follow the [variable and container contracts](../ARCHITECTURE.md#state-and-execu
| 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), [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) |
| Change variables or secrets | [variable pool](../src/graphon/runtime/variable_pool.py), [segment models](../src/graphon/variables/segments.py), [variable models](../src/graphon/variables/variables.py), [conversion](../src/graphon/variables/factory.py), [variable assignment](../src/graphon/nodes/variable_assigner/) | [variable pool tests](../tests/runtime/test_variable_pool.py), [Iteration variable ownership](../tests/engine/test_iteration_variable_scopes.py), [variable tests](../tests/variables/), [assignment tests](../tests/nodes/variable_assigner/), [HTTP secret masking](../tests/http/test_executor_secret_masking.py) |
| Change persistence or resume | [runtime state](../src/graphon/runtime/runtime_state/), [container state](../src/graphon/runtime/container_state.py) | [runtime tests](../tests/runtime/), [engine serialization](../tests/engine/test_runtime_state_serialization.py), [frame failure restoration](../tests/engine/test_frame_failures.py), [version isolation](../tests/test_snapshot_version_isolation.py) |
| Change persistence or resume | [runtime state](../src/graphon/runtime/runtime_state/), [container state](../src/graphon/runtime/container_state.py), [nested file snapshots](../src/graphon/variables/file_snapshot.py) | [runtime tests](../tests/runtime/), [file snapshots](../tests/variables/test_file_snapshots.py), [engine serialization](../tests/engine/test_runtime_state_serialization.py), [frame failure restoration](../tests/engine/test_frame_failures.py), [version isolation](../tests/test_snapshot_version_isolation.py) |
| Change model invocation | [graph-facing LLM protocol](../src/graphon/nodes/llm/runtime_protocols.py), [Slim adapter](../src/graphon/dsl/slim/llm.py), [model runtime](../src/graphon/model_runtime/) | [LLM node tests](../tests/nodes/llm/), [Slim tests](../tests/dsl/test_slim_llm.py), [model dispatch](../tests/model_runtime/test_model_dispatch.py) |
| Change file or HTTP integration | [file](../src/graphon/file/), [engine adapter binding](../src/graphon/engine/engine.py), [HTTP](../src/graphon/http/), [node ports](../src/graphon/nodes/protocols.py) | [file tests](../tests/file/), [execution file isolation](../tests/engine/test_file_runtime.py), [HTTP tests](../tests/http/), [HTTP node tests](../tests/nodes/http_request/), [extractor tests](../tests/nodes/document_extractor/) |

Expand Down
8 changes: 7 additions & 1 deletion src/graphon/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def __init__(
container_handler_factories: Sequence[ContainerHandlerFactory] = (),
*,
file_runtime: WorkflowFileRuntimeProtocol | None = None,
emit_frame_events: bool = True,
) -> None:
"""Build an engine for one graph execution.

Expand All @@ -86,6 +87,9 @@ def __init__(
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.
emit_frame_events: Publish frame lifecycle and variable observations.
False skips their construction and value copies without changing
execution. Supply it again when rebuilding from a snapshot.

Raises:
ValueError: If ``workers`` is not a positive integer.
Expand Down Expand Up @@ -114,7 +118,9 @@ def __init__(

# === State Management ===
self._event_stream = EventStream(self._layers)
self._frame_registry = FrameRegistry(self._event_stream)
self._frame_registry = FrameRegistry(
self._event_stream if emit_frame_events else None
)
root_frame = self._frame_registry.create(
frame_id=ROOT_FRAME_ID,
container_id="",
Expand Down
3 changes: 2 additions & 1 deletion src/graphon/engine/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ def reset_observations(self) -> None:
self._open_frame_ids.clear()

def record_failure(self, frame_id: str, error: str) -> None:
self._frame_errors.setdefault(frame_id, error)
if self._event_stream is not None:
self._frame_errors.setdefault(frame_id, error)
if frame_id == ROOT_FRAME_ID:
return
root_state = self[ROOT_FRAME_ID].state
Expand Down
18 changes: 17 additions & 1 deletion src/graphon/file/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,21 @@
from collections.abc import Mapping, Sequence
from typing import Any, assert_never

from pydantic import BaseModel, Field, model_validator
from pydantic import (
BaseModel,
Field,
SerializationInfo,
SerializerFunctionWrapHandler,
model_serializer,
model_validator,
)

from graphon.model_runtime.entities.message_entities import ImagePromptMessageContent

from . import helpers
from .constants import FILE_MODEL_IDENTITY
from .enums import FileTransferMethod, FileType
from .serialization import SerializedFile, file_markers_enabled

_FILE_REFERENCE_PREFIX = "dify-file-ref:"

Expand Down Expand Up @@ -112,6 +120,14 @@ class File(BaseModel):
size: int = -1
_storage_key: str

@model_serializer(mode="wrap")
def _serialize_file( # ruff: ignore[missing-return-type-private-function] - Keep the declared File JSON Schema.
self, handler: SerializerFunctionWrapHandler, info: SerializationInfo
):
if info.mode == "python" and file_markers_enabled():
return SerializedFile(handler(self))
return handler(self)

def __init__(
self,
*,
Expand Down
31 changes: 31 additions & 0 deletions src/graphon/file/serialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Scoped file markers that retain Pydantic's selected fields during projection."""

from collections.abc import Generator
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Any, Final

_FILE_MARKERS_ENABLED: Final[ContextVar[bool]] = ContextVar(
"file_markers_enabled", default=False
)


class SerializedFile: # ruff: ignore[class-as-data-structure] - Pydantic would serialize a dataclass and lose the file marker.
__slots__ = ("data",)

def __init__(self, data: dict[str, Any]) -> None:
self.data = data


def file_markers_enabled() -> bool:
return _FILE_MARKERS_ENABLED.get()


@contextmanager
def mark_serialized_files() -> Generator[None]:
"""Mark files while Pydantic projects their enclosing models."""
token = _FILE_MARKERS_ENABLED.set(True)
try:
yield
finally:
_FILE_MARKERS_ENABLED.reset(token)
7 changes: 6 additions & 1 deletion src/graphon/model_runtime/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!-- knowledge
last_checked: "2026-11-09T05:21:15Z"
last_checked: "2026-11-11T05:46:47Z"
-->
# Model Runtime

Expand Down Expand Up @@ -39,9 +39,14 @@ blocks retain their order and block state; see the
[SlimLLM](../dsl/slim/llm.py) shares this aggregation for blocking ordinary and
structured output calls, covered by the [Slim tests](../../../tests/dsl/test_slim_llm.py).

[LLMResultChunkDelta](entities/llm_entities.py) tool calls with a nonempty function name carry the current argument snapshot, replacing earlier arguments for that ID, including with an empty string.
Updates with an empty name append arguments to their ID, or to the most recently created call when the ID is empty; the latter requires a preceding call.
Calls keep their first-seen order, and a named call without an ID starts a new call with a generated ID; see the [tool call tests](../../../tests/model_runtime/test_large_language_model_tool_calls.py) and [dispatch tests](../../../tests/model_runtime/test_model_dispatch.py).

After a `LargeLanguageModel.invoke` stream is fully consumed without errors, `on_after_invoke` receives a result containing all tool calls, assembled with the same merging rules as blocking results.
Iteration failures, including before the first chunk, notify `on_invoke_error` once with the original exception before normal exception conversion and propagation, and skip `on_after_invoke`.
See the [callback regression tests](../../../tests/model_runtime/test_model_dispatch.py).
With no active callbacks, streaming invocation yields chunks without accumulating a complete result; enabling DEBUG on the wrapper's logger adds a `LoggingCallback` and enables accumulation.

Hosts can display chunks while calling `consume(chunk)` on one [LLMResultAccumulator](model_providers/base/large_language_model.py) per invocation.
After consuming the stream, call its `to_result(model=..., prompt_messages=...)` and use the returned `message` for replay or [JSON persistence](../../../tests/model_runtime/test_llm_result_accumulator.py).
Expand Down
7 changes: 6 additions & 1 deletion src/graphon/model_runtime/entities/llm_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,12 @@ def _validate_intervals(self) -> LLMPollingConfig:


class LLMResultChunkDelta(BaseModel):
"""Model class for llm result chunk delta."""
"""Stream content with tool-call updates and cumulative usage snapshots.

A tool call with a function name carries its current argument snapshot.
Repeating its ID replaces that snapshot. Argument fragments omit the
function name and append to their ID, or to the latest call without an ID.
"""

index: int
message: AssistantPromptMessage
Expand Down
Loading
Loading