---
title: "加锁决定轮次"
description: "加锁决定轮次按业务优先级，给决定之前已接纳的所有事件排序。当优先级更高的事件即使晚到也必须胜出时使用它，例如同一笔保险理赔中，申请人的撤回优先于审核人的批准。"
canonical_url: "https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/locked-decision-rounds/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/design-patterns/external-interaction/locked-decision-rounds.mdx"
locale: "zh-Hans"
language: "python"
---

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

# 加锁决定轮次

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

加锁决定轮次按业务优先级，给决定之前已接纳的所有事件排序。当优先级更高的事件即使晚到也必须胜出时使用它，例如同一笔保险理赔中，申请人的撤回优先于审核人的批准。

**Flow 图：ClaimDecisionFlow**

**Step 列表**

1. `StartClaimReview`（起始 Step）：Starts the claim review with its first decision round. 下一步：`OpenDecisionRound`。
2. `AnswerRoundCandidates`：Sends every candidate's answer without holding a lock, then routes on the round's decision. 下一步：`PayClaim`、`CloseClaim`、`OpenDecisionRound`，或 `EscalateClaim`。
3. `ArbitrateDecisionRound`：Waits for the round's wake-up or deadline, closes the round, and picks the highest-ranked candidate. 下一步：这个分支结束，或 `AnswerRoundCandidates`。 写入 `roundOutcomes`、`roundWindows`。
4. `CloseClaim`：Completes the Flow with the withdrawn or denied claim. 下一步：Flow 完成。
5. `EscalateClaim`：Completes the Flow with a claim that no round decided. 下一步：Flow 完成。
6. `OpenDecisionRound`：Opens the round's window under the round's locks and starts its arbitration wait. 下一步：`ArbitrateDecisionRound`。 写入 `currentRoundId`、`roundWindows`。
7. `PayClaim`：Completes the Flow with the approved claim. 下一步：Flow 完成。
8. `RecoverDecisionRound`：After arbitration exhausts its retries, closes the round and records the failure for every candidate. 下一步：这个分支结束，或 `AnswerRoundCandidates`。 写入 `roundOutcomes`、`roundWindows`。

**RPC 列表**

- `get_current_round_id`：读取 `currentRoundId`。
- `submit_claim_withdrawal`
- `submit_reviewer_decision`

例子: [examples/python/dex_examples/patterns/locked-decision-rounds/claim_decision_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/locked-decision-rounds/claim_decision_flow.py)

图中展示主路径。它省略了从 `ArbitrateDecisionRound` 到 `RecoverDecisionRound` 的失败路由，也省略了提交 RPC 对候选 map 的写入和唤醒消息的发布。

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

## 工作方式

每一轮有一个轮次 ID，它在同一个 Flow run 内唯一。Python、Java 和 TypeScript 的入口固定到启动调用返回的 run。Go 和 Rust 的入口做不到：迟到请求仍可能到达时，不要复用 Flow ID，或者使用跨 run 唯一的轮次键。两个 AttributeMap 以它为键：这一轮的窗口和它的候选。读取或修改它们的每个 RPC 和 Step，都锁住这两个 map 中这一轮的实例。Step 从它的 movement 选项拿到这些锁。类型化的提交入口从输入取出轮次 ID，传入两把锁和两项加载。只通过这个入口调用原始 RPC。

1. `OpenDecisionRound` 在这一轮的锁下打开这一轮的窗口，然后进入 `ArbitrateDecisionRound`。
2. 每个提交指明自己的轮次。只有这一轮的窗口打开时，它才接纳事件。Flow 仍活跃时，针对已关闭或未知轮次的提交得到“closed”，不会进入更新的轮次。
3. 被接纳的事件成为候选。它的键是轮次 ID、事件类型和事件 ID。它还带有 payload 引用、优先级和接纳顺序。RPC 回答“received”，这只确认已接纳。重试的提交发现自己的键已在集合里，就不再追加。
4. 一轮的第一个候选在同一次提交里发布一条唤醒消息。之后的接纳只追加。
5. `ArbitrateDecisionRound` 用 `AnyOf` 等待 5 天的截止 Timer 和这一轮的唤醒消息。它的 `Execute` 拿这一轮的锁并关闭窗口。它选出优先级最高的候选，优先级相同时先接纳的胜出。没有候选时，决定就是截止分支。它在一次提交里记录决定和给每个候选的答复。
6. `AnswerRoundCandidates` 不持有锁。示例记录答复，然后路由：批准进入批准分支，撤回或拒绝就关闭理赔。截止时打开下一轮，最多两轮，之后升级处理。

<a id="arbitrate-by-business-priority"></a>

## 按业务优先级仲裁

