FairSharePool

class FairSharePool(engine: LocalHeddle, slots: Int, timeSource: TimeSource.WithComparableMarks, costUnit: Duration, clockStart: Long = 0)

Wait your turn for a slot. A build farm has four agents and two lanes, web and mobile; a program handing them out wants to say "run this in web's lane when it is web's turn" and have that one line wait. A FairSharePool holds a LocalHeddle, which knows whose turn it is, and a count of slots. withSlot suspends until fair share grants the caller's leaf a slot, runs the work, and charges the lane the time the work took, however it ends. acquire is the same wait on its own: the caller hands the slot back with complete or cancel.

The part that is easy to get wrong, and silent when it is, is a waiter that gives up at the moment it is granted. The pool hands that slot back: a waiter cancelled while queued leaves its queue, and one cancelled after its grant was made but before it took hands the lease back to the engine, so the farm never runs one agent short.

How it works

One lock guards the engine, a first-in-first-out queue of waiters per leaf, the set of leases the pool holds open, and the slot count. After every change, while fewer than slots leases are open and some leaf has a waiter, the pool asks the engine for the next lease, with every leaf that has a waiter as both the waiting and the eligible set, and grants it to the head waiter of the leaf the engine picked. The pick is made at the engine's default reservation, and the lease is then sized to the waiter's own: one that asked for less has the difference handed back at once with LocalHeddle.shrink, which leaves every position and the wake memory as a lease opened at its size would (#3648), and one that asked for more has the lease extended to it. If the engine cannot extend it, the lease is granted at the default and the rest is charged as an overrun at complete. Waiters are resumed only once the lock is released.

A grant's Lease.startedAt is now at the moment the grant is made, which can be a little before its waiter runs. withSlot starts its clock when the block starts, so that gap is never charged.

The engine's open leases are adopted

The leases the engine already holds open when the pool is built, say after a LocalHeddle.restore, count against slots like any other, and complete and cancel settle them. now counts in whole cost units from clockStart, so persist now() beside the snapshot and pass it back, plus the downtime if you know it, as clockStart after a restart: an adopted lease's startedAt is then on the same clock. With the default of 0, an adopted lease reads as just started.

So a pool can restart with every slot held. A caller that waited through withSlot or acquire died with the old program, and nothing will ever settle the lease it held, so the pool grants nothing until those leases are closed. Once the pool is built, find them with pool.withEngine { engine, _ -> engine.reconcileLeases(live, pool.now()) }, naming as live only the leases whose work survived, and settle each orphan with pool.complete(orphan.lease.id, orphan.defaultSettlement) after the block returns. now takes no lock, so it is safe to read inside the block. With a clockStart of 0, now reads no later than any adopted lease's startedAt, so every default settlement reads 0.

Refusals

A leaf no lease can end at is refused, never queued for good: acquire answers SlotOutcome.Refused with the engine's own WaitExplanation.NoLiveLineage or WaitExplanation.LifetimeExhausted. When every slot is busy that is checked on arrival, once per leaf that has no waiter yet, so a pool with no free slot, or with none at all, still refuses an unleasable name at once and queues a healthy one. A leaf is always asked about on its own, so a full lane next in line never gets another leaf's waiters refused.

Failures

A failure while handing out slots, the engine throwing or answering something its own contract rules out, is delivered to the waiters: every queued waiter's acquire throws it, and the call that set the hand-out going, a stranger's complete or a cancelled waiter's handler, returns as usual. The next arrival starts a fresh hand-out. An engine refusing to take back the lease of a waiter cancelled after its grant is delivered the same way: the slot is freed, and the engine, which still holds the lease, reports it as an orphan through LocalHeddle.reconcileLeases.

A failure with no waiter queued has nobody to throw to, so it is logged at error, with its throwable, on the us.tractat.kuilt.heddle.FairSharePool logger: a withEngine block that leaves the engine throwing, or an engine refusing a hand-back, while nobody waits. It means the engine broke its own contract, so it is logged once the lock is released, and never thrown at the call that set the hand-out going. A failure that does reach a waiter is not logged as well: that waiter's acquire throws it.

A waiter cancelled before it takes its failure, as the failure is handed over or after that but before the waiter runs, drops it: its acquire throws the cancellation, as any cancelled call does. A failure every waiter it was handed to dropped reached nobody, so it is logged as above, once however many copies were dropped. One that any waiter took is not logged, though others dropped it.

Threads

Every member is safe to call from any thread. Resuming happens outside the lock, after the outermost call returns from it. A waiter resumed through a dispatcher that runs it inline with no event loop, such as a direct executor, and that calls complete at once, nests one resume per such complete on the stack. Coroutines' own Unconfined dispatcher queues them on the thread's event loop instead.

The pool owns the engine from here on: reach it only through withEngine, which runs under the pool's lock and catches the pool up afterwards, and change the slot count with resize.

Parameters

engine

the scheduler deciding whose turn it is. The pool reconciles its capacity to slots.

slots

how many leases may be open at once, at least 0.

timeSource

the clock now reads and withSlot measures with. It should be monotonic: a reading that goes back before a mark is taken as no time at all, so a block whose clock stepped back is charged 0, and now never reads below clockStart.

costUnit

how long one unit of LocalHeddle cost is: positive and finite.

clockStart

what now reads at construction, in cost units; non-negative.

Throws

when an argument is out of range, or the engine refuses to reconcile its capacity to slots; the engine is unchanged.

Samples

val farm = Topology("farm", listOf(Topology.Lane("web", Weight.of(3)), Topology.Lane("mobile")))
val web = farm.groupId("web")
val mobile = farm.groupId("mobile")
val (heddle, booted) = LocalHeddle.fromTopology(farm, LocalPolicy(defaultReservation = 3L), epoch = 0L)
check(booted.refusals.isEmpty())
val pool = FairSharePool(heddle, slots = 1, TimeSource.Monotonic, costUnit = 1.minutes)

val built = mutableListOf<String>()
coroutineScope {
    // One agent: whichever lane's turn comes second waits for the first build to finish.
    launch { built += pool.withSlot(web) { "web build" } }
    launch { built += pool.withSlot(mobile) { "mobile build" } }
}
check(built.sorted() == listOf("mobile build", "web build"))

// A name the farm does not declare is refused before anything runs.
val refused = try {
    pool.withSlot(GroupId("nightly")) { "never runs" }
} catch (e: SlotRefusedException) {
    "refused: ${e.reason}"
}
check(refused.startsWith("refused"))
val farm = Topology("farm", listOf(Topology.Lane("web", Weight.of(3)), Topology.Lane("mobile")))
val web = farm.groupId("web")
val mobile = farm.groupId("mobile")
val (heddle, booted) = LocalHeddle.fromTopology(farm, LocalPolicy(defaultReservation = 3L), epoch = 0L)
check(booted.refusals.isEmpty())
// Two agents, and one unit of cost is one minute on an agent. The pool owns the engine now.
val pool = FairSharePool(heddle, slots = 2, TimeSource.Monotonic, costUnit = 1.minutes)

// Waits until fair share grants web a slot: at once, on an idle farm.
val build = pool.acquire(web)
check(build is SlotOutcome.Granted)
// The build took five minutes against the default estimate of three: two are overrun.
check(pool.complete(build.lease.id, actualCost = 5L) == LeaseOutcome.Done(charged = 5L, overrun = 2L, unrecorded = 0L))

// A name the farm does not declare is refused, never left waiting.
check(pool.acquire(GroupId("nightly")) is SlotOutcome.Refused)

val next = pool.acquire(mobile)
check(next is SlotOutcome.Granted)
pool.cancel(next.lease.id)
val farm = Topology("farm", listOf(Topology.Lane("web", Weight.of(3)), Topology.Lane("mobile")))
val web = farm.groupId("web")
val mobile = farm.groupId("mobile")
val policy = LocalPolicy(defaultReservation = 3L)
val (heddle, booted) = LocalHeddle.fromTopology(farm, policy, epoch = 0L)
check(booted.refusals.isEmpty())
// A test clock, so the sample can let two minutes pass.
val clock = TestTimeSource()
val before = FairSharePool(heddle, slots = 2, clock, costUnit = 1.minutes)
check(before.acquire(web) is SlotOutcome.Granted)
check(before.acquire(mobile) is SlotOutcome.Granted)
clock += 2.minutes

// Persist the pool's clock beside the snapshot. now() takes no lock, so it is safe in the block.
val (snapshot, stoppedAt) = before.withEngine { engine, _ -> engine.persist() to before.now() }

// After the crash: restore under a raised epoch, your persisted boot counter, and start the
// pool's clock where it stopped. Both leases are adopted: every slot is taken.
val restored = LocalHeddle.restore(snapshot, policy, epoch = snapshot.epoch + 1)
val pool = FairSharePool(restored, slots = 2, clock, costUnit = 1.minutes, clockStart = stoppedAt)

coroutineScope {
    val next = async(start = CoroutineStart.UNDISPATCHED) { pool.acquire(web) }
    check(!next.isCompleted) // both slots are held by builds that died with the old program

    // None of the old builds is running, so name none as live, and settle each orphan at the
    // default: the two minutes it ran. With the default clockStart of 0, now() would read 0,
    // and every default settlement would read 0 too.
    val found = pool.withEngine { engine, _ -> engine.reconcileLeases(live = emptySet(), now = pool.now()) }
    check(found.orphaned.map { it.defaultSettlement } == listOf(2L, 2L))
    found.orphaned.forEach { pool.complete(it.lease.id, it.defaultSettlement) }

    val granted = next.await()
    check(granted is SlotOutcome.Granted)
    pool.complete(granted.lease.id, actualCost = 3L)
}

Constructors

Link copied to clipboard
constructor(engine: LocalHeddle, slots: Int, timeSource: TimeSource.WithComparableMarks, costUnit: Duration, clockStart: Long = 0)

Functions

Link copied to clipboard
suspend fun acquire(leaf: GroupId, reservation: Long = defaultReservation): SlotOutcome

Suspend until fair share grants leaf a slot, and answer SlotOutcome.Granted with its lease, or SlotOutcome.Refused when no lease can end at leaf as the tree stands now. The caller holds a granted slot until it calls complete or cancel.

Link copied to clipboard

Close lease without charging it, as LocalHeddle.cancel does. A lease the pool counts frees its slot. A lease the engine does not hold changes nothing.

Link copied to clipboard
fun complete(lease: LeaseId, actualCost: Long): LeaseOutcome

Close lease and charge it actualCost, as LocalHeddle.complete does, with the pool's waiting leaves as the waiting set. A lease the pool counts frees its slot, and the next waiter is granted it. A lease the engine does not hold answers LeaseOutcome.Unknown or LeaseOutcome.Stale and changes nothing.

Link copied to clipboard
fun now(): Long

The pool's clock: clockStart plus the whole cost units elapsed since construction, floored.

Link copied to clipboard
fun resize(slots: Int)

Change how many leases may be open at once to slots, reconciling the engine's capacity to it. Raising the count grants queued waiters at once, in the engine's own order. Lowering it preempts nothing: every open lease stays open, and the next grant waits until fewer than slots are.

Link copied to clipboard
fun view(): PoolView

The pool as it stands: each leaf's queued reservations, the open count and the slot count, copied under the pool's lock. Use it where the engine is not needed, say a gauge of the open count; for a question the engine answers, read the view withEngine hands its block, so the answer and the view are of the same moment.

Link copied to clipboard
fun <R> withEngine(block: (engine: LocalHeddle, view: PoolView) -> R): R

Run block on the engine, under the pool's lock, and answer what it returned. This is the one way to reach the engine once it is in a pool: LocalHeddle.persist for a snapshot, LocalHeddle.explain for why a lane waits, LocalHeddle.previewPicks for who goes next, LocalHeddle.apply for a reload, LocalHeddle.reconcileLeases to find orphans. Every other thread waits on the lock meanwhile, so keep the block short.

Link copied to clipboard
suspend fun <T> withSlot(leaf: GroupId, reservation: Long = defaultReservation, block: suspend (Lease) -> T): T

Suspend until fair share grants leaf a slot, run block with its lease, and charge the lease the time the block took, in whole cost units rounded up. Answers what block returned.