The design: 1. The epoch fence: other activations of the leaf to 2. The hand-off fence: other writers

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 the-design-1.md, and llms.txt lists every page.

Part of The design, in Live checkpoint advance: fenced redesign.

1. The epoch fence: other activations of the leaf

Claim eagerly, never lazily. Before an activation's first append, it claims an epoch. The claim is one serialised sequence per leaf and partition, in three steps:

  1. Persist (ClaimRow). The activation writes the epoch it read plus one to its _lattice_leaf-append-epoch row (LeafAppendEpochFence.ClaimRowAsync), as a strict conditional write on the ETag it read. It learns the partition's retired floor only through a refusal and a bump (below). Only claims write that row. So every conflict, empty-ETag included, means another activation claimed: this one is stale, the write fails closed and the activation deactivates. The caller's retry reaches the live activation (section 5).

    The write never goes through TopologySeedPersist.WriteAdoptingBenignFirstCreateRaceAsync, which adopts the winner's row on an empty-ETag conflict, the shape of #5593. Keeping the epoch out of LeafNodeState also means the leaf's ordinary persists never conflict with a claim.

  2. Write the entry (ClaimWrite). At every WAL partition the activation writes, ClaimAppendEpochAsync reads the durable entry row and refuses the claim at or below the retired floor, or below the higher of the loaded and durable entries. A claim equal to the durable entry, and not below the loaded one, is admitted without a write (AlreadyDurable): it is a re-presentation after a WAL shard restart or move, which then costs no re-claim. It rests on two things: the epoch row's strict conditional write (step 1), which gives each epoch one holder within an incarnation, so an equal claim is the same claimant (ReadPositionHonestClaimAdoptsNoCas, 16 states, drops it); and retirement raising the floor to the leaf's epoch row as well as its entry (below, #5641), so epoch values never recur across incarnations. Otherwise it writes the entry row as a conditional (ETag) max-merge: the row never moves down. Two overlapping claims for one leaf can reach the shard in either order (claim calls interleave like appends, and a delayed write can land late), so a plain write could leave the durable entry below the in-memory one, and a restart would reload the lower value and readmit the superseded activation (StaleEpochNeverAppendsClaimEntryOverwrite, 12 states). An ETag conflict re-reads and re-decides.

  3. Raise (ClaimRaise). Under _stateGate, the shard raises the in-memory entry to the epoch and reads _nextOffset, the allocator's next offset, not the readable head (DurableContiguousTailOffset). It returns that offset as the claim head. The raise is refused if another claim has raised the entry above this epoch since the write, or if a retirement since the write has raised the floor to it. Anything allocated before the raise lies below the claim head; anything after it is checked against the raised entry. The entry row was written before the raise, so a restart can never lose a raise whose head was already returned.

Any refusal bumps while the row holds. A refusal, by the entry at the write or the raise, or by the floor, returns the higher of the entry and the floor. The activation then persists the higher of that and its row, plus one, to its own epoch row, conditionally on the ETag of its own last write (LeafAppendEpochFence, as #5633 implements it):

  • The ETag holds. No activation has claimed since this one wrote the row, so it is not stale, whatever refused it, and it claims again above the refusal, at most LeafAppendEpochFence.MaxClaimRounds (8) rounds, after which it appends unstamped (reported, section 4).
  • The ETag conflicts. Another activation has claimed since, so this one is stale: it stops, and the caller's retry reaches the live one (WitnessClaimRefused).

An entry refusal with the ETag holding would mean the entry above this activation's epoch was left by an incarnation the row no longer records: the purge straddle (below), which the row floor of #5641 now refuses first. The model has ClaimBump for the bump (WitnessClaimBumped); it bounds the rounds by MaxEpoch and stops a bump that has no room, standing for the unstamped fallback, which WalLiveAdvanceGateFlip.cfg covers. Revision 5 stopped the activation on an entry refusal, which stopped a re-created incarnation in the straddle (OnlySupersededRefusedEntryRefusalStops, red in 9 states at revision 6); since #5641 closes the straddle it is a redundancy row.

The ETag in the model. Production compares the row's ETag; the model compares the pair of the row's incarnation (rowInc, raised by Recreate, the purge's delete) and its epoch. Within an incarnation every row write raises the epoch, so the pair identifies a write, and an epoch value that recurs after a purge never matches an old activation's write. Comparing the epoch alone would let a pre-purge activation's compare succeed where production's ETag fails.

The stamped append. Once the cluster's fence gate is open (section 4), an activation appends through new stamped methods; the existing methods are unchanged:

  • AppendStampedAsync, for a single entry;
  • AppendBatchStampedAsync, for a batch. This is the dominant path: WalCommitLogWriter.AppendManyAsync reaches IWalShardGrain.AppendBatchAsync today, and WalBatchedSingleEntryAppends routes even single entries there. Each entry of the stamped batch carries its own stamp (leaf identity, epoch, and the shard routing generation of section 2). Under the one _stateGate section that assigns the batch's offsets, the shard checks every entry's stamp before it assigns any offset. A batch is rejected at its first failing entry, so nothing of it is allocated (WalAppendFenceOutcome, as #5633 implements it); the response carries the outcome per entry and the unstamped watermark (section 4). The coalescing writer fails the callers of a rejected batch, and their seams retry them (section 5).

The shard accepts a stamped entry only if the leaf's entry is loaded and the epoch is not below it. It does not check the retired floor on the append path (#5635). The shard reports a refusal as an outcome, not an exception: StaleEpoch, UnloadedEntry, StaleGeneration and so on (WalAppendFenceOutcome). The leaf turns StaleEpoch into the existing LeafRetiredException, with ActivationSuperseded set and the superseded epoch, which its callers' seams retry (section 5; the wire form is under Wire formats). An entry not yet loaded rejects the append as unloaded (below); the leaf re-presents its claim and retries. The stored record does not change: the stamp is a call argument, never part of the record.

The retired floor at the claim, not the append (#5635). A purge and re-creation of the leaf resets its entry, so a claim written before the retirement and raised after it would pass an entry-only check. The floor is therefore checked at the claim's entry write and at its raise. Dropping the raise check fails in 8 states (StaleEpochNeverAppendsIgnoresRetiredFloor).

The floor is not checked on appends. It is one value per partition, while epochs are per leaf: checking it on the append path would reject every live leaf of the partition whose epoch is at or below an epoch another leaf retired, superseding leaves that nothing superseded. Revision 4 specified that check; production member 1 (#5633) found the over-retirement and removed it (#5635). A retired incarnation's own appends do not need it: retiring the leaf deletes its entry, so its appends are rejected as unloaded and its re-presented claim is refused by the floor.

The condition that makes the append check unnecessary. Retirement must remove the WAL shard's loaded entry, not only its rows. It therefore goes through the WAL shard activation (RetireAppendEpochAsync in #5633), which, in order: takes the per-leaf gate, serialising it with that leaf's claims; raises the durable floor; deletes the entry row; drains any in-flight stamped batch; and removes the entry from the loaded entries under _stateGate. An unloaded entry rejects every stamped append (UnloadedEntry). Every retirement path, the leaf's clear and the WAL GC's orphan-pin retirement, goes through it. A retirement that only wrote rows would leave the loaded entry admitting a surviving activation of the retired incarnation, and would need the append check back (StaleEpochNeverAppendsRecreateKeepsLoadedEntry, 9 states). In the model, AppendAdmits is the entry check alone, RetireOther (WithOtherRetire) raises the shared floor above epochs L holds, and OnlySupersededRefused states that only a superseded activation is ever refused, at a claim or at an append. It is behavioural: putting the floor back in the admission predicate (OnlySupersededRefusedFloorAtAppend) or in the append guards beside it (OnlySupersededRefusedFloorInAppendGuards) both fail.

Another leaf's retirement at the claim. The claim-time checks are partition-wide too: a claim between its row write and its raise when another leaf is retired with a higher epoch is refused by the floor. Its ETag holds, so it bumps and re-claims (above). Cost: one extra claim round per claim in flight at another leaf's retirement in the same partition (N3, below). One epoch per activation, across partitions. An activation has one epoch, stamped on every partition it writes. A floor-only bump forced on partition P2 therefore changes the epoch it would stamp on P1. Production does not stamp P1 with an epoch it never claimed there: StampForAsync stamps only when the partition's claimed epoch equals the activation's, so the next append to P1 first re-claims P1 under the new epoch, and P1's claim head is unset until then, so P1 is disarmed until the leaf replays to the new head. The model checks a weaker discipline that over-approximates it: OtherPartitionBump (WithSecondPartition, WalLiveAdvanceTwoPartition.cfg) bumps a raised activation's epoch from another partition at any time and keeps stamping P1 without a re-claim, which P1 admits because the epoch is above its entry; every property still holds (WitnessOtherPartitionEpoch), because any other activation must first win the leaf's epoch row, and its claim on P1 then exceeds the bumped epoch.

Arming. The activation is armed for the live advance on a partition only when:

  • its claim on that partition has been raised (an explicit guard; see the redundancy checks for why it is kept);
  • its marker state is initialised (section 2);
  • it has replayed to that partition's claim head;
  • every append it has issued there has been applied (the applied-prefix tracker);
  • it has read past every unstamped append reported to it, its own included (section 4);
  • the hand-off conditions in section 2 hold.

Everything another activation appended before the claim lies below the claim head and has been read. Everything an older activation tries to append after it is rejected. A newer activation's appends all lie above this activation's own.

A lazy fence, where the shard rejects an older epoch only once the newer one has appended, is not enough: a stale duplicate can append between the newer activation's claim and its first append (NoTrimPastAckedLazyFence).

Loading entries. The shard keeps the entries it has loaded in memory, in a dictionary keyed by leaf. Entries load lazily: an append from a leaf whose entry is not loaded is rejected as unloaded, and the leaf's re-presented claim (same epoch) loads it. No storage read ever happens on the append path or under the lock.

Retiring entries: a monotone floor. An entry is retired only when its leaf is retired: by the step that retires the leaf's materialiser pins, under the retirement token (#5358), or by a purge tail, under the lineage check (#5417). Retiring raises the partition's floor row, durably and before the entry row is deleted, to at least the higher of the leaf's entry and its epoch row: the clear passes the epoch-row value it already reads into the WAL shard's retirement (#5641). No removal ever lowers the floor, so the entries stay bounded by live leaves.

Why the row, not only the entry (#5641). A clear deletes the leaf's epoch row, so epoch values recur in the re-created incarnation. A pre-purge duplicate D that wrote the row (epoch e) but not yet its entry at a partition leaves no entry there, so a floor built from entries alone stays below e. D's entry write then lands after the purge, D raises and appends, and the re-created incarnation R, reading the row as absent, claims the same e and is admitted as AlreadyDurable: both hold e, neither is ever found stale, and R arms past D's acknowledged appends. Raising the floor to the row refuses D's straddling entry write; D's bump then either meets the deleted row and stops, or lands before the clear's conditional row delete, which then conflicts and keeps the row (see "The purge straddle"). The model's Recreate is one atomic step; the reviewer's three-step clear (read the row, retire, conditional delete) is clean at 20,374,851 states, and the promoted module should model the clear in those three steps. Building the floor from entries alone fails (ReadPositionHonestFloorFromEntryOnly, 17 states).

A re-created leaf (a purge re-creation, or an id reused by a create) starts a new epoch row. Its first claim lands in an absent entry, so it must exceed the floor, and therefore every epoch a surviving duplicate of the old incarnation holds. ReadPositionHonestRecreateDropsFloor removes the floor raise and fails.

The purge straddle. A pre-purge duplicate D can write its row (epoch e) before the purge and its entry after it. Raising the floor to the row (above) refuses that entry write, since e is at or below the floor. D then bumps. The clear reads the row, retires the partitions, then deletes the row conditionally on what it read, so D's bump meets either the deleted row, and D stops, or, landing first, the row the clear read: the clear's conditional delete then conflicts and the row is kept with D's bumped epoch, so the next activation continues above it and no value recurs. Either way no entry is left above a held row of the re-created incarnation. Production's bump on any refusal while the row holds (section 1, "Any refusal bumps while the row holds") is therefore redundant in the model since #5641; it is kept, because it is the general recovery for an entry above a held row, however one arises, and it is what #5633 implements (redundancy row EntryRefusalStops).

Retirement code runs whether the gate is open or closed, so rows are retired on every path a new silo runs: every leaf clear (purge, reclaim, orphan repair) and the WAL GC's orphan-pin retirement, which also re-drives an interrupted clear. A retirement on a 10.2.0 silo, during a rollback or a rejoin after the gate opened, deletes none of these rows (so the epoch row survives, epoch values cannot recur, and the floor needs no row value), and it also removes the leaf's materialiser pins, so the orphan-pin pass never finds the leaf again; IGrainStorage cannot enumerate rows, so the rows would leak for good (#5634). The leftover rows are safe (a leaked entry only ever sits above a re-claim, and a leaked epoch row makes a re-created leaf continue from a higher epoch), so the cost is storage only. A per-partition epoch directory row makes a partition's entries enumerable, and a sweep walks it and retires the entries of leaves that no longer exist (review N1). The directory row is bucketed or paged to stay within the provider's row limits (Azure Table: 64 KiB per property, 1 MiB per entity). It is built in its own production member (#5634), which lands before #5605's bucket reaches main.

Moves and restarts. The entry, floor and generation rows live in grain storage, not in the WAL stream, so a WAL move, which switches the stream's provider, does not touch them. A restart of the shard grain, including the reactivation at a move's cutover, loses only the in-memory entries, which reload through re-presented claims; nothing is accepted from an unloaded entry (StaleEpochNeverAppendsUnloadedEntryAccepted). It also loses the in-memory unstamped watermark, which restarts at the recovered allocator head minus one (section 4).

Abandoned flushes (#4621). The restarted watermark assumes nothing is allocated below the recovered head after the restart. That holds: the reactivated allocator recovers from the highest stored offset (WalShardGrain.cs:440) and ignores abandoned flush windows. A flush abandoned before the restart that lands late conflicts create-only with the reissued offset, and one side fails. So no entry lands below the restarted watermark unreported.

Cost.

  • Per append: one dictionary lookup and one comparison under the lock the append already holds, per stamp. No allocation and no grain call. A stamped entry carries 24 more bytes on the request: leaf identity, epoch and routing generation. The response carries the 8-byte unstamped watermark, and a batch response the per-entry outcome. The stored record is unchanged.
  • Per activation: one conditional row write, plus one claim call, one entry-row read and one entry-row write per partition it writes. A fresh estate of N leaves writing P partitions costs at most N x P entry-row writes once, not O(N^2). The first write after every leaf activation waits for that claim: a leaf-row read and write, then per partition a grain call with an entry read and write, about four sequential storage round trips before the first append (change 11).
  • Per retirement: a leaf clear reads the leaf's epoch row and, if it has one, calls the WAL shard's retirement at every partition, each a floor write and an entry delete, so a tree purge costs N x P grain calls with storage I/O for N leaves with rows. The WAL GC's orphan-pin retirement costs a grain call and a floor and entry read at the partition whose pin it removes.
  • After a retirement (N3): the floor is one scalar per partition, so after any leaf's retirement every new leaf whose epoch row is older than the floor pays one refused claim per partition it writes, then bumps and claims above the floor; and every claim in flight in that partition when another leaf is retired with a higher epoch pays one extra round. Appends are never affected (#5635). A bump forced at one partition costs one extra claim round at every partition the activation writes, and a re-arm (a replay to the new claim head) at each.
  • Per shard restart: one extra claim round trip for each leaf that appends afterwards.
  • Storage: one entry row per (partition, live leaf that wrote it), one floor row per partition, one generation row per (partition, shard root that re-claimed there), one epoch row per leaf, and the marker rows.
  • Memory: about 100 bytes per leaf that has appended to the partition since the shard activated.

2. The hand-off fence: other writers

Every foreign-author path follows one protocol:

  1. Open. The initiator sets a durable open marker on the owner before its first admission of a write the owner will own.

  2. Close by fencing. In order, the initiator:

    • (a) stops admitting writes for the range;
    • (b) may wait a bounded time for writes it admitted earlier to return. This is an optional latency optimisation: no bound makes a rejection in (c) impossible;
    • (c) bumps and re-claims its own epoch (a leaf initiator: it persists its row plus one, conditionally on its own last ETag) or its routing generation (a shard-level initiator) at every partition it may have written. A same-value re-claim would fence nothing; the model's Close raises the initiator's epoch (fEpoch' = fEpoch + 1). The re-claim returns allocator heads, exactly as a claim does;
    • (d) closes the marker, recording those heads.

    A leaf initiator's own rejected appends are a self-fence, not supersession. A donor's appends admitted under its old epoch and not yet allocated at (c) are rejected as stale. With its row ETag still held and the stamp below its own current epoch, that rejection is a distinct internal outcome: the activation does not deactivate, and its seam retry re-admits the write under the current epoch, where span admission forwards a key the narrow moved and a key it still owns re-appends. On the wire it stays the existing LeafRetiredException with ActivationSuperseded set and no new field: a 10.2.0 shard root calling this leaf across a gate race deserializes it and retries until its deadline, and every new seam already retries it. A genuine supersession still meets the next current-epoch append and deactivates. The self-fence has its own counter (change 7). It also covers a floor bump's own in-flight appends (#5643). The order is narrow (a), then bump (c), then close (d); the in-memory epoch moves only after the row's conditional write succeeds. The initiator's own claim heads move too, so it is disarmed until it replays to them (N3).

  3. Re-arm by replay. The owner holds the live advance while any marker is open. It re-arms only after replaying to the recorded heads.

Why the drain is a fence and not a wait. Every stamped append carries the epoch or generation its write was admitted under. So after (c), a write admitted before the close either was allocated already, and lies below the recorded heads, or will be rejected when it arrives. A wait cannot replace this: a write's call can return by timeout while its append is still delivered and allocated later (ReadPositionHonestDrainWithoutFence). The design relies on no gate draining anything: split commits never take _splitGate, the adaptive split's reject phase only flips a phase, and the fold's serial-turn guard excludes point writes.

The routing generation is durable (S1). A shard-level initiator's generation entry at a partition lives in its slot of the partition's _lattice_wal-routing-generations row (#5987), with the same semantics as a leaf's entry: a conditional max-merge write, an in-memory copy raised under the lock, an unloaded entry that rejects until a re-presented re-claim reloads it, and no loss across a restart or a move. If a restart lost it, a write admitted before a close would pass the reset entry after the close (ReadPositionHonestGenerationNotDurable, 14 states). A raise of any fenced identity, a leaf's epoch, a shard root's routing generation (per initiator) or the tree's range-delete generation, drains the in-flight stamped batches before it reads its heads, so no entry of a batch admitted under the old value is allocated above the heads the raise returns.

Stamped at admission. The stamp is taken where the write is admitted, not where the append is built. A leaf captures its epoch in the same synchronous step as span admission. A shard root captures its routing generation in the same step as its phase check (ThrowIfRejectedForKey) and passes it to the leaf through a new stamped leaf-write method. If the append read the current epoch instead, a write admitted before the close would carry the re-claimed epoch and be accepted (ReadPositionHonestStampAtAppend).

An implementation may carry an admission mark instead of the epoch value: the activation's count of hand-off closes plus one, captured in the same synchronous step as span admission. At dispatch, a write whose mark predates a close is refused as a self-fence (section 2) and re-admitted, where span admission forwards a moved key. The raised epoch therefore never stamps a write admitted before the close, which is all ReadPositionHonestStampAtAppend requires. It refuses fewer writes than a captured epoch value, because a claim or a floor-refusal bump is not a close. Mark 0 means "not captured" and is never carried by a stamped entry. The fence that counts the closes must therefore exist at admission, not be created lazily at the activation's first append. Otherwise a write admitted before that first append reads "no fence yet" as mark 0, a close lands before it is dispatched, and it is stamped with the raised epoch above the heads. A path that appends with mark 0 stamps at dispatch, so it must not append a key the initiator may have narrowed away: it captures its own mark before its span check, as the tx-terminal backstop does (the census, below).

The unstamped leaf methods stay unstamped (S3). A write that reaches a leaf through an existing leaf-write method carries no routing generation: a 10.2.0 shard root admitted it, or a path the census missed. The leaf appends it through the unstamped WAL method, never stamped with its own epoch alone. A leaf-epoch stamp would pass the leaf's own check and escape every shard-level fence unreported; an unstamped append is admitted and reported (section 4), which is safe and disarms the leaves it reaches.

What the close heads must bound (S2, #5664). The owner re-arms after replaying to the close heads and may then live-advance past anything above them, so the heads must bound every record the initiator appends that the owner holds, not only those stamped before the bump. Three production shapes fall outside that bound unless guarded:

  • A write admitted before the narrow but stamped after the bump. The stamp must be the epoch captured at admission ("Stamped at admission", above, which also admits an admission mark), carried to the append. Taken at dispatch, it is the raised epoch, and the write is accepted above the heads (ReadPositionHonestStampAtAppend, 13 states).
  • A partition whose claim was reset. After a WAL shard restart or move resets a partition's loaded claim, the initiator has still stamped appends there. The close must re-claim every partition it has claimed in this activation, and record no head (-1) only for a partition it never claimed. A head recorded as -1 where it did append lets the owner skip them (ReadPositionHonestCloseHeadUnderstated, 13 states).
  • A close while the initiator's gate view is closed. It cannot bump. If it has claimed any partition, a stamped append may be in flight, so it must leave the marker open, and the owner keeps advancing by replay, until a later close can bump and re-claim. Only an initiator that never stamped may close on unfenced heads. A close that records heads without a fence is ReadPositionHonestDrainWithoutFence.

The span re-check at apply (StoreAdmittedEntry) and the receiver's own forward or straggler transfer make each of these harmless while the initiator stays up: the moved row reaches the owner as the owner's own append. That argument fails when the initiator's record is durable but the forward never happens. It can crash between its append and its apply, or its reactivated replay can no longer own the key. The record is then owned by the owner and applied by every WAL reader, and a live advance past it diverges for good. The model lets a hand-off never happen for exactly this reason (HandOff is optional), so it does not rely on the forward; the three guards are what make the heads a bound.

Who stamps. Whoever calls the WAL append stamps it with its own epoch (and, for a write admitted at a shard root, that shard's routing generation). A record appended by the leaf that owns it is that leaf's own append, tracked by its applied-prefix tracker, and needs no marker. A marker on the owner is needed only for records a different author appends, such as a donor's appends of moved keys before its narrow, which the donor's bump fences.

The stamp census. Production member 2 carries a census of every path that appends an entry a leaf owns, with a detector per path. Each path is stamped, classified, or stated "unstamped, disarms". A path that bypasses the stamp is the gap the fold's point-only guard has today (ReadPositionHonestDrainPointOnly). The census starts from the paths that reach a leaf without shard-root admission:

Path Where Treatment
Point, batch, CRDT apply, merge, delete Shard root admission, then the stamped leaf-write method Stamped with the shard's routing generation and the leaf's epoch
Saga prepare BPlusLeafGrain.PendingTx Stamped at the participant's admission
Stranded relocation, leaf to leaf BPlusLeafGrain.SpanAdmission.cs:431, MergeManyAsync Appended by the receiver: stamped with the receiver's own epoch, its own append. The donor's own earlier appends of those keys are fenced by its bump under its marker on the receiver
Re-routing a terminal's stranded prepared keys, and the backstop appends BPlusLeafGrain.PendingTx.cs:2534, :2719ff Whichever leaf calls the append stamps with its own epoch: the sibling's re-routed appends are its own; a backstop append by the re-routing leaf for a key it no longer owns stays stamped with that leaf's epoch, under its marker on the sibling. The backstop forwards keys outside its span to the owner, which appends them itself; it captures its admission mark before its span check, so a local key a split narrows away while the forwards are awaited is self-fenced and re-admitted, never appended under the raised epoch
Split transfers BPlusLeafGrain.Split.cs, MergeEntriesAsync Appended by the sibling: stamped with the sibling's own epoch (born under the gate, it claims eagerly). The donor's pre-narrow appends of moved keys are fenced by the donor's bump under the split's marker on the sibling
Adaptive split coordinator's drain TreeShardSplitGrain.cs:1023, :1037 Under the adaptive split's shard-level marker; the donor shard's generation
Bulk seeding and the resize mirror ShardRootGrain.BulkLoad.cs; the resize mirror Under the bulk switch's marker; the shard's generation. The seed is the bulk-seed stamp class, naming no leaf, so it claims no append epoch (#5812); on a shard with no root the load opens no marker and seeds unstamped, admitted and reported
Shadow forwards, plain and CRDT ShardRootGrain.Split.cs Under the adaptive split's marker; the forwarding shard's generation
Compaction reap, replayed terminals BPlusLeafGrain.cs:3434; BPlusLeafGrain.ReplayedTerminals.cs:147 Leaf-internal: stamped with the leaf's own epoch. They are the leaf's own appends, tracked like any other. Both append with mark 0, so a reap collected before a split narrows the leaf can be stamped with the raised epoch above the close heads. That is harmless by content: a reap only drops a tombstone at or below its own stamp, so a reader that skips it never resurrects or changes a visible value, and a replayed terminal carries no row data and sits under the prepare clamp (re-review of #5644, N-a)
Coordinator saga terminals AtomicWriteGrain.FlushPendingTerminalsAsync (:2356); ShardRootGrain.TxTerminal (:352) The terminal stamp class (below)

Coordinator terminals (S6). A saga terminal appended by a coordinator, not by a leaf, carries a new stamp class, "terminal", which the shard admits like an unstamped append but does not report in the unstamped watermark. The WAL shard accepts the terminal class only for records whose Op is TxCommit or TxAbort (S2); a record of any other kind sent with it is admitted unstamped and reported, so the class cannot be used to bypass a fence or the watermark. Excluding it is safe because of two guards the leaf already has: the leaf-wide prepare clamp (#5572), which holds the advance on every partition while any prepare is pending; and _recentlyTerminal, which makes a terminal applied after its prepare resolved idempotent. A terminal only ever resolves a prepare the leaf itself recorded, so the advance never passes a terminal whose prepare is still pending, and passing one whose prepare has resolved changes nothing. Without the class, every saga would raise its partitions' watermark and send every leaf writing them back to replay, the demand #5569 and #5570 are about. The exclusion is sound because a TxCommit or TxAbort record carries only its TransactionId and no row data (WalRecord.cs): replaying one with no pending bucket is a no-op. The model has no sagas, so this rests on the clamp; it is a gap entry in the refinement note, member 2's detector proves a terminal-class append never raises the watermark and never passes a pending prepare, and the promoted module adds one prepare and its terminal.

Crash and cost. If the initiator crashes, the marker stays open until its recovery re-drives the close. The cost is latency (the owner advances by replay), never data. A write admitted before the close and not yet allocated at (c) is rejected unacknowledged and retried at its seam (section 5).

Path Initiator Open Admission stops at Fence at close
Split Donor leaf In the sibling's marker row, written in the sibling's birth (InitializeSiblingAsync) The donor's narrow of HighKeyExclusive; span admission forwards moved keys afterwards The donor bumps its epoch and re-claims it at every partition it writes; the heads close the sibling's marker; its own rejected appends are a self-fence
Leaf reclaim Absorbed neighbour leaf On the survivor, before its range widens The neighbour's unlink The neighbour's entry is retired (the floor rises), so its later stamped appends are rejected; the heads are captured in the retire step
Adaptive split Donor shard root Shard-level marker on the target shard root The reject phase The donor shard root re-claims its routing generation at every partition; the heads close the marker at completion
Shard fold Folded shard root Shard-level marker on the survivor shard root The fold's quiesce, point and batch The same routing-generation re-claim
Range delete The tree's range-delete fence grain (below) A range-scoped marker on every shard root of the tree, before any shard appends The end of every shard's walk, or the intent's recorded deadline The fence grain re-claims the tree's range-delete generation at every partition once; the heads close every shard's marker
Bulk load / append The shard root, for writes admitted before the switch At the bulk leaf's birth, with the birth hint (shared by a run of append chunks) The switch, in the shard root's serial turn The shard root re-claims its routing generation at every partition; the heads close the marker. Completed append tokens close in batches (section 3, #5702)

A resumed division applies no read position (#5706). A forward division (a split, or the bulk switch's narrow) drains the mutations admitted before it reads the heads it gives the new leaf as its read position, so nothing admitted earlier lies above them unapplied. A division resumed on the recovery path (CompleteSplitAsync) cannot drain commits that were in flight when the original activation died, so it applies no read position, and the sibling replays from its own start. The close heads do not cover this: they gate arming only, not the sibling's replay start.

Range delete: fenced at the tree. A range delete's record is replayed by every overlapping leaf of every shard, not only by the authoring shard's leaves. A shard-scoped fence therefore fails after a partial fan-out: shard A's walk appends, shard B's walk fails, and B's armed leaves pass A's record and never delete those keys, a permanent divergence from replicas and views that 10.2.0 does not have (it converges at B's next replay). So the fence is tree-level, and is owned by a new per-tree grain, TreeRangeDeleteFenceGrain, keyed by tree id.

One generation for every walk (revision 4, B1). Every shard's walk of a fenced range delete is stamped with the tree's range-delete generation, not with its own shard's routing generation. Revision 3 stamped each walk with its shard's generation and closed the shards one at a time. That is unsound when a walk is abandoned: shard A's walk, still in flight, is stamped with A's generation, which B's close does not re-claim, so A's record can be allocated above B's recorded heads, and B's leaves, which replay every overlapping range-delete record, re-arm and pass it (ReadPositionHonestRangeDeletePerShardClose, 13 states). With one generation, one re-claim at each partition fences every shard's walk at once, and the heads it returns are valid for every shard's marker. No two-phase close is needed.

  1. Intent. LatticeGrain.DeleteRangeAsync asks the fence grain to open an intent before any shard appends. The intent records the operation id, the range, and a deadline, taken once when the call starts in the form of LatticeGrain.SagaDecisionDeadline (LatticeGrain.cs:3448): the silo's SiloMessagingOptions.ResponseTimeout less a margin. A CancellationToken carries no deadline to read. The fence grain persists the intent in its own state and returns the tree's current range-delete generation.
  2. Open. The fence grain opens a range-scoped marker, idempotently, in the shard-level marker row of every shard root of the tree, and records each in the intent. Every shard's B+ tree spans the whole key space, so every shard can hold an overlapping leaf.
  3. Fan out. LatticeGrain runs the shard walks as today, with one issue HLC for all shards, through a new stamped shard-root method that names the intent and carries the generation. The shard root trusts the generation it is given and stamps the walk's leaf appends with it at admission. It does not ask the fence grain per page: the WAL shard's generation check already rejects a walk whose intent has closed, and only that rejection's seam retry asks the fence grain.
  4. Close. When every walk has returned, or the intent's deadline has passed, the fence grain re-claims the tree's range-delete generation at every partition (the re-claim returns allocator heads), records the heads in every shard's marker, closes the markers, and deletes the intent.
  5. Re-drive. The fence grain owns one reminder per tree, registered while any intent is open and unregistered when none is. Each tick closes every intent whose deadline has passed. LatticeGrain is a stateless worker, so if it dies mid-fan-out nothing marks the fan-out ended; the recorded deadline is what lets the reminder tell "ended" from "still running".

The deadline affects liveness only. A close that comes before every walk has finished is safe: the walk's next stamped append is rejected and, with the intent closed, the walk goes on unstamped and reported. The cost is that a range delete outlasting one response timeout, such as a paged drain (LatticeGrain.DrainShardRangeDeleteAsync), runs its later pages unstamped, which disarms the partitions they reach until their leaves replay past them.

A walk with no open intent is appended unstamped (B2). A shard root stamps a range-delete walk only when the call comes through the stamped method with an intent's generation (step 3). A range-delete walk that reaches a shard root through the existing shard-root method is appended unstamped, so it is admitted and reported (section 4), never stamped under a fence that holds nothing. That covers, without any resume rule:

  • replication apply: LatticeGrain.ApplyDeleteRangeAsync fans out with shard.DeleteRangeAsync to every shard (LatticeGrain.ReplicationApply.cs:338);
  • resize and reshard shadow forwards: ShardRootGrain.DeleteRangeBoundedCoreAsync forwards to the destination tree (ShardRootGrain.cs:2070);
  • a fan-out spanning the gate opening: a LatticeGrain fan-out begun while its view of the gate was closed opened no intent, so its later walks go through the existing method;
  • a 10.2.0 caller.

These stay unstamped by design, rather than being routed through the fence. The cost is bounded: an unstamped walk raises the unstamped watermark on each partition it reaches, and every armed leaf writing those partitions then replays from its checkpoint past it. A live-advanced leaf's checkpoint is near the head, so that is a tail replay, never a replay from -1 and never more than 10.2.0 already does on every advance. The busiest case is a replicated repocontext tree, whose RepoContextStore range-deletes in steps (:1187, :1587), so each step reaches each peer as an unstamped walk. A predicate-filtered replicated delete is not affected: it ships the matched keys, which the receiver applies as point tombstones through ApplyMergeManyAsync, stamped as usual. A counter of unstamped reports by source makes the cost observable (change 7). Stamping a walk with no open intent fails (ReadPositionHonestRangeDeleteWithoutIntent, 13 states).

A walk outliving its intent (B1). A walk still running after its intent closed has its next stamped append rejected by the re-claimed generation. The shard root's seam retry then asks the fence grain whether its own intent, named by id in the stamped call, is still open. If it is (another delete's close re-claimed the shared generation), the walk is re-stamped with the generation the fence grain returns; if not, it appends unstamped, so the walk completes as it would in 10.2.0. Two concurrent range deletes on one tree share the generation, so one's close rejects the other's in-flight appends once, and each is retried this way.

Rule 3: re-stamp only under the walk's own intent (revision 6). Markers are range-scoped, and a leaf disjoint from an open marker ignores it. So another open intent, I2 on range R2, does not hold a leaf X that overlaps the walk's range R1 but not R2: X re-armed after the walk's own intent I1 closed. A walk re-stamped under I2 would be admitted above I1's close heads, and X would live-advance past a range-delete record it must replay, and never apply the delete. Re-stamping only while I1 is open is safe: I1's markers still hold every leaf overlapping R1. In the model, OtherIntentClose (under WithTreeWalk) is that case: another delete's close re-claims the shared generation while the walk's own intent, whose marker holds L, stays open, and GRestamp re-stamps the walk (WitnessTreeWalkRestampedOwnIntent). GRestamp's guard reads L's marker (hoOpen), which is a safe over-approximation of rule 3: it includes re-stamps under a newer intent covering L, which production forbids. Dropping the guard stands for re-stamping under an intent disjoint from L (ReadPositionHonestRestampUnderAnyIntent, 15 states). Re-stamping under any intent whose range contains the walk's would also be sound, but needs a containment test for no benefit.

That is sound only if the open check is atomic with the close. The close is not one instant: it re-claims the generation at every partition (several awaits), records the heads, and closes the markers. An open check answered between the first re-claim and the marker close says "open", the walk re-stamps with the post-close generation, its append is accepted above the heads the close already recorded, and the owner re-arms after replaying to those heads and passes it: the divergence the fence exists to prevent (ReadPositionHonestRestampDuringClose, 16 states). Two rules close it:

  1. The intent is closed before the close's first re-claim. The fence grain marks the intent closing, durably, in the same turn that begins the close. From then on the open check answers "not open".
  2. One source for both answers. The open check and the generation it hands out are answered by the fence grain from that single state, in turns that do not interleave with a close: TreeRangeDeleteFenceGrain is non-reentrant, and its open check is neither [AlwaysInterleave] nor [ReadOnly]. No shard root caches either answer.

In the model, GReject leaves a rejected walk to GRestamp (an intent is open and not closing: re-stamp with the current generation) or GUnstamped (otherwise: append unstamped and report it). closing marks a close between its re-claim and its marker close; it is always false in the model, because Close marks the intent closed atomically with the re-claim, which rule 1 makes true in production. The mutation splits Close into the re-claim and a later CloseMark and lets the open check read the marker alone. WalLiveAdvanceTreeWalkConcurrent.cfg (two windows) is the case where a re-stamp under a second delete's intent is reachable (WitnessTreeWalkRestamped). The record is unchanged (it is not clipped; see Backward compatibility). A leaf whose range is disjoint from an open range-delete marker ignores it, by the same overlap test the replay judge uses (IsDisjointRangeDelete).

Cost per range delete call (S4): one fence-grain call to open and one intent write; one marker write per shard to open and one to close; one generation re-claim per WAL partition, once, not once per shard; and the reminder only while an intent is open. Every overlapping leaf of the tree is disarmed for the call's duration, advancing by replay. Stepped range deletes pay that cost per step, because each step is its own DeleteRangeAsync call with its own intent:

  • cursor deletes (LatticeCursorGrain.cs:569, :582);
  • RepoContextStore (:1187, :1587);
  • the vector index (LatticeVectorIndexStore.cs:291);
  • view maintenance (ViewMaintainerGrain.cs:1587).

Between steps the markers are closed, so overlapping leaves re-arm after a replay to the step's close heads. They are not held across the whole stepped operation. A caller that wants one fence for a whole stepped operation is a later optimisation, not part of this design.

In the model, the foreign author f stands for the walk on the owner's own shard, and g (WithTreeWalk, WalLiveAdvanceTreeWalk.cfg) for another shard's walk. Both are stamped with fEpoch, the tree's generation, and are admitted only under the open marker. Close re-claims it once and fences both.

Hand-offs in flight across the gate (B2). A split (LeafNodeState.SplitInFlight and SplitSiblingId, resumed by CompleteSplitAsync), an adaptive split (ShardRootState.SplitInProgress), a bulk graft (PendingBulkGraft), a shard fold, or a cursor range delete can be started by a 10.2.0 silo, or by any silo while the gate is closed, and so never open a marker. Two rules close that window:

  1. Resume opens the marker. Every resume path of an in-flight hand-off opens its marker idempotently before its next admission, before it admits a stamped write.
  2. Absence never means closed. A leaf or shard with no marker row is held, not armed, until its marker state is initialised: a shard root writes the initialised flag only in a serial turn in which it has no hand-off in flight; a leaf born under the gate writes it at its birth; an existing leaf takes its shard's flag once that is set and the leaf itself has no split in flight.

Dropping rule 1 fails in 17 states (ReadPositionHonestResumeWithoutMarker). Rule 2 is implied by rule 1 in the model (see Redundancy checks); it is kept because a resume path the census misses would otherwise read as closed.

Purging a tree's fence rows (#5668, #5703). The per-tree rows (each shard root's _lattice_shard-handoff marker, every partition's _lattice_wal-routing-generations table, and the TreeRangeDeleteFenceGrain state) are retired by the purge, before its registry removal and re-driven while RegistryUnregisterPending:

  1. Floors first. The purge reads every row: the fence grain's generation, every shard root's marker, and every partition's generation entries (each shard-root initiator and the range-delete initiator). It then raises every initiator's routing floor in _lattice_tree-routing-floor, a map from initiator tag (s{i} for shard root i, t0 for the range-delete fence) to floor, to the highest generation seen, in one write, before any delete. On an ETag conflict it re-covers the row before deleting it. Raising every initiator to the tree's highest is at least each one's own, and safe at a purge, where no initiator of the purged tree survives; the model raises each over its own. Written after the deletes, a crash between them leaves a re-drive reading rows that are already gone, so no floor is raised, at the WAL either (ReadPositionHonestRoutingFloorAfterDeletes, 15 states).
  2. Then retire. The fence grain (its state and reminder), then the markers, then each partition, where RetireRoutingGenerationsAsync raises the WAL shard's in-memory floor and drops the loaded entries before deleting any row. A row absent at the purge's read is skipped (RetireRowsAsync deletes only rows it read). That is safe because a row created after the read cannot be the purged incarnation's: a deleted tree's shard roots refuse operations before any routing-generation work; a write still in seam retry fails at the floor check (#5705, below); a marker write meets the seen-then-absent guard; and the re-created incarnation exists only after the purge's registry removal, which follows the retirement, and creates its rows above the floor.
  3. Re-creation starts above the floor. A re-created incarnation initialises every first routing generation at its initiator's floor plus one, on every initialisation path, including one taken while the gate is closed that opens later. Starting at 1 leaves the live incarnation at or below its own floor, so the WAL refuses its every claim and #5705's guard fails its writes as deleted (LiveGenerationAboveFloorRoutingRecreatedAtOne, 4 states). That is a different property from losing the floor, which admits the straddler (#5697 review, N1).

The WAL-side floor is load-bearing (#5697 review, S1). ClaimRoutingGenerationAsync loads the floor map once per WAL shard activation and refuses a claim at or below the initiator's floor; the refusal threshold includes it. A straddling shard root of the purged incarnation admitted a write before the purge and dispatches it after. A shard root's first initialisation (below) claims only its own generation and the range-delete fence's. So a straddler of another shard root s', whose keys the re-created tree maps to this shard's leaves (a different shard or virtual-slot count), and whose own re-created counterpart has not initialised or no longer exists, is refused only by s''s WAL-side floor (ReadPositionHonestRoutingWalIgnoresFloor, 15 states, WalLiveAdvanceRecreateCrossShard.cfg). In the model, SAlloc admits a straddler only at or above its initiator's entry and above its initiator's WAL-side floor (WithSecondInitiator adds the second shard root s2).

The rules that complete it:

  • The purge leaves the marker state uninitialised. A deleted marker is absent, and rule 2 holds the leaves until their marker state is initialised again. Read as closed, it releases a foreign write the open marker held (ReadPositionHonestRoutingPurgeKeepsMarkerInit, 13 states). A shard root activation that outlives the purge would still cache the old marker, which reads initialised, so it drops that cache when it re-seeds a purged tombstone (EnsureRootAsync).

  • The re-created incarnation's first initialisation is a fence. While the marker is uninitialised and the floor is above 0, EnsureRoutingGenerationSlowAsync seeds the floor plus one, drives the fence grain through ITreeRangeDeleteFenceGrain.EnsureInitialisedAsync (which seeds its floor plus one if it has no generation, claims everywhere and returns its heads), claims its own generation at every partition, and records the per-partition maximum of both head vectors as a close (token recreate:{floor}, the whole range), all before TryInitialiseHandOffMarkerAsync. Every step is idempotent, and a failure leaves the marker uninitialised. A tree whose floor is 0 has no straddler, so its initialisation claims nothing extra. The recorded heads place any straddler append made between the purge's WAL trim and the retirement below the point the leaves re-arm from. After a new-build purge the WAL-side floor alone refuses a later straddler, so the claim is not what refuses it there; after a 10.2.0 purge's catch-up (below) it is (ReadPositionHonestRoutingInitWithoutClaim, 16 states, WalLiveAdvanceRecreateLegacyPurge.cfg).

  • A write admitted at or below its initiator's floor is never re-stamped (#5705). A write admitted before the delete can still be in its shard root's seam retry when an immediate purge retires the rows. Its leaf re-presents the old generation, and the WAL floor refuses it. The retry would then reload the shard root's marker. If the purge deleted it, #5663's refusal-driven raise would re-create it at the floor plus one, because HandOffMarkerRows.UpdateAsync re-reads and writes an absent row rather than conflicting; if the re-created incarnation's marker already exists, the reload reads the floor plus one. Either way the write would be re-admitted under a generation the re-created incarnation shares, the #5641 shape for generations, and admitted above the heads its first initialisation recorded (ReadPositionHonestStraddlerRaiseRecreatesMarker, 18 states). In production (#5703):

    • Writes. NextRoutingRetryAsync, the one seam every shard-root retry loop calls, throws today's deleted-tree outcome (the existing InvalidOperationException) when the write's admitted generation is at or below floor[stale.Initiator], before any reload or raise. A live incarnation's generations are above its floor, so it never fires for one.
    • Marker writes, for the open and close paths, which carry no stamp. A shard root that has seen its marker row, and then finds it absent with floor[ShardRoot(i)] at or above the highest generation it saw, never re-creates it. With floor 0 it does: that is the lost-row case of #5663.

    In the model, StraddleRetry and SFail are that retry: the purged incarnation's pending write fails. The marker-write guard is not modelled separately, because the model has no purged-incarnation close.

A purge that finishes on 10.2.0 (#5697 review, S2; #5716). A 10.2.0 silo's purge knows none of these rows. It leaves each shard root's marker, initialised and at the purged incarnation's generation, the partition entries and the fence state, and raises no floor; its leaf clear also keeps the leaf's epoch row, so the re-created leaf claims above it. A new-build shard root re-creating the tree would otherwise adopt that marker: the same generation, its old closes, and no first-initialisation fence (ReadPositionHonestRoutingAdoptsPredatingMarker, 15 states). So re-seeding a purged tombstone runs a catch-up before the tombstone is lifted:

  • Identity, not inference (#5716). The marker carries the re-seed incarnation that seeded it, and the catch-up retires only a marker of another incarnation. Inferring "predates" from a generation above 0 or an initialised flag fails under a duplicate activation: a second activation re-seeding concurrently finds the marker the first has just seeded and run its init fence on, retires it, and raises the floor to its generation, while the first keeps stamping that cached generation, now at the floor. The WAL then refuses a live tree's claims and #5705's guard fails its writes as deleted (LiveGenerationAboveFloorCatchUpRetiresLiveMarker, 8 states).
  • The retirement. For a marker of another incarnation, the catch-up raises only its own shard root's floor over the marker's generation and entries, and resets the marker to generation 0, uninitialised, keeping its opens and closes. The first-initialisation fence then seeds the floor plus one, tags the marker with this incarnation and claims everywhere. The catch-up leaves the partition entries, and a running WAL shard keeps its in-memory floor until it reactivates, so on this path the fence's claim is what refuses a straddler of this shard root.
  • Per-initiator floors. A catch-up raises its own initiator's floor only. Another shard root may already have caught up and be live at its own floor plus one, below this marker's generation; a tree-wide raise would leave it at or below its floor, and the WAL would refuse its every claim (LiveGenerationAboveFloorCatchUpTreeWide, 7 states).

In the model, WithLegacyPurge makes every purge a 10.2.0 one (LegacyPurgeTreeRows); CatchUp is the first activation's run and CatchUpSkip a duplicate's that finds the marker this incarnation seeded. A re-created leaf arms only once its shard root has caught up, because it exists only after the re-seed. The residue below is not modelled.

Unmodelled mixed-version residue. Three cases remain outside the design's guarantee:

  • a re-seed run on a 10.2.0 silo, which runs no catch-up;
  • the range-delete fence state the purged incarnation left behind;
  • a cross-shard straddler spanning a 10.2.0 purge: a shard root's catch-up raises only its own initiator's floor, so another shard root's straddler is fenced only once that shard root re-seeds, which a re-created tree with fewer shards never does. Closing it would take cross-shard catch-up calls on every re-seed, against the cost directive.

For any of them to do harm, a straddler's seam retry must outlast its deadline across a gate close, the 10.2.0 purge settling, the re-creation and the gate reopening: the gate is closed while a 10.2.0 silo is present, so a write admitted in that window is unstamped and reported. The model excludes them: a cross-shard straddler does not span a 10.2.0 purge (LegacyPurgeTreeRows), and every re-seed is the new build's. Operators should not purge trees during a rolling upgrade from 10.2.0.

Shard-level marker. The moved slots of an adaptive split or a shard fold, and the leaves a range delete reaches, scatter across a shard's leaves, so a per-leaf marker would cost one call per leaf. A leaf reads its shard's marker fresh, after the last own append it would advance over, never from an earlier tick's cache. It reads it through a new interleaving, read-only shard-root call, GetHandOffMarkerAsync, which returns the marker's generation, open ranges and close heads. Read-only is load-bearing: this is a new leaf-to-shard-root wait-for edge, and a serial shard-root turn that calls the leaf must not be able to deadlock against it. The read costs one call per advance tick, not per write.

Saga terminals keep the leaf-wide prepare clamp (#5572): the advance holds on every partition while any prepare is pending.