---
title: "Cross-tree (multi-tree) atomic writes - Atomic Multi-Key Writes"
url: "https://nsta1.github.io/Orleans.Lattice/docs/lattice/atomic-writes/cross-tree-multi-tree-atomic-writes.html"
source: "https://github.com/NSTA1/Orleans.Lattice/blob/release/10.5/docs/lattice/atomic-writes.md?plain=1#L1425-L1806"
agent_spec: "https://nsta1.github.io/Orleans.Lattice/docs/agents/invariants.yaml"
package: "Orleans.Lattice"
version: "10.5.0"
documents: "Orleans.Lattice 10.5.0 (release line 10.5)"
built: "2026-12-05"
all-pages: "https://nsta1.github.io/Orleans.Lattice/llms.txt"
bundle: "https://nsta1.github.io/Orleans.Lattice/docs/lattice/llms-full.txt"
---
# Cross-tree (multi-tree) atomic writes

Part of [Atomic Multi-Key Writes](../atomic-writes.md).

`SetManyAtomicAsync` is bound to a single tree. To commit a batch through
the cross-tree coordinator - typically because it spans distinct `ILattice`
trees all-or-nothing - use the `IGrainFactory.SetManyAtomicAsync` extension
(or the `BeginAtomicWrite` fluent builder). The cross-tree primitive extends the
same atomic-visibility guarantee the single-tree saga gives *within* a
tree to a set of trees: either every targeted key across every
participating tree becomes visible, or none of them do - observed
atomically by readers on the local cluster and on every cluster the
trees replicate to.

## Public surface

