@@ -32,6 +32,7 @@ import (
3232 gtransport "google.golang.org/api/transport/grpc"
3333 "google.golang.org/grpc"
3434 "google.golang.org/grpc/codes"
35+ "google.golang.org/grpc/status"
3536)
3637
3738const (
@@ -49,8 +50,8 @@ type DynamicChannelSelectionStrategy int
4950
5051const (
5152 // DCPPowerOfTwoLeastBusy compares two random active channels and returns the
52- // lower weighted-load channel. It falls back to a full scan if random picks
53- // only find draining entries.
53+ // channel with lower picker load, including any active error penalty. It falls
54+ // back to a full scan if random picks only find draining entries.
5455 DCPPowerOfTwoLeastBusy DynamicChannelSelectionStrategy = iota
5556 // DCPRoundRobin cycles through active channels and skips draining entries.
5657 DCPRoundRobin
@@ -69,6 +70,19 @@ type DynamicChannelPoolConfig struct {
6970 DCPMaxRPCPerChannel float64
7071 // DCPMinRPCPerChannel is the low-load threshold used by scale-down checks.
7172 DCPMinRPCPerChannel float64
73+ // DCPErrorPenaltyStep is the picker load added for each qualifying error. Zero
74+ // defaults to 5, or to ceil(DCPMaxRPCPerChannel) when that is smaller. An
75+ // explicitly set step must not exceed ceil(DCPMaxRPCPerChannel). One transient
76+ // error therefore biases selection only slightly; repeated errors within the
77+ // penalty window accumulate up to ceil(DCPMaxRPCPerChannel), so a persistently
78+ // failing channel looks exactly as busy as a full one.
79+ DCPErrorPenaltyStep int32
80+ // DCPErrorPenaltyDuration controls the penalty window. Every qualifying error
81+ // restarts the window, and the accumulated penalty expires to zero when it
82+ // lapses. Zero defaults to 5 seconds; negative disables the penalty. Active
83+ // penalty counts toward scale-up so lost capacity can be replaced, while
84+ // scale-down and draining deliberately ignore it.
85+ DCPErrorPenaltyDuration time.Duration
7286
7387 DCPScaleDownCheckInterval time.Duration // DCPScaleDownCheckInterval controls periodic downscale evaluation.
7488 DCPScaleUpCooldown time.Duration // DCPScaleUpCooldown prevents repeated scale-up bursts.
@@ -89,6 +103,8 @@ func DefaultDynamicChannelPoolConfig() DynamicChannelPoolConfig {
89103 DCPMaxChannels : 10 ,
90104 DCPMaxRPCPerChannel : 25 ,
91105 DCPMinRPCPerChannel : 15 ,
106+ DCPErrorPenaltyStep : 5 ,
107+ DCPErrorPenaltyDuration : 5 * time .Second ,
92108 DCPScaleDownCheckInterval : 3 * time .Minute ,
93109 DCPScaleUpCooldown : 10 * time .Second ,
94110 DCPDownscaleConsecutiveLowLoadChecks : 3 ,
@@ -123,6 +139,12 @@ func normalizeDCPConfig(cfg DynamicChannelPoolConfig) (DynamicChannelPoolConfig,
123139 if cfg .DCPMinRPCPerChannel == 0 {
124140 cfg .DCPMinRPCPerChannel = def .DCPMinRPCPerChannel
125141 }
142+ if cfg .DCPErrorPenaltyStep == 0 {
143+ cfg .DCPErrorPenaltyStep = min (def .DCPErrorPenaltyStep , int32 (math .Ceil (cfg .DCPMaxRPCPerChannel )))
144+ }
145+ if cfg .DCPErrorPenaltyDuration == 0 {
146+ cfg .DCPErrorPenaltyDuration = def .DCPErrorPenaltyDuration
147+ }
126148 if cfg .DCPScaleDownCheckInterval == 0 {
127149 cfg .DCPScaleDownCheckInterval = def .DCPScaleDownCheckInterval
128150 }
@@ -163,6 +185,10 @@ func normalizeDCPConfig(cfg DynamicChannelPoolConfig) (DynamicChannelPoolConfig,
163185 // scale-down qualification and flapping.
164186 case cfg .DCPMinRPCPerChannel >= cfg .DCPMaxRPCPerChannel :
165187 return cfg , fmt .Errorf ("DCPMinRPCPerChannel must be less than DCPMaxRPCPerChannel" )
188+ case cfg .DCPErrorPenaltyStep < 0 :
189+ return cfg , fmt .Errorf ("DCPErrorPenaltyStep must be non-negative" )
190+ case cfg .DCPErrorPenaltyStep > int32 (math .Ceil (cfg .DCPMaxRPCPerChannel )):
191+ return cfg , fmt .Errorf ("DCPErrorPenaltyStep must be <= ceil(DCPMaxRPCPerChannel)" )
166192 case cfg .DCPScaleDownCheckInterval <= 0 :
167193 return cfg , fmt .Errorf ("DCPScaleDownCheckInterval must be positive" )
168194 case cfg .DCPMaxScaleUpPercent <= 0 || cfg .DCPMaxScaleUpPercent > 100 :
@@ -181,40 +207,45 @@ type dynamicChannelPool struct {
181207 entries atomic.Pointer [[]* dcpEntry ]
182208 cfg DynamicChannelPoolConfig
183209 targetRPCPerChannel float64
210+ penaltyMax int32
184211
185212 ctx context.Context
186213 cancel context.CancelFunc
187214 sc * sessionClient
188215
189- dial func (context.Context ) (gtransport.ConnPool , error )
190- rrIndex atomic.Uint64
191- nextID atomic.Uint64
192- totalRPCLoad atomic.Int32
193- dialMu sync.Mutex
194- lastScaleUp atomic.Int64
195- scaleUpSignal chan struct {}
196- done chan struct {}
197- stopOnce sync.Once
198- lowLoadRuns int
199- monitorMu sync.Mutex
200- primeSession atomic.Value // string
201- metrics * dcpMetrics
216+ dial func (context.Context ) (gtransport.ConnPool , error )
217+ rrIndex atomic.Uint64
218+ nextID atomic.Uint64
219+ totalRPCLoad atomic.Int32
220+ totalPenaltyLoad atomic.Int64
221+ dialMu sync.Mutex
222+ lastScaleUp atomic.Int64
223+ scaleUpSignal chan struct {}
224+ done chan struct {}
225+ stopOnce sync.Once
226+ lowLoadRuns int
227+ monitorMu sync.Mutex
228+ primeSession atomic.Value // string
229+ metrics * dcpMetrics
202230
203231 drainingCount atomic.Int64
204232}
205233
206234// dcpEntry represents one logical DCP slot.
207235type dcpEntry struct {
208- id uint64
209- pool gtransport.ConnPool
210- delegate spannerClient
211- client spannerClient
212- parent * dynamicChannelPool
213- unaryLoad atomic.Int32
214- streamLoad atomic.Int32
215- state atomic.Int32 // dcpState*
216- createdAt atomic.Int64 // UnixNano creation time
217- lastActivity atomic.Int64 // UnixNano last pick/RPC/release time
236+ id uint64
237+ pool gtransport.ConnPool
238+ delegate spannerClient
239+ client spannerClient
240+ parent * dynamicChannelPool
241+ unaryLoad atomic.Int32
242+ streamLoad atomic.Int32
243+ state atomic.Int32 // dcpState*
244+ createdAt atomic.Int64 // UnixNano creation time
245+ lastActivity atomic.Int64 // UnixNano last pick/RPC/release time
246+ penaltyExpiry atomic.Int64 // UnixNano penalty expiry; zero means no penalty
247+ penaltyLoad atomic.Int32 // Accumulated error penalty, capped by config
248+ penaltyMu sync.Mutex // Serializes rare penalty updates and removal
218249}
219250
220251// newDynamicChannelPool creates the initial channel set and starts scale workers.
@@ -227,6 +258,7 @@ func newDynamicChannelPool(ctx context.Context, sc *sessionClient, cfg DynamicCh
227258 p := & dynamicChannelPool {
228259 cfg : cfg ,
229260 targetRPCPerChannel : math .Max (1 , math .Floor ((cfg .DCPMinRPCPerChannel + cfg .DCPMaxRPCPerChannel )/ 2 )),
261+ penaltyMax : int32 (math .Ceil (cfg .DCPMaxRPCPerChannel )),
230262 ctx : poolCtx ,
231263 cancel : cancel ,
232264 sc : sc ,
@@ -277,6 +309,7 @@ func (p *dynamicChannelPool) Invoke(ctx context.Context, method string, args, re
277309 e .lastActivity .Store (time .Now ().UnixNano ())
278310 }()
279311 err = e .pool .Invoke (ctx , method , args , reply , opts ... )
312+ e .applyErrorPenalty (err )
280313 return err
281314}
282315
@@ -291,6 +324,7 @@ func (p *dynamicChannelPool) NewStream(ctx context.Context, desc *grpc.StreamDes
291324 e .lastActivity .Store (time .Now ().UnixNano ())
292325 stream , err := e .pool .NewStream (ctx , desc , method , opts ... )
293326 if err != nil {
327+ e .applyErrorPenalty (err )
294328 e .streamLoad .Add (- 1 )
295329 p .totalRPCLoad .Add (- 1 )
296330 return nil , err
@@ -463,6 +497,7 @@ func (s *dcpConnPoolTrackedStream) CloseSend() error {
463497
464498func (s * dcpConnPoolTrackedStream ) finish (err error ) {
465499 s .once .Do (func () {
500+ s .entry .applyErrorPenalty (err )
466501 s .entry .streamLoad .Add (- 1 )
467502 s .entry .parent .totalRPCLoad .Add (- 1 )
468503 s .entry .lastActivity .Store (time .Now ().UnixNano ())
@@ -471,7 +506,7 @@ func (s *dcpConnPoolTrackedStream) finish(err error) {
471506
472507var errDCPNoEntries = spannerErrorf (codes .Unavailable , "spanner_dcp: no available channels" )
473508
474- // pickPowerOfTwo selects the lower weighted -load entry from two random active
509+ // pickPowerOfTwo selects the lower picker -load entry from two random active
475510// entries. It retries when either random choice is draining and falls back to a
476511// full least-loaded scan if random sampling cannot find an active pair.
477512func (p * dynamicChannelPool ) pickPowerOfTwo () (* dcpEntry , error ) {
@@ -491,7 +526,7 @@ func (p *dynamicChannelPool) pickPowerOfTwo() (*dcpEntry, error) {
491526 if e1 .isDraining () || e2 .isDraining () {
492527 continue
493528 }
494- if e1 .weightedLoad () <= e2 .weightedLoad () {
529+ if e1 .pickLoad () <= e2 .pickLoad () {
495530 return e1 , nil
496531 }
497532 return e2 , nil
@@ -516,15 +551,15 @@ func (p *dynamicChannelPool) pickRoundRobin() (*dcpEntry, error) {
516551 return nil , errDCPNoEntries
517552}
518553
519- // pickLeastLoaded returns the active entry with the lowest weighted load.
554+ // pickLeastLoaded returns the active entry with the lowest picker load.
520555func (p * dynamicChannelPool ) pickLeastLoaded () (* dcpEntry , error ) {
521556 var best * dcpEntry
522557 min := int32 (math .MaxInt32 )
523558 for _ , e := range p .getEntries () {
524559 if e .isDraining () {
525560 continue
526561 }
527- l := e .weightedLoad ()
562+ l := e .pickLoad ()
528563 if l < min {
529564 min = l
530565 best = e
@@ -543,9 +578,13 @@ func (p *dynamicChannelPool) maybeSignalScaleUp(e *dcpEntry) {
543578 active := p .Num ()
544579 avg := float64 (0 )
545580 if active > 0 {
546- avg = float64 (p .totalRPCLoad .Load ()) / float64 (active )
581+ // The two totals may be observed at slightly different instants. This
582+ // signal is only a hint; scaleUp recomputes exact per-entry load.
583+ load := int64 (p .totalRPCLoad .Load ()) + int64 (p .totalPenaltyLoad .Load ())
584+ avg = float64 (load ) / float64 (active )
547585 }
548- if float64 (e .rpcLoad ()) <= p .cfg .DCPMaxRPCPerChannel && avg <= p .cfg .DCPMaxRPCPerChannel {
586+ entryLoad := int64 (e .rpcLoad ()) + int64 (e .currentPenalty ())
587+ if float64 (entryLoad ) <= p .cfg .DCPMaxRPCPerChannel && avg <= p .cfg .DCPMaxRPCPerChannel {
549588 return
550589 }
551590 select {
@@ -591,11 +630,11 @@ func (p *dynamicChannelPool) scaleUp() {
591630 }
592631 entries := p .getEntries ()
593632 active := 0
594- var load int32
633+ var load int64
595634 for _ , e := range entries {
596635 if ! e .isDraining () {
597636 active ++
598- load += e .rpcLoad ()
637+ load += int64 ( e .rpcLoad ()) + int64 ( e . currentPenalty () )
599638 }
600639 }
601640 if active == 0 {
@@ -693,6 +732,8 @@ func (p *dynamicChannelPool) evaluateScaleDown() {
693732 entries := p .getEntries ()
694733 active := 0
695734 var load int32
735+ // Error penalties are deliberately excluded from scale-down load so a
736+ // failing channel is not retained as busy.
696737 for _ , e := range entries {
697738 if ! e .isDraining () {
698739 active ++
@@ -783,6 +824,7 @@ func (p *dynamicChannelPool) removeEntries(count int) {
783824 toDrain := make (map [* dcpEntry ]bool )
784825 for i := 0 ; i < count && i < len (candidates ); i ++ {
785826 candidates [i ].e .state .Store (dcpStateDraining )
827+ candidates [i ].e .clearErrorPenalty ()
786828 toDrain [candidates [i ].e ] = true
787829 }
788830 keep := make ([]* dcpEntry , 0 , len (entries )- len (toDrain ))
@@ -842,6 +884,7 @@ func (e *dcpEntry) close() error {
842884 if ! e .state .CompareAndSwap (dcpStateActive , dcpStateClosed ) && ! e .state .CompareAndSwap (dcpStateDraining , dcpStateClosed ) {
843885 return nil
844886 }
887+ e .clearErrorPenalty ()
845888 var errs []error
846889 if e .client != nil {
847890 errs = append (errs , e .client .Close ())
@@ -862,6 +905,86 @@ func (e *dcpEntry) rpcLoad() int32 { return e.unaryLoad.Load() + e.streamLoad.Lo
862905// weightedLoad returns the current in-flight RPC load for this entry.
863906func (e * dcpEntry ) weightedLoad () int32 { return e .rpcLoad () }
864907
908+ // applyErrorPenalty accumulates load for errors that indicate channel-specific
909+ // health or capacity trouble. Internal is deliberately excluded: only
910+ // Unavailable and ResourceExhausted steer subsequent picks away from a channel.
911+ // Updates are serialized because they are rare and must keep the pool aggregate
912+ // consistent. The hot pick path remains lock-free while the penalty is active.
913+ func (e * dcpEntry ) applyErrorPenalty (err error ) {
914+ if err == nil || e .parent .cfg .DCPErrorPenaltyDuration < 0 {
915+ return
916+ }
917+ code := status .Code (err )
918+ if code != codes .Unavailable && code != codes .ResourceExhausted {
919+ return
920+ }
921+ e .penaltyMu .Lock ()
922+ defer e .penaltyMu .Unlock ()
923+ if e .state .Load () != dcpStateActive {
924+ return
925+ }
926+ now := time .Now ()
927+ expiry := e .penaltyExpiry .Load ()
928+ current := int32 (0 )
929+ oldContribution := int32 (0 )
930+ if expiry != 0 {
931+ oldContribution = e .penaltyLoad .Load ()
932+ if now .UnixNano () < expiry {
933+ current = oldContribution
934+ }
935+ }
936+ load := e .parent .cfg .DCPErrorPenaltyStep
937+ if current != 0 {
938+ max := e .parent .penaltyMax
939+ if current >= max - e .parent .cfg .DCPErrorPenaltyStep {
940+ load = max
941+ } else {
942+ load = current + e .parent .cfg .DCPErrorPenaltyStep
943+ }
944+ }
945+ e .penaltyLoad .Store (load )
946+ e .penaltyExpiry .Store (now .Add (e .parent .cfg .DCPErrorPenaltyDuration ).UnixNano ())
947+ e .parent .totalPenaltyLoad .Add (int64 (load - oldContribution ))
948+ }
949+
950+ // currentPenalty returns active accumulated error load and lazily clears an
951+ // expired penalty.
952+ func (e * dcpEntry ) currentPenalty () int32 {
953+ expiry := e .penaltyExpiry .Load ()
954+ if expiry == 0 {
955+ return 0
956+ }
957+ if time .Now ().UnixNano () < expiry {
958+ return e .penaltyLoad .Load ()
959+ }
960+ e .penaltyMu .Lock ()
961+ defer e .penaltyMu .Unlock ()
962+ expiry = e .penaltyExpiry .Load ()
963+ if expiry == 0 {
964+ return 0
965+ }
966+ if time .Now ().UnixNano () < expiry {
967+ return e .penaltyLoad .Load ()
968+ }
969+ // Leave penaltyLoad intact; expiry alone gates whether load is used.
970+ e .penaltyExpiry .Store (0 )
971+ e .parent .totalPenaltyLoad .Add (- int64 (e .penaltyLoad .Load ()))
972+ return 0
973+ }
974+
975+ // clearErrorPenalty removes an entry's aggregate contribution when the entry
976+ // leaves the live pool. The expiry swap makes repeated close paths harmless.
977+ func (e * dcpEntry ) clearErrorPenalty () {
978+ e .penaltyMu .Lock ()
979+ defer e .penaltyMu .Unlock ()
980+ if e .penaltyExpiry .Swap (0 ) != 0 {
981+ e .parent .totalPenaltyLoad .Add (- int64 (e .penaltyLoad .Load ()))
982+ }
983+ }
984+
985+ // pickLoad returns the in-flight RPC load plus any active error penalty.
986+ func (e * dcpEntry ) pickLoad () int32 { return e .rpcLoad () + e .currentPenalty () }
987+
865988// TODO: Investigate replacing dcpSpannerClient and dcpConnPoolTrackedStream with
866989// per-entry gRPC unary/stream client interceptors injected when dialing each DCP
867990// entry. The interceptors could track load and trigger scale-up for both the
@@ -881,6 +1004,7 @@ func (c *dcpSpannerClient) startUnary(ctx context.Context) func(error) {
8811004 c .entry .parent .maybeSignalScaleUp (c .entry )
8821005 c .entry .lastActivity .Store (time .Now ().UnixNano ())
8831006 return func (err error ) {
1007+ c .entry .applyErrorPenalty (err )
8841008 c .entry .unaryLoad .Add (- 1 )
8851009 c .entry .parent .totalRPCLoad .Add (- 1 )
8861010 c .entry .lastActivity .Store (time .Now ().UnixNano ())
@@ -926,6 +1050,7 @@ func (c *dcpSpannerClient) startStream(ctx context.Context) *dcpStreamRef {
9261050 c .entry .parent .maybeSignalScaleUp (c .entry )
9271051 c .entry .lastActivity .Store (time .Now ().UnixNano ())
9281052 ref := & dcpStreamRef {finish : func (err error ) {
1053+ c .entry .applyErrorPenalty (err )
9291054 c .entry .streamLoad .Add (- 1 )
9301055 c .entry .parent .totalRPCLoad .Add (- 1 )
9311056 c .entry .lastActivity .Store (time .Now ().UnixNano ())
0 commit comments