diff --git a/doc/adr/0005-reactive-live-admission.md b/doc/adr/0005-reactive-live-admission.md index d82cb18..d608db7 100644 --- a/doc/adr/0005-reactive-live-admission.md +++ b/doc/adr/0005-reactive-live-admission.md @@ -40,8 +40,10 @@ configured.** `(inFlight+1) * footprint`. MemAvailable is instantaneous, so memory is checked raw. - **Far vs near the line.** Far from the reserve, jobs are admitted freely (cheap - jobs and bursts sail through). Near it, admission serialises: admit one, wait a - short **settle window** (default 3s) for the reading to reflect it, re-probe. + jobs and bursts sail through). Near it, admission serialises: every dispatch + decision takes one probe, and a runner that does not fit ends the round + (#192). The message loop keeps polling and the next message or empty poll + re-probes. The near-line margin is not a separate tuned constant — it is one footprint wide, implicit in the admission arithmetic. - **Local admission and reporting.** `admitOne` checks headroom before each @@ -52,8 +54,11 @@ configured.** gate is the real limiter. The operator cannot set it. - **Fail safe.** A probe error admits (the semaphore backstops; stranding acquired work is worse than a brief over-admit) and reports a conservative - local capacity estimate of 1. Context cancellation unblocks a - parked admission so shutdown never hangs on a full host. + local capacity estimate of 1. Admission never blocks the + message loop (#192), so shutdown cannot hang on a full host. A runner is + charged the largest declaration among the known not-yet-started assignments + (the default job when none), and `JobStarted` replaces that charge with the + started job's real declaration. - **Go decides, bash reads.** The admission decision lives in the Go listener (ADR-0003 already scopes "the concurrency pool / capacity" to Go). The host reading is a thin shell-out, `listener/host-probe.sh`, emitting `loadavg1 / @@ -81,9 +86,11 @@ into device-count sizing with an explicit `mode: auto`. - The coarse `1/nproc` footprint can under-admit genuinely cheap jobs on small-core hosts (they are treated as ~one core each). A future measured / adaptive refinement can tighten the footprint; it is not load-bearing today. -- There is a small settle latency near the line, by design (back-pressure). Real - waiting only happens when the host is actually full, where running more would - make every job slower. +- Near the line a shortfall is retried on the next message or poll rather than + immediately (back-pressure). Not dispatching only happens when the host is + actually full, where running more would make every job slower. +- An idle runner holds at most the largest known declaration until its + `JobStarted` arrives, so the host can briefly be over-reserved (#192). - A co-tenant that grows *after* admission can briefly cross the reserve; reactive admission corrects on the next decision, and ephemeral jobs finish and self-heal, so the breach is a tolerated transient. diff --git a/doc/adr/0006-declared-job-cores.md b/doc/adr/0006-declared-job-cores.md index 361afd3..bfef77b 100644 --- a/doc/adr/0006-declared-job-cores.md +++ b/doc/adr/0006-declared-job-cores.md @@ -44,12 +44,12 @@ charges that declaration against a per-host core budget.** label means recreating each host's set while it is idle. - **Capacity.** The capacity advertised before GitHub assigns a job assumes the default cost of 1, because a job's labels are known only once it is assigned. - A larger job then waits in `admitOne` on the host it was assigned to. The + A larger job is not admitted on that round and is retried on the next message (#192). The default size is clamped to the host budgets like any other, so a host whose RAM budget is under 4 GB still advertises one slot (#177). Everything else in ADR-0005 stands: `reserve` is the only host knob, the -settle window, the internal safety ceiling, fail-safe probing, and Go deciding +internal safety ceiling, fail-safe probing, and Go deciding while bash reads `/proc`. ## Alternatives @@ -71,9 +71,32 @@ while bash reads `/proc`. - Workflows own their cost declaration. A job that under-declares still meets the loadavg check, so the host degrades rather than collapses. - A runner is minted for one assignment but GitHub may give it a different - queued job. Committed cores therefore match in total, not job by job. -- Head-of-line: within one batch a large job that does not fit parks the - smaller jobs behind it until it starts. + queued job. Until `JobStarted` arrives, committed cores are a pessimistic + estimate (the largest known declaration per runner); after it, each runner + is charged the job it really took, matched by its JIT runner name, not by the + assignment it was minted for (#192). +- Head-of-line: within one batch a large job that does not fit ends the round; + later messages re-probe, so smaller jobs behind it start once it fits or the + budget frees (#192). +- A runner is minted before its job is known, so it is charged the largest + declared size among the known not-yet-started assignments (the default job + when none). `JobStarted` names the runner and the job it took; the charge + becomes that job's declared size, clamped to the budget. A `JobStarted` for a + runner the listener does not hold leaves every charge unchanged and is + logged; its job still leaves the known assignments, since it is no longer + waiting for a runner. A GPU runner keeps its card and is re-attributed + there, clamped to the budget stored for that card. +- One ledger owns the charge lifecycle (known assignment, runner charged, + started, exited). Committed totals are sums over the held runners, not + counters; a started or completed job id cannot return to the known + assignments while it is among the most recent 4096 retired ids (older ones + are forgotten, bounding memory); a runner name already held is refused; an exit releases only + its own record. The result does not depend on the order these events + arrive in (#192). +- Each dispatch mints a runner name of its own (the job id plus a per-dispatch + suffix), so a `JobStarted` for an earlier runner of a redelivered assignment + never names its replacement. A CPU runner is charged the size that passed + admission and keeps that probe's budget for the later clamp (#192). - The label set on every cpu scale set is part of the routing contract. A new `cpu-cores-` value needs adding to `runner-types.yaml` and each host's scale set recreated before workflows use it. diff --git a/doc/adr/0007-declared-job-vram.md b/doc/adr/0007-declared-job-vram.md index 23193f8..fd9acc0 100644 --- a/doc/adr/0007-declared-job-vram.md +++ b/doc/adr/0007-declared-job-vram.md @@ -42,8 +42,11 @@ the GPU it chose.** committed to running jobs plus the job's declaration fits the budget AND the live free VRAM (`nvidia-smi`) is still at least `reserve`. The live check counts processes the listener did not start. One GPU hosts several jobs - while their declarations fit. While no GPU fits, admission waits the settle - window and re-probes (ADR-0005). + while their declarations fit. While no GPU fits, the round ends after one probe and the next + message re-probes (ADR-0005, #192). A runner is placed and charged by the + largest VRAM declared among the known not-yet-started assignments, and + `JobStarted` adjusts the charge to the started job's declaration on the same + card. - **Charge.** VRAM is charged after the worker slot is acquired and the context checked (the #177 ordering), and released when the job exits or on any failure path before it starts. @@ -101,5 +104,5 @@ the GPU it chose.** runners on one GPU); ADR-0005; ADR-0006; ADR-0002; ADR-0003. - `listener/gpuprobe.go` (`CommandGPUProbe`, `jobVRAM`, `vramBudget`, `pickGPU`, `gpuDevices`), `listener/listener.go` (`reconcile`, `admitGPU`, - `chargeGPU`, `releaseGPU`, `vramCapacity`), `listener/gpu-probe.sh`, + `vramCapacity`), `listener/ledger.go`, `listener/gpu-probe.sh`, `listener/provision-job.sh`, `lib/runner-container.sh`. diff --git a/doc/arch/overview.html b/doc/arch/overview.html index cee7dc0..9e5a06a 100644 --- a/doc/arch/overview.html +++ b/doc/arch/overview.html @@ -514,11 +514,9 @@

4. Job 資料流

yes - + - - - settle + re-probe + round ends, next msg @@ -1056,7 +1054,7 @@

13. 反應式准入

ADR-0005 的 CPU/RAM reactive live-admission。每個 job 准入前以 live host reading 判斷。

- + capacityFor (local snapshot) @@ -1101,16 +1099,16 @@

13. 反應式准入

admit yes - + no - settle (3s default) + round ends - re-probe (loop) + next message re-probes @@ -1321,7 +1319,7 @@

16. ADR 交叉引用

0005 Reactive Live-admission - Per-job CPU/RAM admission, reserve headroom, settle window + Per-job CPU/RAM admission, reserve headroom, non-blocking per-round probe hostprobe.go, host-probe.sh, listener.go (admitOne/capacityFor) diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index ead870d..5789a16 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -225,6 +225,34 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- **Admission no longer blocks the message loop** (#192): a job that does not + fit the reactive CPU/RAM budget or any GPU is now denied after one probe + and the listener keeps polling, instead of waiting inside admission while + an idle runner held the budget and no later message could free it. The + next message or empty poll re-probes and dispatches it. `Config.SettleWindow` + is removed. A new runner is charged the largest size declared among the + known not-yet-started assignments (the default job when none; for a GPU + host the largest VRAM declaration picks the card and is charged), and + `JobStarted` replaces that charge with the started job's declaration + (same card for VRAM), matched by the JIT runner name, not by the assignment + the runner was minted for. A `JobStarted` for a runner the listener does not + hold leaves every charge unchanged and is logged; its job still leaves the + known assignments. Until it arrives an idle runner holds the larger + charge, so a mixed batch packs after the jobs start. + Every message envelope, with or without statistics, now retries admission. + One `ledger` (`listener/ledger.go`) owns the charge lifecycle of every + runner: committed cores, GiB and VRAM are sums over the held runners, a + started or completed job id cannot return to the known assignments while it + is among the most recent 4096 retired ids, a + runner name already held is refused, an exit releases only its own record, + and a runner now gives up its charge before its assignment key can be + reused. A GPU re-attribution clamps to the budget stored for the pinned + card even when a later probe omits it. Every dispatch mints a runner name + of its own (the job id plus a per-dispatch suffix), so a delayed or + replayed `JobStarted` of an earlier runner cannot resize a replacement, and + a CPU runner is charged the size that passed admission, with the host + budget of that same probe kept for the later re-attribution, instead of a + later read of a probe snapshot the capacity reporter may have replaced. - **Orphan reaping works again** (#186): since #168 the listener unit set `HOME` to the runner home itself, so the SEC-3 guard (RUNNER_HOME must not equal HOME) refused every orphan sweep and stranded containers and `jit-*` diff --git a/listener/README.md b/listener/README.md index 6338c7b..29fa067 100644 --- a/listener/README.md +++ b/listener/README.md @@ -249,8 +249,15 @@ Pin the builder images by digest in production via `RUNNER_KANIKO_IMAGE` / - **Reactive live-admission (ADR-0005, #163):** by default the listener admits each job only while every resource (CPU, memory) keeps a reserve headroom free (default 10%, the one operator knob, upward-only). Local capacity snapshots - record admission headroom. A batch that would breach the reserve parks and - re-probes. + record admission headroom. A runner that would breach the reserve is not + admitted that round; the next message envelope (with or without statistics) + or empty poll re-probes (#192). + A new runner is charged the largest size declared among the known + not-yet-started assignments (the default job when none), since GitHub picks + its job only later. `JobStarted` re-attributes that charge, by JIT runner + name, to the job the runner really took; a GPU runner keeps its card and is + re-attributed on it. A `JobStarted` for a runner the listener does not hold + changes no charge. The host reading is `host-probe.sh` (`HOST_PROBE_CMD`). - **GPU VRAM admission (ADR-0007, #180):** `mode: vram` gates dispatch on declared per-GPU VRAM and live reserve. Capacity snapshots estimate how diff --git a/listener/charge_test.go b/listener/charge_test.go new file mode 100644 index 0000000..9281277 --- /dev/null +++ b/listener/charge_test.go @@ -0,0 +1,441 @@ +package listener + +import ( + "bytes" + "context" + "log" + "strings" + "testing" + "time" + + "github.com/actions/scaleset" +) + +// #192: a JIT runner is minted before GitHub says which job it will take, so it +// is charged the largest declaration among the assignments known not to have +// started, and re-attributed when JobStarted names the job it really took. + +// cpuListener is a reactive listener on an 8-core host (budget 7 at reserve 10) +// whose provisioner holds every job until the returned func is called. +func cpuListener() (*Listener, func()) { + release := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + return l, func() { close(release); l.wg.Wait() } +} + +func startedMsg(runner string, labels ...string) []*scaleset.JobStarted { + return startedAs(runner, jobOfRunner(runner), labels...) +} + +// startedAs reports that runner took the job jobID, which need not be the +// assignment the runner was minted for: GitHub may hand any queued job of the +// scale set to any of its runners, so only the JIT runner name identifies the +// charge to re-attribute. +func startedAs(runner, jobID string, labels ...string) []*scaleset.JobStarted { + js := &scaleset.JobStarted{RunnerName: runner} + js.JobID = jobID + js.RequestLabels = labels + return []*scaleset.JobStarted{js} +} + +func TestRunnerChargedLargestKnownDeclaration(t *testing.T) { + l, stop := cpuListener() + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + jobs := []*scaleset.JobAssigned{assigned(1, "small", "cpu-cores-1"), assigned(2, "big", "cpu-cores-4")} + if err := l.reconcile(context.Background(), stats, jobs); err != nil { + t.Fatal(err) + } + if got := l.committedSize(); got.cores != 4 || got.gb != 16 { + t.Errorf("committed = %+v, want 4 cores 16 GiB (largest known declaration)", got) + } + stop() + if got := l.committedSize(); got != (jobSize{}) { + t.Errorf("committed after exit = %+v, want 0", got) + } +} + +func TestRunnerChargedDefaultWithoutAssignment(t *testing.T) { + l, stop := cpuListener() + if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, nil); err != nil { + t.Fatal(err) + } + if got := l.committedSize(); got != defaultJob { + t.Errorf("committed = %+v, want the default job %+v", got, defaultJob) + } + stop() +} + +// A known assignment is retained after the round it arrived in, so a later +// round (an empty poll) still sizes its runner by it. +func TestKnownAssignmentRetainedAcrossRounds(t *testing.T) { + l, stop := cpuListener() + ctx := context.Background() + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 0}, []*scaleset.JobAssigned{assigned(1, "big", "cpu-cores-4")}); err != nil { + t.Fatal(err) + } + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, nil); err != nil { + t.Fatal(err) + } + if got := l.committedSize(); got.cores != 4 { + t.Errorf("committed cores = %d, want 4 from the retained assignment", got.cores) + } + stop() +} + +func TestJobStartedReattributesCharge(t *testing.T) { + l, stop := cpuListener() + jobs := []*scaleset.JobAssigned{assigned(1, "big", "cpu-cores-4"), assigned(2, "small", "cpu-cores-1")} + if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, jobs); err != nil { + t.Fatal(err) + } + // Runner big-r1 was minted for "big" but took "small". + l.handleJobStarted(startedAs("big-r1", "small", "cpu-cores-1")) + if got := l.committedSize(); got.cores != 1 || got.gb != 4 { + t.Errorf("committed after JobStarted = %+v, want 1 core 4 GiB", got) + } + stop() + if got := l.committedSize(); got != (jobSize{}) { + t.Errorf("committed after exit = %+v, want 0 (not negative)", got) + } +} + +func TestJobStartedUnknownRunnerIgnored(t *testing.T) { + l, stop := cpuListener() + defer stop() + if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, []*scaleset.JobAssigned{assigned(1, "big", "cpu-cores-4")}); err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + prev := log.Writer() + log.SetOutput(&buf) + defer log.SetOutput(prev) + l.handleJobStarted(startedMsg("ghost-runner", "cpu-cores-1")) + if got := l.committedSize(); got.cores != 4 { + t.Errorf("committed cores = %d, want 4 unchanged", got.cores) + } + if !strings.Contains(buf.String(), "ghost-runner") { + t.Errorf("log %q does not name the unknown runner", buf.String()) + } +} + +// With the budget freed, the next round dispatches the runner that was denied. +// The first runner really holds the budget and gives it up through its own +// exit, not through a ledger edit. +func TestReconcileDispatchesAfterRelease(t *testing.T) { + release := make(chan struct{}) + mnt := &recordingMinter{config: "jit"} + l := New(&fakeSession{}, mnt, &recordingProvisioner{block: release}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 2, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + ctx := context.Background() + // 2-core host at reserve 10: budget 1 core, which the first runner fills. + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, nil); err != nil { + t.Fatal(err) + } + if len(mnt.gotNames) != 1 || l.committedSize().cores != 1 { + t.Fatalf("first round minted %d runners holding %d cores, want 1 runner holding 1", len(mnt.gotNames), l.committedSize().cores) + } + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2} + if err := l.reconcile(ctx, stats, nil); err != nil { + t.Fatal(err) + } + if len(mnt.gotNames) != 1 { + t.Fatalf("minted %d runners while the budget was full, want 1", len(mnt.gotNames)) + } + close(release) + l.wg.Wait() + if got := l.committedSize(); got != (jobSize{}) { + t.Fatalf("committed after the first runner exited = %+v, want 0", got) + } + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, nil); err != nil { + t.Fatal(err) + } + l.wg.Wait() + if len(mnt.gotNames) != 2 { + t.Errorf("minted %d runners after release, want 2", len(mnt.gotNames)) + } +} + +// No GPU has room: the message loop still reaches AcquireJobs, and no runner is +// minted onto the full card. +func TestRunKeepsPollingWhenNoGPUFits(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + polledAfter2 := make(chan struct{}, 1) + sess := &fakeSession{ + messages: []*scaleset.RunnerScaleSetMessage{ + msgWithAssigned(1, 1, assigned(1, "a", "vram-gb-16")), + { + MessageID: 2, + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, + JobAvailableMessages: []*scaleset.JobAvailable{{JobMessageBase: scaleset.JobMessageBase{RunnerRequestID: 77}}}, + }, + }, + // The poll after message 2 runs only once its acquire and dispatch are done. + beforePoll: func(last int) { + if last == 2 { + select { + case polledAfter2 <- struct{}{}: + default: + } + } + }, + } + mnt := &recordingMinter{config: "jit"} + l := New(sess, mnt, &recordingProvisioner{}, Config{ + Image: "img-gpu", + GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 30000)}}, + Reserve: 20, + MaxRunners: 100, + }) + done := make(chan struct{}) + go func() { _ = l.Listen(ctx); close(done) }() + select { + case <-polledAfter2: + case <-time.After(2 * time.Second): + t.Fatal("message loop stalled: it never polled again after the second message while no GPU fit") + } + if got := sess.acquiredReqIDs; len(got) != 1 || len(got[0]) != 1 || got[0][0] != 77 { + t.Errorf("acquired %v, want [[77]]", got) + } + if len(mnt.gotNames) != 0 { + t.Errorf("minted %v onto a card with no room", mnt.gotNames) + } + if got := l.vramCommitted(0); got != 0 { + t.Errorf("card 0 committed = %d, want 0", got) + } + cancel() + <-done +} + +func TestGPUMaxVRAMChargeAndJobStarted(t *testing.T) { + release := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, Config{ + GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 0), rtx5090(1, 0)}}, + Reserve: 20, + MaxRunners: 100, + }) + ctx := context.Background() + // 25 GiB budget per card: runner "first" holds 16 GiB on card 0. + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, []*scaleset.JobAssigned{assigned(1, "first", "vram-gb-16")}); err != nil { + t.Fatal(err) + } + if got := l.vramCommitted(0); got != 16 { + t.Fatalf("card 0 committed = %d, want 16", got) + } + // "second" is vram-gb-8 but a vram-gb-16 assignment is known: 16 does not + // fit card 0 beside the first runner, so it must go to card 1 at 16. + jobs := []*scaleset.JobAssigned{assigned(2, "second", "vram-gb-8")} + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, jobs); err != nil { + t.Fatal(err) + } + if a, b := l.vramCommitted(0), l.vramCommitted(1); a != 16 || b != 16 { + t.Fatalf("committed (card 0, card 1) = (%d, %d), want (16, 16)", a, b) + } + // Runner second-r2 took a job other than the one it was minted for. + l.handleJobStarted(startedAs("second-r2", "other", "vram-gb-8")) + if a, b := l.vramCommitted(0), l.vramCommitted(1); a != 16 || b != 8 { + t.Errorf("after JobStarted committed (card 0, card 1) = (%d, %d), want (16, 8)", a, b) + } + l.handleJobStarted(startedAs("ghost-runner", "ghost", "vram-gb-1")) + if a, b := l.vramCommitted(0), l.vramCommitted(1); a != 16 || b != 8 { + t.Errorf("after a JobStarted for an unknown runner committed (card 0, card 1) = (%d, %d), want (16, 8) unchanged", a, b) + } + close(release) + l.wg.Wait() + if a, b := l.vramCommitted(0), l.vramCommitted(1); a != 0 || b != 0 { + t.Errorf("after exit committed = (%d, %d), want (0, 0)", a, b) + } +} + +// runUntilInFlight runs Listen over msgs with provisioning held, waits until +// want runners are in flight, then calls check before releasing them. +func runUntilInFlight(t *testing.T, l *Listener, sess *fakeSession, block chan struct{}, want int64, check func()) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + sess.cancel = cancel + done := make(chan struct{}) + go func() { _ = l.Listen(ctx); close(done) }() + deadline := time.Now().Add(2 * time.Second) + for l.inFlight.Load() != want && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if got := l.inFlight.Load(); got != want { + t.Errorf("in flight = %d, want %d", got, want) + } + check() + close(block) + <-done +} + +// Review round 2: an envelope that assigns a job and also reports it started or +// completed must not leave the job in the known set, or its size inflates the +// next runner's charge. +func TestEnvelopeAssignedThenStartedNotKnown(t *testing.T) { + for name, retire := range map[string]func(m *scaleset.RunnerScaleSetMessage){ + "started": func(m *scaleset.RunnerScaleSetMessage) { + js := &scaleset.JobStarted{RunnerName: "other"} + js.JobID = "big" + js.RequestLabels = []string{"cpu-cores-4"} + m.JobStartedMessages = []*scaleset.JobStarted{js} + }, + "completed": func(m *scaleset.RunnerScaleSetMessage) { + jc := &scaleset.JobCompleted{} + jc.JobID = "big" + m.JobCompletedMessages = []*scaleset.JobCompleted{jc} + }, + } { + t.Run(name, func(t *testing.T) { + block := make(chan struct{}) + m := msgWithAssigned(1, 1, assigned(1, "big", "cpu-cores-4")) + retire(m) + sess := &fakeSession{messages: []*scaleset.RunnerScaleSetMessage{m}} + l := New(sess, &recordingMinter{config: "jit"}, &recordingProvisioner{block: block}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + runUntilInFlight(t, l, sess, block, 1, func() { + if got := l.committedSize(); got != defaultJob { + t.Errorf("committed = %+v, want the default job %+v (the retired job is not known)", got, defaultJob) + } + }) + }) + } +} + +// Review round 2: a nonempty envelope without statistics (a JobStarted that +// frees budget) must still retry admission against the last statistics. +func TestEnvelopeWithoutStatsRetriesAdmission(t *testing.T) { + block := make(chan struct{}) + started := &scaleset.JobStarted{RunnerName: "a-r1"} + started.JobID = "a" + started.RequestLabels = []string{"cpu-cores-1"} + sess := &fakeSession{messages: []*scaleset.RunnerScaleSetMessage{ + msgWithAssigned(1, 1, assigned(1, "a", "cpu-cores-4")), + msgWithAssigned(2, 2, assigned(2, "b", "cpu-cores-4")), + {MessageID: 3, JobStartedMessages: []*scaleset.JobStarted{started}}, + }} + l := New(sess, &recordingMinter{config: "jit"}, &recordingProvisioner{block: block}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + // Runner a holds 4 of 7 cores, so b (4 cores) is denied until a's charge + // drops to the 1 core it really declared. + runUntilInFlight(t, l, sess, block, 2, func() {}) +} + +// Review round 2: re-attribution must clamp against the pinned card's own +// budget even when a later successful probe omits that card. +func TestJobStartedGPUCardMissingFromProbe(t *testing.T) { + release := make(chan struct{}) + probe := &switchGPUProbe{gpus: []GPU{rtx5090(0, 0)}} + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, Config{ + GPUProbe: probe, + Reserve: 20, + MaxRunners: 100, + }) + ctx := context.Background() + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, []*scaleset.JobAssigned{assigned(1, "r", "vram-gb-16")}); err != nil { + t.Fatal(err) + } + probe.mu.Lock() + probe.gpus = []GPU{rtx5090(1, 0)} // a good probe that no longer lists card 0 + probe.mu.Unlock() + if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, nil); err != nil { + t.Fatal(err) + } + l.handleJobStarted(startedMsg("r-r1", "vram-gb-all")) + if got := l.vramCommitted(0); got != 25 { + t.Errorf("card 0 committed = %d, want 25 (its own budget, not the whole-GPU sentinel)", got) + } + close(release) + l.wg.Wait() + if got := l.vramCommitted(0); got != 0 { + t.Errorf("card 0 committed after exit = %d, want 0", got) + } +} + +// A JobStarted for a runner the listener does not hold leaves every charge +// unchanged, but its job has started somewhere, so it is no longer a known +// assignment and stops sizing the next runner. +func TestListenUnknownJobStartedRetiresJobOnly(t *testing.T) { + block := make(chan struct{}) + sess := &fakeSession{messages: []*scaleset.RunnerScaleSetMessage{ + msgWithAssigned(1, 1, assigned(1, "big", "cpu-cores-4"), assigned(2, "mid", "cpu-cores-2")), + { + MessageID: 2, + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, + JobStartedMessages: startedAs("ghost-runner", "big", "cpu-cores-4"), + }, + }} + l := New(sess, &recordingMinter{config: "jit"}, &recordingProvisioner{block: block}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + var buf bytes.Buffer + prev := log.Writer() + log.SetOutput(&buf) + defer log.SetOutput(prev) + // The first runner holds 4 of 7 cores. With "big" retired the second is + // charged "mid"'s 2 cores and fits; were "big" still known it would be + // charged 4 and denied. + runUntilInFlight(t, l, sess, block, 2, func() { + if got := l.committedSize(); got.cores != 6 || got.gb != 24 { + t.Errorf("committed = %+v, want 6 cores 24 GiB (4 unchanged + 2 for the next runner)", got) + } + }) + if !strings.Contains(buf.String(), "ghost-runner") { + t.Errorf("log %q does not name the unknown runner", buf.String()) + } +} + +// Review round 3: a worker must give up its charge record BEFORE its assignment +// key becomes reusable, or a redelivery admitted in between mints a replacement +// under the same JIT name that the old worker's exit then deletes (#192). The +// record's lock is held so the exiting goroutine parks at that step; while it +// is parked the assignment key must still be reserved. +func TestAssignmentKeyHeldUntilWorkerRecordGone(t *testing.T) { + release := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, []*scaleset.JobAssigned{assigned(1, "dup", "cpu-cores-1")}); err != nil { + t.Fatal(err) + } + reserved := func() bool { + l.assignedMu.Lock() + defer l.assignedMu.Unlock() + _, ok := l.assigned["dup"] + return ok + } + l.ledger.mu.Lock() + close(release) + deadline := time.Now().Add(300 * time.Millisecond) + for time.Now().Before(deadline) { + if !reserved() { + t.Error("assignment key was released while the worker record was still held") + break + } + time.Sleep(2 * time.Millisecond) + } + l.ledger.mu.Unlock() + l.wg.Wait() +} diff --git a/listener/hostprobe.go b/listener/hostprobe.go index 175287a..b6a26c5 100644 --- a/listener/hostprobe.go +++ b/listener/hostprobe.go @@ -215,6 +215,11 @@ func clampSize(h HostResources, size jobSize, reserve float64) jobSize { } } +// budgetOf is the host's whole budget in the unit jobs declare. +func budgetOf(h HostResources, reserve float64) jobSize { + return jobSize{cores: int64(coreBudget(h, reserve)), gb: int64(memBudget(h, reserve))} +} + // admits reports whether a job of the given size may start beside what is // already committed to running jobs. Its cores and GiB must each fit their // budget, CPU free from loadavg must still keep the reserve (load the listener @@ -231,8 +236,8 @@ func admits(h HostResources, committed, cost jobSize, reserve float64) bool { // admitCount returns how many ADDITIONAL default-size jobs fit now, clamped to // ceiling. A job's declared size is only known once GitHub assigns it, so the -// capacity advertised ahead of that assumes defaultJob; a larger job waits in -// admitOne until it fits. +// capacity advertised ahead of that assumes defaultJob; a larger job is not +// admitted that round and is retried on the next message. func admitCount(h HostResources, committed jobSize, reserve float64, ceiling int) int { cost := clampSize(h, defaultJob, reserve) n := 0 diff --git a/listener/job_workdir_test.go b/listener/job_workdir_test.go index 85b7aae..82b01f7 100644 --- a/listener/job_workdir_test.go +++ b/listener/job_workdir_test.go @@ -230,10 +230,10 @@ func TestListenerRefusesUnsafeSocketJobIDs(t *testing.T) { } var mintedSafe, provisionedSafe bool for _, setting := range *minted { - if setting.Name == id || setting.Name == canonicalJobID(id) { + if jobOfRunner(setting.Name) == id || jobOfRunner(setting.Name) == canonicalJobID(id) { t.Errorf("minted unsafe job %q", id) } - mintedSafe = mintedSafe || setting.Name == "safe-next" + mintedSafe = mintedSafe || jobOfRunner(setting.Name) == "safe-next" } for _, job := range prov.jobs { if job.RequestID == 1 { diff --git a/listener/ledger.go b/listener/ledger.go new file mode 100644 index 0000000..ce9086a --- /dev/null +++ b/listener/ledger.go @@ -0,0 +1,189 @@ +package listener + +import ( + "sync" + + "github.com/actions/scaleset" +) + +// retiredCap bounds how many started or completed job ids the ledger +// remembers: the most recent retiredCap of them. A retired id only has to +// outlive the redelivery of its own assignment, so the oldest are forgotten +// first, and an assignment replayed after its id was forgotten is known again. +const retiredCap = 4096 + +// ledgerWorker is what one runner currently holds: a reactive size, or VRAM +// on one GPU. +type ledgerWorker struct { + token uint64 + size jobSize + budget jobSize // the host budget of the probe that admitted it; zero when none, kept so a re-attribution clamps to the same snapshot + gpu int // pinned GPU index, or -1 when not pinned + vramGB int64 // GiB charged on gpu + totalMiB int64 // the pinned card's total VRAM, kept so a probe that omits the card cannot change a clamp +} + +// ledger owns the charge lifecycle of every runner (#192): a job becomes a +// known assignment, a runner is charged for it, the job starts and the charge +// is re-attributed, then the runner exits. One mutex guards all of it and the +// committed totals are sums over the held workers, never incremental +// counters, so no order of these events can leave a total negative or +// stranded: +// +// - a started or completed job id is retired first, as a set, and while it +// is among the most recent retiredCap retired ids it cannot re-enter the +// known assignments; +// - a runner name already held is refused, so a redelivered assignment +// cannot overwrite a live record; +// - an exit removes a record only when it still carries the exiting +// worker's token, so a stale exit cannot delete a replacement. +type ledger struct { + mu sync.Mutex + known map[string][]string // job id -> labels of assignments not yet started or completed + retired map[string]struct{} + retiredOrder []string + workers map[string]*ledgerWorker // JIT runner name -> current charge + nextToken uint64 +} + +func newLedger() *ledger { + return &ledger{ + known: make(map[string][]string), + retired: make(map[string]struct{}), + workers: make(map[string]*ledgerWorker), + } +} + +// noteEnvelope applies one envelope's job events in a single critical +// section: the started and completed ids are retired first, then only the +// assignments not retired are recorded, whatever order the envelope listed +// them in. A started job is retired whether or not this listener holds the +// runner that took it: the job is no longer waiting for a runner, so it stops +// sizing the next one. Charges are not touched here. +func (g *ledger) noteEnvelope(assigned []*scaleset.JobAssigned, started []*scaleset.JobStarted, completed []*scaleset.JobCompleted) { + g.mu.Lock() + defer g.mu.Unlock() + for _, js := range started { + if js != nil { + g.retire(js.JobID) + } + } + for _, jc := range completed { + if jc != nil { + g.retire(jc.JobID) + } + } + for _, job := range assigned { + if job == nil { + continue + } + if _, gone := g.retired[job.JobID]; !gone { + g.known[job.JobID] = job.RequestLabels + } + } +} + +// retire forgets a job's assignment and remembers its id. g.mu is held. +func (g *ledger) retire(jobID string) { + delete(g.known, jobID) + if _, seen := g.retired[jobID]; seen { + return + } + g.retired[jobID] = struct{}{} + g.retiredOrder = append(g.retiredOrder, jobID) + if len(g.retiredOrder) > retiredCap { + delete(g.retired, g.retiredOrder[0]) + g.retiredOrder = g.retiredOrder[1:] + } +} + +// knownDeclared is the largest declared size among the known assignments +// (defaultJob when there are none) with their label sets, for the GPU gate. +func (g *ledger) knownDeclared() (jobSize, [][]string) { + g.mu.Lock() + defer g.mu.Unlock() + if len(g.known) == 0 { + return defaultJob, nil + } + var cost jobSize + sets := make([][]string, 0, len(g.known)) + for _, labels := range g.known { + s := jobSizeOf(labels) + cost.cores, cost.gb = max(cost.cores, s.cores), max(cost.gb, s.gb) + sets = append(sets, labels) + } + return cost, sets +} + +// dispatch records the charge of the runner named name. It refuses a name that +// is already held (a duplicate or redelivered assignment) without changing +// anything; the caller then drops the runner. +func (g *ledger) dispatch(name string, w ledgerWorker) (token uint64, ok bool) { + g.mu.Lock() + defer g.mu.Unlock() + if _, held := g.workers[name]; held { + return 0, false + } + g.nextToken++ + w.token = g.nextToken + g.workers[name] = &w + return w.token, true +} + +// started replaces the charge of the runner named name with what resize makes +// of its current record. It reports false for a runner the ledger does not +// hold, leaving every charge unchanged. +func (g *ledger) started(name string, resize func(ledgerWorker) ledgerWorker) bool { + g.mu.Lock() + defer g.mu.Unlock() + w, ok := g.workers[name] + if !ok { + return false + } + token := w.token + *w = resize(*w) + w.token = token + return true +} + +// exit releases the charge of the runner named name, only when the record is +// still the exiting worker's own. +func (g *ledger) exit(name string, token uint64) { + g.mu.Lock() + defer g.mu.Unlock() + if w, ok := g.workers[name]; ok && w.token == token { + delete(g.workers, name) + } +} + +// committedSize is the size committed to held runners. +func (g *ledger) committedSize() jobSize { + g.mu.Lock() + defer g.mu.Unlock() + var sum jobSize + for _, w := range g.workers { + sum = sum.plus(w.size) + } + return sum +} + +// vramByGPU sums the VRAM, in GiB, held per GPU index. Key -1 counts the +// runners holding every GPU because they were not pinned, one each. +func (g *ledger) vramByGPU() map[int]int64 { + g.mu.Lock() + defer g.mu.Unlock() + sums := make(map[int]int64) + for _, w := range g.workers { + if w.gpu < 0 { + sums[-1]++ + } else if w.vramGB > 0 { + sums[w.gpu] += w.vramGB + } + } + return sums +} + +// vramCommitted is the VRAM, in GiB, committed on GPU gpu. +func (g *ledger) vramCommitted(gpu int) int64 { + return g.vramByGPU()[gpu] +} diff --git a/listener/ledger_test.go b/listener/ledger_test.go new file mode 100644 index 0000000..c85cc95 --- /dev/null +++ b/listener/ledger_test.go @@ -0,0 +1,129 @@ +package listener + +import ( + "testing" + + "github.com/actions/scaleset" +) + +// holdCharge puts a charge in the ledger as a runner named name, for tests +// that need a runner already holding budget. +func holdCharge(l *Listener, name string, w ledgerWorker) uint64 { + token, ok := l.ledger.dispatch(name, w) + if !ok { + panic("holdCharge: name already held: " + name) + } + return token +} + +func jobStarted(jobID, runner string, labels ...string) *scaleset.JobStarted { + js := &scaleset.JobStarted{RunnerName: runner} + js.JobID = jobID + js.RequestLabels = labels + return js +} + +func jobCompleted(jobID string) *scaleset.JobCompleted { + jc := &scaleset.JobCompleted{} + jc.JobID = jobID + return jc +} + +// Review round 3 (#192): the charge lifecycle must not depend on the order its +// events arrive in. Each case replays one order over the ledger and expects +// literal outcomes: nothing known for a started or completed job, nothing +// committed once every worker exited, and a replacement worker never released +// by an older exit. +func TestLedgerOrderInsensitive(t *testing.T) { + cpu := jobSize{cores: 4, gb: 16} + one := jobSize{cores: 1, gb: 4} + resizeTo := func(s jobSize) func(ledgerWorker) ledgerWorker { + return func(w ledgerWorker) ledgerWorker { w.size = s; return w } + } + big := func() []*scaleset.JobAssigned { return []*scaleset.JobAssigned{assigned(1, "job", "cpu-cores-4")} } + started := func() []*scaleset.JobStarted { return []*scaleset.JobStarted{jobStarted("job", "r", "cpu-cores-1")} } + done := func() []*scaleset.JobCompleted { return []*scaleset.JobCompleted{jobCompleted("job")} } + + tests := []struct { + name string + run func(g *ledger) (held jobSize) + wantKnown int + wantHeld jobSize + }{ + {"assign then start then exit", func(g *ledger) jobSize { + g.noteEnvelope(big(), nil, nil) + tok, _ := g.dispatch("r", ledgerWorker{size: cpu}) + g.noteEnvelope(nil, started(), nil) + g.started("r", resizeTo(one)) + held := g.committedSize() + g.exit("r", tok) + return held + }, 0, one}, + {"start before assign", func(g *ledger) jobSize { + g.noteEnvelope(nil, started(), nil) + g.noteEnvelope(big(), nil, nil) + return jobSize{} + }, 0, jobSize{}}, + {"assign start complete in one envelope", func(g *ledger) jobSize { + g.noteEnvelope(big(), started(), done()) + return jobSize{} + }, 0, jobSize{}}, + {"exit before start", func(g *ledger) jobSize { + g.noteEnvelope(big(), nil, nil) + tok, _ := g.dispatch("r", ledgerWorker{size: cpu}) + g.exit("r", tok) + g.started("r", resizeTo(one)) + g.noteEnvelope(nil, started(), nil) + return g.committedSize() + }, 0, jobSize{}}, + {"duplicate dispatch refused", func(g *ledger) jobSize { + g.dispatch("r", ledgerWorker{size: cpu}) + if _, ok := g.dispatch("r", ledgerWorker{size: cpu}); ok { + t.Error("a name already held was dispatched again") + } + return g.committedSize() + }, 0, cpu}, + {"stale exit after replacement", func(g *ledger) jobSize { + old, _ := g.dispatch("r", ledgerWorker{size: cpu}) + g.exit("r", old) + g.dispatch("r", ledgerWorker{size: one}) + g.exit("r", old) + return g.committedSize() + }, 0, one}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := newLedger() + held := tc.run(g) + if held != tc.wantHeld { + t.Errorf("held = %+v, want %+v", held, tc.wantHeld) + } + if len(g.known) != tc.wantKnown { + t.Errorf("known assignments = %d, want %d", len(g.known), tc.wantKnown) + } + for name, w := range g.workers { + g.exit(name, w.token) + } + if got := g.committedSize(); got != (jobSize{}) { + t.Errorf("committed after every exit = %+v, want 0", got) + } + }) + } +} + +// Review round 3 (#192): when a later good probe omits the pinned card, the +// ledger keeps the budget it stored for that card. +func TestLedgerGPUBudgetStored(t *testing.T) { + g := newLedger() + g.dispatch("r", ledgerWorker{gpu: 0, vramGB: 16, totalMiB: 32768}) + if got := g.vramCommitted(0); got != 16 { + t.Fatalf("card 0 committed = %d, want 16", got) + } + if got := g.vramCommitted(1); got != 0 { + t.Fatalf("card 1 committed = %d, want 0", got) + } + g.dispatch("loose", ledgerWorker{gpu: -1}) + if got := g.vramByGPU()[-1]; got != 1 { + t.Errorf("unpinned holders = %d, want 1", got) + } +} diff --git a/listener/listener.go b/listener/listener.go index c6fd923..d0b9a66 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -11,6 +11,7 @@ import ( "crypto/rand" "encoding/hex" "errors" + "fmt" "log" "os" "path/filepath" @@ -30,12 +31,6 @@ import ( // a Reaper is configured but no interval is set. const defaultReapInterval = 5 * time.Minute -// defaultSettleWindow is how long reactive admission waits before re-probing -// when the host is at/over the reserve line (#163): long enough for a just- -// started job to begin showing in the lagging loadavg, short enough not to stall -// throughput. Overridable via Config.SettleWindow (tests use milliseconds). -const defaultSettleWindow = 3 * time.Second - // defaultPoolBound is the worker-pool ceiling used when no MaxRunners is // configured -- a sane, conservative concurrency default so an unconfigured // listener still bounds in-flight jobs rather than spawning unboundedly. @@ -122,6 +117,10 @@ type Provisioner interface { Provision(ctx context.Context, req ProvisionRequest) error } +// runnerNameStamp makes the JIT runner names of one listener start differ from +// those of another; a test replaces it to get predictable names. +var runnerNameStamp = func() string { return uuid.NewString()[:8] } + // JITConfigMinter mints the single-use, server-side JIT config a given runner // consumes once (`run.sh --jitconfig `) and then de-registers. The // production implementation (ClientJITMinter, wired in main.go) calls the @@ -187,10 +186,6 @@ type Config struct { // Zero falls back to defaultReservePercent (defaultVRAMReservePercent with // a GPUProbe). Ignored when neither probe is set. Reserve int - // SettleWindow is how long admission waits before re-probing when the host is - // at/over the reserve line (near-line serialization, #163). Zero falls back - // to defaultSettleWindow. Ignored when HostProbe is nil. - SettleWindow time.Duration // Reaper, when set, sweeps orphaned containers on startup and on // ReapInterval (#105), sparing the listener's currently-tracked jobs. Nil // disables reaping. @@ -252,30 +247,30 @@ type Listener struct { sem chan struct{} // counting semaphore: one token per in-flight slot wg sync.WaitGroup inFlight atomic.Int64 // jobs currently being provisioned (locally derived capacity, #102) - // committedCores and committedGB sum the sizes running jobs declared - // (ADR-0006), charged at dispatch and released when the job exits. - // last holds the latest probe, used to clamp a declared size (cpu-cores-all, - // ram-gb-all, or a value above the host) to the budgets. - committedCores atomic.Int64 - committedGB atomic.Int64 - last atomic.Pointer[HostResources] + // ledger owns every runner's charge from dispatch to exit (ADR-0006, + // #192). last holds the latest admission probe, used only when a later + // admission probe fails, to clamp a declared size to the budgets. + ledger *ledger + last atomic.Pointer[HostResources] + // nameStamp and runnerSeq make every dispatch's JIT runner name unique: the + // stamp differs per listener start, the sequence per dispatch (#192). + nameStamp string + runnerSeq atomic.Uint64 // Reactive live-admission (ADR-0005, #163): when probe is set, each job is - // admitted only while every resource keeps reserve headroom free; settle is - // how long admission waits before re-probing at/over the line. Nil probe = - // the fixed/device ceiling path (probe-less). + // admitted only while every resource keeps reserve headroom free; a job that + // does not fit ends the reconcile round and is retried on the next message + // (#192). Nil probe = the fixed/device ceiling path (probe-less). probe HostProbe reserve float64 // fraction in [0,1]; the per-resource headroom kept free - settle time.Duration - // Shared-GPU admission (#180): gpuProbe reads per-GPU VRAM; committedVRAM - // sums, per GPU index, the GiB running jobs were charged at dispatch, and - // lastGPUs is the latest good reading, the fail-safe's GPU list when the - // probe errors. All guarded by vramMu. - gpuProbe GPUProbe - vramMu sync.Mutex - committedVRAM map[int]int64 - lastGPUs []GPU + // Shared-GPU admission (#180): gpuProbe reads per-GPU VRAM; the VRAM + // charged per GPU index is summed by the ledger, and lastGPUs is the latest + // good reading, the fail-safe's GPU list when the probe errors. lastGPUs is + // guarded by vramMu. + gpuProbe GPUProbe + vramMu sync.Mutex + lastGPUs []GPU reapMu sync.Mutex // keeps new socket workdirs out of a sweep with an older tracked snapshot trackedMu sync.Mutex // guards tracked @@ -304,24 +299,20 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) reserve = max(reserve, float64(minVRAMReservePercent)/100) } } - settle := cfg.SettleWindow - if settle <= 0 { - settle = defaultSettleWindow - } return &Listener{ - session: session, - minter: minter, - prov: prov, - cfg: cfg, - bound: bound, - sem: make(chan struct{}, bound), - probe: cfg.HostProbe, - gpuProbe: cfg.GPUProbe, - committedVRAM: make(map[int]int64), - reserve: reserve, - settle: settle, - tracked: make(map[string]int), - assigned: make(map[string]struct{}), + session: session, + minter: minter, + prov: prov, + cfg: cfg, + bound: bound, + sem: make(chan struct{}, bound), + probe: cfg.HostProbe, + gpuProbe: cfg.GPUProbe, + ledger: newLedger(), + nameStamp: runnerNameStamp(), + reserve: reserve, + tracked: make(map[string]int), + assigned: make(map[string]struct{}), } } @@ -353,8 +344,10 @@ func resolveBound(cfg Config) int { return defaultPoolBound } -// Listen advertises the resolved pool bound on every poll. It reconciles -// assigned demand at startup, on messages with statistics, and on empty polls. +// Listen advertises the resolved pool bound on every poll. It retries +// admission at startup, on every message envelope and on empty polls, against +// the latest statistics: an envelope without statistics (a JobStarted or +// JobCompleted that frees budget) reuses the last ones it saw. // It acknowledges each envelope before acquiring its available jobs in one // bounded request, even during shutdown. New runners pass local admission before // minting and dispatch. Mint errors end Listen; provisioning failures are @@ -420,14 +413,22 @@ func (l *Listener) Listen(ctx context.Context) (err error) { return err } lastMessageID = msg.MessageID + // The ledger applies the whole envelope at once, so a job assigned and + // started in one envelope is never left in the known set (#192). A + // started job leaves the known set even when its runner is not one this + // listener holds; handleJobStarted then leaves every charge unchanged. + l.ledger.noteEnvelope(msg.JobAssignedMessages, msg.JobStartedMessages, msg.JobCompletedMessages) + l.handleJobStarted(msg.JobStartedMessages) if err := l.acquire(ctx, msg.JobAvailableMessages); err != nil { return err } + // Every envelope retries admission: a JobStarted or JobCompleted frees + // budget even when it carries no fresh statistics (#192). if msg.Statistics != nil { latest = msg.Statistics - if err := l.reconcile(ctx, latest, msg.JobAssignedMessages); err != nil { - return err - } + } + if err := l.dispatch(ctx, latest, msg.JobAssignedMessages); err != nil { + return err } } } @@ -453,6 +454,10 @@ func (l *Listener) acquire(ctx context.Context, jobs []*scaleset.JobAvailable) e type assignedRequest struct { ProvisionRequest rawJobID string + // runnerName is the JIT runner name minted for this dispatch: the raw job + // id plus a suffix of its own, so a message for an earlier runner of the + // same assignment never names this one (#192). + runnerName string } func (l *Listener) reserveAssignment(rawJobID string) bool { @@ -475,6 +480,13 @@ func (l *Listener) releaseAssignment(rawJobID string) { // through exit, including any time the runner spends waiting for a job. An // assignment can supply metadata for one of the new runners. func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSetStatistic, jobs []*scaleset.JobAssigned) error { + l.ledger.noteEnvelope(jobs, nil, nil) + return l.dispatch(ctx, stats, jobs) +} + +// dispatch mints runners for the shortfall against stats; the caller has +// already recorded jobs as known. +func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetStatistic, jobs []*scaleset.JobAssigned) error { if stats == nil { return nil } @@ -506,15 +518,18 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet if ctx.Err() != nil { return nil } - // The size the next job declares (ADR-0006). A spare runner with no - // assignment yet runs whatever GitHub hands it, so it costs the default. - var labels []string - if len(pending) > 0 { - labels = pending[0].RequestLabels - } - cost := jobSizeOf(labels) - if l.gpuProbe == nil && l.probe != nil && !l.admitOne(ctx, cost) { - return nil + // The runner is minted before GitHub says which job it takes, so it is + // charged the largest declaration among the assignments known not to + // have started, the default when there is none (ADR-0006, #192). + // JobStarted corrects the charge once the real job is known. + cost, labelSets := l.ledger.knownDeclared() + var charged, budget jobSize + if l.gpuProbe == nil && l.probe != nil { + var admitted bool + charged, budget, admitted = l.admitOne(ctx, cost) + if !admitted { + return nil + } } // Acquire a worker slot (back-pressure when the pool is full). Honour // cancellation so shutdown does not block forever waiting for a slot. @@ -531,22 +546,13 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet gpu, minor, vramGB, vramTotalMiB := -1, -1, int64(0), int64(0) if l.gpuProbe != nil { var ok bool - gpu, minor, vramGB, vramTotalMiB, ok = l.admitGPU(ctx, labels) + gpu, minor, vramGB, vramTotalMiB, ok = l.admitGPU(ctx, labelSets...) if !ok || ctx.Err() != nil { <-l.sem return nil } } - // Charge only now, after the slot and the ctx check (#177), so a - // cancelled admission never holds a size or VRAM. - var charged jobSize - if l.gpuProbe != nil { - l.chargeGPU(gpu, vramGB) - } else if l.probe != nil { - charged = l.charge(cost) - } - var job scaleset.JobAssigned hasAssignment := len(pending) > 0 if hasAssignment { @@ -554,9 +560,28 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet } else { job.JobID = "runner-" + uuid.NewString() } + // Charge only now, after the slot and the ctx check (#177), so a + // cancelled admission never holds a size or VRAM. A redelivered + // assignment never gets here while its first runner runs: + // reserveAssignment skips it above. Each dispatch mints a fresh runner + // name, so the ledger's refusal of a held name is only a guard (#192). + // The charge is the size admitOne admitted, with the budget of the same + // probe, never a later read of a snapshot another probe replaced. + runnerName := fmt.Sprintf("%s-%s%d", job.JobID, l.nameStamp, l.runnerSeq.Add(1)) + token, held := l.ledger.dispatch(runnerName, ledgerWorker{size: charged, budget: budget, gpu: gpu, vramGB: vramGB, totalMiB: vramTotalMiB}) + if !held { + log.Printf("dropping assignment for job %q: a runner of that name is already held", job.JobID) + <-l.sem + if hasAssignment { + pending = pending[1:] + l.releaseAssignment(job.JobID) + } + continue + } jobID := canonicalJobID(job.JobID) req := assignedRequest{ - rawJobID: job.JobID, + rawJobID: job.JobID, + runnerName: runnerName, ProvisionRequest: ProvisionRequest{ JobID: jobID, RequestID: job.RunnerRequestID, @@ -576,10 +601,7 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet workDir, err := socketJobWorkDir(jobID) if err != nil { <-l.sem - l.release(charged) - if l.gpuProbe != nil { - l.releaseGPU(gpu, vramGB) - } + l.ledger.exit(req.runnerName, token) if hasAssignment { pending = pending[1:] l.releaseAssignment(req.rawJobID) @@ -592,14 +614,11 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet // Once minting starts, finish the bounded request and dispatch on // success even if shutdown begins during the request. requestCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), l.cfg.RequestTimeout) - jit, err := l.minter.Mint(requestCtx, job.JobID, job.RequestLabels, req.JobWorkDir) + jit, err := l.minter.Mint(requestCtx, runnerName, job.RequestLabels, req.JobWorkDir) cancel() if err != nil { <-l.sem - l.release(charged) - if l.gpuProbe != nil { - l.releaseGPU(gpu, vramGB) - } + l.ledger.exit(req.runnerName, token) return err } req.EncodedJITConfig = jit @@ -609,17 +628,16 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet l.wg.Add(1) l.inFlight.Add(1) l.track(req.JobID) - go func(req assignedRequest, hasAssignment bool, charged jobSize) { + go func(req assignedRequest, hasAssignment bool) { defer l.wg.Done() defer l.inFlight.Add(-1) defer func() { <-l.sem }() - defer l.release(charged) - if l.gpuProbe != nil { - defer l.releaseGPU(req.GPU, req.VRAMGB) - } + // Defers run last to first: the charge record is released before + // the assignment key becomes reusable (#192). if hasAssignment { defer l.releaseAssignment(req.rawJobID) } + defer l.ledger.exit(req.runnerName, token) defer l.untrack(req.JobID) // Time the job so the structured per-job record carries its duration // (#131). The container exit status comes from the Provision result: @@ -630,7 +648,7 @@ func (l *Listener) reconcile(ctx context.Context, stats *scaleset.RunnerScaleSet if err != nil { l.reportJobErr(req.ProvisionRequest, err) } - }(req, hasAssignment, charged) + }(req, hasAssignment) } return nil } @@ -871,104 +889,120 @@ func (l *Listener) reactiveCapacity(ctx context.Context) int { if err != nil { return 1 } - l.last.Store(&h) return admitCount(h, l.committedSize(), l.reserve, l.bound) } -// admitOne is the per-job reactive gate (#163): it blocks until admitting one -// more job keeps every resource at/above the reserve, re-probing after a settle -// window while the host is at/over the line (near-line serialization). It fails -// safe -- a probe error admits (the semaphore ceiling is the backstop, and -// stranding acquired work is worse than a brief over-admit). It returns false -// only when the context is cancelled, so a shutdown never blocks on a full host. -func (l *Listener) admitOne(ctx context.Context, cost jobSize) bool { - for { - h, err := l.probe.Probe(ctx) - if err != nil { - return true - } - l.last.Store(&h) - if admits(h, l.committedSize(), clampSize(h, cost, l.reserve), l.reserve) { - return true - } - select { - case <-time.After(l.settle): - case <-ctx.Done(): - return false +// admitOne is the per-job reactive gate (#163, #192): one probe, then it +// reports whether admitting one more job keeps every resource at/above the +// reserve. A job that does not fit is not admitted this round; the message loop +// keeps polling and the next dispatch decision re-probes. It returns the size +// to charge and the host budget, both from the probe that made the decision, so +// the charge is the admitted size. It fails safe -- a probe error admits (the +// semaphore ceiling is the backstop, and stranding acquired work is worse than +// a brief over-admit), clamped to the last admission probe if there was one. +func (l *Listener) admitOne(ctx context.Context, cost jobSize) (charge, budget jobSize, ok bool) { + h, err := l.probe.Probe(ctx) + if err != nil { + if last := l.last.Load(); last != nil { + return clampSize(*last, cost, l.reserve), budgetOf(*last, l.reserve), true } + return cost, jobSize{}, true } + l.last.Store(&h) + charge = clampSize(h, cost, l.reserve) + return charge, budgetOf(h, l.reserve), admits(h, l.committedSize(), charge, l.reserve) } -// charge commits an admitted job's declared size, clamped to the latest -// probe's budgets so a whole-host declaration holds exactly the whole budget, -// and returns the amount to release when the job exits. If no probe has -// succeeded, retain the declared cost so the job is fully accounted for once -// probing recovers. -func (l *Listener) charge(cost jobSize) jobSize { - charged := cost - if h := l.last.Load(); h != nil { - charged = clampSize(*h, cost, l.reserve) +// handleJobStarted re-attributes each started job's runner to the size the job +// really declared (#192): the runner was charged the largest known declaration +// when it was minted. A GPU runner keeps its card and is clamped to the budget +// the ledger stored for that card, never to the live probe list. A runner this +// listener does not hold is logged and every charge is left unchanged; its job +// has already left the known assignments (ledger.noteEnvelope). +func (l *Listener) handleJobStarted(started []*scaleset.JobStarted) { + for _, js := range started { + if js == nil { + continue + } + labels := js.RequestLabels + held := l.ledger.started(js.RunnerName, func(w ledgerWorker) ledgerWorker { + switch { + case l.gpuProbe != nil: + if w.gpu < 0 { + return w + } + gb := int64(jobVRAM(labels, int(wholeGPU))) + if w.totalMiB > 0 { + gb = min(gb, int64(vramBudget(GPU{TotalMiB: w.totalMiB}, l.reserve))) + } else { + gb = min(gb, w.vramGB) + } + w.vramGB = gb + case l.probe != nil: + w.size = jobSizeOf(labels) + if w.budget != (jobSize{}) { + w.size = jobSize{cores: min(w.size.cores, w.budget.cores), gb: min(w.size.gb, w.budget.gb)} + } + } + return w + }) + if !held { + log.Printf("job started on unknown runner %q: charge left unchanged", js.RunnerName) + } } - l.committedCores.Add(charged.cores) - l.committedGB.Add(charged.gb) - return charged -} - -// release returns a job's charged size when it exits or fails to start. -func (l *Listener) release(charged jobSize) { - l.committedCores.Add(-charged.cores) - l.committedGB.Add(-charged.gb) } // committedSize is the total size committed to running jobs. func (l *Listener) committedSize() jobSize { - return jobSize{cores: l.committedCores.Load(), gb: l.committedGB.Load()} + return l.ledger.committedSize() } -// admitGPU is the per-job shared-GPU gate (#180, ADR-0007): it blocks until a -// GPU can take the job's declared VRAM (pickGPU), re-probing after the settle -// window while none can, and returns the GPU index, device minor and GiB to -// charge there, plus that card's total MiB (#185; 0 when not pinned). The total -// is taken from the selected reading under the same lock, never looked up later -// in a snapshot the capacity reporter may have replaced. It returns false only -// when the context is cancelled. +// admitGPU is the per-job shared-GPU gate (#180, ADR-0007, #192): one probe and +// one pickGPU, returning the GPU index, device minor and GiB to charge there, +// plus that card's total MiB (#185; 0 when not pinned). The total is taken from +// the selected reading under the same lock, never looked up later in a snapshot +// the capacity reporter may have replaced. It returns false when no GPU can +// take the job's declared VRAM this round; the next dispatch decision re-probes. // // It fails safe when the probe errors: whole-GPU, one job per GPU, over the // last good GPU list (only a GPU with nothing committed takes a job, charged // its whole budget). With no reading ever, it admits only while nothing is in // flight, and the unpinned job holds the host until it exits. // Run serializes dispatch, so only releases can change commitments between -// this selection and chargeGPU. -func (l *Listener) admitGPU(ctx context.Context, labels []string) (gpu, minor int, gb, totalMiB int64, ok bool) { - for { - want := int64(jobVRAM(labels, int(wholeGPU))) - gpus, err := l.gpuProbe.Probe(ctx) - l.vramMu.Lock() - if err == nil && len(gpus) > 0 { - l.lastGPUs = gpus - } else { - gpus, want = idleReadings(l.lastGPUs), wholeGPU - } - if l.committedVRAM[-1] == 0 { - switch { - case len(gpus) > 0: - selected, cost, fits := pickGPU(gpus, l.committedVRAM, want, l.reserve) - gpu, minor, gb, ok = selected.Index, selected.Minor, cost, fits - totalMiB = selected.TotalMiB - case l.inFlight.Load() == 0: - gpu, minor, ok = -1, -1, true - } - } - l.vramMu.Unlock() - if ok { - return gpu, minor, gb, totalMiB, true - } - select { - case <-time.After(l.settle): - case <-ctx.Done(): +// this selection and the ledger dispatch. +func (l *Listener) admitGPU(ctx context.Context, labelSets ...[]string) (gpu, minor int, gb, totalMiB int64, ok bool) { + // The largest declaration among the label sets (#192); no set means a + // whole GPU. + want := int64(0) + for _, labels := range labelSets { + want = max(want, int64(jobVRAM(labels, int(wholeGPU)))) + } + if want == 0 { + want = wholeGPU + } + gpus, err := l.gpuProbe.Probe(ctx) + l.vramMu.Lock() + defer l.vramMu.Unlock() + if err == nil && len(gpus) > 0 { + l.lastGPUs = gpus + } else { + gpus, want = idleReadings(l.lastGPUs), wholeGPU + } + committed := l.ledger.vramByGPU() + if committed[-1] != 0 { + return 0, 0, 0, 0, false + } + switch { + case len(gpus) > 0: + selected, cost, fits := pickGPU(gpus, committed, want, l.reserve) + if !fits { return 0, 0, 0, 0, false } + return selected.Index, selected.Minor, cost, selected.TotalMiB, true + case l.inFlight.Load() == 0: + return -1, -1, 0, 0, true } + return 0, 0, 0, 0, false } // idleReadings returns the GPUs with their stale live usage dropped, for the @@ -982,34 +1016,9 @@ func idleReadings(gpus []GPU) []GPU { return out } -// chargeGPU commits gb GiB on GPU gpu at dispatch. An unpinned job (gpu < 0) -// holds every GPU until it exits, even if the probe recovers. -func (l *Listener) chargeGPU(gpu int, gb int64) { - if gpu < 0 { - gb = 1 - } - l.vramMu.Lock() - l.committedVRAM[gpu] += gb - l.vramMu.Unlock() -} - -// releaseGPU returns a job's charged VRAM when it exits or fails to start. -func (l *Listener) releaseGPU(gpu int, gb int64) { - if gpu < 0 { - gb = 1 - } - l.vramMu.Lock() - if l.committedVRAM[gpu] -= gb; l.committedVRAM[gpu] <= 0 { - delete(l.committedVRAM, gpu) - } - l.vramMu.Unlock() -} - // vramCommitted is the VRAM, in GiB, committed to running jobs on GPU gpu. func (l *Listener) vramCommitted(gpu int) int64 { - l.vramMu.Lock() - defer l.vramMu.Unlock() - return l.committedVRAM[gpu] + return l.ledger.vramCommitted(gpu) } // vramCapacity estimates how many GPUs can take another minimum-size job, @@ -1028,7 +1037,8 @@ func (l *Listener) vramCapacity(ctx context.Context, inFlight int) int { } else { l.lastGPUs = gpus } - if l.committedVRAM[-1] != 0 { + committed := l.ledger.vramByGPU() + if committed[-1] != 0 { return 0 } if len(gpus) == 0 && inFlight == 0 { @@ -1036,7 +1046,7 @@ func (l *Listener) vramCapacity(ctx context.Context, inFlight int) int { } n := 0 for _, g := range gpus { - if _, _, ok := pickGPU([]GPU{g}, l.committedVRAM, want, l.reserve); ok { + if _, _, ok := pickGPU([]GPU{g}, committed, want, l.reserve); ok { n++ } } diff --git a/listener/listener_test.go b/listener/listener_test.go index 23aaa9a..2fd2cc1 100644 --- a/listener/listener_test.go +++ b/listener/listener_test.go @@ -31,6 +31,7 @@ type fakeSession struct { checkContext bool getErr error // returned once messages are drained (a real transport error) cancel context.CancelFunc // if set, called when messages drain to end the loop via ctx + idleGate <-chan struct{} // if set, drained polls wait for it, then return empty messages until ctx ends (#192) polledAfter []int // lastMessageID passed to each GetMessage protocol []string // acquire and ack calls in order closeErr error @@ -49,6 +50,19 @@ func (f *fakeSession) GetMessage(ctx context.Context, lastMessageID int, maxCapa f.polledAfter = append(f.polledAfter, lastMessageID) f.reportedCap = append(f.reportedCap, maxCapacity) f.mu.Unlock() + if len(f.messages) == 0 && f.idleGate != nil { + select { + case <-ctx.Done(): + return nil, fmt.Errorf("failed to get next message: %w", ctx.Err()) + case <-f.idleGate: + } + select { + case <-ctx.Done(): + return nil, fmt.Errorf("failed to get next message: %w", ctx.Err()) + case <-time.After(5 * time.Millisecond): + return nil, nil + } + } if len(f.messages) == 0 { // A genuine transport error ends the loop with that error. if f.getErr != nil { @@ -1249,7 +1263,7 @@ func TestListenDeduplicatesInFlightRawJobID(t *testing.T) { if err := l.Listen(context.Background()); !errors.Is(err, stop) { t.Fatalf("Listen returned %v, want %v", err, stop) } - if want := []string{jobID, siblingID, jobID}; !slices.Equal(minter.gotNames, want) { + if want, got := []string{jobID, siblingID, jobID}, jobsOfRunners(minter.gotNames); !slices.Equal(got, want) { t.Errorf("Mint names = %q, want %q", minter.gotNames, want) } var provisioned []int64 @@ -1383,7 +1397,7 @@ func TestListenReturnsMintErrorAfterDispatchingEarlierAssignment(t *testing.T) { minter := &recordingMinter{ config: "jit", onMint: func(_ context.Context, name string) error { - if name == "failed" { + if jobOfRunner(name) == "failed" { return mintErr } return nil @@ -1395,7 +1409,7 @@ func TestListenReturnsMintErrorAfterDispatchingEarlierAssignment(t *testing.T) { if err := l.Listen(context.Background()); !errors.Is(err, mintErr) { t.Errorf("Listen returned %v, want %v", err, mintErr) } - if got := minter.gotNames; !slices.Equal(got, []string{"first", "failed"}) { + if got := jobsOfRunners(minter.gotNames); !slices.Equal(got, []string{"first", "failed"}) { t.Errorf("Mint names = %q, want [first failed]", got) } if len(prov.jobs) != 1 || prov.jobs[0].RequestID != 41 { @@ -1409,3 +1423,67 @@ func TestListenReturnsMintErrorAfterDispatchingEarlierAssignment(t *testing.T) { l.releaseAssignment(name) } } + +// #192: an idle runner holds the whole reactive budget, so the next dispatch is +// denied. The message loop must still go back to GetMessage/AcquireJobs: only +// later messages can start or finish jobs and free the budget. +func TestRunKeepsPollingWhenAdmissionFull(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + polledAfter3 := make(chan struct{}, 1) + sess := &fakeSession{ + messages: []*scaleset.RunnerScaleSetMessage{ + msgWithAssigned(1, 1, assigned(1, "a")), + msgWithAssigned(2, 2, assigned(2, "b")), + { + MessageID: 3, + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, + JobAvailableMessages: []*scaleset.JobAvailable{ + {JobMessageBase: scaleset.JobMessageBase{RunnerRequestID: 77}}, + }, + }, + }, + // The poll after message 3 runs only once its acquire and dispatch are done. + beforePoll: func(last int) { + if last == 3 { + select { + case polledAfter3 <- struct{}{}: + default: + } + } + }, + } + // Idle runner "a" stays inside Provision and keeps its charge. + block := make(chan struct{}) + prov := &recordingProvisioner{block: block} + mnt := &recordingMinter{config: "jit"} + // 2-core host, 10% reserve: budget 1 core, so one 1-core runner fills it. + l := New(sess, mnt, prov, Config{ + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 2, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + done := make(chan struct{}) + go func() { _ = l.Listen(ctx); close(done) }() + + select { + case <-polledAfter3: + case <-time.After(2 * time.Second): + t.Fatal("message loop stalled: it never polled again after the third message while admission was full") + } + if got := sess.acquiredReqIDs; len(got) != 1 || len(got[0]) != 1 || got[0][0] != 77 { + t.Errorf("acquired %v, want [[77]]", got) + } + if got := jobsOfRunners(mnt.gotNames); !slices.Equal(got, []string{"a"}) { + t.Errorf("minted runners for %q, want only [a]: b must be denied while a holds the budget", got) + } + if got := l.committedSize().cores; got != 1 { + t.Errorf("committed cores = %d, want 1 held by runner a", got) + } + // Release the blocked Provision before waiting: Listen's shutdown waits + // for workers and Provision ignores ctx. + cancel() + close(block) + <-done +} diff --git a/listener/reactive_test.go b/listener/reactive_test.go index e32b084..1ea3e41 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -13,7 +13,8 @@ import ( ) // countingProbe returns an over-the-line reading for its first overUntil calls, -// then a healthy one, so a test can prove admission re-probes after settling. +// then a healthy one, so a test can prove a denied dispatch is admitted on a +// later round, which probes again. type countingProbe struct { mu sync.Mutex calls int @@ -56,7 +57,7 @@ func TestReactiveCapacityFromHeadroom(t *testing.T) { } // Six cores committed: exactly one more one-core job fits. nearLine := newL(stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 0.30, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}) - nearLine.committedCores.Store(6) + holdCharge(nearLine, "held", ledgerWorker{size: jobSize{cores: 6}, gpu: -1}) if got := nearLine.capacityFor(0); got != 1 { t.Errorf("near-line capacity = %d, want 1", got) } @@ -74,7 +75,7 @@ func TestReactiveCapacityFromHeadroom(t *testing.T) { // The #163 success criterion: a burst of 8 CPU-heavy shards arriving in one // message must never breach the 10% line. On an 8-core host (cpu free 1.0) the -// budget is 7 cores, so 7 undeclared (one-core) shards run and the 8th parks +// budget is 7 cores, so 7 undeclared (one-core) shards run and the 8th is not admitted // until a slot frees, self-healing when a job finishes. The // safety ceiling (MaxRunners) is set high so only the reactive gate binds. func TestReactiveBurstNeverBreachesReserve(t *testing.T) { @@ -92,18 +93,18 @@ func TestReactiveBurstNeverBreachesReserve(t *testing.T) { started: make(chan struct{}, 8), release: make(chan struct{}), } + sess.idleGate = probe.release l := New(sess, &recordingMinter{config: "jit"}, probe, Config{ - Image: "img", - HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, - Reserve: 10, - SettleWindow: time.Millisecond, - MaxRunners: 100, + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, }) done := make(chan struct{}) go func() { _ = l.Listen(ctx); close(done) }() - // Exactly 7 may start; the 8th must park (reactive gate, not the semaphore). + // Exactly 7 may start; the 8th must not start (reactive gate, not the semaphore). for i := 0; i < 7; i++ { select { case <-probe.started: @@ -115,7 +116,7 @@ func TestReactiveBurstNeverBreachesReserve(t *testing.T) { case <-probe.started: t.Fatal("an 8th shard started -- the burst breached the 10% reserve line") case <-time.After(150 * time.Millisecond): - // good: the 8th is parked, waiting for headroom. + // good: the 8th is not admitted, waiting for headroom. } if got := probe.peakLive(); got > 7 { t.Fatalf("peak concurrency %d breached the reserve line (want <= 7)", got) @@ -126,7 +127,7 @@ func TestReactiveBurstNeverBreachesReserve(t *testing.T) { select { case <-probe.started: case <-time.After(2 * time.Second): - t.Fatal("the parked 8th shard never admitted after a slot freed") + t.Fatal("the unadmitted 8th shard never admitted after a slot freed") } cancel() <-done @@ -135,40 +136,24 @@ func TestReactiveBurstNeverBreachesReserve(t *testing.T) { } } -// Near/over the line, admission settles and re-probes rather than admitting or -// giving up: once headroom returns, the parked job admits. -func TestAdmitOneSettlesThenAdmits(t *testing.T) { +// Near/over the line, admission probes once and denies without waiting (#192); +// the next decision re-probes and admits once headroom returns. +func TestAdmitOneDeniesThenAdmitsOnNextProbe(t *testing.T) { p := &countingProbe{ - overUntil: 2, + overUntil: 1, over: HostResources{Free: map[Resource]float64{ResourceCPU: 0.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}, ok: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}, } l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{HostProbe: p, Reserve: 10, SettleWindow: time.Millisecond, MaxRunners: 100}) - if !l.admitOne(context.Background(), jobSize{1, 4}) { - t.Fatal("admitOne should admit once headroom returns") + Config{HostProbe: p, Reserve: 10, MaxRunners: 100}) + if _, _, ok := l.admitOne(context.Background(), jobSize{1, 4}); ok { + t.Fatal("admitOne must deny while over the line") } - if p.callCount() < 3 { - t.Errorf("expected re-probing after settle, calls = %d, want >= 3", p.callCount()) + if p.callCount() != 1 { + t.Errorf("probe calls after a denial = %d, want 1", p.callCount()) } -} - -// A context cancelled while admission is parked over the line unblocks cleanly -// (returns false) rather than settling forever. -func TestAdmitOneCtxCancelUnblocks(t *testing.T) { - p := &countingProbe{ - overUntil: 1 << 30, // always over the line - over: HostResources{Free: map[Resource]float64{ResourceCPU: 0.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}, - } - l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{HostProbe: p, Reserve: 10, SettleWindow: time.Hour, MaxRunners: 100}) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - time.Sleep(10 * time.Millisecond) - cancel() - }() - if l.admitOne(ctx, jobSize{1, 4}) { - t.Fatal("admitOne must return false when the context is cancelled while over the line") + if _, _, ok := l.admitOne(context.Background(), jobSize{1, 4}); !ok { + t.Fatal("admitOne should admit once headroom returns") } } @@ -233,19 +218,26 @@ func (p cancelOnProbe) Probe(context.Context) (HostResources, error) { // (budget 7 at reserve 10) and returns the provisioner that holds every job // until release is closed, so a test can see which jobs were admitted together. func heldListen(t *testing.T, jobs ...*scaleset.JobAssigned) (*labelProbe, func()) { + t.Helper() + return heldListenMsgs(t, len(jobs), msgWithAssigned(1, len(jobs), jobs...)) +} + +// heldListenMsgs is heldListen over scripted messages; capacity bounds how many +// started jobs the provisioner can queue. +func heldListenMsgs(t *testing.T, capacity int, msgs ...*scaleset.RunnerScaleSetMessage) (*labelProbe, func()) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) sess := &fakeSession{ - messages: []*scaleset.RunnerScaleSetMessage{msgWithAssigned(1, len(jobs), jobs...)}, + messages: msgs, cancel: cancel, } - prov := &labelProbe{started: make(chan string, len(jobs)), release: make(chan struct{})} + prov := &labelProbe{started: make(chan string, capacity), release: make(chan struct{})} + sess.idleGate = prov.release l := New(sess, &recordingMinter{config: "jit"}, prov, Config{ - Image: "img", - HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, - Reserve: 10, - SettleWindow: time.Millisecond, - MaxRunners: 100, + Image: "img", + HostProbe: stubProbe{res: HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: 8, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, }) done := make(chan struct{}) go func() { _ = l.Listen(ctx); close(done) }() @@ -281,7 +273,7 @@ func (p *labelProbe) next(t *testing.T, within time.Duration) (string, bool) { } } -// A cpu-cores-all job takes the whole budget, so a second one parks until the +// A cpu-cores-all job takes the whole budget, so a second one is not admitted until the // first finishes: whole-host bats shards run one at a time on a host. func TestCoresAllJobsRunOneAtATime(t *testing.T) { prov, stop := heldListen(t, @@ -297,16 +289,26 @@ func TestCoresAllJobsRunOneAtATime(t *testing.T) { } prov.releaseAll() if _, ok := prov.next(t, 2*time.Second); !ok { - t.Fatal("the parked cpu-cores-all job never started after the first finished") + t.Fatal("the blocked cpu-cores-all job never started after the first finished") } } -// Declared cores pack up to the budget: 4 + 2 fit in 7, a further 4 waits. +// Declared cores pack up to the budget once JobStarted retires the larger +// declarations (#192): runners are charged the largest known assignment (4 +// cores), so only one starts until the 4-core job has started; then the +// runner for the 2-core job fits (4 + 2 of 7), and a further 4 does not. func TestDeclaredCoresPackUpToTheBudget(t *testing.T) { - prov, stop := heldListen(t, - assigned(1, "four", "cpu", "cpu-cores-4"), - assigned(2, "two", "cpu", "cpu-cores-2"), - assigned(3, "four-more", "cpu", "cpu-cores-4"), + prov, stop := heldListenMsgs(t, 3, + msgWithAssigned(1, 2, + assigned(1, "four", "cpu", "cpu-cores-4"), + assigned(2, "two", "cpu", "cpu-cores-2"), + ), + &scaleset.RunnerScaleSetMessage{ + MessageID: 2, + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, + JobStartedMessages: startedMsg("four-r1", "cpu", "cpu-cores-4"), + }, + msgWithAssigned(3, 3, assigned(3, "four-more", "cpu", "cpu-cores-4")), ) defer stop() for i := 0; i < 2; i++ { @@ -373,21 +375,27 @@ var gpuDevicesAll = []string{"/dev/nvidia0", "/dev/nvidia1", "/dev/nvidiactl", " // heldGPUListen runs one message of assigned jobs against a vram-mode listener // over the given GPUs (reserve 20) and returns the holding provisioner. func heldGPUListen(t *testing.T, gpus []GPU, jobs ...*scaleset.JobAssigned) (*gpuHoldProvisioner, func()) { + t.Helper() + return heldGPUListenMsgs(t, gpus, len(jobs), msgWithAssigned(1, len(jobs), jobs...)) +} + +// heldGPUListenMsgs is heldGPUListen over scripted messages. +func heldGPUListenMsgs(t *testing.T, gpus []GPU, capacity int, msgs ...*scaleset.RunnerScaleSetMessage) (*gpuHoldProvisioner, func()) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) sess := &fakeSession{ - messages: []*scaleset.RunnerScaleSetMessage{msgWithAssigned(1, len(jobs), jobs...)}, + messages: msgs, cancel: cancel, } - prov := &gpuHoldProvisioner{started: make(chan ProvisionRequest, len(jobs)), release: make(chan struct{})} + prov := &gpuHoldProvisioner{started: make(chan ProvisionRequest, capacity), release: make(chan struct{})} + sess.idleGate = prov.release l := New(sess, &recordingMinter{config: "jit"}, prov, Config{ - Image: "img-gpu", - Devices: gpuDevicesAll, - Runtime: "nvidia", - GPUProbe: stubGPUProbe{gpus: gpus}, - Reserve: 20, - SettleWindow: time.Millisecond, - MaxRunners: 100, + Image: "img-gpu", + Devices: gpuDevicesAll, + Runtime: "nvidia", + GPUProbe: stubGPUProbe{gpus: gpus}, + Reserve: 20, + MaxRunners: 100, }) done := make(chan struct{}) go func() { _ = l.Listen(ctx); close(done) }() @@ -397,19 +405,26 @@ func heldGPUListen(t *testing.T, gpus []GPU, jobs ...*scaleset.JobAssigned) (*gp // Jobs whose declarations fit share one GPU: 8 + 8 of a 25 GiB budget run // together on GPU 0, and a further 16 waits. func TestVRAMJobsShareOneGPU(t *testing.T) { - prov, stop := heldGPUListen(t, []GPU{rtx5090(0, 0)}, - assigned(1, "eight-a", "gpu", "vram-gb-8"), - assigned(2, "eight-b", "gpu", "vram-gb-8"), - assigned(3, "sixteen", "gpu", "vram-gb-16"), + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 3} + prov, stop := heldGPUListenMsgs(t, []GPU{rtx5090(0, 0)}, 3, + msgWithAssigned(1, 3, + assigned(1, "eight-a", "gpu", "vram-gb-8"), + assigned(2, "eight-b", "gpu", "vram-gb-8"), + assigned(3, "sixteen", "gpu", "vram-gb-16"), + ), + &scaleset.RunnerScaleSetMessage{MessageID: 2, Statistics: stats, JobStartedMessages: startedMsg("eight-a-r1", "gpu", "vram-gb-8")}, + &scaleset.RunnerScaleSetMessage{MessageID: 3, Statistics: stats, JobStartedMessages: startedMsg("eight-b-r2", "gpu", "vram-gb-8")}, ) defer stop() + // Runners are charged the largest known declaration (16, #192) and the + // JobStarted messages bring each down to its real 8. for i := 0; i < 2; i++ { req, ok := prov.next(t, 2*time.Second) if !ok { t.Fatalf("only %d of the 2 vram-gb-8 jobs that fit a 25 GiB budget started", i) } - if req.GPU != 0 || req.VRAMGB != 8 { - t.Errorf("job %s pinned to GPU %d with %d GiB, want GPU 0 with 8", req.JobID, req.GPU, req.VRAMGB) + if req.GPU != 0 || req.VRAMGB != 16 { + t.Errorf("job %s pinned to GPU %d with %d GiB, want GPU 0 with the dispatch-time 16", req.JobID, req.GPU, req.VRAMGB) } } if req, ok := prov.next(t, 150*time.Millisecond); ok { @@ -443,14 +458,14 @@ func TestPinnedJobRequestCarriesAdmittedCardTotal(t *testing.T) { func TestAdmitGPUReturnsAdmittedCardTotal(t *testing.T) { l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 30000), rtx2000(1, 0)}}, - Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + Reserve: 20, MaxRunners: 100}) gpu, _, _, total, ok := l.admitGPU(context.Background(), []string{"vram-gb-4"}) if !ok || gpu != 1 || total != 16380 { t.Fatalf("admitGPU = (gpu %d, total %d, %v), want (1, 16380, true)", gpu, total, ok) } idle := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + Config{GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, MaxRunners: 100}) gpu, _, _, total, ok = idle.admitGPU(context.Background(), []string{"vram-gb-1"}) if !ok || gpu != -1 || total != 0 { t.Fatalf("unpinned admitGPU = (gpu %d, total %d, %v), want (-1, 0, true)", gpu, total, ok) @@ -477,7 +492,7 @@ func TestUndeclaredGPUJobsRunOnePerGPU(t *testing.T) { } prov.releaseAll() if _, ok := prov.next(t, 2*time.Second); !ok { - t.Fatal("the parked whole-GPU job never started after the first finished") + t.Fatal("the blocked whole-GPU job never started after the first finished") } } @@ -512,33 +527,22 @@ func TestGPUJobsPinnedToDistinctGPUs(t *testing.T) { } } -// A GPU listener re-probes after the settle window while no GPU has room, and -// admits once one does. -func TestAdmitGPUSettlesThenAdmits(t *testing.T) { - p := &countingGPUProbe{overUntil: 2, over: []GPU{rtx5090(0, 30000)}, ok: []GPU{rtx5090(0, 0)}} +// A GPU listener probes once per decision while no GPU has room, and admits on +// the next decision once one does (#192). +func TestAdmitGPUDeniesThenAdmitsOnNextProbe(t *testing.T) { + p := &countingGPUProbe{overUntil: 1, over: []GPU{rtx5090(0, 30000)}, ok: []GPU{rtx5090(0, 0)}} l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{GPUProbe: p, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + Config{GPUProbe: p, Reserve: 20, MaxRunners: 100}) + if _, _, _, _, ok := l.admitGPU(context.Background(), []string{"vram-gb-4"}); ok { + t.Fatal("admitGPU must deny while no GPU has room") + } + if p.callCount() != 1 { + t.Errorf("probe calls after a denial = %d, want 1", p.callCount()) + } gpu, _, gb, _, ok := l.admitGPU(context.Background(), []string{"vram-gb-4"}) if !ok || gpu != 0 || gb != 4 { t.Fatalf("admitGPU = (%d, %d, %v), want (0, 4, true) once the GPU frees", gpu, gb, ok) } - if p.callCount() < 3 { - t.Errorf("expected re-probing after settle, calls = %d, want >= 3", p.callCount()) - } -} - -// A context cancelled while no GPU has room unblocks admission. -func TestAdmitGPUCtxCancelUnblocks(t *testing.T) { - l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 30000)}}, Reserve: 20, SettleWindow: time.Hour, MaxRunners: 100}) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - time.Sleep(10 * time.Millisecond) - cancel() - }() - if _, _, _, _, ok := l.admitGPU(ctx, []string{"vram-gb-1"}); ok { - t.Fatal("admitGPU must return false when cancelled while no GPU has room") - } } type countingGPUProbe struct { @@ -657,21 +661,21 @@ func (p cancelOnGPUProbe) Probe(context.Context) ([]GPU, error) { func TestGPUAdmissionFailSafeUsesLastKnownGPUs(t *testing.T) { p := &switchGPUProbe{gpus: []GPU{rtx5090(0, 0), rtx5090(1, 0)}} l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{GPUProbe: p, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + Config{GPUProbe: p, Reserve: 20, MaxRunners: 100}) ctx := context.Background() gpu, _, gb, _, ok := l.admitGPU(ctx, []string{"vram-gb-4"}) if !ok || gpu != 0 || gb != 4 { t.Fatalf("healthy admitGPU = (%d, %d, %v), want (0, 4, true)", gpu, gb, ok) } - l.chargeGPU(gpu, gb) + first := holdCharge(l, "first", ledgerWorker{gpu: gpu, vramGB: gb}) p.set(nil, errors.New("nvidia-smi failed")) gpu, _, gb, _, ok = l.admitGPU(ctx, []string{"vram-gb-1"}) if !ok || gpu != 1 || gb != 25 { t.Fatalf("fail-safe admitGPU = (%d, %d, %v), want (1, 25, true): the empty GPU, whole", gpu, gb, ok) } - l.chargeGPU(gpu, gb) + holdCharge(l, "second", ledgerWorker{gpu: gpu, vramGB: gb}) short, cancel := context.WithTimeout(ctx, 50*time.Millisecond) defer cancel() @@ -679,7 +683,7 @@ func TestGPUAdmissionFailSafeUsesLastKnownGPUs(t *testing.T) { t.Fatalf("fail-safe admitted (%d, %d) although every known GPU holds a job", gpu, gb) } - l.releaseGPU(0, 4) + l.ledger.exit("first", first) gpu, _, gb, _, ok = l.admitGPU(ctx, []string{"vram-gb-1"}) if !ok || gpu != 0 || gb != 25 { t.Fatalf("fail-safe admitGPU after release = (%d, %d, %v), want (0, 25, true)", gpu, gb, ok) @@ -690,7 +694,7 @@ func TestGPUAdmissionFailSafeUsesLastKnownGPUs(t *testing.T) { // pinned to any GPU (-1). func TestGPUAdmissionFailSafeWithoutAnyReading(t *testing.T) { l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, - Config{GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, SettleWindow: time.Millisecond, MaxRunners: 100}) + Config{GPUProbe: stubGPUProbe{err: errors.New("no nvidia-smi")}, Reserve: 20, MaxRunners: 100}) gpu, _, _, _, ok := l.admitGPU(context.Background(), []string{"vram-gb-1"}) if !ok || gpu != -1 { t.Fatalf("admitGPU on an idle listener = (gpu %d, %v), want (-1, true)", gpu, ok) @@ -759,7 +763,7 @@ func TestVRAMCapacity(t *testing.T) { t.Errorf("two idle GPUs: capacity = %d, want 2", got) } full := newL(stubGPUProbe{gpus: two}, 100) - full.chargeGPU(0, 25) + holdCharge(full, "held", ledgerWorker{gpu: 0, vramGB: 25}) if got := full.capacityFor(1); got != 1 { t.Errorf("one GPU full: capacity = %d, want 1", got) } @@ -796,7 +800,7 @@ func TestGPUFailSafeRecoveryWaitsForUnpinnedJob(t *testing.T) { probe := &switchGPUProbe{err: errors.New("no nvidia-smi")} release := make(chan struct{}) l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &recordingProvisioner{block: release}, - Config{GPUProbe: probe, SettleWindow: time.Millisecond, MaxRunners: 2}) + Config{GPUProbe: probe, MaxRunners: 2}) defer l.wg.Wait() defer close(release) stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} diff --git a/listener/round4_test.go b/listener/round4_test.go new file mode 100644 index 0000000..7294814 --- /dev/null +++ b/listener/round4_test.go @@ -0,0 +1,156 @@ +package listener + +import ( + "context" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/actions/scaleset" +) + +// gatedProvisioner holds the nth Provision call until gates[n] is closed. +type gatedProvisioner struct { + gates []chan struct{} + calls atomic.Int64 +} + +func (p *gatedProvisioner) Provision(_ context.Context, _ ProvisionRequest) error { + n := int(p.calls.Add(1)) - 1 + <-p.gates[n] + return nil +} + +// swapProbe is a host probe whose reading a test can replace between calls. +type swapProbe struct { + mu sync.Mutex + res HostResources + calls int +} + +func (s *swapProbe) Probe(context.Context) (HostResources, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + return s.res, nil +} + +func (s *swapProbe) callCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.calls +} + +func (s *swapProbe) set(r HostResources) { + s.mu.Lock() + s.res = r + s.mu.Unlock() +} + +func hostOf(cores float64) HostResources { + return HostResources{Free: map[Resource]float64{ResourceCPU: 1.0, ResourceMem: 1.0}, Cores: cores, MemGB: 64} +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +// Review round 4 (#192): the same assignment can be redelivered and +// re-dispatched after its first runner exited. A JobStarted that was delayed +// from the first runner names that first runner, so it must not resize the +// replacement: every dispatch mints a runner name of its own. +func TestDelayedJobStartedDoesNotResizeReplacement(t *testing.T) { + gates := []chan struct{}{make(chan struct{}), make(chan struct{})} + mnt := &recordingMinter{config: "jit"} + l := New(&fakeSession{}, mnt, &gatedProvisioner{gates: gates}, Config{ + Image: "img", HostProbe: stubProbe{res: hostOf(8)}, Reserve: 10, MaxRunners: 100, + }) + ctx := context.Background() + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + jobs := []*scaleset.JobAssigned{assigned(1, "job", "cpu-cores-4")} + if err := l.reconcile(ctx, stats, jobs); err != nil { + t.Fatal(err) + } + close(gates[0]) + waitFor(t, "first runner exit", func() bool { return l.inFlight.Load() == 0 }) + if err := l.reconcile(ctx, stats, jobs); err != nil { + t.Fatal(err) + } + if len(mnt.gotNames) != 2 { + t.Fatalf("minted %d runners, want 2", len(mnt.gotNames)) + } + if mnt.gotNames[0] == mnt.gotNames[1] { + t.Errorf("both dispatches minted the name %q", mnt.gotNames[0]) + } + if got := l.committedSize().cores; got != 4 { + t.Fatalf("replacement charged %d cores, want 4", got) + } + l.handleJobStarted(startedMsg(mnt.gotNames[0], "cpu-cores-1")) + if got := l.committedSize().cores; got != 4 { + t.Errorf("a delayed start of the first runner resized the replacement to %d cores, want 4", got) + } + close(gates[1]) + l.wg.Wait() +} + +// Review round 4 (#192): the size a runner is charged is the one that passed +// admission, not a later read of a probe snapshot the capacity reporter may +// have replaced in between. +func TestChargeIsTheAdmittedSize(t *testing.T) { + probe := &swapProbe{res: hostOf(8)} // budget 7 cores at reserve 10 + gate := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &gatedProvisioner{gates: []chan struct{}{gate}}, Config{ + Image: "img", HostProbe: probe, Reserve: 10, MaxRunners: 4, + }) + // Fill every worker slot so dispatch, once admitted, waits for one. The + // slots are taken directly, with nothing in flight, only to hold dispatch + // between admission and charging. + for range cap(l.sem) { + l.sem <- struct{}{} + } + done := make(chan error, 1) + go func() { + done <- l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, + []*scaleset.JobAssigned{assigned(1, "job", "cpu-cores-all")}) + }() + waitFor(t, "admission probe", func() bool { return probe.callCount() >= 1 }) // admission read the 8-core host + probe.set(hostOf(4)) // budget 3 cores + l.reactiveCapacity(context.Background()) // the reporter replaces the snapshot + <-l.sem // a slot frees: dispatch charges now + if err := <-done; err != nil { + t.Fatal(err) + } + if got := l.committedSize().cores; got != 7 { + t.Errorf("charged %d cores, want the 7 that passed admission", got) + } + close(gate) + l.wg.Wait() +} + +func init() { runnerNameStamp = func() string { return "r" } } + +// jobOfRunner is the assignment job id a minted runner name was made from: the +// name less the "-r" suffix every dispatch adds (#192). +func jobOfRunner(name string) string { + if i := strings.LastIndex(name, "-r"); i >= 0 { + return name[:i] + } + return name +} + +func jobsOfRunners(names []string) []string { + out := make([]string, len(names)) + for i, n := range names { + out[i] = jobOfRunner(n) + } + return out +}