---
title: "Client APIs"
description: "How Dex Server handles each Client call. The Application page explains the Client concept and its guarantees."
canonical_url: "https://docs.superdurable.io/zh-Hans/reference/server/client-apis/"
source: "docs/reference/server/runtime-client.mdx"
locale: "en"
site_locale: "zh-Hans"
language: "python"
---

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

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

# Client APIs

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

The [Client](https://docs.superdurable.io/zh-Hans/concepts/application.md#client) section of the Application page
explains the concept and its
[guarantees](https://docs.superdurable.io/zh-Hans/concepts/application.md#client-guarantees). For each language's
names, parameters, and errors, see the Client page of each SDK reference:
[Go](https://docs.superdurable.io/zh-Hans/reference/go/client.md), [Python](https://docs.superdurable.io/zh-Hans/reference/python/client.md),
[Java](https://docs.superdurable.io/zh-Hans/reference/java/client.md), [TypeScript](https://docs.superdurable.io/zh-Hans/reference/typescript/client.md),
and [Rust](https://docs.superdurable.io/zh-Hans/reference/rust/client.md).

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

## Example

This handler starts a Flow. The query string supplies the Flow ID and the start
input.

**Python**

```python
flow_id = required_query("workflowId")
run_id = await app_state.client.start_flow(
    app_state.client_apis,
    flow_id,
    required_query("keyword"),
    start_options(),
)
return started_flow(flow_id, run_id)
```

例子: [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)

Run it from the
[examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).

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

## Start a Flow

**StartFlow** creates a Flow run. It takes a registered Flow, a business
**Flow ID**, the start Step input, and **StartFlowOptions**. It returns as soon
as the server accepts the request.

The Flow ID is the identity your application chooses. The server creates the
Run ID. See [StartFlowOptions](https://docs.superdurable.io/zh-Hans/reference/python/start-flow-options.md) for the timeout,
request idempotency, ID reuse, retry, initial Attributes, and configuration
overrides. When a reply is lost, retry the start with the same request ID; see
[Retention and start deduplication](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#retention-and-start-deduplication).
To get a result back, [wait for a Step](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#wait-for-a-step).

The Client encodes the start input and RPC arguments with the Flow's
registered definition. So a service that only starts Flows still builds and
registers the Flow objects. The Client never runs a Step, so the Flow's
services can be stand-ins, as in the
[Quick Start example folder](https://github.com/superdurable/dex/tree/main/examples/python/quick-start).
Pass the Client and the Flow definition to each HTTP handler through its
constructor or factory.

Pass business facts as start input or initial Attributes. The Flow's Steps and
RPC handlers apply the business rules and write the resulting state. If an
initial status depends on those rules, compute it in the first Step. Then the
rules live in one place, and each status change commits with the Flow's
progress.

A Step's **Execute** can use a Client to act on another Flow. It changes its
own Flow through its Context.

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

## Stop a Flow

**StopFlow** closes an active Flow. By default, it cancels the Flow. You can
instead terminate it, or fail it with a reason. Each of these closes the run
when the stop commits. Dex starts no new Steps or cleanup for that run: no
later Step decision, failure route, or cleanup runs. A plain read-only RPC can still query the retained run. Running Steps get a
cancellation signal. A handler that ignores it can keep running and make more external
calls, and Dex discards its uncommitted result. A Flow that
waits for the stopped one reads its terminal state instead of waiting for a
report. Make that Flow accept a report that arrived before the stop only once.

StopFlow can also complete a Flow, with an optional output that becomes a Flow
result. Since 0.1.34.

- **Graceful complete** works like the **GracefulComplete** Step decision.
  Active Steps keep running, and their decisions still apply. The Flow
  completes when no Step is active, or at once when none is. A Step can stop
  its own Flow this way and then return. Since 0.1.34, it also wakes Steps that
  wait on the
  [graceful completion condition](https://docs.superdurable.io/zh-Hans/reference/server/step-and-flow-close.md#graceful-completion-condition).
- **Force complete** works like the **ForceComplete** Step decision. The server
  cancels every active Step and completes the Flow. Like the Step decision,
  the close waits for pending Attribute Sync writes and transactional RPCs.

The output appears in the Flow results with an empty Step type and Step
execution ID. Outputs that Steps already returned through graceful completion
stay in the results. A later stop of any type still applies while a graceful
completion waits, and another graceful completion adds its output. The complete
stop types ignore the stop reason. The server rejects an output with any other
stop type as **INVALID_ARGUMENT**. While a Flow closes, it rejects the complete
stop types as described in
[Requests during Flow close](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#requests-during-flow-close). Servers before 0.1.34
reject the complete stop types as **INVALID_ARGUMENT**.

<a id="invoke-an-rpc"></a>

## Invoke an RPC

**InvokeRPC** calls a registered [RPC](https://docs.superdurable.io/zh-Hans/concepts/primitives/rpc.md) handler and
returns its result. A query-only RPC can also read a closed Flow run that the
server still retains. An RPC that commits effects needs an active Flow run.
To retry an RPC without applying it twice, reuse its request ID, as described
in [RPC request IDs](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#rpc-request-ids).

Application writes to Flow state go through RPCs. The low-level FlowService
**SetAttributes** request is a separate API.

<a id="publish-to-a-channel"></a>

## Publish to a Channel

**PublishToChannel** is a FlowService request that stores Channel messages for
a Flow on the server. It needs no connected Worker. The publication can satisfy
a matching wait in the same commit. A Worker runs the resulting **Execute**
when one is available. The SDK Clients do not expose this
request. Call it through gRPC, or with `dexcli api call PublishToChannel`. A
closing Flow rejects it, as
[Requests during Flow close](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#requests-during-flow-close) describes.

A repeated **PublishToChannel** request stores its messages again. Put a
business ID in each message, so the consuming Step can skip one it already
handled.

<a id="deduplicate-commands"></a>

## Deduplicate commands

Send a command as an RPC when the caller needs its result. An RPC needs a
connected Worker; see
[Routing and availability](https://docs.superdurable.io/zh-Hans/reference/server/workers.md#routing-and-availability).
To store a command while no Worker runs, publish it with
[PublishToChannel](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#publish-to-a-channel). A waiting Step handles it when a
Worker runs again.

A new RPC request ID lets the handler run and commit its changes again, and a
repeated **PublishToChannel** stores the message again. So give each command
an ID from your caller, and send it with the RPC arguments or the Channel
message:

- The RPC or Step that handles a command skips an ID it already handled.
- Each handler checks and updates the same receipt, such as an AttributeMap
  entry, under the same [lock](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#attribute-locks).
  The receipt and the command's Flow changes commit together.
- When repeats can arrive in a later run or after the receipt expires, keep
  the receipt where the handler and the caller can still check it; see
  [Confirm that a message was handled](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#confirm-message-handled).
- Give each external effect its own stable key, such as the command ID plus
  the operation name when that operation runs once per command. For an API
  without idempotency keys, see
  [Keyless API calls](https://docs.superdurable.io/zh-Hans/design-patterns/failure-handling/execute-failure-recovery.md#keyless-api-calls).

<a id="requests-during-flow-close"></a>

## Requests during Flow close

While a Flow closes, the server rejects these new requests with gRPC
**FAILED_PRECONDITION** and sub-status **FLOW_CLOSING**:

- transactional or locking RPCs;
- **WaitForStepCompletion** and **WaitForAttributeMatch**;
- Channel message deletion;
- Channel publication by a client (**PublishToChannel**);
- **StopFlow** with a complete stop type. Since 0.1.34.

A rejected publication stores no message. A closing Flow starts no Step, so no
Step could consume the message. Changed in 0.1.26: before, the server accepted
the publication and stored the message.

While a Flow closes, the server still accepts **SetAttributes** and RPCs that
are neither transactional nor locking. An RPC that commits during the close
starts and cancels no Steps. An RPC whose result publishes to a Channel fails
during the close, as [Pending close](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#pending-close) describes.

When the run closes before an RPC commits, Dex rejects the RPC's Flow changes.
External calls that its handler already made stay done, so call external
providers from a Step, not from an RPC handler.

<a id="pending-close"></a>

### Pending close

A close decision can leave the run in a pending close before its terminal
commit. For example, a **ForceCompleteIfChannelsEmpty** decision checks the
Channels and accepts the close in one atomic commit. The server cancels the
consumer Steps at once. When Attribute Sync writes are pending, or a
transactional or locking RPC was admitted before the close, the run waits for
them. During that wait:

- the run still reports **RUNNING**. Dex cancels running Steps, starts no new
  Step, and discards the uncommitted results of cancelled handlers. Running
  application code can ignore cancellation;
- an RPC that is neither transactional nor locking is still admitted;
- a transactional or locking RPC admitted before the close can still commit;
- a new transactional or locking RPC is rejected with **FLOW_CLOSING**;
- any RPC whose result publishes to a Channel fails with
  **FAILED_PRECONDITION** and **FLOW_CLOSING**, whether it is transactional,
  locking, or neither. The server rejects the whole Dex result: it commits no
  Attribute write, no publication, and no reply. No Step could consume the
  message. Changed in 0.1.38: before, the server stored the message, but no
  Step could consume it.

So a lock on an RPC changes whether it is admitted during the close. It gives
no guarantee that a Step consumes what the RPC published. The final terminal
commit rejects new effects. A retry to the same run that reuses a request ID
the run still retains can return the earlier result; see
[RPC request IDs](https://docs.superdurable.io/zh-Hans/reference/server/data-primitive-semantics.md#rpc-request-ids).

<a id="confirm-message-handled"></a>

### Confirm that a message was handled

An accepted RPC reply confirms the publication, not its handling. When a
caller must confirm each message:

- Give each message a stable business ID. The consuming Step records that ID
  as handled in the same commit as its Dex effects, and skips an ID it has
  already handled. An external effect uses the same ID for idempotency.
- The caller reads that record, for example with a Client Attribute read.
- To deliver a missing message again, keep its business ID and use a new RPC
  request ID. A network retry of the same delivery reuses its request ID; a
  new delivery that reuses it returns the old reply and publishes nothing.
- **GetAttributes** reads the latest run of a Flow ID unless it names a run ID;
  see [Target one run](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#target-one-run). When a Flow ID is
  reused across runs, keep a receipt that must survive the reuse where the
  caller can read it across runs. The latest run's record does not show what
  an earlier run handled.
- When no run accepts the message, report it as unconfirmed.

The Flow reports **RUNNING** until the server records the terminal close.

Each SDK exposes a typed Flow closing error. When you get it, read the Flow
state again after the close, before you decide whether to do anything more.
The error does not prove that an earlier request succeeded.

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

## Read Attributes

**GetAttributes** reads registered Attributes and AttributeMap instances from
outside the Flow. The API has only a batch form. Pass one read for each value:
a singleton Attribute, or one AttributeMap instance. To read one value, pass one
read.

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)
for the read semantics: one commit, the current or latest Flow run, no Worker,
committed state only, no locks, and large and hard-delete values.

The Rust call blocks the calling thread, like every other Rust Client method. It
takes a tuple of 1 to 12 reads and returns a tuple of the same size. To read
more values, make several calls. Values from different calls can come from
different commits.

The Attribute primitive example reads a status Attribute, the **payment** instance of a progress AttributeMap, and an email Attribute that the Flow never sets.

**Python**

```python
flow = app_state.attribute
payment_progress = flow.progress.instance("payment")
try:
    values = await app_state.client.get_attributes(
        required_query("workflowId"),
        flow.status,
        payment_progress,
        flow.email,
    )
except FlowNotFoundError as error:
    response = jsonify({"error": str(error)})
    response.status_code = 404
    return response
return jsonify(
    {
        "status": values.get(flow.status, "not started"),
        "paymentProgress": values.get(payment_progress, "not started"),
        # This Flow never sets email, so get returns None.
        "email": values.get(flow.email),
    }
)
```

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

Run the HTTP example from the
[examples playground](https://github.com/superdurable/dex/tree/main/examples/playground).
Its **Read Attributes** endpoint is available in every example server.

<a id="unset-values"></a>

### Unset values

An Attribute or AttributeMap instance without a stored value is unset. Each SDK
represents an unset read in its own way:

| SDK        | Unset read                                                                                                                                                                           |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Go         | The destination keeps its previous value. **AttributeReadResult.IsSet** and **IsMapInstanceSet** return false.                                                                       |
| Python     | The read is absent from the returned **AttributeValues**. **values.get(read, default)** returns the default, **read in values** is false, and **values\[read]** raises **KeyError**. |
| Java       | **AttributeValues.get(read)** returns **Optional.empty()**.                                                                                                                          |
| TypeScript | The tuple element is **undefined**.                                                                                                                                                  |
| Rust       | The tuple element is **None**. Each element is an **Option** of the read's value type.                                                                                               |

In Python and TypeScript, a stored value that decodes to **None** or **null** is
still set. In Java, a stored value that decodes to **null** reads as
**Optional.empty()**, the same as an unset value. An **Optional** cannot hold
**null**.

<a id="read-definitions"></a>

### Definitions

Each read must use a definition that a Flow in the Client's Registry declares.
A definition from any registered Flow works. Dex reads the key by name, and does
not check that the target Flow's type declares it. If the target Flow has a
same-named Attribute with another value type, the value fails to decode.

<a id="read-attributes-errors"></a>

### Errors

- A Flow ID that does not exist, or whose latest Flow run is being purged,
  returns a Flow-not-found error.
- A definition that is not registered in the Client's Registry, or that does not
  match the registered definition, fails before any request. Go, Python, and
  Rust compare the definition with the registered one, including its value type.
  Java and TypeScript require the exact registered definition object.
- These inputs are rejected before any request: an empty or blank Flow ID, no
  reads, two reads of the same value, an empty AttributeMap instance key, or a
  key that contains **/**.
- An AttributeMap passed without an instance is rejected. Python and TypeScript
  raise **TypeError** before any request. Go, Java, and Rust reject it at
  compile time.
- A stored value that cannot be decoded returns a value mapping error.

The SDK doc comments name each error type.

<a id="等待-flow"></a>

<a id="wait-for-a-flow"></a>

## Wait for a Flow

**WaitForFlow** waits for a terminal Flow status. A bounded wait can return a
long-poll timeout while the Flow is still open. Call it again to keep waiting.

Only a COMPLETED Flow returns the outputs of its completing Step decisions. A
Flow that fails, is canceled, is terminated, or times out returns no outputs.
This holds even when a Step gave a completing decision with an output before
another Step or a client closed the Flow. **GetFlowState** and the result that a parent receives from
a child Flow follow the same rule. Changed in 0.1.26: before, such a Flow kept
the outputs collected before it closed.

Give every result a user must see a durable read path: a result Attribute that
a Client reads, or the Flow's output from **WaitForFlow**. Use an Attribute
when the result must survive a failure or be readable while the Flow runs.

<a id="wait-for-a-step"></a>

## Wait for a Step

**WaitForStepCompletion** waits for one **StepExecutionID** to complete while
the Flow continues. It confirms completion but does not return the Step output.
To return a row that a Step writes in an API response, wait for that Step; see
[Step completion](https://docs.superdurable.io/zh-Hans/design-patterns/responsive-update/wait-for-step-completion.md).

<a id="wait-for-an-attribute-match"></a>

## Wait for an Attribute match

**WaitForAttributeMatch** waits until an Attribute satisfies a typed scalar
comparison, and returns the matched current value. It targets the current
active Flow run. For an AttributeMap, also supply the instance.

- String and Boolean values support equal and not-equal.
- Integer and floating-point values also support greater-than,
  greater-than-or-equal, less-than, and less-than-or-equal.
- A missing Attribute never matches.
- The server rejects object, bytes, null, blob-backed, non-finite
  floating-point, cross-type, and invalid ordering comparisons.
- The wait works only while the Flow is active.

Treat a revision Attribute as a watermark: when it changes quickly, the wait
may return only the latest of several changes. See
[Wait for Attribute Match](https://docs.superdurable.io/zh-Hans/design-patterns/responsive-update/wait-for-attribute-match.md)
for the complete revision pattern and its code.

<a id="wait-timeouts-and-limits"></a>

## Wait timeouts and limits

These rules apply to **WaitForStepCompletion**, **WaitForAttributeMatch**, and
Stream long-polls.

A wait returns when its condition holds, the Flow closes, or its timeout
expires, so a returned wait is only a checkpoint. Read the Flow result or the
business state to see what happened.

- **RequestTimeout** is the total time the SDK call may take. The default, 0,
  waits until success, Flow close, or caller cancellation. With a positive
  value, the call returns a typed request-timeout error when it expires. A later
  call waits again from the current state.
- Each Flow allows 1,000 concurrent waits by default. The server setting is
  **limits.maxLongPollWaitersPerFlow**. A wait beyond the limit fails with a
  resource-exhausted error. See [Limits](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#limits).
- A waiting call holds one slot until it returns, times out, is cancelled, or
  the caller disconnects.
- The server caps how long each transport attempt waits. When an attempt hits
  the cap, the SDK reattaches automatically with the same Request ID. The cap
  does not reset **RequestTimeout**.

<a id="查看-flow"></a>

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

## Describe a Flow

**DescribeFlow** reads the IDs, Flow type, status, and start time of the current
or latest Flow run. The Go SDK also returns the close time when available.
DescribeFlow does not wait for the Flow to finish. Use it for a one-off status check, for example
after a read-only RPC returns a non-terminal business state. A missing ID, or an
ID that does not belong to a Flow, returns a typed Flow-not-found error.

<a id="target-one-run"></a>

## Target one run

DescribeFlow, GetAttributes, WaitForFlow, StopFlow, and InvokeRPC take an
optional run ID. Without it, reads and waits address the latest run of the
Flow ID, and StopFlow and InvokeRPC address its active or latest run. With it,
the call addresses that run, even when a newer run of the Flow ID exists. Use
it when a caller tracks one run, such as a parent that claimed a child run.

- **Reads.** DescribeFlow returns that run's status and close time.
  GetAttributes returns the values that run holds; a closed run keeps the
  values it held when it closed.
- **Wait.** WaitForFlow on a run that has already closed returns its result at
  once.
- **Stop.** StopFlow with a run ID never affects a newer run. When that run has
  already closed, it returns **NOT_FOUND** with the Flow-not-found sub-status,
  so the caller can treat the run as already stopped.
- **RPC.** A query-only RPC can read that run while the server retains it. An
  RPC that needs an active run fails when that run is closed, as it does for
  a closed Flow, and never runs on a newer run. Request IDs are recorded per
  run.
- **Errors.** A run that does not exist, belongs to another Flow ID, or is being
  deleted after its retention period returns the call's typed Flow-not-found
  error. A run ID that is not in its canonical 36-character form returns
  **INVALID_ARGUMENT**.

The SDK Clients expose the run ID on all five calls since Go SDK 1.45.17,
Python SDK 1.45.18, Java SDK 1.45.3, TypeScript SDK 1.45.17, and Rust SDK
1.45.9. Earlier SDKs already take it on some RPC calls; see each SDK's API
reference.

<a id="read-open-step-executions"></a>

## Read open Step executions

**GetFlowState** reads the open Step executions of the current or latest Flow
run. It reads committed state once and does not wait.

- Each open Step execution reports its Step type, Step execution ID, and
  whether a WaitFor or Execute call is open or the Step waits for its
  conditions.
- An open call reports its attempt and whether it is pending, running, or
  waiting for its retry backoff.
- While a Step method retries, the open call reports its latest failed
  attempt: the attempt number, the Worker error type, the message, and the
  stack trace when the Worker sent one. A Step that has not failed reports no
  failure.
- A closed run reports no open Step executions.
- A missing Flow returns a typed Flow-not-found error.

Use it to tell a Flow that is still running from one whose active Step keeps
failing and retrying, for example in a test harness.

The TypeScript Client exposes it as **getFlowState** since 1.45.1. Other SDKs
reach it through their generated FlowService client.

<a id="搜索-flow"></a>

<a id="search-flows"></a>

## Search Flows

**SearchFlows** returns one page of Flow runs that match a search query. It
excludes the server's internal Flow runs. To get the next page, pass the
returned page token with the same query. See
[Search backends](https://docs.superdurable.io/zh-Hans/reference/server/search.md) for the query backends.

<a id="skip-a-timer"></a>

## Skip a Timer

**SkipTimer** makes one waiting [Timer](https://docs.superdurable.io/zh-Hans/concepts/primitives/timer.md) ready immediately.
Choose the Step execution, and either the Timer's condition ID or its zero-based
condition index.

The Flow timeout is a Timer too. To fire it early, for example in a test that
keeps the real timeout, skip Step type **sys:timeout_handler**, execution 1,
condition index 0, with no condition ID:

```bash
dexcli flow skip-timer FLOW_ID --step-type sys:timeout_handler --execution 1 --condition-index 0 --yes
```

Skipping it starts the timeout policy now, as if the deadline had passed. The
Go, Python, Java, and TypeScript Clients take the same selector: a Step
execution ID with Step type **sys:timeout_handler** and execution 1, and Timer
index 0. In Rust, `StepExecutionId` is built from a Step instance, so use the
command above. For a running Flow, the call fails with **INVALID_ARGUMENT**
when the Flow has no pending timeout, such as a Flow started without one or
one whose timeout already fired.

<a id="更新-flowconfig"></a>

<a id="update-flowconfig"></a>

## Update FlowConfig

**UpdateFlowConfig** changes the **FlowConfig** of an active Flow. See
[Update FlowConfig with a Client](https://docs.superdurable.io/zh-Hans/reference/python/flow.md#update-flow-config-with-a-client)
for the merge rules and the fields.

<a id="触发-continue-as-new"></a>

<a id="trigger-continue-as-new"></a>

**TriggerContinueAsNew** was removed in server-zd 0.1.26. See the
[change log](https://docs.superdurable.io/zh-Hans/reference/server/changelog.md#v0-1-26).

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

## Flow definitions

Since 0.1.26. The server stores Flow Definition Graph (FDG 2.0) JSON documents
that Workers upload, one document for each Flow type. Dex Web reads them to
render Flows without a definition directory. Three FlowService RPCs serve them.
Any authenticated caller may use them; they are not admin RPCs.

**UploadFlowDefinitions** stores up to 256 documents. Each item names a Flow
type, carries the JSON bytes, and has a **generated_at** time. The request also
carries an **uploader** string of at most 128 bytes, such as the SDK name and
version, for diagnostics. The server decides each item on its own and returns
one outcome for it, in request order:

| Outcome           | When                                                                                                 | Write |
| ----------------- | ---------------------------------------------------------------------------------------------------- | ----- |
| **CREATED**       | No document is stored for the Flow type.                                                             | Yes   |
| **UNCHANGED**     | The stored document has the same SHA-256 digest.                                                     | No    |
| **REPLACED**      | The digest differs, and **generated_at** is strictly later than the stored one, or **force** is set. | Yes   |
| **KEPT_EXISTING** | Otherwise. The result reports the stored digest and **generated_at**.                                | No    |

Times compare at microsecond precision. Restarting a Worker with the same
documents writes nothing. During a rolling deployment, an older Worker that
starts after a newer one keeps the newer graph, because its **generated_at** is
older. Runs that the older code starts then show the newer graph. Set
**force** to replace a stored document whatever its **generated_at**: use it to
roll a definition back on purpose, or to replace a document whose
**generated_at** came from a fast clock. An identical document is still
**UNCHANGED** with **force**.

Concurrent uploads of one Flow type are safe. Each item is written with a
conditional write and decided again when another write wins, so a newer
document is never lost. Items are not atomic as a group: when a call fails with
**UNAVAILABLE** partway, earlier items may already be stored. Repeating the
call is safe.

The server checks only the basics, and Dex Web validates the full graph when
it reads it. Each of these fails the whole request with **INVALID_ARGUMENT**
and the **FLOW_DEFINITION_INVALID** sub-status before anything is stored:

- more than 256 items, or one Flow type twice;
- an empty Flow type, one longer than **matching.maxFlowTypeLength** bytes, or
  one whose percent-encoded object key, with **objectStore.prefix**, would be
  longer than 1024 bytes. The check is conservative: a non-empty prefix counts
  as its length plus one byte with every object store, so a key of exactly
  1024 bytes may be rejected;
- content larger than [**flowDefinitions.maxDefinitionBytes**](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#flow-definitions);
- content that is not a JSON object, nests objects and arrays more than 128
  levels deep, lacks a **schemaVersion** that starts with **2.**, or has a
  **flow\.name** different from the Flow type;
- a missing **generated_at**, one outside the protobuf Timestamp range (years
  1 to 9999), or one more than 24 hours after the server's clock;
- an **uploader** longer than 128 bytes.

The whole request must also fit in **api.grpcMaxMessageBytes**.

**ListFlowDefinitions** returns the Flow types that have a stored document,
names only, one page at a time. A page holds at most **page_size** names; 0 and
values above 1000 mean 1000. Pass the returned page token to read the next
page; an empty token means the last page. Tokens are opaque. Pages follow the
order of the stored object keys, which is stable but not exactly the order of
Flow types. Objects under the prefix that the server did not write are skipped,
so a page can hold fewer names than **page_size**, even none, and still have a
next page.

**GetFlowDefinitions** returns the stored documents of up to 256 Flow types,
with the digest, **generated_at**, upload time, and uploader of each. The
content is byte for byte what was uploaded. A Flow type without a stored
document is left out. The server reads the documents one at a time and never
reads more than fits in one **api.grpcMaxMessageBytes** response. When they
would not fit, the call fails with **RESOURCE_EXHAUSTED** and the
**FLOW_DEFINITION_RESPONSE_TOO_LARGE** sub-status; request fewer Flow types.

The server keeps each document in its own object under
**PREFIX/registry/flow-definitions/**, so the documents use no server memory
between calls. See
[Object storage layout](https://docs.superdurable.io/zh-Hans/reference/server/object-storage.md#flow-definitions).
There is no delete operation yet. A failure to read or write object storage
returns **UNAVAILABLE**. A stored object that does not decode, names another
Flow type, or has a digest that does not match its content fails Upload and
Get for that Flow type with **INTERNAL**. A stored object larger than
**api.grpcMaxMessageBytes** fails Upload with **INTERNAL**, and fails Get with
**RESOURCE_EXHAUSTED** and the **FLOW_DEFINITION_RESPONSE_TOO_LARGE**
sub-status. In [request metrics](https://docs.superdurable.io/zh-Hans/reference/server/metrics.md),
uploads count as **flow_write**, and lists and gets as **flow_read**.

<a id="time-travel"></a>

## Time travel

Time travel creates a new attempt of a Flow run from a point in its history.
The FlowService call is **ResetFlow**; the docs call it Time Travel. The Flow
run keeps its Run ID. It restores the run's state at the target point: its
Attributes, its Channel messages, and the Steps that were waiting or ready. The point must be inside the
[recent history window](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#history-window);
otherwise the call fails with **FAILED_PRECONDITION**. Time travel to the
beginning is always available.

**reset_type** selects the target point: the beginning, a history event time, a
Step type, a Step execution, or an event ID. Since 0.1.33,
**FLOW_RESET_TYPE_EVENT_ID** takes **event_id**, the **event_id** of an event
that **GetHistoryEvents** returns. The target is the first point at or after
that event where time travel can stop, as for a history event time. Time travel
stops only after events that change Flow progress, never inside a Step attempt.
The event must belong to the history of the selected **run_attempt**, which
includes the attempts it started from, and must be inside the window. An event
of an abandoned attempt, or one the window pruned, fails with
**FAILED_PRECONDITION**. An **event_id** of zero or less fails with
**INVALID_ARGUMENT**.

The Flow timeout restarts at the time travel, as if the run started then. When
the restored state still waits for the timeout, the new attempt times out after
the run's full Flow timeout, counted from the time travel. When the timeout had
already fired at the target point, the restored state keeps that outcome, such
as a running timeout handler. Changed in 0.1.33: before, the restored timeout
kept the original deadline from the run's start, so it could fire right after
the time travel.

By default, the window keeps about the newest 50,000 history events of each
run on **serve**, and 5,000 on **dev**. The server key is
**history.windowEvents**, and a Flow can set its own size in its Flow
configuration.

Write reapply is on by default. It applies again the RPC calls, Channel
publications, and Attribute writes that reached the run after the target point.
While it is on, **ResetFlow** keeps those writes in memory, to apply them again. Memory grows with the number and size of
those writes. A long Flow run with large values can exceed the replay budget
even when the target state is small. The request then fails with
**RESOURCE_EXHAUSTED** and changes nothing. Set **skip_writes_reapply** to
**true** (`dexcli flow time-travel -skip-writes-reapply`) if those writes should not be applied again. Or raise
[**history.timeTravelReplayMemoryBytes**](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#history-checkpoints)
and restart the node before you retry.

When the restored point is in a [pending close](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#pending-close), write reapply
skips each RPC whose result publishes to a Channel, with all of its writes.
Changed in 0.1.38: before, it applied that RPC again.

<a id="sub-flows-across-a-time-travel"></a>

### SubFlows across a time travel

Since 0.1.33. A time travel can restore a Step whose `WaitFor` waits on SubFlow
conditions. The `sub_flow_reset_policy` field of `ResetFlowRequest` decides
what happens to each such condition. Each condition names the child Flow that
its Step started.

The policy can attach the condition to its child. When the child run has ended,
its result completes the condition. This holds even when the parent has not
received that result yet: the time travel reads the result from the child run.
When the child run still runs, the condition keeps waiting for it. A child
cannot be attached when the parent has no result and the child run no longer
exists, for example because it was purged after its retention.
When the child Flows a time travel reads keep changing while it computes,
`ResetFlow` fails with `ABORTED`, and the caller may retry the same request.

The values are:

- `SUB_FLOW_RESET_POLICY_UNSPECIFIED`: the default. For `ResetFlow` it means
  `SUB_FLOW_RESET_POLICY_ATTACH_ELSE_RESTART`.
- `SUB_FLOW_RESET_POLICY_ALWAYS_RESTART`: restarts every child, whether it
  ended or still runs.
- `SUB_FLOW_RESET_POLICY_ALWAYS_FAIL`: fails every condition, whether its
  child ended or still runs.
- `SUB_FLOW_RESET_POLICY_ALWAYS_REJECT`: rejects the time travel when any
  restored Step waits on a SubFlow condition.
- `SUB_FLOW_RESET_POLICY_ATTACH_ELSE_RESTART`: attaches each condition, and
  restarts a child that cannot be attached.
- `SUB_FLOW_RESET_POLICY_ATTACH_ELSE_FAIL`: attaches each condition, and fails
  a condition whose child cannot be attached.
- `SUB_FLOW_RESET_POLICY_ATTACH_ELSE_REJECT`: attaches each condition, and
  rejects the time travel when a child cannot be attached.

A restart starts the child again with the start it received: its Flow type,
starting Step, input, and options. The child keeps its Flow ID. A child run
that still runs is terminated first. The restored condition then accepts only
the restarted run's result, so a late result of the earlier run is ignored. The
time travel reads the original start from the child run. When that run no
longer exists, or its start wrote hard-delete Attributes, the child cannot be
restarted and the time travel is rejected. Under `ResetFlow`, a child that cannot
be attached is always gone, so `SUB_FLOW_RESET_POLICY_ATTACH_ELSE_RESTART`
rejects it.

A failure terminates the child run when it may still run. The condition then
completes with a `FAILED` child result whose error type is
`FLOW_ERROR_TYPE_SUB_FLOW_ABANDONED`. The Step's `Execute` receives it like any
failed child.

A restart or a failure needs the child's start to have reached the child. While
the start is still on its way, the time travel is rejected, so no child starts
after its condition was abandoned. Retry the time travel a moment later. An
attaching policy keeps waiting for such a child instead.

A rejection returns `FAILED_PRECONDITION` and changes nothing. Its message
names each Step execution and child Flow ID that caused it. An unknown policy
value fails with `INVALID_ARGUMENT`.

Changed in 0.1.33: a restored condition whose child run no longer exists used to
wait forever. The default policy now rejects the time travel with
`FAILED_PRECONDITION` instead. A condition whose child still runs keeps
waiting for it, as before. A condition whose child ended still completes with
that child's result. When the parent had not received the result yet, the
condition now completes at the time travel instead of when the result arrives.

<a id="clone-fork"></a>

## Clone fork

Since 0.1.33. **CloneForkFlow** creates a new Flow whose first run starts from a
copy of another Flow run's state at one point. The call only reads the source
run, so the source never changes; a running source keeps running. A typical use is an agent session that branches into a new
session while the old session continues. The call requires Server protocol
version 6.

**source_flow_id** and **source_run_id** name the source run. An empty
**source_run_id** selects the latest run. **flow_id** is the new Flow ID. It
must differ from **source_flow_id**; to return a Flow to an earlier point, use
time travel. **request_id** is required.

<a id="clone-fork-points"></a>

### Point selection

**point_type** selects the copied point. The default,
**FLOW_CLONE_FORK_POINT_TYPE_CURRENT**, copies the latest committed state of the
source run's current run attempt. The other types select a point as the time
travel types of the same name do: **BEGINNING**, **HISTORY_EVENT_TIME**,
**STEP_TYPE**, **STEP_EXECUTION_ID** with **step_method**, and **EVENT_ID**.
For them, **run_attempt** selects the attempt whose history holds the point, and
the point must be inside the source run's
[history window](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#history-window). The
beginning is always available.

The source run may be closed. The state at the point must be **RUNNING**,
without a pending close or a requested graceful completion. Otherwise the call
fails with **FAILED_PRECONDITION**; select an earlier point.

<a id="clone-fork-copies"></a>

### What the new run copies

The new run copies the state at the point:

- its Attributes, except hard-delete Attributes;
- its pending Channel messages, Step executions, Step counters, and waits;
- the Step timers, which keep their fire times;
- every value that this state holds, including values that history offload
  moved to object storage.

Hard-delete Attributes are the exception to the point: the new run gets the
source run's current hard-delete Attributes, as a time travel keeps them. It
receives each current value, including a value written after the point, and
lacks each hard-delete Attribute that is unset now, even one set at the point.
The new run stores these values in objects of its own.

The new run keeps every copied value for its whole life. A time travel of the
new run to its beginning therefore returns to the copied point. Steps that were
running at the point are dispatched again with the same attempt number,
snapshot, and locks, and their retry total duration restarts.

The new run starts at run attempt 1, with the source run's Flow type and
FlowConfig. Its history starts with one **FlowStartedOrContinued** event. The
event's **clone_fork_source** names the source run, its run attempt, and the
last source event that the point includes. The response returns the same
source fields.

The new run leaves out the source run's history, Stream messages, outbox
messages, and the request IDs that deduplicate RPCs and Channel publications. It
has no parent Flow and no sticky Worker. The source run's input after the point,
such as RPCs, Channel publications, and Attribute writes, is not applied. The
one exception is hard-delete Attributes, which take their current values as
described above.

**attributes** are written after the copy, in the same change that creates the
run. **flow_config_override** changes the copied FlowConfig, as a StartFlow
override changes the server default. An empty **worker_target.task_queue** keeps
the source run's task queue. Set a task queue of its own when Workers choose
their Flows by task queue, such as the task queue of an agent session.
Otherwise the source's Workers also run the new run's Steps. Limits and other
run settings come from the server configuration, as for StartFlow.

<a id="clone-fork-flow-timeout"></a>

### Flow timeout

The Flow timeout restarts at the clone fork. **flow_timeout_seconds** sets its
duration. Zero keeps the source run's duration, and a source run without a Flow
timeout gives a new run without one. When the source run's timeout had already
fired at the point, the new run keeps that outcome, such as a running timeout
handler. A positive **flow_timeout_seconds** then fails with
**FAILED_PRECONDITION**.

<a id="clone-fork-id-reuse"></a>

### ID reuse and retries

**id_reuse_policy** and **flow_already_started_options** decide on the new Flow
ID as they do for StartFlow, in the same change that creates the run. A
conflict fails with **ALREADY_EXISTS** and the **FLOW_ALREADY_STARTED**
sub-status. **ID_REUSE_POLICY_ALLOW_TERMINATE_IF_RUNNING** terminates a running
latest run with the reason
"terminated by CloneForkFlow with ALLOW_TERMINATE_IF_RUNNING".

A request whose **request_id** started the latest run of **flow_id** is a
retry. The server copies nothing again, and **flow_already_started_options**
decides whether the retry returns that run or fails with **ALREADY_EXISTS**.

<a id="sub-flows-across-a-clone-fork"></a>

### SubFlows across a clone fork

**sub_flow_reset_policy** decides what happens to each SubFlow condition that a
copied Step waits on. It takes the values of
[SubFlows across a time travel](https://docs.superdurable.io/zh-Hans/reference/server/client-apis.md#sub-flows-across-a-time-travel), and its
default is also **SUB_FLOW_RESET_POLICY_ATTACH_ELSE_RESTART**. The source run's
children report only to the source run, so the policies act as follows:

- A child that ended attaches. Its result completes the copied condition, read
  from the source run or from the child run.
- A child that still runs cannot be attached, and neither can a child whose
  start has not reached it yet. The policy's second action applies.
- A restart starts a new child whose Flow ID derives from the new Flow ID, with
  the start that the source run's child received. While that start is still on
  its way to the source run's child, a restart is rejected. Retry a moment
  later.
- A failure completes the condition with a **FAILED** child result whose error
  type is **FLOW_ERROR_TYPE_SUB_FLOW_ABANDONED**. It terminates no child, and
  it applies at once, even while the child's start is on its way.
- A rejection fails the call with **FAILED_PRECONDITION** and names each Step
  execution and child Flow ID.

The source run's children never change.

<a id="clone-fork-errors"></a>

### Errors and limits

| Status                  | When                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **NOT_FOUND**           | The source Flow or run does not exist, or is being purged.                                                                                                                                                                                                                                                                                                                                                                      |
| **INVALID_ARGUMENT**    | **flow_id** equals **source_flow_id**, a required field is empty, or a field does not fit the point type.                                                                                                                                                                                                                                                                                                                       |
| **FAILED_PRECONDITION** | The point is outside the history window or does not exist, its state is not RUNNING, the SubFlow reset policy rejects a copied wait, a copied value is no longer stored, or the timeout rule above rejects the request.                                                                                                                                                                                                         |
| **ALREADY_EXISTS**      | The ID reuse policy rejects the new run.                                                                                                                                                                                                                                                                                                                                                                                        |
| **RESOURCE_EXHAUSTED**  | The copied state exceeds [**limits.maxFlowStateBytes**](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#flow-state-budget), the computation needs more than [**history.timeTravelReplayMemoryBytes**](https://docs.superdurable.io/zh-Hans/reference/server/configuration.md#history-checkpoints), or the new Flow's partition already holds 64 clone forks in progress or 4 GiB of their staged copies. |
| **ABORTED**             | The staged copy expired or was replaced several times in a row, or the child Flows the call reads kept changing while it computed. Retry with the same **request_id**.                                                                                                                                                                                                                                                          |

The server stages the copy on the new Flow's partition in chunks of about
8 MiB before it creates the run. A staging that no chunk extends for 10 minutes
expires. The stagings in progress on one partition hold at most 4 GiB, about 64
copies at the default **limits.maxFlowStateBytes** of 64 MiB. The cap is fixed,
so a larger **limits.maxFlowStateBytes** leaves room for fewer copies at once.
