Fair share in one program
A build farm has four agents and two teams. Web pays for three parts and mobile for one. Each time an agent frees up, someone must say whose build runs next. Heddle can make that call inside your own program, with no network and no extra servers.
It keeps the promise over time, not build by build. A team that sat idle does not come back owed a pile of turns. A build that ran long pays for every minute.
This page follows one farm from its first build, through a change to its tree, to a crash and a restart. Every example is one compiled sample, sampleBuildFarm, quoted in order. Every result a code block shows is a check in that sample, so the examples cannot drift from what the engine does.
Draw the tree
Write down who shares the farm and in what proportions:
A group divides its share among its children. A lane is where work is charged, so it is what a build belongs to. Each weight is relative to its siblings: web's 3 against mobile's 1 means three quarters of the agents' time goes to web while both teams have work queued. Groups nest, so web could split its share between a pull-requests lane and a nightly lane, at weights of its own.
groupId turns a path of names into the id the engine uses. The two lanes are both called builds, and they are still different lanes, because an id is the whole path.
A group with a template() takes children your program attaches while it runs: one per customer, say, all at the same weight. When the tree comes from an admin's file rather than code, decode a TopologyDocument and call Topology.from, which lists every problem with an address instead of throwing.
A rename or a move is a delete plus an add. A child is known by its name and its place in the tree. Rename it, or move it under another group, and the engine retires the old child and starts a new one with no fairness history.
The tree is not fixed. You can change it while builds run, and Change the tree while builds run shows how.
Start the engine
LocalHeddle.fromTopology loads the tree into an engine called heddle, which the rest of this page uses. Every lease id it hands out is stamped with epoch, which a restart raises. It also says what the start did. booted.refusals names each group it left out because its children's weights do not fit together. Here that list is empty, and the check says so.
Heddle counts in whatever unit your program counts time in. Here it is minutes. It never reads a clock: every time is a number you pass in, so a replay of the same calls makes the same choices.
Before it can hand out time, the engine needs a supply of it. reconcileCapacity tells it how many agents run at once, and from then on it keeps its own supply topped up. When its supply would drop below one round of builds (every agent once, at the default estimate), it refills to two rounds. Until you call it, an acquire the engine cannot fund answers SupplyExhausted and changes nothing. Call it again whenever the farm grows or shrinks.
Lease one agent at a time
When an agent frees up, ask who goes next, run that build, and report how long it took:
acquire opens a lease: one agent, given to one lane, with an estimate of the time it will take set aside. complete closes it and charges the real time. startedAt is stored on the lease for your own bookkeeping. No pick ever reads it.
Two sets steer each pick. waiting is every lane with work queued. eligible is the lanes this particular agent can run, which is usually all of them. The difference matters, and the Mac agent further down shows why.
The first eight builds, with every build finishing on its estimate:
Six to two: three to one. previewPicks answers "who goes next?" for several builds ahead without moving anything, and the real builds then match it. Showing who goes next turns it into a status line a person can read.
Ask why a team is waiting
Mobile has a build queued and web got the agent. explain says why:
explain runs the very pick the next acquire would make, on a throwaway copy, so its answer always agrees with what happens next. Here it says that at the top of the tree, the farm picks web. The first number is mobile's progress: the time it has been given, divided by its weight. The other two are lines it is judged against, an average over everyone waiting and over everyone this agent can run. Mobile sits at 6, level with both, so it was in the running. It lost because web's next build ends sooner by that same measure. How the next turn is chosen explains those numbers and works this exact moment out by hand.
The other answers are plainer: NotWaiting (nothing queued), NotEligible (this agent cannot run it), NoLiveLineage (the tree is being reshaped around it) and SupplyExhausted. A log line or a metric should use the answer's kind and its group ids. The numbers move on every pick.
entitlement is the fair share as a number of agents: of four, web is owed three while both teams keep work queued. To turn every answer explain can give into words a person can act on, from a running engine or a saved one, see Explaining a wait.
A build that runs long
The estimate only decides how much time to set aside. complete charges what the build really took, and the six extra minutes are reported as the overrun. A charge is never refused, even when it is bigger than the estimate. Web paid for its long build by moving ahead of the line, so mobile gets the next agent. A build that finishes early hands the unused minutes back the same way.
A team that goes quiet
While mobile had nothing queued, web used every agent, which is the point of sharing. When mobile's work returns, it is not twelve builds behind web, or mobile would take agent after agent until it caught up. It comes back exactly as far behind as it was when it went quiet: web's long build still counts, so mobile is owed one more build than the three-to-one pattern gives it. It takes that build first, and then the pattern resumes. Pausing neither costs a team its place nor buys it a better one.
A team counts as quiet only when it is missing from waiting. A team that is waiting but cannot run on this agent is not quiet, and keeps its place. A team with a build still running but nothing queued is quiet, and that case has one known gap.
No more than one at once
Some work should never run twice at the same time, however many agents are free. Deploys are a good example. Give that lane a ceiling with maxConcurrent:
While one deploy runs, the next agent goes to builds, though deploys weigh three times as much. explain answers AtCeiling and names the lane and its limit. A capped lane is owed nothing while it waits, so builds are owed all four agents. When the deploy finishes, deploys compete again like a team back from a quiet spell: not owed the turns they sat out, and still a third of a build ahead, as they were when they reached the ceiling. So builds take the next agent.
A ceiling of 0 pauses a lane. On a group it counts every build beneath it, and in a group's template it caps each attached child on its own. When several are full on the way down, explain names the one nearest the top. A ceiling never stops or refuses a build that is already running.
Better estimates, and other endings
A Mac agent. Web is still waiting, but this agent cannot run its builds, so only mobile is eligible. Web keeps its place for the next agent it can use.
An estimate. How long the lane's last build took is a good guess for the next. A closer estimate makes the order fairer while builds are running. The charge is corrected at
completeeither way.extendsets aside more time for a build still running. It is optional:completecharges an overrun anyway.cancelcloses a lease for a build that never ran, and charges nothing. A build that ran settles withcompleteat the time it took, even one that failed or was stopped halfway.admitcharges work that started without a pick, such as a build someone ran by hand. It is never refused for lack of supply, because the work is already running. Passwaitingtoo, and the scheduler sees the queue as a pick would have, so a lane that sat idle and comes back is placed as a pick would place it.
Change the tree while builds run
Shares get renegotiated, and teams come and go. A web build is running when the farm's admin saves a new tree: web drops from three parts to two, and a new forks group takes one part, shared by the contributors' forks:
apply takes the whole new tree, works out what changed, and makes every change in one step, so no pick ever sees a tree halfway through. generation counts your reloads, and the engine uses it to name the parts a reload adds. Reusing a number is safe, because the engine moves it past any it already holds.
A build that was running when its team's weight changed carries on. It keeps its lease, and complete charges it once, as usual. From your side, nothing changed. The team itself starts again at its new weight, level with the line. It is neither owed for its past nor charged for it.
Forks open and close while the farm runs, so the tree cannot list them. A group with a template() takes children your program attaches as it goes:
A group is named by its path from the top, here listOf("forks"), and the child by its own name. attachedChildId turns the pair into the id you lease with. Every child of forks gets the weight its template gives, 1 by default.
Taking something out waits for its builds. A fork you detach, or a lane a reload leaves out, closes at once: nothing new is leased there, and acquire answers NoLiveLineage. Builds already running on it finish normally. Until they do, the change comes back in refusals as Draining, naming the leases it waits for. Once they finish, make the same call again and the removal completes. If a build's work is gone, reconcileLeases finds it, so a lost build holds a removal up only until you settle it.
Each child's change lands on its own. When one child's change cannot land yet, because it is draining or was refused, that child is held back. So is any group above it whose change must retire an old part, such as a reweight or a removal, and that group is listed in refusals too. A new group held back takes the groups beneath it along, and each is listed. If that group is waiting for builds, they wait as Draining too. No lane runs under a group the engine never added, and an attach there is refused the same way. A group that was already running keeps its old part, so a new lane under it still lands. Every other change in the same reload still lands. Call apply with the same tree later, and only what is left is done.
Two finer points:
Refusedis the other answer. It means the engine could not make a change for a reason that waiting on its own leases will not cure, and itsreasonsays why. That child is left as it was.An overrun nobody pays for. While a team at the top of the tree drains away, one of its last builds may run long.
completereports the overrun inDone, but it is counted against no one.
After a crash
The agent host restarts. Some builds the engine still holds leases for are gone, and the host may be running one the engine never heard of:
reconcileLeases compares the leases the engine holds with the work you say is still running, and reports both kinds of mismatch. It changes nothing; settling is your call. An orphan is a lease whose work is gone, with how long it has been since it started. The default settlement, defaultSettlement, charges that time but no more than the lease was given, since a lost build cannot show that it really ran long. If you have evidence that it did, pass more. Work that will resume belongs in live, so it never becomes an orphan.
When the engine restarts too
So far only the agent host went down. If the program that runs the engine restarts as well, save the engine first and load it back after. Three rules keep that safe:
Store the saved form exactly as it comes. Do not edit it, or rebuild it from parts. The engine reads it back whole, and checks it on the way in.
Restore under a higher epoch. Keep a boot counter on disk and raise it on every start. Lease ids are numbered afresh in each epoch, so a reused epoch could hand out an id that an earlier run already used.
Upgrade one release at a time. Each release reads the format the release before it wrote, as well as its own. A snapshot from 0.7.5 still loads in 0.7.6. 0.7.6 no longer keeps the origin 0.7.5 stored, so it folds that number into the positions as it reads them, rounding up, so that no lane gains a turn.
The farm's engine restarts while kept is still running:
persist takes a snapshot: one value holding everything the engine needs to carry on. Take it from the same place you call the engine from, since the engine is not thread-safe. The value itself never changes, so encoding and writing it can happen anywhere.
restore starts an engine from it. Every lease that was open is open again under its old id, so complete works on it as before. The agent count comes back, so there is no need to call reconcileCapacity again, though doing so is harmless. The engine also keeps what it needs to pick in the same order, and the tree it last loaded. The one thing not saved is the policy, so pass the same LocalPolicy the old engine ran with.
An old lease id that is no longer open now answers Stale, not Unknown, so you can tell "from before the restart" apart from "never heard of it". Builds that died with the old program are still leases on the new one. Find and settle them with reconcileLeases, as above.
restore throws IllegalArgumentException if the epoch is not above the snapshot's. Raise your boot counter even when you restore the same snapshot a second time, say after a crash straight after the first restore. Two engines under one epoch can hand out the same lease id.
A removal that was still waiting for its builds when the engine stopped is still waiting after the restore. Call apply with the same tree once those builds finish, and the removal completes, exactly as it would have before.
What a snapshot holds
The books: every part of the tree, and everything handed down and charged.
Every open lease, with its id, the path it was charged down, and its
startedAt.The engine's memory of who was quiet, so a team waking up is held level just as the old engine would have held it.
The agent count last given to
reconcileCapacity.The tree last passed to
apply, or the one the engine started from. Attached children are in the books, so they come back too.The epoch of the engine that took it.
Not kept: the LocalPolicy, which restore takes afresh, and the counter that numbers lease ids, which starts again at zero under the new epoch.
What the saved form looks like
Encoded, a snapshot is a two-item list, [formatVersion, state], as a JSON array or a CBOR array. Both formats are tested. The module brings no format of its own, so add kotlinx-serialization-json or kotlinx-serialization-cbor to your build. Do not use ProtoBuf: it writes a snapshot but cannot read the books back, because their maps hold other maps. The list is a list rather than an object so that a store that reorders an object's keys, as Postgres jsonb does, cannot move state ahead of the version. Equal snapshots encode to equal bytes.
LocalHeddleSnapshot.FORMAT_VERSION is the format this release writes, and SUPPORTED_FORMAT_VERSIONS lists the formats it reads. 0.7.5 writes and reads format 1 alone. It is the first frozen format: a later release that changes what it means ships a reader for it. A consumer coming from 0.7.4 starts from its topology again. 0.7.4's snapshots also say format 1, in an older layout, and are not read: they fail to decode, so do not keep them across the upgrade.
decode reads the version first and never throws for what the bytes hold. It gives one of three answers:
Restoredholds the snapshot, ready forrestore.UnsupportedVersionmeans this release does not read the format the bytes were written in. It names the format it found and the formats it reads. Either a newer release wrote them, or a development build of 0.7.5 did, in format 2. The engine reads nothing past the version, so nothing is half-loaded.Corruptmeans the bytes are not a snapshot, or hold one that does not add up, such as a lease on a part of the tree the books do not hold. Itsreasonsays which. A snapshot the engine built always adds up, so one that does not was damaged or changed after it was written.
The check on the way in is about shape and consistency. Every open lease must reserve a positive amount and come from an epoch no later than the snapshot's. Its path must lead from the top of the tree to its lane, over parts the books hold and none that has retired. The leases must be in id order, and the tree must be valid. The check does not ask whether every number is one an engine could have reached. A huge but well-formed reservation still decodes, and that gap is tracked by #3261. So read snapshots only from storage your own program writes.
How fair is it?
Over time, each lane gets its weight's share of the time while it has work queued, and the check is one call away: compare entitlement with what each lane was really charged. Three limits come with that promise, stated plainly.
Per fork, not end to end. Each fork in the tree keeps its own children close to their weights. A lane deep in the tree inherits the small gaps of every fork above it.
Estimates steer order. A lease counts at its estimate until it completes. So a lane that always guesses low looks cheaper while its builds run, and wins turns it should not. A lane that always guesses high loses turns the same way. The charge is corrected at
complete, but a pick already made stays made.A sibling's refund. Say web has a build running that reserved more than it will use when mobile goes quiet. If that build finishes early while mobile is away, its unused minutes come back to web after mobile's place was measured, and mobile returns owed a little more than it is. That one came with the clock, and was accepted as the price of fixing short bursts. A build of mobile's own that straddles its quiet spell is fine: its refund lands on mobile, where it belongs.
The last two shrink as estimates get closer to the truth, so:
Set
defaultReservationat or a little below a typical build, not the worst case. A small default favours lanes whose builds run long; a large one penalises them.Pass a
reservationwhen you know better, such as the lane's last build time, as the Mac agent above does.Know where the quiet-spell effect lives. It needs a lane that goes quiet while a sibling's build still runs. A lane that always has work queued never meets it. A build that runs past its estimate hands nothing back, so it adds nothing either.
Both are known gaps, and they are the bound #3239 accepted, measured by a benchmark. The cancel is not a gap: cancel is for work that never ran, and work that held its slot settles with complete. What it does not promise gives the arithmetic and the measured sizes.
The promise also asks one thing of you: cancel only a build that never ran. A cancel charges nothing, so a build that ran and was then cancelled is free time, and the other teams pay for it. A team that is always busy and cancels one build in four takes 4/7 of the agents where its share is half. Settle a build that ran with complete and the time it took, even when it failed.
One more thing before you wire it in: the engine is not thread-safe, so call it from one place at a time. How the next turn is chosen covers that, and states the rule exactly, works the first eight builds by hand, and gives the measured numbers, the limits and what to check on your own engine.