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
7 changes: 6 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!-- knowledge
last_checked: "2026-11-19T01:18:53Z"
last_checked: "2026-11-24T18:14:20Z"
-->
# Architecture

Expand Down Expand Up @@ -148,6 +148,11 @@ 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
[response gating regressions](docs/development.md#response-gating-regressions).

When a root reply repeats a streamed node output, the filter forwards each unread source chunk with its original final flag.
Once the final chunk has been read, remaining references in that reply emit the buffered text under the reply node's execution ID and text selector.
If the template ends with a repeated reference or a trailing literal, that segment closes the reply.
See the [response filter tests](tests/engine/test_response_stream_filter.py).

[Template assembly](src/graphon/engine/filter/builtin/response_stream/template_stream.py)
keeps child source streams distinct by frame, execution, attempt, and selector.
A child Answer emits under its reserved execution ID and the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@

from __future__ import annotations

from collections import Counter
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from functools import cached_property
from uuid import uuid4

from graphon.engine_events.base import NodeEvent
from graphon.engine_events.node import NodeRunRetryEvent, NodeRunStreamChunkEvent
from graphon.enums import BuiltinNodeTypes, NodeState
from graphon.nodes.base.template import Template, TextSegment, VariableSegment
from graphon.nodes.base.template import Template, VariableSegment
from graphon.runtime.execution import ROOT_FRAME_ID
from graphon.runtime.runtime_state import GraphProtocol, NodeProtocol
from graphon.runtime.runtime_state_protocol import ReadOnlyVariablePool
Expand Down Expand Up @@ -52,6 +54,15 @@ def from_node(cls, node: NodeProtocol) -> _ResponseSession:
def is_complete(self) -> bool:
return self.index >= len(self.template.segments)

@cached_property
def repeated_selectors(self) -> set[Selector]:
selector_counts = Counter(
tuple(segment.selector)
for segment in self.template.segments
if isinstance(segment, VariableSegment)
)
return {selector for selector, count in selector_counts.items() if count > 1}


@dataclass
class _StreamBuffers:
Expand Down Expand Up @@ -271,7 +282,11 @@ def flush(
else:
break
else:
events.extend(self._create_text_chunks(segment, session, graph=graph))
events.extend(
self._create_response_text_chunks(
segment.text, session, graph=graph
)
)
session.index += 1

if (
Expand Down Expand Up @@ -391,10 +406,10 @@ def _read_root_variable_chunks(
else:
output_node_id = source_selector_prefix
execution_id = self._get_or_create_execution_id(output_node_id)
has_stream_events = self.stream_buffers.has_events(segment.selector)
selector = tuple(segment.selector)

while self.stream_buffers.has_unread(segment.selector):
event = self.stream_buffers.pop(segment.selector)
while self.stream_buffers.has_unread(selector):
event = self.stream_buffers.pop(selector)
if event is None:
continue

Expand All @@ -414,9 +429,17 @@ def _read_root_variable_chunks(
else:
events.append(event)

if self.stream_buffers.is_closed(segment.selector):
buffered_events = self.stream_buffers.events.get(selector)
if self.stream_buffers.is_closed(selector):
if (
not events
and buffered_events
and selector in session.repeated_selectors
):
text = "".join(event.chunk for event in buffered_events)
events = self._create_response_text_chunks(text, session, graph=graph)
is_complete = True
elif not has_stream_events and (value := variable_pool.get(segment.selector)):
elif buffered_events is None and (value := variable_pool.get(segment.selector)):
is_last_segment = session.index == len(session.template.segments) - 1
events.append(
self._create_stream_chunk_event(
Expand All @@ -432,9 +455,9 @@ def _read_root_variable_chunks(

return events, is_complete

def _create_text_chunks(
def _create_response_text_chunks(
self,
segment: TextSegment,
text: str,
session: _ResponseSession,
*,
graph: GraphProtocol,
Expand All @@ -452,7 +475,7 @@ def _create_text_chunks(
node_id=current_response_node.id,
execution_id=execution_id,
selector=self._get_text_segment_selector(current_response_node),
chunk=segment.text,
chunk=text,
is_final=is_last_segment,
graph=graph,
)
Expand Down
2 changes: 1 addition & 1 deletion src/graphon/nodes/llm/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ def _yield_run_completion(
)
yield StreamChunkEvent(
selector=[self._node_id, "text"],
chunk="",
chunk=clean_text if self._polling_model_instance() is not None else "",
is_final=True,
)
yield StreamCompletedEvent(
Expand Down
66 changes: 62 additions & 4 deletions tests/engine/test_response_stream_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1364,7 +1364,7 @@ def test_response_stream_filters_keep_interleaved_buffers_and_cursors_separate()


@pytest.mark.parametrize("streamed", [False, True])
def test_response_stream_filter_preserves_shared_selector_consumption(
def test_response_stream_filter_repeats_variable_text_within_one_reply(
streamed: bool,
) -> None:
source = _TestNode("source")
Expand Down Expand Up @@ -1394,17 +1394,75 @@ def test_response_stream_filter_preserves_shared_selector_consumption(
output = list(event_filter.on_event(GraphRunStartedEvent()))
if streamed:
output.extend(
event_filter.on_event(_stream_chunk("value", selector=["source", "text"]))
event_filter.on_event(
_stream_chunk("val", selector=["source", "text"], is_final=False)
)
)
assert (
"".join(
event.chunk
for event in output
if isinstance(event, NodeRunStreamChunkEvent)
)
== "val"
)
output.extend(
event_filter.on_event(_stream_chunk("ue", selector=["source", "text"]))
)

text = "".join(
event.chunk for event in output if isinstance(event, NodeRunStreamChunkEvent)
)
# Root streams currently share one read cursor per selector, unlike saved values.
assert text == ("value/!next:" if streamed else "value/value!next:value")
assert text == ("value/value!next:" if streamed else "value/value!next:value")
Comment thread
WH-2099 marked this conversation as resolved.
Resolved
assert list(event_filter.flush()) == []


@pytest.mark.parametrize(
("chunk_texts", "suffix"),
[(["done"], ""), (["do", "ne", ""], "!")],
ids=["polling", "tokens"],
)
def test_root_reply_forwards_source_chunks_once_for_repeated_references(
chunk_texts: list[str], suffix: str
) -> None:
template = Template.from_answer_template(
"{{#source.text#}}/{{#source.text#}}" + suffix
)
graph = _variable_response_graph(segments=template.segments)
source_chunks = [
_stream_chunk(
text, selector=["source", "text"], is_final=index == len(chunk_texts) - 1
)
for index, text in enumerate(chunk_texts)
]
expected_source_chunks = [event.model_copy(deep=True) for event in source_chunks]
output = filter_engine_events(
[
GraphRunStartedEvent(),
FrameStartedEvent(
frame_id=ROOT_FRAME_ID,
node_execution_ids={"source": "source-run", "answer": "answer-run"},
),
*source_chunks,
],
context=_context(graph),
filters=[ResponseStreamFilter()],
)

chunks = [event for event in output if isinstance(event, NodeRunStreamChunkEvent)]
assert chunks[: len(source_chunks)] == expected_source_chunks
reply_chunks = chunks[len(source_chunks) :]
assert "".join(event.chunk for event in reply_chunks) == "/done" + suffix
assert all(
event.id == "answer-run"
and event.node_id == "answer"
and event.selector == ["answer", "answer"]
for event in reply_chunks
)
assert not any(event.is_final for event in reply_chunks[:-1])
assert reply_chunks[-1].is_final


def test_response_stream_filter_can_load_before_filter_chain_initializes() -> None:
graph = _variable_response_graph()
context = _context(graph)
Expand Down
8 changes: 8 additions & 0 deletions tests/nodes/llm/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,14 @@ def test_polling_llm_checks_until_success(monkeypatch: pytest.MonkeyPatch) -> No
"cursor": "2",
}
assert completed_event.node_run_result.outputs["text"] == "checked"
text_chunks = [
event
for event in events
if isinstance(event, StreamChunkEvent) and event.selector == ["llm", "text"]
]
assert "".join(event.chunk for event in text_chunks) == "checked"
assert not any(event.is_final for event in text_chunks[:-1])
assert text_chunks[-1].is_final


def test_polling_llm_saves_video_output_file(
Expand Down
Loading