---
title: "高级：短生命周期父 Flow"
description: "处理完排队的请求后完成父 Flow，不会丢掉最后时刻到达的请求。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/subflows/short-lived-parent/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/subflows/short-lived-parent.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# 高级：短生命周期父 Flow

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/short-lived-parent.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/short-lived-parent.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/short-lived-parent.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/short-lived-parent.rust.md)

处理完排队的请求后完成父 Flow，不会丢掉最后时刻到达的请求。

**Flow 图：AdvancedShortLiveParentFlow**

**Step 列表**

1. `Init`（起始 Step）：Queue the requests and start the request handlers. 下一步：`HandleRequest`。 写入 `CurrSubFlowNum`；发布到 `RequestChannel`。
2. `HandleRequest`：Take the next queued request and count it as running. 下一步：`HandleSubFlow`。 读取 `CurrSubFlowNum`、`RequestChannel`；锁定 `CurrSubFlowNum`；写入 `CurrSubFlowNum`。
3. `HandleSubFlow`：Run a child Flow for the request, then complete once no work remains. 下一步：`HandleRequest`。 读取 `CurrSubFlowNum`；锁定 `CurrSubFlowNum`；写入 `CurrSubFlowNum`。

**RPC 列表**

- `send_request`：读取 `RequestChannel`；发布到 `RequestChannel`。

例子: [examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py)

Init Step 向 `RequestChannel` 写入请求，初始化 `CurrSubFlowNum`，并启动 N 个 worker。`CurrSubFlowNum` 记录正在运行的 SubFlow 数量。HandleRequest Step 的 Execute 持有它的 Attribute lock 并加一；HandleSubFlow Step 的 Execute 持有同一把 lock 并减一。

最后一个 active worker 返回 `ForceCompleteIfChannelsEmpty`。Dex 检查 `RequestChannel`，只有为空才完成 Flow。如果 RPC 已先发布新请求，Dex 改为再调度一个 HandleRequest Step。检查和完成一起发生，中间不会插进新请求。在应用代码里先查 size 再完成做不到这一点。

## 核心实现

**Python**

