From 65eb1c1a029e246a2c2f0ef6ea12c173b6065a77 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:40:18 +0800 Subject: [PATCH 01/10] =?UTF-8?q?fix(listener):=20=E5=87=86=E5=85=A5?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=8D=A1=E4=BD=8F=20message=20loop=EF=BC=8C?= =?UTF-8?q?=E5=96=AE=E6=AC=A1=E6=8E=A2=E6=B8=AC=E5=BE=8C=E4=BA=A4=E9=82=84?= =?UTF-8?q?=E8=BC=AA=E8=A9=A2=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/changelog/CHANGELOG.md | 6 ++ listener/listener.go | 111 ++++++++++++------------------- listener/listener_test.go | 67 +++++++++++++++++++ listener/reactive_test.go | 129 +++++++++++++++---------------------- 4 files changed, 164 insertions(+), 149 deletions(-) diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index ead870d..42d803e 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -225,6 +225,12 @@ 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. - **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/listener.go b/listener/listener.go index c6fd923..c824322 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -30,12 +30,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. @@ -187,10 +181,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. @@ -261,12 +251,12 @@ type Listener struct { last atomic.Pointer[HostResources] // 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 = + // 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 @@ -304,10 +294,6 @@ 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, @@ -319,7 +305,6 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) gpuProbe: cfg.GPUProbe, committedVRAM: make(map[int]int64), reserve: reserve, - settle: settle, tracked: make(map[string]int), assigned: make(map[string]struct{}), } @@ -875,28 +860,19 @@ func (l *Listener) reactiveCapacity(ctx context.Context) int { 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. +// 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 fails safe -- a +// probe error admits (the semaphore ceiling is the backstop, and stranding +// acquired work is worse than a brief over-admit). 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 - } + h, err := l.probe.Probe(ctx) + if err != nil { + return true } + l.last.Store(&h) + return admits(h, l.committedSize(), clampSize(h, cost, l.reserve), l.reserve) } // charge commits an admitted job's declared size, clamped to the latest @@ -925,13 +901,12 @@ func (l *Listener) committedSize() jobSize { return jobSize{cores: l.committedCores.Load(), gb: l.committedGB.Load()} } -// 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 @@ -940,35 +915,29 @@ func (l *Listener) committedSize() jobSize { // 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(): + want := int64(jobVRAM(labels, int(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 + } + if l.committedVRAM[-1] != 0 { + return 0, 0, 0, 0, false + } + switch { + case len(gpus) > 0: + selected, cost, fits := pickGPU(gpus, l.committedVRAM, 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 diff --git a/listener/listener_test.go b/listener/listener_test.go index 23aaa9a..f419553 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 { @@ -1409,3 +1423,56 @@ 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() + acquired := 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}}, + }, + }, + }, + onAcquire: func(context.Context) error { + select { + case acquired <- struct{}{}: + default: + } + return nil + }, + beforePoll: func(int) {}, + } + // Idle runner "a" stays inside Provision and keeps its charge. + block := make(chan struct{}) + prov := &recordingProvisioner{block: block} + // 2-core host, 10% reserve: budget 1.8 cores, so one 1-core runner fills it. + 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: 2, MemGB: 64}}, + Reserve: 10, + MaxRunners: 100, + }) + done := make(chan struct{}) + go func() { _ = l.Listen(ctx); close(done) }() + + select { + case <-acquired: + case <-time.After(2 * time.Second): + t.Fatal("message loop stalled: AcquireJobs for the third message never ran while admission was full") + } + // 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..4f4b058 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -74,7 +74,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 +92,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 +115,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 +126,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 +135,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 l.admitOne(context.Background(), jobSize{1, 4}) { + 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 !l.admitOne(context.Background(), jobSize{1, 4}) { + t.Fatal("admitOne should admit once headroom returns") } } @@ -240,12 +224,12 @@ func heldListen(t *testing.T, jobs ...*scaleset.JobAssigned) (*labelProbe, func( cancel: cancel, } prov := &labelProbe{started: make(chan string, len(jobs)), 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 +265,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,7 +281,7 @@ 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") } } @@ -380,14 +364,14 @@ func heldGPUListen(t *testing.T, gpus []GPU, jobs ...*scaleset.JobAssigned) (*gp cancel: cancel, } prov := &gpuHoldProvisioner{started: make(chan ProvisionRequest, len(jobs)), 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) }() @@ -443,14 +427,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 +461,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 +496,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,7 +630,7 @@ 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"}) @@ -690,7 +663,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) @@ -796,7 +769,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} From f9489d3da2fa7e884756b2232c6d3f5ff38752f1 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:41:45 +0800 Subject: [PATCH 02/10] =?UTF-8?q?refactor(listener):=20=E6=95=B4=E7=90=86?= =?UTF-8?q?=20reserve=20=E8=A8=BB=E8=A7=A3=E7=9A=84=E6=8F=9B=E8=A1=8C=20(#?= =?UTF-8?q?192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- listener/listener.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/listener/listener.go b/listener/listener.go index c824322..2651cad 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -253,8 +253,7 @@ type Listener struct { // Reactive live-admission (ADR-0005, #163): when probe is set, each job is // 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). + // (#192). Nil probe = the fixed/device ceiling path (probe-less). probe HostProbe reserve float64 // fraction in [0,1]; the per-resource headroom kept free From ae90136c39fdafe5cc5d00ff06676d90ccd46d01 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:48:59 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(listener):=20=E6=96=B0=20runner=20?= =?UTF-8?q?=E4=BB=A5=E5=B7=B2=E7=9F=A5=E6=9C=80=E5=A4=A7=E5=AE=A3=E5=91=8A?= =?UTF-8?q?=E8=A8=88=E8=B2=BB=EF=BC=8CJobStarted=20=E4=BE=9D=E5=AF=A6?= =?UTF-8?q?=E9=9A=9B=E5=B7=A5=E4=BD=9C=E9=87=8D=E6=96=B0=E6=AD=B8=E5=B1=AC?= =?UTF-8?q?=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/changelog/CHANGELOG.md | 8 +- listener/charge_test.go | 216 +++++++++++++++++++++++++++++++++++++ listener/listener.go | 171 ++++++++++++++++++++++++++--- listener/reactive_test.go | 60 ++++++++--- 4 files changed, 423 insertions(+), 32 deletions(-) create mode 100644 listener/charge_test.go diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index 42d803e..c6347cd 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -230,7 +230,13 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 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. + 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). A `JobStarted` for a runner the listener does not hold + is logged and ignored. Until it arrives an idle runner holds the larger + charge, so a mixed batch packs after the jobs start. - **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/charge_test.go b/listener/charge_test.go new file mode 100644 index 0000000..b2e1674 --- /dev/null +++ b/listener/charge_test.go @@ -0,0 +1,216 @@ +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 { + js := &scaleset.JobStarted{RunnerName: runner} + js.JobID = runner + 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) + } + l.handleJobStarted(startedMsg("big", "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 + log.SetOutput(&buf) + defer log.SetOutput(log.Writer()) + 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. +func TestReconcileDispatchesAfterRelease(t *testing.T) { + prov := &recordingProvisioner{} + mnt := &recordingMinter{config: "jit"} + l := New(&fakeSession{}, 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, + }) + l.committedCores.Store(1) // an idle runner holds the whole 1-core budget + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} + if err := l.reconcile(context.Background(), stats, nil); err != nil { + t.Fatal(err) + } + if len(mnt.gotNames) != 0 { + t.Fatalf("minted %d runners while the budget was full", len(mnt.gotNames)) + } + l.committedCores.Store(0) + if err := l.reconcile(context.Background(), stats, nil); err != nil { + t.Fatal(err) + } + l.wg.Wait() + if len(mnt.gotNames) != 1 { + t.Errorf("minted %d runners after release, want 1", len(mnt.gotNames)) + } +} + +// No GPU has room: the message loop still reaches AcquireJobs. +func TestRunKeepsPollingWhenNoGPUFits(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + acquired := 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}}}, + }, + }, + onAcquire: func(context.Context) error { + select { + case acquired <- struct{}{}: + default: + } + return nil + }, + } + l := New(sess, &recordingMinter{config: "jit"}, &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 <-acquired: + case <-time.After(2 * time.Second): + t.Fatal("message loop stalled: AcquireJobs never ran while no GPU fit") + } + 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) + } + l.handleJobStarted(startedMsg("second", "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) + } + 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) + } +} diff --git a/listener/listener.go b/listener/listener.go index 2651cad..1179f2b 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -272,6 +272,24 @@ type Listener struct { assignedMu sync.Mutex assigned map[string]struct{} // raw JobIDs reserved for minting or provisioning + + // workMu guards workers and known (#192). workers holds each in-flight + // runner's CURRENT charge by JIT runner name (the job id passed to Mint), so + // JobStarted can re-attribute it and exit releases what is held now. known + // holds the labels of every assignment seen and not yet started or + // completed: a runner is minted before GitHub says which job it takes, so it + // is charged the largest of these. + workMu sync.Mutex + workers map[string]*workerCharge + known map[string][]string +} + +// workerCharge is what one runner currently holds: a reactive size, or VRAM on +// a GPU. +type workerCharge struct { + size jobSize + gpu int + vramGB int64 } // New wires a Session + JITConfigMinter + Provisioner + Config into a Listener. @@ -306,6 +324,8 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) reserve: reserve, tracked: make(map[string]int), assigned: make(map[string]struct{}), + workers: make(map[string]*workerCharge), + known: make(map[string][]string), } } @@ -404,6 +424,8 @@ func (l *Listener) Listen(ctx context.Context) (err error) { return err } lastMessageID = msg.MessageID + l.handleJobStarted(msg.JobStartedMessages) + l.handleJobCompleted(msg.JobCompletedMessages) if err := l.acquire(ctx, msg.JobAvailableMessages); err != nil { return err } @@ -459,6 +481,7 @@ 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.noteAssigned(jobs) if stats == nil { return nil } @@ -490,13 +513,11 @@ 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) + // 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.knownCost() if l.gpuProbe == nil && l.probe != nil && !l.admitOne(ctx, cost) { return nil } @@ -515,7 +536,7 @@ 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 @@ -593,14 +614,14 @@ 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) { + l.workMu.Lock() + l.workers[req.rawJobID] = &workerCharge{size: charged, gpu: gpu, vramGB: vramGB} + l.workMu.Unlock() + 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) - } + defer l.releaseWorker(req.rawJobID) if hasAssignment { defer l.releaseAssignment(req.rawJobID) } @@ -614,7 +635,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 } @@ -889,6 +910,116 @@ func (l *Listener) charge(cost jobSize) jobSize { return charged } +// noteAssigned records the labels of assignments not yet started (#192). +func (l *Listener) noteAssigned(jobs []*scaleset.JobAssigned) { + l.workMu.Lock() + defer l.workMu.Unlock() + for _, job := range jobs { + if job != nil { + l.known[job.JobID] = job.RequestLabels + } + } +} + +// knownCost is the size a new runner is charged: the largest declared size +// among the known not-yet-started assignments (defaultJob when none), plus +// those assignments' label sets for the GPU gate. +func (l *Listener) knownCost() (jobSize, [][]string) { + l.workMu.Lock() + defer l.workMu.Unlock() + if len(l.known) == 0 { + return defaultJob, nil + } + var cost jobSize + sets := make([][]string, 0, len(l.known)) + for _, labels := range l.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 +} + +// 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 runner this listener does not hold is ignored. +func (l *Listener) handleJobStarted(started []*scaleset.JobStarted) { + for _, js := range started { + if js == nil { + continue + } + l.workMu.Lock() + delete(l.known, js.JobID) + w, ok := l.workers[js.RunnerName] + if !ok { + l.workMu.Unlock() + log.Printf("job started on unknown runner %q: charge left unchanged", js.RunnerName) + continue + } + switch { + case l.gpuProbe != nil: + l.reattributeGPU(w, js.RequestLabels) + case l.probe != nil: + size := jobSizeOf(js.RequestLabels) + if h := l.last.Load(); h != nil { + size = clampSize(*h, size, l.reserve) + } + l.committedCores.Add(size.cores - w.size.cores) + l.committedGB.Add(size.gb - w.size.gb) + w.size = size + } + l.workMu.Unlock() + } +} + +// reattributeGPU moves a pinned runner's VRAM charge to the started job's +// declaration, on the same card. workMu is held. +func (l *Listener) reattributeGPU(w *workerCharge, labels []string) { + if w.gpu < 0 { + return + } + l.vramMu.Lock() + defer l.vramMu.Unlock() + gb := int64(jobVRAM(labels, int(wholeGPU))) + for _, g := range l.lastGPUs { + if g.Index == w.gpu { + gb = min(gb, int64(vramBudget(g, l.reserve))) + } + } + l.committedVRAM[w.gpu] += gb - w.vramGB + if l.committedVRAM[w.gpu] <= 0 { + delete(l.committedVRAM, w.gpu) + } + w.vramGB = gb +} + +// handleJobCompleted forgets assignments that finished without a runner of +// ours seeing them start. +func (l *Listener) handleJobCompleted(done []*scaleset.JobCompleted) { + l.workMu.Lock() + defer l.workMu.Unlock() + for _, jc := range done { + if jc != nil { + delete(l.known, jc.JobID) + } + } +} + +// releaseWorker returns what a runner holds NOW when it exits. +func (l *Listener) releaseWorker(name string) { + l.workMu.Lock() + w := l.workers[name] + delete(l.workers, name) + l.workMu.Unlock() + if w == nil { + return + } + l.release(w.size) + if l.gpuProbe != nil { + l.releaseGPU(w.gpu, w.vramGB) + } +} + // 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) @@ -913,8 +1044,16 @@ func (l *Listener) committedSize() jobSize { // 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) { - want := int64(jobVRAM(labels, int(wholeGPU))) +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() diff --git a/listener/reactive_test.go b/listener/reactive_test.go index 4f4b058..4799f84 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -217,13 +217,20 @@ 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", @@ -285,12 +292,22 @@ func TestCoresAllJobsRunOneAtATime(t *testing.T) { } } -// 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", "cpu", "cpu-cores-4"), + }, + msgWithAssigned(3, 3, assigned(3, "four-more", "cpu", "cpu-cores-4")), ) defer stop() for i := 0; i < 2; i++ { @@ -357,13 +374,19 @@ 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", @@ -381,19 +404,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", "gpu", "vram-gb-8")}, + &scaleset.RunnerScaleSetMessage{MessageID: 3, Statistics: stats, JobStartedMessages: startedMsg("eight-b", "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 { From 74d2db3d84e47624413a8af37fd8eac711fae8e8 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:48:59 +0800 Subject: [PATCH 04/10] =?UTF-8?q?docs(listener):=20ADR-0005/0006/0007?= =?UTF-8?q?=E3=80=81README=20=E8=88=87=E6=9E=B6=E6=A7=8B=E5=9C=96=E6=94=B9?= =?UTF-8?q?=E7=82=BA=E5=96=AE=E6=AC=A1=E6=8E=A2=E6=B8=AC=E3=80=81=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E7=AD=89=E5=BE=85=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/adr/0005-reactive-live-admission.md | 21 ++++++++++++++------- doc/adr/0006-declared-job-cores.md | 14 ++++++++++---- doc/adr/0007-declared-job-vram.md | 7 +++++-- doc/arch/overview.html | 16 +++++++--------- listener/README.md | 4 ++-- listener/hostprobe.go | 4 ++-- 6 files changed, 40 insertions(+), 26 deletions(-) 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..878653b 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 @@ -72,8 +72,14 @@ while bash reads `/proc`. 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. +- 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 is logged and ignored. - 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..216dbd0 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. 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/listener/README.md b/listener/README.md index 6338c7b..b98a9e9 100644 --- a/listener/README.md +++ b/listener/README.md @@ -249,8 +249,8 @@ 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 re-probes (#192). 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/hostprobe.go b/listener/hostprobe.go index 175287a..1fcebe4 100644 --- a/listener/hostprobe.go +++ b/listener/hostprobe.go @@ -231,8 +231,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 From 8a9f18487f0413f3c8055031a968e9674bb9d6f1 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:54:25 +0800 Subject: [PATCH 05/10] =?UTF-8?q?fix(listener):=20=E6=AF=8F=E5=80=8B=20env?= =?UTF-8?q?elope=20=E9=83=BD=E9=87=8D=E8=A9=A6=E5=87=86=E5=85=A5=EF=BC=8C?= =?UTF-8?q?=E4=B8=A6=E5=85=88=E8=A8=98=E9=8C=84=E6=8C=87=E6=B4=BE=E5=86=8D?= =?UTF-8?q?retire=E5=95=9F=E5=8B=95=E8=88=87=E5=AE=8C=E6=88=90=E7=9A=84=20?= =?UTF-8?q?job=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/changelog/CHANGELOG.md | 3 ++ listener/charge_test.go | 81 ++++++++++++++++++++++++++++++++++++++ listener/listener.go | 24 ++++++++--- 3 files changed, 102 insertions(+), 6 deletions(-) diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index c6347cd..4884b69 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -237,6 +237,9 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). (same card for VRAM). A `JobStarted` for a runner the listener does not hold is logged and ignored. 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; + an envelope's assignments are recorded before its started and completed + jobs are retired. - **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/charge_test.go b/listener/charge_test.go index b2e1674..9705d85 100644 --- a/listener/charge_test.go +++ b/listener/charge_test.go @@ -214,3 +214,84 @@ func TestGPUMaxVRAMChargeAndJobStarted(t *testing.T) { 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"} + 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() {}) +} diff --git a/listener/listener.go b/listener/listener.go index 1179f2b..607e8ea 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -287,9 +287,9 @@ type Listener struct { // workerCharge is what one runner currently holds: a reactive size, or VRAM on // a GPU. type workerCharge struct { - size jobSize - gpu int - vramGB int64 + size jobSize + gpu int + vramGB int64 } // New wires a Session + JITConfigMinter + Provisioner + Config into a Listener. @@ -424,16 +424,22 @@ func (l *Listener) Listen(ctx context.Context) (err error) { return err } lastMessageID = msg.MessageID + // Record the envelope's assignments before retiring started and + // completed jobs, so a job assigned and started in one envelope is not + // left in the known set (#192). + l.noteAssigned(msg.JobAssignedMessages) l.handleJobStarted(msg.JobStartedMessages) l.handleJobCompleted(msg.JobCompletedMessages) 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 } } } @@ -482,6 +488,12 @@ func (l *Listener) releaseAssignment(rawJobID string) { // 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.noteAssigned(jobs) + 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 } From 060d0ce0597a86d21a54d86c1a45e984ebebbc83 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:55:49 +0800 Subject: [PATCH 06/10] =?UTF-8?q?fix(listener):=20GPU=20=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E6=AD=B8=E5=B1=AC=E4=BB=A5=20worker=20=E8=A8=98=E9=8C=84?= =?UTF-8?q?=E7=9A=84=E9=87=98=E9=81=B8=E5=8D=A1=E9=A0=90=E7=AE=97=E7=82=BA?= =?UTF-8?q?=E4=B8=8A=E9=99=90=EF=BC=8C=E4=B8=8D=E5=8F=97=E6=8E=A2=E6=B8=AC?= =?UTF-8?q?=E6=BC=8F=E5=88=97=E8=A9=B2=E5=8D=A1=E5=BD=B1=E9=9F=BF=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/changelog/CHANGELOG.md | 3 ++- listener/charge_test.go | 31 +++++++++++++++++++++++++++++++ listener/listener.go | 11 ++++++++--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index 4884b69..22254e3 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -239,7 +239,8 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). charge, so a mixed batch packs after the jobs start. Every message envelope, with or without statistics, now retries admission; an envelope's assignments are recorded before its started and completed - jobs are retired. + jobs are retired; and a GPU re-attribution clamps to the pinned card's own + budget even when a later probe omits that card. - **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/charge_test.go b/listener/charge_test.go index 9705d85..c1a8419 100644 --- a/listener/charge_test.go +++ b/listener/charge_test.go @@ -295,3 +295,34 @@ func TestEnvelopeWithoutStatsRetriesAdmission(t *testing.T) { // 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", "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) + } +} diff --git a/listener/listener.go b/listener/listener.go index 607e8ea..78278b4 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -290,6 +290,7 @@ type workerCharge struct { size jobSize gpu int vramGB int64 + totalMiB int64 // the pinned card's total VRAM, kept for re-attribution when a probe omits the card } // New wires a Session + JITConfigMinter + Provisioner + Config into a Listener. @@ -627,7 +628,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS l.inFlight.Add(1) l.track(req.JobID) l.workMu.Lock() - l.workers[req.rawJobID] = &workerCharge{size: charged, gpu: gpu, vramGB: vramGB} + l.workers[req.rawJobID] = &workerCharge{size: charged, gpu: gpu, vramGB: vramGB, totalMiB: vramTotalMiB} l.workMu.Unlock() go func(req assignedRequest, hasAssignment bool) { defer l.wg.Done() @@ -993,11 +994,15 @@ func (l *Listener) reattributeGPU(w *workerCharge, labels []string) { l.vramMu.Lock() defer l.vramMu.Unlock() gb := int64(jobVRAM(labels, int(wholeGPU))) + total := w.totalMiB for _, g := range l.lastGPUs { - if g.Index == w.gpu { - gb = min(gb, int64(vramBudget(g, l.reserve))) + if g.Index == w.gpu && total == 0 { + total = g.TotalMiB } } + if total > 0 { + gb = min(gb, int64(vramBudget(GPU{TotalMiB: total}, l.reserve))) + } l.committedVRAM[w.gpu] += gb - w.vramGB if l.committedVRAM[w.gpu] <= 0 { delete(l.committedVRAM, w.gpu) From 62ab7c2110b00aa679fa9986f04afb068b0e8a51 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:03:38 +0800 Subject: [PATCH 07/10] =?UTF-8?q?fix(listener):=20address=20review=20round?= =?UTF-8?q?=203=EF=BC=8C=E4=BB=A5=E5=96=AE=E4=B8=80=20ledger=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=20runner=20=E8=A8=88=E8=B2=BB=E7=94=9F=E5=91=BD?= =?UTF-8?q?=E9=80=B1=E6=9C=9F=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 listener/ledger.go:已知指派、已退場 job id、runner 計費記錄由同一把鎖持有, committed 的 CPU/RAM/VRAM 改為對持有中 runner 的加總,不再增減計數器 - 已 started 或 completed 的 job id 不會再回到已知指派;已持有的 runner 名稱拒絕再次 dispatch; exit 只釋放自己 token 的記錄 - worker 結束時先釋放計費記錄,再釋放指派鍵,避免重送指派在空窗內以同名取代 - 新增 TestLedgerOrderInsensitive 與 TestAssignmentKeyHeldUntilWorkerRecordGone;ADR-0006、ADR-0007 與 CHANGELOG 同步 --- doc/adr/0006-declared-job-cores.md | 6 + doc/adr/0007-declared-job-vram.md | 2 +- doc/changelog/CHANGELOG.md | 12 +- listener/charge_test.go | 40 +++- listener/ledger.go | 184 ++++++++++++++++++ listener/ledger_test.go | 130 +++++++++++++ listener/listener.go | 297 ++++++++--------------------- listener/reactive_test.go | 10 +- 8 files changed, 453 insertions(+), 228 deletions(-) create mode 100644 listener/ledger.go create mode 100644 listener/ledger_test.go diff --git a/doc/adr/0006-declared-job-cores.md b/doc/adr/0006-declared-job-cores.md index 878653b..f3c01b9 100644 --- a/doc/adr/0006-declared-job-cores.md +++ b/doc/adr/0006-declared-job-cores.md @@ -80,6 +80,12 @@ while bash reads `/proc`. 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 is logged and ignored. +- 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 never returns to the known + assignments; 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). - 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 216dbd0..fd9acc0 100644 --- a/doc/adr/0007-declared-job-vram.md +++ b/doc/adr/0007-declared-job-vram.md @@ -104,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/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index 22254e3..b747c54 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -237,10 +237,14 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). (same card for VRAM). A `JobStarted` for a runner the listener does not hold is logged and ignored. 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; - an envelope's assignments are recorded before its started and completed - jobs are retired; and a GPU re-attribution clamps to the pinned card's own - budget even when a later probe omits that card. + 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 can never return to the known assignments, 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. - **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/charge_test.go b/listener/charge_test.go index c1a8419..e3fda38 100644 --- a/listener/charge_test.go +++ b/listener/charge_test.go @@ -123,7 +123,7 @@ func TestReconcileDispatchesAfterRelease(t *testing.T) { Reserve: 10, MaxRunners: 100, }) - l.committedCores.Store(1) // an idle runner holds the whole 1-core budget + idle := holdCharge(l, "idle", ledgerWorker{size: jobSize{cores: 1, gb: 4}, gpu: -1}) // an idle runner holds the whole 1-core budget stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} if err := l.reconcile(context.Background(), stats, nil); err != nil { t.Fatal(err) @@ -131,7 +131,7 @@ func TestReconcileDispatchesAfterRelease(t *testing.T) { if len(mnt.gotNames) != 0 { t.Fatalf("minted %d runners while the budget was full", len(mnt.gotNames)) } - l.committedCores.Store(0) + l.ledger.exit("idle", idle) if err := l.reconcile(context.Background(), stats, nil); err != nil { t.Fatal(err) } @@ -326,3 +326,39 @@ func TestJobStartedGPUCardMissingFromProbe(t *testing.T) { t.Errorf("card 0 committed after exit = %d, want 0", got) } } + +// 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/ledger.go b/listener/ledger.go new file mode 100644 index 0000000..0eee57c --- /dev/null +++ b/listener/ledger.go @@ -0,0 +1,184 @@ +package listener + +import ( + "sync" + + "github.com/actions/scaleset" +) + +// retiredCap bounds how many started or completed job ids the ledger +// remembers. A retired id only has to outlive the redelivery of its own +// assignment, so the oldest are forgotten first. +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 + 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 a retired +// id can never 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. +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..ad82953 --- /dev/null +++ b/listener/ledger_test.go @@ -0,0 +1,130 @@ +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 78278b4..978d7d3 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -242,13 +242,11 @@ 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 probe, used to clamp a declared size + // (cpu-cores-all, ram-gb-all, or a value above the host) to the budgets. + ledger *ledger + last atomic.Pointer[HostResources] // Reactive live-admission (ADR-0005, #163): when probe is set, each job is // admitted only while every resource keeps reserve headroom free; a job that @@ -257,14 +255,13 @@ type Listener struct { probe HostProbe reserve float64 // fraction in [0,1]; the per-resource headroom kept free - // 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 @@ -272,25 +269,6 @@ type Listener struct { assignedMu sync.Mutex assigned map[string]struct{} // raw JobIDs reserved for minting or provisioning - - // workMu guards workers and known (#192). workers holds each in-flight - // runner's CURRENT charge by JIT runner name (the job id passed to Mint), so - // JobStarted can re-attribute it and exit releases what is held now. known - // holds the labels of every assignment seen and not yet started or - // completed: a runner is minted before GitHub says which job it takes, so it - // is charged the largest of these. - workMu sync.Mutex - workers map[string]*workerCharge - known map[string][]string -} - -// workerCharge is what one runner currently holds: a reactive size, or VRAM on -// a GPU. -type workerCharge struct { - size jobSize - gpu int - vramGB int64 - totalMiB int64 // the pinned card's total VRAM, kept for re-attribution when a probe omits the card } // New wires a Session + JITConfigMinter + Provisioner + Config into a Listener. @@ -321,12 +299,10 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) sem: make(chan struct{}, bound), probe: cfg.HostProbe, gpuProbe: cfg.GPUProbe, - committedVRAM: make(map[int]int64), + ledger: newLedger(), reserve: reserve, tracked: make(map[string]int), assigned: make(map[string]struct{}), - workers: make(map[string]*workerCharge), - known: make(map[string][]string), } } @@ -425,12 +401,10 @@ func (l *Listener) Listen(ctx context.Context) (err error) { return err } lastMessageID = msg.MessageID - // Record the envelope's assignments before retiring started and - // completed jobs, so a job assigned and started in one envelope is not - // left in the known set (#192). - l.noteAssigned(msg.JobAssignedMessages) + // 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). + l.ledger.noteEnvelope(msg.JobAssignedMessages, msg.JobStartedMessages, msg.JobCompletedMessages) l.handleJobStarted(msg.JobStartedMessages) - l.handleJobCompleted(msg.JobCompletedMessages) if err := l.acquire(ctx, msg.JobAvailableMessages); err != nil { return err } @@ -488,7 +462,7 @@ 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.noteAssigned(jobs) + l.ledger.noteEnvelope(jobs, nil, nil) return l.dispatch(ctx, stats, jobs) } @@ -530,7 +504,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS // 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.knownCost() + cost, labelSets := l.ledger.knownDeclared() if l.gpuProbe == nil && l.probe != nil && !l.admitOne(ctx, cost) { return nil } @@ -556,15 +530,6 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS } } - // 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 { @@ -572,6 +537,25 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS } 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. The ledger refuses a + // runner name it already holds: a redelivered assignment is dropped + // here, uncharged, and admitted on a later round once the old runner + // has exited (#192). + var charged jobSize + if l.gpuProbe == nil && l.probe != nil { + charged = l.clampCharge(cost) + } + token, held := l.ledger.dispatch(job.JobID, ledgerWorker{size: charged, 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, @@ -594,10 +578,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS workDir, err := socketJobWorkDir(jobID) if err != nil { <-l.sem - l.release(charged) - if l.gpuProbe != nil { - l.releaseGPU(gpu, vramGB) - } + l.ledger.exit(req.rawJobID, token) if hasAssignment { pending = pending[1:] l.releaseAssignment(req.rawJobID) @@ -614,10 +595,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS cancel() if err != nil { <-l.sem - l.release(charged) - if l.gpuProbe != nil { - l.releaseGPU(gpu, vramGB) - } + l.ledger.exit(req.rawJobID, token) return err } req.EncodedJITConfig = jit @@ -627,17 +605,16 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS l.wg.Add(1) l.inFlight.Add(1) l.track(req.JobID) - l.workMu.Lock() - l.workers[req.rawJobID] = &workerCharge{size: charged, gpu: gpu, vramGB: vramGB, totalMiB: vramTotalMiB} - l.workMu.Unlock() go func(req assignedRequest, hasAssignment bool) { defer l.wg.Done() defer l.inFlight.Add(-1) defer func() { <-l.sem }() - defer l.releaseWorker(req.rawJobID) + // 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.rawJobID, 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: @@ -908,144 +885,55 @@ func (l *Listener) admitOne(ctx context.Context, cost jobSize) bool { return admits(h, l.committedSize(), clampSize(h, cost, l.reserve), 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 +// clampCharge is the size a runner is charged for a declared cost, clamped to +// the latest probe's budgets so a whole-host declaration holds exactly the +// whole budget. If no probe has succeeded, the declared cost is retained so the +// job is fully accounted for once probing recovers. +func (l *Listener) clampCharge(cost jobSize) jobSize { if h := l.last.Load(); h != nil { - charged = clampSize(*h, cost, l.reserve) - } - l.committedCores.Add(charged.cores) - l.committedGB.Add(charged.gb) - return charged -} - -// noteAssigned records the labels of assignments not yet started (#192). -func (l *Listener) noteAssigned(jobs []*scaleset.JobAssigned) { - l.workMu.Lock() - defer l.workMu.Unlock() - for _, job := range jobs { - if job != nil { - l.known[job.JobID] = job.RequestLabels - } - } -} - -// knownCost is the size a new runner is charged: the largest declared size -// among the known not-yet-started assignments (defaultJob when none), plus -// those assignments' label sets for the GPU gate. -func (l *Listener) knownCost() (jobSize, [][]string) { - l.workMu.Lock() - defer l.workMu.Unlock() - if len(l.known) == 0 { - return defaultJob, nil - } - var cost jobSize - sets := make([][]string, 0, len(l.known)) - for _, labels := range l.known { - s := jobSizeOf(labels) - cost.cores, cost.gb = max(cost.cores, s.cores), max(cost.gb, s.gb) - sets = append(sets, labels) + return clampSize(*h, cost, l.reserve) } - return cost, sets + return cost } // 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 runner this listener does not hold is ignored. +// 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 ignored. func (l *Listener) handleJobStarted(started []*scaleset.JobStarted) { for _, js := range started { if js == nil { continue } - l.workMu.Lock() - delete(l.known, js.JobID) - w, ok := l.workers[js.RunnerName] - if !ok { - l.workMu.Unlock() - log.Printf("job started on unknown runner %q: charge left unchanged", js.RunnerName) - continue - } - switch { - case l.gpuProbe != nil: - l.reattributeGPU(w, js.RequestLabels) - case l.probe != nil: - size := jobSizeOf(js.RequestLabels) - if h := l.last.Load(); h != nil { - size = clampSize(*h, size, l.reserve) + 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 = l.clampCharge(jobSizeOf(labels)) } - l.committedCores.Add(size.cores - w.size.cores) - l.committedGB.Add(size.gb - w.size.gb) - w.size = size - } - l.workMu.Unlock() - } -} - -// reattributeGPU moves a pinned runner's VRAM charge to the started job's -// declaration, on the same card. workMu is held. -func (l *Listener) reattributeGPU(w *workerCharge, labels []string) { - if w.gpu < 0 { - return - } - l.vramMu.Lock() - defer l.vramMu.Unlock() - gb := int64(jobVRAM(labels, int(wholeGPU))) - total := w.totalMiB - for _, g := range l.lastGPUs { - if g.Index == w.gpu && total == 0 { - total = g.TotalMiB - } - } - if total > 0 { - gb = min(gb, int64(vramBudget(GPU{TotalMiB: total}, l.reserve))) - } - l.committedVRAM[w.gpu] += gb - w.vramGB - if l.committedVRAM[w.gpu] <= 0 { - delete(l.committedVRAM, w.gpu) - } - w.vramGB = gb -} - -// handleJobCompleted forgets assignments that finished without a runner of -// ours seeing them start. -func (l *Listener) handleJobCompleted(done []*scaleset.JobCompleted) { - l.workMu.Lock() - defer l.workMu.Unlock() - for _, jc := range done { - if jc != nil { - delete(l.known, jc.JobID) + return w + }) + if !held { + log.Printf("job started on unknown runner %q: charge left unchanged", js.RunnerName) } } } -// releaseWorker returns what a runner holds NOW when it exits. -func (l *Listener) releaseWorker(name string) { - l.workMu.Lock() - w := l.workers[name] - delete(l.workers, name) - l.workMu.Unlock() - if w == nil { - return - } - l.release(w.size) - if l.gpuProbe != nil { - l.releaseGPU(w.gpu, w.vramGB) - } -} - -// 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, #192): one probe and @@ -1060,7 +948,7 @@ func (l *Listener) committedSize() jobSize { // 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. +// 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. @@ -1079,12 +967,13 @@ func (l *Listener) admitGPU(ctx context.Context, labelSets ...[]string) (gpu, mi } else { gpus, want = idleReadings(l.lastGPUs), wholeGPU } - if l.committedVRAM[-1] != 0 { + committed := l.ledger.vramByGPU() + if committed[-1] != 0 { return 0, 0, 0, 0, false } switch { case len(gpus) > 0: - selected, cost, fits := pickGPU(gpus, l.committedVRAM, want, l.reserve) + selected, cost, fits := pickGPU(gpus, committed, want, l.reserve) if !fits { return 0, 0, 0, 0, false } @@ -1106,34 +995,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, @@ -1152,7 +1016,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 { @@ -1160,7 +1025,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/reactive_test.go b/listener/reactive_test.go index 4799f84..9868a71 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -56,7 +56,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) } @@ -667,14 +667,14 @@ func TestGPUAdmissionFailSafeUsesLastKnownGPUs(t *testing.T) { 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() @@ -682,7 +682,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) @@ -762,7 +762,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) } From 2165b71f61950a03f94fa3d6d0cfdc7afab927a1 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:10:05 +0800 Subject: [PATCH 08/10] =?UTF-8?q?fix(listener):=20=E6=AF=8F=E6=AC=A1?= =?UTF-8?q?=E6=B4=BE=E7=99=BC=E4=BD=BF=E7=94=A8=E7=8D=A8=E7=AB=8B=20runner?= =?UTF-8?q?=20=E5=90=8D=E7=A8=B1=EF=BC=8C=E4=B8=94=20CPU=20=E8=A8=88?= =?UTF-8?q?=E8=B2=BB=E6=B2=BF=E7=94=A8=E9=80=9A=E9=81=8E=E5=87=86=E5=85=A5?= =?UTF-8?q?=E7=9A=84=E5=A4=A7=E5=B0=8F=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/adr/0006-declared-job-cores.md | 4 + doc/changelog/CHANGELOG.md | 7 +- listener/charge_test.go | 10 +- listener/hostprobe.go | 5 + listener/job_workdir_test.go | 4 +- listener/ledger.go | 1 + listener/listener.go | 82 ++++++++++------- listener/listener_test.go | 6 +- listener/reactive_test.go | 10 +- listener/round4_test.go | 142 +++++++++++++++++++++++++++++ 10 files changed, 222 insertions(+), 49 deletions(-) create mode 100644 listener/round4_test.go diff --git a/doc/adr/0006-declared-job-cores.md b/doc/adr/0006-declared-job-cores.md index f3c01b9..e2bbb83 100644 --- a/doc/adr/0006-declared-job-cores.md +++ b/doc/adr/0006-declared-job-cores.md @@ -86,6 +86,10 @@ while bash reads `/proc`. assignments; 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/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index b747c54..fdf0bfb 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -244,7 +244,12 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 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. + 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/charge_test.go b/listener/charge_test.go index e3fda38..6b48368 100644 --- a/listener/charge_test.go +++ b/listener/charge_test.go @@ -30,7 +30,7 @@ func cpuListener() (*Listener, func()) { func startedMsg(runner string, labels ...string) []*scaleset.JobStarted { js := &scaleset.JobStarted{RunnerName: runner} - js.JobID = runner + js.JobID = jobOfRunner(runner) js.RequestLabels = labels return []*scaleset.JobStarted{js} } @@ -85,7 +85,7 @@ func TestJobStartedReattributesCharge(t *testing.T) { if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, jobs); err != nil { t.Fatal(err) } - l.handleJobStarted(startedMsg("big", "cpu-cores-1")) + l.handleJobStarted(startedMsg("big-r1", "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) } @@ -204,7 +204,7 @@ func TestGPUMaxVRAMChargeAndJobStarted(t *testing.T) { 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) } - l.handleJobStarted(startedMsg("second", "vram-gb-8")) + l.handleJobStarted(startedMsg("second-r2", "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) } @@ -277,7 +277,7 @@ func TestEnvelopeAssignedThenStartedNotKnown(t *testing.T) { // frees budget) must still retry admission against the last statistics. func TestEnvelopeWithoutStatsRetriesAdmission(t *testing.T) { block := make(chan struct{}) - started := &scaleset.JobStarted{RunnerName: "a"} + started := &scaleset.JobStarted{RunnerName: "a-r1"} started.JobID = "a" started.RequestLabels = []string{"cpu-cores-1"} sess := &fakeSession{messages: []*scaleset.RunnerScaleSetMessage{ @@ -316,7 +316,7 @@ func TestJobStartedGPUCardMissingFromProbe(t *testing.T) { if err := l.reconcile(ctx, &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, nil); err != nil { t.Fatal(err) } - l.handleJobStarted(startedMsg("r", "vram-gb-all")) + 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) } diff --git a/listener/hostprobe.go b/listener/hostprobe.go index 1fcebe4..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 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 index 0eee57c..76b7368 100644 --- a/listener/ledger.go +++ b/listener/ledger.go @@ -16,6 +16,7 @@ const retiredCap = 4096 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 diff --git a/listener/listener.go b/listener/listener.go index 978d7d3..7b3f9f5 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -7,6 +7,7 @@ package listener import ( + "fmt" "context" "crypto/rand" "encoding/hex" @@ -116,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 @@ -243,10 +248,14 @@ type Listener struct { wg sync.WaitGroup inFlight atomic.Int64 // jobs currently being provisioned (locally derived capacity, #102) // ledger owns every runner's charge from dispatch to exit (ADR-0006, - // #192). 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. + // #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; a job that @@ -300,6 +309,7 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) probe: cfg.HostProbe, gpuProbe: cfg.GPUProbe, ledger: newLedger(), + nameStamp: runnerNameStamp(), reserve: reserve, tracked: make(map[string]int), assigned: make(map[string]struct{}), @@ -440,6 +450,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 { @@ -505,8 +519,13 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS // 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() - if l.gpuProbe == nil && l.probe != nil && !l.admitOne(ctx, cost) { - return nil + 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. @@ -542,11 +561,10 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS // runner name it already holds: a redelivered assignment is dropped // here, uncharged, and admitted on a later round once the old runner // has exited (#192). - var charged jobSize - if l.gpuProbe == nil && l.probe != nil { - charged = l.clampCharge(cost) - } - token, held := l.ledger.dispatch(job.JobID, ledgerWorker{size: charged, gpu: gpu, vramGB: vramGB, totalMiB: vramTotalMiB}) + // 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 @@ -558,7 +576,8 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS } jobID := canonicalJobID(job.JobID) req := assignedRequest{ - rawJobID: job.JobID, + rawJobID: job.JobID, + runnerName: runnerName, ProvisionRequest: ProvisionRequest{ JobID: jobID, RequestID: job.RunnerRequestID, @@ -578,7 +597,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS workDir, err := socketJobWorkDir(jobID) if err != nil { <-l.sem - l.ledger.exit(req.rawJobID, token) + l.ledger.exit(req.runnerName, token) if hasAssignment { pending = pending[1:] l.releaseAssignment(req.rawJobID) @@ -591,11 +610,11 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS // 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.ledger.exit(req.rawJobID, token) + l.ledger.exit(req.runnerName, token) return err } req.EncodedJITConfig = jit @@ -614,7 +633,7 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS if hasAssignment { defer l.releaseAssignment(req.rawJobID) } - defer l.ledger.exit(req.rawJobID, token) + 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: @@ -866,34 +885,28 @@ 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, #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 fails safe -- a -// probe error admits (the semaphore ceiling is the backstop, and stranding -// acquired work is worse than a brief over-admit). -func (l *Listener) admitOne(ctx context.Context, cost jobSize) bool { +// 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 { - return true + 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) - return admits(h, l.committedSize(), clampSize(h, cost, l.reserve), l.reserve) -} - -// clampCharge is the size a runner is charged for a declared cost, clamped to -// the latest probe's budgets so a whole-host declaration holds exactly the -// whole budget. If no probe has succeeded, the declared cost is retained so the -// job is fully accounted for once probing recovers. -func (l *Listener) clampCharge(cost jobSize) jobSize { - if h := l.last.Load(); h != nil { - return clampSize(*h, cost, l.reserve) - } - return cost + charge = clampSize(h, cost, l.reserve) + return charge, budgetOf(h, l.reserve), admits(h, l.committedSize(), charge, l.reserve) } // handleJobStarted re-attributes each started job's runner to the size the job @@ -921,7 +934,10 @@ func (l *Listener) handleJobStarted(started []*scaleset.JobStarted) { } w.vramGB = gb case l.probe != nil: - w.size = l.clampCharge(jobSizeOf(labels)) + 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 }) diff --git a/listener/listener_test.go b/listener/listener_test.go index f419553..ea8f8c3 100644 --- a/listener/listener_test.go +++ b/listener/listener_test.go @@ -1263,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 @@ -1397,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 @@ -1409,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 { diff --git a/listener/reactive_test.go b/listener/reactive_test.go index 9868a71..1035446 100644 --- a/listener/reactive_test.go +++ b/listener/reactive_test.go @@ -145,13 +145,13 @@ func TestAdmitOneDeniesThenAdmitsOnNextProbe(t *testing.T) { } l := New(&fakeSession{}, &recordingMinter{}, &recordingProvisioner{}, Config{HostProbe: p, Reserve: 10, MaxRunners: 100}) - if l.admitOne(context.Background(), jobSize{1, 4}) { + if _, _, ok := l.admitOne(context.Background(), jobSize{1, 4}); ok { t.Fatal("admitOne must deny while over the line") } if p.callCount() != 1 { t.Errorf("probe calls after a denial = %d, want 1", p.callCount()) } - if !l.admitOne(context.Background(), jobSize{1, 4}) { + if _, _, ok := l.admitOne(context.Background(), jobSize{1, 4}); !ok { t.Fatal("admitOne should admit once headroom returns") } } @@ -305,7 +305,7 @@ func TestDeclaredCoresPackUpToTheBudget(t *testing.T) { &scaleset.RunnerScaleSetMessage{ MessageID: 2, Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2}, - JobStartedMessages: startedMsg("four", "cpu", "cpu-cores-4"), + JobStartedMessages: startedMsg("four-r1", "cpu", "cpu-cores-4"), }, msgWithAssigned(3, 3, assigned(3, "four-more", "cpu", "cpu-cores-4")), ) @@ -411,8 +411,8 @@ func TestVRAMJobsShareOneGPU(t *testing.T) { 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", "gpu", "vram-gb-8")}, - &scaleset.RunnerScaleSetMessage{MessageID: 3, Statistics: stats, JobStartedMessages: startedMsg("eight-b", "gpu", "vram-gb-8")}, + &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 diff --git a/listener/round4_test.go b/listener/round4_test.go new file mode 100644 index 0000000..63a703a --- /dev/null +++ b/listener/round4_test.go @@ -0,0 +1,142 @@ +package listener + +import ( + "context" + "sync" + "strings" + "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 +} + +func (s *swapProbe) Probe(context.Context) (HostResources, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.res, nil +} + +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 + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &gatedProvisioner{gates: []chan struct{}{make(chan struct{})}}, Config{ + Image: "img", HostProbe: probe, Reserve: 10, MaxRunners: 4, + }) + for range cap(l.sem) { // no worker slot is free, so dispatch waits after admission + 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")}) + }() + time.Sleep(200 * time.Millisecond) // admission has passed on the 8-core reading + 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) + } +} + +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 +} From d00be77c055e7feabf48eb5e18896e9a40f5bbc7 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:15:58 +0800 Subject: [PATCH 09/10] =?UTF-8?q?test(listener):=20=E5=8A=A0=E5=BC=B7?= =?UTF-8?q?=E5=87=86=E5=85=A5=E8=88=87=E9=87=8D=E6=96=B0=E6=AD=B8=E5=B1=AC?= =?UTF-8?q?=E7=9A=84=E5=9B=9E=E6=AD=B8=E6=B8=AC=E8=A9=A6=EF=BC=8C=E7=B9=9E?= =?UTF-8?q?=E9=81=8E=E5=87=86=E5=85=A5=E6=88=96=E6=94=B9=E7=94=A8=20job=20?= =?UTF-8?q?id=20=E6=AF=94=E5=B0=8D=E6=99=82=E6=9C=83=E5=A4=B1=E6=95=97=20(?= =?UTF-8?q?#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 輪詢回歸測試(CPU):第一個 runner 真的佔住整個 budget,第二個不會被開出, 且第三個 message 的 AcquireJobs 照常進行。 - 輪詢回歸測試(GPU):卡已滿時不會開出 runner,也不會在卡上記帳。 - 釋放後再派發:第一個 runner 透過真正的結束流程釋放額度,不再直接改 ledger。 - 重新歸屬:JobStarted 的 job id 和 runner 被開出時的 assignment 不同,只有依 JIT runner 名稱比對才會通過;補上 GPU 未知 runner 不改變記帳的斷言。 - 新增 message loop 層級的測試:未知 runner 的 JobStarted 不改變任何記帳,但該 job 已開始,不再是已知 assignment,也不再影響下一個 runner 的保守計費。 - round4 測試改成等待准入探測,不再 sleep,結束時釋放 provisioner。 --- listener/charge_test.go | 127 ++++++++++++++++++++++++++++++-------- listener/listener_test.go | 33 ++++++---- listener/reactive_test.go | 3 +- listener/round4_test.go | 32 +++++++--- 4 files changed, 149 insertions(+), 46 deletions(-) diff --git a/listener/charge_test.go b/listener/charge_test.go index 6b48368..9281277 100644 --- a/listener/charge_test.go +++ b/listener/charge_test.go @@ -29,8 +29,16 @@ func cpuListener() (*Listener, func()) { } 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 = jobOfRunner(runner) + js.JobID = jobID js.RequestLabels = labels return []*scaleset.JobStarted{js} } @@ -85,7 +93,8 @@ func TestJobStartedReattributesCharge(t *testing.T) { if err := l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, jobs); err != nil { t.Fatal(err) } - l.handleJobStarted(startedMsg("big-r1", "cpu-cores-1")) + // 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) } @@ -102,8 +111,9 @@ func TestJobStartedUnknownRunnerIgnored(t *testing.T) { t.Fatal(err) } var buf bytes.Buffer + prev := log.Writer() log.SetOutput(&buf) - defer log.SetOutput(log.Writer()) + 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) @@ -114,38 +124,52 @@ func TestJobStartedUnknownRunnerIgnored(t *testing.T) { } // 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) { - prov := &recordingProvisioner{} + release := make(chan struct{}) mnt := &recordingMinter{config: "jit"} - l := New(&fakeSession{}, mnt, prov, Config{ + 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, }) - idle := holdCharge(l, "idle", ledgerWorker{size: jobSize{cores: 1, gb: 4}, gpu: -1}) // an idle runner holds the whole 1-core budget - stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1} - if err := l.reconcile(context.Background(), stats, nil); err != nil { + 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) != 0 { - t.Fatalf("minted %d runners while the budget was full", len(mnt.gotNames)) + 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) } - l.ledger.exit("idle", idle) - if err := l.reconcile(context.Background(), stats, nil); err != nil { + stats := &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 2} + if err := l.reconcile(ctx, stats, nil); err != nil { t.Fatal(err) } - l.wg.Wait() if len(mnt.gotNames) != 1 { - t.Errorf("minted %d runners after release, want 1", len(mnt.gotNames)) + 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. +// 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() - acquired := make(chan struct{}, 1) + polledAfter2 := make(chan struct{}, 1) sess := &fakeSession{ messages: []*scaleset.RunnerScaleSetMessage{ msgWithAssigned(1, 1, assigned(1, "a", "vram-gb-16")), @@ -155,15 +179,18 @@ func TestRunKeepsPollingWhenNoGPUFits(t *testing.T) { JobAvailableMessages: []*scaleset.JobAvailable{{JobMessageBase: scaleset.JobMessageBase{RunnerRequestID: 77}}}, }, }, - onAcquire: func(context.Context) error { - select { - case acquired <- struct{}{}: - default: + // 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: + } } - return nil }, } - l := New(sess, &recordingMinter{config: "jit"}, &recordingProvisioner{}, Config{ + mnt := &recordingMinter{config: "jit"} + l := New(sess, mnt, &recordingProvisioner{}, Config{ Image: "img-gpu", GPUProbe: stubGPUProbe{gpus: []GPU{rtx5090(0, 30000)}}, Reserve: 20, @@ -172,9 +199,18 @@ func TestRunKeepsPollingWhenNoGPUFits(t *testing.T) { done := make(chan struct{}) go func() { _ = l.Listen(ctx); close(done) }() select { - case <-acquired: + case <-polledAfter2: case <-time.After(2 * time.Second): - t.Fatal("message loop stalled: AcquireJobs never ran while no GPU fit") + 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 @@ -204,10 +240,15 @@ func TestGPUMaxVRAMChargeAndJobStarted(t *testing.T) { 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) } - l.handleJobStarted(startedMsg("second-r2", "vram-gb-8")) + // 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 { @@ -327,6 +368,42 @@ func TestJobStartedGPUCardMissingFromProbe(t *testing.T) { } } +// 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 diff --git a/listener/listener_test.go b/listener/listener_test.go index ea8f8c3..2fd2cc1 100644 --- a/listener/listener_test.go +++ b/listener/listener_test.go @@ -1430,7 +1430,7 @@ func TestListenReturnsMintErrorAfterDispatchingEarlierAssignment(t *testing.T) { func TestRunKeepsPollingWhenAdmissionFull(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - acquired := make(chan struct{}, 1) + polledAfter3 := make(chan struct{}, 1) sess := &fakeSession{ messages: []*scaleset.RunnerScaleSetMessage{ msgWithAssigned(1, 1, assigned(1, "a")), @@ -1443,20 +1443,22 @@ func TestRunKeepsPollingWhenAdmissionFull(t *testing.T) { }, }, }, - onAcquire: func(context.Context) error { - select { - case acquired <- struct{}{}: - default: + // 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: + } } - return nil }, - beforePoll: func(int) {}, } // Idle runner "a" stays inside Provision and keeps its charge. block := make(chan struct{}) prov := &recordingProvisioner{block: block} - // 2-core host, 10% reserve: budget 1.8 cores, so one 1-core runner fills it. - l := New(sess, &recordingMinter{config: "jit"}, prov, Config{ + 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, @@ -1466,9 +1468,18 @@ func TestRunKeepsPollingWhenAdmissionFull(t *testing.T) { go func() { _ = l.Listen(ctx); close(done) }() select { - case <-acquired: + case <-polledAfter3: case <-time.After(2 * time.Second): - t.Fatal("message loop stalled: AcquireJobs for the third message never ran while admission was full") + 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. diff --git a/listener/reactive_test.go b/listener/reactive_test.go index 1035446..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 diff --git a/listener/round4_test.go b/listener/round4_test.go index 63a703a..7294814 100644 --- a/listener/round4_test.go +++ b/listener/round4_test.go @@ -2,8 +2,8 @@ package listener import ( "context" - "sync" "strings" + "sync" "sync/atomic" "testing" "time" @@ -25,16 +25,24 @@ func (p *gatedProvisioner) Provision(_ context.Context, _ ProvisionRequest) erro // swapProbe is a host probe whose reading a test can replace between calls. type swapProbe struct { - mu sync.Mutex - res HostResources + 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 @@ -99,10 +107,14 @@ func TestDelayedJobStartedDoesNotResizeReplacement(t *testing.T) { // have replaced in between. func TestChargeIsTheAdmittedSize(t *testing.T) { probe := &swapProbe{res: hostOf(8)} // budget 7 cores at reserve 10 - l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &gatedProvisioner{gates: []chan struct{}{make(chan struct{})}}, Config{ + gate := make(chan struct{}) + l := New(&fakeSession{}, &recordingMinter{config: "jit"}, &gatedProvisioner{gates: []chan struct{}{gate}}, Config{ Image: "img", HostProbe: probe, Reserve: 10, MaxRunners: 4, }) - for range cap(l.sem) { // no worker slot is free, so dispatch waits after admission + // 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) @@ -110,16 +122,18 @@ func TestChargeIsTheAdmittedSize(t *testing.T) { done <- l.reconcile(context.Background(), &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, []*scaleset.JobAssigned{assigned(1, "job", "cpu-cores-all")}) }() - time.Sleep(200 * time.Millisecond) // admission has passed on the 8-core reading - probe.set(hostOf(4)) // budget 3 cores - l.reactiveCapacity(context.Background()) // the reporter replaces the snapshot - <-l.sem // a slot frees: dispatch charges now + 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" } } From c1b1057a0a3f250cf8df9201bac45fa1b68e8ab0 Mon Sep 17 00:00:00 2001 From: cyc <54975526+ycpss91255@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:18:10 +0800 Subject: [PATCH 10/10] =?UTF-8?q?docs(listener):=20=E8=A8=BB=E8=A7=A3?= =?UTF-8?q?=E8=88=87=E6=96=87=E4=BB=B6=E6=94=B9=E7=82=BA=E5=AF=A6=E9=9A=9B?= =?UTF-8?q?=E8=A1=8C=E7=82=BA=EF=BC=9Aretire=20=E4=B8=8A=E9=99=90=E3=80=81?= =?UTF-8?q?=E6=9C=AA=E7=9F=A5=20runner=20=E7=9A=84=20JobStarted=E3=80=81?= =?UTF-8?q?=E6=AF=8F=E5=80=8B=20envelope=20=E9=87=8D=E8=A9=A6=E5=87=86?= =?UTF-8?q?=E5=85=A5=20(#192)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - retire 的 job id 只保留最近 4096 個,超過就忘掉最舊的;ledger 註解、ADR-0006、 CHANGELOG 不再說「永遠不會再回到已知 assignment」。 - 未知 runner 的 JobStarted:不改變任何記帳,只記 log;但該 job 已開始,離開已 知 assignment,不再影響下一個 runner 的保守計費。ledger、listener、ADR-0006、 CHANGELOG、README 一致。 - Listen 註解:啟動、每個 message envelope(包含沒有 statistics 的)與空輪詢都 依最新的 statistics 重試准入。 - dispatch 註解:重送的 assignment 由 reserveAssignment 擋下;每次派發都有獨立 的 runner 名稱,ledger 拒絕同名只是防護。 - ADR-0006:派發時是保守估計,JobStarted 之後依 JIT runner 名稱歸屬實際 job; README 補上保守計費、同卡 GPU 重新歸屬與空輪詢重試。 - gofmt 整理 ledger.go、ledger_test.go、listener.go。 --- doc/adr/0006-declared-job-cores.md | 15 ++++++--- doc/changelog/CHANGELOG.md | 9 ++++-- listener/README.md | 11 +++++-- listener/ledger.go | 20 +++++++----- listener/ledger_test.go | 1 - listener/listener.go | 49 ++++++++++++++++-------------- 6 files changed, 65 insertions(+), 40 deletions(-) diff --git a/doc/adr/0006-declared-job-cores.md b/doc/adr/0006-declared-job-cores.md index e2bbb83..bfef77b 100644 --- a/doc/adr/0006-declared-job-cores.md +++ b/doc/adr/0006-declared-job-cores.md @@ -71,7 +71,10 @@ 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. + 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). @@ -79,11 +82,15 @@ while bash reads `/proc`. 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 is logged and ignored. + 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 never returns to the known - assignments; a runner name already held is refused; an exit releases only + 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 diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index fdf0bfb..5789a16 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -234,13 +234,16 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 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). A `JobStarted` for a runner the listener does not hold - is logged and ignored. Until it arrives an idle runner holds the larger + (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 can never return to the known assignments, 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 diff --git a/listener/README.md b/listener/README.md index b98a9e9..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 runner that would breach the reserve is not admitted that - round; the next message re-probes (#192). + 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/ledger.go b/listener/ledger.go index 76b7368..ce9086a 100644 --- a/listener/ledger.go +++ b/listener/ledger.go @@ -7,8 +7,9 @@ import ( ) // retiredCap bounds how many started or completed job ids the ledger -// remembers. A retired id only has to outlive the redelivery of its own -// assignment, so the oldest are forgotten first. +// 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 @@ -17,9 +18,9 @@ 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 + 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 @@ -29,8 +30,9 @@ type ledgerWorker struct { // 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 a retired -// id can never re-enter the known assignments; +// - 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 @@ -55,7 +57,9 @@ func newLedger() *ledger { // 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. +// 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() diff --git a/listener/ledger_test.go b/listener/ledger_test.go index ad82953..c85cc95 100644 --- a/listener/ledger_test.go +++ b/listener/ledger_test.go @@ -111,7 +111,6 @@ func TestLedgerOrderInsensitive(t *testing.T) { } } - // 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) { diff --git a/listener/listener.go b/listener/listener.go index 7b3f9f5..d0b9a66 100644 --- a/listener/listener.go +++ b/listener/listener.go @@ -7,11 +7,11 @@ package listener import ( - "fmt" "context" "crypto/rand" "encoding/hex" "errors" + "fmt" "log" "os" "path/filepath" @@ -300,19 +300,19 @@ func New(session Session, minter JITConfigMinter, prov Provisioner, cfg Config) } } return &Listener{ - 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{}), + 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{}), } } @@ -344,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 @@ -412,7 +414,9 @@ func (l *Listener) Listen(ctx context.Context) (err error) { } 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). + // 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 { @@ -557,10 +561,10 @@ func (l *Listener) dispatch(ctx context.Context, stats *scaleset.RunnerScaleSetS 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. The ledger refuses a - // runner name it already holds: a redelivered assignment is dropped - // here, uncharged, and admitted on a later round once the old runner - // has exited (#192). + // 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)) @@ -913,7 +917,8 @@ func (l *Listener) admitOne(ctx context.Context, cost jobSize) (charge, budget j // 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 ignored. +// 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 {