EntitlementLedger

The replicated, conflict-free tally of who was granted what fairness entitlement, who passed it down, and who spent it.

It is the one genuinely-new CRDT of the fair-share layer: a BoundedCounter grown a path dimension. Where a bounded counter escrows one shared budget across replicas, this escrows a whole tree of budgets — indexed by the edge each grant crossed — and every peer can merge its copy with any other and always agree, with no clock and no central referee.

What you can do with it

Construct and merge ledger states (via ZERO and bootstrap, or the internal test factory) — the merge (piece) is a provable join-semilattice — and drive the economics on top of it: holdings (derived spendable authority), the conserving mutators mint / delegate / release / transfer / spend (each returning a Patch or null when holdings are insufficient), and validate (the integrity report).

Safety vs. diagnostics

Safety is the local holdings check each mutator runs on the actor's own complete state before it emits a patch — a peer never spends beyond holdings(P, self), with zero coordination, because every term of that check reads a slot only that peer writes. validate is a diagnostic, not a safety gate. It is eventually consistent: on a fully-delivered state its report is exact, but under partial delivery of a multi-hop transfer-funded charge it may transiently list a false LedgerConflict.PerEdgeSafety / LedgerConflict.PersistentNegativeHoldings that a later anti-entropy round dissolves. Each feasibility-consuming mutator carries a witness that keeps the direct and single-hop base-transfer cases from false-firing; deeper transfer chains — and a carried hand-off at any depth, which the witness does not copy (#2594) — are the accepted transient. Consumers must not hard-gate on validate().isEmpty() while rebalancing is in flight — gate on the mutator's null.

One root per ledger (structural, plus a diagnostic)

A ledger describes one tree, with exactly one root: the group bootstrap was called with. holdings credits a group's creditIn from the minted supply whenever that group has no inbound edge — and every MintRecord is bound to the root it was minted at (#1751), so a rootless group is credited only the mints naming it. Merging two independently-bootstrapped ledgers therefore leaves each root holding its own supply and Σ holdings still equal to mintedTotal: the double count is unrepresentable, not merely undetected.

Doing it is still a caller mistake — one ledger, one tree — so validate reports LedgerConflict.MultipleRoots when the merged state carries mints at more than one root. That is defence in depth over an already-structural guarantee, not the guarantee itself.

Delta-state idiom: two patches from one base lose the first

Every mutator reads the receiver and returns a patch carrying absolute slot values, and the join is max. Two patches computed from the same base therefore do not compose — the merge keeps the larger and silently drops the other:

val a = ledger.delegate(r, e, 10)!!   // issued(e)[r] = 10
val b = ledger.delegate(r, e, 5)!! // issued(e)[r] = 5 ← also read from `ledger`
ledger.piece(a).piece(b) // issued(e)[r] = 10, NOT 15

That is the price of absolute-value deltas, and it is what buys duplicate-delivery idempotence — but it means a caller must thread the state: call each mutator on a ledger that has already absorbed the previous patch, never fan several out from one snapshot. HeddleNode does this by running each op inside its Quilter.mutate block, so the op always sees fresh state.

Lifecycle (H2)

Each edge carries a Lifecycle in a per-edge max-register (PREPARED < ACTIVE < CLOSING < RETIRED, join = max). The transitions prepare / activate / close / retire climb that chain under strict generation-and-drain discipline (design §5.3): close admits no new delegation, retire finalizes only a fully drained edge (outstanding == 0): a closing one, or a prepared one nothing has crossed. An edge present without an explicit register entry defaults to Lifecycle.ACTIVE — the H1b "present edge is ACTIVE" assumption, now made explicit rather than assumed. Delegation is gated on Lifecycle.ACTIVE, and two Lifecycle.ACTIVE inbound generations for one child surface as LedgerConflict.DualActiveInbound with the contested lineage quarantined (§5.2, §10.11).

The representation

