基于 Temporal 的批处理流程示例

基于 Temporal 的批处理流程示例

本文通过 Python 示例,演示如何使用主工作流持续获取任务,将每个 batch 交给一个子工作流处理,并限制同时执行的子工作流数量。设置 batch_size=1 时,每个子工作流只处理一个任务,即不将多个任务合并成批。子工作流结束后,主工作流补充下一批;所有任务处理结束后,返回执行情况,包括成功批次数、失败批次数和运行轮数。执行历史较大时,通过 Continue-as-New 分轮处理。

示例使用 temporalio==1.34.0,连接本地 Temporal Server。任务来源和批次处理逻辑均为模拟实现。


各部分负责什么


主工作流如何调度批次

获取任务并启动子工作流

主工作流通过 running 列表跟踪已启动的子工作流;对于已完成的子工作流,统计其执行结果并移除对应句柄。

  1. 当子工作流的并发名额尚未用满时,通过 Activity 获取一批任务。
  1. 如果获取到的任务非空,以这批任务作为参数启动一个子工作流,并将返回的句柄加入 running。
  1. 按实际获取的任务数推进 offset。
  1. 继续检查是否还有空位。有空位就获取下一批,直到并发名额用满。

这里的两个参数分别控制不同的事情:

任意子工作流结束后补充下一批

并发名额用满后,主工作流调用:

await self._wait_and_summarize(running, state.summary, asyncio.FIRST_COMPLETED)

只要有子工作流结束,等待就可以返回。主工作流统计已经结束的批次,并将对应句柄从 running 中移除,再回到循环中获取下一批。

例如,处理 [0, 1] 的子工作流先结束后,主工作流即可启动处理 [4, 5] 的子工作流,无需等待仍在处理 [2, 3] 的子工作流结束。

running 中可能暂时包含已经结束、但尚未汇总的句柄。因此日志中的“占用并发名额”和“剩余待汇总”描述的是父工作流维护的状态,不是子工作流此刻的精确运行数量。

判断任务是否取完

本例约定:获取到的 batch 长度小于 batch_size,就表示任务已取完。

exhausted = len(batch) < config.batch_size
if not batch:
    break

例如,7 个任务、每批 5 个,会先获取 [0, 1, 2, 3, 4],再获取 [5, 6]。第二批处理完成后即可汇总,不需要再读取一次空列表。

实际数据源也需要遵循这个约定:数量不足的一批代表末尾。

统计成功和失败

每个子工作流对应一个批次。成功完成时,successful_batches 加一;抛出 ChildWorkflowError 时,failed_batches 加一。失败批次不会阻止主工作流继续调度其他批次。

任务全部取完后,主工作流等待剩余子工作流结束,再返回 Summary。


通过 Continue-as-New 控制执行历史

工作流持续启动 Activity 和子工作流,会不断产生历史事件。主工作流检查 is_continue_as_new_suggested(),在 Temporal 建议换轮时停止获取新任务。

换轮过程是:

  1. 停止获取新批次。
  1. 等待本轮所有子工作流结束,并统计结果。
  1. 调用 workflow.continue_as_new(args=[config, state])。
  1. 新一轮从 state.offset 继续获取任务,并保留累计统计。

Continue-as-New 保留相同的 Workflow ID,创建新的 Run ID 和新的执行历史。它不会自动保留局部变量,所以读取位置和累计统计放在 State 中,显式传给下一轮。

State 中只保存:

当前轮的子工作流句柄无需传递,因为换轮前已经全部结束。

为什么保留 exhausted

循环可能因为“任务取完”退出,也可能因为“需要换轮”退出。exhausted 记录前一种情况:

await self._wait_and_summarize(running, state.summary)
if exhausted:
    return state.summary
workflow.continue_as_new(args=[config, state])

exhausted 为 True 时,说明任务已全部取完。等待剩余子工作流结束后直接返回执行结果,不再换轮。

如何快速观察换轮

默认情况下,较少任务不容易触发 Temporal 的换轮建议。参考 Continue-As-New 文档,本例提供两个测试配置:

