-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathdispatch.go
More file actions
3890 lines (3735 loc) · 168 KB
/
Copy pathdispatch.go
File metadata and controls
3890 lines (3735 loc) · 168 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
// Per-request dispatch state machine for the consumer inference path.
//
// This file holds the speculative TTFT-aware dispatch loop that handleChatCompletions
// drives: it picks a provider (or queues), waits for the first CONTENT chunk with a
// speculative backup race, fails over invisibly on provider error/timeout up to
// maxDispatchAttempts, and commits exactly once. It is a PURELY STRUCTURAL extraction
// of what previously lived inline in consumer.go — every select arm, timer Stop/Reset,
// channel-close+ErrorCh grace window, heldChunks cap, liveness extension, speculative
// race (backup dispatch / cancel-loser / skipBackup), refund-exactly-once, breaker
// call, DD metric, and status code is preserved exactly.
//
// Control-flow mapping (former labeled blocks → methods):
//
// for attempt := range maxDispatchAttempts → dispatchState.run (the orchestrator)
// dispatch-primary block (incl. queue path) → dispatchState.dispatchPrimary
// firstChunkWait + speculative race → dispatchState.waitFirstChunk
// noBackupWait → dispatchState.waitNoBackup
// race + sub-waits → dispatchState.runRace
// backupFailedPrimaryWait → dispatchState.raceBackupFailedWaitPrimary
// primaryFailedBackupWait → dispatchState.racePrimaryFailedWaitBackup
// backupFailedWaitPrimary → dispatchState.raceBackupErrWaitPrimary
// acceptedWait → dispatchState.waitAccepted
//
// The former labeled jumps become method returns: `continue dispatch` → outcomeRetry,
// `break`/commit → outcomeCommitted, `break <label>` into the accepted wait →
// outcomeAccepted, `return` (client gone, after refund) → outcomeClientGone, and the
// queue-rejection `writeJSON; return` paths → outcomeResponseWritten. The orchestrator
// switches on the outcome, exactly reproducing the original flow.
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/eigeninference/d-inference/coordinator/internal/e2e"
"github.com/eigeninference/d-inference/coordinator/protocol"
"github.com/eigeninference/d-inference/coordinator/registry"
"github.com/eigeninference/d-inference/coordinator/saferun"
"github.com/eigeninference/d-inference/coordinator/store"
"github.com/google/uuid"
)
// dispatchOutcome is the result of a per-attempt dispatch phase (provider
// selection, first-chunk wait, accepted wait). The orchestrator (dispatchState.run)
// switches on it to reproduce the original loop's continue/break/return flow.
type dispatchOutcome int
const (
// outcomeCommitted: a content chunk (or a clean close) committed the attempt.
// The orchestrator stops the loop and streams the response.
outcomeCommitted dispatchOutcome = iota
// outcomeAccepted: legacy/unstamped preamble liveness earned a bounded
// content wait. AcceptedCh itself never produces this outcome.
outcomeAccepted
// outcomeRetry: the attempt failed (provider error / timeout). Equivalent to
// the original `continue dispatch` — the orchestrator advances to the next attempt.
outcomeRetry
// outcomeFailFast: the loop must stop without a committed provider (e.g.
// model-too-large, or no-provider on a retry attempt). Equivalent to `break`.
outcomeFailFast
// outcomeClientGone: the request context was cancelled; the reservation was
// already refunded and the handler must return with no response body.
outcomeClientGone
// outcomeResponseWritten: a terminal HTTP response was already written
// (queue rejection / queue timeout / queue insufficient funds 402 etc.) and
// the handler must return immediately.
outcomeResponseWritten
// outcomeProceed: provider selection succeeded; the orchestrator continues
// to the first-chunk wait for this attempt.
outcomeProceed
)
type dispatchTerminalFailure struct {
errText string
statusCode int
terminalCause string
deadline bool
attribution dispatchSlotAttribution
}
// dispatchState carries everything the per-request dispatch loop needs. The
// immutable inputs are set once by runDispatch; the mutable fields track the
// in-flight attempt (selected provider, held preamble, commit/accept flags,
// last error for the exhaustion ladder, and the version to steer retries away from).
type dispatchState struct {
s *Server
// ---- immutable inputs (set once) ----
w http.ResponseWriter
r *http.Request
model string
publicModel string
rawBody []byte
consumerKey string
consumerLocation *store.ProviderLocation
reservedMicroUSD int64
serviceReservation bool
estimatedPromptTokens int
requestedMaxTokens int
tokenAdmission registry.TokenAdmission
requiresVision bool
hasTools bool
requiresToolConstraint bool
toolChoiceMode string
toolChoiceName string
parallelToolCalls bool
isResponsesAPI bool
consumerEndpoint string
requestedStopSequences []string
stream bool
metadataDetails bool
policy selfRoutePolicy
allowedProviderSerials []string
cachePlan registry.CachePlan
timing *registry.RequestTiming
profile *registry.RequestProfile
deadline time.Duration
speculativeAt time.Duration
// Deterministic test seams for speculative timer/ingress arbitration.
// Production requests leave both nil.
onSpeculativeDispatch func()
onSpeculativeDeferral func()
// modelMaxContext is the model's context window (0 = unknown), used by
// shouldStopFailover/classifyRejection to tell a fleet-wide context overflow
// apart from a memory-pressured provider's shrunk KV budget when a "batch token
// budget" rejection arrives.
modelMaxContext int
// refundReservation refunds the shared base reservation (the caller's closure).
refundReservation func()
// ---- mutable per-request state ----
provider *registry.Provider
pr *registry.PendingRequest
requestID string
firstChunk string
heldChunks []string
initialError *protocol.InferenceErrorMessage
lastErr string
lastErrCode int
lastErrReason string
// lastErrProviderBudget is the rejecting provider's reported token budget
// (ActiveTokenBudgetMax) for d.model at the time lastErr was set, or 0 when the
// error is not a provider rejection / the provider reported no budget. Captured
// by setLastInferenceError so shouldStopFailover can classify a "batch token
// budget" rejection as deterministic (budget >= context) vs transient
// (budget < context — this node was memory-pressured).
lastErrProviderBudget int64
// lastErrRejectionReason is the typed CapacityRejectionReason from the
// last provider error ("" for legacy providers). classifyRejection
// treats a typed token_budget as AUTHORITATIVE transient: the provider's
// live gate named the shortage, so a deterministic-unservable verdict
// must never be re-derived from the stale heartbeat budget fallback.
lastErrRejectionReason protocol.CapacityRejectionReason
// lastErrTerminalCause is the typed terminal_cause from the last provider
// error ("" for legacy providers). shouldStopFailover trusts a typed
// admission_timeout as transient capacity directly — the provider's engine
// TOLD us it was busy — instead of inferring from error-string substrings
// that the fixed "admission_timeout: …" text would never match.
lastErrTerminalCause string
// lastErrCoordinatorCause is a non-wire marker for coordinator-synthetic
// terminals such as a provider disconnect. A provider cannot set it.
lastErrCoordinatorCause protocol.CoordinatorInferenceErrorCause
// lastErrAttemptUsage is the typed partial usage from the last provider
// error (nil for legacy providers), applied to the failed attempt's route
// row by providerFailedRoutingOutcomeFor so pre-content typed failures on
// the ordinary dispatch path keep their observability data.
lastErrAttemptUsage *protocol.UsageInfo
// genuineFault is request-wide terminal precedence, separate from the
// lastErr* per-attempt scratch used to persist each attempt's route outcome.
// Capacity/lifecycle refusals, deadline refusals, neutral typed causes, and
// deterministic client/model errors never enter this slot.
genuineFault *dispatchTerminalFailure
committed bool
lastFailedVersion string
excludeProviders map[string]struct{}
// capacityRetries counts pre-content TRANSIENT-capacity failovers (this
// node's live KV budget, a full queue, a drain). Bounded by
// maxCapacityClassRetries so a fleet-wide transient cannot storm; a
// DETERMINISTIC-context rejection (prompt > model context) stops on the first
// attempt regardless (see classifyRejection / failoverOutcome).
capacityRetries int
// firstChunkTimeoutRetries counts attempts that ended in a
// coordinator-synthesized first-chunk TIMEOUT (untyped 504 → the
// "first_chunk_timeout" 429 on exhaustion). Bounded by
// maxFirstChunkTimeoutRetries so a slow-provider storm cannot burn a
// fresh fleet scan per attempt across the ladder (the 2026-09-01
// congestion collapse; see the constant). Each counted attempt was on a
// distinct provider — the timed-out provider joins excludeProviders.
firstChunkTimeoutRetries int
// lastFailureDeadline is scoped to the most recent terminal attempt. A
// deadline refusal remains eligible for deadline_unreachable only while no
// later genuine provider fault has replaced it.
lastFailureDeadline bool
// unservable is set when the dispatch loop stops because the request cannot
// be served (deterministic-context rejection, or a transient that exhausted
// maxCapacityClassRetries). The exhausted ladder then emits a single
// uptime-neutral 429 with unservableReason instead of retrying/5xx'ing.
unservable bool
unservableReason string
// terminalClientError is set when a dispatched provider returned a DETERMINISTIC
// client-shape 4xx (400/413/422/415 — invalid tool payload / role / response_format
// / unsupported media). That rejection is identical on every provider (the bad
// request body is forwarded unchanged), so the loop stops immediately and the
// exhausted ladder surfaces terminalClientErrorCode ONCE — instead of failing over
// up to maxDispatchAttempts (the prod 29×/max-63 storm). String-blind: the status
// code is ground truth; the human-readable provider string drifts across versions.
terminalClientError bool
terminalClientErrorCode int
// terminalClientErrorReason, when non-empty, overrides the exhausted
// ladder's rejection-ledger reason_code for a latched terminal client
// error ("template_render_failed" for the jinja_* stop — distinguishable
// from the StatusCode-driven stop's generic "client_error").
terminalClientErrorReason string
// terminalClientErrorMessage, when non-empty, overrides the surfaced
// error-body message (the jinja_* stop surfaces the curated
// model_capability text, not the provider's raw template backtrace).
terminalClientErrorMessage string
// servedKVSlot latches the KV-cache backend attribution of the SLOT the
// most recent attempt was dispatched to (v0.8.0 paged rollout, Gate G5) —
// the resolved kind AND whether that kind was a silent degrade. It is NOT
// per-attempt scratch: the failure tails run after a retry has cleared
// d.provider/d.pr, and a 5xx from a paged slot that just fell over is
// exactly the sample the rollout dashboard must not lose. Zero value until
// the request reaches a slot, which tags unknown on both dimensions.
servedKVSlot dispatchSlotAttribution
// ---- Routing v2 wave-2 plan/hedge state ----
// plan is the bounded dispatch plan retained by the FIRST full-scan
// reservation (registry.ReserveProviderWithPlan): up to eight provisional
// alternates from the same scan that chose the primary. Retries and the
// speculative backup consume it (ReserveNextFromPlan, then one refresh)
// before any rescan. nil for queue-path and no-reservation flows —
// selection behavior is then exactly legacy.
plan *registry.DispatchPlan
// planRefreshUsed latches the request's single RefreshDispatchPlan across
// BOTH consumers (failover retries and the speculative backup). The plan
// object enforces once-per-plan-chain; this enforces once-per-request.
planRefreshUsed bool
// probesLaunched: the one parallel capacity-probe round has started
// (maybeProbePlanCandidates). One round per request, launched only after
// the primary frame handoff so probes never add primary latency.
probesLaunched bool
// hedgeAdvanceCh delivers the probe round's refined ABSOLUTE speculative
// launch instant (hedgeLaunchAt) when a confirmed backup's quoted q90
// proves the 50% point too late to be useful. Buffered 1, written at most
// once by the quote collector; nil until probes launch. waitFirstChunk
// consumes at most one value under only-earlier / only-once /
// never-after-fire guards; without a value the 50% default stands.
hedgeAdvanceCh chan time.Time
// hedgeGovernorVerdict is the governor's decision for this request's
// speculative launch ("" = the governor never ran: no speculative point
// reached, or an owner-served prefer request). Telemetry/log only.
hedgeGovernorVerdict string
// providerDispatches counts inference frames actually handed to a
// provider — primary, queued, plan-retry, and speculative-backup sends
// alike, incremented only after the writer confirms final authorization
// and socket handoff. Client-visible exhaustion messages report this
// machine count; route rows keep the loop index d.attempt untouched.
providerDispatches int
// visionImageCount is the number of media parts in the request (0 for
// text-only), carried into capacity probes as count-only shape metadata.
visionImageCount int
// lastErrFeasibleAfterMS is the enriched rejection's forecast of when a
// request of this shape could next be admitted (0 = absent/legacy),
// captured by setLastInferenceError and surfaced into the exhaustion
// 429's Retry-After.
lastErrFeasibleAfterMS int64
// ---- per-attempt scratch (reset each attempt) ----
attempt int
preambleLiveness bool
// dispatchErr captures the non-empty error string from dispatchOneProvider
// for this attempt so outcome telemetry can classify the routing decision.
dispatchErr string
// dispatchErrCode captures the HTTP status code associated with dispatchErr.
dispatchErrCode int
// providerBodyTooLargeErr preserves a protocol-0 cache-buster overflow
// while failover tries providers whose newer protocol does not add it.
providerBodyTooLargeErr string
providerBodyTooLargeBytes int
minPrefixCacheProtocol int
}
// traits builds the routing traits for the current attempt, steering away from
// the most recently failed provider's binary version.
func (d *dispatchState) traits() registry.RequestTraits {
return registry.RequestTraits{
HasTools: d.hasTools,
RequiresToolConstraint: d.requiresToolConstraint,
ToolChoiceMode: d.toolChoiceMode,
ToolChoiceName: d.toolChoiceName,
ParallelToolCalls: d.parallelToolCalls,
AvoidVersion: d.lastFailedVersion,
MinPrefixCacheProtocol: d.minPrefixCacheProtocol,
}
}
func (d *dispatchState) configurePending(pr *registry.PendingRequest) {
if pr == nil {
return
}
stampModelTokenReservation(pr, modelTokenReservation(d.r))
pr.ConsumerEndpoint = d.consumerEndpoint
pr.RequestedStopSequences = append(
pr.RequestedStopSequences[:0], d.requestedStopSequences...)
pr.MetadataDetails = d.metadataDetails
}
func (d *dispatchState) excludedProviderIDs() []string {
ids := make([]string, 0, len(d.excludeProviders))
for id := range d.excludeProviders {
ids = append(ids, id)
}
return ids
}
func (d *dispatchState) shouldQueueCompatibleProvider(decision registry.RoutingDecision) bool {
return d.providerBodyTooLargeErr != "" &&
d.lastErrCode == http.StatusRequestEntityTooLarge &&
decision.CapacityRejections > 0
}
// envTTFTTerminalReject is the kill switch for the terminal TTFT-rejection fix.
// A reservation that fails because every candidate exceeds the TTFT ceiling
// (errTTFTTooSlow) is DETERMINISTIC: it is computed from the same fleet-wide
// estimate on every scan, so re-running it within the same request cannot
// succeed. Default true: the dispatch ladder stops on the FIRST such rejection
// at ANY attempt and returns the same 429 the attempt-0 path always produced
// (prod: mid-ladder rejections previously looped to maxDispatchAttempts,
// re-running the doomed scan ~63x per request and writing a ttft_429 route row
// each time — 28% of inference_routes). Set =false to restore the legacy
// attempt-0-only fast path. Read live (not a Server field) following the
// cold_dispatch.go flag pattern, so it stays confined to this file and is
// overridable in tests via t.Setenv.
const envTTFTTerminalReject = "EIGENINFERENCE_TTFT_TERMINAL_REJECT"
// ttftTerminalRejectEnabled reports whether a TTFT-too-slow reservation
// rejection terminates the dispatch ladder on any attempt. Default true.
func ttftTerminalRejectEnabled() bool {
return envEnabledDefaultTrue(envTTFTTerminalReject)
}
// envJinjaTerminalReject is the kill switch for the deterministic
// template-render rejection stop (E4, 2026-07-15 platform errors deep dive).
// A provider error_reason of jinja_channel_tags / jinja_null_bridge /
// jinja_template means the model's chat template could not render the
// request's tool schemas or message history — the same body renders the same
// way on every provider, so failing over is pure waste (prod: 1.57 dispatch
// rows per jinja request, observed up to 17 attempts, 0% eventual success).
// Default true: the ladder stops on the FIRST jinja_* rejection at any
// attempt and surfaces one 422 model_capability invalid_request_error. Set
// =false to restore the legacy fail-over-on-500 behavior. Read live (not a
// Server field) following the envTTFTTerminalReject pattern, so it stays
// confined to this file and is overridable in tests via t.Setenv.
const envJinjaTerminalReject = "EIGENINFERENCE_JINJA_TERMINAL_REJECT"
// jinjaTerminalRejectEnabled reports whether a jinja_* provider rejection
// terminates the dispatch ladder. Default true.
func jinjaTerminalRejectEnabled() bool {
return envEnabledDefaultTrue(envJinjaTerminalReject)
}
// jinjaTerminalRejectMessage is the OpenAI-style error body surfaced for a
// latched template-render failure — a curated model_capability message
// instead of the provider's raw Jinja backtrace (which names filters and
// template internals no API consumer can act on).
const jinjaTerminalRejectMessage = "the request's tool schemas or message history cannot be rendered by this model's chat template; simplify the tool parameter schemas or message structure, or use a different model"
// queueMaxTTFTMs returns the TTFT ceiling for queued requests. Public routes
// inherit the prompt-scaled admission threshold; self-route / prefer-owner paths
// are not subject to the public SLA ceiling.
//
// When hardReject is false (the default soft gate), a zero ceiling is returned
// so the scheduler's enforceTTFT path is disabled: candidates over the estimated
// deadline are no longer dropped (and no errTTFTTooSlow is produced). The router
// still ranks by cost (which is TTFT-weighted), so the fastest provider wins, but
// a request is served on the best-available provider instead of being rejected
// on a pessimistic prefill estimate.
func queueMaxTTFTMs(policy selfRoutePolicy, deadline time.Duration, hardReject bool) float64 {
if policy.enabled || policy.prefer {
return 0
}
if !hardReject {
return 0
}
return float64(deadline.Milliseconds())
}
// routingOutcomeKey returns a stable requestID + attempt identifier used for
// telemetry updates. It prefers the explicit dispatch requestID, falling back
// to the pending request's ID when the dispatch requestID has not been set yet.
func (d *dispatchState) routingOutcomeKey() string {
if d.requestID != "" {
return d.requestID
}
if d.pr != nil {
return d.pr.RequestID
}
return ""
}
// recordRoutingDecision writes a best-effort snapshot of the scheduler decision
// for the current attempt. It never blocks inference.
func (d *dispatchState) recordRoutingDecision(decision registry.RoutingDecision, dispatchErr, outcomeOverride string) {
d.recordRoutingDecisionFor(d.provider, d.pr, d.routingOutcomeKey(), d.attempt, decision, dispatchErr, outcomeOverride)
}
func (d *dispatchState) recordRoutingDecisionFor(provider *registry.Provider, pr *registry.PendingRequest, requestID string, attempt int, decision registry.RoutingDecision, dispatchErr, outcomeOverride string) {
s := d.s
if requestID == "" && pr != nil {
requestID = pr.RequestID
}
providerID := ""
if provider != nil {
providerID = provider.ID
} else if decision.ProviderID != "" {
providerID = decision.ProviderID
}
outcome := outcomeOverride
if outcome == "" {
switch {
case providerID != "":
outcome = "selected"
case dispatchErr == errModelTooLarge:
outcome = "model_too_large"
case dispatchErr == errTTFTTooSlow:
outcome = "ttft_429"
case dispatchErr == "no provider available":
outcome = "no_provider"
default:
outcome = "error"
}
}
keyID := ""
if pr != nil {
keyID = pr.KeyID
}
// Scans per attempt (rescans included). Plan-based retries reuse the
// previous scan and report zero, which is not emitted.
if decision.ScanCount > 0 {
s.ddCount("routing.scans", int64(decision.ScanCount), []string{"model:" + d.model, "outcome:" + outcome})
}
record := &store.InferenceRouteRecord{
RequestID: requestID,
Attempt: attempt,
ProviderID: providerID,
Model: d.model,
PublicModel: d.publicModel,
ConsumerKeyHash: store.HashKey(d.consumerKey),
KeyID: keyID,
Outcome: outcome,
CostMs: decision.CostMs,
StateMs: decision.StateMs,
QueueMs: decision.QueueMs,
PendingMs: decision.PendingMs,
BacklogMs: decision.BacklogMs,
ThisReqMs: decision.ThisReqMs,
HealthMs: decision.HealthMs,
TTFTMs: decision.TTFTMs,
BestTTFTMs: decision.BestTTFTMs,
EffectiveQueue: decision.EffectiveQueue,
CandidateCount: decision.CandidateCount,
CapacityRejections: decision.CapacityRejections,
ModelTooLargeRejections: decision.ModelTooLargeRejections,
VisionRejections: decision.VisionRejections,
TTFTRejections: decision.TTFTRejections,
EffectiveTPS: decision.EffectiveTPS,
StaticTPS: decision.StaticTPS,
EstimatedPromptTokens: d.estimatedPromptTokens,
RequestedMaxTokens: d.requestedMaxTokens,
RequiresVision: d.requiresVision,
HasTools: d.hasTools,
SelfRouteOnly: d.policy.enabled,
PreferOwner: d.policy.prefer,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if provider != nil {
provider.Mu().Lock()
record.ProviderStatus = string(provider.Status)
record.ProviderTrustLevel = string(provider.TrustLevel)
record.ProviderVersion = provider.Version
record.HardwareChip = provider.Hardware.ChipName
record.HardwareChipFamily = provider.Hardware.ChipFamily
record.HardwareTier = provider.Hardware.ChipTier
record.MemoryGB = provider.Hardware.MemoryGB
record.GPUCores = provider.Hardware.GPUCores
record.CPUCores = provider.Hardware.CPUCores.Total
record.SystemMemoryPressure = provider.SystemMetrics.MemoryPressure
record.SystemCPUUsage = provider.SystemMetrics.CPUUsage
record.SystemThermalState = provider.SystemMetrics.ThermalState
if cap := provider.BackendCapacity; cap != nil {
record.GPUMemoryActiveGB = cap.GPUMemoryActiveGB
record.GPUMemoryPeakGB = cap.GPUMemoryPeakGB
record.GPUMemoryCacheGB = cap.GPUMemoryCacheGB
for _, slot := range cap.Slots {
if slot.Model == d.model {
record.SlotState = slot.State
record.BackendRunning = slot.NumRunning
record.BackendWaiting = slot.NumWaiting
record.ActiveTokenBudgetUsed = slot.ActiveTokenBudgetUsed
record.ActiveTokenBudgetMax = slot.ActiveTokenBudgetMax
record.QueuedTokenBudget = slot.QueuedTokenBudget
break
}
}
}
provider.Mu().Unlock()
}
// Phase-0 shadow TTFT admission/spread metrics. No-op unless the request was
// evaluated (admission mode != off AND a provider was selected). Emitted on
// the synchronous path (cheap counter incr), not inside the async store write.
s.emitTTFTShadowMetrics(d.model, decision)
if decision.CacheDiscountMs > 0 {
s.ddIncr("routing.cache_evaluation", []string{
"mode:active",
"tier:" + lowCardinalityCacheTier(decision.CacheTier),
})
}
// Off the request path: the batching sink coalesces this snapshot with its
// neighbours into one multi-row write (route_telemetry_submit.go).
s.submitRouteRecord(record)
}
// timingMsBetween returns the elapsed milliseconds between two request-lifecycle
// timestamps, or 0 when either endpoint is unset or the interval is non-positive.
// It keeps the latency-decomposition fields defensive: never a negative value,
// never a panic on a zero timestamp.
func timingMsBetween(a, b time.Time) float64 {
if a.IsZero() || b.IsZero() || !b.After(a) {
return 0
}
return float64(b.Sub(a).Milliseconds())
}
// applyTimingDecomposition fills the coordinator-side latency-decomposition
// fields (ParseMs..DispatchMs) on a routing outcome from the per-request timing
// stamps. Each segment is populated only when both of its endpoints are set
// (timingMsBetween returns 0 otherwise), so a partially-instrumented request
// never records a negative or bogus segment. QueueWaitMs is 0 for requests that
// were dispatched without queueing (QueuedAt unset).
//
// firstChunk is passed in (not read from t.FirstChunkAt) so this can also be
// called from the provider read-loop goroutine (handleComplete) with a value
// obtained via PendingRequest.FirstChunkAtSafe; t.FirstChunkAt itself must only
// be read directly by the dispatch goroutine that owns the request.
func applyTimingDecomposition(out *store.InferenceRouteOutcome, t *registry.RequestTiming, firstChunk time.Time) {
if out == nil || t == nil {
return
}
out.ParseMs = timingMsBetween(t.ReceivedAt, t.ParsedAt)
out.ReserveMs = timingMsBetween(t.ParsedAt, t.ReservedAt)
// Remote-media fetch (when it happened) sits between ReservedAt and
// RoutedAt; anchor the route segment past it so a multi-second download
// doesn't masquerade as routing latency. The fetch duration itself is
// reported via the X-Timing header and DD histogram (no outcome column).
routeAnchor := t.ReservedAt
if !t.MediaFetchedAt.IsZero() {
routeAnchor = t.MediaFetchedAt
}
out.RouteMs = timingMsBetween(routeAnchor, t.RoutedAt)
out.EncryptMs = timingMsBetween(t.RoutedAt, t.EncryptedAt)
out.QueueWaitMs = timingMsBetween(t.QueuedAt, t.DispatchedAt)
out.DispatchMs = timingMsBetween(t.DispatchedAt, firstChunk)
}
// commitFirstContent records the first CONTENT chunk on the committed attempt and
// stamps FirstContentAt (the actual_ttft_ms anchor) in the SAME instant, on the
// dispatch goroutine that reads the chunk. Stamping HERE — rather than later in
// writeCommittedResponse — guarantees FirstContentAt is set before ANY route
// outcome is built for this attempt: the committed/success outcome written by
// this goroutine (e.g. waitFirstChunk / waitAccepted's defer) AND the terminal
// completeRouteOutcome written concurrently by handleComplete on the provider
// read-loop. Without it a fast single-chunk completion could persist
// actual_ttft_ms as 0/NULL (applyPendingRouteTelemetry derives it solely from
// FirstContentAt). pr is the COMMITTED attempt — the backup on a speculative
// backup win, the primary otherwise. MarkFirstChunkArrived is kept (idempotent:
// it preserves an earlier preamble's first-byte time for dispatch_to_first_chunk_ms).
func (d *dispatchState) commitFirstContent(pr *registry.PendingRequest, chunk string) {
d.firstChunk = chunk
pr.MarkFirstChunkArrived()
pr.MarkFirstContentArrived()
d.stampFirstContent(pr)
// Mark THIS attempt as the committed one so handleComplete's fallback only
// ever stamps FirstContentAt for the attempt that actually delivered content —
// never a late-completing abandoned/retried attempt sharing the same Timing.
pr.MarkContentCommitted()
d.s.observeTTFTCalibration(pr)
// First CONTENT chunk == the provider ACCEPTED and is serving: clear the
// pair's capacity-reject streak NOW rather than at completion. A long
// generation on a busy box must keep vouching for the pair while the box
// legitimately sheds concurrent dispatches — waiting for the completion
// accept (noteInferenceSuccess) would let transient fullness masquerade as
// the zero-accepts black-hole signature. See registry/capacity_cooldown.go.
//
// The recorder takes the registry WRITE lock, which in production waits
// behind every queued writer (~190 ms at the median, seconds at the tail),
// and this runs BEFORE the chunk is written to the client. It is pure
// bookkeeping, so it runs off this goroutine and the first byte no longer
// waits for it. Exactly-once for the capacity-503 RATE window is kept by
// stamping the request BEFORE the recorder runs: the completion-time
// re-offer (noteInferenceSuccess) fires only for an unstamped request, and
// the recorder declines to store an offered accept only when rate tracking
// is disabled (PenaltyMs <= 0) — in which case the completion re-offer
// would store nothing either. So the unconditional stamp never loses an
// outcome and never double counts.
//
// The accept carries the instant it was OBSERVED — the first content
// chunk, stamped above by MarkFirstContentArrived — not the instant the
// goroutine finally holds the lock: a capacity reject for the same pair
// recorded in between happened AFTER this accept and must survive it
// (registry.RecordCapacityAcceptObserved).
pr.MarkRateOutcomeCounted()
providerID, model := pr.ProviderID, pr.Model
observedAt := pr.FirstContentAtSafe()
if observedAt.IsZero() {
observedAt = time.Now()
}
saferun.Go(d.s.logger, "api.recordCapacityAccept", func() {
d.s.registry.RecordCapacityAcceptObserved(providerID, model, observedAt, true)
})
}
func (d *dispatchState) successRoutingOutcomeFor(pr *registry.PendingRequest) *store.InferenceRouteOutcome {
return committedRouteOutcome(pr)
}
// errorRoutingOutcome builds an error / timeout / cancelled outcome.
func (d *dispatchState) errorRoutingOutcome(status, class string, code int) *store.InferenceRouteOutcome {
return d.errorRoutingOutcomeFor(d.pr, status, class, code)
}
func (d *dispatchState) errorRoutingOutcomeFor(pr *registry.PendingRequest, status, class string, code int) *store.InferenceRouteOutcome {
providerReason, errorText := "", ""
if routeOutcomeUsesProviderErrorText(class) {
providerReason = d.lastErrReason
errorText = d.lastErr
}
out := routeOutcomeWithReason(status, class, code, providerReason, errorText)
applyPendingRouteTelemetry(out, pr)
return out
}
func routeOutcomeUsesProviderErrorText(class string) bool {
class = strings.ToLower(strings.TrimSpace(class))
return class == errorReasonProviderError ||
class == errorClassDeadlineUnreachable ||
// client_error rows keep the provider-supplied reason too: a jinja_*
// template-render failure is recorded as class client_error (not a
// provider fault) but its reason must stay jinja_* on the row, so the
// inference.error{reason:jinja_*} series measures real render failures
// instead of being silenced by the reclassification. The reason is
// still whitelisted downstream (normalizeInferenceErrorReason).
class == errorClassClientError ||
strings.HasPrefix(class, "provider_error") ||
strings.HasPrefix(class, "provider_disconnect") ||
strings.Contains(class, "provider_incomplete")
}
func (d *dispatchState) setLastError(errText string, statusCode int) {
d.lastErr = errText
d.lastErrCode = statusCode
d.lastErrReason = ""
// Not a provider capacity rejection (timeout / no-provider / coordinator
// fault): clear any budget captured from a prior attempt so it never bleeds
// into a later classification.
d.lastErrProviderBudget = 0
d.lastErrRejectionReason = ""
// Same bleed-through rule for the typed terminal fields: a coordinator-
// synthesized error is not a provider terminal, so a stale typed cause from
// a prior attempt must not reclassify it (shouldStopFailover trusts a typed
// admission_timeout as transient capacity) and stale usage must not land on
// its route row. An empty cause here is also what lets the wait loops'
// 504 branches tell a synthetic timeout from a typed provider 504.
d.lastErrTerminalCause = ""
d.lastErrCoordinatorCause = ""
d.lastErrAttemptUsage = nil
d.lastErrFeasibleAfterMS = 0
d.lastFailureDeadline = false
}
func isGenuinePreContentFault(
msg protocol.InferenceErrorMessage,
providerBudget int64,
modelContext int,
) bool {
if msg.StatusCode < http.StatusInternalServerError {
return false
}
if isProviderHealthNeutralErrorReason(msg.ErrorReason) {
return false
}
switch msg.FailureCode {
case protocol.FailureCodeInvalidRequest,
protocol.FailureCodeInvalidMedia,
protocol.FailureCodeMediaTooLarge,
protocol.FailureCodeUnsupportedMedia,
protocol.FailureCodeTemplateRender,
protocol.FailureCodeModelUnavailable,
protocol.FailureCodeCapacity,
protocol.FailureCodeCancelled:
return false
}
switch class, _ := classifyTerminalCause(msg.TerminalCause); class {
case causeClassNeutral, causeClassCapacity:
return false
case causeClassFault:
return true
}
return classifyRejection(
msg.ErrorReason, msg.Error, providerBudget, modelContext,
msg.RejectionReason,
) == rejectionNotCapacity
}
func terminalFailureFromMessage(msg protocol.InferenceErrorMessage) dispatchTerminalFailure {
return dispatchTerminalFailure{
errText: msg.Error,
statusCode: msg.StatusCode,
terminalCause: msg.TerminalCause,
deadline: isDeadlineUnreachableErrorReason(msg.ErrorReason),
}
}
func (d *dispatchState) captureGenuineFault(
provider *registry.Provider,
msg protocol.InferenceErrorMessage,
providerBudget int64,
) {
if !isGenuinePreContentFault(msg, providerBudget, d.modelMaxContext) {
return
}
fault := terminalFailureFromMessage(msg)
fault.attribution = d.providerSlotAttribution(provider, d.model)
d.genuineFault = &fault
}
func (d *dispatchState) currentTerminalFailure() dispatchTerminalFailure {
return dispatchTerminalFailure{
errText: d.lastErr,
statusCode: d.lastErrCode,
terminalCause: d.lastErrTerminalCause,
deadline: d.lastFailureDeadline,
}
}
func (d *dispatchState) terminalFailureForExhaustion() (
dispatchTerminalFailure,
bool,
) {
if d.genuineFault != nil && !d.terminalClientError {
return *d.genuineFault, true
}
return d.currentTerminalFailure(), false
}
// classifyExhaustedStatus preserves provider-attempt telemetry while mapping a
// coordinator-synthesized pre-content timeout to the retryable status exposed to
// the caller. A typed provider 504 (safety deadline / backpressure timeout) is a
// real provider terminal and must remain 504; an untyped 504 is the dispatch
// loop's existing discriminator for its own first-content timeout.
func classifyExhaustedStatus(statusCode int, terminalCause string) (code int, reason string, reclassified bool) {
if statusCode == http.StatusGatewayTimeout && !isTypedTimeout504Cause(terminalCause) {
return http.StatusTooManyRequests, "first_chunk_timeout", true
}
return statusCode, "dispatch_exhausted", false
}
type exhaustedDominance int
const (
exhaustedUndecided exhaustedDominance = iota
exhaustedClientError
exhaustedGenuineFault
exhaustedUnservable
exhaustedDeadline
)
func (d *dispatchState) resolveDominantExhaustedStatus(
failure dispatchTerminalFailure,
stickyFault bool,
) (statusCode int, reason string, timeoutReclassified bool, dominance exhaustedDominance) {
statusCode, reason, timeoutReclassified = classifyExhaustedStatus(
failure.statusCode, failure.terminalCause)
if timeoutReclassified && failure.errText == errQueueDeadlineExpired {
// Never dispatched: the synthetic timeout came from the queue wait.
reason = rejectionReasonQueueDeadline
}
switch {
case d.terminalClientError:
statusCode = d.terminalClientErrorCode
reason = "client_error"
if d.terminalClientErrorReason != "" {
reason = d.terminalClientErrorReason
}
return statusCode, reason, timeoutReclassified, exhaustedClientError
case stickyFault:
return statusCode, reason, timeoutReclassified, exhaustedGenuineFault
case d.unservable:
statusCode = http.StatusTooManyRequests
reason = d.unservableReason
if reason == "" {
reason = rejectionReasonOversized
}
return statusCode, reason, timeoutReclassified, exhaustedUnservable
case failure.deadline:
return http.StatusTooManyRequests, rejectionReasonDeadlineUnreachable,
timeoutReclassified, exhaustedDeadline
default:
return statusCode, reason, timeoutReclassified, exhaustedUndecided
}
}
func (d *dispatchState) noteProviderBodyTooLarge(errText string, bodyBytes int) {
d.providerBodyTooLargeErr = errText
d.providerBodyTooLargeBytes = bodyBytes
d.setLastError(errText, http.StatusRequestEntityTooLarge)
}
func (d *dispatchState) preflightLegacyCacheBust() {
_, err := minimumLegacyCacheBustOverflow(d.rawBody, d.requiresVision)
if errors.Is(err, errProviderBodyTooLarge) {
d.minPrefixCacheProtocol = 1
}
}
func (d *dispatchState) noteProviderBodyTooLargeFor(
provider *registry.Provider,
errText string,
) {
if provider == nil {
return
}
if d.excludeProviders == nil {
d.excludeProviders = make(map[string]struct{})
}
d.excludeProviders[provider.ID] = struct{}{}
bodyBytes, _ := providerBodySizeError(
d.rawBody, d.requiresVision, provider)
d.noteProviderBodyTooLarge(errText, bodyBytes)
}
func (d *dispatchState) latchProviderBodyTooLarge(errText string) {
d.noteProviderBodyTooLarge(errText, d.providerBodyTooLargeBytes)
d.terminalClientError = true
d.terminalClientErrorCode = http.StatusRequestEntityTooLarge
d.terminalClientErrorReason = "payload_too_large"
d.terminalClientErrorMessage = errText
}
// setLastInferenceError records a pre-content provider rejection as the dispatch
// loop's last error and snapshots the rejecting provider's reported token budget
// for d.model. shouldStopFailover needs that budget to tell a fleet-wide
// DETERMINISTIC context overflow apart from THIS node's memory-pressured KV budget
// (see classifyRejection). provider may be nil (budget 0 = unknown).
func (d *dispatchState) setLastInferenceError(provider *registry.Provider, msg protocol.InferenceErrorMessage) {
msg = normalizeInferenceErrorForInternalUse(msg)
providerBudget := providerReportedBudget(provider, d.model)
if msg.AvailableTokenBudget != nil {
// Enriched rejection (routing v2): the LIVE gate budget at rejection
// time beats the last heartbeat's snapshot — this closes the
// documented stale-snapshot LIMITATION in classifyRejection, where a
// budget that shrank below the model context between heartbeats
// misclassified a node-pressured reject as fleet-deterministic. The
// wire field is a pointer precisely so an EXPLICIT zero survives:
// it means "this node has no headroom RIGHT NOW" (maximally
// transient, budget frees as sequences retire), never "unknown".
providerBudget = *msg.AvailableTokenBudget
}
d.lastErr = msg.Error
d.lastErrCode = msg.StatusCode
d.lastErrReason = msg.ErrorReason
d.lastFailureDeadline = isDeadlineUnreachableErrorReason(msg.ErrorReason)
d.lastErrProviderBudget = providerBudget
d.lastErrRejectionReason = msg.RejectionReason
d.lastErrTerminalCause = msg.TerminalCause
d.lastErrCoordinatorCause = msg.CoordinatorCause
d.lastErrAttemptUsage = msg.AttemptUsage
d.lastErrFeasibleAfterMS = msg.FeasibleAfterMS
d.captureGenuineFault(provider, msg, providerBudget)
}
// providerReportedBudget reads a provider's reported token budget for a model,
// tolerating a nil provider (returns 0 = unknown).
func providerReportedBudget(provider *registry.Provider, model string) int64 {
if provider == nil {
return 0
}
return provider.ReportedTokenBudgetMaxForModel(model)
}
// providerFailedRoutingOutcome builds the outcome for a POST-DISPATCH provider
// failure: the request had already been admitted to a specific provider (passed
// the admission gate and was dispatched over the WebSocket) and that provider
// then reported an error — including provider-reported OOM / model-load failures
// that surface on pr.ErrorCh. It flags AdmittedButFailed to expose the
// admission-gate mismatch (coordinator said "this provider can serve" but it
// could not). It is intentionally only used from the post-dispatch wait loops;
// pre-dispatch failures (queue reservation DB error, invalid key, keygen, send
// failure) and coordinator-side timeouts are NOT flagged.
func (d *dispatchState) providerFailedRoutingOutcome() *store.InferenceRouteOutcome {
return d.providerFailedRoutingOutcomeFor(d.pr)
}
func (d *dispatchState) providerFailedRoutingOutcomeFor(pr *registry.PendingRequest) *store.InferenceRouteOutcome {
if isDeadlineUnreachableErrorReason(d.lastErrReason) {
// The provider declined work before execution because the coordinator's
// remaining absolute budget could not be met. Preserve the typed reason
// without marking the provider as admitted-but-failed.
out := d.errorRoutingOutcomeFor(
pr, "error", errorClassDeadlineUnreachable, d.lastErrCode)
applyAttemptUsage(out, d.lastErrAttemptUsage)
return out
}
if isTerminalClientErrorCode(d.lastErrCode) || isNonProviderFaultErrorReason(d.lastErrReason) {
// Deterministic non-provider fault: a 4xx status the provider maps for
// malformed bodies, OR a structured non-provider-fault reason (jinja_*
// template-render failures, tool_noncompliance model-output 422s).
// Record as client_error WITHOUT AdmittedButFailed so neither pollutes
// the admission-mismatch gauge — keyed on the SAME vocabulary as the
// reputation and breaker exemptions (isNonProviderFaultErrorReason).
// The structured reason survives on the row (see
// routeOutcomeUsesProviderErrorText). Typed partial usage (if any)
// still lands on the row — observability only, no billing effect.
out := d.errorRoutingOutcomeFor(pr, "error", errorClassClientError, d.lastErrCode)
applyAttemptUsage(out, d.lastErrAttemptUsage)
return out
}
class := "provider_error"
if d.lastErrCoordinatorCause.IsProviderDisconnect() {
class = "provider_disconnect_pre_commit"
}
out := d.errorRoutingOutcomeFor(pr, "error", class, d.lastErrCode)
out.AdmittedButFailed = true
// Pre-content typed failures on the ordinary dispatch path flow through
// the deferred route update via this builder (not the standalone
// preResponse/postCommit constructors), so the typed attempt_usage
// retained by setLastInferenceError must be applied here too or the row
// records null token counts for the most common failure path.
applyAttemptUsage(out, d.lastErrAttemptUsage)
return out
}
// isTerminalClientErrorCode reports whether a provider-returned status code is a
// DETERMINISTIC client-shape rejection that fails identically on every provider,
// so the dispatch loop must stop and return it ONCE rather than fail over.
//
// Set: 400 (invalidRole / invalidToolPayload / mediaUnsupportedByModel + all VLM
// client MediaError), plus 413/415 defensively (unambiguous client shapes; not
// emitted by the provider map today but correct if a future version does).
//
// EXCLUDES 422 deliberately: the provider maps invalidResponseFormatOutput→422,
// which is thrown for BOTH a deterministic request-shape fault ("json_schema
// requires a json_schema payload") AND a model-OUTPUT-validation fault ("model
// output was not valid JSON"). The latter depends on what the model GENERATED, so
// a re-sample at temperature>0 (or a different provider/model) could succeed —
// stopping it would turn a recoverable request into a lost success (hurting
// uptime). 422 therefore stays on the normal failover path.
//
// Also EXCLUDES 404 ("model not loaded" — a cold-miss/lifecycle that MUST fail
// over, and which matches the "not loaded" capacity marker), 408 and 429
// (transient). 402 (the only coordinator-emitted 4xx) is excluded, so a code in
// this set can ONLY originate from a provider InferenceErrorMessage.
func isTerminalClientErrorCode(code int) bool {
switch code {
case http.StatusBadRequest, // 400
http.StatusRequestEntityTooLarge, // 413
http.StatusUnsupportedMediaType: // 415
return true
}
return false
}
func dispatchErrorClass(errText string) string {
if strings.Contains(errText, errProviderBodyTooLarge.Error()) {
return errorClassClientError
}
switch errText {
case "insufficient funds for provider price":
return "insufficient_funds"
case "no provider with E2E encryption":
return "encryption_missing"
case "provider public key invalid", "failed to encrypt request", "failed to generate session keys", "failed to marshal request":
return "encryption_error"
case errFirstContentDeadlineExpired:
return "first_chunk_timeout"