Sixteen components, each already a join-semilattice, so piece is just their componentwise join (the product-of-lattices idiom), and a seventeenth, forgotten, that is not (see Forgetting below):

  • records — the immutable topology (parent/child/weight per edge) as a grow-only set of records per edge id. A healthy id carries a singleton set; two divergent records under one id are both retained (never collapsed by a last-writer-wins on a parent pointer, which §5.2 forbids) so a later phase's validate can report the divergence.

  • minted — root supply, keyed by a unique MintId so mints union rather than collide.

  • issued / returned / leafSpent / rollupSpent — per-edge monotone GCounters. Every (edge, replica) slot is written exclusively by that replica, so the merge is per-slot max and no honest concurrency can race.

  • transfers — peer-to-peer hand-offs at a path, a per-donor-row matrix keyed by PathKey; the row for a donor is written only by that donor.

  • the relocation counters — issuedRelocIn, leafRelocIn/leafRelocOut, rollupRelocIn/rollupRelocOut, and the row matrices transferRelocIn/transferRelocOut, described next.

  • gauges — the per-edge virtual-time seat register (Gauge), joined componentwise max. This is the only multi-writer per-edge component: unlike a counter slot, which exactly one replica writes, any peer may assert a position for any edge. The pairing of each position with the issuance its writer observed is what makes that safe under an order-free join — see Gauge and grossVirtualService.

The spent split (leafSpent vs rollupSpent) is the load-bearing choice: a completed charge on a leaf path charges the leaf's own final edge in leafSpent and every strict-prefix edge in rollupSpent, which keeps the conservation identity topology-independent even when a former leaf later gains a child.

All three lattice laws (idempotent, commutative, associative) hold by construction, and duplicate or reordered delivery of any patch is absorbed idempotently by the counters' max — convergence comes from the lattice, not from event ids.