| Member | Purpose |
|---|---|
| `IGrainFactory.SetManyAtomicAsync(IReadOnlyList<LatticeTreeBatch>, operationId, ct)` | Commit per-tree slices atomically; returns a `CrossTreeAtomicWriteOutcome`. |
| `IGrainFactory.BeginAtomicWrite(operationId)` | Open a `LatticeAtomicWriteBuilder` for fluent, per-tree staging. |
| `LatticeAtomicWriteBuilder.ForTree(treeId)` | Select (creating if needed) the tree that subsequent staging calls target; re-selecting a tree continues its slice. |
| `LatticeAtomicWriteBuilder.Set(key, value)` / `Set<T>(key, value[, serializer])` | Stage a raw, or serialized (System.Text.Json by default), value write under the current tree. |
| `LatticeAtomicWriteBuilder.SetWhere<T>(key, value, predicate[, serializer])` | Stage a value write under the current tree's guard predicate, evaluated once server-side against the pre-saga value of every key in that tree's slice; a tree carries at most one predicate. |
| `LatticeAtomicWriteBuilder.Set(LatticeStagedCrdtWrite)` / `SetMany(IEnumerable<LatticeStagedCrdtWrite>)` | Couple one or more staged CRDT mutations into the write (see [Coupling a CRDT mutation into an atomic write](#coupling-a-crdt-mutation-into-an-atomic-write)). |
| `LatticeAtomicWriteBuilder.Delete(key)` | Stage a retraction (tombstone) for `key` under the current `ForTree(...)`; rides the saga and flips jointly with sibling `Set` calls. |
| `LatticeAtomicWriteBuilder.CommitAsync(ct)` | Commit every staged slice through `IGrainFactory.SetManyAtomicAsync`; returns a `CrossTreeAtomicWriteOutcome`. |
| `LatticeTreeBatch(TreeId, Entries, Predicate = null, EntryDeltas = null, EntryDeletes = null)` | One tree's slice: tree id, key/value entries, optional server-side guard predicate, optional per-entry CRDT deltas, and an optional parallel per-entry is-delete channel (a `true` slot tombstones its key). |
| `CrossTreeAtomicWriteOutcome` | `Committed` (all trees committed) or `PreconditionFailed` (a guard failed; nothing committed anywhere). |

A stable `operationId` is **required** (there is no auto-generated
overload): a cross-tree saga touches multiple registries, so a stable
idempotency key is mandatory for safe retry. The `operationId` must not
contain `/` (reserved as the grain-key separator). Tree ids in the batch
must be distinct and non-empty, and each tree's slice must not repeat a
key - staging a `Set` and a `Delete` for the same key counts as a repeat.
A batch that breaks either rule throws `ArgumentException` before any
write is staged or any saga state is persisted, so the `operationId`
stays free for a corrected retry. Each participating tree's write bounds
are applied up front as well, against that tree's own options, before
anything is staged or persisted: a key longer than its tree's
[`MaxKeyLength`](../configuration/options-reference-2.md#maxkeylength) - a delete key included -
or an upsert value larger than its
[`MaxValueSizeBytes`](../configuration/options-reference-2.md#maxvaluesizebytes) fails with
`ArgumentException`, and a tree whose slice carries an upsert while that
tree is at an enforcing [`MaxLiveKeys`](../configuration/options-reference-2.md#maxlivekeys) or
[`MaxEstimatedBytes`](../configuration/options-reference-2.md#maxestimatedbytes) cap fails the
whole write with `LatticeQuotaExceededException`. The caps are a
best-effort check against the tree's cached footprint that lets the write
through when the footprint cannot be read, and a slice that only deletes
skips them. The checks run on a fresh submission only: a re-submission
that re-attaches to a cross-tree write already under way is not checked
again.

The cross-tree coordinator also runs any registered write interceptor
(schema enforcement and schema versioning) before the saga is dispatched.
It applies the interceptor to each tree's plain whole-value upserts with
`atomic: true`, so a rejected or dead-lettered value aborts the whole
cross-tree commit before any participating tree is mutated, and an
accepted transformed value is substituted into that tree's slice. Tombstone
deletes and staged CRDT-delta entries do not carry a whole value for this
pass, so they are not schema-checked by the coordinator.

## Usage

```csharp verify
// Fluent builder: atomically move an order between two trees, only if
// the source order's total still clears a threshold.
var outcome = await grainFactory
    .BeginAtomicWrite("xfer:txn-1001")
    .ForTree("orders-east")
        .SetWhere("order:42", new Order("42", 0m), o => o.Total >= 100m)
    .ForTree("orders-west")
        .Set("order:42", new Order("42", 250m))
    .CommitAsync(cancellationToken);

if (outcome == CrossTreeAtomicWriteOutcome.PreconditionFailed)
{
    // The guard failed; nothing was committed on either tree.
}
```

```csharp verify
// Mixed set + delete across trees: move a row from one tree's key to
// another's, retracting the old key inside the same cross-tree saga.
await grainFactory
    .BeginAtomicWrite("rekey:order-42")
    .ForTree("orders-east")
        .Delete("order:42")
    .ForTree("orders-west")
        .Set("order:42", new Order("42", 250m))
    .CommitAsync(cancellationToken);
```

```csharp verify
// Explicit batch list form.
var batches = new List<LatticeTreeBatch>
{
    new("orders", new List<KeyValuePair<string, byte[]>>
    {
        new("order:42/status", Encoding.UTF8.GetBytes("shipped")),
    }),
    new("inventory", new List<KeyValuePair<string, byte[]>>
    {
        new("sku:99/reserved", Encoding.UTF8.GetBytes("0")),
    }),
};

CrossTreeAtomicWriteOutcome result =
    await grainFactory.SetManyAtomicAsync(batches, "fulfil:order-42", cancellationToken);
```

## Coupling a CRDT mutation into an atomic write

A staged CRDT write lets a typed CRDT mutation ride a cross-tree atomic
write so it commits all-or-nothing alongside sibling last-writer-wins
(LWW) writes on other trees.

The `GCounter`, `GSet`, `PnCounter`, `OrSet`, `OrFlag`, `RwFlag`,
`MvRegister`, `Rga`, and `VersionVector` accessors expose a `Stage*`
counterpart for each of their live mutators other than `MergeAsync` (for
example `StageIncrementAsync`, `StageAddAsync`, `StageTickAsync`); the
`OrMap`, `RwSet`, `MaxRegister`, and `MinRegister` accessors expose none.
A `Stage*` call:

1. reads the key's current snapshot once,
2. mints the typed CRDT delta **once** (the same dot-minting logic the
   live mutator uses),
3. folds the delta into the snapshot to produce the merged state, and
4. returns a `LatticeStagedCrdtWrite` carrying the key, the serialized
   merged state (the **value**), and the serialized typed delta.

It performs **no** durable write - the saga owns the commit. Hand the
token to the builder's `Set(LatticeStagedCrdtWrite)` overload under the
`ForTree(...)` whose configured merge mode matches the accessor's
primitive (the accessor was obtained from that same tree).

```csharp verify
// Stage a PnCounter increment from a CRDT-mode tree's accessor. Staging
// mints the typed delta once and folds it into a merged snapshot; it does
// not write durably - the saga owns the commit.
var metrics = grainFactory.GetGrain<ILattice>("metrics");
LatticeStagedCrdtWrite staged =
    await metrics.PnCounter("orders:placed")
                 .StageIncrementAsync("replica-east", 1, cancellationToken);

// Couple the staged CRDT mutation with a sibling LWW Set on another tree.
// Either both land or neither does.
var outcome = await grainFactory
    .BeginAtomicWrite("place-order:1001")
    .ForTree("metrics").Set(staged)
    .ForTree("orders").Set("order:1001", new Order("1001", 250m))
    .CommitAsync(cancellationToken);

if (outcome == CrossTreeAtomicWriteOutcome.Committed)
{
    // The merged counter value is readable locally right away.
}
```

**Convergence and consistency contract.** The merged value stored by the
saga is computed from a stage-time snapshot and stored LWW by HLC. Reads
on the authoring cluster see that merged value immediately, and it
replicates to every peer through the cross-tree saga's prepared /
terminal path. A single authoring cluster's staged CRDT write therefore
converges everywhere on its merged value.

Two concurrent staged CRDT writes to the **same key** - whether in the
same cluster or on different clusters - converge by the **per-replica
typed-delta union**, identical to the live (non-atomic) accessor path.
The cross-tree atomic write ships the staged typed delta and merge mode
alongside the merged-state value on the two-phase prepared / terminal
replication path, and the receiver **folds the typed delta into its
current visible state** (the primitive's `MergeDelta`) on the saga's
terminal commit rather than installing the prepared value
last-writer-wins. So a counter written `+5` on one cluster and `+3` on
another converges to `8` on **both** clusters, exactly as the live
`IncrementAsync` accessor would. The same holds for the internal
tag-index flag-membership rows, which use the same per-entry carry: an
active-active membership add on each cluster converges to the union
through the atomic (prepared) path, not only the eventual accessor path.

A key whose committed value reaches a leaf as a cross-migration backstop
(a leaf split moved the key away between the prepare and the terminal, or
the saga's coordinator re-delivers committed values to a leaf that holds no
prepared bucket for it) has no delta to fold there. On a tree whose merge
mode resolves to a CRDT, that leaf **joins** the staged merged state into
the key's current state through the primitive's state merge and stores the
result at a stamp above the row, durably, so a mutation acknowledged on the
key after the stage-time snapshot survives the terminal. The join keeps
exactly what the delta fold keeps: both are pointwise per replica (or per
dot), so concurrent writes from different replicas accumulate (issue
[#4611](https://github.com/NSTA1/Orleans.Lattice/issues/4611)).

Value-only sagas - a plain `Set(key, bytes)` slice with no staged CRDT
delta - stay on the last-writer-wins prepared path unchanged: the highest
HLC wins, because there is no typed delta to fold.

**Compensation.** An aborting saga drops the staged value **and** the
staged delta on every cluster (the prepare-phase write never became
visible), so there is no byte-inverse compensation: abort means the
mutation never happened.

## How it works - two-level saga

A single **coordinator grain** keyed by `operationId` is the global
decision authority. The flow is:

1. **Prepare-and-pause.** Each participating tree runs the existing
   single-tree saga in a new prepare-and-pause mode: it stages the
   prepared writes into the per-leaf pending-tx buckets, registers a
   *delegation* mapping its local txid to the coordinator, then pauses
   without broadcasting any terminal. Each tree votes prepared,
   precondition-failed (its guard missed), or failed. A failed vote
   normally means its staging failed and it aborted itself, but a tree
   whose batched dispatch is refused for saturation or shutdown, or whose
   saga state write fails with a fault other than a conflict, also votes
   failed and keeps its prepared writes staged rather than aborting. A
   tree that throws instead of voting - a transient routing or storage
   fault before its writes are staged, an admission refusal, a
   state-write conflict, or a retryable failure of the park step itself,
   with its prepared writes still staged - casts no vote: the coordinator stays in its preparing
   phase and the call surfaces the fault. The coordinator's keepalive
   reminder, or a re-submission under the same `operationId`, then
   re-dispatches prepare to every tree, and a tree that already staged
   its writes re-parks and votes prepared.
2. **Single global decision.** Once every tree has voted, the
   coordinator writes **one** decision - commit only if every tree voted
   prepared, otherwise abort - to its own persistent state. This single
   write is the cross-tree linearization point.
3. **Finalize.** The coordinator fans out a finalize call to every
   tree whose saga voted prepared (a tree whose guard missed, or whose
   staging failed and it aborted itself, has already terminated; a tree
   that voted failed with its writes still staged is not finalized
   either), which marks its
   per-tree registry and broadcasts the per-shard terminals exactly as
   the single-tree saga does.

Between prepare and the coordinator's decision, every participating
tree's registry *delegates* the status of its prepared txid to the
coordinator. A reader dialling a per-tree registry (a single-txid,
multi-txid, or snapshot status read) for a
delegated txid resolves it against the coordinator and caches the
terminal verdict locally. Before the coordinator decides, every
delegated read returns `InFlight`, so the prepared keys are invisible
(indistinguishable from pre-saga); after it decides, every tree returns
the **same** global verdict. The global visibility flip is therefore the
coordinator's single decision write, applied uniformly across all trees.

If the dial to the coordinator itself fails, the per-tree registry
answers `Indeterminate` rather than `InFlight`: it has no evidence
about the verdict, so it declines to answer instead of asserting
"not committed". The prepared keys are then *hidden* rather than
resolved to their pre-saga values, and resolve normally as soon as the
coordinator is reachable again. See
[After the retention window](how-it-works.md#after-the-retention-window-indeterminate-not-inflight).

## Cross-cluster cross-tree visibility (receiver barrier)

The authoring-cluster flip above is a *single* write, but each
participating tree's terminals replicate to remote clusters on their
**own** per-tree WAL feed. A receiver can therefore apply tree A's
terminal long before tree B's terminal arrives. Without a receiver-side
barrier a remote reader could observe tree A committed while tree B is
still pre-saga - a partial cross-tree view the authoring cluster never
exposes.

The receiver closes this gap with an internal **receiver coordinator
grain**, distinct from the
authoring-side coordinator and keyed by the compound
`(originClusterId, operationId)`. Each tree's cross-tree terminal carries
the operation id and the participant tree-set (`WalRecord`'s
`CrossTreeOperationId` / `CrossTreeParticipants`). When a tree's per-shard
gate completes on the receiver, instead of flipping that tree's registry
immediately the receiver:

1. durably registers the tree's local txid as **delegated to the receiver
   coordinator** in the per-tree registry, then
2. notifies the receiver coordinator that this tree's terminal has
   arrived (with its commit/abort vote).

The receiver coordinator holds a frozen **wait set** of the trees it must
hear from and decides only once a terminal has arrived for every tree in
the set; the global verdict is `Committed` iff every arrived terminal
voted commit. Before the coordinator decides, a delegated read on any
participating tree's registry dials the receiver coordinator and resolves
`InFlight` - so every tree stays invisible (an unreachable receiver
coordinator resolves `Indeterminate`, which also keeps the keys hidden).
After it decides, every tree
resolves the same verdict and the receiver flips them **together**,
mirroring the authoring cluster's single-write flip. The coordinator only
ever *returns* the decision (it never calls back into a tree grain), so
the calling tree router performs the per-tree finalizes - itself inline
and siblings via their apply grains - without any circular wait.

**Partial replication is valid.** The wait set is scoped to the trees
actually replicated on the receiver: it is the intersection of the
batch's participant set with the receiver's configured replicated trees
(`LatticeReplicationOptions.ReplicatedTrees`). The tree that received the
terminal is always in the set. A participating tree that is **not**
replicated on this receiver is simply excluded, so a cross-tree batch
spanning a mix of replicated and non-replicated trees completes its
barrier on the present subset rather than blocking forever on a tree that
will never arrive. The set is fixed when the first terminal freezes it: a
later terminal computed under a changed replication configuration does not
change it, and a tree whose terminal arrives after it became replicated
joins it (issue #4692). A participant that stops being replicated here
before its terminal arrives is removed from an undecided barrier, which then
decides on the trees that remain - or, when none remain, clears to unopened
rather than deciding over no arrivals (issue #4741). The receiver thus preserves cross-tree atomic
visibility across exactly the trees it hosts, whatever subset of the
batch that is.

## Guarantees and non-guarantees

- **All-or-nothing commit across trees.** On a `Committed` outcome every
  key on every participating tree holds its target value; on
  `PreconditionFailed` nothing is committed on any tree. A mid-flight
  write failure compensates every tree and throws
  `InvalidOperationException`.
- **Refused while a cross-tree-consistent backup set is captured.** A
  cross-tree-consistent backup set fences the saga decision registry of
  every member tree while it captures (see
  [Backup architecture](../../lattice.backup/architecture.md#backup-set-and-the-cross-tree-fence)).
  A cross-tree write that tries to start on a fenced tree is refused, not
  retried or queued: it is compensated on every tree and throws
  `InvalidOperationException`, and the caller retries it once the capture
  completes. This applies to every tree of the write that had not yet
  registered when the fence went up; a write that had already registered on
  every tree finishes normally, and the capture waits for it. Single-tree writes and atomic batches are never
  refused by a capture: a batch whose commit or abort decision falls
  inside any snapshot capture of its tree waits for the capture to
  release the tree's saga decision gate (issue #4485).
- **Crash recovery.** The coordinator grain drives the saga to a
  terminal state via a keepalive reminder if its silo crashes mid-flight,
  exactly as the single-tree saga does.
- **Participating trees must agree on cluster identity.** The protocol
  repeatedly carries a guard verdict reached on one participating tree
  across the tree boundary to another, and that step is sound only when
  the two trees resolve the same origin cluster id. Because
  `LatticeReplicationOptions.ClusterId` is a *per-tree* named option, no
  options validator can check the relation - it is handed one tree's
  options at a time. The check therefore runs where a participant set
  first exists: at the coordinator's admission of a cross-tree write, and
  at the replicated cross-tree barrier's wait-set freeze on the receiver.
  A disagreement throws `InvalidOperationException` naming both trees and
  their resolved ids. At the coordinator this happens before anything is
  staged, persisted, or dispatched, so the rejected write leaves no state
  behind. On a receiver it happens only after the tree's registry has
  recorded the terminal's arrival and persisted a delegation of the saga
  to the barrier, which records nothing; the delegation remains, so reads
  on that tree resolve to in flight and see pre-saga values, the
  replicated prepared writes stay pending, and each redelivery of the
  terminal fails the same check. The check is on *agreement*,
  not on any particular value, so a host that never configured replication
  (uniform empty cluster id) always passes; a tree whose slice of the batch
  is empty is dropped from the participant set before the check. It is not
  re-run on a resumed saga, whose participants already have writes staged
  and must still be driven to a terminal decision. Configure `ClusterId`
  cluster-wide (`AddLatticeReplication` does) and avoid per-tree overrides
  on trees you span in one cross-tree write.
- **Idempotent retry.** Re-submitting the same `operationId` with the
  same tree-set and key-set re-attaches to the in-flight (or completed)
  saga and returns its memoized outcome. Re-submitting the same
  `operationId` with a *different* tree-set or key-set throws
  `LatticeIdempotencyKeyMismatchException`.
- **Atomicity, not cross-tree read isolation.** The guarantee is
  all-or-nothing *commit* of the write, anchored to the coordinator's single
  decision write as one global linearization point: at any single instant the
  saga is either undecided (no tree reports a verdict - `InFlight`, or
  `Indeterminate` if a tree cannot reach the coordinator) or decided (every
  tree returns the same verdict), never durably half-applied. It is **not** a
  cross-tree read snapshot: Lattice has no read operation spanning trees, so a
  reader issuing *separate* per-tree reads at *different* instants that
  straddle the linearization point may legitimately compose a mixed view (one
  tree's pre-saga value, another tree's post-saga value), exactly as two
  independent `SELECT`s under read-committed isolation can. What it can never
  observe is a single tree showing a *partial* slice of one cross-tree saga:
  within any one read, every saga key on that tree resolves against one global
  verdict.

The cross-tree workload is exercised under concurrent shard splits in
the chaos suite - see
[Chaos Tests: Test 11](../chaos-tests.md#test-11---cross-tree-atomic-write-under-shard-churn-chaoscrosstreeatomicwriteintegrationtests).

Previous: [Cross-cluster atomic visibility](cross-cluster-atomic-visibility.md). Contents: [Atomic Multi-Key Writes](../atomic-writes.md).