选定设计采用哪一种“同时”的含义：

| 排序方式                      | 使用                                                                                                              |
| ------------------------- | --------------------------------------------------------------------------------------------------------------- |
| 最先提交的事件胜出                 | [回应窗口](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.md)            |
| 同一次检查时一起就绪的 Channel，按声明顺序 | [带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md) |
| 决定之前已接纳的所有事件，按优先级         | 加锁决定轮次                                                                                                          |

锁的顺序是提交顺序，不是业务优先级。所以加锁的 RPC 从不在有优先级的事件之间做决定，它只负责接纳。

关闭的窗口确定了候选，之后的事件不再改变任何东西。不要用时钟或 Timer 宽限窗口等待新的事件。

<a id="rules"></a>

## 规则

- 决定只由这一轮的 Attribute 状态得出，所以重试的 `Execute` 会得到同样的决定。`Execute` 在重试和退避期间一直持有锁，所以这期间不会有新的候选加入。
- 截止点是成功提交的加锁关窗，不是 Timer：在它之前接纳的候选都有资格。
- 这一轮已关闭或不存在时，用 `DeadEnd` 结束当前分支。
- 仲裁 `Execute` 用完重试时，关窗和决定都不会提交。给它设一个短的重试预算和一个失败路由。恢复 Step 拿同一组锁，再次核对窗口，然后在一次提交里关闭这一轮。它根据已存的候选重新仲裁，或者像示例那样记录失败，然后进入不持有锁的答复 Step。
- 在释放锁之后发送答复，因为提交 RPC 在等这些锁。每条通知以业务理赔、轮次和候选键为键。接收方负责去重，因为 Step 重试可能再次发送。
- 提交时带一个稳定的 request ID。用同一个 ID 向同一个 run 重试，只要 Dex 还保留这个请求，就得到已记录的结果。Java 不能指定这个 ID，所以每次 Java 调用都是新请求。Flow 关闭之后，新的提交会得到错误。
- 即使 Flow 默认是 ASYNC，仲裁和恢复的 `Execute` 也保持 SYNC。这样决定和答复在答复 Step 运行之前就已持久化。参见 [Durability](https://docs.superdurable.io/zh-Hans/reference/go/step-options.md#durability)（英文）。
- 从这一轮的 Attribute 读取候选和结果，永远不要从唤醒消息读取。Timer 胜出时，可能留下一条等待中的唤醒消息。
- 每一轮只启动一个仲裁等待。

[Developer reference](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#decision-windows-and-rounds)（英文）说明锁冲突、request ID 的保留、唤醒消息的清理和 Rust 的失败路由。

<a id="test"></a>

## 测试

集成测试覆盖这些场景：

- 被接纳的批准决定这一轮。
- 撤回优先于更早的审核决定；优先级相同时，先接纳的胜出。
- 针对已关闭或未知轮次的提交得到“closed”。
- Flow 关闭之后，用同一个 ID 向同一个 run 重试得到已记录的结果（Java 除外）；新的提交得到错误。
- 在 Timer 触发之后、加锁关窗之前接纳的候选有资格。
- 仲裁失败时，它暂存的写入都不保留；恢复关闭这一轮，并答复每个候选。

<a id="example"></a>

## 核心实现

`ClaimDecisionFlow` 以理赔 ID 启动。调用方通过 `SubmitClaimWithdrawalWithRoundLocks` 和 `SubmitReviewerDecisionWithRoundLocks` 提交。

**Python**

```python
def round_invoke_options(round_id: str, request_id: str | None = None) -> RPCInvokeOptions:
    """Returns the options of a submission call: the named round's locks and loads."""
    return RPCInvokeOptions(
        lock_attribute_map_instances=round_locks(round_id),
        load_attribute_map_instances=round_loads(round_id),
        request_id=request_id,
    )


def admit_candidate(context: Context, key: CandidateKey, rank: int) -> RPCResult[str]:
    """Appends one candidate while its round is open, under the round's locks.

    The answer confirms admission only; the arbitration Step decides the outcome.
    """
    if read_round_window(context, key.round_id) != ROUND_WINDOW_OPEN:
        return RPCResult(SUBMISSION_ROUND_CLOSED)
    candidates = read_round_candidates(context, key.round_id)
    if any(candidate.key == key for candidate in candidates):
        # A retried submission adds nothing.
        return RPCResult(SUBMISSION_RECEIVED)
    candidates.append(
        RoundCandidate(
            key=key,
            payload_ref=key.event_id,
            rank=rank,
            admission_order=len(candidates) + 1,
        )
    )
    ROUND_CANDIDATES.set(context, key.round_id, candidates)
    if len(candidates) == 1:
        # The first candidate wakes the arbitration wait; later admissions only append.
        ROUND_WAKEUPS.publish(context, key.round_id, None)
    return RPCResult(SUBMISSION_RECEIVED)


def round_step_options(round_id: str) -> StepOptions:
    """Locks and loads the round for execute, and stores its writes before the next Step runs."""
    return StepOptions(
        execute_lock_attributes=round_locks(round_id),
        execute_load_attribute_map_instances=round_loads(round_id),
        execute_durability=StepDurability.SYNC,
    )


def arbitration_step_options(round_id: str) -> StepOptions:
    """Adds a short retry budget and the failure route to the round's options."""
    return StepOptions(
        execute_lock_attributes=round_locks(round_id),
        execute_load_attribute_map_instances=round_loads(round_id),
        execute_durability=StepDurability.SYNC,
        execute_retry=ARBITRATION_RETRY,
        execute_method_timeout=ARBITRATION_ATTEMPT_TIMEOUT,
    ).on_execute_failure_proceed_to(RecoverDecisionRound, round_step_options(round_id))


class OpenDecisionRound(Step[DecisionRound]):
    def execute(self, context: Context, decision_round: DecisionRound) -> StepDecision:
        ROUND_WINDOWS.set(context, decision_round.round_id, ROUND_WINDOW_OPEN)
        CURRENT_ROUND_ID.set(context, decision_round.round_id)
        return go_to_many(
            StepMovement.of(
                ArbitrateDecisionRound,
                decision_round,
                options=arbitration_step_options(decision_round.round_id),
            )
        )


class ArbitrateDecisionRound(Step[DecisionRound]):
    def wait_for(self, context: Context, decision_round: DecisionRound) -> Wait:
        return Wait.any_of(
            Timer.by_duration(REVIEW_ROUND_DEADLINE),
            ROUND_WAKEUPS.for_one(decision_round.round_id),
        )

    def execute(self, context: Context, decision_round: DecisionRound) -> StepDecision:
        if read_round_window(context, decision_round.round_id) != ROUND_WINDOW_OPEN:
            return dead_end()
        # While the Flow is active, a later submission for this round gets SUBMISSION_ROUND_CLOSED.
        ROUND_WINDOWS.set(context, decision_round.round_id, ROUND_WINDOW_CLOSED)
        outcome = decide_round(
            decision_round, read_round_candidates(context, decision_round.round_id)
        )
        ROUND_OUTCOMES.set(context, decision_round.round_id, outcome)
        # Failing after the staged writes shows that a failed attempt commits none of them.
        if decision_round.fail_arbitration:
            raise ArbitrationError("arbitration failed")
        return go_to(AnswerRoundCandidates, outcome)


class ClaimDecisionFlow(Flow[ClaimReview]):
    @rpc
    def submit_claim_withdrawal(
        self, context: Context, withdrawal: ClaimWithdrawal
    ) -> RPCResult[str]:
        """Admits the claimant's withdrawal into the named round.

        Returns SUBMISSION_ROUND_CLOSED when that round is closed or unknown.
        Call it only through submit_claim_withdrawal_with_round_locks, which takes the round's locks.
        """
        key = CandidateKey(
            round_id=withdrawal.round_id, event_type=EVENT_WITHDRAWAL, event_id=withdrawal.event_id
        )
        return admit_candidate(context, key, WITHDRAWAL_RANK)


async def submit_claim_withdrawal_with_round_locks(
    client: AsyncClient,
    flow: ClaimDecisionFlow,
    flow_id: str,
    run_id: str,
    request_id: str,
    withdrawal: ClaimWithdrawal,
) -> str:
    """Submits a withdrawal to one run under the locks and loads of the round it names.

    Pass the run ID that start_flow returned, so a late call never reaches a newer run.
    Returns SUBMISSION_RECEIVED, or SUBMISSION_ROUND_CLOSED for a closed or unknown round of an
    active Flow. A retry with the same request ID returns the recorded result while Dex retains
    that request. A new request to a closed Flow, and an exhausted lock wait, raise the client
    error.
    """
    return await client.invoke_rpc(
        flow.submit_claim_withdrawal,
        flow_id,
        withdrawal,
        run_id=run_id,
        options=round_invoke_options(withdrawal.round_id, request_id),
    )
```

例子: [examples/python/dex_examples/patterns/locked-decision-rounds/claim_decision_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/locked-decision-rounds/claim_decision_flow.py)

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

## 下一步

- [空闲定时器](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/idle-timer.md)
- [回应窗口](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.md)
- [带截止时间的决定](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/decision-with-deadline.md)
- [执行时选择映射实例](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#runtime-selected-map-instances)（英文）
- [Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md)
