Table of Contents

Trim and GC

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 trim-and-gc.md, and llms.txt lists every page.

Part of Write-Ahead Log.

The WAL grows monotonically and must be trimmed. Trim is driven by ILatticeWalGc, a per-tree single-pass collector that advances the per-partition trim watermark to the largest contiguous prefix that every registered consumer has already acknowledged.

The collector ships in Orleans.Lattice so single-cluster deployments that never call AddLatticeReplication(...) still get durable WAL maintenance. The predicate is expressed against min(cursor across registered consumers) - not min(cursor across remote peers) - so the local in-memory projection (the materialiser that rebuilds the leaf state from the WAL on activation) is just another consumer. A lagging materialiser pins the log exactly the same way a lagging remote peer does.

Predicate

A WAL entry is trim-eligible only when four independent clauses all accept it: the entitlement clause, the offset-reader clause, the causal-stable clause, and the blocked-floor clause.

The entitlement clause has two axes. On the HLC axis it is satisfied when either of the following holds:

Condition Meaning
entry.Timestamp <= minCursor Every registered consumer has reported a cursor at or beyond this entry's HLC.
entry.Timestamp <= ttlCeiling The entry's wall-clock component is older than now - WalRetention (when configured).

On the offset axis, when a durable materialiser offset floor is available, the floor admits every entry at or below it that no consumer outside the floor's population still needs, so an entry the HLC axis refuses can still be entitled on durable offset evidence alone. The floor can also refuse an entry that only the in-memory consumer cursor would admit, because that cursor tracks what a leaf folded into its cache rather than what it made durable. It never overrules the TTL ceiling, and a tree with no durable floor evaluates the HLC axis alone. A pass that cannot read the durable pin or offset census at all is not a tree with no durable floor: the floor is unknown, so the pass fails closed, trims nothing on any partition - TTL included - and retries on the next pass (issue #3576).

The causal-stable clause is satisfied when either of the following holds:

Condition Meaning
causalStable is null No consumer has reported a per-origin VersionVector through the causal+ overload of ReportCursorAsync. The clause degrades to a no-op so the GC behaves identically to the legacy HLC-only predicate.
causalStable.DominatesOrEquals(entry.VectorClock) Every consumer that reported a vector has fully observed the entry's causal predecessors. Entries with a null VectorClock (legacy peers, range deletes, pre-causal+ entries) are treated as the empty frontier and pass automatically.

The blocked-floor clause holds back every entry whose HLC is at or after the lowest buffer pin any consumer reports (see Consumer registration), so a buffering receiver can recover from its staging state; it is inert while no consumer reports a pin.

