@@ -399,10 +399,31 @@ func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error {
399399
400400 if finalState == pool .StateInitializing {
401401 // Another goroutine is initializing - WAIT for it to complete
402- // Use the request context directly to respect the caller's timeout
403- // This prevents goroutines from waiting longer than their request timeout
402+ // Use a context with the minimum of DialTimeout and the command timeout
403+ // to prevent waiting too long for initialization
404+ waitCtx := ctx
405+ cmdDeadline , hasCmdDeadline := ctx .Deadline ()
406+ dialTimeout := c .opt .DialTimeout
407+
408+ if hasCmdDeadline {
409+ // Calculate the minimum timeout
410+ dialDeadline := time .Now ().Add (dialTimeout )
411+ if dialDeadline .Before (cmdDeadline ) {
412+ // DialTimeout is shorter, use it
413+ var cancel context.CancelFunc
414+ waitCtx , cancel = context .WithTimeout (ctx , dialTimeout )
415+ defer cancel ()
416+ }
417+ // else: command timeout is shorter, use ctx as-is
418+ } else {
419+ // No command deadline, use DialTimeout
420+ var cancel context.CancelFunc
421+ waitCtx , cancel = context .WithTimeout (ctx , dialTimeout )
422+ defer cancel ()
423+ }
424+
404425 finalState , err := cn .GetStateMachine ().AwaitAndTransition (
405- ctx ,
426+ waitCtx ,
406427 []pool.ConnState {pool .StateIdle , pool .StateInUse },
407428 pool .StateIdle , // Target is IDLE (but we're already there, so this is a no-op)
408429 )
0 commit comments