Repository navigation
Description
Answer nodes inside Loop and Iteration should stream their selected response while each body execution is running. Graphon's external ResponseStreamFilter will assemble and order those replies so downstream applications can consume them without a completion-time workaround.
Preserve the existing Answer node, its answer and files outputs, and ordinary node execution. All response selection, template assembly, caching, buffering, ordering, and stream progress belong to ResponseStreamFilter and its private package. The engine publishes raw producer chunks and generic execution observations.
Status
Updated 2026-12-04. Stage G is verifying the combined Graphon changes and preparing a release readiness report for maintainers. Verification started on merged main at 5d00f29.
| Package | Scope | Status |
|---|---|---|
| A | Generic execution identity, frame lifecycle, and committed values | #366, merged 2026-10-28 |
| B | Reusable template assembly inside the filter package | #365, merged 2026-10-27 |
| C | Answer changes | Canceled; #364 closed without merging. Do not recreate or use as a dependency. |
| D | Per-frame response sessions for Loop and sequential Iteration | #374, merged 2026-11-16 |
| E | Parallel and nested reply ordering | Merged 2026-11-18 in #401 |
| F | Complete filter pause/resume and snapshot compatibility | Merged in #412 |
| G | Integration verification and release readiness | Draft correction #458 is open. Required CI blocks release readiness. |
| H | Dify upgrade, paired snapshots, and duplicate fallback removal | Planned; requires a published Graphon version containing the verified work |
The filter streams eligible replies in order. Its v4 snapshot now records how far each reply has been displayed and retains buffered text across a pause. The published v0.9.0 tag predates #412. H waits for a published Graphon distribution containing the revision verified in G. Graphon v0.9.0.
Problem and expected behavior
Historical code inspection on 2026-10-23 used Dify 9f75925, which pinned Graphon to 4fa2214:
- The outer response filter registered the scoped root graph, excluding inner Answer nodes.
- Child LLM chunks existed, but
ResponseStreamFilter._handle_stream_chunkdropped selectors not referenced by its registered response nodes. - Dify compensated by publishing the entire inner Answer on
NodeRunSucceededEvent, producing one complete reply per round.
The earlier second-round Stream llm.text is already closed failure is documented in dify#42547. This is historical evidence, not a fresh reproduction against current Dify. The related downstream proposal dify#43026 is closed without merging.
Start → Iteration over [1, 2, 3] → Answer: "done"
└─ Iteration Start → LLM → Answer: "result: {{#llm.text#}}\n"
Each eligible round should stream result: , selected LLM tokens, and the newline in template order, exactly once. The following root done must wait for container completion and all pending replies. Loop has the same requirement. In parallel Iteration, raw producer events remain immediate while displayed replies follow numeric item order.
Planned architecture
The diagram shows how E orders replies, how F saves and restores progress, and where Dify will consume the paired snapshots in H. ResponseStreamFilter runs outside engine execution and engine layers.
flowchart TB
FilterInputs["Graph definitions, root template interfaces, run identity and host file adapter"]
subgraph Execution["Engine execution"]
Nodes["Producers and unchanged Answer nodes"]
Frames["Workers, frames and container handlers"]
Events["Raw chunks, traversal, results and generic frame observations"]
Nodes --> Frames --> Events
end
subgraph Filter["External ResponseStreamFilter - owns all response state"]
Selection["Template discovery and frame-qualified reachability"]
Values["Detached frame values and committed replacements"]
Sources["Per-frame source buffers"]
Assembly["Per-frame template sessions and response cursors"]
Ordering["Hierarchical reply order and pending text - E"]
FilterSnapshot["Complete filter snapshot and restore - F"]
LifecycleAndOutputs["Pass through ordinary lifecycle and completed answer/files outputs"]
Selection --> Assembly
Values --> Assembly
Sources --> Assembly
Assembly --> Ordering
Ordering -->|"Drain before graph success"| LifecycleAndOutputs
Selection -.-> FilterSnapshot
Values -.-> FilterSnapshot
Sources -.-> FilterSnapshot
Assembly -.-> FilterSnapshot
Ordering -.-> FilterSnapshot
end
FilterInputs --> Selection
FilterInputs --> Assembly
Events --> Selection
Events --> Values
Events --> Sources
Events -->|"Frame/container lifecycle"| Ordering
Events --> LifecycleAndOutputs
Ordering --> Replies["Selected response chunks"]
Replies --> Host["Host / Dify consumer"]
LifecycleAndOutputs --> Host
Frames -.-> EngineState["Engine execution snapshot"]
EngineState -.-> PairedSnapshots["Host saves and restores both at one drained pause boundary"]
FilterSnapshot -.-> PairedSnapshots
Both output paths pass through the filter. The ordinary result path preserves Answer completion and attachment handling; full-value frame observations and unselected raw chunks are consumed without forwarding them. The host renders text from the filtered reply path and removes its duplicate success-time text fallback in H.
1. Generic engine observations
A has merged the frame event contract, described in the current architecture:
| Event | Contract |
|---|---|
FrameStartedEvent |
Detached typed variable baseline and reserved node execution IDs after setup, before body events; parent frame and owning container invocation/execution identify child context. Item index and declared root metadata are optional for custom containers. |
FrameVariablesUpdatedEvent |
Detached committed replacements at selectors, including empty and None values. Publish successful writes before dependent traversal or child execution; partial failures report only writes that succeeded. |
FrameFinishedEvent |
Terminal outcome after the frame's final direct execution/state event, before removal, even when no Answer was reached. Pause leaves unfinished frames open. |
Keep frame observations enabled (emit_frame_events=True, the default) for these sessions. D's current filter uses them to establish the root baseline as well as child state when initialized with EngineEventFilterContext.from_engine(). Rebuilding an engine must supply its observation option again.
Use the persisted root entry execution ID as run identity, plus frame_id, node execution id, and retry_index; workflow_id alone does not distinguish a new run from a resume. Reserved IDs do not imply that a node is reachable. Retain the existing source chunk payload and retry boundary semantics.
Commit observations cover outputs/defaults, node update requests, Loop initialization, container write-back, shared pools, and successful external-command writes. Update the filter's value view from these committed replacements, without applying request/result outputs a second time. Captured payloads must remain stable after later mutations and frame removal. Generic execution causality must not impose reply order on parallel producers.
2. Per-frame response assembly
D builds on A and B inside the filter package. Its merged implementation preserves root event shapes, shared-selector cursors, and v1/v2 snapshot loading; the child source/cursor and final-marker rules below do not redefine that root contract:
- Discover child Answer/End templates from retained definitions; preserve root Python template interfaces. Do not construct executable child nodes or invoke factories to discover templates.
- Activate eligible sessions on frame start and follow frame-qualified taken/skipped edges. Child bodies do not receive root
GraphRunStartedEvent, and their synthetic start events are hidden. - Keep detached frame values, source buffers, and session progress independently of live engine frames. For child sessions, scope sources by frame, execution, retry attempt, and selector; give each response and repeated template occurrence its own cursor.
- Buffer reverse variable arrival until its template position is eligible. Reuse private assembly helpers and the host file adapter for literals, streaming text, final-value fallback, empty values, and files. Do not replay content already emitted.
- Emit child Answer text using the reserved Answer execution identity and
[answer_id, "answer"]. A source final marker closes only that source; emit exactly one Answer final marker after the whole template, including empty replies. - Keep
pass_unmatched_chunks=False. Consume full-value baselines/commits without forwarding them to reply consumers; they may contain secrets or unselected values. Nested replies are assembled once by their owning session.
For a child Answer with unchanged inputs from a successful producer attempt, concatenated filtered text must equal the completed answer. Retries and overwrites need explicit policies because displayed text cannot be retracted. The filter preserves text already displayed, can replace a wholly hidden retry attempt, and uses committed replacements for later occurrences. Restoring a snapshot must preserve those decisions.
3. Parallel and nested reply ordering
E adds presentation order without changing execution scheduling or the final Iteration result array:
- Stream the currently eligible reply live and keep its prefix, variables, and suffix contiguous. Buffer later items while continuing to consume engine events; blocking consumption could prevent the earlier item from completing.
- Track explicit invocation/frame hierarchy. Reserve a nested group's position at container start, before its first reply. Integrate root sessions and container groups so neither interrupts an active reply.
- An Answer final marker ends one reply, not the body. Advance only after the preceding frame and descendants finish and all their replies drain. Explicit completion releases a frame with no reached Answer; zero-item containers leave no pending group.
- Keep the following root response behind container execution and pending replies. Drain eligible text before graph success. Settle failure/abort on the terminal event because the iterator can raise before
flush(); retain state on pause. - Release frame values and buffered chunks once no unfinished response needs them. Test retry, handled-failure, overwrite, missing-source-final, and terminal-discard behavior without replay or a stuck cursor.
4. Complete filter persistence
F writes filter snapshot v4. It records run identity, per-frame values and templates, source attempts and cursors, traversal state, pending replies, hierarchy, and display positions. A buffered reply survives removal of its execution frame. Merged snapshot implementation.
The v1, v2, and v3 readers restore root progress. Those formats lack child display history, so the filter treats completed legacy frames as drained and suppresses child presentation for the entire restored run, including later rounds. Ordinary answer and files results remain available. A new run enables child streaming again. Snapshot compatibility and resume behavior.
Fully consume the filtered iterator through a quiescent pause before saving the engine and filter snapshots together. Restore that pair and rebind the host file adapter. Repeated initialize() calls through filter_engine_events preserve progress for the same run. A new run of the same workflow starts fresh. The filter owns presentation state.
The no-replay guarantee covers supported paired pause/resume, not network acknowledgements or crash recovery.
Delivery plan
flowchart LR
A["A: engine observations - merged"] --> D["D: per-frame sessions - merged"]
B["B: private assembly helpers - merged"] --> D
D --> E["E: parallel and nested ordering - merged"]
E --> F["F: complete filter snapshots - merged"]
F --> G["G: integration and release readiness - in progress"]
G --> Publish["Maintainer publishes verified Graphon version"]
Publish --> H["H: Dify upgrade and fallback removal"]
The arrows into D/E/F/G require the preceding implementation PRs to merge. G verifies the full acceptance matrix on the combined source and opens a correction PR if necessary; publishing a release remains a separate maintainer action. H waits for a published version containing the verified changes.
- A: Merge generic observations and compatibility suppression of full-value events in the existing filter (feat(engine): expose frame lifecycle and committed values #366).
- B: Merge reusable private assembly while preserving root behavior and snapshots (refactor(response-stream): extract reusable template assembly #365).
- D added per-frame response sessions in #374.
- E added ordered presentation for parallel and nested replies in #401.
- F added paired pause/resume for root and child replies and migration from older root snapshots in #412.
- G reproduced a release blocker on
5d00f29in both Loop and Iteration. When an outer branch skipped a referenced source, the child Answer saved()but streamed only(and a final marker. A second Answer in the same body also failed to display, even though the following root reply and graph success arrived. The draft filter correction restores the suffix and queued replies while preserving the case where a frame finishes without reaching an Answer. Draft #458 and original report in #439. - H: Reinspect current Dify consumers, upgrade the Graphon dependency, persist/restore paired snapshots, and remove duplicate nested-Answer success-time text emission in the same integration change. Preserve
filesand attachment handling. Displayed text may follow node/container success, but must precede workflow success.
Each package follows Development Style: behavior-focused failing tests before implementation, fresh independent test review, relevant checks, knowledge review, and final naming review. Reconcile with merged helpers and subsequent fixes, including #345, rather than implementing against the original planning baseline.
Acceptance matrix
| Area | Required observation |
|---|---|
| Raw execution boundary | Immediate producer chunks with correct frame/attempt identity; no engine-assembled Answer stream or presentation buffers. Frame observations are stable under delayed consumption and later mutation. |
| Frame lifecycle and values | Start before body events; committed writes before dependent traversal; finish after direct events. Include no-reply/zero-item frames, shared pools, partial command writes, Loop initialization/write-back, failure, abort, and resume. |
| Answer compatibility | Existing answer and files, ordinary lifecycle, file formatting, root Answer/End behavior, public filter imports, and custom-container execution remain compatible. |
| Execution compatibility | Existing runtime snapshots remain loadable; execution with one worker and bounded queues continues making progress while the filter consumes events and buffers later replies. |
| Loop and sequential Iteration | At least two rounds; filtered prefix and first selected token arrive before producer completion; each template appears once and reused selectors never inherit another round's closed source. |
| Parallel Iteration | Hold item 0 open while item 1 emits/completes: item 1's raw chunks arrive immediately, item 0 streams live, and displayed replies remain contiguous in numeric item order. |
| Nested/multiple/absent replies | Explicit hierarchy handles repeated same-kind containers and delayed inner replies. Both Answers in item 0 precede item 1; no-reply frames release the next group on completion. A following root response waits for all pending replies. |
| Child template assembly and identity | Reverse variable arrival, repeated references, two Answers sharing a source, empty/non-streaming/file values, prefix/suffix, and retry/overwrite cases; stable child Answer identity and one final marker. |
| Visibility | Unselected output/reasoning and full-value baseline/commit data never enter displayed replies. Keep unmatched-chunk pass-through disabled. |
| Pause/resume | Same-instance and reconstructed engine/filter restore with partial displayed text, later buffered replies, active siblings, between-round pauses, and removed frames; repeated filter initialization, new-run reset, and legacy migration have explicit coverage. |
| Terminal behavior | Handled failures, missing producer finals, skipped branches, retries, overwrites, failure, and abort do not duplicate fallback, leave a stuck cursor, or depend on flush() after an exception. |
| Downstream integration | Published dependency version, paired snapshots, preserved attachments, and removal of success-time text fallback deliver each reply once before workflow success. |
On the correction, G’s readiness report records 214 focused tests and 12 additional public-engine scenarios passing, along with just check and just build. The installed wheel loaded the public filter and runtime, seven snapshot codec modules, and three frozen filter fixtures.
Release decision on 2026-12-04. Hold the release. On draft head 619dd54, both Python 3.12 and 3.13 CI jobs passed 1,465 tests and failed only the repository documentation review deadline check. That check also failed on the starting revision. The required CLA status is missing because the repository’s Actions policy blocked the pull_request_target workflow before it ran a job. Release readiness also requires verifying the merged correction. Dify verification belongs to H after a qualifying release. PR checks, documentation review #457, and CLA diagnostic.
Remaining risks are retention/exposure of captured values, missing a committed mutation path, buffering behind a slow earlier item, loss of filter progress on resume, and duplicate text during the downstream upgrade.
Activity
feat(response-stream): add per-frame response sessions
feat(response-stream): add per-frame response sessions
fix(response-stream): reconcile resume snapshots with main