A fourth clause bounds the trim by the read position of every offset-reading consumer (issues #4579, #4584). The replication shipper and every materialised-view maintainer read each partition by offset, so the HLC cursor they report cannot hold the entries they have not read: a WAL partition is not HLC-ordered in offset (a silo whose clock trails, a merge that keeps its source stamp), so an unread entry can carry an HLC at or below a cursor already reported. That cursor is also visible only to the GC pass on the silo the consumer runs on, while every silo runs a pass. Each offset-reading consumer registers with the tree's durable consumer set before it reads the log. On every pass the GC asks each registered consumer for the lowest offset per partition it has not durably consumed, and refuses any entry at or above it. The consumer's own persisted position is the answer, so the bound holds on every silo and across a restart. This clause overrules the cursor arm and the materialiser offset admission, but not the TTL ceiling, which stays a bound: a consumer that falls behind it detects the trimmed gap on its next read. A registered consumer that has read nothing holds the whole log, and a member whose position cannot be read counts as position 0. Before the TTL ceiling trims an entry at or past a consumer's position, the pass durably records that consumer's saga decision-purge hold in the tree's WAL purge-hold coordination seam (issue #4534), so the transaction registry keeps every decision the consumer's peer may need to be re-seeded with; a failed hold write skips the trim, and so does a pass that cannot read the set of registered consumers at all. See Decision-purge holds.

An incremental backup capture is deliberately not an offset-reading consumer: the GC may trim past it, and the capture then falls back to a full backup. Its gap detection, like a view's, is exact by offset and made against what was actually read. The shared WAL subscriber probes the tail again whenever a read jumps an offset, so a trim that lands after its pre-read check is reported as a fall-off rather than read across. A jump the tail has not passed is a hole - a slot whose flush failed and was never acknowledged - and is read past. The tail is one past the shard's trim watermark, so a hole directly above a trim point is not mistaken for the trim (see Abandoned flushes, holes and the trim watermark).

The clauses are AND-ed: the cursor / TTL clause is kept for safety so a stale or mis-configured causal-stable computation cannot cause the GC to over-trim past a consumer that is still pinning the HLC half.

minCursor is the minimum HLC across all (treeName, consumerId) entries published to the IWalCursorRegistry. The cursor branch is gated on minCursor > HybridLogicalClock.Zero so range-delete entries (which carry HybridLogicalClock.Zero by design) are never trimmed under an unset / zero cursor.

ttlCeiling is the hard ceiling configured by LatticeOptions.WalRetention (mirrored from LatticeReplicationOptions.WalRetention on replicated trees). When set, a lagging consumer that pins the log past the ceiling is intentionally allowed to "fall off the log" so disk usage stays bounded; that consumer detects the gap on its next read and re-bootstraps via the fall-off-log path described in projection-rebuild.md.

The ceiling never overtakes a leaf materialiser. The scan stops at the durable materialiser offset floor before any arm is consulted, so the ceiling cannot trim past what a leaf has durably checkpointed or snapshotted. A partition named by a standing durable block pin admits nothing at all, from the ceiling or from any consumer cursor, whether or not the leaf is live (issue #4622). A block pin is a Zero frontier that the offset floor does not cover: a data-bearing leaf that has never checkpointed. Such a leaf replays from the "nothing applied" sentinel on a cold activation and could not detect a trimmed prefix. Any other leaf pin the offset floor does not cover caps the partition's ceiling at its frontier: that frontier was published by an empty release, when the leaf held no row there and had applied nothing, so every entry the leaf has since ticked for the partition is stamped above it, even though the pin store's monotone merge keeps the frontier after that write. A leaf publishes an empty release for a partition only after its activation's replay has latched (issue #4669). Until then every partition counts as data-bearing when the leaf resolves its pins, even one it holds no row in yet, so a checkpoint flush that runs part-way through the replay (pass 1 flushes incrementally, sweeping partitions in ascending backlog order) keeps the block on a partition it has not yet read, unless that partition's WAL is proven empty. A held or capped partition grows for as long as the hold stands; watch orleans.lattice.wal.gc.leaf_pin_hold_age (see Metrics).

Not every write a leaf appends is ticked by the leaf. A replicated apply, a replicated or idempotency-keyed range delete, a carried copy from a split, resize or reshard, and a compaction reap keep a stamp from elsewhere, and that stamp can sit below the frontier the leaf published for the partition. The merge can never lower the frontier, so the leaf raises an override hold instead (issue #4641). Before it appends a record stamped below its own clock, it durably records a hold for that partition's pin in the pin store, once per partition per activation. A shard root does the same for the leaves it touches before it appends a saga terminal stamped from an override. The GC reads a held pin whose offset is still the -1 sentinel exactly as a block pin, whether or not the leaf is live: the partition admits nothing, and the leaf is named to the blocked-leaf remedy, which drives it to a checkpoint and capture. The pin store drops the hold in the same write that lands the pin's first real offset, because from then on the offset floor stops the scan below every entry the leaf has not durably covered. A hold that cannot be made durable fails the write before it is appended.

Each pass reads every partition's head before it reads the holds, and it reads the holds before the offset floor, and it trims nothing past the head it read. A write appended after the holds were read was appended after its hold was raised, so it lies past that head; a hold the store dropped before the read was dropped for a real offset the floor then sees.

The scan is conservative: the first non-eligible entry per WAL partition stops the walk for that partition, as does the first entry above the partition's durable materialiser offset floor or at an offset-reading consumer's read position. WAL offsets are dense and append-only but HLC WallClockTicks is mostly-monotonic-with-skew, so a stop-at-first-miss walk preserves correctness while a more aggressive scan would risk trimming an entry younger than a still-pinned later entry.

Consumer registration

Every consumer of the change feed - the outbound replication ship loop, in-process bridges, custom transports, and the local in-memory materialiser - must publish its acked HLC to the registry so its progress contributes to minCursor. A consumer that never registers does not pin the log; the GC will trim under it and the consumer must detect the gap on the next read. A consumer that buffers entries it cannot apply yet also reports its lowest buffered HLC through the blockedAtHlc overloads of ReportCursorAsync; the lowest such pin across consumers is the blocked floor the predicate holds back.

// After successfully applying a batch acknowledged through `appliedHlc`,
// the consumer reports its progress. Subsequent reports must be
// monotonically non-decreasing per (treeName, consumerId).
await registry.ReportCursorAsync(
    treeName: "orders",
    consumerId: "peer:site-b",
    cursor: appliedHlc,
    cancellationToken: cancellationToken);

// On graceful shutdown the consumer unregisters so its stale cursor
// stops pinning the log.
await registry.UnregisterAsync("orders", "peer:site-b", cancellationToken);

AddLattice always registers both the default InMemoryWalCursorRegistry and a lightweight in-memory leaf cursor reporter, so the registry the GC and the saturation sampler read is never absent and every leaf publishes its applied frontier into it - the materialiser drain-lag back-pressure is live for every write workload out of the box, not only on materialiser / replication hosts. The registry is process-local and loses its state on silo restart. A host that needs cross-restart durability supplies its own IWalCursorRegistry implementation by passing a factory to AddWalCursorRegistry(factory), which replaces that in-memory default regardless of registration order. AddLatticeReplication(...) and the durable storage helpers call it without a factory instead, which keeps the in-memory registry and adds the durable-pin-aware leaf reporter described under Surviving a full restart.

Causal-stable frontier

A consumer that has stamped vector clocks on the entries it applies can also report its full per-origin frontier through the causal+ overload of ReportCursorAsync. The GC then computes causalStable as the pointwise minimum of every reported VersionVector: an origin is retained in the meet only when every reporting consumer has named it, and the value at that origin is the smallest HLC across the reports.

Consumers that only report HLC (the legacy overload) continue to pin the cursor half of the predicate but are excluded from the meet. When no consumer has reported a vector, causalStable is null and the GC behaves identically to the legacy HLC-only predicate.

The frontier is cached in the registry behind a per-tree generation counter that bumps on every accepted report or unregister, so a high-frequency GC pass that observes a stable registry reads the frontier in O(1).

A consumer registers a vector by passing the additional VersionVector argument:

await registry.ReportCursorAsync(
    treeName: "orders",
    consumerId: "peer:site-b",
    cursor: appliedHlc,
    vector: appliedFrontier,
    cancellationToken: cancellationToken);

The registry takes a defensive clone of the supplied vector, so callers may continue to mutate their local frontier after the report returns.

How the retention bounds interact

WAL retention is governed by three layered bounds. The GC only ever removes entries that all applicable bounds agree are safe to drop, so the effective trim frontier is whichever bound binds first.

Bound Knob Default What it caps Can it trim past a live consumer?
Consumer frontier (none - always on) always on The hard floor: min(cursor) across every registered consumer (overruled, where available, by the durable materialiser offset floor), intersected with the causal-stable frontier and held below the blocked floor. No. This is the durability invariant.
Wall-clock TTL WalRetention null (disabled) Entries older than now - WalRetention fall off the log even if a consumer still pins them. Yes - this is the only bound that does.
Advisory byte ceiling WalMaxRetainedBytes null (disabled) Schedules byte-pressure trim work when the WAL's on-disk occupancy - physical bytes, dead bytes not yet compacted included, or the retained payload for a provider that cannot report physical size - exceeds the ceiling, but only within the consumer frontier. No - it surfaces an over-threshold signal instead.

WalBytePressureReclaimTarget (default 0.8) is not itself a bound: it is the low-water hysteresis fraction of WalMaxRetainedBytes that disarms the byte-pressure policy once a trim has reclaimed enough, so a tree hovering near the ceiling is not trimmed on every pass. It is inert unless WalMaxRetainedBytes is set.

WalMaxRetainedBytes also accepts a per-tree override set at runtime (issue #3333). The silo-wide option is the default for every tree; a single tree can pin its own ceiling through lattice_treeadmin_tree_set_config (applyWalMaxRetainedBytes), which is persisted on the tree's registry entry and re-read on every GC pass, so it takes effect on that tree's next pass with no silo restart. Passing null clears the override. Because the ceiling is advisory in both forms, an override can never trim past the consumer frontier and so cannot lose data - it only moves where byte-pressure trimming and the cadence floor engage. See Configuration.

Production caution - set at least one absolute cap. With every knob at its default (WalRetention = null, WalMaxRetainedBytes = null), the only active bound is the consumer frontier. The WAL shrinks as consumers catch up, but a permanently lagging or dead consumer pins the log and grows it without limit - the advisory byte ceiling deliberately will not rescue you, because it never trims past a live cursor. WalRetention is the only knob that trims past a stuck consumer, so any deployment where unbounded growth is unacceptable should set WalRetention (a wall-clock floor on consumer lag) and, where a hard size budget matters, WalMaxRetainedBytes as well. A consumer that falls off the log re-bootstraps via the fall-off-log path in projection-rebuild.md.

Scheduling

Formal model. WalGcStarvationDrive models the shared drive budget, frozen per-pass order, timer reservation, refusal accounting, re-arm and turn occupancy. Admission progress assumes returned physical capacity, a stable undeleted tree and recurring GC/runtime opportunities. Floor advancement additionally requires timely durable progress within the drive budget: replay must earn and bank checkpoint/coverage/pin progress before expiry; eventual storage completion alone is insufficient. Returning the outer drive permit does not itself lift the floor or end shared cold replay. The finite instance assumes finite timer competition and finite WAL append, not arbitrary ongoing load. Timer dispatch returns the grain turn independently of drive completion. These runtime opportunities and storage premises do not establish a wall-clock latency bound or fairness from jitter.

ILatticeWalGc.RunOnceAsync(treeName) is a single-pass GC invocation.

The core library ships a per-silo background scheduler that drives this pass for every registered tree. It is registered by AddLatticeWalGc, which the shipped durable WAL storage packages and AddLatticeReplication call for you, so a durable-WAL host gets bounded WAL retention out of the box - including for non-replicated trees - and WalRetention is effective with no extra wiring.

The cadence is adaptive and per tree. Each tree's interval moves inside the band [WalGcMinInterval, WalGcInterval] (30 seconds to 1 hour by default). A pass that trims at least one entry snaps that tree back to the floor, so a growing log keeps being collected; a pass that reclaims nothing doubles the tree's interval towards the ceiling, so a quiet tree relaxes and costs little. A tree whose pass reports blocked or over_ceiling is held at the floor, and one that reclaims nothing while its scan still stops on WAL it must retain relaxes no further than five minutes (clamped into the band); see WalGcMinInterval for the full rule. A pass is retention housekeeping, not a latency-sensitive operation - its cost scales with trees x WalPartitions storage reads and runs on every silo - which is why the quiet-path ceiling is deliberately coarse. A host that needs a tighter disk bound - a high write rate paired with a small WalRetention - can lower it; set WalGcInterval to TimeSpan.Zero (or any non-positive value) to disable the built-in scheduler and let the host own the cadence (an admin trigger, an Orleans reminder, or - for replicated trees - the replication package's per-tree maintenance grain).

The first pass is not run at silo start; it is staggered by a random offset in [WalGcStartupDelay / 2, WalGcStartupDelay) - 15 to 30 seconds by default, capped at WalGcInterval. That lets the silo finish activating before the scheduler adds scan/trim I/O, and de-correlates the first pass across silos so a rolling cluster restart does not align every silo's full-tree fan-out into a correlated I/O storm.

// Tighten the built-in scheduler on a high-write host, or disable it.
siloBuilder.ConfigureLattice(o => o.WalGcInterval = TimeSpan.FromMinutes(5));
siloBuilder.ConfigureLattice(o => o.WalGcInterval = TimeSpan.Zero); // disable

A pass whose cursor floor is held by dormant leaves also drives those leaves forward: when an unusable durable pin blocks the floor, or a dormant pin the scheduler can repair holds it, the scheduler touches the leaves behind those pins in a bounded reactivation sweep so their checkpoints, and with them the floor, can advance. The sweep's drives share the per-silo WAL replay permits with leaf activations; see Starvation-drive admission for how a pass sizes its fan-out to that share and what a refused drive costs. The two cases log differently (#3613). A blocked floor's warnings say the cursor floor is blocked and the WAL stays retained. A repair of a dormant pin holding a usable floor logs once per episode, naming the holding consumer, its partition and offset; its give-up warning states that the floor reports usable, so the tree is not retaining without bound, and its episode-end message counts the holders it drove instead of reporting a block that cleared. A deleted tree is the exception: before a pass touches leaves to heal its floor, the scheduler reads the tree's deletion state, and it never reactivates a deleted tree's leaves. It retires any pin still held against a discarded copy - an undone resize's destination, whose discard trims the copy's log itself - and leaves any other deleted tree's floor where its pins hold it; see Discarding an undone resize's copy.

The scheduler composes with the replication maintenance grain: RunOnceAsync and the underlying IWalStorageProvider.TrimAsync are idempotent, and the pass never trims past the minimum consumer cursor or the leaf-materialiser checkpoint floor, so a tree collected by both drivers is trimmed safely and it never over-trims. To drive a single pass manually instead (or in addition), call RunOnceAsync directly:

LatticeWalGcReport report = await gc.RunOnceAsync(
    treeName: "orders",
    cancellationToken: cancellationToken);

// The report exposes the inputs and the outcome:
//   - report.TreeName        - the tree the pass targeted
//   - report.MinCursor       - minimum cursor across registered consumers, or null
//   - report.TtlCeilingHlc   - TTL ceiling synthesised from WalRetention, or null
//   - report.CausalStable    - pointwise-min VersionVector across consumers, or null
//   - report.BlockedFloor    - lowest buffer pin across consumers, or null
//   - report.ShardsScanned   - WAL partitions whose provider resolved and were
//                              visited; zero means none could be, not an empty WAL
//   - report.EntriesTrimmed  - total entries the pass found eligible and asked the
//                              provider to trim, across all partitions
//   - report.ByteCeiling, RetainedBytesBefore, RetainedBytesAfter,
//     LogicalRetainedBytes, BytePressureTriggered, BytePressureOverThreshold,
//     CeilingUnsatisfiable - the advisory byte-pressure inputs and verdicts
//   - report.CursorFloorState, BlockingConsumerId, BlockingConsumerIds - whether
//     the cursor floor was usable, and which consumers blocked it
//   - report.RetainedBacklog - whether a partition's scan stopped on WAL it had to retain

Reclamation floor-holder read

ILatticeWalReclamation.GetWalReclamationAsync(treeId) is the public read for a tree whose WAL usage is flat and whose reclamation might be idle or wedged. The MCP tool is lattice_treeadmin_wal_reclamation. The report echoes the tree id as the caller named it, but the probe reads the physical tree that alias resolution currently targets, because materialiser pins are published under the physical copy a leaf belongs to.

PinStoreReadable = false means the durable pin store did not answer; the other fields are not measurements, and IsWedged = false means "not established", not "healthy". When the store answers, PinCount counts the materialiser pins and PinsWithoutOffset counts the pins still at the -1 no-offset sentinel. The FloorHolder, when present, is the pin with the lowest usable offset; if no pin has a usable offset it is one of the -1 pins, and if the tree has no pins it is null. The holder carries its consumer id, parsed leaf id when available, WAL partition, pin offset, persisted checkpoint, and state. The state is one of CheckpointedUncovered, NeverCheckpointed, NoDurableState, Unreadable, Orphaned, or CheckpointedCoverageUnknown.

IsWedged is keyed on that holder, not on WAL growth: it is true exactly when the holder has a usable offset (PinOffset >= 0) and its persisted checkpoint is still -1 (NeverCheckpointed). That shape will not clear on its own because the durable pin store merges pins upward and the GC will not drive a leaf with no proven checkpoint. The same NeverCheckpointed state on a holder at offset -1 is the benign sentinel that clears when the leaf checkpoints.

Metrics

The GC and its scheduler publish a family of instruments on the orleans.lattice meter, all catalogued in Metrics. The ones to start from:

Instrument Tags Description
orleans.lattice.wal.entries_trimmed tree, shard Counter. WAL entries removed by a GC pass, reported once per WAL partition the pass scanned. The tag is named shard for compatibility but its value is a WAL partition index. A partition that was scanned but reclaimed nothing records a zero, so an absent series means the partition was not scanned on this silo.
orleans.lattice.wal.gc.passes tree, outcome Counter. One count per scheduled pass, by outcome: reclaimed, blocked, no_consumer, no_partitions, idle, over_ceiling, stranded, unclassified or failed. Only reclaimed states that WAL came back; every other arm says why nothing was trimmed. no_partitions means no pinned WAL provider resolved on this silo (issue #2465), not an empty WAL. It outranks the other non-reclaiming arms and is zero-primed per tree. Inspect WAL placement and provider registration. ShardsScanned counts only resolved partitions visited for trimming or compaction; partial resolution keeps the existing outcome and does not imply every partition was examined. With no cursor and no TTL, no_consumer names the no-predicate return; blocked names an unusable durable pin, while stranded can describe a legitimate lagging consumer holding retained WAL.
orleans.lattice.wal.gc.interval tree Histogram (seconds). The adaptive interval the scheduler chose for the tree after its latest pass. A series pinned at WalGcMinInterval is a tree the scheduler is holding at the floor - reclaiming, blocked, or over its byte ceiling.
orleans.lattice.wal.gc.trim_stop tree, shard, reason Counter. Why each WAL partition's trim scan stopped: exhausted, empty, offset_floor, cursor_floor, causal_frontier, block_pin, durability_unverified, durability_hold or durable_offset_refusal. The shard tag carries the WAL partition index.

The floor-holder diagnostics explain why a retained floor did or did not enter a repair drive. orleans.lattice.wal.gc.floor_holder_admission is tagged by tree, tenant and status; admitted means the floor-defining candidate entered the blocked-leaf drive, blocked means the floor's own holder could not be admitted, and unreached means the pass exited through the floor-blocked heal arm before the floor-holder classifier ran. orleans.lattice.wal.gc.never_checkpointed_pin_offset splits NeverCheckpointed holders into offset_absent (the benign -1 pin sentinel) and offset_usable (the wedging shape that can hold the offset floor), tagged by tree, WAL partition, status and tenant; both arms are zero-primed for evaluated trees.

Offset-floor repair admission is partition-local: offsets from different WAL partitions are not comparable. The scheduler keeps a bounded ascending candidate sample for each resolved partition and compares candidates with that partition's own floor. A partition retains enough candidates to fill one distinct-leaf drive pass; measured populations share any larger tree budget proportionally. Before the first population measurement, the initial per-partition cap uses the registry-pinned partition count. The aggregate offset sample is bounded by the larger of the tree candidate budget and the active partition count times the per-pass touch budget. An above-floor candidate is prefetched only after its own partition's floor holder was admitted.

Orphan-pin removal has its own decision counters. orleans.lattice.wal.gc.orphan_pin_sweep partitions each examined durable pin into retired, retire_failed, deferred, refused_malformed_id, refused_ambiguous_partition, live, unresolved or unreadable; the decision arms also carry a cause of orphaned or no_durable_state. orleans.lattice.wal.gc.drive_orphan_pin_retirement records the same removal/refusal outcomes when the blocked-leaf drive reports that it could not drive a leaf, with cause="not_driven". Both routes remove only through the pin grain's fence (issue #5358): each key's retirement token is taken before its pins are read, and a removal is refused when the consumer was merged since - as a leaf re-created under the same grain id does when it seeds its block pin. A refused removal counts as retire_failed, and the next sweep re-examines the pin against a fresh read.

Two further GC signals separate a tree that is catching up from one that is stuck (issue #3149). orleans.lattice.wal.gc.floor_head_distance records, for each WAL partition a pass scanned, how many offsets lie from the first entry the scan had to retain through the partition's newest entry - zero when the scan released everything it was offered - and orleans.lattice.wal.gc.terminal_breach counts each pass of a tree that has been over its byte ceiling, with a usable cursor floor, reclaiming nothing, for ten consecutive passes, the point at which over_ceiling has stopped being a transient.