---
title: "有业务标识的子 Flow"
description: "当每个子任务都有自己的业务编号时，使用这个模式。人和其他系统用这个编号查找、重试或停止子任务。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/subflows/child-flows-with-business-identity.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/child-flows-with-business-identity.go.md) · [Java](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.rust.md)

当每个子任务都有自己的业务编号时，使用这个模式。人和其他系统用这个编号查找、重试或停止子任务。

例如，一个订单分成几个包裹发货。每个发货单有一个发货单号。承运商、客服团队和订单都用这个单号找到发货单。订单仍然需要知道每个发货单最后的结果。

订单把每个发货单作为独立的顶层 Flow 启动。发货单号就是它的 Flow ID。

**Flow 图：OrderFulfillmentFlow**

**Step 列表**

1. `StartShipments`（起始 Step）：Checks the order, registers its shipment numbers, then starts one branch per shipment. 下一步：Flow 失败、Flow 完成，或 `StartShipment`。 写入 `shipmentRecords`；锁定 `shipmentRecordsLock`。
2. `AwaitShipment`：Reads the claimed shipment run at each interval until it ends. 下一步：`AwaitShipment`（再次），或 `RecordShipmentEnd`。
3. `ClaimShipment`：Claims the started run and merges a report that arrived before the claim. 下一步：Flow 完成，或 `AwaitShipment`。 读取 `pendingShipmentReports`；写入 `pendingShipmentReports`、`shipmentRecords`；锁定 `shipmentRecordsLock`。
4. `RecordShipmentEnd`：Records how the claimed shipment run ended. 下一步：Flow 完成。 写入 `shipmentRecords`；锁定 `shipmentRecordsLock`。
5. `StartShipment`：Starts the shipment as a top-level Flow named by its shipment number. 下一步：`ClaimShipment`。

**RPC 列表**

- `record_shipment_outcome`：读取 `pendingShipmentReports`、`shipmentRecords`；写入 `pendingShipmentReports`、`shipmentRecords`；锁定 `shipmentRecordsLock`。

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

**Flow 图：ShipmentFlow**

**Step 列表**

1. `DeliverShipment`（起始 Step）：Waits for the carrier, then commits the delivered outcome. 下一步：`ReportShipmentOutcome`。 写入 `shipmentOutcome`。
2. `ReportShipmentOutcome`：Reports the committed outcome to the order that started this shipment. 下一步：Flow 完成。

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

<a id="how-it-works"></a>

## 工作方式

1. `StartShipments` 为每个发货单启动一个分支。
2. `StartShipment` 通过 Client 启动一个 `ShipmentFlow`。它的 Flow ID 是发货单号。发货单有自己的 Flow timeout。`StartShipment` 把启动返回的 run ID 交给下一个 Step。
3. `ClaimShipment` 把这个 run ID 记录为被认领的 run。它还会合并在认领之前到达的报告。
4. 发货单送达。`DeliverShipment` 把结果存进 `shipmentOutcome` Attribute。
5. `ReportShipmentOutcome` 带着自己的 run ID 调用订单的报告 RPC。这个 RPC 在 Go 里是 `RecordShipmentOutcome`，在 Python 里是 `record_shipment_outcome`，在 Java、TypeScript 和 Rust 里是 `recordShipmentOutcome`。它把结果填进该发货单的记录。
6. `AwaitShipment` 每隔一段时间读取一次这个 run。仍在运行的发货单稍后再读。发货单关闭后，`RecordShipmentEnd` 记录终止状态；如果报告还没有填入结果，它也记录读到的结果。

报告 RPC 和写这些记录的 Step 共用一把锁。RPC 从不等锁：Step 持有锁时，RPC 直接失败。Step 的锁在它的重试和退避期间一直持有。所以调用 Client 的 Step，也就是 `StartShipment` 和 `AwaitShipment`，不拿锁。它们各自把结果交给一个只写记录的短小加锁 Step。

自己失败或超时的发货单不会报告，因为它的报告 Step 不会运行。第 6 步的定时读取会处理它。子 Flow 也可以把最终失败转到一个恢复 Step，或把超时交给 timeout handler，由它们向父 Flow 报告。每个发货单的 Flow timeout 要长于它的重试预算。

