Heuristic:1Panel dev MaxKB SSE Chunk Buffering Tip
| Knowledge Sources | |
|---|---|
| Domains | Streaming, Optimization, API |
| Last Updated | 2026-10-10 00:00 GMT |
Overview
Buffer SSE chunks per-node in a FIFO queue (`NodeChunkManage`) and drain them sequentially to preserve node execution order while nodes run concurrently on a thread pool.
Description
MaxKB's workflow engine runs DAG nodes concurrently on a `ThreadPoolExecutor(max_workers=200)`. Each node produces SSE chunks by calling `to_stream_chunk_response()`, which formats data as `data: <json>\n\n` (the SSE protocol). However, chunks from different nodes must be sent to the client in a deterministic order — not the order in which threads happen to complete. The `NodeChunkManage` class maintains a FIFO list of `node_chunk` objects. Each `node_chunk` has its own internal `chunk_list`. The `pop()` method drains the current node's chunks completely before moving to the next node. Between nodes, if the previous node produced output, a `\n\n` separator chunk is injected to visually delimit node outputs.
Usage
Use this heuristic when debugging SSE ordering issues or designing new workflow nodes that produce streaming output. If chunks from different nodes appear interleaved or out of order, verify that the node's `node_chunk.add_chunk()` is being called in the correct sequence and that the `NodeChunkManage` is draining properly. This applies to any workflow using `run_stream()` mode.
The Insight (Rule of Thumb)
- Action: Each node writes chunks to its own `node_chunk.chunk_list` via `add_chunk()`. The `NodeChunkManage.pop()` drains one node at a time in FIFO order.
- Value: `ThreadPoolExecutor(max_workers=200)` allows 200 concurrent nodes, but output is serialized per-node. A `\n\n` separator is injected between consecutive node outputs if the previous node had content.
- Trade-off: High concurrency for computation, but sequential output delivery. A slow node blocks delivery of subsequent nodes' chunks even if they have already completed.
- Compatibility: Works with all `BaseToResponse` implementations (`SystemToResponse`, `OpenAI-compatible`, `LoopToResponse`). The SSE format `data: <json>\n\n` is produced by `BaseToResponse.format_stream_chunk()`.
Reasoning
The workflow engine submits nodes to a `ThreadPoolExecutor` for concurrent execution. Each node runs `run_chain_manage()` which adds its `node_chunk` to the `NodeChunkManage` FIFO list. When the engine yields chunks via `await_result()`, it calls `pop()` repeatedly. The `pop()` method processes the current node's chunk_list until it is exhausted (signaled by `is_end()`), then moves to the next node. This ensures that all chunks from node A are sent before any chunks from node B, even if node B finished first. The `\n\n` separator between nodes serves as a visual delimiter in the chat output. The final chunk is sent with `is_end=True` and empty content to signal stream completion.
Code Evidence
Thread pool with 200 max workers from `apps/application/flow/workflow_manage.py:30`:
executor = ThreadPoolExecutor(max_workers=200)
NodeChunkManage FIFO drain logic from `apps/application/flow/workflow_manage.py:67-89`:
def pop(self):
if self.current_node_chunk is None:
try:
current_node_chunk = self.node_chunk_list.pop(0)
self.current_node_chunk = current_node_chunk
except IndexError as e:
pass
if self.current_node_chunk is not None:
try:
chunk = self.current_node_chunk.chunk_list.pop(0)
return chunk
except IndexError as e:
if self.current_node_chunk.is_end():
self.current_node_chunk = None
if self.work_flow.answer_is_not_empty():
chunk = self.work_flow.base_to_response.to_stream_chunk_response(
self.work_flow.params['chat_id'],
self.work_flow.params['chat_record_id'],
'\n\n', False, 0, 0)
self.work_flow.append_answer('\n\n')
return chunk
return self.pop()
return None
SSE chunk formatting from `apps/common/handle/base_to_response.py:29-30`:
@staticmethod
def format_stream_chunk(response_str):
return 'data: ' + response_str + '\n\n'
Stream result generator from `apps/application/flow/workflow_manage.py:321-350`:
def await_result(self, is_cleanup=True):
try:
while self.is_run():
while True:
chunk = self.node_chunk_manage.pop()
if chunk is not None:
yield chunk
else:
break
while True:
chunk = self.node_chunk_manage.pop()
if chunk is None:
break
yield chunk
finally:
...
yield self.base_to_response.to_stream_chunk_response(
self.params.get('chat_id'),
self.params.get('chat_record_id'),
'', [], '', True, message_tokens, answer_tokens, {})
Node chunk added per node from `apps/application/flow/workflow_manage.py:361`:
self.node_chunk_manage.add_node_chunk(current_node.node_chunk)