---
title: "Locked Decision Rounds"
description: "Locked decision rounds rank every event admitted before a decision by business priority. Use them when a higher-priority event must win even if it arrives later, such as a claimant's withdrawal over a reviewer's approval of the same insurance claim."
canonical_url: "https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds/"
source: "docs/content/design-patterns/external-interaction/locked-decision-rounds.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Locked Decision Rounds

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds.go.md) · [Java](https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds.java.md) · [TypeScript](https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds.typescript.md) · [Rust](https://docs.superdurable.io/design-patterns/external-interaction/locked-decision-rounds.rust.md)

Locked decision rounds rank every event admitted before a decision by business priority. Use them when a higher-priority event must win even if it arrives later, such as a claimant's withdrawal over a reviewer's approval of the same insurance claim.

**Flow graph: ClaimDecisionFlow**

**Steps**

1. `StartClaimReview` (start Step): Starts the claim review with its first decision round. Next: `OpenDecisionRound`.
2. `AnswerRoundCandidates`: Sends every candidate's answer without holding a lock, then routes on the round's decision. Next: `PayClaim`, `CloseClaim`, `OpenDecisionRound`, or `EscalateClaim`.
3. `ArbitrateDecisionRound`: Waits for the round's wake-up or deadline, closes the round, and picks the highest-ranked candidate. Next: this branch ends, or `AnswerRoundCandidates`. Writes `roundOutcomes`, `roundWindows`.
4. `CloseClaim`: Completes the Flow with the withdrawn or denied claim. Next: the Flow completes.
5. `EscalateClaim`: Completes the Flow with a claim that no round decided. Next: the Flow completes.
6. `OpenDecisionRound`: Opens the round's window under the round's locks and starts its arbitration wait. Next: `ArbitrateDecisionRound`. Writes `currentRoundId`, `roundWindows`.
7. `PayClaim`: Completes the Flow with the approved claim. Next: the Flow completes.
8. `RecoverDecisionRound`: After arbitration exhausts its retries, closes the round and records the failure for every candidate. Next: this branch ends, or `AnswerRoundCandidates`. Writes `roundOutcomes`, `roundWindows`.

**RPCs**

- `get_current_round_id`: Reads `currentRoundId`.
- `submit_claim_withdrawal`
- `submit_reviewer_decision`

Example: [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)

The graph shows the main path. It omits the failure route from `ArbitrateDecisionRound` to `RecoverDecisionRound`, and the submission RPCs' writes to the candidates map and their wake-up publication.

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

## How it works

Each round has a round ID that is unique within one Flow run. The Python, Java, and TypeScript entries pin the run the start call returned. Go and Rust entries cannot: do not reuse a Flow ID while a late request can arrive, or use a round key unique across runs. Two AttributeMaps are keyed by it: the round's window and its candidates. Every RPC and Step that reads or changes them locks the round's instance of both maps. A Step gets these locks from its movement options. A typed submit entry derives the round ID from its input and passes both locks and both loads. Call the raw RPC only through that entry.

1. `OpenDecisionRound` opens the round's window under the round's locks, then moves to `ArbitrateDecisionRound`.
2. Each submission names its round. It admits the event only while that round's window is open. While the Flow is active, a submission for a closed or unknown round answers "closed" and never enters a newer round.
3. An admitted event becomes a candidate. Its key is the round ID, the event type, and the event ID. It also holds a payload reference, a rank, and its admission order. The RPC answers "received", which confirms admission only. A retried submission finds its key and adds nothing.
4. The first candidate of a round publishes one wake-up in the same commit. Later admissions only append.
5. `ArbitrateDecisionRound` waits for `AnyOf` the 5-day deadline Timer and the round's wake-up. Its `Execute` takes the round's locks and closes the window. It picks the highest-ranked candidate, and the earlier admission breaks a tie. With no candidate, the decision is the deadline branch. It records the decision and an answer for every candidate in one commit.
6. `AnswerRoundCandidates` holds no lock. The example records the answers, then routes: an approval proceeds to the approved branch, and a withdrawal or a denial closes the claim. A deadline opens the next round, up to two rounds, then escalates.

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

## Arbitrate by business priority

Choose which meaning of "at the same time" the design uses:

| Ranking                                                | Use                                                                                                                   |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| The first committed event wins                         | [Response Window](https://docs.superdurable.io/design-patterns/external-interaction/response-window.md)               |
| Channels ready in the same check, by declaration order | [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md) |
| Every event admitted before the decision, by rank      | Locked decision rounds                                                                                                |

Lock order is commit order, not business priority. A locked RPC therefore never decides between ranked events; it only admits them.

The closed window fixes the candidates, and later events change nothing. Do not wait for newer events with a clock or a Timer grace window.

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

## Rules

- The decision comes only from the round's Attribute state, so a retried `Execute` reaches the same decision. `Execute` keeps the locks through its retries and backoff, so no candidate joins meanwhile.
- The cutoff is the committed locked close, not the Timer: a candidate admitted before it is eligible.
- A round already closed or missing ends the branch with `DeadEnd`.
- When the arbitration `Execute` exhausts its retries, neither the close nor the decision commits. Give it a short retry budget and a failure route. The recovery Step takes the same locks and checks the window again, then closes the round in one commit. It arbitrates again from the stored candidates or, as the example does, records the failure, then moves to the unlocked answer Step.
- Send answers after the locks are released, because the submission RPCs wait for them. Key each notification by the business claim, the round, and the candidate key. The receiver deduplicates, because a Step retry can send it again.
- Submit with a stable request ID. A same-ID retry to the same run returns the recorded result while Dex retains that request. Java cannot choose the ID, so each Java call is new. After the Flow closes, a new submission gets an error.
- Keep the arbitration and recovery `Execute` SYNC even when the Flow default is ASYNC. The decision and the answers are then stored before the answer Step runs. See [Durability](https://docs.superdurable.io/reference/go/step-options.md#durability).
- Read the candidates and the outcome from the round's Attributes, never from the wake-up. A Timer win can leave the wake-up pending.
- Start one arbitration wait per round.

The [Developer reference](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#decision-windows-and-rounds) covers lock conflicts, request ID retention, wake-up cleanup, and the Rust failure route.

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

## Test it

The integration tests cover these scenarios:

- An admitted approval decides the round.
- A withdrawal outranks an earlier reviewer decision; the earlier admission breaks a tie.
- A submission for a closed or unknown round answers "closed".
- After the Flow closed, a same-ID retry to the same run returns the recorded result, except in Java; a new submission gets an error.
- A candidate admitted after the Timer fired, but before the locked close, is eligible.
- An arbitration failure leaves none of its staged writes; recovery closes the round and answers every candidate.

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

## Core implementation

`ClaimDecisionFlow` starts with a claim ID. Callers submit through `SubmitClaimWithdrawalWithRoundLocks` and `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),
    )
```

Example: [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>

## Next

- [Idle Timer](https://docs.superdurable.io/design-patterns/external-interaction/idle-timer.md)
- [Response Window](https://docs.superdurable.io/design-patterns/external-interaction/response-window.md)
- [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md)
- [Select map instances at execution time](https://docs.superdurable.io/reference/server/data-primitive-semantics.md#runtime-selected-map-instances)
- [Attribute](https://docs.superdurable.io/concepts/primitives/attribute.md)