Config(
    total_tasks=103,
    batch_size=3,
    max_concurrent_children=4,
    test_continue_as_new=True,
    max_history_length=100,
)

开启 test_continue_as_new 后,历史事件数量达到 max_history_length 就会触发换轮流程,无需修改 Server 配置。关闭时,只使用 Temporal 的换轮建议。

max_history_length 是事件历史条数,不是任务数,也不是批次数。触发后还要等待现有子工作流结束,因此当前轮最终的历史条数可能超过该值。


完整代码

将以下文件保存在同一个目录中。代码与当前示例文件一致。

activities.py:获取一个 batch

offset 是读取位置,total_tasks 仅用于限定模拟任务的总数。函数根据参数生成编号列表,不依赖外部数据源。

"""模拟分页获取任务的 Activity。"""

from temporalio import activity


@activity.defn
async def fetch_batch(offset: int, batch_size: int, total_tasks: int) -> list[int]:
    """模拟分页读取任务,返回任务编号列表;相同参数始终返回相同结果。

    例如,共 7 个任务,每批最多取 5 个:
        await fetch_batch(0, 5, 7)  # 返回 [0, 1, 2, 3, 4]。
        await fetch_batch(5, 5, 7)  # 返回 [5, 6],最后一批不足 5 个。
        await fetch_batch(7, 5, 7)  # 返回 [],任务已取完。
    """
    return list(range(offset, min(offset + batch_size, total_tasks)))

workflows.py:批次处理和父工作流调度

BatchWorkflow 用 workflow.sleep() 模拟耗时,用 fail_task_ids 模拟批次失败。其余部分负责批次调度、结果汇总和换轮。

"""拉取任务、并发启动批次子工作流,并在换轮前等待所有子工作流结束。"""

import asyncio
from dataclasses import dataclass, field
from datetime import timedelta

from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError, ChildWorkflowError


@dataclass
class Config:
    total_tasks: int = 23
    # 以下两个参数仅用于模拟子工作流耗时和失败。
    child_delay: float = 0.3
    fail_task_ids: list[int] = field(default_factory=list)

    batch_size: int = 5
    max_concurrent_children: int = 3
    # 仅用于测试:历史达到 max_history_length 条事件时触发换轮。
    test_continue_as_new: bool = False
    max_history_length: int = 100

    # TODO:增加校验


@dataclass
class Summary:
    successful_batches: int = 0
    failed_batches: int = 0
    runs: int = 0


@dataclass
class State:
    offset: int = 0
    summary: Summary = field(default_factory=Summary)


@workflow.defn
class BatchWorkflow:
    @workflow.run
    async def run(self, batch: list[int], config: Config) -> None:
        """接收一个 batch;此处仅模拟处理,后续可替换为实际业务逻辑。"""
        # 按首个任务编号除以 3 的余数,模拟 child_delay 的 1、2 或 3 倍耗时。
        # 例如 child_delay=1 时,首个编号为 0、1、2 的批次分别等待 1、2、3 秒。
        # 便于观察先完成的批次释放并发名额后,主工作流如何补充新批次。
        await workflow.sleep(config.child_delay * (1 + batch[0] % 3))
        if any(task in config.fail_task_ids for task in batch):
            raise ApplicationError("模拟批次处理失败", non_retryable=True)


