Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
a12106d
graph: re-arm pure-streaming loop nodes on every iteration
merceod Sep 21, 2026
9a8b40b
worker: find streaming consumers nested in loops; stop stream-termina…
merceod Sep 21, 2026
4824083
test: loop re-arms a pure-streaming inner node each iteration
merceod Sep 21, 2026
c8e11dc
test: worker finds streaming consumers nested in loops
merceod Sep 21, 2026
08c5617
conductor: end a stream-terminated partition on the worker's final-ch…
merceod Sep 21, 2026
18a1adc
test: stream-terminated partitions end on the worker signal and propa…
merceod Sep 21, 2026
0bd6f52
worker: leave a cancelled request out of its scheduled batch instead …
merceod Sep 23, 2026
66163c9
test: a dropped request is left out of the batch, the others run
merceod Sep 23, 2026
86d733f
Merge remote-tracking branch 'origin/main' into engine/streaming-loop…
NSagan271 Oct 2, 2026
1fa63e8
Fix bug that the pre-merge PR was trying to fix by skipping requests …
NSagan271 Oct 2, 2026
e1be906
check for missing uuids when building executing batch
NSagan271 Oct 2, 2026
8ed8fa8
Revert "Fix bug that the pre-merge PR was trying to fix by skipping r…
NSagan271 Oct 2, 2026
67b2ad3
Drop a stale reference in the missing-uuid backstop comment
NSagan271 Oct 2, 2026
ccf16e9
un-ingest returned streaming edges on cancelled speculation
NSagan271 Oct 3, 2026
845db0f
Merge remote-tracking branch 'origin/main' into engine/streaming-loop…
NSagan271 Oct 3, 2026
4798271
ruff
NSagan271 Oct 3, 2026
98fe080
_settle_speculation is now idempotent on worker
stephen-dwq Oct 3, 2026
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
13 changes: 13 additions & 0 deletions mstar/conductor/conductor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,19 @@ def _process_done_forward(
pstate.metadata = fwd_args.full_metadata
pstate.metadata.kwargs.update(fwd_args.step_metadata)

# The worker's signal is authoritative for a stream-terminated
# partition: the pass that consumed the stream's final chunk has run.
# Treat it as the partition's own `request_done` so its downstream
# connections get `producer_done` and the chain closes. A model that
# inferred the end from the connection counters instead
# (`consumed_count >= token_count`) could race: `consumed_count` counts
# chunks popped for execution, and every worker-graphs-done report from
# a worker carries every buffer's count, so a colocated consumer's report
# could finish this partition while its last step was still running,
# and that step's output arrived for a request already gone.
if incoming_connections and partition_done_from_worker:
fwd_args.request_done = True

# Check max output tokens for partitions that produce tokens
if pstate.num_output_tokens >= request_data.max_output_tokens:
logger.info(
Expand Down
24 changes: 24 additions & 0 deletions mstar/graph/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,16 @@ def _advance_one_iter(self):
self.curr_iter += 1
self.inner_registry.reset_for_iter()
self._uncache_outputs()
# Re-arm pure-streaming inner nodes (no loop-back edge) so the next
# streamed chunk can be fed to them on this new iteration. Walk up
# through any enclosing loops to the worker-graph registry that owns
# the ``ready_for_streaming`` set.
reg = self._managing_registry
while isinstance(reg, LoopStateRegistry):
reg = reg.loop._managing_registry
rearm = getattr(reg, "rearm_streaming", None)
Comment thread
NSagan271 marked this conversation as resolved.
Resolved
if rearm is not None:
rearm(set(self.section.get_nodes().keys()))

def ingest_external_input(self, graph_edge: GraphEdge):
# track one copy of each external input for re-injection on the next iteration
Expand Down Expand Up @@ -779,6 +789,20 @@ def reset_for_iter(self):
self.ready_streaming_next_iter, self.ready_for_streaming
)

def rearm_streaming(self, node_names: set[str]):
"""Re-add a loop's pure-streaming inner nodes to ``ready_for_streaming``.

Called when a ``Loop`` advances an iteration. A node whose inputs are
ALL streaming has no loop-back edge, so nothing re-injects into it
across iterations, and ``register_ingested_input`` already dropped it
from ``ready_for_streaming`` when it consumed the previous chunk.
Without this the loop stalls after one item (a talker or codec loop
that only consumes an upstream stream). Loop-back nodes are re-armed
implicitly by their re-injected inputs, so intersecting with
``only_streaming_inputs`` leaves them untouched.
"""
self.ready_for_streaming |= (node_names & self.only_streaming_inputs)

def clear(self):
super().clear()
self.ready_names.clear()
Expand Down
88 changes: 70 additions & 18 deletions mstar/worker/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from mstar.engine.engine import ExecutingBatch
from mstar.engine.resources import AllocationFailed, StepContext
from mstar.engine.resources.kv.transfer import TransferEngineInfo
from mstar.graph.base import GraphEdge, GraphNode, SpeculativeNodeInfo
from mstar.graph.base import GraphEdge, GraphNode, GraphSection, SpeculativeNodeInfo
from mstar.graph.graph_io import format_graph_edge_list
from mstar.graph.loop_indices import NestedLoopIndices
from mstar.model.base import Model, WorkerGraph
Expand Down Expand Up @@ -400,26 +400,51 @@ def __init__(
conn.edge_name for conn in self._my_consumer_connections
}

# Build consumer node cache: edge_name -> next_node name
# Build consumer node cache: edge_name -> consuming node name.
self._consumer_node_cache: dict[str, str] = {}
if self._my_consumer_connections and model:
walks = model.get_graph_walk_graphs()
for conn in self._my_consumer_connections:
for section in walks.values():
if hasattr(section, 'input_names') and conn.edge_name in section.input_names:
self._consumer_node_cache[conn.edge_name] = section.name
self._consumer_node_cache = self._build_consumer_node_cache(
self._my_consumer_connections, model.get_graph_walk_graphs(),
)

@staticmethod
def _build_consumer_node_cache(
connections, walks: dict[str, GraphSection],
) -> dict[str, str]:
"""Map each incoming streaming edge to the node that consumes it.

Recurses through ``get_nodes()`` so a consumer nested inside a
``Loop`` / ``Sequential`` / ``Parallel`` is found too. Matching the
walk's top-level ``input_names`` only finds a walk that is itself a
single ``GraphNode``; a decode ``Loop`` whose inner node consumes the
streamed edge would be missed, and its chunks routed to ``next_node=""``.
"""
cache: dict[str, str] = {}
for conn in connections:
for section in walks.values():
for node in section.get_nodes().values():
if conn.edge_name in node.input_names:
cache[conn.edge_name] = node.name
Comment thread
NSagan271 marked this conversation as resolved.
Resolved
return cache

def _get_node_names_for_partition(self, partition_name: str, model: Model) -> list[str]:
"""Get the node names that belong to a partition."""
"""Get the node names that belong to a partition.

Recurses into each walk so nodes nested in a ``Loop`` / ``Sequential``
/ ``Parallel`` are included. Taking the section's own ``name`` would
return the Loop's name (e.g. ``"talker_decode_loop"``) instead of the
consuming node's, so its ``StreamBuffer`` would never be created and
routing the streamed edge would fail with a ``KeyError``.
"""
walks = model.get_graph_walk_graphs()
partitions = model.get_partitions()
for pdef in partitions:
if pdef.name == partition_name:
nodes = set()
for walk_name in pdef.graph_walks:
section = walks.get(walk_name)
if section and hasattr(section, 'name'):
nodes.add(section.name)
if section is not None:
nodes.update(section.get_nodes().keys())
return list(nodes)
return []

Expand Down Expand Up @@ -962,24 +987,39 @@ def _build_executing_batch(self, batch: ScheduledBatch) -> ExecutingBatch:
final_stream_rids: set[str] = set()
batch_partition = self.worker_graphs_manager.get_partition_for_node(batch.node_name)

request_ids: list[str] = []
for request_id, node in batch.node_objects.items():
tensors = {}
ready_inputs = node.ready_signals.ready_inputs
for input_name, edge in ready_inputs.items():
tensors[input_name] = [
self.tensor_manager.get_tensor(
request_id=request_id, uuid=info.uuid
) for info in edge.tensor_info
]
try:
for input_name, edge in ready_inputs.items():
tensors[input_name] = [
self.tensor_manager.get_tensor(
request_id=request_id, uuid=info.uuid
) for info in edge.tensor_info
]
fwd_info = self.worker_graphs_manager.get_fwd_info(request_id, batch_partition)
except KeyError:
# The request was cancelled (its tensors and graph state
# dropped) after this batch was scheduled. It has no step to
# run any more; the others in the batch still do, so leave it
# out rather than failing them all with it.
logger.warning(
"Worker %s: request %s was dropped before its %s step ran; leaving it out of the batch",
self.worker_id, request_id, batch.node_name,
)
continue
for edge in ready_inputs.values():
if edge._final_stream_chunk:
final_stream_rids.add(request_id)
per_request_inputs[request_id] = tensors
per_request_info[request_id] = self.worker_graphs_manager.get_fwd_info(request_id, batch_partition)
per_request_info[request_id] = fwd_info
request_ids.append(request_id)

return self._make_executing_batch(
node_name=batch.node_name,
graph_walk=batch.graph_walk,
request_ids=list(batch.node_objects.keys()),
request_ids=request_ids,
per_request_input_tensors=per_request_inputs,
per_request_info=per_request_info,
final_stream_rids=final_stream_rids,
Expand Down Expand Up @@ -2257,6 +2297,18 @@ def _postprocess_batch(
stops = engine.check_stop_for_batch(batch_N.node_batch, cpu_outputs)
# the same host copy, before stops, so a request ending here still indexes its pages
engine.extend_prefix_chains(batch_N.node_batch, cpu_outputs)

# Stream-terminated loop: a stream-consuming node inside a loop has no
# internal stop signal (unlike a self-EOS loop), so when it consumes the
# terminal chunk of its stream (``final_stream_rids``: the StreamBuffer
# popped ``is_final``, which a ``continue_after_done`` policy never
# sets) end its innermost enclosing loop. Without this the loop would
# spin to ``max_iters`` and the partition would never report done.
for rid in batch_N.node_batch.final_stream_rids:
nested = per_req_nested_idxs.get(rid)
if nested is not None and nested.loop_name_order:
stops.setdefault(rid, set()).add(nested.loop_name_order[-1])

if batch_N.node_batch.failed_requests:
# A rid whose stop check raised has no trustworthy stop decision:
# routing it would either run its loop forever or end it early.
Expand Down
104 changes: 104 additions & 0 deletions test/modular/test_stream_partition_done.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""A stream-terminated partition ends on the worker's final-chunk signal.

The worker sets ``partition_done`` on the worker-graphs-done report of the pass
that consumed a stream's final chunk. The conductor must treat that as the
partition's ``request_done`` (so ``producer_done`` reaches its downstream
connections) even when the model reports the partition as not done: the model
only sees connection counters, and ``consumed_count`` counts chunks popped for
execution as reported by every colocated worker-graphs-done message, so a
counter-based end can fire while the partition's last step is still running.
"""
from dataclasses import dataclass, field

from mstar.conductor.conductor import Conductor, RequestData
from mstar.conductor.request_info import (
CurrentForwardConductorMetadata,
PartitionDefinition,
PartitionState,
StreamingConnectionState,
)
from mstar.model.base import ForwardPassArgs


class _StubModel:
"""Never ends a partition on its own; records what it was asked."""

def __init__(self):
self.calls = []

def get_partition_forward_pass_args(self, partition_name, partition_metadata, persist_signals,
incoming_connections=None):
self.calls.append((partition_name, [c.edge_name for c in incoming_connections or []]))
return ForwardPassArgs(full_metadata=partition_metadata, inputs=[], unpersist_tensors=[],
request_done=False)


@dataclass
class _Recorder:
producer_done: list = field(default_factory=list)
partition_inputs: list = field(default_factory=list)


def _conductor(rid="r"):
c = object.__new__(Conductor)
c.model = _StubModel()
rec = _Recorder()
c._send_producer_done = lambda request_id, frm, to: rec.producer_done.append((request_id, frm, to))
c._send_partition_inputs = lambda request_id, pname, fwd_args: rec.partition_inputs.append(pname)
c._un_persist_tensors = lambda request_id, tensors: None
c._set_partition_worker_graph_ids = lambda request_id, pname, walk: None
meta = lambda walk: CurrentForwardConductorMetadata(graph_walk=walk, is_prefill=False) # noqa: E731
conns = {
"A->B": StreamingConnectionState(from_partition="A", to_partition="B", edge_name="tok"),
"B->C": StreamingConnectionState(from_partition="B", to_partition="C", edge_name="codes"),
}
req = RequestData(
persist_signals={}, persist_signal_ref_cnt={}, worker_graph_to_workers={}, all_worker_graph_ids=set(),
max_output_tokens=10_000, random_seed=0, resource_configs={},
partition_states={p: PartitionState(partition_name=p, metadata=meta(p.lower())) for p in "ABC"},
partition_definitions={p: PartitionDefinition(name=p, graph_walks={p.lower()}) for p in "ABC"},
streaming_connections=conns,
)
c.requests = {rid: req}
return c, req, rec


def test_worker_final_chunk_signal_ends_the_partition_and_propagates_producer_done():
c, req, rec = _conductor()
# B consumed the final chunk of A->B: B is done, and C must learn its producer is done
all_done = c._process_done_forward("r", "B", partition_done_from_worker=True)
assert req.partition_states["B"].is_done is True
assert req.streaming_connections["B->C"].producer_done is True
assert rec.producer_done == [("r", "B", "C")]
assert all_done is False # A and C are still running
assert c.model.calls == [("B", ["tok"])]


def test_counter_heuristics_are_not_needed_and_an_ordinary_pass_does_not_end_it():
c, req, rec = _conductor()
# B finished a pass but did not consume the final chunk: it waits for more stream data
all_done = c._process_done_forward("r", "B", partition_done_from_worker=False)
assert req.partition_states["B"].is_done is False
assert req.streaming_connections["B->C"].producer_done is False
assert rec.producer_done == [] and rec.partition_inputs == []
assert all_done is False


def test_partition_without_incoming_connections_ignores_the_flag():
"""A producer-only partition (no stream in) ends only through the model's answer."""
c, req, rec = _conductor()
c._process_done_forward("r", "A", partition_done_from_worker=True)
assert req.partition_states["A"].is_done is False
assert rec.producer_done == []


def test_chain_closes_partition_by_partition():
c, req, rec = _conductor()
c.model.get_partition_forward_pass_args = lambda partition_name, partition_metadata, persist_signals, \
incoming_connections=None: ForwardPassArgs(full_metadata=partition_metadata, inputs=[], unpersist_tensors=[],
request_done=partition_name == "A")
assert c._process_done_forward("r", "A") is False # A ends itself (its own stream input is exhausted)
assert req.streaming_connections["A->B"].producer_done is True
assert c._process_done_forward("r", "B", partition_done_from_worker=True) is False
assert c._process_done_forward("r", "C", partition_done_from_worker=True) is True # every partition done
assert rec.producer_done == [("r", "A", "B"), ("r", "B", "C")]
75 changes: 75 additions & 0 deletions test/modular/test_streaming_consumer_nodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""A streaming consumer nested inside a ``Loop`` must be found by the worker's
partition-node and consumer-node lookups.

Both used to inspect only a walk's top-level section: a walk that is itself a
single ``GraphNode`` matched, but a decode ``Loop`` whose inner node consumes
the streamed edge did not. Its chunks were then routed to ``next_node=""`` and
its ``StreamBuffer`` was never created (``KeyError`` when routing the edge).
"""
from types import SimpleNamespace

from mstar.conductor.request_info import PartitionDefinition
from mstar.graph.base import GraphEdge, GraphNode, Loop, Sequential
from mstar.graph.special_destinations import EMIT_TO_CLIENT
from mstar.streaming.chunk_policy import FixedChunkPolicy
from mstar.streaming.topology import Connection, StreamingGraphEdge
from mstar.worker.worker import Worker


def _model():
producer = GraphNode(
name="producer",
input_names=["text_inputs"],
outputs=[StreamingGraphEdge(next_node="consumer", name="chunk", target_partition="B")],
)
consumer_loop = Loop(
name="consumer_loop",
section=GraphNode(
name="consumer",
input_names=["chunk"],
outputs=[StreamingGraphEdge(next_node="codec", name="codes", target_partition="C")],
),
max_iters=8,
outputs=[],
)
codec_chunk = Sequential([
GraphNode(name="codec", input_names=["codes"],
outputs=[GraphEdge(next_node="post", name="pcm")]),
GraphNode(name="post", input_names=["pcm"],
outputs=[GraphEdge(next_node=EMIT_TO_CLIENT, name="audio", output_modality="audio")]),
])
walks = {"produce": producer, "consume": consumer_loop, "decode_audio": codec_chunk}
partitions = [
PartitionDefinition(name="A", graph_walks={"produce"}, initial_walk="produce"),
PartitionDefinition(name="B", graph_walks={"consume"}, initial_walk="consume", producer_partitions=["A"]),
PartitionDefinition(name="C", graph_walks={"decode_audio"}, initial_walk="decode_audio",
producer_partitions=["B"]),
]
return SimpleNamespace(
get_graph_walk_graphs=lambda: walks,
get_partitions=lambda: partitions,
)


def _connections():
return [
Connection(from_partition="A", to_partition="B", edge_name="chunk",
chunk_policy_factory=lambda: FixedChunkPolicy(chunk_size=1)),
Connection(from_partition="B", to_partition="C", edge_name="codes",
chunk_policy_factory=lambda: FixedChunkPolicy(chunk_size=1)),
]


def test_partition_nodes_recurse_into_loops_and_sequentials():
model = _model()
# ``self`` is unused by the lookup, so call it unbound on a stub.
assert Worker._get_node_names_for_partition(None, "A", model) == ["producer"]
# the Loop's inner node, not the Loop's own name
assert Worker._get_node_names_for_partition(None, "B", model) == ["consumer"]
assert set(Worker._get_node_names_for_partition(None, "C", model)) == {"codec", "post"}
assert Worker._get_node_names_for_partition(None, "missing", model) == []


def test_consumer_node_cache_finds_nested_consumers():
cache = Worker._build_consumer_node_cache(_connections(), _model().get_graph_walk_graphs())
assert cache == {"chunk": "consumer", "codes": "codec"}
Loading
Loading