Relocation counters — a net decrease without a decrement (#1665 slice 1)

A generation is sometimes retired with entitlement still riding on it (the advisory-retire race), and making the child whole means moving an already-recorded quantity from the dead edge onto the live one. A grow-only GCounter cannot be decreased, so the move rides a second monotone counter that cancels the first — the PNCounter idiom, applied per-edge-per-slot:

effIssued(e)[r]      = issued(e)[r]      + issuedRelocIn(e)[r]
effLeafSpent(e)[r] = leafSpent(e)[r] + leafRelocIn(e)[r] − leafRelocOut(e)[r]
effRollupSpent(e)[r] = rollupSpent(e)[r] + rollupRelocIn(e)[r] − rollupRelocOut(e)[r]
effTransfer(k)[s][r] = transfers(k)[s][r] + transferRelocIn(k)[s][r] − transferRelocOut(k)[s][r]

Every stored component still only grows; the effective value is derived and may fall, exactly as outstanding/holdings already do. There is no issuedRelocOut — issuance is never net-decreased. Because the new families are ordinary GCounter maps joined componentwise, piece stays idempotent/commutative/associative by the same product-of-lattices argument that already covers the base eight; adding them makes the CRDT strictly larger, not structurally different.

The transfer pair (issue #2366) exists because a hand-off is keyed by the generation that carried it, so a generation move has to move it too — and the pocket it belongs to is only right if all three of its terms (net inflow, charged service, hand-offs) move together. Unlike the counter pair it is symmetric in neither direction and its Out half is mandatory: the dead key's rows must read zero afterwards, or a second Reconcile carries them a second time. See relocationPatch.

Slot ownership is what makes this sound. The base counters on a live edge belong to the data plane — replica r writes its own slot, and only ever a value it derived locally. The relocation counters belong to the control plane exclusively (log apply); the data plane never touches them. So a re-home adds its credit to issuedRelocIn(t)[r] rather than fabricating an absolute on the contended base issued(t)[r] that r's own delegate writes concurrently — two writers on one max-joined slot would silently erase one side, with conservation and per-edge safety blind to the loss.

Spend relocation rides the quiesce fence (#1693). Moving an already-charged spend drains the dead edge to zero headroom, so one straggler charge afterwards would leave a permanently unclearable per-edge-safety violation. What makes it safe is that the move's magnitude is derived from log-recorded per-peer promises rather than any peer's gossip view — see relocationPatch and ControlCommand.Quiesce.

Equal ledgers encode to equal bytes

piece builds its maps through a HashMap (or takes one side's map as it is) and its record sets with +, so iteration order follows the merge history. A Quilter hashes this encoding for its anti-entropy root, and two peers whose bytes differ would ship the whole ledger to each other on every round, so every unordered field, at every level, goes through a canonical serializer. A new field must too, and it needs its own arm in EntitlementLedgerCanonicalEncodingTest, since no test reds on a field it never writes.

Its encoded shape is also part of LocalHeddleSnapshot's format 1: a field added here takes a default, and any other change needs a frozen surrogate there first.

Forgetting (#3192, design §5.5)

A retired edge stays in the books for good, because the work done under it still counts, so a group whose children come and go grows without bound. The internal forget drops a retired leaf edge's slots from the sixteen components and folds what they added up to into the seventeenth, forgotten: holdings, leafSpentTotal, the generation floor and the "has child edges" test read the fold beside the live edges, so each answers as it did before.

Forgetting removes slots, so it is not a join, and it breaks §10 invariant 2 (monotonicity). It is scoped to a single writer, as invariant 4's quiesced edge is: LocalHeddle is its only caller, and piece throws rather than take a fold that is not the receiver's own, or accept from a ledger that never forgot an edge numbered at or below the floor of the one that did. A replicated ledger never holds a fold, and :kuilt-heddle refuses one at decode. Forgetting between peers is open (#3332).

Samples

val root = GroupId("root")
val alice = ReplicaId("alice")
val bob = ReplicaId("bob")

// The same mint act (same nonce) observed independently on two peers.
val onAlice = EntitlementLedger.bootstrap(root, mapOf(alice to 100L, bob to 100L), nonce = "genesis")
val onBob = EntitlementLedger.bootstrap(root, mapOf(alice to 100L, bob to 100L), nonce = "genesis")

// Merging is idempotent, commutative, and associative — either order agrees.
check(onAlice.piece(onBob) == onBob.piece(onAlice))

// Reading one edge's summary is a pure projection (null here — no edges minted yet).
check(onAlice.edge(AttachmentId("acme")) == null)
val root = GroupId("root")
val leaf = GroupId("leaf")
val alice = ReplicaId("alice")
val e = AttachmentId("root→leaf")

var ledger = EntitlementLedger.bootstrap(root, mapOf(alice to 100L), nonce = "genesis")
// prepare then activate the edge, then delegate 10 units down it.
ledger = ledger.piece(checkNotNull(ledger.prepare(AttachmentRecord(e, root, leaf, Weight.ONE))))
ledger = ledger.piece(checkNotNull(ledger.activate(e)))
ledger = ledger.piece(checkNotNull(ledger.delegate(alice, e, 10L)))

// Close the edge, then try to retire it while entitlement is still outstanding — refused.
ledger = ledger.piece(checkNotNull(ledger.close(e)))
check(ledger.retire(e) == null) // 10 units still outstanding

// Drain it (return the grant), then retire succeeds; the register now reads RETIRED.
ledger = ledger.piece(checkNotNull(ledger.release(alice, e, 10L)))
ledger = ledger.piece(checkNotNull(ledger.retire(e)))
check(ledger.lifecycle(e) == Lifecycle.RETIRED)

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard

Promote edge to Lifecycle.ACTIVE — delegation across it is now admitted (design §5.3). null if edge is unknown/divergent, or already Lifecycle.CLOSING/Lifecycle.RETIRED (a closing edge cannot be resurrected — closure dominance, §10.10). Idempotent from prepared/active.

Link copied to clipboard

Whether activating edge on this ledger keeps its parent's active children inside the weight budget: true when LocalHeddle.apply would let the activation through on budget grounds, false when it would refuse it as over budget.

Link copied to clipboard

Summaries of every Lifecycle.ACTIVE edge whose parent is parent, in a deterministic order (by AttachmentId). Non-active generations (prepared, closing, retired) are excluded — this is the parent-facing scheduling view, and only active edges are candidates. An edge counts if any record under its id names parent and its lifecycle is active — divergent records are retained, not collapsed, and their reconciliation is a later concern.

Link copied to clipboard

r's own base slots on edge — its ControlCommand.QuiesceAck payload.

Link copied to clipboard

id's base issuance — Σ_r issued(id)[r], excluding relocation credit. This is the Gauge's fold axis: the read advances the gauge's position by (baseIssuance − folded) units of the edge's own service. It is published so a consumer can relate a gauge's Gauge.folded to the issuance it has seen since, for diagnostics; grossVirtualService and virtualService are the reads that interpret the register. edge's EdgeSummary.issued is the effective value, which deliberately is not this.

Link copied to clipboard

transferRelocIn − transferRelocOut for one hand-off at edge — the residual unackedCarriedDonors filters on. HeddleInternalApi, test support.

Link copied to clipboard
open fun causalDots(): Set<Dot>
Link copied to clipboard
Link copied to clipboard

Promote edge to Lifecycle.CLOSING — no new delegation is admitted, but spend and release still drain it (design §5.3). null if edge is unknown/divergent, or already Lifecycle.RETIRED. Idempotent from closing.

Link copied to clipboard

r delegates amount down edge, moving authority from the parent group into the child. null if:

Link copied to clipboard

edge's drain witness — its counter slots at their observed absolute values — read from this (the proposer's) state so the H5 control plane can carry it in a governed Retire command. Governed retire applies against a topology-only projection whose counters are empty, so without this the published RETIRED patch would carry no witness and a laggard that received RETIRED before the draining release/spend deltas would transiently false-fire LedgerConflict.ClosureViolation. Carrying the proposer's observed witness ships the drained counters alongside RETIRED (§5.1, §10.10). HeddleInternalApi — control-plane support.

Link copied to clipboard

The parent-facing EdgeSummary for id, or null if the edge is entirely unknown to this ledger. Reported at effective values (base ± relocation, see the class KDoc), so an edge that received a re-homed generation reads the credit it now carries and a drained one reads zero outstanding. spent is the total charged through the edge — effective leafSpent + rollupSpent.

Link copied to clipboard

r's effective issuance across edge — issued + issuedRelocIn. HeddleInternalApi, test support.

Link copied to clipboard
open operator override fun equals(other: Any?): Boolean

Structural equality over every lattice component.

Link copied to clipboard

id's stored virtual-time Gauge, or null when the edge carries none — either it has never been seated, or this view is simply missing the patch that seated it. The two are indistinguishable here on purpose: absence is the seat-bump predicate (see Gauge), and it is a local read, so a peer that has not seen the seat may re-seat from its own front. That is safe precisely because its bump folds its own observed issuance.

Link copied to clipboard

id's gross virtual service — the Gauge's position advanced by (baseIssued − folded) units, over G · w, or baseIssued / w when no gauge is stored, read on the edge's 1/16-unit grid (grossVirtualServiceAt, #3313, #3353). null if id is unknown or divergent (no single record ⇒ no single weight to divide by).

Link copied to clipboard

grossVirtualService as a VirtualTime, exact: never held at a ceiling, never thrown on how far the edge has run (design §7.1). null if id is unknown or divergent.

Link copied to clipboard

Whether this ledger has forgotten anything: true once a retired edge has been folded away into the ledger's forgotten totals, false while every edge it ever held is still kept whole.

Link copied to clipboard
open override fun hashCode(): Int
Link copied to clipboard
fun holdings(group: GroupId, r: ReplicaId): Long

The units r may spend at group, derived from the merged state:

Link copied to clipboard
fun isLeaf(group: GroupId): Boolean

True when group has no Lifecycle.ACTIVE child edge (design §5.2: "leaves have no active outbound edges"). These are the only groups at which spend may charge service. Exactly when this is false, activeChildren is non-empty and the allocator can hand group's holdings down. So no group's holdings are usable both ways, and this predicate never refuses a group the allocator does not descend into. (spend can still refuse one for other reasons: the root has no edge to charge, and a quarantined lineage holds nothing.)

Link copied to clipboard

The edge ids carrying a base issued slot — the control plane's reconciliation witness-shape gate.

Link copied to clipboard

The edge ids carrying an issuedRelocIn slot — where a re-home's credit legally lands.

Link copied to clipboard

Total service charged where an edge is a path's final edge (the conservation term), at effective values — a relocation moves leaf spend between edges in equal and opposite amounts, so this sum is invariant under any move. The leaf spend of every forgotten edge is in it too, folded, so it is invariant under forgetting as well.

Link copied to clipboard

The Lifecycle of id, or null if id is entirely unknown to this ledger. A known edge with no explicit register entry reads as Lifecycle.ACTIVE (the H1b default); the transitions prepare / activate / close / retire write the register explicitly.

Link copied to clipboard

The live entitlement path from the root down to group's inbound edge, in root→group order (empty when group is the root), or null if the lineage is quarantined (a divergent record, two live inbound edges, no live path to the root, or a cycle — see holdings/validate). A caller that must charge service against a captured path (design §4.4) reads this at reservation time, while the topology is valid, and later hands the captured list to spendCaptured.

Link copied to clipboard

The live inbound edges of child — every non-divergent edge whose record targets child and whose lifecycle is Lifecycle.ACTIVE or Lifecycle.CLOSING (a still-draining closing edge counts; it can carry entitlement). Sorted by id so every peer folds the same order.

Link copied to clipboard
fun mint(mintId: MintId, root: GroupId, holder: ReplicaId, amount: Long): Patch<EntitlementLedger>

Introduce root supply at root: credit holder with amount units under mintId. Control-plane only (design §9); the one non-conserving op and the only mutator with no feasibility gate, so it never returns null. mintId MUST be unique per mint act so distinct acts union rather than max-collide (design fix 4).

Link copied to clipboard

The distinct groups supply has been minted at, sorted by id: the roots of the trees this ledger funds. One on a healthy ledger, and empty before the first mint. More than one is the LedgerConflict.MultipleRoots fault (#1751), so a caller about to mint can ask it first rather than learn of the fault afterwards.

Link copied to clipboard

Total minted supply.

Link copied to clipboard
fun origin(parent: GroupId): Int128

Zero, for every parent. 0.7.5 kept an origin per parent, raised by a rebase. Nothing rebases now and no ledger holds one (design §7.1, step B): a position is absolute, and a 0.7.5 ledger is read with each origin translated into its children's positions. Kept because 0.7.5 published it.

Link copied to clipboard
open override fun piece(other: EntitlementLedger): EntitlementLedger

The join: the componentwise least-upper-bound of this and other.

Link copied to clipboard

Introduce a new attachment generation: record record and mark its edge Lifecycle.PREPARED (design §5.3 create). null if the edge id is already known to this ledger — each generation is prepared exactly once; changing a weight or parent mints a new id, never re-preparing an old one. No entitlement may cross a prepared edge until activate.

Link copied to clipboard

The sub-ledger restricted to id's own components (plus its path's transfer rows). Pins the projection homomorphism (design §10.8): restriction to an edge's components commutes with piece. HeddleInternalApi — test support.

Link copied to clipboard

The single AttachmentRecord for id — its parent, child and weight — or null if id is unknown or divergent (two conflicting records under one id, which a healthy ledger never has; see validate). The parent-facing read a scheduler pairs with edge's EdgeSummary to build a policy input.

Link copied to clipboard

r returns amount of unused entitlement up edge, restoring the parent's holdings. null if:

Link copied to clipboard

The §4 generation-move: drain each fenced retired edge in finals and re-home everything it carried — net inflow and already-charged service — onto the child's live inbound liveEdge (relocation design §4, issue #1665 slice 3 / #1693). This is the conserving recovery for the advisory-retire race, and it is pure: acked finals in, patch out.

Link copied to clipboard

Finalize a drained edge: promote edge to Lifecycle.RETIRED (design §5.3). null unless edge is currently Lifecycle.CLOSING and fully drained (EdgeSummary.outstanding == 0, i.e. every delegated unit has been returned or spent). This is the drain gate: a retire is refused while entitlement is still outstanding across the edge. Once retired, nothing crosses again and its history stays queryable via edge forever.

Link copied to clipboard

The RETIRED inbound edges of child — every non-divergent edge whose record targets child and whose lifecycle is Lifecycle.RETIRED. These are the edges a raced advisory-retire may have stranded budget on (reconcileStranded); the H5 control plane reads it on its log-pure projection to gate a reconciliation witness (§9 #3, §5.4). HeddleInternalApi — control-plane + test support.

Link copied to clipboard

Seat edge at front — write its first Gauge, keyed on gauge absence.

seat at a VirtualTime front, ⌈V · w · G⌉ on the edge's own grid (design §7.1). null as seat answers it, and null too when that seat would pass the position limit, where no child lands.

Link copied to clipboard
fun spend(r: ReplicaId, group: GroupId, amount: Long): Patch<EntitlementLedger>?

Charge amount of completed service by r at leaf group. requires group is a leaf; null if r's holdings there are insufficient. Charges leafSpent(inbound(group))[r] and rollupSpent(e)[r] for every strict-prefix edge e — one atomic patch keeping per-edge outstanding correct at every level (design fix 1). amount 0 is a no-op cancel.

Link copied to clipboard

Charge amount of completed service by r against a path captured earlier (design §4.4 / §10.4: "charge every edge of the path captured at reservation; history never moves to a newer generation"). Unlike spend, this does not recompute the lineage or re-check isLeaf/holdings from the current topology — it charges the exact capturedPath edges directly: leafSpent on the captured final edge and rollupSpent on every captured strict-prefix edge.

Link copied to clipboard

The raw stored slot value of one counter family at (edge, r). Every family is grow-only, so this value never falls under piece — the property the lattice rests on, and the one the derived effective reads deliberately do not have. HeddleInternalApi, test support.

Link copied to clipboard
open override fun toString(): String
Link copied to clipboard
fun transfer(group: GroupId, from: ReplicaId, to: ReplicaId, amount: Long): Patch<EntitlementLedger>?

Move amount of holdings at group from peer from to peer to — same lineage, different pocket (design §4.3, verbatim BoundedCounter.transfer). null if from's holdings at group are insufficient. Appends to from's own transfer row.

Link copied to clipboard

The donor rows recorded at path (empty if none) — HeddleInternalApi, test support.

Link copied to clipboard

The integrity faults derivable from this merged state, in one canonical order (identical on every replica). This is an eventually-consistent diagnostic, not a safety gate — safety is the local holdings check in the mutators. On a fully-delivered state the report is exact; the per-patch witness keeps the direct and single-hop base-transfer cases honest under partial delivery, but a partially-delivered multi-hop transfer-funded charge — or a carried hand-off at any depth, which witness does not copy (#2594) — may transiently list a false conflict that self-heals on anti-entropy. The checks:

Link copied to clipboard

id's virtual service net of returns — grossVirtualService − returned / w (design §7.1's b + committedService / weight, with the gauge supplying b and the fold). The raw position a pick reads, before the wake clamp (rawTicksAt), computed wide and narrowed only here. null if id is unknown or divergent. Past the ceiling it reads the ceiling, and below the floor the floor, as grossVirtualService does.

Link copied to clipboard

virtualService as a VirtualTime, exact: never held at a ceiling, never thrown on how far the edge has run (design §7.1). null if id is unknown or divergent.