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
54 changes: 37 additions & 17 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,31 +156,51 @@ event-stream behavior until a frame baseline is supplied.
[Template assembly](src/graphon/engine/filter/builtin/response_stream/template_stream.py)
feeds the filter output for both scopes. Child sources are keyed by execution,
attempt, and selector within their frame; each response and template occurrence
has its own cursor. An occurrence that has started reading a source remains on
that source through retries and overwrites. Retries replace undisplayed attempts;
committed replacements supply later occurrences. Successful and handled-failure
results close unfinished child sources without replaying their final values.
Child Answer chunks use the reserved Answer ID and `[answer_id, "answer"]`, with
one final marker after the complete template, including empty replies. Source
final markers close only their source. Ordinary Answer `answer` and `files`
has its own cursor. Read occurrences retain their source versions across committed
replacements, which supply later occurrences. Retries rebuild wholly undisplayed
child replies using the new attempt without rereading unrelated captured values;
once a reply is displayed, occurrences already reading a source stay on that attempt.
Successful and handled-failure results close unfinished child sources without
replaying their final values. Child Answer chunks use the reserved execution ID and
`[answer_node_id, "answer"]` selector, with one final marker after the complete
template, including empty replies. Source final markers close only their source.
Ordinary Answer `answer` and `files`
outputs and host-bound file formatting remain unchanged.

The filter's [reply order](src/graphon/engine/filter/builtin/response_stream/reply_order.py)
reserves container groups at node start, before their first child reply. Frames
with item indices drain in numeric order within an invocation; a frame keeps its
place until it and its descendants finish and their replies drain. The current
reply streams live from prefix through suffix without interruption by descendants
or siblings.
The filter keeps consuming raw events while later replies wait. Containers without
descendant Answer or End definitions do not delay independent root responses.

Failed or aborted frames close displayed child Answers and discard their remaining
templates. Graph termination also settles frames before `flush()` is needed.
Completed frames release captured values and source buffers. Root chunks retain
their existing event shapes and shared source cursors. Filter persistence supports
only root response state: v1 migration discards child response state, and v2 stores
root state directly. Sessions started from an initial frame baseline record observed
templates. After a failed item, pending siblings wait for container continuation or
a successful or handled result; a failed container discards them. Graph success,
including partial success, drains eligible replies before its terminal event. Graph
failure or abort discards pending replies before `flush()` is needed. Completed
frames release captured values and source buffers; queued text is released as it
drains or is discarded. Root chunks retain their existing event shapes and shared
source cursors.

Filter persistence supports only root response state: v1 migration discards child
response state, and v2 stores root state directly. Sessions started from an initial
frame baseline record observed
skipped edges in v2 snapshots, so resumed templates do not consult future live
node states. Snapshots without this optional metadata retain the paired graph's
skip lookup.
After a child frame containing an Answer or End starts, `dumps()` and `loads()`
reject that filter instance's state, including after the frame finishes. Resuming
such a child frame is also rejected. Child pause/resume support and ordering
across parallel or nested response groups remain follow-up stages of
reject that filter instance's state, including after the frame finishes. Pending
container response reservations are also rejected, including before the first child
frame starts. Resuming a frame in a container with descendant responses is rejected.
Complete child pause/resume and ordering-state serialization remain stage F of
[#356](https://github.com/langgenius/graphon/issues/356).
Current sequential Loop/Iteration behavior, source policies, and these boundaries
are exercised by the [container response tests](tests/engine/test_container_response_streaming.py).
The [container response tests](tests/engine/test_container_response_streaming.py)
cover sequential Loop/Iteration, source policies, files, and snapshot boundaries;
the [reply ordering tests](tests/engine/test_response_reply_ordering.py) cover parallel
and nested replies, failure outcomes, and root compatibility.

## State and execution invariants

Expand Down
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Follow the [variable and container contracts](../ARCHITECTURE.md#state-and-execu
| 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 |
| 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), [container response tests](../tests/engine/test_container_response_streaming.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), [container response tests](../tests/engine/test_container_response_streaming.py), [reply ordering tests](../tests/engine/test_response_reply_ordering.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), [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) |
Expand Down
69 changes: 62 additions & 7 deletions src/graphon/engine/filter/builtin/response_stream/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@
GraphRunSucceededEvent,
)
from graphon.engine_events.node import (
NodeRunExceptionEvent,
NodeRunFailedEvent,
NodeRunReasoningChunkEvent,
NodeRunRetryEvent,
NodeRunStartedEvent,
NodeRunStreamChunkEvent,
NodeRunSucceededEvent,
)
from graphon.engine_events.traversal import GraphEdgeSkippedEvent, GraphEdgeTakenEvent
from graphon.entities.workflow_start_reason import WorkflowStartReason
Expand All @@ -29,8 +34,9 @@
from graphon.runtime.runtime_state import GraphProtocol

from . import snapshot
from .frame_graph import build_child_graph
from .frame_graph import build_child_graph, find_response_container_ids
from .frame_session import _FrameSession
from .reply_order import _ReplyOrder
from .snapshot import ResponseStreamFilterSnapshot

__all__ = ["ResponseStreamFilter"]
Expand All @@ -48,19 +54,23 @@ def __init__(self, *, pass_unmatched_chunks: bool = False) -> None:
self._graph_config: Mapping[str, Any] | None = None
self._awaiting_root_baseline = False
self._has_child_progress = False
self._reply_order = _ReplyOrder()
self._response_container_ids: set[str] = set()

