sangkyoonnam commented on code in PR #836:
URL: https://github.com/apache/burr/pull/836#discussion_r4182612231
##########
burr/core/parallelism.py:
##########
@@ -171,6 +172,89 @@ async def arun(self, parent_context: ApplicationContext):
)
return state
+ def stream(
+ self,
+ parent_context: ApplicationContext,
+ *,
+ task_key: str,
+ intermediate_stream_outputs: bool,
+ intermediate_nodes: bool,
+ ) -> Generator["StreamItem", None, None]:
+ """Streams results from the sub-application using
Application.stream_iterate."""
+ app = self._create_app_builder(parent_context).build()
+ filtered_inputs = {
+ key: value for key, value in self.inputs.items() if not
key.startswith("__")
+ }
+ for action, streaming_result in app.stream_iterate(
+ halt_after=self.graph.halt_after, inputs=filtered_inputs
+ ):
+ should_emit_node = intermediate_nodes or action.name in
self.graph.halt_after
+ if intermediate_stream_outputs and should_emit_node:
+ for item in streaming_result:
+ yield StreamItem(
+ result=item,
+ state_update=None,
+ action=action,
+ task_key=task_key,
+ application_id=self.application_id,
+ )
+ result, state = streaming_result.get()
+ if should_emit_node:
+ yield StreamItem(
+ result=result,
+ state_update=state,
+ action=action,
+ task_key=task_key,
+ application_id=self.application_id,
+ )
+
+ async def astream(
+ self,
+ parent_context: ApplicationContext,
+ *,
+ task_key: str,
+ intermediate_stream_outputs: bool,
+ intermediate_nodes: bool,
+ ) -> AsyncGenerator["StreamItem", None]:
+ """Streams results from the sub-application using
Application.astream_iterate."""
+ app = await self._create_app_builder(parent_context).abuild()
Review Comment:
`astream` always calls `abuild()`. `arun` at 157-168 falls back to `build()`
with a warning when the persister or initializer is sync. So an async
`MapStates` under a parent with a sync persister works with `arun()` and fails
here. `AsyncMap` below is an async `MapStates` that doubles each of `xs` into
`ys`:
```python
app = (ApplicationBuilder().with_actions(m=AsyncMap(), final=Result("ys"))
.with_transitions(("m", "final")).with_state(xs=[1, 2, 3])
.with_entrypoint("m").with_state_persister(InMemoryPersister()).build())
_, res = await app.astream_result(halt_after=["m"])
async for _ in res:
pass
# ValueError: You are building the async application, but have used an sync
persister...
```
On main the same call ends with `ys=[2, 4, 6]` in state. Sharing the builder
branch with `arun` would keep the two in step.
##########
burr/core/parallelism.py:
##########
@@ -308,6 +394,142 @@ async def state_generator():
return _arun_and_update() # type: ignore
return _run_and_update()
+ def stream_run_and_update(
+ self, state: State, **run_kwargs
+ ) -> Union[Generator[Tuple[StreamItem, Optional[State]], None, None],
AsyncGenerator]:
+ """Streaming counterpart to run_and_update for parallel actions."""
+ if self.is_async():
+ return self._astream_run_and_update(state, **run_kwargs)
+ return self._stream_run_and_update(state, **run_kwargs)
+
+ def _stream_run_and_update(
+ self, state: State, **run_kwargs
+ ) -> Generator[Tuple[StreamItem, Optional[State]], None, None]:
+ context: ApplicationContext = run_kwargs.get("__context")
+ if context is None:
+ raise ValueError("This action requires a context to run")
+ state_without_internals = state.wipe(
+ delete=[item for item in state.keys() if item.startswith("__")]
+ )
+ tasks = list(self.tasks(state_without_internals, context, run_kwargs))
+ emitted_results: "queue.Queue[StreamItem]" = queue.Queue()
+
+ def execute_task(task_index: int, task: SubGraphTask) -> Tuple[int,
State]:
+ task_key = str(task_index)
+ final_state = None
+ for item in task.stream(
+ context,
+ task_key=task_key,
+ intermediate_stream_outputs=self._intermediate_stream_outputs,
+ intermediate_nodes=self._intermediate_nodes,
+ ):
+ if item.state_update is not None:
+ final_state = item.state_update
+ emitted_results.put(item)
+ if final_state is None:
+ raise ValueError(
+ "Parallel streaming task did not emit a final state
update. "
+ "Ensure the subgraph halts on a concrete node."
+ )
+ return task_index, final_state
+
+ final_states: Dict[int, State] = {}
+ with context.parallel_executor_factory() as executor:
Review Comment:
This one isn't a regression, since main's map action ran every branch to
completion before returning anything. It's new with streaming: when the
consumer stops early, the branches keep running, and finalizing the stream
blocks until they finish. Three branches, five tokens at 0.3s each:
```python
_, res = app.stream_result(halt_after=["par"])
for item in res:
break
del res # returns at once; the stream sits in a reference cycle
gc.collect() # took 1.22s; all three branches ran to completion
```
So the wait lands on whichever GC pass collects the stream, which can be
unrelated later code. The `with` exit waits in `shutdown(wait=True)`. A cleanup
path inside that block, before the wait, could cancel queued futures and have
each worker check a flag between items. That's cooperative, so it won't
interrupt a branch blocked on I/O, and it only runs when the generator is
closed. The container has no public `close()` today, so prompt early exit would
need one too. Whether that lands here or in a follow-up seems like a call for
the maintainers.
##########
burr/core/parallelism.py:
##########
@@ -308,6 +394,142 @@ async def state_generator():
return _arun_and_update() # type: ignore
return _run_and_update()
+ def stream_run_and_update(
+ self, state: State, **run_kwargs
+ ) -> Union[Generator[Tuple[StreamItem, Optional[State]], None, None],
AsyncGenerator]:
+ """Streaming counterpart to run_and_update for parallel actions."""
+ if self.is_async():
+ return self._astream_run_and_update(state, **run_kwargs)
+ return self._stream_run_and_update(state, **run_kwargs)
+
+ def _stream_run_and_update(
+ self, state: State, **run_kwargs
+ ) -> Generator[Tuple[StreamItem, Optional[State]], None, None]:
+ context: ApplicationContext = run_kwargs.get("__context")
+ if context is None:
+ raise ValueError("This action requires a context to run")
+ state_without_internals = state.wipe(
+ delete=[item for item in state.keys() if item.startswith("__")]
+ )
+ tasks = list(self.tasks(state_without_internals, context, run_kwargs))
+ emitted_results: "queue.Queue[StreamItem]" = queue.Queue()
+
+ def execute_task(task_index: int, task: SubGraphTask) -> Tuple[int,
State]:
+ task_key = str(task_index)
+ final_state = None
+ for item in task.stream(
+ context,
+ task_key=task_key,
+ intermediate_stream_outputs=self._intermediate_stream_outputs,
+ intermediate_nodes=self._intermediate_nodes,
+ ):
+ if item.state_update is not None:
+ final_state = item.state_update
+ emitted_results.put(item)
+ if final_state is None:
+ raise ValueError(
+ "Parallel streaming task did not emit a final state
update. "
+ "Ensure the subgraph halts on a concrete node."
+ )
+ return task_index, final_state
+
+ final_states: Dict[int, State] = {}
+ with context.parallel_executor_factory() as executor:
+ if not hasattr(executor, "submit"):
+ raise TypeError("Parallel streaming requires an executor that
supports submit().")
+ futures = [
+ executor.submit(execute_task, task_index, task)
+ for task_index, task in enumerate(tasks)
+ ]
+ while futures:
+ try:
+ item = emitted_results.get(timeout=0.01)
+ yield item, None
+ continue
+ except queue.Empty:
+ pass
+ still_running = []
+ for future in futures:
+ if future.done():
+ task_index, final_state = future.result()
+ final_states[task_index] = final_state
+ else:
+ still_running.append(future)
+ futures = still_running
+ while not emitted_results.empty():
+ yield emitted_results.get(), None
+
+ def state_generator() -> Generator[State, None, None]:
+ for task_index in range(len(tasks)):
+ yield final_states[task_index]
+
+ final_state = self.reduce(state_without_internals, state_generator())
+ final_state = final_state.update(
+ **{key: value for key, value in state.get_all().items() if
key.startswith("__")}
+ )
+ yield {}, final_state
+
+ async def _astream_run_and_update(
+ self, state: State, **run_kwargs
+ ) -> AsyncGenerator[Tuple[StreamItem, Optional[State]], None]:
+ context: ApplicationContext = run_kwargs.get("__context")
+ if context is None:
+ raise ValueError("This action requires a context to run")
+ state_without_internals = state.wipe(
+ delete=[item for item in state.keys() if item.startswith("__")]
+ )
+ all_tasks = await
async_utils.arealize(self.tasks(state_without_internals, context, run_kwargs))
+ emitted_results: asyncio.Queue[StreamItem] = asyncio.Queue()
+
+ async def execute_task(task_index: int, task: SubGraphTask) ->
Tuple[int, State]:
+ task_key = str(task_index)
+ final_state = None
+ async for item in task.astream(
+ context,
+ task_key=task_key,
+ intermediate_stream_outputs=self._intermediate_stream_outputs,
+ intermediate_nodes=self._intermediate_nodes,
+ ):
+ if item.state_update is not None:
+ final_state = item.state_update
+ await emitted_results.put(item)
+ if final_state is None:
+ raise ValueError(
+ "Parallel streaming task did not emit a final state
update. "
+ "Ensure the subgraph halts on a concrete node."
+ )
+ return task_index, final_state
+
+ workers = [asyncio.create_task(execute_task(i, task)) for i, task in
enumerate(all_tasks)]
Review Comment:
Same on the async side. After `break` and `del res`, all three workers are
still pending and run to completion about 1.2s later. Cancelling the unfinished
`workers` in a `finally` and awaiting all of them with `gather(...,
return_exceptions=True)` would clean up once the generator is closed. It would
also retrieve the failed workers' exceptions, which show up as "Task exception
was never retrieved" in the persister case above. Main's `arun()` also leaves
siblings running when one branch raises, so that part goes beyond this PR. A
test that breaks after the first item and then closes the stream would pin the
early-exit behavior down for both variants.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]