From 9fadac3bf465b20c0a4338866dedc20e25f17fd6 Mon Sep 17 00:00:00 2001 From: Numinous Forge Date: Sun, 6 Sep 2026 00:30:51 +0000 Subject: [PATCH] Forge task 30589095b35cf00ef20dee1214ba0e27 Verified tree: 73959842c03bd84c15a1fd52e99695888909e72a Policy: f6b77f17eafcfc1feefc4567319da0e564d02ed90cc71129956ec97444f4781d --- CHANGELOG.md | 4 + coordinator/api/dispatch.go | 12 +- .../api/dispatch_speculative_outcome_test.go | 20 +- .../api/first_byte_serving_slot_lock_test.go | 210 ++++++++++++++ coordinator/api/kv_backend_metrics.go | 46 ++-- coordinator/api/kv_backend_metrics_test.go | 18 +- coordinator/api/server.go | 1 + .../api/serving_slot_lock_helpers_test.go | 257 ++++++++++++++++++ 8 files changed, 522 insertions(+), 46 deletions(-) create mode 100644 coordinator/api/first_byte_serving_slot_lock_test.go create mode 100644 coordinator/api/serving_slot_lock_helpers_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bce30f870..a4c87dd94b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/coordinator/api/dispatch.go b/coordinator/api/dispatch.go index 175dbc712d..c87ab74191 100644 --- a/coordinator/api/dispatch.go +++ b/coordinator/api/dispatch.go @@ -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). @@ -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 { diff --git a/coordinator/api/dispatch_speculative_outcome_test.go b/coordinator/api/dispatch_speculative_outcome_test.go index 7adeaa97ec..d5d1e68bb3 100644 --- a/coordinator/api/dispatch_speculative_outcome_test.go +++ b/coordinator/api/dispatch_speculative_outcome_test.go @@ -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) @@ -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 @@ -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) } @@ -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", @@ -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) } diff --git a/coordinator/api/first_byte_serving_slot_lock_test.go b/coordinator/api/first_byte_serving_slot_lock_test.go new file mode 100644 index 0000000000..c4b75fb2ca --- /dev/null +++ b/coordinator/api/first_byte_serving_slot_lock_test.go @@ -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()) + } +} diff --git a/coordinator/api/kv_backend_metrics.go b/coordinator/api/kv_backend_metrics.go index 3b64bb1127..e5b24602dd 100644 --- a/coordinator/api/kv_backend_metrics.go +++ b/coordinator/api/kv_backend_metrics.go @@ -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 @@ -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, diff --git a/coordinator/api/kv_backend_metrics_test.go b/coordinator/api/kv_backend_metrics_test.go index b7cb612836..c16db887c9 100644 --- a/coordinator/api/kv_backend_metrics_test.go +++ b/coordinator/api/kv_backend_metrics_test.go @@ -269,9 +269,10 @@ func TestRequestOutcomeSegmentsByServingSlotBackend(t *testing.T) { for _, row := range fleet { p := registerHeartbeatedProvider(t, srv, row.providerID, row.model, row.backend) d := &dispatchState{ - s: srv, - model: row.model, - pr: ®istry.PendingRequest{RequestID: "req-" + row.providerID, ProviderID: p.ID, Model: row.model}, + s: srv, + model: row.model, + provider: p, + pr: ®istry.PendingRequest{RequestID: "req-" + row.providerID, ProviderID: p.ID, Model: row.model}, } d.noteServingSlot() // Every failover path clears these before the exhaustion ladder runs. @@ -349,16 +350,19 @@ func TestDispatchKVBackendTagFollowsTheServingSlot(t *testing.T) { t.Fatalf("before dispatch = %q, want %q", got, registry.KVBackendUnknown) } - d.pr = ®istry.PendingRequest{RequestID: "req-latch", ProviderID: primary.ID, Model: model} + // d.provider always accompanies d.pr in production (they are assigned + // together at every dispatch/promotion site), and the serving-slot latch now + // resolves the backend from the held provider rather than the registry. + d.provider, d.pr = primary, ®istry.PendingRequest{RequestID: "req-latch", ProviderID: primary.ID, Model: model} d.noteServingSlot() - d.pr = nil + d.provider, d.pr = nil, nil if got := d.kvBackendAttribution().Backend; got != registry.KVBackendPaged { t.Errorf("after failover cleared d.pr = %q, want %q (the latch is what keeps a crashed "+ "paged slot's 5xx attributable)", got, registry.KVBackendPaged) } - // Speculative backup takes over: the live pending request wins. - d.pr = ®istry.PendingRequest{RequestID: "req-latch-backup", ProviderID: backup.ID, Model: model} + // Speculative backup takes over: the live pending request (and its provider) wins. + d.provider, d.pr = backup, ®istry.PendingRequest{RequestID: "req-latch-backup", ProviderID: backup.ID, Model: model} if got := d.kvBackendAttribution().Backend; got != registry.KVBackendContiguous { t.Errorf("after a backup win = %q, want %q", got, registry.KVBackendContiguous) } diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 407c382e3a..22bebe65ca 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -229,6 +229,7 @@ type Server struct { codeResumeSender func(string, protocol.CodeAttestationResumeChallenge) error codeResumeBeforeIdentityCheck func() // test seam between cache match and challenge record codeResumeFallbackBeforeAPNs func() // test seam after nonce consume, before ctx recheck + beforeServingSlotAttribution func() // test seam after provider handoff, before serving-slot KV latch (first-byte lock regression) codeAttestThrottle *codeAttestThrottle // per-device APNs push budget + reuse cache (v0.6.0) trustReuseCache *trustReuseCache // per-device trust-reuse cache: skip a fleet-wide live MDM herd on restart (DAR-326) trustReuseJournal hardUntrustJournal diff --git a/coordinator/api/serving_slot_lock_helpers_test.go b/coordinator/api/serving_slot_lock_helpers_test.go new file mode 100644 index 0000000000..a261df9c73 --- /dev/null +++ b/coordinator/api/serving_slot_lock_helpers_test.go @@ -0,0 +1,257 @@ +package api + +import ( + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" +) + +// Helper-level regressions for the first-byte serving-slot lock dependency. +// +// noteServingSlotFor / dispatchState.kvBackendAttribution run between the +// inference-frame handoff and the first client byte. Before the fix they +// resolved the slot's KV backend through Registry.SlotKVBackendTags -> +// Registry.GetProvider, which takes the registry READ lock, so a concurrent +// registry WRITE lock (a heartbeat/registration burst) stalled the first byte. +// The fix resolves from the *registry.Provider the dispatch goroutine already +// holds (Provider.SlotKVBackendTags, provider lock only). These tests hold the +// registry write lock and assert each helper completes anyway — with the old +// registry-backed methods each blocks for the whole lock hold. + +// seedKVBackend registers a provider and drives one heartbeat so the slot has a +// concrete kv_backend observation (paged/contiguous), returning the provider. +func seedKVBackend(t *testing.T, reg *registry.Registry, id, model, backend string) *registry.Provider { + t.Helper() + p := reg.Register(id, nil, &protocol.RegisterMessage{ + Models: []protocol.ModelInfo{{ID: model, ModelType: "chat", Quantization: "4bit"}}, + }) + kb := backend + reg.Heartbeat(id, &protocol.HeartbeatMessage{ + Type: protocol.TypeHeartbeat, + Status: "serving", + BackendCapacity: &protocol.BackendCapacity{ + TotalMemoryGB: 64, + Slots: []protocol.BackendSlotCapacity{ + {Model: model, State: "running", KVBackend: &kb}, + }, + }, + }) + return p +} + +// runWhileWriteLockHeld runs fn on a goroutine while the registry write lock is +// held and asserts it finishes inside a bounded window. A helper that reaches +// the registry read lock would block here for the whole hold; the bounded +// channel wait makes that a deterministic failure rather than a hang, and the +// deferred release never leaves a goroutine or the registry wedged. +func runWhileWriteLockHeld(t *testing.T, reg *registry.Registry, fn func()) { + t.Helper() + release := reg.HoldWriteLockForTest() + done := make(chan struct{}) + go func() { + fn() + close(done) + }() + select { + case <-done: + release() + case <-time.After(time.Second): + // Do not leave the blocked goroutine wedged behind the lock: releasing + // lets it drain before the test exits. + release() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("helper remained blocked after the registry lock was released") + } + t.Fatal("helper blocked on the registry lock between handoff and first byte") + } +} + +// TestNoteServingSlotForPrimaryNoRegistryLock covers the primary handoff choke +// point (dispatchPrimary -> noteServingSlotFor(d.provider, d.pr)). +func TestNoteServingSlotForPrimaryNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + + const model = "primary-model" + provider := seedKVBackend(t, reg, "primary-provider", model, registry.KVBackendPaged) + pr := ®istry.PendingRequest{RequestID: "r1", Model: model, ProviderID: provider.ID} + d := &dispatchState{s: srv, model: model, provider: provider, pr: pr} + + runWhileWriteLockHeld(t, reg, func() { d.noteServingSlotFor(provider, pr) }) + + if d.servedKVSlot.providerID != provider.ID { + t.Fatalf("latched providerID = %q, want %q", d.servedKVSlot.providerID, provider.ID) + } + if d.servedKVSlot.backend.Backend != registry.KVBackendPaged { + t.Fatalf("latched backend = %q, want paged", d.servedKVSlot.backend.Backend) + } +} + +// TestNoteServingSlotForBackupPointerNoRegistryLock covers the backup pointer +// path (racePrimaryFailedWaitBackup -> noteServingSlotFor(backupProvider, +// backupPR)): the latch must re-point to the backup's slot, from the backup +// provider already in hand. +func TestNoteServingSlotForBackupPointerNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + + const model = "backup-model" + primary := seedKVBackend(t, reg, "backup-primary", model, registry.KVBackendPaged) + backup := seedKVBackend(t, reg, "backup-secondary", model, registry.KVBackendContiguous) + + primaryPR := ®istry.PendingRequest{RequestID: "rp", Model: model, ProviderID: primary.ID} + d := &dispatchState{s: srv, model: model, provider: primary, pr: primaryPR} + // Primary latched first. + d.noteServingSlotFor(primary, primaryPR) + + backupPR := ®istry.PendingRequest{RequestID: "rb", Model: model, ProviderID: backup.ID} + runWhileWriteLockHeld(t, reg, func() { d.noteServingSlotFor(backup, backupPR) }) + + if d.servedKVSlot.providerID != backup.ID { + t.Fatalf("latched providerID = %q, want backup %q", d.servedKVSlot.providerID, backup.ID) + } + if d.servedKVSlot.backend.Backend != registry.KVBackendContiguous { + t.Fatalf("latched backend = %q, want contiguous", d.servedKVSlot.backend.Backend) + } +} + +// TestKVBackendAttributionPromotedLatchMismatchNoRegistryLock covers the +// promoted-winner / latch-mismatch branch of dispatchState.kvBackendAttribution: +// the live d.pr names a provider the latch has not caught up with (a backup +// promoted outside the noteServingSlot choke point). It must resolve — and +// re-latch — to the promoted provider without the registry lock. +func TestKVBackendAttributionPromotedLatchMismatchNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + + const model = "promoted-model" + primary := seedKVBackend(t, reg, "promoted-primary", model, registry.KVBackendPaged) + winner := seedKVBackend(t, reg, "promoted-winner", model, registry.KVBackendContiguous) + + primaryPR := ®istry.PendingRequest{RequestID: "rp", Model: model, ProviderID: primary.ID} + d := &dispatchState{s: srv, model: model, provider: primary, pr: primaryPR} + d.noteServingSlotFor(primary, primaryPR) // latch names the primary + + // Promotion: d.provider/d.pr now point at the winner, latch still on primary. + winnerPR := ®istry.PendingRequest{RequestID: "rw", Model: model, ProviderID: winner.ID} + d.provider = winner + d.pr = winnerPR + + var got kvBackendAttribution + runWhileWriteLockHeld(t, reg, func() { got = d.kvBackendAttribution() }) + + if got.Backend != registry.KVBackendContiguous { + t.Fatalf("attribution backend = %q, want contiguous (the promoted winner)", got.Backend) + } + if d.servedKVSlot.providerID != winner.ID { + t.Fatalf("latch re-pointed to %q, want winner %q", d.servedKVSlot.providerID, winner.ID) + } +} + +// TestKVBackendAttributionGenuineFaultLiveWinnerNoRegistryLock covers the +// genuine-fault / live-winner branch: a sticky genuine fault latched from an +// earlier attempt, but a survivor is producing content. Live content names its +// own serving slot (d.provider), resolved without the registry lock, and the +// frozen fault snapshot is not consulted while a live winner remains. +func TestKVBackendAttributionGenuineFaultLiveWinnerNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + + const model = "fault-model" + faulted := seedKVBackend(t, reg, "fault-faulted", model, registry.KVBackendPaged) + winner := seedKVBackend(t, reg, "fault-winner", model, registry.KVBackendContiguous) + + // A genuine fault from the faulted provider froze the latch/snapshot. + d := &dispatchState{s: srv, model: model} + d.genuineFault = &dispatchTerminalFailure{ + attribution: d.providerSlotAttribution(faulted, model), + } + // A survivor is now the live winner producing content. + winnerPR := ®istry.PendingRequest{RequestID: "rw", Model: model, ProviderID: winner.ID} + d.provider = winner + d.pr = winnerPR + + var got kvBackendAttribution + runWhileWriteLockHeld(t, reg, func() { got = d.kvBackendAttribution() }) + + if got.Backend != registry.KVBackendContiguous { + t.Fatalf("live-winner attribution backend = %q, want contiguous", got.Backend) + } +} + +// TestFrozenTerminalAttributionSurvivesReLatchNoRegistryLock covers frozen +// terminal attribution: once a genuine fault has latched, a later neutral +// re-latch attempt must NOT move the attribution to a different provider, and +// the exhausted path must return the frozen fault's own slot snapshot. Both run +// under the write lock without touching the registry. +func TestFrozenTerminalAttributionSurvivesReLatchNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + + const model = "frozen-model" + faulted := seedKVBackend(t, reg, "frozen-faulted", model, registry.KVBackendPaged) + other := seedKVBackend(t, reg, "frozen-other", model, registry.KVBackendContiguous) + + d := &dispatchState{s: srv, model: model} + faultAttr := d.providerSlotAttribution(faulted, model) + failure := dispatchTerminalFailure{attribution: faultAttr} + d.genuineFault = &failure + d.servedKVSlot = faultAttr // frozen at the fault's slot + + // A neutral re-latch to another provider must be a no-op (freeze rule), and + // the exhausted attribution must still name the fault's slot. Both under lock. + otherPR := ®istry.PendingRequest{RequestID: "ro", Model: model, ProviderID: other.ID} + var exhausted kvBackendAttribution + runWhileWriteLockHeld(t, reg, func() { + d.noteServingSlotFor(other, otherPR) + exhausted = d.exhaustedKVBackendAttribution(failure, true) + }) + + if d.servedKVSlot.providerID != faulted.ID { + t.Fatalf("frozen latch moved to %q, want faulted %q", d.servedKVSlot.providerID, faulted.ID) + } + if exhausted.Backend != registry.KVBackendPaged { + t.Fatalf("frozen exhausted attribution = %q, want paged (the fault's slot)", exhausted.Backend) + } +} + +func TestServingSlotMissingOrMismatchedProviderNoRegistryLock(t *testing.T) { + srv, reg, _, ts := setupTestServer(t) + defer ts.Close() + const model = "pointer-match-model" + actual := seedKVBackend(t, reg, "pointer-actual", model, registry.KVBackendContiguous) + wrong := seedKVBackend(t, reg, "pointer-wrong", model, registry.KVBackendPaged) + pr := ®istry.PendingRequest{RequestID: "pointer-request", ProviderID: actual.ID, Model: model} + for _, tc := range []struct { + name string + provider *registry.Provider + }{{"nil", nil}, {"mismatched", wrong}} { + t.Run(tc.name, func(t *testing.T) { + t.Run("latch", func(t *testing.T) { + d := &dispatchState{s: srv, model: model, provider: tc.provider, pr: pr} + runWhileWriteLockHeld(t, reg, func() { d.noteServingSlotFor(tc.provider, pr) }) + if got := d.servedKVSlot.backend; got != newUnknownKVBackendAttribution() { + t.Fatalf("invalid provider latch = %+v, want unknown backend and fallback", got) + } + if d.servedKVSlot.providerID != "" { + t.Fatalf("invalid provider attributed to %q", d.servedKVSlot.providerID) + } + }) + t.Run("live", func(t *testing.T) { + d := &dispatchState{s: srv, model: model, provider: tc.provider, pr: pr} + var got kvBackendAttribution + runWhileWriteLockHeld(t, reg, func() { got = d.kvBackendAttribution() }) + if got != newUnknownKVBackendAttribution() { + t.Fatalf("invalid live provider = %+v, want unknown backend and fallback", got) + } + if d.servedKVSlot.backend != newUnknownKVBackendAttribution() { + t.Fatalf("invalid live provider saved another slot's attribution: %+v", d.servedKVSlot) + } + }) + }) + } +}