def initialize(self, context: EngineEventFilterContext) -> None:
with use_workflow_file_runtime(context.file_runtime):
self._file_runtime = context.file_runtime
self._root_session = None
self._frame_sessions.clear()
self._reply_order.clear()
self._has_child_progress = False
self._awaiting_root_baseline = context.run_id is not None
root_session = _FrameSession(
cast(GraphProtocol, context.graph),
None
if self._awaiting_root_baseline
else context.runtime_state.variable_pool,
reply_order=self._reply_order,
pass_unmatched_chunks=self._pass_unmatched_chunks,
)
if self._pending_state is not None:
Expand All @@ -70,12 +80,29 @@ 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._pending_state = None

def on_event(self, event: EngineEvent) -> Iterable[EngineEvent]:
self._ensure_initialized()
with use_workflow_file_runtime(self._file_runtime):
return self._process_event(event)
output = self._process_event(event)
chunks = self._reply_order.drain()
if isinstance(
event,
(
GraphRunSucceededEvent,
GraphRunPartialSucceededEvent,
GraphRunFailedEvent,
GraphRunAbortedEvent,
),
):
self._reply_order.clear()
if isinstance(event, GraphRunStartedEvent):
return [*output, *chunks]
return [*chunks, *output]

def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: ignore[too-many-return-statements]
match event:
Expand All @@ -99,6 +126,9 @@ 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._reply_order.finish_frame(
event.frame_id, succeeded=event.outcome == "succeeded"
)
return [*output, event]
case (
GraphRunSucceededEvent()
Expand All @@ -115,6 +145,7 @@ def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: igno
for chunk in session.finish(succeeded=succeeded)
]
self._frame_sessions.clear()
self._reply_order.finish(succeeded=succeeded)
return [*output, event]
case (
FrameVariablesUpdatedEvent()
Expand All @@ -123,6 +154,7 @@ def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: igno
| GraphEdgeSkippedEvent()
):
if session := self._frame_sessions.get(event.frame_id):
self._update_container_replies(event)
return session.on_event(event)
if isinstance(
event,
Expand All @@ -141,38 +173,61 @@ def _process_event(self, event: EngineEvent) -> list[EngineEvent]: # ruff: igno
return []
return [event]

def _update_container_replies(self, event: EngineEvent) -> None:
if not isinstance(event, NodeEvent):
return
if event.node_id not in self._response_container_ids:
return
if isinstance(
event,
(
NodeRunSucceededEvent,
NodeRunExceptionEvent,
NodeRunFailedEvent,
NodeRunRetryEvent,
),
):
self._reply_order.finish_container(event)
if isinstance(event, NodeRunStartedEvent):
self._reply_order.start_container(event)

def _start_frame_session(self, event: FrameStartedEvent) -> list[EngineEvent]:
# Full-value observations are consumed here, never forwarded to the host.
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:
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)
if graph is None:
return []
session = _FrameSession(
graph,
None,
reply_order=self._reply_order,
frame_id=event.frame_id,
container_id=event.container_id,
pass_unmatched_chunks=self._pass_unmatched_chunks,
)
session.register_responses()
if session.has_responses:
if event.reason == WorkflowStartReason.RESUMPTION:
msg = "Resuming child response progress is not supported yet"
raise ValueError(msg)
self._has_child_progress = True
self._frame_sessions[event.frame_id] = session
return session.start(event)

def flush(self) -> Iterable[EngineEvent]:
self._ensure_initialized()
with use_workflow_file_runtime(self._file_runtime):
return [
output = [
event
for session in self._frame_sessions.values()
for event in session.flush()
]
return [*output, *self._reply_order.drain()]

def dumps(self) -> str:
self._check_snapshot_scope()
Expand All @@ -192,7 +247,7 @@ def loads(self, data: str) -> None:

def _check_snapshot_scope(self) -> None:
# shortcut: v1/v2 store root progress only; add child snapshots in stage F.
if self._has_child_progress:
if self._has_child_progress or self._reply_order.has_pending_containers:
msg = "Snapshots containing child response progress are not supported yet"
raise ValueError(msg)

Expand Down
23 changes: 23 additions & 0 deletions src/graphon/engine/filter/builtin/response_stream/frame_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,29 @@ def get_outgoing_edges(self, node_id: str) -> Sequence[_EdgeDefinition]:
return [edge for edge in self.edges.values() if edge.tail == node_id]


def find_response_container_ids(graph_config: Mapping[str, Any] | None) -> set[str]:
if not graph_config:
return set()
node_configs = {config["id"]: config for config in graph_config.get("nodes", [])}
container_ids: set[str] = set()
for config in node_configs.values():
data = config["data"]
node_type = data.type if isinstance(data, BaseNodeData) else data["type"]
if node_type not in {BuiltinNodeTypes.ANSWER, BuiltinNodeTypes.END}:
continue
descendant_config = config
while container_id := resolve_container_id(
descendant_config, nodes_by_id=node_configs
):
if container_id in container_ids:
break
container_ids.add(container_id)
if container_id not in node_configs:
break
descendant_config = node_configs[container_id]
return container_ids


def _build_node_definition(node_id: str, data: Mapping[str, Any]) -> _NodeDefinition:
node_type = data["type"]
node_class = (
Expand Down
Loading
Loading