@workflow.defn
class BatchParentWorkflow:
    @workflow.run
    async def run(self, config: Config, state: State) -> Summary:
        """累计各轮结果;没有任务时,等待剩余子工作流结束并返回汇总。"""
        state.summary.runs += 1
        # 保存子工作流句柄,完成后按批次统计成功或失败。
        running: list[workflow.ChildWorkflowHandle] = []
        # 批次不足 batch_size 时表示任务已取完,用于区分返回汇总和继续换轮。
        exhausted = False
        while not exhausted and not self._should_continue_as_new(config):
            if len(running) < config.max_concurrent_children:
                batch = await workflow.execute_activity(
                    "fetch_batch",
                    args=[state.offset, config.batch_size, config.total_tasks],
                    result_type=list[int],
                    start_to_close_timeout=timedelta(seconds=10),
                )
                exhausted = len(batch) < config.batch_size
                if not batch:
                    break

                child = await workflow.start_child_workflow(
                    BatchWorkflow.run,
                    args=[batch, config],
                    id=f"{workflow.info().workflow_id}/batch-{state.offset}",
                    retry_policy=RetryPolicy(maximum_attempts=1),
                )
                running.append(child)
                workflow.logger.info(
                    "父工作流补充子工作流:%s,占用并发名额 %s/%s",
                    child.id,
                    len(running),
                    config.max_concurrent_children,
                )
                state.offset += len(batch)
                continue

            # 任意子工作流结束就腾出位置,不等待同一轮的其他批次一起结束。
            await self._wait_and_summarize(
                running, state.summary, asyncio.FIRST_COMPLETED
            )

        # 退出循环后,先等待剩余子工作流全部结束。
        await self._wait_and_summarize(running, state.summary)
        if exhausted:
            return state.summary
        workflow.logger.info(
            "准备 Continue-as-New:第 %s 轮结束,下一批 offset=%s,累计成功 %s 批、失败 %s 批",
            state.summary.runs,
            state.offset,
            state.summary.successful_batches,
            state.summary.failed_batches,
        )
        workflow.continue_as_new(args=[config, state])

    def _should_continue_as_new(self, config: Config) -> bool:
        """检查服务端换轮建议;测试模式下同时检查较低的历史事件数阈值。"""
        info = workflow.info()
        return info.is_continue_as_new_suggested() or (
            config.test_continue_as_new
            and info.get_current_history_length() >= config.max_history_length
        )

    async def _wait_and_summarize(
        self,
        running: list[workflow.ChildWorkflowHandle],
        summary: Summary,
        return_when: str = asyncio.ALL_COMPLETED,
    ) -> None:
        """等待子工作流结束,汇总结果并移除已完成的句柄。"""
        if not running:
            return
        done, _ = await workflow.wait(running, return_when=return_when)
        for child in done:
            try:
                await child
            except ChildWorkflowError:
                summary.failed_batches += 1
                workflow.logger.warning("批次失败:%s", child.id)
            else:
                summary.successful_batches += 1
            running.remove(child)
            workflow.logger.info(
                "子工作流已结束:%s,释放一个并发名额,剩余待汇总 %s 个",
                child.id,
                len(running),
            )

test_demo.py:连接本地 Temporal 并启动

这个文件是演示入口。直接修改 Config 即可调整任务总数、批次大小、并发数和换轮测试参数。

client.execute_workflow() 会等待主工作流整条执行链结束,包括中间的 Continue-as-New,然后返回最终汇总。

"""连接本地 Temporal,运行批次子工作流示例。"""

import asyncio
import logging

from activities import fetch_batch
from temporalio.client import Client
from temporalio.worker import Worker
from workflows import BatchParentWorkflow, BatchWorkflow, Config, State


async def main() -> None:
    client = await Client.connect("127.0.0.1:7233")
    config = Config(
        total_tasks=103,
        batch_size=3,
        max_concurrent_children=4,
        test_continue_as_new=True,
        max_history_length=100,
    )
    async with Worker(
        client,
        task_queue="batch-demo",
        workflows=[BatchParentWorkflow, BatchWorkflow],
        activities=[fetch_batch],
    ):
        result = await client.execute_workflow(
            BatchParentWorkflow.run,
            args=[config, State()],
            id="batch-demo-123",
            task_queue="batch-demo",
        )
        print(result)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

requirements.txt

temporalio==1.34.0

运行示例

先确保本地 Temporal Server 已启动。未启动时,在一个终端运行:

temporal server start-dev

服务地址是 127.0.0.1:7233,管理界面为 http://localhost:8233。

在已安装 Python 3.12 的环境中,进入代码所在目录后执行:

python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python test_demo.py

入口使用任务队列 batch-demo,Workflow ID 为 batch-demo-123。可以在管理界面按该 ID 查找主工作流及其执行历史。