Fixing Priority Preemption in a GPU Lease Scheduler
System DesignModel answerLast updated
Diagnose why a GPU lease manager preempts the wrong tenant, rewrite victim selection to evict the weakest lease, and design regression tests.
A cluster control plane hands out exclusive GPU leases to training jobs. The GPUManager class keeps a map from gpu_id to the current tenant (job_id plus a numeric priority); a fresh request takes an unused GPU if one exists, and otherwise may displace a running tenant.
Operators report that high-priority jobs are sometimes denied even though less important work is still holding hardware. The allocation code in its current shape:
class GPUManager:
def __init__(self, total_gpus):
self.total_gpus = total_gpus
self.active_leases = {} # gpu_id -> {'job_id': ..., 'priority': ...}
def request_gpu(self, job_id, priority):
free_gpus = [i for i in range(self.total_gpus) if i not in self.active_leases]
if free_gpus:
self.active_leases[free_gpus[0]] = {'job_id': job_id, 'priority': priority}
return True
for gpu_id, lease in self.active_leases.items():
if priority > lease['priority']:
self.active_leases[gpu_id] = {'job_id': job_id, 'priority': priority}
return True
return False
Concrete symptom: on a machine with one GPU and jobs arriving in priority order 1, then 2, then 3, the third request is rejected although it outranks the incumbent.
Deliver three things: (1) explain the defect in the preemption path, including why the reported single-GPU sequence may not reproduce it from this snippet alone; (2) rewrite request_gpu so preemption follows a stated, defensible policy; (3) describe unit tests — including adversarial ones — that would have caught this class of bug.
Hints
Hint 1
Trace the reported sequence line by line before trusting it; if the snippet already passes that scenario, the production code probably differs in a way the report hints at.
Hint 2
Ask what the loop is actually deciding: it commits to whichever lease it meets first rather than answering 'is any tenant beatable?'
Hint 3
Preemption destroys live work, so the policy should both check the minimum priority and evict the least valuable lease — with a total order for ties.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Start by reproducing, and notice where the report and the code disagree. Walk the one-GPU case: job 1 gets GPU 0; job 2 sees priority 1 and wins; job 3 sees priority 2 and wins. The pasted version actually satisfies the reported scenario. That mismatch is useful information — say it out loud. It means either the deployed code has an extra return False or break inside the loop, or the failure needs at least two GPUs to surface. Both lead to the same root cause.
Root cause: the loop decides from the first lease it inspects, not from the best candidate. Two shapes of the bug:
- Early exit. If the loop reads
else: return False(orbreak) when the incoming job cannot beat the first lease, then with leases{0: p=5, 1: p=1}a priority-3 request compares against 5, gives up, and returnsFalse— never seeing the p=1 tenant it could have displaced. That is exactly the "high-priority job rejected while weak work runs" symptom. - First-fit. The pasted code preempts the first beatable lease in insertion order. With
{0: p=2, 1: p=1}, a p=3 request evicts the p=2 tenant and leaves p=1 running — it destroys more valuable work than necessary, and the evicted job will soon come back and trigger another preemption cascade.
The operator should be min, not next-if-beatable: compute the least valuable active lease, and only displace it if the requester's priority is strictly greater. Strict comparison prevents equal-priority jobs from churning each other; ties among the lowest priority are broken by gpu_id so behavior is deterministic and tests are reproducible. Complexity stays O(G) per request — one pass for an idle GPU, one min over the map — with O(G) space for the map and O(1) extra per call. Guard total_gpus == 0, where min over an empty map would raise. Keep the evicted lease somewhere (requeue queue, event, metric) instead of silently overwriting it; a preemption that loses the victim's identity is a lost job.
Corrected implementation.
class GPUManager:
def __init__(self, total_gpus):
self.total_gpus = total_gpus
self.active_leases = {} # gpu_id -> {'job_id': ..., 'priority': ...}
self.preempted = [] # (gpu_id, evicted_lease) for requeue/notify
def request_gpu(self, job_id, priority):
for gpu_id in range(self.total_gpus):
if gpu_id not in self.active_leases:
self.active_leases[gpu_id] = {'job_id': job_id, 'priority': priority}
return True
if not self.active_leases: # total_gpus == 0
return False
victim_gpu = min(
self.active_leases,
key=lambda g: (self.active_leases[g]['priority'], g),
)
victim = self.active_leases[victim_gpu]
if priority > victim['priority']:
self.preempted.append((victim_gpu, victim))
self.active_leases[victim_gpu] = {'job_id': job_id, 'priority': priority}
return True
return False
Tests that actually catch it. Naive single-GPU tests pass against both buggy variants, because with one GPU the loop's first entry is also the minimum. The tests must build the order-dependence deliberately.
def test_escalating_priorities_single_gpu():
m = GPUManager(1)
assert m.request_gpu("a", 1)
assert m.request_gpu("b", 2)
assert m.request_gpu("c", 3)
assert m.active_leases[0]["job_id"] == "c"
def test_evicts_weakest_not_first():
m = GPUManager(2)
m.request_gpu("high", 5) # inserted first → GPU 0
m.request_gpu("low", 1) # GPU 1
assert m.request_gpu("mid", 3)
holders = {lease["job_id"] for lease in m.active_leases.values()}
assert holders == {"high", "mid"} # weak lease evicted, strong one untouched
def test_equal_priority_never_preempts():
m = GPUManager(1)
m.request_gpu("x", 2)
assert m.request_gpu("y", 2) is False
def test_zero_gpus():
assert GPUManager(0).request_gpu("z", 100) is False
test_evicts_weakest_not_first fails for both variants: the early-exit version returns False, the first-fit version evicts "high". Then add a property-based test (Hypothesis): generate random (job_id, priority) streams and after each call assert two invariants — a request succeeds iff there was an idle GPU or priority > min(previous priorities); and every recorded eviction had the minimum priority at that moment. Invariant tests cover whole families of ordering bugs, not just this instance.
What a strong answer demonstrates. Verifying the bug report instead of pattern-matching it; naming the flaw as "decides on the first element instead of the extremum"; being explicit about strict inequality, deterministic tie-breaking, the empty-pool case, and the need to requeue the victim; and choosing tests that force the failure mode rather than confirming the happy path.
Likely follow-ups. Graceful preemption: add lease states RUNNING → DRAINING → FREE; a preemption moves the victim to DRAINING with a deadline, signals it to checkpoint, and gives the requester a reservation. DRAINING leases must be excluded from victim selection or two requesters claim the same GPU, and request_gpu becomes asynchronous. Scale: at thousands of GPUs the O(G) scan dominates, so keep free GPUs on a stack/heap and active leases in a min-heap keyed by (priority, gpu_id), making both paths O(log G) — with lazy deletion or an index map to handle updates. Thrashing: add a minimum residency time or a preemption budget so a job that just started cannot be evicted immediately.