---
title: "Data primitive semantics"
description: "Detailed rules for Attributes, RPCs, Channels, Streams, Timers, and SubFlows: parameters, defaults, limits, errors, and edge cases. The concept pages explain what each primitive is and when to use it: Attribute, RPC, Channel, Stream, Timer, and SubFlow."
canonical_url: "https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics/"
source: "docs/reference/server/runtime-data.mdx"
locale: "en"
site_locale: "zh-Hans"
language: "python"
---

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

> 本页内容是英文原文，中文译文还在准备中。

# Data primitive semantics

本页代码为 Python。其他语言：[Go](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.go.md) · [Java](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.java.md) · [TypeScript](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.typescript.md) · [Rust](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.rust.md)

Detailed rules for Attributes, RPCs, Channels, Streams, Timers, and SubFlows:
parameters, defaults, limits, errors, and edge cases. The concept pages explain
what each primitive is and when to use it:
[Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md), [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md),
[Channel](https://docs.superdurable.io/zh-Hans/concepts/primitives/channel.md), [Stream](https://docs.superdurable.io/zh-Hans/concepts/primitives/stream.md),
[Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md), and [SubFlow](https://docs.superdurable.io/zh-Hans/concepts/primitives/subflow.md).
The SDK doc comments describe each API in its own language.

<a id="flow-runs"></a>

## Flow runs

<a id="flow-close-by-new-start"></a>

### Flow close by a new start

A new start with the same Flow ID terminates the running Flow only when the new
start uses an ID reuse policy that terminates the running Flow
(**IDReuseTerminateIfRunning**). A SubFlow restart can terminate an earlier
child too; see [SubFlowReusePolicy](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#subflow-reuse-policy).
[StartFlowOptions](https://docs.superdurable.io/zh-Hans/reference/python/start-flow-options.md#flow-id-request-id-and-already-started)
lists every ID reuse policy.

<a id="attributes"></a>

## Attributes

<a id="initial-attribute-values"></a>

### Initial values and later writes

**StartFlowOptions** can set initial Attributes when the Flow is created.
Initial values and Flow creation are one operation, so the first Step sees them
immediately. See [Attributes](https://docs.superdurable.io/zh-Hans/reference/python/start-flow-options.md#attributes) in
StartFlowOptions.

Setting an Attribute to null deletes it.

After a Flow starts, applications write Attributes through Flow RPCs. A Client
can also use **WaitForAttributeMatch** to wait until a singleton Attribute or
one AttributeMap instance satisfies a scalar comparison. The call returns the
matched current value. See
[Wait for an Attribute match](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#wait-for-an-attribute-match).

<a id="read-attributes-from-outside-a-flow"></a>

### Read Attributes from outside a Flow

Application code outside the Flow reads Attribute values with the Client's
**GetAttributes** call. One call reads any mix of singleton Attributes and
AttributeMap instances.

The read has these semantics:

- **One commit.** The Client sends every read in one server request. All values
  come from the same committed state.
- **Current or latest Flow run.** The call reads the current Flow run, or the
  latest one when no Flow run is open. A closed Flow run stays readable until
  Dex purges it.
- **No Worker.** The server answers the read itself. It dispatches nothing to a
  Worker, uses no Worker capacity, and works while no Worker is running.
- **Committed state only.** The call does not see writes that a running Step or
  RPC has made but not yet committed. An RPC handler, by contrast, also sees
  the writes it made earlier in the same invocation.
- **No locks.** **GetAttributes** takes no Attribute locks. Use an RPC for a
  read-modify-write.
- **Large and hard-delete values.** The server resolves
  [hard-delete](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#hard-delete-attributes) values before it
  responds, and a deleted value reads as unset. The Client loads other large
  values from blob storage, then decodes every value with its definition. The
  call returns values only after all of them decode.

An RPC remains the right choice when the read needs Flow-side validation,
authorization, a derived view, or Attribute locks. See
[Client APIs: Read Attributes](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#read-attributes)
for the example, the unset value in each SDK, and the errors.

<a id="attribute-indexes"></a>

### Indexes

An indexed Attribute can be used in **SearchFlows** queries to find the Flow
runs that match the query.

| Index type                    | Value                           |
| ----------------------------- | ------------------------------- |
| **KEYWORD**                   | One exact string.               |
| **FULL_TEXT**                 | Text for tokenized search.      |
| **KEYWORD_ARRAY**             | A list of exact strings.        |
| **INT**, **DOUBLE**, **BOOL** | The corresponding scalar value. |
| **DATETIME**                  | A date and time value.          |

An **index key** is the key in the search schema, and the key you use in a
query. Index keys come from a limited pool for each namespace, shared by all
Flow types.

The SDK defaults a regular Attribute's index key to its Attribute name. For
application indexes, always override that default with an explicit, generic,
numbered key. Keep business names on Attributes, and share one pool of typed
slots across every Flow type in the namespace. Two indexed fields in the same
Flow need different slots. Reuse a slot across Flow types only with the same
index type; its business meaning can differ. Dex system indexes keep their
reserved names. Slots are limited and cannot be freed, so keep a list of
which slot each Flow type uses; see
[PostgreSQL search](https://docs.superdurable.io/zh-Hans/reference/server/search.md#postgresql-search) for the limits.

| Index type        | Application index keys                |
| ----------------- | ------------------------------------- |
| **KEYWORD**       | **keyword1**, **keyword2**, …         |
| **KEYWORD_ARRAY** | **keywordList1**, **keywordList2**, … |
| **FULL_TEXT**     | **text1**, **text2**, …               |
| **INT**           | **int1**, **int2**, …                 |
| **BOOL**          | **bool1**, **bool2**, …               |
| **DOUBLE**        | **double1**, **double2**, …           |
| **DATETIME**      | **datetime1**, **datetime2**, …       |

Renaming an index does not backfill existing Flow runs. Test changed schemas in
a fresh local **dexcli dev** instance, and plan the migration of an existing
deployment separately.

A generic key can have a different business meaning in each Flow type, so
application queries must filter on **FlowType**. Dex Web already limits
searches to the selected Flow type. Put a caller's filter in parentheses before
you combine it with the **FlowType** filter, so an OR cannot bypass it. Keep the
query unchanged across pages. Do not index sensitive data or PII. The customer-email
value in the Customer Refund example is synthetic data only.

**Python**

```python
status = Attribute(
    "primitive-attribute-status",
    str,
    index=AttributeIndex(IndexType.KEYWORD, "keyword1"),
)
```

例子: [examples/python/dex_examples/primitives/attribute/attribute_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/attribute/attribute_flow.py)

For example, the status Attribute above uses **keyword1** as its index key. To
find completed **AttributeFlow** runs, use this query:

```text
FlowType = 'AttributeFlow' AND keyword1 = 'completed'
```

Pass the query to **SearchFlows**:

**Python**

```python
page = await app_state.client.search_flows(
    "FlowType = 'AttributeFlow' AND keyword1 = 'completed'",
    20,
    "",
)
```

例子: [examples/python/dex_examples/primitives/client-apis/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/client-apis/controller.py)

<a id="indexed-attributemap"></a>

#### Indexed AttributeMap

An indexed **AttributeMap** must use an explicit index key. The index does not
cover all Map instances: each instance write updates the same search field, so
one instance can replace the value that another instance wrote. The Map
instance key is not searchable.

The index does not turn the Map into a **KEYWORD_ARRAY** either.
**KEYWORD_ARRAY** indexes the string array from one write; Dex does not combine
the values from all Map instances. After the example below writes the payment instance with value
authorized, you can query the current search value with:

```text
FlowType = 'AttributeFlow' AND keyword2 = 'authorized'
```

If another Map instance later writes a different value, that value replaces the
search value for **keyword2**. Use a regular Attribute with **KEYWORD_ARRAY**
when you need to search a collection of values. Do not use an AttributeMap index
to find every instance with a value.

**Python**

```python
progress = AttributeMap(
    "primitive-attribute-progress",
    str,
    index=AttributeIndex(IndexType.KEYWORD, "keyword2"),
)
```

例子: [examples/python/dex_examples/primitives/attribute/attribute_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/attribute/attribute_flow.py)

<a id="hard-delete-attributes"></a>

### Hard-delete Attributes

Dex stores every value of a hard-delete Attribute only in object storage,
whatever the value size. Flow history keeps only a reference. Deleting the
Attribute, or setting it to null, permanently deletes the stored value. After
that, neither Dex APIs nor Flow history can recover it.

Step and RPC handlers receive the value directly. The SDKs never write it to
their local blob cache, and Dex Server never writes it to its blob cache.

Enable it on the definition with **HardDeleteOnNull** in Go,
**hardDeleteOnNull** in Java and TypeScript, and **hard_delete_on_null** in
Python and Rust. The option works for both Attributes and AttributeMaps.

**Python**

```python
class AttributeFlow(Flow[str]):
    model_api_key = Attribute(
        "primitive-attribute-model-api-key",
        str,
        hard_delete_on_null=True,
    )


class AttributeStep(Step[str]):
    def execute(self, context: Context, input: str) -> StepDecision:
        self.flow.status.set(context, "completed")
        # The Flow no longer needs the short-lived key, so delete it permanently.
        self.flow.model_api_key.delete(context)
        return graceful_complete(input)
```

例子: [examples/python/dex_examples/primitives/attribute/attribute_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/attribute/attribute_flow.py)

A hard-delete Attribute has these requirements:

- Only string and object values are supported, including bytes. Numeric and
  Boolean value types are rejected.
- It cannot be indexed or synced to an Attribute Store.
  **WaitForAttributeMatch** and Action conditions reject it.
- It needs a server that supports hard-delete Attributes, such as server-zd.
  The SDKs refuse to write the Attribute to an older server.

Each Flow run keeps one current value per Attribute key. A new run with the
same Flow ID has its own values.

- A Step or RPC writes or deletes the value when Dex saves the handler's
  result. An attempt that fails before its result is saved leaves the previous
  value unchanged. When concurrent handlers write the same key, the last
  committed write determines its value.
- A rejected start leaves the running Flow's values unchanged.
- A deleted value reads as absent. Time travel keeps the current value,
  including its absence after deletion. A SubFlow whose start wrote hard-delete
  Attributes cannot be restarted by time travel.
- Removing the option from a definition leaves the stored value in place until
  Dex removes the Flow. Delete the value with the hard-delete definition first.

A value remains stored until it is deleted, or until Dex removes the Flow after
its retention period. Object storage backups and bucket versioning outside Dex
can keep copies. See [Object storage](https://docs.superdurable.io/zh-Hans/reference/server/object-storage.md).

<a id="hard-delete-after-close"></a>

#### Erase after the Flow run closes

Since server-zd 0.1.5, a direct call to the FlowService **SetAttributes** API
can erase a hard-delete Attribute after its Flow run closes and before the Flow
run is purged. The SDK Clients do not expose this API, so send it with
**dexcli api call SetAttributes** or another FlowService client. Set every
Attribute in the request to null. Each Attribute must still have a stored
hard-delete value. The erase leaves the Flow run closed and permanently deletes
its stored objects. Other writes to a closed Flow run return NOT_FOUND.

<a id="attributemap-partitioning-examples"></a>

### AttributeMap partitioning examples

The [AttributeMap patterns](https://docs.superdurable.io/zh-Hans/design-patterns.md#data-storage)
examples fix these layout rules in every SDK. They are part of the stored
layout, so changing them requires a migration.

<a id="hash-partition-algorithm"></a>

#### Hash partition algorithm

The [Hash-Partitioned AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/hash-partitioned-attribute-map.md)
example selects a partition in the same way in every SDK:

1. Require a non-empty ASCII email address.
2. Remove leading and trailing ASCII whitespace.
3. Lowercase ASCII letters from A through Z.
4. Calculate 32-bit FNV-1a over the canonical email bytes with wrapping overflow.
5. Select **hash modulo 1000** and format the instance from **partition-000**
   through **partition-999**.

<a id="chunk-page-tokens"></a>

#### Chunk page tokens

In the [Sequentially Chunked AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/sequentially-chunked-attribute-map.md)
example, the **current** token is always valid after the Flow starts. An empty
**current** returns an empty page. Archive tokens must contain exactly 20
decimal digits and identify a chunk boundary. A malformed token or a
valid-looking token without a stored chunk returns an explicit error.

<a id="attribute-locks"></a>

### Locks

Dex Server lets only one Step execution or RPC invocation hold an Attribute lock
at a time. A Step declares locks separately for **WaitFor** and **Execute** in
its Step options. An RPC declares its locks when it is registered. The
[Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md#locking) page shows an **Execute** lock.
To test a lock, run both writers concurrently and check the final value.

A Step attempt takes its locks when Dex hands it to a Worker. A first attempt
that no Worker has taken yet holds no locks, but later Steps that need the same
lock wait behind it. A returned attempt, for example after a Worker declined its
Step type, and a retry attempt keep their locks while they wait in the queue.
When no Worker can run them, they hold the locks until the Flow times out or
stops. A locked RPC waiting on one of those keys can reach its lock wait limit.

Lock **WaitFor**:

**Python**

```python
def get_step_options(self) -> StepOptions:
    return StepOptions(
        wait_for_lock_attributes=(
            self.flow.status.lock(),
            self.flow.progress.lock("payment"),
        ),
    )
```

例子: [examples/python/dex_examples/primitives/attribute/attribute_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/attribute/attribute_flow.py)

Lock an RPC:

**Python**

```python
@rpc(lock_attributes=(status.lock(), progress.lock("payment")))
def update_status(self, context: Context, input: str) -> RPCResult[str]:
    self.status.set(context, input)
    self.progress.set(context, "payment", input)
    return RPCResult(input)
```

例子: [examples/python/dex_examples/primitives/attribute/attribute_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/attribute/attribute_flow.py)

<a id="whole-map-coordination"></a>

#### Coordinate writes across the whole AttributeMap

An AttributeMap lock protects one exact instance. When an invariant spans
several instances or the whole collection, register a separate singleton bool
Attribute as its coordination key. For example, register **currentMessages** as
an AttributeMap and **currentMessagesLock** as a non-map, non-indexed bool
Attribute in the same **PersistenceSchema**.

Every Step, timeout handler, and RPC that writes, deletes, archives, or
otherwise changes the protected map must request the same singleton Attribute
lock in its lock options for that method. RPCs declare this fixed lock when
they are registered. A writer that requests only a map-instance lock does not
conflict with the singleton lock. Dex then runs all these writers one at a time
within that Flow run; other Flow runs have their own locks.

The bool value is not the lock state. Do not take or release the lock by
reading or toggling the value. Dex takes the lock before the method runs and
releases it after; the coordination Attribute does not need a stored value.
Locking also does not load map entries. Declare exact instance loads, or a
whole-map load when the operation must list the instances. An RPC that needs a busy key follows the [RPC lock wait rules](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#rpc-lock-conflicts).

Keep per-instance locks for updates that touch only one instance. Use the
shared singleton lock when all affected writers must preserve an invariant over
the whole collection.

To make a writer that omits the coordination lock fail, declare the lock on
the map. See [Declared lock requirements](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#declared-lock-requirements).

<a id="lock-holding"></a>

#### Lock holding

A method that declares several locks takes them all at once. It starts only
when every lock is free and it is first in line for each one. It never holds
one lock while it waits for another, so two locked methods cannot block each
other in a cycle.

A Step holds its lock for the whole method, including the external calls it
makes. A retry keeps the lock while it waits in the queue, and an attempt that
no Worker can run holds it until the Flow times out or stops. To release such a
lock, start a Worker that has that Step type, or stop the Flow. Dex has no
command that releases a single lock. The method timeout and the retry policy
bound how long a running Step holds a lock.

This adds up when a locked Step keeps failing. Its retries keep the lock, and
the default retry policy keeps retrying for up to 4 hours. For that whole time,
every other Step and RPC that declares the same lock waits or fails. Set a
short total duration, such as a few minutes, in the locked method's
**StepOptions** retry policy, or keep external calls out of it. The
[StepOptions defaults](https://docs.superdurable.io/zh-Hans/reference/python/step-options.md#defaults) list the retry
window.

When a Step declares a lock that an RPC also takes, an external call made under
the lock can outlast the RPC's lock wait. The same holds for a **WaitFor** or a
Flow timeout handler that declares such a lock. Starting or calling another
Flow is an external call too. A short external call under the lock can fit when
RPCs can wait through its full hold time. A longer hold can fit when no RPC
needs the lock then, or callers can accept a busy answer. The hold time
includes time a retry spends waiting for a Worker.

A lock that only Steps share may cover an external call. Those Steps wait for
the lock and run one at a time.

<a id="rpc-lock-conflicts"></a>

#### RPC lock conflicts

**Changed in server-zd 0.1.38.** A locked RPC waits up to half its handler
timeout for all its keys. With the default 60-second RPC timeout, the lock
wait is 30 seconds. Set the lock wait on the RPC definition to override it.
Zero returns a lock conflict immediately on contention. The lock wait bounds
only the wait for locks. A free lock is taken at once, whatever the caller's
deadline. A locked call that starts executing with a lock wait longer than its
handler timeout fails with `INVALID_ARGUMENT`. A retry that replays or joins an
earlier call is not checked. The caller's deadline includes the wait. The
Worker receives its full handler timeout after the wait.

When a locked RPC has waited for a held key, Dex sends it to its Worker only
while a caller still waits, and no later than shortly before the caller's
deadline. Otherwise the call returns the lock conflict error, and no Worker
has run the RPC. This covers the wait for locks and the waits after the locks
are taken, such as for earlier writes to commit. When calls share a request
ID, the deadline of the first caller sets this bound, and a joiner never
resets it. A queued call that every caller has abandoned leaves the queue. A
locked RPC whose keys were free runs as it would without this bound. After
the Worker receives the RPC, the call runs under its handler timeout.

Each run can queue 64 RPCs per key and 256 RPCs in total. A call that needs
several keys occupies one slot on each key and one slot in the run. It holds
all its keys together once eligible. Repeating an in-flight request ID joins
the existing call. A run entering close rejects its waiting RPCs. After a
coordinator failover, retry an interrupted call with the same request ID.

A waiting RPC joins the back of the queue of every key it requests, including
keys that are free, and holds a queue place on each. Once it reaches the head
of a key's queue, it blocks later requests for that key until it gets all its
keys or leaves. A later RPC waits behind it only up to that later RPC's own
lock wait. For example, an RPC that waits for `balance` and `status` while a
Step holds `balance` also blocks a later RPC that needs only `status`.

A full queue or an expired lock wait returns `ABORTED` with the RPC lock
conflict error. The error message says when the queue is full. The SDK exposes it as
**RPCLockConflictError** in Go, **RpcLockConflictError** in Python and
TypeScript, **RpcLockConflictException** in Java, and
**SdkError::RpcLockConflict** in Rust.

Retry after that error, with a backoff that suits the application. Make the RPC
idempotent so that a retry is safe. Successful calls run one at a time under the
same locks, so concurrent requests do not lose or duplicate updates.

<a id="lock-order"></a>

#### Lock order

RPCs and Steps have separate queues on each key. Within each queue, requests
take the lock in arrival order. When a key becomes free, waiting RPCs have
priority over waiting Steps. A continuous queue of RPCs can therefore delay
a Step indefinitely. A Step retry that already holds the lock can finish
and release it. Keep locked RPCs short.

<a id="decision-windows-and-rounds"></a>

#### Decision windows and rounds

These details apply to the
[Response Window](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/response-window.md) and
[Locked Decision Rounds](https://docs.superdurable.io/zh-Hans/design-patterns/external-interaction/locked-decision-rounds.md)
patterns.

- A response RPC can wait while the deciding **Execute** holds the window
  lock. The Response Window example's HTTP route retries a lock conflict a few
  times with a short backoff. If the retry observes a closed window or a
  retained closed Flow, the route returns `409`. If the retries all conflict,
  it returns the last error.
- For a hard cutoff, a trusted application entry records the receive time
  and reuses it on retries. Under the window lock, the response RPC rejects
  a receive time at or past the stored deadline. A response that passes the
  time check must still find the window open.
- The wait for a lock before the first attempt does not count against the
  retry budget of the locked **Execute**. The total retry duration starts
  with the first dispatched attempt. Dex checks that duration and the maximum
  attempt count when an attempt fails. The method timeout limits each
  attempt.
- A round's locks are chosen per call: the RPC invocation options and the
  options of the Step movement. **WritesRequireLock** cannot enforce these
  dynamically selected locks, so the
  [declared lock requirement](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#declared-lock-requirements) check ignores them.
  A fixed coordination key is the alternative; see
  [Coordinate writes across the whole AttributeMap](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#whole-map-coordination).
- A submission answers "closed" only while the Flow is active, for a closed
  or unknown round. After the Flow closes, a new submission fails before the
  handler runs. A retry with the same caller-chosen request ID returns the
  recorded result when it reaches the same run and Dex still retains that
  request. See [RPC request IDs](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#rpc-request-ids). The Java example cannot
  supply a caller-chosen request ID. Its SDK sends a fresh request ID on each
  call.
- The Python, Java, and TypeScript examples pass the run ID that the start
  call returned, so a late submission never reaches a newer run with the same
  Flow ID. The Go and Rust SDK releases the examples use cannot pin a run.
  With them, do not reuse a Flow ID while a late request can still arrive, or
  use a round key that is unique across runs.
- Without an arbitration failure route, the Flow fails, and senders learn
  the result from its final state.
- A Timer win can leave a round's wake-up pending. A long-running Flow that
  reclaims state deletes it with the round's other state.
- The arbitration failure route needs the round's locks. Go, Python, Java,
  and TypeScript pass Step options with the failure route. In Rust,
  **on_execute_failure_proceed_to** takes no options, so the recovery Step
  would run with its registered options. The Rust example routes the failure
  to an unlocked `HandOffFailedRound` Step. That Step moves to
  `RecoverDecisionRound` with the round's locks.

<a id="stop-a-decided-action"></a>

#### Stop a decided action

The [Attribute](https://docs.superdurable.io/zh-Hans/concepts/primitives/attribute.md#locking) page lists the two
designs for an RPC that stops an action a Step decides. These rules apply to
the design without a lock:

- The deciding **Execute** checks the stop, also in the branch where a Timer
  was selected first.
- A stop that arrives while the decided action runs may not stop it.
- Every later interruptible wait still includes the stop Condition.
- One message reaches one consumer, so parallel consumers each get their own
  stop message, such as one per branch on each branch's Channel. That message
  wakes a waiting branch.
- A durable stop Attribute can record the stop as a fact. It wakes no waiting
  branch, because **WaitFor** has no Attribute Condition. A branch may read
  that Attribute when another event resumes it, when the business accepts that
  its wait is not interrupted at once. The grace then applies per decided
  action or branch.
- When the business allows only one such action overall, decide the actions
  one at a time.

<a id="declared-lock-requirements"></a>

#### Declared lock requirements

A definition can declare the lock that every write or publish requires. The
Worker then fails each handler that writes or publishes without registering
that lock. Dex does not infer a missing lock from what a handler reads and
writes; the declaration states the rule.

| Declared on               | Requirement                                                        | Go (since 1.45.17)                                                                                     | Python (since 1.45.18)                  | Java (since 1.45.3)               | Rust (since 1.45.9)                  | TypeScript (since 1.45.17)        |
| ------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | --------------------------------------- | --------------------------------- | ------------------------------------ | --------------------------------- |
| Attribute                 | Every write holds the Attribute's own lock                         | **WritesRequireLock**                                                                                  | **writes_require_lock=True**            | **writesRequireLock**             | **writes_require_lock**              | **writesRequireLock**             |
| AttributeMap              | A write of an instance holds that instance's lock                  | **WritesRequireLock**                                                                                  | **writes_require_lock=True**            | **writesRequireLock**             | **writes_require_lock**              | **writesRequireLock**             |
| Attribute or AttributeMap | Every write holds the lock of one singleton coordination Attribute | **WritesRequireAttributeLock**                                                                         | **writes_require_lock=**\<Attribute>    | **writesRequireAttributeLock**    | **writes_require_attribute_lock**    | **writesRequireAttributeLock**    |
| Channel or ChannelMap     | Every publish holds the lock of one singleton Attribute            | **PublishesRequireAttributeLock** with **DefineChannelWithOptions** or **DefineChannelMapWithOptions** | **publishes_require_lock=**\<Attribute> | **publishesRequireAttributeLock** | **publishes_require_attribute_lock** | **publishesRequireAttributeLock** |

Only the Go, Python, Java, Rust, and TypeScript SDKs support the declaration so
far. Each TypeScript method returns a new definition; register that definition.

The Worker checks each **WaitFor**, **Execute**, and RPC invocation after the
handler returns successfully:

- **Set** and **Delete** of a declared Attribute or AttributeMap instance count
  as writes. **Publish** to a declared Channel or ChannelMap instance counts as
  a publish. Reads, waits on a Channel, and deletes of pending messages are not
  checked.
- Only the locks that the handler registers count: the **WaitFor** or
  **Execute** lock fields of the Step's own options, and the lock attributes of
  the RPC's registered options.
- The check ignores locks chosen for one call. These are the AttributeMap
  instance locks of one RPC invocation and the options of one Step movement.
  Register the lock instead.
- The check skips Flow timeout handlers, because their locks come from the
  Flow start options.

When a required lock is missing, the invocation fails with
**MissingAttributeLockError** in Go, Python, Rust, and TypeScript, or
**MissingAttributeLockException** in Java. The error names the handler and each write or
publish with the lock it requires. Dex discards the Attribute writes, Channel
publications, and other changes buffered for the invocation's result. Stream
writes that the Step already sent and external side effects stay. Dex retries a
failed Step method under its retry policy. A retry registers the same locks, so
it fails again unless the handler takes another path. An RPC caller receives the
failure as a Worker invocation error whose Worker error type is
`*dex.MissingAttributeLockError` in Go,
`dex.runtime_errors.MissingAttributeLockError` in Python,
`io.superdurable.dex.exceptions.MissingAttributeLockException` in Java,
`dex_sdk::MissingAttributeLockError` in Rust, and
`MissingAttributeLockError` in TypeScript.

An AttributeMap that requires each instance's own lock accepts only writes of
instances whose locks the handler registers. Registered locks are fixed, so this
suits a map with a known set of instances. For instances chosen at run time,
declare a coordination Attribute with **WritesRequireAttributeLock** in Go,
**writes_require_lock** in Python, **writesRequireAttributeLock** in Java,
**writes_require_attribute_lock** in Rust, or **writesRequireAttributeLock** in
TypeScript, and register that lock in every writer. All writers of
the map then run one at a time within the Flow run, as in
[Coordinate writes across the whole AttributeMap](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#whole-map-coordination).

The lock Attribute of a requirement must be a singleton Attribute in the same
Flow's **PersistenceSchema**. Registry construction fails otherwise: Go
**NewRegistry** returns an error, Python **Registry** raises
**FlowDefinitionError**, the Java **Registry** constructor throws
**FlowDefinitionException**, Rust **Registry::register** returns
**SdkError::FlowDefinition**, and the TypeScript **Registry** constructor throws
**FlowDefinitionError**. Go, Rust, and TypeScript also reject a lock Attribute
with an empty name. In Python and TypeScript, the lock Attribute must be the
same object that the schema registers. TypeScript also throws a `TypeError`
when the declaring method receives anything other than an **Attribute**.

The Worker enforces the requirement; the server does not. The Worker compares
writes with the registered locks, while Dex acquires the locks that each call
sends. For a Flow that declares a lock requirement, a Flow start, Step
movement, failure route, or SubFlow start without a Step options override sends
the target Step's registered locks, captured when the sender builds its
Registry. The check cannot see these cases:

- In Go, **StepOptions** passed with **WithStepOptions** replace a registered
  lock field only when that field is non-nil. A nil field keeps the registered
  locks; an empty slice runs the Step without them.
- In Python and TypeScript, the **StepOptions** of a **StepMovement** replace
  the Step's whole options, including its lock fields. Options that leave out
  the lock run the Step without it. Rust **StepMovement::to_with_options** works
  the same way.
- Failure routes follow the same rules. In Go, options passed to
  **ProceedToOnExecuteFailure** or **ProceedToOnFlowTimeoutHandlerFailure**
  replace a lock field of the target Step only when that field is non-nil. In
  Python, options passed to **on_execute_failure_proceed_to** or
  **on_failure_proceed_to** replace the target Step's whole options. Keep the
  required lock in such options.
- In Java, the **StepOptions** passed to **StepMovement.of**,
  **StepOptions.Builder.onExecuteFailureProceedTo**, or
  **FlowTimeoutHandlerOptions.Builder.onFailureProceedTo** replace the target
  Step's whole options, as in Python. Options that leave out the lock run the
  Step without it. The Worker checks against the locks that its own
  **Registry** captured. A Client and a Worker with separate Registries must
  capture the same locks, so **getStepOptions** must return the same locks
  every time.
- In TypeScript, the **StepOptions** of an **ExecuteFailure** or of the
  **failure** of **FlowTimeoutHandlerOptions** also replace the target Step's
  whole options. In a Flow that declares a requirement, each **Registry** also
  copies each RPC's **lockAttributes**. As in Java, the sender's and the
  Worker's Registries must capture the same locks.
- Dex takes an RPC's locks from the Client's definition. A Client built
  without the lock runs the RPC without it.
- A Worker built without the declaration does not check it.
- Writes that run no handler skip the Worker. These include Attribute values
  set when a Flow starts and Attribute edits from Dex Web.

Build every Worker and Client from the same definitions, and keep required
locks in movement options.

The API names are in the [Go Attribute](https://docs.superdurable.io/zh-Hans/reference/go/attribute.md#api-names),
[Go Channel](https://docs.superdurable.io/zh-Hans/reference/go/channel.md#api-names),
[Python Attribute](https://docs.superdurable.io/zh-Hans/reference/python/attribute.md#api-names),
[Python Channel](https://docs.superdurable.io/zh-Hans/reference/python/channel.md#api-names),
[Java Attribute](https://docs.superdurable.io/zh-Hans/reference/java/attribute.md#api-names),
[Java Channel](https://docs.superdurable.io/zh-Hans/reference/java/channel.md#api-names),
[Rust Attribute](https://docs.superdurable.io/zh-Hans/reference/rust/attribute.md#api-names),
[Rust Channel](https://docs.superdurable.io/zh-Hans/reference/rust/channel.md#api-names),
[TypeScript Attribute](https://docs.superdurable.io/zh-Hans/reference/typescript/attribute.md#api-names), and
[TypeScript Channel](https://docs.superdurable.io/zh-Hans/reference/typescript/channel.md#api-names) references.

<a id="rpcs"></a>

## RPCs

Language-specific RPC rules are in the SDK references: Java Flow classes and
[Kotlin](https://docs.superdurable.io/zh-Hans/reference/java/rpc.md#rpc-stubs-and-kotlin), and
[TypeScript codecs](https://docs.superdurable.io/zh-Hans/reference/typescript/rpc.md#rpc-codecs).

<a id="cancel-running-steps"></a>

### Cancel running Steps

An RPC result can cancel active Steps of its Flow. Select the Steps by Step
type: **with_canceling_steps** in Python, **CancelSteps** in Go,
**withCancelingSteps** in Java, **cancelingSteps** in TypeScript, and
**cancel_step** in Rust. The selection covers the whole Flow. An RPC has no
parent Step execution, so it cannot cancel sibling Steps. A Step can cancel
other Steps the same way from its
[StepDecision](https://docs.superdurable.io/zh-Hans/reference/python/step-decisions.md#cancellation-on-stepdecision).

In the example, **GenerateReport** writes a report section by section. The
**stop_report** RPC cancels it and starts **FinishReportStop**.

**Python**

```python
@rpc(timeout=timedelta(seconds=30))
def stop_report(self, context: Context, input: None) -> RPCResult[bool]:
    if REPORT_STATUS.get(context) in (REPORT_READY, REPORT_STOPPED):
        return RPCResult(False)
    return RPCResult(
        True,
        next_steps=(StepMovement.of(FinishReportStop, None),),
    ).with_canceling_steps(GenerateReport)
```

例子: [examples/python/dex_examples/primitives/rpc_canceling_steps](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/rpc_canceling_steps)

Dex applies the cancellation when it commits the RPC. It commits the RPC's
Attribute writes and Channel publications first, then cancels, then starts the
RPC's next Steps. All of it commits together, or none of it does. The RPC's own
next Steps are not canceled, even when they have a selected Step type. A
selected Step that has already finished is skipped, and so is a type with no
active Step. Waiting Steps take the RPC's publications only after the
cancellation, so a canceled Step never takes them. Changed in 0.1.26: a waiting
Step could consume a publication of the same RPC and then be canceled, which
lost the message.

Cancellation ends every active Step of a selected type: one that waits, one that
waits for a retry, and one whose attempt runs on a Worker. For a running
attempt, Dex sends a cancellation to that Worker. A canceled Step is not
retried, and its failure route does not run. Dex discards anything the canceled
attempt returns later, including its StepDecision and Attribute writes. Channel
messages that the Step's wait consumed return to their Channels. See
[Canceled Steps return consumed messages](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#canceled-step-messages).

<a id="cancel-race"></a>

#### Resolve the race from committed state

The RPC handler reads a snapshot of the Flow when it starts. Dex commits its
result later. The Steps to cancel are chosen at commit time, not from the
snapshot. Between the two, a selected Step can finish and commit its own result.
Then the cancellation finds nothing to cancel. A new Step of a selected type can
also start, and the cancellation ends it too. Dex does not reject the RPC in
either case. So the handler cannot assume that the Step it saw is still running,
or that its work did not commit.

Do not decide the outcome in the RPC handler. Start a follow-up Step from the
RPC, and let it read the committed state. In the example,
**FinishReportStop** checks whether the report committed before the
cancellation. If it did, the Stop came too late, and the Flow delivers the
report. Otherwise, it records that the report stopped.

**Python**

```python
def execute(self, context: Context, input: None) -> StepDecision:
    # The report can commit after stop_report read its snapshot.
    if REPORT_STATUS.get(context) == REPORT_READY:
        return dead_end()
    REPORT_STATUS.set(context, REPORT_STOPPED)
    return graceful_complete(REPORT_STOPPED)
```

例子: [examples/python/dex_examples/primitives/rpc_canceling_steps](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/rpc_canceling_steps)

[Attribute locks](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#attribute-locks) do not close this gap on their own. They
keep the RPC from running at the same time only as Step methods that declare
the same locks.

<a id="cancel-honour"></a>

#### Make the Step stop

Dex cannot stop code that ignores cancellation. The Step code must check for it
and return:

- Python: with **AsyncWorker**, Dex cancels the handler's task, so the next
  await raises **CancelledError**. With **Worker**, the handler runs on a thread
  and must check **is_cancellation_requested**.
- Go: Dex cancels the handler's **Context**. Pass it to calls that accept a
  context, or select on **Done**.
- Java: Dex interrupts the handler thread. Blocking calls throw
  **InterruptedException**, and **isCancellationRequested** returns true.
- TypeScript: Dex aborts **context.cancellationSignal**. Pass it to calls that
  accept an **AbortSignal**.
- Rust: check **is_cancelled**, or block in **wait_for_cancellation**.

**Python**

```python
for section in range(1, SECTION_COUNT + 1):
    # A Stop cancels this task, so the await raises CancelledError.
    await asyncio.sleep(SECTION_WORK.total_seconds())
    REPORT_PROGRESS.write(context, section)
```

例子: [examples/python/dex_examples/primitives/rpc_canceling_steps](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/rpc_canceling_steps)

Dex waits about one second for the canceled attempt to end. If the handler is
still running, Dex closes the Worker stream that carried it. The handler keeps
running inside the Worker process until it returns, and its external calls
still take effect. A canceled attempt may also have done part of its work before
it stopped. Keep its external effects idempotent. See
[Failure and redelivery](https://docs.superdurable.io/zh-Hans/reference/python/failure-and-retries.md#failure-and-redelivery).

<a id="read-only-rpcs-and-terminal-flows"></a>

### Read-only RPCs and terminal Flows

To read stored Attribute values from outside the Flow, an application does not
need a read-only RPC. The Client's **GetAttributes** reads committed values
directly, without a Worker. See
[Read Attributes from outside a Flow](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#read-attributes-from-outside-a-flow). Use
a read-only RPC when the read needs Flow-side logic, such as validation,
authorization, Channel messages, or a derived view.

An RPC without Attribute locks and without transactional execution starts by
reading the Flow. If its handler returns only an output and no durable effects,
Dex returns that output without changing the Flow. That read also works on a
closed Flow run that the server still retains. So a successful read-only RPC
does not prove that the Flow is active.

Attribute locks and explicit transactional execution need an active Flow run. A
non-transactional handler that returns Attribute writes, Channel operations,
events, or Step movements also needs an active Flow run, because Dex commits
those effects to the Flow after the handler returns. A closed Flow rejects that
commit, even though the Worker handler may already have run. An external call
the handler made does not roll back with the rejected commit, so send a
provider change from a Step, with its own idempotency key. A server can also
be configured to run every RPC transactionally, which requires an active Flow
run.

When the response needs the current status of the Flow run, use a Flow
lifecycle API, such as **DescribeFlow**. Do not infer that a Flow is closed or open
from whether an RPC succeeded.

**FlowNotActiveOrNotFoundError** means that the target was not found, or that
the operation cannot use its closed Flow run. Java uses
**FlowNotActiveOrNotFoundException**; Rust uses
**SdkError::FlowNotActiveOrNotFound**. The error alone does not tell a missing
Flow from a closed one.

A read-only RPC with no locks, no transactional execution, and no durable
effects can still read a retained closed Flow run, unless the server forces
transactional execution. For such an RPC, treat this error as "no readable
target found", and keep your application's outcome for a missing or expired
Flow. Do not add a lifecycle lookup, a **WaitForFlow** with a short timeout, a
retry, or decoding of old Step outputs only to tell missing from closed. Handle
other service and Worker failures separately.

For writes and RPCs that need an active Flow run, the same error may mean that
the Flow is closed or missing. Apply the operation's business policy; the error
does not prove that the requested action succeeded.

You do not need to look up a Run ID before a normal read-only RPC. When the SDK
offers an optional Run ID, omit it: the server then picks the current Flow run
and uses it for the whole invocation. Pass a Run ID only when the application
must address an exact Flow run across Flow ID reuse.

<a id="load-collection-state"></a>

### Selective state loading

Every RPC receives regular Attribute values and Channel sizes. To read
AttributeMap entries or pending Channel messages, the RPC must declare a load.
This keeps large collections out of RPC requests that do not use them.

Load a whole AttributeMap or ChannelMap when the handler needs all current
instances. Load exact map instances when it needs only known keys. Load a
Channel when the handler needs its pending message IDs or Values. Channel size
and ChannelMap keys and sizes remain available without loading pending messages.

Every SDK declares loads with the RPC. Go puts them in the **RPCOptions** passed
to **DefineRPC** from **GetRPCs**. Dex Server checks each requested definition
against the Flow persistence schema, and returns the loaded scope with the RPC
snapshot. When the handler reads a selectively loaded collection, the SDK checks
that scope.

For an **AttributeMap** entry or instance enumeration outside that scope, the SDK
raises **AttributeMapNotLoadedError**. For pending messages outside that scope,
it raises **ChannelMessagesNotLoadedError**. Java uses
**AttributeMapNotLoadedException** and **ChannelMessagesNotLoadedException**.
For Go, **dexcli visualize** reports an RPC that reads unselected state. See
[State loads](https://docs.superdurable.io/zh-Hans/reference/web/flow-visualization.md#state-loads).

An explicitly loaded collection can be empty; that is not an error. An empty
Channel returns an empty list of pending messages. An absent **AttributeMap**
entry behaves like any absent value in the SDK. Loading takes one snapshot of
the input. It does not consume messages, make the RPC transactional, or protect
the handler from concurrent changes.

<a id="runtime-selected-map-instances"></a>

#### Runtime-selected map instances

Use the RPC definition options for fixed behavior shared by every invocation:
timeout, ordinary Attribute locks, transactionality, whole-map loads, singleton
Channel loads, and fixed exact-instance loads. Go names this type
**RPCOptions**.

Use **RPCInvokeOptions** when the calling code chooses an AttributeMap or
ChannelMap instance from request data. Rust uses **RpcInvokeOptions**.
Invocation options can add exact AttributeMap loads, exact ChannelMap loads, and
AttributeMap instance locks. Dex merges them with the registered definition,
sorted and without duplicates. They cannot replace or clear registered
settings.

Loading and locking are independent. A read-only lookup needs only the exact
load. A read-modify-write RPC must add both the load and the lock for the same
AttributeMap instance. Before the network call, the SDK checks that the
definition belongs to the Flow, that its kind fits, and that the instance key is
not empty and contains no **/**.

**Python**

```python
options=RPCInvokeOptions(
    lock_attribute_map_instances=(
        flow.customer_profiles_by_email_partition.lock(partition_name),
    ),
    load_attribute_map_instances=(
        flow.customer_profiles_by_email_partition.load(partition_name),
    ),
)
```

例子: [examples/python/dex_examples/patterns/hash-partitioned-attribute-map/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/patterns/hash-partitioned-attribute-map/controller.py)

See [Hash-Partitioned AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/hash-partitioned-attribute-map.md)
for the complete lookup and upsert example, and
[Sequentially Chunked AttributeMap](https://docs.superdurable.io/zh-Hans/design-patterns/data-storage/sequentially-chunked-attribute-map.md)
for dynamic pagination loads.

<a id="transactional-reads-and-writes"></a>

### Transactional RPCs

A transactional RPC performs its reads and writes as one atomic operation. An
RPC that holds an Attribute lock is always transactional. You can also make an
RPC transactional explicitly by setting **is_transactional=true**.

Transactional execution matters most for Channel message deletion. Before it
commits any write, Dex checks that every deleted message is still pending. If a
message is gone, the RPC fails with the Channel-message-not-found error
(**NOT_FOUND**) and commits nothing. A non-transactional RPC treats a missing
deletion as a no-op and still commits its other successful effects.

In the example, the caller passes only a pending message ID. The RPC loads the
source Channel, reads the original Value from its snapshot, and then stages the
deletion and the publication to the destination. If a concurrent consumer took
the message first, the deletion check fails, and Dex commits neither effect:

**Python**

```python
@rpc(is_transactional=True, load_channels=(queued_messages,))
def move_queued_message_to_prioritized_messages(
    self, context: Context, queued_message: QueuedMessageReference
) -> None:
    message_to_prioritize = self.queued_messages.find_pending_message(
        context, queued_message.message_id
    )
    self.queued_messages.delete(context, queued_message.message_id)
    if message_to_prioritize is not None:
        self.prioritized_messages.publish(context, message_to_prioritize.value)
```

例子: [examples/python/dex_examples/primitives/channel/channel_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/channel/channel_flow.py)

A transactional commit does not stop other Steps and RPCs from changing the
Flow while the handler runs. If a decision depends on the whole loaded Channel,
ChannelMap, or AttributeMap staying unchanged, every Step and RPC that writes it
must use the same Attribute lock. The lock prevents those changes and makes the
RPC transactional; it does not load collection contents.

<a id="rpc-timeout"></a>

### RPC timeout

An RPC timeout limits one Worker handler invocation.

Every SDK declares the timeout with the RPC. Go puts it in the static
**RPCOptions** passed to **DefineRPC**. A Client invocation cannot override it,
but the caller's context can stop waiting sooner. When the application
does not set a timeout, Dex Server uses its default of 60 seconds, set by
**api.defaultRpcTimeout**. An explicit timeout has no maximum.

**Python**

```python
@rpc(timeout=timedelta(seconds=30))
```

例子: [examples/python/dex_examples/primitives/rpc](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/rpc)

<a id="rpc-request-ids"></a>

### RPC request IDs

Every RPC invocation carries a request ID. Dex Server records the reply of a
successful RPC that it commits under that request ID. A repeat that Dex Server
checks against a recorded request ID returns the recorded output. It applies
the RPC's Flow changes, such as Attribute writes, Channel publications, and
next Steps, no second time. Whether Dex Server checks a repeat depends on the
RPC and on what the repeated attempt returns.

By default, SDKs send a new request ID on each call, so calling an RPC again
from your code runs it again. To make a retried call idempotent, pass the same
request ID on every attempt, where the SDK accepts one. The TypeScript SDK
takes it as **requestId** of **RPCInvokeOptions**, and the Python SDK as
**request_id** of **RPCInvokeOptions**. Use an ID that names the
logical call, such as the ID of an event that is delivered at least once.

How Dex Server answers a repeat depends on the RPC:

| RPC                      | Repeat with a recorded request ID                                                                                                                                                                                                                                                                                                                               |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Transactional or locking | Answered from the recorded reply before a Worker runs the handler. Concurrent calls with the same request ID share one handler execution and its result.                                                                                                                                                                                                        |
| Any other RPC            | The handler runs again on a Worker, and its calls to external systems repeat. When this attempt changes Flow state or records an event, Dex Server discards those changes and returns the recorded reply. When this attempt changes no Flow state and records no event, Dex Server returns its new output without checking the request ID, and records nothing. |

An RPC that is neither transactional nor locking can therefore return a new
output to a repeat. For example, a handler that marks an event processed
returns a different output once the mark exists. Use a transactional RPC when
callers need the exact recorded reply.

For a transactional or locking RPC, the recorded reply includes a refusal that
the handler returned, such as `false`. A business retry after a refusal, such as offering again later, is a
new logical call. Give it a new request ID.

These rules also apply:

- Dex Server compares only the request ID, as it does for StartFlow. A repeat
  with a different RPC name, input, timeout, locks, or loads is still a repeat.
  Dex Server answers it as the table above describes and applies none of its
  Flow changes. Concurrent
  transactional or locking calls with the same request ID share one handler
  execution, whatever their inputs. Changed in 0.1.37: Dex Server compared the
  whole request and rejected a different request under a kept request ID with
  INVALID_ARGUMENT.
- Each run keeps its newest request IDs, as many as
  [**limits.maxRequestIdsPerRun**](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#limits).
  RPC request IDs share this window with the run's other request IDs, such as
  those of Client Attribute writes. A repeat with an older request ID runs as
  a new request. A new run of the same Flow ID starts with no request IDs.
- A failed RPC records nothing. A retry after a Worker error or an
  [RPC timeout](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#rpc-timeout) of the Worker handler runs the handler again.
- A client-side deadline or cancellation leaves the outcome unknown. The server
  may still commit the RPC. A retry with the same request ID applies the Flow
  changes at most once. For a transactional or locking RPC, the retry joins
  the invocation still in flight, or returns the recorded reply after it
  commits. Any other RPC runs its handler again.
- UNAVAILABLE after the server's commit budget also leaves the outcome
  unknown. A retry with the same request ID can run the handler again, and
  still applies the Flow changes at most once.
- After the Flow run closes, a transactional or locking RPC with a recorded
  request ID returns its recorded reply while the server retains the run. With
  a new request ID it fails with NOT_FOUND and FLOW_NOT_EXISTS, as described in
  [Retention](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#retention).
- On a run over its [Flow state budget](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#flow-state-budget),
  an RPC that changes no Flow state keeps no request ID.
- A request ID must be non-empty. Dex Server sets no other length or character
  limit. Each kept request ID counts toward the run's Flow state budget, so
  keep request IDs short.

<a id="trigger-event-request-ids"></a>

#### Connector Trigger events

A Connector Trigger can deliver one provider event more than once. It keeps
the provider event ID and time; your application supplies the final filter
and resolves the Flow ID. For a start target, map each event to a stable Flow
ID, use the event ID as the request ID, and disallow Flow ID reuse. A repeat
then starts no other run while Dex retains that Flow ID. For an RPC target
that receives a stable request ID, a transactional RPC applies each event's
Flow changes at most once while Dex Server keeps that request ID. Otherwise
the RPC handles duplicates in its own bounded state.

<a id="channels"></a>

## Channels

<a id="channel-conditions"></a>

### Wait conditions

A Channel condition in **WaitFor** consumes the oldest pending messages, in FIFO
order. Each SDK names these conditions in its own style; its Channel page lists
the names.

| Condition         | When it proceeds                                | What it consumes                                                          |
| ----------------- | ----------------------------------------------- | ------------------------------------------------------------------------- |
| **ForOne**        | At least one message is pending.                | Exactly one message.                                                      |
| **ForN**          | At least the requested number is pending.       | Exactly that number of messages.                                          |
| **AtLeast**       | At least the requested number is pending.       | Every message currently pending.                                          |
| **AtMost**        | Immediately, including when the queue is empty. | Up to the requested number of currently pending messages.                 |
| **AtLeastAtMost** | At least the lower bound is pending.            | From the lower bound up to the upper bound of currently pending messages. |

**AtMost** does not wait for messages to arrive. When the surrounding Wait
completes, it consumes up to the limit from the messages pending at that time. To wait for at least one message and consume up to a limit, use
**AtLeastAtMost** with a lower bound of 1.

<a id="canceled-step-messages"></a>

### Canceled Steps return consumed messages

A wait consumes its messages when it is satisfied, before **Execute** runs. A
**StepDecision** or an RPC can cancel the Step before its **Execute** commits.
In that case, Dex returns those messages to the front of their Channels or
ChannelMap instances, in their original order, and they are pending again. A
waiting Step can consume them in the same commit.

A canceled **Execute** attempt may already have received a message that Dex
returned. Another Step can then receive the same message. Make message
processing idempotent, for example with a business ID in the message.

Dex drops the consumed messages instead when the Flow close itself cancels the
Step: a **StopFlow** request, a Flow timeout, a failure that closes the Flow, or
a **StepDecision** that cancels the Step and closes the Flow with
**ForceComplete** or **ForceFail**. Every other cancellation returns the
messages, even when the Flow closes in the same commit. For example, a
**StepDecision** that cancels the Step and returns **GracefulComplete** closes
the Flow when no other Step is active, and the returned messages stay pending
in the closed Flow run. **ForceCompleteIfChannelsEmpty** counts the returned
messages as pending, so the Channel is not empty.

Changed in 0.1.26: Dex dropped the consumed messages of every canceled Step.

<a id="channel-waiter-order"></a>

### Waiter order

When several Steps wait on one Channel, Dex offers each new message to them in
the order they started waiting. A Step whose wait needs more messages than are
pending is skipped, and a later Step can take them. A Step that starts waiting
while enough messages are pending takes them at once, even ahead of earlier
waiters that need more.

A wait for several messages (**ForN**, **AtLeast**) can therefore wait forever
while waits for one message (**ForOne**) on the same Channel keep taking the
messages one at a time. Give each Channel one kind of consumer, or use one
ChannelMap instance for each consumer when they need different counts.

<a id="join"></a>

### Join

A **Join** is a named ChannelMap that counts the results of the parallel
branches one Step forks. Each fork starts one round and gives the branches and
the join Step one round token: the round key and the branch count. See
[Join parallel branches](https://docs.superdurable.io/zh-Hans/reference/go/waits.md#join) for the API of each language.

- A fork takes its round key from the forking Step execution. A Step method can
  fork one Join once. For a second independent join, define a second Join or use
  an explicit round key. A fork with an explicit round key can run several times in
  one method. Give each round a key that no other round of that Join in the Flow
  run uses. An RPC has no Step execution, so an RPC forks with an explicit
  round key.
- A report commits with the method's result, so a retried branch reports once.
  A result reported before the join Step waits still counts.
- Results of one round never satisfy the join of another round.
- A fork over an empty branch list is a round with no branches. A
  **ForAllBranches** wait on it is satisfied at once. **ForFirstBranch** and
  **ForBranches** on it fail the wait.
- The join Step consumes results like any Channel wait. When a decision cancels
  it after its wait matched, the results follow
  [the canceled Step rule](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#canceled-step-messages). When Dex drops them, a new
  join for the same round never fires.
- A canceled branch never reports and its failure route does not run. A branch
  that reported before the cancel committed is complete, and its result stays
  pending in the round. Dex picks the Steps to cancel at commit time, so no
  canceller can report on behalf of a branch.
- A decision that cancels sibling Steps selects the Steps that one decision
  started together. Fork starts the branches and the join Step together, so the
  siblings are exactly the branches of that round. They do not include the later
  Steps of a multi-Step branch.
- When an RPC forks a round with an explicit round key, the branches are siblings
  of every Step that this RPC name ever started. Cancel them by Step type
  instead.
- **ForRemainingBranches** resets a round whose other branches keep running. Its
  count equals the count the join consumed: n, or 1 after **ForFirstBranch**.
  The next round's branches start only after the reset completes, so enablement
  messages for the next round stay queued until then.
  Without a reset, late results stay pending until the Flow closes.
- A cancelling join's round is never reset, because its canceled branches never
  report and the reset would wait forever. The next round forks a new round
  directly. Its round key keeps it apart from the old one.

<a id="manage-pending-messages"></a>

### Pending messages

Dex assigns a UUIDv7 message ID when it accepts each publication. A Step or RPC
can list every pending message in FIFO order and delete one by ID. Listing does
not consume messages.

Deleting a message that is no longer pending depends on the caller:

| Caller                                            | Missing message                                                                                                                                                                                                         |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Transactional RPC                                 | The RPC fails with the Channel-message-not-found error and commits nothing. See [Transactional RPCs](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#transactional-reads-and-writes). |
| Non-transactional RPC                             | The deletion is a no-op. The other effects commit.                                                                                                                                                                      |
| Step method or Flow timeout handler               | The deletion is a no-op. The other effects commit.                                                                                                                                                                      |
| Direct **DeleteChannelMessage** (dexcli, Dex Web) | The call fails with **NOT_FOUND** and sub-status **CHANNEL_MESSAGE_NOT_FOUND**.                                                                                                                                         |

Pending messages are queue state, not Flow history. After a Step consumes a
message, the message disappears from the Channel, even though the publication
and consumption stay visible in recent
[Flow history](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#history-window). The message
comes back only when the Step is canceled before its **Execute** commits. See
[Canceled Steps return consumed messages](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#canceled-step-messages).

Every Step method, timeout handler, and RPC always receives Channel sizes. To
read the IDs or Values of pending messages, it must load them explicitly. To
delete a message whose ID it already knows, it does not need to load it.
**StepOptions** selects state separately for **WaitFor** and **Execute**;
**FlowTimeoutHandlerOptions** selects state for the timeout handler. Loading a
Channel takes one snapshot for the invocation and does not consume messages. A
loaded empty Channel returns an empty list. Reading pending messages without
loading the Channel is a usage error.

Treat every snapshot of pending messages inside a Step or RPC as possibly out of
date. Other Steps and RPCs can consume, delete, or publish messages while the
handler runs. Transactional execution checks the selected deletions and commits
the handler's writes atomically, but it does not lock the whole Channel. Read
and write pending messages directly only when the operation can tolerate these
concurrent changes. If a decision requires the queue to stay unchanged, every
Step and RPC that writes it must use the same Attribute lock.

A Step or timeout handler can stage a deletion with its other side effects. Dex
applies the effects of a successful handler in this order: Attribute writes,
best-effort Channel deletions, Channel publications, and then the Step
decision.
**StepDecision** describes only control flow; it does not contain deletions.
Waiting Steps take the publications after the decision's cancellations, so a
Step that the decision cancels never takes them. A decision that also closes
the Flow at once, with **ForceComplete**, **ForceFail**, or a
**ForceCompleteIfChannelsEmpty** that closes, is the exception: a waiting Step
can take a publication, and the close then cancels that Step and drops the
message. Changed in 0.1.26: waiting Steps took the publications before the
cancellations.

An RPC can combine deletion with other durable writes. The move example in
[Transactional RPCs](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#transactional-reads-and-writes) loads **QueuedMessages**,
finds the original Value by message ID, then stages its deletion and
republishes that Value. The caller sends only the ID.

<a id="channelmap"></a>

### ChannelMap

RPCs can always read the current ChannelMap keys and sizes. Load the entire
ChannelMap when the handler needs every instance's pending messages. Load exact
instances when it needs only known keys. Instance keys cannot contain **/**
because Dex uses that character between the map name and instance key.

<a id="streams"></a>

## Streams

Server settings for Streams, with their defaults, are in
[Streams](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#streams).

<a id="stream-write-semantics"></a>

### Write semantics

A direct Step write has these semantics:

- Dex sends it immediately during **WaitFor** or **Execute**. It is not held
  back until the Step completes.
- A later Step failure does not roll the message back.
- One method invocation can write any number of messages to the same or
  different Streams. Each write also counts as a heartbeat, and keeps the last
  explicit heartbeat value. The [Polling with Long-Running Step Heartbeat](https://docs.superdurable.io/zh-Hans/design-patterns/durable-timer/polling-with-long-running-step-heartbeat.md) pattern uses
  these writes to report progress.
- The SDK confirms only that it encoded the message and handed it to the Worker
  output stream. If the Stream Store is disabled, unavailable, full, or rejects
  the message, Dex drops the message without failing the Step.
- Every Step message has the source **#StepExecutionID**, so all attempts and
  messages of one Step execution share it. The source is informational, not
  unique, and does not deduplicate retries. After a Dex Server node crashes, an
  ASYNC Step can also run the same attempt number again, and its batches can
  repeat under the same source.

A Client can write even when the Flow does not exist or is no longer active.
Supply a non-empty source for each write. A source may repeat and may contain
**#**; every call appends another message. RPC handlers cannot write through
their Context, but they can send Stream messages through a Client passed to
them as a dependency.

Python coroutine Steps call **Stream.write** without **await**. Python
synchronous Steps must yield the returned **StepOutput** from a generator. Other
SDKs send the frame through their Step Context, and return once it is queued
locally.

<a id="stream-buffered-text"></a>

### Buffer text chunks

Use the buffered text writer when many small chunks form one text value, such as
LLM deltas. The default flush interval is one second and the soft threshold is
16 KiB of UTF-8 data. The writer sends the current batch, if it is not empty,
when the timer fires, when the size threshold is reached, or when the method
returns. The writer keeps text exactly as written, never splits a chunk, and
ignores empty chunks.

Go, Java, Python async, TypeScript, and Rust stop the timer and flush the rest
before sending the final result or error. Python sync generators check the
elapsed time only when you write another chunk, and must yield from an
explicit final flush. An empty buffer sends no Stream message and no heartbeat.
A retry does not restore unsent text, and batches sent before a retry may appear
again.

<a id="stream-resumable-reads"></a>

### Resumable reads

**ReadStream** returns one message with its value, resume token, creation time,
and source.

- An empty token starts at the current retained head.
- A token older than the retained head also starts at that head.
- Pass the returned token unchanged to read the next message.
- When no next message exists, the call long-polls until a message arrives or
  the wait expires.

Resume is best effort. A slow reader can miss messages trimmed before its next
read.

<a id="stream-listing"></a>

### List messages

Use **ListStreamMessages** to inspect retained messages from newest to oldest.
The call does not block. It returns at once with up to the requested page size.

An empty before-page token starts at the newest retained message. Pass the
returned next-page token unchanged to read the next older page. The page starts
after the token's message, and the token works only for the same Flow type,
Flow ID, and Stream name. An empty next-page token marks the last page.

**Python**

```python
        page = await app_state.client.list_stream_messages(
            required_query("workflowId"),
            app_state.stream.progress,
            required_int_query("pageSize"),
            optional_query("beforePageToken", ""),
        )
```

例子: [examples/python/dex_examples/primitives/stream/controller.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/primitives/stream/controller.py)

Listing is best effort, not a consistent snapshot. Messages appended after the
first page do not appear in the older pages, but trimming can remove messages
between calls. If trimming removes every message older than the page token, Dex
returns an empty page instead of starting again from the newest message.

The page size must be between 1 and **streamStore.maxReadMessages**, which
defaults to 1000. The server rejects a page size outside that range with
**INVALID_ARGUMENT**; it does not reduce a larger value.

Use **ReadStream** for forward, one-message-at-a-time consumption that can
long-poll and resume. Use **ListStreamMessages** for reverse, non-blocking
pagination over currently retained messages.

<a id="stream-capacity"></a>

### Capacity and trimming

**streamCapacityBytes** is an approximate capacity shared by all Flow runs
with the same Flow type and Stream name. It is not a limit for each Flow ID.

The server estimates each message's size from its serialized value, Flow ID,
source, and the configured overhead for each message.

When usage reaches the trim trigger threshold, background trimming removes the
oldest messages across all Flows until usage reaches the trim target. A server
runs several trim workers, but only one job trims a given Stream at a time. If
trimming is too slow and usage reaches **streamCapacityBytes**, the server
rejects the write with **RESOURCE_EXHAUSTED**. The rejection also asks trimming
to free room for that message, so a Client can retry the write. The server
rejects a message larger than the Stream's capacity the same way, but that
message can never fit, so do not retry it.

The server also limits the size of each Stream message, the capacity of one
Stream, and the memory of all Streams on a server. A Client write past the
server-wide total fails with **RESOURCE_EXHAUSTED**, and background trimming
then removes the oldest messages of the largest Streams until the message fits.
Retry the write after a short delay. See
[Streams](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#streams) for each limit and its
default.

<a id="stream-storage"></a>

### Best-effort storage

The Stream Store keeps messages in the memory of the active server process.
**streamStore.backend** defaults to **memory** for both **dexcli dev** and a
production server. The messages disappear when the server process restarts or a
standby takes over. Trimming or a full Stream can also remove or reject
messages. After a loss or a reconnect, a reader rebuilds its view from
Attributes, an RPC, or the Flow result. An operator can set the backend to **disabled**. Client Stream writes
and reads then fail with **FAILED_PRECONDITION**, and Dex drops Step writes
without failing the Step.

<a id="timers"></a>

## Timers

<a id="timer-firing-time"></a>

### Firing time

A Timer's deadline is the server's timestamp for the **WaitFor** result that
declared the Timer, plus the Timer's duration in whole seconds.

Except for an explicit **SkipTimer**, Dex never satisfies a Timer condition
before its deadline. After the deadline, the firing can be late, for example
while the server is busy or failing over. Until the Timer fires, another
condition can still satisfy the wait. So in an **AnyOf**, a Channel message
that commits after the Timer's deadline can still win.

A fired or skipped Timer makes only its own condition ready. Dex then checks
the whole Wait again, and **Execute** runs once the Wait is satisfied and a
Worker takes the Step.

When a Timer's duration comes from a stored business deadline, as
[Business deadlines](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#timer-business-deadline) describes, the wake-up drifts
from that deadline. Rounding the remaining time
up to whole seconds, and the time to save the **WaitFor** result, make it
later. Clock skew between the Worker and the server can make it earlier or
later. Each **WaitFor** retry computes the remaining time again; only the saved
result defines the wait. Compute the remaining time from the current clock,
not the Step's first-attempt time: a Time Travel keeps the original
first-attempt time.

<a id="timer-business-deadline"></a>

### Business deadlines

A Timer's deadline is the time its **WaitFor** result is saved plus its
duration. When **WaitFor** runs again, after a
[Time Travel](https://docs.superdurable.io/zh-Hans/production-operations/deploy-code-changes.md#apply-new-waitfor-code) to it or in a
new Step execution after a deploy, it declares a new Timer, so a fixed
duration starts over. So keep the business deadline where the rerun can read
it: in the Step input, or in an Attribute committed by the time that Step
execution was created; a value from the Flow's start input reaches only the
first Step, so pass it down as Step input. In **WaitFor**, use the stored
deadline minus the current clock as the duration, rounded up to whole seconds
and never below zero.

<a id="subflows"></a>

## SubFlows

When Dex rejects a Wait as invalid, it starts none of the children in that
Wait, and the `WaitFor` result fails. Only a completed child has outputs, so
check the child's status before you decode an output.

<a id="subflow-options"></a>

### SubFlowOptions

**SubFlowOptions** are the SubFlow version of the **StartFlowOptions** of
**StartFlow**. Most options are the same; **SubFlowReusePolicy** is the
difference.

<a id="subflow-step-types"></a>

### Step types that start SubFlows

Dex Server builds each SubFlow ID from the parent Flow ID, the Step execution
ID, and the condition index, joined with a dash. A Step execution ID is the
Step type, a dash, and a counter:

```text
SubFlow:<parent Flow ID>-<Step type>-<counter>-<condition index>
```

A dash inside a Step type makes this ID ambiguous. For example, parent **a-b**
at Step type **C** and parent **a** at Step type **b-C** both produce
**SubFlow:a-b-C-1-0**, so two parents would share one child.

Changed in 0.1.26: a Step whose Step type contains a dash cannot start
SubFlows. Dex Server rejects a WaitFor result that registers a SubFlow
condition from such a Step as an invalid Worker response. The attempt fails
without retry, with an error that names the Step type. Step types with a dash
may still wait on Timers and Channels. To migrate, rename the Step type so it
has no dash.

<a id="subflow-reuse-policy"></a>

### SubFlowReusePolicy

Dex Server generates a SubFlow ID from the parent Flow ID, Step execution ID,
and condition index. When a parent reuses a Flow ID with **IDReusePolicy**, or
time travels, it can enter the same Step execution and try to start the same
SubFlow ID again. **SubFlowReusePolicy** controls what happens in that case.

The default **RESTART_IF_PREVIOUS_EXITS_ABNORMALLY** is usually what a parent
wants: continue waiting for a running child, use a successful child result, and
restart a child that ended abnormally.

| Existing child Flow                        | **ATTACH**        | **RESTART_IF_PREVIOUS_EXITS_ABNORMALLY** | **ALWAYS_RESTART**  |
| ------------------------------------------ | ----------------- | ---------------------------------------- | ------------------- |
| No existing Flow                           | Start             | Start                                    | Start               |
| Running                                    | Attach            | Attach                                   | Terminate and start |
| Completed                                  | Return its result | Return its result                        | Start               |
| Failed, canceled, timed out, or terminated | Return its result | Start                                    | Start               |

Dex Server first compares the Request ID that it generated for this child start
with the existing child's. With a matching Request ID, Dex always attaches to a
running child or returns its final result, whatever the **ReusePolicy**. This
makes a retry safe when Dex Server accepted the original start but the parent
did not receive the response. With a different Request ID, Dex Server applies
the selected **ReusePolicy** from the table.

<a id="subflow-parent-lifecycle"></a>

### Later parent runs and parent close

A later run of the same parent Flow ID generates the same SubFlow ID when it
creates the same Step execution ID, which is the same Step type and counter, and
uses the same condition index. Step execution counters start again in each run,
so this is common. Dex treats that start as a repeated start under the
**SubFlowReusePolicy**. With the default policy, the later run reuses the earlier
run's running or completed child until Dex deletes that child.
**ALWAYS_RESTART** starts a fresh child, but it terminates an old child that is
still running. When both children must keep running, use a different parent Flow
ID.

A child keeps running when its parent Step is canceled or its parent Flow
closes. Dex does not stop it. Stop it explicitly, or give it a Flow timeout. A
child without a Flow timeout can wait forever when no Worker takes its Steps.
