Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- **Coordinator capacity and admission** — Model readiness honors public routing gates while retaining inventory and the fleet-wide health-breaker fallback. Expired capacity probes settle as timeouts; oversized prompt/output sums are rejected without integer wrapping.

## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10)

Source changes since `v0.9.1`. Provider changes require a new signed bundle.
Expand Down
16 changes: 10 additions & 6 deletions coordinator/registry/capacity_quotes.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,12 @@ type QuoteOutcome struct {
}

// quoteDelivery is the tracker→collector handoff for one settled probe.
// quote == nil means transport failure (send error or disconnect).
// timeout marks an expiry sweep; otherwise quote == nil means transport failure.
type quoteDelivery struct {
quoteID string
providerID string
quote *protocol.CapacityQuoteMessage
timeout bool
}

// pendingQuote is one outstanding probe: the provider binding the quote must
Expand Down Expand Up @@ -100,10 +101,10 @@ type quoteTracker struct {
sweeps int
}

// add registers an outstanding probe. The opportunistic sweep (same idiom as
// the sibling cooldown maps) drops expired entries whose collector died
// before its window sweep — a leak only a panicked collector can create,
// since a live one takes back every silent entry at expiry. The >1024 size
// add registers an outstanding probe. The opportunistic sweep settles expired
// entries, including when its collector has not yet processed the timer. Every
// removal must deliver an outcome: collectors treat a missing entry as a claim
// whose delivery is in flight. The >1024 size
// trigger merely makes a sweep WORTH considering; the time gate
// (quoteTrackerSweepInterval) decides whether one actually runs.
func (t *quoteTracker) add(quoteID string, pq *pendingQuote) {
Expand All @@ -120,6 +121,9 @@ func (t *quoteTracker) add(quoteID string, pq *pendingQuote) {
for id, e := range t.pending {
if now.After(e.expiresAt) {
delete(t.pending, id)
if e.deliver != nil {
e.deliver <- quoteDelivery{quoteID: id, providerID: e.providerID, timeout: true}
}
}
}
}
Expand Down Expand Up @@ -345,7 +349,7 @@ func (r *Registry) ProbePlanCandidates(plan *DispatchPlan, shape CapacityProbeSh
func applyQuoteDelivery(plan *DispatchPlan, d quoteDelivery) QuoteOutcome {
if d.quote == nil {
plan.DemoteEntry(d.providerID)
return QuoteOutcome{ProviderID: d.providerID, SendFailed: true}
return QuoteOutcome{ProviderID: d.providerID, Timeout: d.timeout, SendFailed: !d.timeout}
}
if d.quote.AdmissibleNow {
plan.ConfirmEntry(d.providerID, d.quote)
Expand Down
58 changes: 58 additions & 0 deletions coordinator/registry/capacity_quotes_expiry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package registry

import (
"fmt"
"testing"
"time"
)

func TestQuoteTrackerSweepSettlesLiveCollector(t *testing.T) {
reg := New(testLogger())
const model = "swept-quote-model"
planTestProvider(t, reg, "primary", model, 0)
alternate := planTestProvider(t, reg, "alternate", model, 400)
request := planTestRequest("swept-quote", 100, 64)
request.Model = model
_, _, plan := reg.ReserveProviderWithPlan(model, request)
setQuoteCapable(alternate)
conn := attachTestWriter(t, alternate)
out := reg.ProbePlanCandidates(plan, CapacityProbeShape{Model: model}, time.Hour)
probe := readProbeFrame(t, conn)

// Advance just this quote's expiry, then force the opportunistic sweep
// before its collector's timer runs. No scheduler timing race is needed.
tracker := &reg.capacityQuotes
tracker.mu.Lock()
pending := tracker.pending[probe.QuoteID]
pending.expiresAt = time.Now().Add(-time.Second)
for i := range 1025 {
tracker.pending[fmt.Sprintf("unexpired-%d", i)] = &pendingQuote{expiresAt: time.Now().Add(time.Hour)}
}
tracker.lastSweep = time.Time{}
tracker.mu.Unlock()
tracker.add("trigger", &pendingQuote{expiresAt: time.Now().Add(time.Hour)})

select {
case result := <-out:
if !result.Timeout || result.SendFailed || result.Quote != nil || result.ProviderID != alternate.ID {
t.Fatalf("swept outcome = %+v, want timeout for %s", result, alternate.ID)
}
if !plan.entries[0].view.Demoted {
t.Fatal("timeout was published before demoting the plan entry")
}
case <-time.After(time.Second):
// Release the collector on the regressed implementation too, so the
// characterization failure does not leave its hour-long goroutine.
pending.deliver <- quoteDelivery{quoteID: probe.QuoteID, providerID: alternate.ID}
collectOutcomes(t, out)
t.Fatal("expiry sweep removed the probe without settling its live collector")
}
select {
case _, open := <-out:
if open {
t.Fatal("swept probe produced more than one outcome")
}
case <-time.After(time.Second):
t.Fatal("settled collector did not close its output")
}
}
19 changes: 6 additions & 13 deletions coordinator/registry/dedicated_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ import "strings"
// the coordinator entrypoint to read EIGENINFERENCE_DEDICATED_MODELS. An empty
// or all-blank input yields a nil slice (feature disabled).
func ParseDedicatedModels(csv string) []string {
return normalizeDedicatedModels(strings.Split(csv, ","))
}

func normalizeDedicatedModels(patterns []string) []string {
var out []string
for _, p := range strings.Split(csv, ",") {
for _, p := range patterns {
p = strings.ToLower(strings.TrimSpace(p))
if p == "" {
continue
Expand All @@ -32,20 +36,9 @@ func ParseDedicatedModels(csv string) []string {
// empty (or all-blank) list disables the feature. Called once at startup before
// the coordinator begins serving.
func (r *Registry) SetDedicatedModels(patterns []string) {
normalized := make([]string, 0, len(patterns))
for _, p := range patterns {
p = strings.ToLower(strings.TrimSpace(p))
if p == "" {
continue
}
normalized = append(normalized, p)
}
normalized := normalizeDedicatedModels(patterns)
r.mu.Lock()
defer r.mu.Unlock()
if len(normalized) == 0 {
r.dedicatedModels = nil
return
}
r.dedicatedModels = normalized
}

Expand Down
45 changes: 43 additions & 2 deletions coordinator/registry/model_capacity.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ type ModelCapacity struct {
// providerCapSnap is a per-provider snapshot collected under the registry
// lock, then aggregated into ModelCapacity outside the lock.
type providerCapSnap struct {
providerID string
model string
warm bool
running bool
hasHeadroom bool // pending < maxConcurrency
hasHeadroom bool // public model gates and concurrency both pass
effectiveTPS float64
prefillTPS float64
activeRequests int // numRunning + numWaiting from backend slot, or pendingCount
Expand Down Expand Up @@ -68,6 +69,7 @@ func (r *Registry) ModelCapacitySnapshot() []ModelCapacity {

// Phase 1: collect per-provider snapshots under the lock.
var snaps []providerCapSnap
breakerModels := make(map[string]struct{})

r.mu.RLock()
for _, p := range r.providers {
Expand Down Expand Up @@ -108,7 +110,11 @@ func (r *Registry) ModelCapacitySnapshot() []ModelCapacity {
// path enforces, so the public capacity feed doesn't advertise a capped
// box (e.g. Gemma at 2) as routable up to the flat fallback (24) and lure
// upstream routers into sending requests this coordinator immediately 429s.
hasHeadroom := r.hasConcurrencyHeadroomForModelCapResolvedLocked(p, m.ID)
passesGates, reason := r.providerRoutingGateReasonLockedEx(p, m.ID, RequestTraits{}, false, now, false, false)
if reason == GateBreaker || reason == GateEjection {
breakerModels[m.ID] = struct{}{}
}
hasHeadroom := passesGates && r.hasConcurrencyHeadroomForModelCapResolvedLocked(p, m.ID)
// Count only pending requests for this specific model, not the
// total across all models. Using the total inflates
// activeRequests for multi-model providers.
Expand All @@ -135,6 +141,7 @@ func (r *Registry) ModelCapacitySnapshot() []ModelCapacity {
)

snap := providerCapSnap{
providerID: p.ID,
model: m.ID,
hasHeadroom: hasHeadroom,
effectiveTPS: decodeTPS,
Expand Down Expand Up @@ -180,6 +187,17 @@ func (r *Registry) ModelCapacitySnapshot() []ModelCapacity {
}
p.mu.Unlock()
}
// A strict per-provider gate cannot decide the fleet-wide breaker valve.
// Only affected models need the shared dispatch scan; inventory stays intact.
for model := range breakerModels {
if fallback := r.modelCapacityBreakerFallbackLocked(model); fallback != nil {
for i := range snaps {
if snaps[i].model == model {
snaps[i].hasHeadroom = fallback[snaps[i].providerID]
}
}
}
}
r.mu.RUnlock()

// Phase 2: aggregate per-model outside the lock.
Expand Down Expand Up @@ -305,3 +323,26 @@ func (r *Registry) ModelCapacitySnapshot() []ModelCapacity {
}
return result
}

// modelCapacityBreakerFallbackLocked returns the fleet's last-resort cohort only
// when dispatch would bypass health breakers. Capacity has no request shape, so
// test the smallest positive text reservation (one output token, no deadline).
// Healthy-but-busy peers suppress the fallback through the shared scan tallies;
// structural, thermal, memory and cooldown gates still apply on its second pass.
// Caller holds r.mu and no provider lock. No reservation is committed.
func (r *Registry) modelCapacityBreakerFallbackLocked(model string) map[string]bool {
request := &PendingRequest{Model: model, RequestedMaxTokens: 1}
scan := r.scanCandidatesLocked(model, request, false)
if len(scan.pool) > 0 || !shouldBypassBreakerFailOpen(nil, scan.breakerRejected, scan.capacityRejections, scan.ttftRejections) {
return nil
}
scan = r.scanCandidatesLocked(model, request, true)
if len(scan.pool) == 0 {
return nil
}
providers := make(map[string]bool, len(scan.pool))
for _, candidate := range scan.pool {
providers[candidate.provider.ID] = true
}
return providers
}
107 changes: 107 additions & 0 deletions coordinator/registry/model_capacity_gates_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package registry

import (
"fmt"
"github.com/eigeninference/d-inference/coordinator/attestation"
"testing"
)

func TestModelCapacityDoesNotAdvertiseStructurallyExcludedPairs(t *testing.T) {
for _, tc := range []struct {
name string
exclude func(*Registry, *Provider)
}{
{"broken template", func(_ *Registry, p *Provider) {
p.mu.Lock()
p.Models[0].TemplateRenderOK = boolPtr(false)
p.mu.Unlock()
}},
{"mixed dedicated family", func(r *Registry, p *Provider) {
r.SetDedicatedModels([]string{"gemma-4"})
addAdvertisedModel(p, qwenBuild)
}},
} {
t.Run(tc.name, func(t *testing.T) {
reg := New(testLogger())
p := makeSchedulerProvider(t, reg, "excluded", gemmaBuild, 100)
initial := reg.ModelCapacitySnapshot()
if len(initial) != 1 || !initial[0].Ready || initial[0].RoutableProviders != 1 {
t.Fatalf("healthy pair must initially be ready: %+v", initial)
}
tc.exclude(reg, p)
request := &PendingRequest{RequestID: "excluded", Model: gemmaBuild, RequestedMaxTokens: 64}
if selected, _ := reg.ReserveProviderEx(gemmaBuild, request); selected != nil {
t.Fatal("precondition: routing must exclude this provider/model pair")
}
found := false
for _, capacity := range reg.ModelCapacitySnapshot() {
if capacity.ModelID != gemmaBuild {
continue
}
found = true
if capacity.Ready || capacity.CanAccept || capacity.RoutableProviders != 0 {
t.Fatalf("unroutable pair advertised ready: %+v", capacity)
}
if capacity.WarmProviders != 1 {
t.Fatalf("excluded pair lost its resident inventory: %+v", capacity)
}
}
if !found {
t.Fatal("excluded pair disappeared from model inventory")
}
})
}
}

func TestModelCapacityPreservesFleetBreakerFallback(t *testing.T) {
for _, health := range []bool{false, true} {
for _, peer := range []string{"none", "healthy", "busy", "thermal", "broken template"} {
t.Run(fmt.Sprintf("ejection=%v/peer=%s", health, peer), func(t *testing.T) {
reg := New(testLogger())
model := "capacity-breaker"
bad := makeSchedulerProvider(t, reg, "bad", model, 100)
if health {
bad.AttestationResult = &attestation.VerificationResult{Valid: true, SerialNumber: "CAPACITY-BAD"}
for range healthEjectionConsecTrip {
reg.RecordProviderServeOutcome("serial:CAPACITY-BAD", false, 500, "boom")
}
if !reg.HealthEjectionOpen("serial:CAPACITY-BAD") {
t.Fatal("ejection did not open")
}
} else {
for range providerBreakerConsecTrip {
reg.RecordProviderOutcome(bad.ID, false, 500, "boom")
}
if !reg.ProviderBreakerOpen(bad.ID) {
t.Fatal("breaker did not open")
}
}
if peer != "none" {
p := makeSchedulerProvider(t, reg, "peer", model, 50)
switch peer {
case "busy":
p.BackendCapacity.Slots[0].MaxConcurrency = 1
p.AddPending(&PendingRequest{RequestID: "busy", Model: model})
case "thermal":
p.SystemMetrics.ThermalState = "critical"
case "broken template":
p.Models[0].TemplateRenderOK = boolPtr(false)
}
}
capacity := reg.ModelCapacitySnapshot()
request := &PendingRequest{RequestID: "probe", Model: model, RequestedMaxTokens: 1}
selected, decision := reg.ReserveProviderEx(model, request)
want := 1
if peer == "busy" {
want = 0
}
if (selected != nil) != (want > 0) || decision.CandidateCount != want {
t.Fatalf("dispatch precondition: selected=%v decision=%+v", selected != nil, decision)
}
if len(capacity) != 1 || capacity[0].RoutableProviders != want || capacity[0].Ready != (want > 0) {
t.Fatalf("capacity disagrees with dispatch cohort: %+v; want %d", capacity, want)
}
})
}
}
}
Loading
Loading