LocalHeddle
A fair-share scheduler for one process: it decides which group's work runs in each free slot, so that over time each group gets the share its weight promises, and it keeps the books on what each one actually used.
Each slot is a lease. When a slot frees, ask acquire who goes next: it picks one leaf of the tree and reserves an estimated cost for it. When the work finishes, complete charges what it really cost and hands back what it did not use. Cost is time, by convention, in whatever unit the caller counts in. A lease that runs long is extended, or charged its overrun at the end; a charge is never refused. Work another scheduler already started is admitted, with no pick. A job shorter than the slot's reservation is shrinked straight after the pick, as if the lease had been opened at its size. Every call that charges, admit, extend and complete, takes the waiting set, and the wake memory observes it as a pick would have before the charge lands (#3471).
Start one with fromTopology, and change the tree while it runs with apply: a reload is one unit, a reweight moves the leases open under it onto the new edge, and a removal drains (see apply). Attached children come and go with attach and detach.
How a pick works
acquire walks down from root, and at each group makes one EEVDF pick among the children that lead to an eligible leaf (FairShareAllocator.pickChild), then delegates the reservation down to the child it picked. "Lead to" is strict: a child counts only when a lineage of ACTIVE edges runs from it down to an eligible leaf, so a subtree whose only leaf sits behind a closing edge is never picked in place of a sibling that can run. The deadline it orders by is ev + reservation / weight, and every candidate in one pick shares this slot's reservation: it is EEVDF by the slot's request length, so between two children that request alike, the one further behind goes first. Two sets steer it, and they are different on purpose:
waiting is every leaf with work queued that a descent could reach: a leaf behind ACTIVE edges, the same test the pick applies. It decides who is competing, which is what seats a new group at its parent's front and what tells a group returning from idle apart from one that never left.
eligible is the waiting leaves this particular slot can run. Only they can be picked.
A group that is waiting and reachable but cannot run on this slot keeps its claim: it is not idle, so the next slot it can run on does not clamp it as a waker. Work no descent can reach is a different case and counts as idle, even if the caller lists it as waiting: a leaf whose only route crosses a closing edge, or a named group that has gained an ACTIVE child. A subtree holding only such work is observed idle, so it banks no credit through the reshape window (design §10.5): when it can be reached again, say because a new child under it activates, it comes back by its parent's clock, as far ahead or behind as it was when it was cut off, rather than owed the slots it could not have used (§7.2, #3376). One this engine never saw leave is clamped as a waker.
A wrong estimate
An open lease counts at its reservation. A wrong estimate reorders picks and never changes a charge. Reserve at or below the cost and extend: a refund is what can move a sibling.
A pick delegates the reservation down the lease's path, so while the lease is open every group on it carries the estimate, not the cost. complete then charges the leaf exactly the cost it is given, extending an overrun or handing the unused remainder back up the path, so a leaf's spend is the sum of the costs its completions reported, whatever was reserved. What the estimate did change is the picks made while the lease was open. A lane that reserves low looks cheaper than it is and can win a pick it should not, and one that reserves high loses one. Where each job waits on the one before, those picks lean the lane's share: on an ensemble of 48 closed-loop rigs at one level, by about 0.01 on average, towards the lane that reserves low.
A refund is what reaches an honest sibling. The parent's net-service clock counted the open reservation at the weight of everyone asking, and the refund lands at the weight of whoever is still asking, so a lease that settles under its reservation while a sibling is away moves that sibling (#3376). On an ensemble of 54 two-level rigs, a lane that reserves four times the cost on the job that empties its queue gains about 0.045 and costs its honest sibling about 0.03 on average; reserving 1 and extending as it runs, it costs the sibling about 0.003. That holds for the means only. One rig's sibling can lose about as much beside a lane that reserves low: 0.0805 at worst beside one reserving a quarter of the cost, against 0.0844 beside the refund.
So size LocalPolicy.defaultReservation at or a little below a typical job, never at the longest: an estimate that runs short is corrected by extend or by the overrun at complete, and neither hands anything back. Pass a reservation per acquire when the lane's history gives a better one, and extend a lease that reaches what it holds.
What a lease ends at
A lease ends only at a leasable group: a leaf (no ACTIVE child edge) that the topology declares a lane, or an attached child whose template carries no template of its own. Being a leaf is not enough. A group whose children are all inactive reads as a leaf in the ledger, and only the topology can tell a lane from a group that has nothing attached right now, such as a group with a template before its first child is attached, or an attached repository before its first author is. That group is never leased, and work named at it is never wanted. The pick's terminal, the lift of acquire's two sets into demand, admit, explain and entitlement read this one predicate, so none of them can accept a group the others refuse.
Ceilings
A node of the topology may carry a ceiling, Topology.Node.maxConcurrent: the most leases open beneath it at once. A lease counts at every group its path passes through, a draining one included. Before a pick builds its demand views, every leaf beneath a group at its ceiling is dropped from both sets, so the pick goes to a sibling, and the capped group counts as idle at its parent: it banks no credit while it waits, and once a lease beneath it closes it comes back as far ahead or behind its siblings as it was when it reached the ceiling (#3376). A ceiling of 0 pauses everything beneath it. When every eligible leaf is capped, acquire returns AcquireOutcome.NothingEligible. previewPicks filters the same way, counting the leases already open and the ones a preview opens; explain tells a capped leaf WaitExplanation.AtCeiling, naming the capped group nearest the root; and entitlement owes a capped leaf nothing, so its siblings share its slots. The count is derived from the open leases on every call, so a ceiling persists nothing and a reload that changes only ceilings changes no edge. admit, extend, complete and apply charge work that is already running, so no ceiling refuses them, and lowering one preempts nothing.
Asking why
explain says why a leaf is not what the next acquire picks, or that it is, by running that very pick on a throwaway copy of the engine. entitlement says what share of the slots the leaf is owed while the waiting set holds still. Neither changes anything.
Every delegation is seated first
Delegating down an edge that has no virtual-time gauge yet would seat it at its own origin, for good: a permanent lifetime credit (#1752). So every delegation this engine makes, picked or not, goes through one helper that seats an unseated edge at its parent's front first. A pick seats the parent's newborns itself; admit, extend and an overrun at complete rely on the helper.
All or nothing
Every call that changes the engine runs on a working copy of its whole state (ledger, open leases, wake memory, capacity) and the engine keeps that copy only when the call returns. So a call that throws changes nothing, whatever it throws: the engine reads, and its persisted snapshot encodes, exactly as before, and the next call starts clean. A whole reload is one operation, however many children it changes.
The copy costs one copy of the open leases and of the wake memory per call.
The ordinary refusals keep one change, the allocator's wake memory. An acquire refused with AcquireOutcome.NoLiveLineage leaves the ledger as it was, but the pick it tried at the root observed who was waiting, and forgetting that would treat the next observation as the first. So does the NoLiveLineage of the admit overload that takes a waiting set, which observes it at the root.
Supply
Supply is minted at root, and the engine mints its own: tell it how many slots you run with reconcileCapacity, and acquire and extend top the root up inside the same operation whenever it would fall below LocalPolicy.supply's low watermark, so supply never runs out between calls to it. The top-up is part of the operation: one that is refused leaves none behind. Until a capacity is reconciled nothing is minted ahead, and acquire and extend are refused with a SupplyExhausted outcome when the root holds less than they need. complete and admit are never refused: work that already ran or already started is charged, so when the root is short they mint the shortfall. The low watermark is the headroom that keeps them from needing to.
Every mint of an epoch, top-ups included, rewrites one record carrying the epoch's running total, so the ledger keeps one mint record per epoch however much it serves.
Reconciling leases
reconcileLeases compares the open leases with the work the caller still has running and reports both directions: orphans, open leases whose work is gone, each with how long it ran from its startedAt; and live ids the engine holds no lease for. It changes nothing. Settle an orphan with complete, by default at LeaseReconciliation.Orphan.defaultSettlement.
Persisting
persist takes a LocalHeddleSnapshot, everything a restart needs, and restore starts an engine from one under a later epoch: every open lease is valid again under its old id, the topology last applied is the one it leases by, and the next pick is the one this engine would have made. Encode the snapshot as JSON or CBOR; decode reads it back and names an unsupported version or corrupt bytes rather than throwing. After a restore, settle what did not survive the restart with reconcileLeases.
A draining path
A reload can close an edge on an open lease's path. Nothing new crosses a closing edge, so an extend there returns LeaseOutcome.PathDraining and changes nothing. A complete still settles: what was reserved is charged at the leaf as usual, and an overrun, which would need a new delegation, is charged instead at the deepest group of the path still reached through ACTIVE edges from the root. That group's own edge advances by the overrun, which is the fairness that still matters, since a closing edge is never picked again. When the root's own child edge is the closing one there is no such group below the root, and the ledger has no counter for spend at the root, so the overrun is recorded on no edge, and LeaseOutcome.Done.unrecorded reports it (#3493).
The lifetime limit
Two counters the ledger keeps in Long grow for as long as the engine runs, in cost units: an edge's issuance, which counts every reservation, extension and overrun that crosses it, and the root's minted supply, the sum of every epoch's mint record. Two weight-1 lanes at MAX_RESERVATION, charged in full, reach Long.MAX_VALUE after about 524,000 leases. So a pick keeps LIFETIME_HEADROOM in hand: acquire answers AcquireOutcome.LifetimeExhausted rather than carry either counter past Long.MAX_VALUE − LIFETIME_HEADROOM, and changes nothing but the wake memory. That run then ends in the refusal after 507,903 leases.
Work already running is never refused for it, and no call throws at it. admit, extend and complete use the headroom, up to Long.MAX_VALUE itself, and a charge that still does not fit is recorded whole or not at all, never in part:
an overrun at complete goes down the path as far as every edge has room for it in whole, and is charged at the deepest group it reaches, as on a draining path. An overrun above MAX_RECORDED_OVERRUN, what the root cannot fund in whole, and what no edge has room for are reported in LeaseOutcome.Done.unrecorded;
an admit that does not fit reserves nothing, and changes nothing but the lease it opens, with Lease.reserved
0, so the cost arrives as an overrun when it completes;an extend that does not fit changes nothing, the wake memory included, and answers LeaseOutcome.Done with the whole amount LeaseOutcome.Done.unrecorded. explain answers WaitExplanation.LifetimeExhausted for a leaf behind a full counter.
A charge left unrecorded is service the lane's position does not show: credit, on the favour side, but credit that cannot be spent on a pick, since the only way to spend it is an acquire across the full counter, which is refused. The headroom holds 16,384 charges of MAX_RESERVATION after a counter's last acquire; past that a charge is reported rather than recorded. One absurd cost cannot end an engine: an overrun above MAX_RECORDED_OVERRUN, half the headroom, is recorded nowhere, so complete(lease, Long.MAX_VALUE) reports its overrun and the next acquire leases, on a young engine as on an old one. An overrun within the cap leaves a counter past the watermark only when that counter was already within the cap of it.
What it does not do
It reads no clock and draws no random number: every time is a number the caller passes in, and every output is ordered by id, so a replay of the same calls gives the same picks on every target. It owns no concurrency either — call acquire once per free slot.
Not thread-safe. One engine has one writer, and the caller serializes calls to it, snapshot included: taking one reads the engine's own maps. The value it returns is immutable, so a reader that must not hold the caller's lock is handed a snapshot taken under it.
Failure surface
Nothing suspends and nothing times out. An argument out of range throws IllegalArgumentException, a reservation or extension above MAX_RESERVATION included.
Arithmetic that would leave Long throws ArithmeticException rather than wrapping. An edge's position, its service in ticks of 1/16 of a unit, is 128-bit, and every pick orders the full position, so no position refuses a pick: a position only counts up from the edge's start, and nothing rebases it (#3472). Positions are whole ticks, so no join can grow a denominator (#3313, #3231), and nothing narrows one on its way to a comparison. What bounds an engine's lifetime instead is the Long counters the ledger keeps, and no call throws at them (see "The lifetime limit").
An edge's position also has a ceiling, Long.MAX_VALUE less room for one MAX_RESERVATION lease, divided by its weight's denominator: the highest position the public virtual-time reads report exactly. Past it they report the ceiling, the penalty side. Nothing brings a busy parent's positions back down (#3472), so a long-running one passes its ceiling, and only those reads saturate: every pick, seat and wake clamp orders the wide position exactly. A newborn is seated at the front, a clamped waker at the front plus what its open leases reserve, less its sleeper credit (#3238), and a returner where its parent's net-service clock puts it. The ceiling is measured net of returns, so returned service never reaches it (#3360). A weight set so fine that one full lease could carry a child past its ceiling is refused at apply (#3353).
Nothing is narrowed on the way to a pick, a seat or a wake clamp, so each is taken against the exact front, and nothing an understated front would have handed out is kept as credit (#3353).
The diagnostics still answer in exact Rationals, which are Long over Long. Those can throw ArithmeticException: explain's WaitExplanation.BehindAtLevel fronts, whose numerator carries the least common multiple of the sibling weights' denominators, and entitlement. Each position in them is first held inside its window, so a child past its ceiling reads the ceiling there.
apply keeps the weight arithmetic in range the same way: a reload whose weights would put one parent's products of numerators and denominators out of Long refuses that child with a StepRefusal.Refused, and its siblings land. So does one too fine for a full lease: keep every weight's denominator at or below 30,719 (#3353). The limit holds at any lease size, because it is sized for the largest lease, MAX_RESERVATION. It is necessary, not sufficient: several fine weights whose denominators share no factor are refused below it too. Refused so, a group the reload adds takes every group beneath it out with it, each a StepRefusal.Refused of its own, so no lane activates below a group the root cannot reach (#3466); a running group whose reweight is refused keeps its old edge, and what is beneath it. A reload refuses the sibling whose activation tips the set over, and siblings activate in id order, so of two new siblings that fit alone but not together, the one whose id sorts last is refused. A boot, which has no previous tree to keep, leaves out their parent and everything beneath it instead (see fromTopology).
A state the engine's own invariants rule out throws IllegalStateException: that is a bug in the engine, or a ledger conflict the engine did not create, such as two live inbound edges into one group, a divergent record, or a cycle on a lease's path (#1737). apply never leaves one on an open lease's path: before it swaps a reload in, it checks that every open lease's path is its leaf's one live lineage. A boot throws neither: fromTopology reports a set of weights that does not fit in Boot.result, and leaves out the group that holds it.
Samples
val tree = twoLanes()
val heavy = tree.groupId("heavy")
val light = tree.groupId("light")
val (heddle, booted) = LocalHeddle.fromTopology(tree, LocalPolicy(defaultReservation = 3L), epoch = 0L)
check(booted.refusals.isEmpty())
// Four slots: the engine mints its own supply ahead of them.
heddle.reconcileCapacity(totalSlots = 4L)
// Both groups have work queued, and this slot can run either.
val queued = setOf(heavy, light)
val first = heddle.acquire(waiting = queued, eligible = queued, startedAt = 100L)
check(first is AcquireOutcome.Acquired)
// The job overran its 3-unit estimate: all 5 units are charged, 2 of them as overrun.
check(heddle.complete(first.lease.id, actualCost = 5L, waiting = queued) == LeaseOutcome.Done(charged = 5L, overrun = 2L, unrecorded = 0L))
// Over many slots the shares follow the weights, 2 : 1.
val picks = (0 until 30).map {
val lease = (heddle.acquire(queued, queued, startedAt = it.toLong()) as AcquireOutcome.Acquired).lease
heddle.complete(lease.id, actualCost = 3L, waiting = queued)
lease.leaf
}
check(picks.count { it == heavy } in 19..21)// The admin's file: web gets three parts to mobile's one, and forks are attached as they open.
val text = """
{"root": "farm", "children": [
{"type": "lane", "name": "web", "weight": "3"},
{"type": "lane", "name": "mobile"},
{"type": "group", "name": "forks", "template": {"maxConcurrent": 1}}
]}
"""
val parsed = Topology.from(Json.decodeFromString<TopologyDocument>(text))
// Invalid would carry every problem in the file, each with its address, for the admin to fix.
check(parsed is TopologyParse.Valid)
val farm = parsed.topology
val policy = LocalPolicy(defaultReservation = 3L)
// The epoch is a boot counter you persist and raise on every start.
val (heddle, booted) = LocalHeddle.fromTopology(farm, policy, epoch = 0L)
check(booted.refusals.isEmpty())
heddle.reconcileCapacity(totalSlots = 4L)
// A contributor opens a fork while the program runs.
check(heddle.attach(listOf("forks"), "ana", generation = 1L).refusals.isEmpty())
val web = farm.groupId("web")
val mobile = farm.groupId("mobile")
val ana = farm.attachedChildId(listOf("forks"), "ana")
// Each free slot: lease it, run the work, charge what it really cost.
val queued = setOf(web, mobile, ana)
val first = heddle.acquire(waiting = queued, eligible = queued, startedAt = 0L)
check(first is AcquireOutcome.Acquired)
check(heddle.complete(first.lease.id, actualCost = 4L, waiting = emptySet()) is LeaseOutcome.Done)
val running = (heddle.acquire(queued, queued, startedAt = 4L) as AcquireOutcome.Acquired).lease
val lost = (heddle.acquire(queued, queued, startedAt = 4L) as AcquireOutcome.Acquired).lease
// Under the scheduling lock, persist. Encode and store the text exactly as it comes.
val stored = Json.encodeToString(LocalHeddleSnapshot.serializer(), heddle.persist())
// After the restart: decode, restore under the raised counter, and settle what did not survive.
val decoded = LocalHeddle.decode(stored, Json)
check(decoded is RestoreResult.Restored)
val restored = LocalHeddle.restore(decoded.snapshot, policy, epoch = 1L)
val orphan = restored.reconcileLeases(live = setOf(running.id), now = 10L).orphaned.single()
check(orphan.lease == lost)
check(restored.complete(orphan.lease.id, orphan.defaultSettlement, waiting = emptySet()) == LeaseOutcome.Done(charged = 3L, overrun = 0L, unrecorded = 0L))
check(restored.complete(running.id, actualCost = 3L, waiting = emptySet()) == LeaseOutcome.Done(charged = 3L, overrun = 0L, unrecorded = 0L))Types
What fromTopology booted: the engine, and what booting it did, in the shape a reload reports. ApplyResult.refusals is empty when the whole tree booted; otherwise it names every group left out, and heddle runs the rest.
Properties
The reservation an acquire makes when the caller names none: LocalPolicy.defaultReservation.
How far this engine has come: moved by every call that can change it, acquire, admit, extend, shrink, complete, cancel, reconcileCapacity, apply, attach and detach, whatever the call returns, since a refused acquire may still move the wake memory. Never moved by a read (topology, snapshot, persist, previewPicks, previewApply, explain, entitlement, reconcileLeases), nor by a call that throws, which changes nothing, nor by a checked apply refused as ApplyOutcome.TreeChanged, which reads topology and stops. Costs one field read: compare it with the revision the last pass saw before copying anything.
The tree this engine runs: the one fromTopology booted, or the one apply was last given, or after a restore, the one the persisted engine ran. It is always equal to the LocalHeddleSnapshot.lastApplied that persist writes. attach and detach leave it as it is: an attached child is the ledger's, and the tree holds only its group's template.
Functions
Charge work another scheduler already started at leaf: open a lease for it with no pick, delegating reservation down the leaf's lineage, and leave the wake memory as acquire(waiting, eligible = {leaf}) would have (#3320). Never refused for supply, since the work is already running; a shortfall at the root is minted.
Move the tree to new: add what it adds, remove what it removes, and give every reweighted group a new edge at its new weight, as Topology.Companion.diff lists the steps. Open leases survive it, and each is still charged once, at complete.
apply new at generation, but only if topology is still startedFrom, the tree the edit was made from: the save of an admin page that two people may edit at once. When someone applied another tree in between, it applies nothing and returns ApplyOutcome.TreeChanged naming the running tree; otherwise it returns ApplyOutcome.Applied with exactly what apply returns.
Attach the child at path, with the weight and ceiling the template it is attached under gives, and every attached group above it that is not attached yet, as one unit (Topology.attach). A GroupPath.Nested names a child beneath an attached one: an author beneath a repository, say, where the declared group's template carries the authors' template. The repository is a group and is never leased; work is charged to an author.
Attach the child name to the group at group, read from the root down, with the weight and ceiling that group's template in the topology gives (Topology.attach). Applied as one unit, like apply. Attaching a child that is already attached does nothing; attaching a leaf whose detach is still draining gives it a new edge and moves its draining leases onto it. A group waits instead, as attach of a path says. The same as attach of GroupPath.Attached(group, name).
Close lease without charging it: everything reserved goes back up the path.
Close lease and charge its leaf actualCost. Beyond the reservation, the shortfall is extended inline first (minted at the root if the root is short) and reported as the overrun; below it, the unused remainder is handed back up the path. Never refused.
Detach the attached child at path and everything attached beneath it (Topology.detach): closed at once, top-down, so nothing new is leased beneath it, and retired bottom-up once the leases beneath each complete, until when each waiting group is StepRefusal.Draining. Detach again once they have drained.
Detach the attached child name from the group at group (Topology.detach): closed at once, and retired once its open leases complete, until when it is StepRefusal.Draining. The same as detach of GroupPath.Attached(group, name), so a child whose template carries a template takes everything attached beneath it along.
leaf's fair share of totalSlots slots right now, as an exact rational, while waiting stays as it is. Answered by a view of this engine's state: see LocalHeddleView.entitlement.
Why leaf is not, or is, what the next acquire on these same arguments picks. Changes nothing, not even the wake memory. Answered by a view of this engine's state: see LocalHeddleView.explain.
Everything a restart needs, as one value to encode and store: see LocalHeddleSnapshot. Like snapshot, it is taken under the caller's scheduling lock, since it reads the engine's own maps; the value it returns is immutable, so encoding and writing it can happen off the lock.
What apply of new at generation would do, worked out on a copy of this engine: the ApplyResult it would return, and the engine straight after it as a LocalHeddleView. A read: it changes nothing here, the wake memory and revision included, and persist returns the same snapshot after it as before.
What the checked apply of new at generation from startedFrom would do now: ApplyOutcome.TreeChanged exactly when it would refuse, and otherwise PreviewOutcome.Previewed with what the unchecked previewApply returns. A read, like that one, whichever it returns.
Who would go next: the leaves reservations.size calls to acquire would pick, in order, if nothing else happened in between. Changes nothing, not even the wake memory. Answered by a view of this engine's state: see LocalHeddleView.previewPicks.
Who would go next, with each leaf's own next job: the leaves a caller's loop over queues would pick, in order, acquiring at reservation and then shrinking or extending the lease to the winner's head, if nothing else happened in between. Changes nothing, not even the wake memory. Answered by a view of this engine's state: see LocalHeddleView.previewPicks.
Tell the engine how many slots the caller runs at once, totalSlots. It sizes the supply watermarks of LocalPolicy.supply and nothing else: it mints nothing and changes no lease, and calling it again with the same value changes nothing. Until it is called with a positive value no supply is minted ahead, and an acquire or extend the root cannot fund is refused.
What every group is owed of the whole pool while waiting holds still, read once from this engine's state and answered group by group. Answered by a view of this engine's state: see LocalHeddleView.shareLine. The line keeps what it read, so it does not follow the engine.
Hand back amount of what lease reserves, up the path it was opened on, as complete hands back an unused remainder. The lease stays open, reserving amount less. It charges nothing and observes nothing, so it takes no waiting set, and it is never refused, as complete is not: a draining path takes the refund as it takes cancel's.
The engine's whole state, as an immutable value. Costs a sort of the open leases and of the wake memory.