```python
DEFAULT_CONCURRENCY = 10
MAX_BUFFERED_REQUESTS = 100


class ShortLiveInit(Step[ParentInput]):
    def __init__(
        self,
        request_channel: Channel[str],
        curr_subflow_num: Attribute[int],
    ) -> None:
        self.request_channel = request_channel
        self.curr_subflow_num = curr_subflow_num

    def get_step_type(self) -> str:
        return "Init"

    def execute(self, context: Context, input: ParentInput) -> StepDecision:
        for request in input.requests:
            self.request_channel.publish(context, request)
        self.curr_subflow_num.set(context, 0)
        concurrency = input.concurrency if input.concurrency > 0 else DEFAULT_CONCURRENCY
        return go_to_many(
            *(StepMovement.of(ShortLiveHandleRequest, None) for _ in range(concurrency))
        )


class ShortLiveHandleRequest(Step[None]):
    def __init__(
        self,
        request_channel: Channel[str],
        curr_subflow_num: Attribute[int],
    ) -> None:
        self.request_channel = request_channel
        self.curr_subflow_num = curr_subflow_num

    def get_step_type(self) -> str:
        return "HandleRequest"

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_lock_attributes=(self.curr_subflow_num.lock(),))

    def wait_for(self, context: Context, input: None) -> Wait:
        return Wait.until(self.request_channel.for_one())

    def execute(self, context: Context, input: None) -> StepDecision:
        request = self.request_channel.results(context)[0]
        self.curr_subflow_num.set(context, (self.curr_subflow_num.get(context) or 0) + 1)
        return go_to(ShortLiveHandleSubFlow, request)


class ShortLiveHandleSubFlow(Step[str]):
    def __init__(
        self,
        example_subflow: ExampleSubFlow,
        request_channel: Channel[str],
        curr_subflow_num: Attribute[int],
    ) -> None:
        self.example_subflow = example_subflow
        self.request_channel = request_channel
        self.curr_subflow_num = curr_subflow_num

    def get_step_type(self) -> str:
        return "HandleSubFlow"

    def get_step_options(self) -> StepOptions:
        return StepOptions(execute_lock_attributes=(self.curr_subflow_num.lock(),))

    def wait_for(self, context: Context, request: str) -> Wait:
        return Wait.until(SubFlow.run(self.example_subflow, request))

    def execute(self, context: Context, request: str) -> StepDecision:
        current = (self.curr_subflow_num.get(context) or 0) - 1
        self.curr_subflow_num.set(context, current)
        if current == 0:
            return force_complete_if_channels_empty(
                None,
                StepMovement.of(ShortLiveHandleRequest, None),
                self.request_channel,
            )
        return go_to(ShortLiveHandleRequest, None)


class AdvancedShortLiveParentFlow(Flow[ParentInput]):
    request_channel = Channel("RequestChannel", str)
    curr_subflow_num = Attribute("CurrSubFlowNum", int)

    def __init__(self, example_subflow: ExampleSubFlow) -> None:
        self.init = ShortLiveInit(self.request_channel, self.curr_subflow_num)
        self.handle_request = ShortLiveHandleRequest(
            self.request_channel, self.curr_subflow_num
        )
        self.handle_subflow = ShortLiveHandleSubFlow(
            example_subflow, self.request_channel, self.curr_subflow_num
        )

    def get_steps(self) -> StepList[ParentInput]:
        return StepList.start_step(self.init).other_steps(
            self.handle_request, self.handle_subflow
        )

    def get_persistence_schema(self) -> PersistenceSchema:
        return PersistenceSchema.of(self.request_channel, self.curr_subflow_num)

    @rpc
    def send_request(self, context: Context, request: str) -> RPCResult[bool]:
        if self.request_channel.size(context) >= MAX_BUFFERED_REQUESTS:
            return RPCResult(False)
        self.request_channel.publish(context, request)
        return RPCResult(True)
```

例子: [examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/parallel-subflows/advanced_short_live_parent_flow.py)

<a id="early-requests"></a>

## 空批次和提前到达的请求

示例做了简化：Flow 一启动，它的 RPC 就能发布请求，而且即使批次为空也启动 worker。父 Flow 如果要处理空批次，就加一个接收开关：

- 只有第一个 Step 把启动批次排进队列后，接收才开放。RPC 读取这个开关，在那之前拒绝请求。于是空的启动批次可以直接完成，因为不可能有请求在等待。
- 修改子 Flow 计数的 Step 锁住开关所在的 Attribute。RPC 不加 lock。
- 缓冲上限是软上限。并发的 RPC 可能读到同一个大小，而且 Channel 大小只计算排队中的请求，不包括已经领取的工作。需要硬上限时，用原子的准入，比如加锁的预留。在启动 Flow 的地方用上限检查启动批次。
- 调用方必须确认每个请求都已处理时，消费的 Step 在同一次提交里记录请求的业务 ID，调用方读取这份记录；见 [确认消息已处理](https://docs.superdurable.io/zh-Hans/reference/server/runtime-client.md#confirm-message-handled)（英文）。

以下步骤描述带接收开关的变体。它额外的 Step `AdmitBatch` 不在上面的图中。

1. `AdmitBatch` 持有接收开关 Attribute 的 lock，接收启动批次。批次为空时返回 `GracefulComplete`，因为接收从未开放。
2. 否则 `AdmitBatch` 在同一次提交中把每个请求排进 `Requests` Channel、开放接收、把运行中子 Flow 计数设为 0，并在 `HandleRequest` 中启动 worker。
3. `sendRequest` 不加 lock 地读取接收开关 Attribute。只有在接收开放且当前队列长度低于上限时，它才接受请求，并把它排进同一个 Channel。

## 下一步

- [多父 Flow 分区](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/partitioning.md)
- [Step decision](https://docs.superdurable.io/zh-Hans/reference/python/step-decisions.md#forcecompleteifchannelsempty)
