WAL grain API
This page is part of the documentation for Orleans.Lattice 10.5.0 (release line 10.5), built 2026-12-05. It is also published as markdown, with every table and list, at wal-grain-api.md, and llms.txt lists every page.Part of Write-Ahead Log.
Each WAL partition is owned by an internal grain keyed
{treeId}/{partition} where partition is a stable FNV-1a hash of the key
reduced modulo the tree's pinned LatticeOptions.WalPartitions (default 8). The grain is internal to the core and is the single producer-side
entry point for foreground commits and the read-back source for the
replication change feed. Its operations, described by behaviour:
| Operation | Behaviour |
|---|---|
| Single append | Appends one captured WalRecord and returns the dense per-partition offset assigned to it. |
| Batch append | Appends a contiguous batch of captured records under a single grain hop and returns the dense per-input offsets in input order (the offset at position i is the one assigned to the record at position i). An empty batch returns an empty list and performs no provider work. The whole batch coalesces into one provider flush when under WalMaxBatchEntries / WalMaxBatchBytes; an over-budget batch cuts over across multiple flushes using the same in-flight cap as the single append. |
| Page read | Reads a contiguous page from a starting offset, clamped to the durable gap-free prefix: no offset above a lower offset whose flush is still in flight, or whose abandoned flush may still land, is returned, so a cursor-advancing reader never skips a prefix hole a write can still fill. Returns the entries and the offset to resume from. A negative starting offset or a page size below one is refused with ArgumentOutOfRangeException; a read at or beyond the durable prefix returns an empty page that resumes from the requested offset. |
| Filtered replay read | The leaf replay read (issue #3565). Examines at most the requested number of entries of an inclusive offset window, clamped like the page read to the durable gap-free prefix, and returns those the reader's WalKeyFilter does not exclude, plus the last examined entry routing-only (key and kind, no payload) when it is excluded. The resume offset therefore still moves past everything examined, and an empty page still means an empty window. The grain re-applies the rule to whatever the storage provider yields, so no excluded payload crosses the grain boundary. Validates its arguments like the page read. |
| Next offset | Returns the offset the next append will use. |
| Readable head | Returns the head a reader may resume from: one past the highest offset a read would expose. Lower than the next offset while a flush is in flight, while an abandoned flush may still land, or while a trailing hole sits above every stored entry (issue #4621). |
| Trim watermark | Returns the partition's trim watermark when a reader may trust it, otherwise null. See Abandoned flushes, holes and the trim watermark. |
| Trim-watermark refresh | Returns the trim watermark under the same trust rule, re-derived from storage through IWalStorageProvider.RefreshTrimWatermarkAsync, so a value the provider cached above the stored trim point stops hiding entries from reads (issue #6036). |
| Resume floor | Returns the lowest offset the storage provider still persists or, when it persists none, one past its highest persisted offset (zero for a partition that has never stored an entry). It is derived from persisted offsets only, never from the in-memory offset allocator, so an append whose offset is reserved but not yet stored cannot make a still-valid cursor look trimmed (#5205). Rises to the first still-stored offset once IWalStorageProvider.TrimAsync runs (driven by ILatticeWalGc), so it reflects the persisted footprint; the state API's change observation reads it to refuse a resume point the GC has already trimmed. |
| Entry count | Obsolete trim-unaware diagnostic retained for one minor version. Returns the next offset to be assigned. Use the resume floor for the trim-aware footprint. |
The grain also serves the replication shipper's bytes-shaped page read (the
same durable gap-free window, each entry carried as the payload bytes the
encoder wrote at append time, read through IWalStorageProvider.ReadEncodedAsync),
reports the provider's retained-payload and physical byte sizes for the WAL partition
(-1 when the provider does not support byte accounting; the retained size is
also -1 when its scan cannot take a slot under the silo's
MaxConcurrentWalUsageScansPerSilo
bound), and fences itself
against appends and retires its activation during a placement move (see
Moving a partition to another account).
Saga terminal mutations (MutationKind.TxCommit / TxAbort) carry their
shard index in mutation.Key as a base-10 invariant-culture string; the
commit-log writer maps that shard index to a WAL partition by taking
shardIndex % WalPartitions. When the shard count exceeds the partition
count, multiple shards collapse onto the same WAL partition; receivers
dedupe by TransactionId, so multiple terminal appends with the same id
are idempotent on the apply side.
Per-tree WalPartitions pin resolution on the hot path
LatticeOptions.WalPartitions is pinned per tree in the tree
registry at the tree's first registration and is tree-immutable thereafter, so
the writer-side routing and the activation-time materialiser can never
disagree on the partition fan-out shape. The pinned value is exposed
through the cached per-tree WAL partition lookup, a
hot-path-optimised entry point that returns an already-completed
ValueTask<int> on a cache hit and falls back to a one-shot
tree-registry lookup only on the first call per
tree per silo. The foreground commit-log writer uses this fast path on
every single and batched append, so the WAL commit-log writer never
serialises through the cluster-singleton registry activation on the
write path. The full resolved per-tree options lookup (used by
admin grains and the activation-time materialiser) also populates the
fast-path cache as a side effect, so any tree touched by any caller
becomes cache-warm for subsequent writer calls.
Activation-time replay under WalPartitions > 1
Formal model.
ReplayPermits treats replay
admission as a process-wide resource, not a new permit pool per partition.
Its ownership and banking checks do not equate a caller deadline with the
lifetime of the shared cold-replay owner; see Recovery and rebuild.
The leaf grain's activation-time materialiser is partition-aware. When
LatticeOptions.WalPartitions > 1 the activation hook iterates
[0, WalPartitions) and, for each partition, runs an independent
fall-off-log classification, slice read loop, and projection-checkpoint
advance. Per-partition state lives in an additive per-partition
checkpoint slot (long[]?) of the leaf's persisted row;
partition 0 is mirrored into the legacy scalar checkpoint slot for
downgrade safety. The per-leaf
saga pending-tx clamp is also partition-scoped: each prepared mutation
records the (transactionId, partition) pair it arrived under, and the
projection-checkpoint advance for partition P is clamped behind
(min unresolved prepare offset for P) - 1 so cross-partition offsets
are never compared. A prepare already recorded verbatim in the leaf's
durable replay ledger no longer clamps, because a resumed replay rebuilds
it from the ledger (see
Resumable cold replay).
Each leaf reports one cursor per partition to the WAL cursor registry
under consumer ids of the form
_lattice_materialiser_{treeId}_{leafGrainId}_{partition}, so the
WAL GC trims each partition independently against its own
slowest consumer. With WalPartitions = 1 the unsuffixed
_lattice_materialiser_{treeId}_{leafGrainId} shape is preserved, so a
tree pinned to a single partition stays wire-compatible with its existing
cursor registrations.
Surviving a full restart
The WAL GC trims each partition through the minimum cursor across the consumers currently registered in the WAL cursor registry. The default registry is process-local and is wiped when a silo restarts, so on a cold start a forward consumer that persists its own cursor (the replication shipper re-reports its durably-advanced cursor eagerly on activation) could momentarily be the only registered consumer for a tree, while a dormant leaf - which re-registers its pin only lazily, on its next activation and checkpoint flush - is absent. Without a backstop the GC would compute its trim floor over the forward consumer alone and trim the WAL past the leaf's durable checkpoint, discarding the committed-but-not-yet-checkpointed tail the leaf still needs to replay.
In-memory cursor reporting is always on (the lightweight
in-memory leaf cursor reporter wired by AddLattice), but the durable
backstop below is the opt-in layer: it engages only when the host adds
the durable-pin-aware reporter through AddWalCursorRegistry (directly,
or transitively via durable WAL storage / views / replication). To close
that window each leaf then also mirrors its checkpoint frontier
into a sharded cluster-wide durable pin store (WalMaterialiserPinShards
grain activations per tree, each persisted through the configured grain
storage; the GC reads every shard under the current count plus the legacy
unsuffixed key, so raising the shard count loses no trim floor - lowering
it is covered under
WalMaterialiserPinShards). The
mirror is fire-and-forget and coalesced off the checkpoint path - a
debounce keeps a busy every-write-checkpoint leaf from issuing a durable
write per write - and because a too-low durable pin only ever retains
more WAL, a coalesced or slightly stale pin is always safe. On each
pass the GC consults the durable pins and lowers its HLC trim floor for any
materialiser consumer that is missing from the in-memory registry
(a consumer that is present has a fresher in-memory cursor already
folded into that floor; one
registered only with a Zero block-pin-only cursor contributed nothing
to it, so it is treated as missing). The checkpoint offsets the pins
record are used for every leaf, present or not: they form the durable
materialiser offset floor, which stops each trim scan and can overrule
the in-memory cursor (see Predicate). A leaf seeds a
durable Zero "block" pin when it is created - before its data becomes
reachable in the WAL - and that pin holds the WAL head for the leaf until it
produces its first checkpoint; the TTL ceiling (LatticeOptions.WalRetention) still bounds
growth in that state. Because durable WAL storage is the deployment
shape most exposed to this hazard, AddAzureTableWalStorage and
AddFileWalStorage automatically wire the cursor registry and WAL GC
seams (both idempotent) so durable storage never ships without the
durable floor.
Two cold-path retention barriers turn the durable pin from a best-effort mirror into an authoritative trim floor, so a write-once leaf that goes dormant can never have the shared WAL trimmed past its checkpoint (the "fall off the log" wedge). Neither adds a synchronous durable write to the steady-state checkpoint path:
- First real frontier. The first time a leaf crosses from its
Zeroblock pin to a real checkpoint frontier it awaits a batched report to the pin store (once per activation) instead of the fire-and-forget mirror, so the floor leavesZeropromptly rather than after a debounce window. The pin store merges the report at once but coalesces its own durable write, so a crash before that write lands leaves the durable pin at its last persisted value - at worst the block pin seeded at the leaf's birth - which only retains more WAL. Every subsequent advance uses the debounced fire-and-forget mirror. - Graceful deactivation. On deactivation, after its final checkpoint
flush (which publishes the pin it persists) and a snapshot capture for any
checkpointed partition no snapshot covers yet, the leaf awaits the same
batched pin-store report of its current frontier. It skips that pin-store call, counting
the skip on
orleans.lattice.leaf.deactivation.barrier.elided, only when a pin this same deactivation already had acknowledged covers every partition. So a leaf can never go dormant on a clean shutdown (and then have the WAL trimmed past its checkpoint across a restart) without leaving a correct durable floor behind.
Both writes go through the pin store's monotonic-max merge, so they are idempotent and never roll a pin backwards, and both swallow transient failures so neither deactivation nor the checkpoint path is ever blocked. A write that faults is not recorded as written, so the next report for those pins retries it rather than being coalesced away.