Skip to content
Merged
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
Expand Up @@ -4,6 +4,10 @@

- Restore a reconnecting provider's reputation and account linkage from a live store lookup keyed to the attested Secure Enclave public key, excluding the registering session's own row, so a restart, lid-close, or reconnect no longer resets standing to the 0.60 cold-start default. Device metadata comes from the newest row and reputation from the newest row that earned it, with a deterministic `last_seen`/`id` tie-break shared by the memory and PostgreSQL stores. Hardware trust is still re-earned live on every connection.

## Unreleased — first-byte serving-slot latch

- Resolve the dispatched slot's KV-backend attribution from the provider the dispatch goroutine already holds, on every path that runs between provider handoff and the first client byte: the primary handoff latch, the speculative backup-pointer re-latch, and the promoted-winner / latch-mismatch and genuine-fault live-winner reads before the committed response. None of these take the registry read lock any more, so a concurrent registry write lock can no longer stall the first byte. Preserve the model/provider/slot attribution, frozen terminal (genuine-fault) attribution, exactly-once accounting, reservations, and failover/retry/speculative behavior; a provider mismatch resolves to unknown rather than borrowing another slot's tag or reaching for the registry lock.

## Unreleased — provider console entry

- Open the provider workspace directly from the console home page, removing the Consumer/Provider selection page. Keep chat and API access in workspace navigation.
Expand Down
12 changes: 9 additions & 3 deletions coordinator/api/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -1754,8 +1754,14 @@ func (d *dispatchState) dispatchPrimary() dispatchOutcome {
}
// The request is now on a slot. Latch that slot's KV backend so the
// exhaustion ladder can still attribute the outcome after a failover has
// cleared d.provider/d.pr (v0.8.0 paged rollout, Gate G5).
d.noteServingSlot()
// cleared d.provider/d.pr (v0.8.0 paged rollout, Gate G5). Resolve it from
// the provider we already hold: this runs between the handoff and the first
// client byte, so it must not take the registry read lock (see
// noteServingSlotFor). d.provider is the slot d.pr was written to.
if s.beforeServingSlotAttribution != nil {
s.beforeServingSlotAttribution()
}
d.noteServingSlotFor(d.provider, d.pr)
// Routing v2 W2: the primary frame is handed off — confirm the retained
// alternates in parallel with the in-flight prompt (one probe round per
// request; zero added primary latency by construction).
Expand Down Expand Up @@ -3060,7 +3066,7 @@ func (d *dispatchState) racePrimaryFailedWaitBackup(backupProvider *registry.Pro
// re-latch is a no-op by design: the terminal response will be the
// primary's 4xx/422/429, so the primary keeps the attribution even
// though the backup keeps racing (noteServingSlotFor's freeze rule).
d.noteServingSlotFor(backupPR)
d.noteServingSlotFor(backupProvider, backupPR)
backupDeadline := time.NewTimer(d.firstTokenWait(d.deadline - d.speculativeAt))
for {
select {
Expand Down
20 changes: 10 additions & 10 deletions coordinator/api/dispatch_speculative_outcome_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ func TestSpeculativeBackupFailureAttributesBackupKVBackend(t *testing.T) {
heartbeatKV(primary, &paged)
heartbeatKV(backup, &contiguous)

// Dispatch latched the PRIMARY's slot...
d.pr = primaryPR
// Dispatch latched the PRIMARY's slot (d.provider always accompanies d.pr)...
d.provider, d.pr = primary, primaryPR
d.noteServingSlot()
if got := d.kvBackendAttribution().Backend; got != registry.KVBackendPaged {
t.Fatalf("primary latch = %q, want %q", got, registry.KVBackendPaged)
Expand Down Expand Up @@ -164,8 +164,8 @@ func TestDeterministicPrimaryVerdictKeepsPrimaryAttribution(t *testing.T) {
heartbeatSlotKV(d, primary, registry.KVBackendPaged)
heartbeatSlotKV(d, backup, registry.KVBackendContiguous)

// Dispatch latched the primary's slot...
d.pr = primaryPR
// Dispatch latched the primary's slot (d.provider always accompanies d.pr)...
d.provider, d.pr = primary, primaryPR
d.noteServingSlot()

// ...then the primary failed with a deterministic client 4xx: runRace's
Expand Down Expand Up @@ -211,12 +211,12 @@ func TestPromotedBackupSavedOnLiveMismatch(t *testing.T) {
heartbeatSlotKV(d, primary, registry.KVBackendPaged)
heartbeatSlotKV(d, backup, registry.KVBackendContiguous)

d.pr = primaryPR
d.provider, d.pr = primary, primaryPR
d.noteServingSlot()

// Promotion outside the choke point: d.pr moves to the backup with no
// explicit re-latch.
d.pr = backupPR
// Promotion outside the choke point: d.provider/d.pr move to the backup
// with no explicit re-latch (they are always assigned together).
d.provider, d.pr = backup, backupPR
if got := d.kvBackendAttribution().Backend; got != registry.KVBackendContiguous {
t.Fatalf("live mismatch read = %q, want the backup's %q", got, registry.KVBackendContiguous)
}
Expand All @@ -240,7 +240,7 @@ func TestFrozenLatchSurvivesLiveMismatchRead(t *testing.T) {
heartbeatSlotKV(d, primary, registry.KVBackendPaged)
heartbeatSlotKV(d, backup, registry.KVBackendContiguous)

d.pr = primaryPR
d.provider, d.pr = primary, primaryPR
d.noteServingSlot()
verdict := protocol.InferenceErrorMessage{
Error: "prompt malformed",
Expand All @@ -249,7 +249,7 @@ func TestFrozenLatchSurvivesLiveMismatchRead(t *testing.T) {
}
d.latchDeterministicLoser(primary, verdict)

d.pr = backupPR
d.provider, d.pr = backup, backupPR
if got := d.kvBackendAttribution().Backend; got != registry.KVBackendContiguous {
t.Fatalf("live read = %q, want the backup's %q (live reads stay truthful)", got, registry.KVBackendContiguous)
}
Expand Down
210 changes: 210 additions & 0 deletions coordinator/api/first_byte_serving_slot_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
package api

import (
"context"
"encoding/json"
"net/http"
"strings"
"sync"
"testing"
"time"

"github.com/eigeninference/d-inference/coordinator/protocol"
"nhooyr.io/websocket"
)

// TestServingSlotLatchDoesNotWaitOnRegistryWriteLock is the deterministic
// regression for the post-handoff serving-slot bookkeeping stalling the first
// client byte. TestFirstByteReachesClientWhileRegistryWriteLockHeld exercises
// the same interval but races the write-lock acquisition against the dispatch
// goroutine reaching the latch, so it reproduces the bug only intermittently.
//
// This test forces the exact ordering through the real dispatch/HTTP path with
// the beforeServingSlotAttribution seam: the seam fires on the dispatch
// goroutine AFTER the inference frame is handed off and BEFORE the serving-slot
// KV latch. The test parks the dispatch goroutine there, takes the registry
// WRITE lock, and only then lets the latch run. Before the fix the latch
// resolved the slot through Registry.SlotKVBackendTags -> Registry.GetProvider,
// which takes the registry READ lock, so the dispatch goroutine blocked on the
// held write lock and the first byte never reached the client. After the fix
// the latch reads the provider the goroutine already holds and never touches
// the registry, so the first byte is delivered while the lock is still held.
func TestServingSlotLatchDoesNotWaitOnRegistryWriteLock(t *testing.T) {
srv, reg, _, ts := setupTestServer(t)
defer ts.Close()

// Seam: park the dispatch goroutine between handoff and the serving-slot
// latch until the test holds the registry write lock, then let it run.
reachedLatch := make(chan struct{})
proceed := make(chan struct{})
var reachedOnce, proceedOnce sync.Once
// releaseProceed is idempotent and deferred: any early t.Fatal below still
// unparks the dispatch goroutine from the seam, so httptest's Close never
// waits on a handler blocked at <-proceed.
releaseProceed := func() { proceedOnce.Do(func() { close(proceed) }) }
defer releaseProceed()
srv.beforeServingSlotAttribution = func() {
reachedOnce.Do(func() { close(reachedLatch) })
<-proceed
}

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

pubKey := testPublicKeyB64()
const model = "serving-slot-lock-model"
models := []protocol.ModelInfo{{ID: model, ModelType: "chat", Quantization: "4bit"}}
conn := connectProvider(t, ctx, ts.URL, models, pubKey)
defer conn.Close(websocket.StatusNormalClosure, "")

challengeCtx, challengeCancel := context.WithTimeout(ctx, 5*time.Second)
waitForChallenge(t, challengeCtx, conn, pubKey)
challengeCancel()
time.Sleep(200 * time.Millisecond)
makeProviderRoutable(reg)

gotRequest := make(chan protocol.InferenceRequestMessage, 1)
sendChunkNow := make(chan struct{})
sendCompleteNow := make(chan struct{})
// Idempotent, deferred releases: an early t.Fatal still lets the provider
// goroutine and the streaming handler drain to completion (LIFO with
// releaseProceed above), so no goroutine is left blocked on a gate and
// httptest's Close does not wait on an outstanding request.
var chunkOnce, completeOnce sync.Once
releaseChunk := func() { chunkOnce.Do(func() { close(sendChunkNow) }) }
releaseComplete := func() { completeOnce.Do(func() { close(sendCompleteNow) }) }
defer releaseComplete()
defer releaseChunk()
providerErr := make(chan error, 1)
go func() {
var inferReq protocol.InferenceRequestMessage
for {
_, data, err := conn.Read(ctx)
if err != nil {
providerErr <- err
return
}
var env struct {
Type string `json:"type"`
}
_ = json.Unmarshal(data, &env)
switch env.Type {
case protocol.TypeAttestationChallenge:
_ = conn.Write(ctx, websocket.MessageText, makeValidChallengeResponse(data, pubKey))
continue
case protocol.TypeInferenceRequest:
_ = json.Unmarshal(data, &inferReq)
default:
continue
}
break
}
gotRequest <- inferReq
<-sendChunkNow
writeEncryptedTestChunk(t, ctx, conn, inferReq, pubKey,
`data: {"id":"chatcmpl-1","choices":[{"delta":{"content":"Hello"}}]}`+"\n\n")
<-sendCompleteNow
sendComplete(ctx, conn, inferReq.RequestID, protocol.UsageInfo{PromptTokens: 5, CompletionTokens: 1})
for {
if _, _, err := conn.Read(ctx); err != nil {
return
}
}
}()

type result struct {
resp *http.Response
err error
}
responses := make(chan result, 1)
go func() {
body := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}],"stream":true}`
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, ts.URL+"/v1/chat/completions", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer test-key")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
responses <- result{resp, err}
}()

select {
case <-gotRequest:
case err := <-providerErr:
t.Fatalf("provider read: %v", err)
case <-time.After(10 * time.Second):
t.Fatal("provider never received the inference request")
}

// The dispatch goroutine handed the frame off and is parked at the seam,
// immediately before the serving-slot latch.
select {
case <-reachedLatch:
case <-time.After(10 * time.Second):
t.Fatal("dispatch goroutine never reached the serving-slot latch seam")
}

// Make the provider's first content chunk available before the latch runs
// so nothing but the latch itself can gate the first byte.
releaseChunk()

// Hold the registry write lock, THEN let the latch run under it. A
// registry read lock inside the latch (the pre-fix path) would now block.
release := reg.HoldWriteLockForTest()
released := false
defer func() {
if !released {
release()
}
}()
releaseProceed()

var resp *http.Response
select {
case r := <-responses:
if r.err != nil {
t.Fatalf("request: %v", r.err)
}
resp = r.resp
case <-time.After(2 * time.Second):
t.Fatal("response headers did not reach the client within 2 s while the registry write lock was held (serving-slot latch took the registry read lock)")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d", resp.StatusCode)
}

firstBytes := make(chan string, 1)
go func() {
buf := make([]byte, 4096)
n, _ := resp.Body.Read(buf)
firstBytes <- string(buf[:n])
}()
select {
case first := <-firstBytes:
if !strings.Contains(first, "Hello") {
t.Fatalf("first bytes = %q, want the provider's content", first)
}
case <-time.After(2 * time.Second):
t.Fatal("first chunk did not reach the client within 2 s while the registry write lock was held")
}

release()
released = true
releaseComplete()

deadline := time.Now().Add(5 * time.Second)
buf := make([]byte, 4096)
var rest strings.Builder
for time.Now().Before(deadline) {
n, err := resp.Body.Read(buf)
rest.Write(buf[:n])
if err != nil {
break
}
if strings.Contains(rest.String(), "[DONE]") {
break
}
}
if !strings.Contains(rest.String(), "[DONE]") {
t.Fatalf("stream did not finish after the lock was released: %q", rest.String())
}
}
46 changes: 20 additions & 26 deletions coordinator/api/kv_backend_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,39 +191,33 @@ func usableMetricSample(v float64) bool {
// the half of Gate G5 that catches a paged regression — would all land in
// kv_backend:unknown.
func (d *dispatchState) noteServingSlot() {
d.noteServingSlotFor(d.pr)
d.noteServingSlotFor(d.provider, d.pr)
}

// noteServingSlotFor re-latches the attribution to an explicit pending request.
// The speculative race paths need this: the backup is dispatched by
// dispatchOneProvider (not the noteServingSlot choke point), so once the
// PRIMARY has failed and the backup becomes the racer of record — or wins the
// race outright — the latch must follow it. Otherwise a backup failure that
// turns terminal after the race helpers clear d.pr would book under the
// PRIMARY's kv_backend tag, misattributing exactly the 5xx/timeout population
// Gate G5 segments per backend in a mixed-backend fleet. The invariant the
// re-latch sites maintain: the latch always names the slot whose failure would
// be the terminal one — the last slot still racing.
//
// EXCEPTION — a latched terminal verdict freezes the ordinary latch. This
// includes deterministic client/unservable verdicts and a genuine fault
// snapshot. Re-latching to a later neutral racer would book the controlling
// terminal under the wrong backend. Genuine faults carry their own immutable
// dispatchSlotAttribution and may replace one another atomically. A backup that
// goes on to WIN is unaffected: commit-path reads go through the live d.pr (see
// kvBackendAttribution), not the terminal snapshot.
func (d *dispatchState) noteServingSlotFor(pr *registry.PendingRequest) {
// noteServingSlotFor follows the request's retained provider, including explicit
// backup promotion, without acquiring the global registry lock before first byte.
// Missing or mismatched providers resolve to unknown rather than another slot.
// A terminal verdict freezes the latch; live winners resolve independently.
func (d *dispatchState) noteServingSlotFor(provider *registry.Provider, pr *registry.PendingRequest) {
if pr == nil || pr.ProviderID == "" {
return
}
if d.attributionLatchFrozen() {
return
}
d.servedKVSlot = dispatchSlotAttribution{
providerID: pr.ProviderID,
model: pr.Model,
backend: d.s.kvBackendAttribution(pr.ProviderID, pr.Model),
if provider != nil && provider.ID != pr.ProviderID {
provider = nil
}
d.servedKVSlot = d.providerSlotAttribution(provider, pr.Model)
}

// liveSlotBackend resolves a live winner from its matching retained provider.
// It must not acquire the global registry lock before the committed response.
func (d *dispatchState) liveSlotBackend(pr *registry.PendingRequest) kvBackendAttribution {
if pr == nil || d.provider == nil || d.provider.ID != pr.ProviderID {
return newUnknownKVBackendAttribution()
}
return d.s.providerKVBackendAttribution(d.provider, pr.Model)
}

// attributionLatchFrozen reports whether a terminal verdict has latched — from
Expand Down Expand Up @@ -269,13 +263,13 @@ func (d *dispatchState) kvBackendAttribution() kvBackendAttribution {
// A sticky speculative loser must not contaminate a survivor that
// produces content. Live content always names its own serving slot;
// the terminal snapshot is consulted only after no live winner remains.
return d.s.kvBackendAttribution(pr.ProviderID, pr.Model)
return d.liveSlotBackend(pr)
}
if pr.ProviderID == d.servedKVSlot.providerID &&
pr.Model == d.servedKVSlot.model {
return d.servedKVSlot.backend
}
att := d.s.kvBackendAttribution(pr.ProviderID, pr.Model)
att := d.liveSlotBackend(pr)
if !d.attributionLatchFrozen() {
d.servedKVSlot = dispatchSlotAttribution{
providerID: pr.ProviderID,
Expand Down
Loading
Loading