示例处理的边界情况见[生产检查清单](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.md#production-checklist)。

**Python**

```python
# dex:group group-id:start group-label:"Start shipments"
# dex:explanation text:"Starts the shipment as a top-level Flow named by its shipment number."
class StartShipment(Step[TrackedShipment]):
    """Starts ShipmentFlow with the shipment number as its Flow ID.

    It takes no lock: a report must never wait for the start call or its retries.
    """

    def __init__(
        self,
        client_provider: Callable[[], AsyncClient],
        shipment_flow: ShipmentFlow,
    ) -> None:
        self.client_provider = client_provider
        self.shipment_flow = shipment_flow

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, tracked: TrackedShipment
    ) -> StepDecision:
        number = tracked.shipment.shipment_number
        try:
            run_id = await self.client_provider().start_flow(
                self.shipment_flow,
                number,
                ShipmentRequest(order_flow_id=context.flow_id, shipment=tracked.shipment),
                StartFlowOptions(
                    timeout=SHIPMENT_TIMEOUT,
                    id_reuse_policy=IdReusePolicy.DISALLOW,
                    request_id=shipment_start_request_id(context.flow_id, tracked.shipment),
                    ignore_already_started=True,
                ),
            )
        except FlowAlreadyStartedError:
            # Another request owns this shipment number; this order does not track it.
            return go_to(ClaimShipment, StartedShipment(tracked=tracked, rejected=True))
        return go_to(
            ClaimShipment,
            StartedShipment(tracked=dataclasses.replace(tracked, shipment_run_id=run_id)),
        )


# dex:group group-id:start group-label:"Start shipments"
# dex:explanation text:"Claims the started run and merges a report that arrived before the claim."
class ClaimShipment(Step[StartedShipment]):
    """Records the claimed run, or the rejection, and merges a pending report of that run."""

    def get_step_options(self) -> StepOptions:
        """Takes the records lock, so the claim never races a report."""
        return StepOptions(
            execute_lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
            execute_load_attribute_maps=(PENDING_SHIPMENT_REPORTS,),
        )

    def execute(self, context: Context, started: StartedShipment) -> StepDecision:
        number = started.tracked.shipment.shipment_number
        pending: dict[str, ShipmentReport] | None = PENDING_SHIPMENT_REPORTS.get(context, number)
        # The claim or the rejection settles every early report of this shipment.
        if pending is not None:
            PENDING_SHIPMENT_REPORTS.delete(context, number)
        if started.rejected:
            SHIPMENT_RECORDS.set(context, number, ShipmentRecord(status=SHIPMENT_REJECTED))
            return graceful_complete()
        run_id = started.tracked.shipment_run_id
        # Claim the run: reports and reads of any other run of this number are ignored.
        report = (pending or {}).get(run_id)
        outcome = report.outcome if report is not None else ""
        SHIPMENT_RECORDS.set(
            context,
            number,
            ShipmentRecord(status=SHIPMENT_STARTED, run_id=run_id, outcome=outcome),
        )
        return go_to(AwaitShipment, started.tracked)


# dex:group group-id:track group-label:"Track shipment"
# dex:explanation text:"Reads the claimed shipment run at each interval until it ends."
class AwaitShipment(Step[TrackedShipment]):
    """Reads the claimed shipment run at each interval until it ends.

    It takes no lock: a report must never wait for the reads or their retries.
    """

    def __init__(self, client_provider: Callable[[], AsyncClient]) -> None:
        self.client_provider = client_provider

    def wait_for(self, context: Context, tracked: TrackedShipment) -> Wait:
        return Wait.until(
            Timer.by_duration(timedelta(seconds=tracked.reconcile_interval_seconds))
        )

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, tracked: TrackedShipment
    ) -> StepDecision:
        number = tracked.shipment.shipment_number
        reading = await reconcile_shipment(
            self.client_provider(), number, tracked.shipment_run_id
        )
        if reading.status == FlowStatus.RUNNING.value:
            return go_to(AwaitShipment, tracked)
        return go_to(
            RecordShipmentEnd,
            EndedShipment(
                shipment_number=number,
                shipment_run_id=tracked.shipment_run_id,
                reading=reading,
            ),
        )


# dex:group group-id:track group-label:"Track shipment"
# dex:explanation text:"Records how the claimed shipment run ended."
class RecordShipmentEnd(Step[EndedShipment]):
    """Merges the terminal status, and the read outcome when no report filled it."""

    def get_step_options(self) -> StepOptions:
        """Takes the same lock as the report RPC and loads the records."""
        return StepOptions(
            execute_lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
            execute_load_attribute_maps=(SHIPMENT_RECORDS,),
        )

    def execute(self, context: Context, ended: EndedShipment) -> StepDecision:
        # Merge with the record, which may already hold the reported outcome.
        record, _ = load_shipment_record(context, ended.shipment_number)
        SHIPMENT_RECORDS.set(
            context,
            ended.shipment_number,
            ShipmentRecord(
                status=ended.reading.status,
                run_id=ended.shipment_run_id,
                outcome=record.outcome or ended.reading.outcome,
            ),
        )
        return graceful_complete()

async def reconcile_shipment(client: AsyncClient, number: str, run_id: str) -> ShipmentRecord:
    """Reads the claimed run of a shipment: its status first, then its outcome.

    Returns a "running" record while that run runs, and an "unavailable" record
    when that run no longer exists or another run replaced it. Keeps an outcome
    only when the run is still the claimed one after the read. Any other failure
    raises, so the Step retries.
    """
    info, found = await describe_claimed_run(client, number, run_id)
    if info is None or not found:
        return ShipmentRecord(status=SHIPMENT_UNAVAILABLE)
    if info.status is FlowStatus.RUNNING:
        return ShipmentRecord(status=info.status.value)
    try:
        values = await client.get_attributes(number, SHIPMENT_OUTCOME)
    except FlowNotFoundError:
        return ShipmentRecord(status=info.status.value)
    # The Attribute read targets the latest run, so confirm it is still the claimed one.
    _, still_claimed = await describe_claimed_run(client, number, run_id)
    if not still_claimed:
        return ShipmentRecord(status=info.status.value)
    # An unset outcome Attribute leaves the outcome empty: the shipment ended without one.
    return ShipmentRecord(
        status=info.status.value, outcome=values.get(SHIPMENT_OUTCOME, "")
    )
```

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

<a id="report-after-the-outcome-commits"></a>

## 结果提交后再报告

发货单在一个 Step 里提交结果，在下一个 Step 里报告。两个 Step 都为 `Execute` 显式声明 SYNC durability。这样即使 Flow 默认是 ASYNC，报告 Step 也只会在结果存好之后开始。

报告带上发货单自己的 run ID。Client 支持 RPC request ID 时，报告还带有稳定的 request ID：`report:`、发货单号、`:` 和 run ID。

订单已经关闭时，报告会返回带类型的错误。发货单到此结束尝试。它的结果仍然可以通过 Client 读取。

**Python**

```python
# dex:group group-id:deliver group-label:"Deliver"
# dex:explanation text:"Waits for the carrier, then commits the delivered outcome."
class DeliverShipment(Step[ShipmentRequest]):
    """Waits for the simulated carrier, then stores the outcome."""

    def get_step_options(self) -> StepOptions:
        """Stores the outcome before the report Step starts, even when the Flow defaults to ASYNC."""
        return StepOptions(execute_durability=StepDurability.SYNC)

    def wait_for(self, context: Context, request: ShipmentRequest) -> Wait:
        return Wait.until(
            Timer.by_duration(timedelta(seconds=request.shipment.delivery_delay_seconds))
        )

    def execute(self, context: Context, request: ShipmentRequest) -> StepDecision:
        outcome = "delivered to " + request.shipment.destination
        SHIPMENT_OUTCOME.set(context, outcome)
        return go_to(
            ReportShipmentOutcome,
            PendingReport(
                order_flow_id=request.order_flow_id,
                report=ShipmentReport(
                    shipment_number=request.shipment.shipment_number,
                    shipment_run_id=context.run_id,
                    outcome=outcome,
                ),
            ),
        )


# dex:group group-id:report group-label:"Report"
# dex:explanation text:"Reports the committed outcome to the order that started this shipment."
class ReportShipmentOutcome(Step[PendingReport]):
    """Sends the committed outcome to the order's RPC."""

    def __init__(
        self,
        client_provider: Callable[[], AsyncClient],
        order_flow_provider: Callable[[], OrderFulfillmentFlow],
    ) -> None:
        self.client_provider = client_provider
        self.order_flow_provider = order_flow_provider

    def get_step_options(self) -> StepOptions:
        """Keeps the report SYNC, like the Step that stores the outcome."""
        return StepOptions(execute_durability=StepDurability.SYNC)

    async def execute(  # type: ignore[override]
        self, context: AsyncContext, pending: PendingReport
    ) -> StepDecision:
        try:
            await self.client_provider().invoke_rpc(
                self.order_flow_provider().record_shipment_outcome,
                pending.order_flow_id,
                pending.report,
                options=RPCInvokeOptions(
                    request_id=f"report:{pending.report.shipment_number}:{pending.report.shipment_run_id}",
                ),
            )
        except (FlowNotFoundError, FlowNotActiveOrNotFoundError):
            # A closed order ends the attempts; the outcome stays readable through the Client.
            pass
        return graceful_complete(pending.report.outcome)
```

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

<a id="records"></a>

## 每个发货单一条记录

订单在 `shipmentRecords` AttributeMap 里为每个发货单保存一条记录，以发货单号为键。记录把状态、被认领的 run ID 和结果分成三个字段。

报告 RPC 把结果填进发货单的记录。报告可能在 `ClaimShipment` 记录 run 之前到达。这时 RPC 把它存进 `pendingShipmentReports` AttributeMap，以发货单号为键。每一项保存每个 run ID 的第一份报告。`ClaimShipment` 合并被认领 run 的报告。它接受哪些报告，见[生产检查清单](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/child-flows-with-business-identity.md#production-checklist)。

**Python**

```python
@rpc(
    lock_attributes=(SHIPMENT_RECORDS_LOCK.lock(),),
    load_attribute_maps=(SHIPMENT_RECORDS, PENDING_SHIPMENT_REPORTS),
)
def record_shipment_outcome(self, context: Context, report: ShipmentReport) -> None:
    """Fills the outcome of a shipment's record.

    It accepts only the run this order claimed. The first report wins, and
    any other report changes nothing. Before the claim, it keeps the first
    report of each run for ClaimShipment to merge.
    """
    record, found = load_shipment_record(context, report.shipment_number)
    # Ignore an unknown shipment and a report without a run.
    if not found or not report.shipment_run_id:
        return
    if record.status == SHIPMENT_STARTING:
        pending: dict[str, ShipmentReport] = (
            PENDING_SHIPMENT_REPORTS.get(context, report.shipment_number) or {}
        )
        if report.shipment_run_id not in pending:
            PENDING_SHIPMENT_REPORTS.set(
                context,
                report.shipment_number,
                {**pending, report.shipment_run_id: report},
            )
        return
    # Ignore a rejected shipment, another run, and a repeated report.
    if (
        not record.run_id
        or record.run_id != report.shipment_run_id
        or record.outcome
    ):
        return
    SHIPMENT_RECORDS.set(
        context,
        report.shipment_number,
        dataclasses.replace(record, outcome=report.outcome),
    )
```

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/order_fulfillment_flow.py)

`AwaitShipment` 每隔一段时间描述一次发货单。仍在运行的发货单在下一个间隔再读，即使它的报告已经到达。发货单关闭后，`RecordShipmentEnd` 记录它的状态；报告还没有填入结果时，也记录结果。

客服团队可以按单号取消发货单。在结果提交之前被取消的发货单没有结果，订单把它记录为 `canceled`。在结果提交之后、或在报告发出之后被取消的发货单仍可能有结果，订单会保留它。

<a id="lookup"></a>

## 按单号查找发货单

任何调用方都可以按单号找到发货单，不需要知道订单。示例的 HTTP 路由先描述这个 ID 对应的 Flow。它不是 `ShipmentFlow` 时返回 404，所以订单 ID 不能被当作发货单读取或取消。

**Python**

```python
async def describe_shipment(number: str) -> FlowInfo | None:
    """Describes the Flow named by a shipment number.

    Returns None when no ShipmentFlow has that Flow ID. Any other failure raises.
    """
    try:
        info = await app_state.client.describe_flow(number)
    except FlowNotFoundError:
        return None
    return info if info.flow_type == SHIPMENT_FLOW_TYPE else None

@blueprint.get("/shipment")
async def get_shipment() -> tuple[dict[str, str], int]:
    """Looks a shipment up by its shipment number, which is its Flow ID."""
    number = required_query("shipmentNumber")
    info = await describe_shipment(number)
    if info is None:
        return {"error": f"shipment {number} not found"}, 404
    values = await app_state.client.get_attributes(number, SHIPMENT_OUTCOME)
    return {
        "shipmentNumber": number,
        "status": info.status.value,
        "outcome": values.get(SHIPMENT_OUTCOME, ""),
    }, 200

@blueprint.get("/cancel-shipment")
async def cancel_shipment() -> tuple[str | dict[str, str], int]:
    """Stops a shipment by its number. Its order records it at the next reconcile read."""
    number = required_query("shipmentNumber")
    if await describe_shipment(number) is None:
        return {"error": f"shipment {number} not found"}, 404
    await app_state.client.stop_flow(
        number,
        StopFlowOptions(type=StopType.CANCEL, reason="shipment canceled"),
    )
    return "canceled", 200
```

例子: [examples/python/dex_examples/patterns/child-flows-business-identity/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/child-flows-business-identity/controller.py)

可以在 [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) 里试用这些路由。发货单字段默认是当前订单的第二个发货单。

<a id="choose"></a>

## 选择这个模式还是 SubFlow

子任务只为父 Flow 存在时，选择 [SubFlow](https://docs.superdurable.io/zh-Hans/concepts/primitives/subflow.md)。Dex 从父 Flow 派生它的 Flow ID，父 Flow 用 Condition 等待它。

子任务需要自己的标识时，选择顶层子 Flow：

- 人或系统按它自己的编号查找、重试或停止它。
- 父 Flow 之外的调用方也可以启动它。
- 它可以比父 Flow 活得更久，有自己的 Flow timeout。

代价是更多代码。父 Flow 要启动子 Flow、认领它的 run、接收它的报告，并一直读取它，直到它结束。

<a id="production-checklist"></a>

## 生产检查清单

- **认领子 run。** 启动返回后，`ClaimShipment` 记录 run ID。从这以后，订单只接受这个 run 的报告和读取。订单先把每个单号登记为 `starting`。所有写这些记录的地方都锁住单例 Attribute `shipmentRecordsLock`：`StartShipments`、`ClaimShipment`、`RecordShipmentEnd` 和报告 RPC。这个锁 Attribute 不存任何值，只让写入方一次一个地修改记录。
- **加锁的 Step 里不调用 Client。** `StartShipment` 和 `AwaitShipment` 调用 Client，不拿锁。报告遇到锁时会返回锁冲突错误，发货单会重试它。加锁的 Step 不做任何调用，所以只短暂持有锁。
- **只接受被认领的 run 发来的报告。** 状态仍是 `starting` 的发货单还没有被认领的 run。RPC 在 `pendingShipmentReports` 里按发货单号保存每个 run 的第一份报告。用别的单号发来的报告不会把它挡掉。`ClaimShipment` 合并被认领 run 的报告，再删除这个发货单的整项，所以结果只计一次。拒绝时也会删除这一项。未知或 `rejected` 的单号、来自其他 run 的报告、或者记录里已经有结果时，报告都不会改变什么。其余情况下，RPC 填入结果。
- **先读结果，再确认 run。** `AwaitShipment` 调用 `reconcileShipment`（Python 和 Rust 里是 `reconcile_shipment`）。它的第一次 Describe 只在找不到 Flow，或 run ID 与被认领的不同时，才记录 `unavailable`。读到终止状态后，它读结果 Attribute。Attribute 未设置表示发货单结束时没有结果。Attribute 读取返回 FlowNotFound 时，函数保留这个状态，并跳过第二次 Describe。Attribute 读取看到的是发货单最新的 run。读取成功时，函数再描述一次发货单，检查 run ID。run 已消失或被取代时，函数保留状态，丢弃这次读取的结果。订单已经收到的报告仍保留在记录里。
- **其他读取错误会重试。** 其他错误让 `AwaitShipment` 这个 Step 失败，Dex 会重试它。重试期间不持有锁，所以报告仍能到达。
- **考虑发货单号以后被重新使用。** 找不到发货单，或者同一单号的另一个 run 取代了被认领的 run 时，订单记录 `unavailable`。这是业务策略。订单运行期间，只要被认领的 run 仍是发货单最新的 run，订单就能知道它的终止状态。其他调用方重新使用这个单号，或者这个 run 的数据被删除之后，订单就读不到它了。一个发货单号只属于一个订单。另一个请求已经用过这个单号时，启动会返回带类型的 already-started 错误。示例把这个发货单记录为 `rejected`，并忽略发给它的报告。订单从不等待、计数或停止被拒绝的发货单，因为那个 run 属于另一个请求。每次业务尝试都使用自己的发货单号。
- **拒绝同一订单里的重复单号。** `StartShipments` 在启动任何发货单之前先检查订单：对账间隔为正数，送达延迟不是负数，发货单号都不重复。
- **对启动请求做摘要。** 启动的 request ID 是完整启动请求的摘要。只要原来的 run 仍是发货单最新的 run，重试的 Step 重复的就是同一次启动。如果其他调用方在认领之前重新使用了这个单号，重试会收到 already-started 错误，订单记录 `rejected`。要保护尚未认领的启动，所有启动发货单的入口都必须禁止 ID 复用。

<a id="next"></a>

## 下一步

- [持久化定时器](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer.md)
- [连同子 Flow 一起取消](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/cancel-case.md)
- [等待一半完成](https://docs.superdurable.io/zh-Hans/design-patterns/subflows/wait-for-half.md)
- [有自己身份的子 Flow](https://docs.superdurable.io/zh-Hans/concepts/flow.md#child-flows)
