package redis

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
	
)

const (
	minLatencyMeasurementInterval = 10 * time.Second
)

var (
	errClusterNoNodes = errors.New("redis: cluster has no nodes")
	errNoWatchKeys    = errors.New("redis: Watch requires at least one key")
	errWatchCrosslot  = errors.New("redis: Watch requires all keys to be in the same slot")
)

// ClusterOptions are used to configure a cluster client and should be
// passed to NewClusterClient.
type ClusterOptions struct {
	// A seed list of host:port addresses of cluster nodes.
	Addrs []string

	// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
	ClientName string

	// NewClient creates a cluster node client with provided name and options.
	// If NewClient is set by the user, the user is responsible for handling maintnotifications upgrades and push notifications.
	NewClient func(opt *Options) *Client

	// The maximum number of retries before giving up. Command is retried
	// on network errors and MOVED/ASK redirects.
	// Default is 3 retries.
	MaxRedirects int

	// Enables read-only commands on slave nodes.
	ReadOnly bool
	// Allows routing read-only commands to the closest master or slave node.
	// It automatically enables ReadOnly.
	RouteByLatency bool
	// RouteByLatencyTolerance widens RouteByLatency from "the single fastest node" to
	// "any node within this much of the fastest", round-robining between them.
	//
	// RouteByLatency alone takes a strict minimum, so when several nodes are equally
	// close - replicas sharing an availability zone, say - every client picks the same
	// one and the others take no read traffic. Latency is estimated from ten pings and
	// refreshed at most every 10s, so a difference well inside the noise can decide the
	// whole read load for the next interval.
	//
	// Zero keeps the strict-minimum behaviour. Has no effect unless RouteByLatency is set.
	RouteByLatencyTolerance time.Duration
	// Allows routing read-only commands to the random master or slave node.
	// It automatically enables ReadOnly.
	RouteRandomly bool

	// Optional function that returns cluster slots information.
	// It is useful to manually create cluster of standalone Redis servers
	// and load-balance read/write operations between master and slaves.
	// It can use service like ZooKeeper to maintain configuration information
	// and Cluster.ReloadState to manually trigger state reloading.
	ClusterSlots func(context.Context) ([]ClusterSlot, error)

	// Following options are copied from Options struct.

	Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

	OnConnect func(ctx context.Context, cn *Conn) error

	Protocol                     int
	Username                     string
	Password                     string
	CredentialsProvider          func() (username string, password string)
	CredentialsProviderContext   func(ctx context.Context) (username string, password string, err error)
	StreamingCredentialsProvider auth.StreamingCredentialsProvider

	// MaxRetries is the maximum number of retries before giving up.
	// For ClusterClient, retries are disabled by default (set to -1),
	// because the cluster client handles all kinds of retries internally.
	// This is intentional and differs from the standalone Options default.
	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration

	DialTimeout time.Duration

	// DialerRetries is the maximum number of retry attempts when dialing fails.
	//
	// default: 5
	DialerRetries int

	// DialerRetryTimeout is the backoff duration between retry attempts.
	//
	// default: 100 milliseconds
	DialerRetryTimeout time.Duration

	// DialerRetryBackoff controls the delay between dial retry attempts.
	// See Options.DialerRetryBackoff for details.
	DialerRetryBackoff func(attempt int) time.Duration

	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	ContextTimeoutEnabled bool

	// MaxConcurrentDials is the maximum number of concurrent connection creation goroutines.
	// If <= 0, each node's pool defaults it to that node's PoolSize. If > PoolSize, it
	// is capped at PoolSize. Note: ClusterOptions itself leaves the field un-normalized
	// (introspecting it after init still reports the zero value); resolution happens in
	// each node's Options so the pipeline pool can widen its own dial cap.
	MaxConcurrentDials int

	PoolFIFO              bool
	PoolSize              int // applies per cluster node and not for the whole cluster
	PoolTimeout           time.Duration
	MinIdleConns          int
	MaxIdleConns          int
	MaxActiveConns        int // applies per cluster node and not for the whole cluster
	ConnMaxIdleTime       time.Duration
	ConnMaxLifetime       time.Duration
	ConnMaxLifetimeJitter time.Duration

	// ReadBufferSize is the size of the bufio.Reader buffer for each connection.
	// Larger buffers can improve performance for commands that return large responses.
	// Smaller buffers can improve memory usage for larger pools.
	//
	// default: 32KiB (32768 bytes)
	ReadBufferSize int

	// WriteBufferSize is the size of the bufio.Writer buffer for each connection.
	// Larger buffers can improve performance for large pipelines and commands with many arguments.
	// Smaller buffers can improve memory usage for larger pools.
	//
	// default: 32KiB (32768 bytes)
	WriteBufferSize int

	// PipelineReadBufferSize, PipelineWriteBufferSize and PipelinePoolSize
	// configure an optional separate connection pool used for pipelining on
	// each node, with its own (typically larger) buffers. See the same-named
	// fields on Options for details. The pool is created only when PipelineReadBufferSize or PipelineWriteBufferSize is set (PipelinePoolSize alone does not enable it).
	PipelineReadBufferSize  int
	PipelineWriteBufferSize int
	PipelinePoolSize        int

	// AutoPipelineOptions is the default config for BOTH autopipeliner faces
	// (AutoPipeline and AsyncAutoPipeline), applied when they are called
	// without explicit options. See Options.AutoPipelineOptions.
	AutoPipelineOptions *AutoPipelineOptions

	TLSConfig *tls.Config

	// DisableRoutingPolicies disables the request/response policy routing system.
	// When disabled, all commands use the legacy routing behavior.
	// Experimental. Will be removed when shard picker is fully implemented.
	DisableRoutingPolicies bool

	// DisableIndentity - Disable set-lib on connect.
	//
	// default: false
	//
	// Deprecated: Use DisableIdentity instead.
	DisableIndentity bool

	// DisableIdentity is used to disable CLIENT SETINFO command on connect.
	//
	// default: false
	DisableIdentity bool

	IdentitySuffix string // Add suffix to client name. Default is empty.

	// Deprecated: All RediSearch commands now have stable RESP3 parsing and this
	// flag is a no-op. It is kept for backwards compatibility and will be removed
	// in a future release.
	UnstableResp3 bool

	// PushNotificationProcessor is the processor for handling push notifications.
	// If nil, a default processor will be created for RESP3 connections.
	PushNotificationProcessor push.NotificationProcessor

	// FailingTimeoutSeconds is the timeout in seconds for marking a cluster node as failing.
	// When a node is marked as failing, it will be avoided for this duration.
	// Default is 15 seconds.
	FailingTimeoutSeconds int

	// MaintNotificationsConfig provides custom configuration for maintnotifications upgrades.
	// When MaintNotificationsConfig.Mode is not "disabled", the client will handle
	// cluster upgrade notifications gracefully and manage connection/pool state
	// transitions seamlessly. Requires Protocol: 3 (RESP3) for push notifications.
	// If nil, maintnotifications upgrades are in "auto" mode and will be enabled if the server supports it.
	// The ClusterClient supports SMIGRATING and SMIGRATED notifications for cluster state management.
	// Individual node clients handle other maintenance notifications (MOVING, MIGRATING, etc.).
	MaintNotificationsConfig *maintnotifications.Config
	// ShardPicker is used to pick a shard when the request_policy is
	// ReqDefault and the command has no keys.
	ShardPicker routing.ShardPicker

	// ClusterStateReloadInterval is the interval for reloading the cluster state.
	// MOVED/ASK redirects still trigger an immediate reactive reload, so this
	// only bounds how stale a topology can get without traffic errors.
	// Default is 60 seconds.
	ClusterStateReloadInterval time.Duration
}

func ( *ClusterOptions) () {
	switch .MaxRedirects {
	case -1:
		.MaxRedirects = 0
	case 0:
		.MaxRedirects = 3
	}

	if .RouteByLatency || .RouteRandomly {
		.ReadOnly = true
	}

	if .DialTimeout == 0 {
		.DialTimeout = 5 * time.Second
	}
	if .DialerRetries == 0 {
		.DialerRetries = 5
	}
	if .DialerRetryTimeout == 0 {
		.DialerRetryTimeout = 100 * time.Millisecond
	}

	if .PoolSize == 0 {
		.PoolSize = 5 * runtime.GOMAXPROCS(0)
	}
	// Do NOT normalize MaxConcurrentDials here. clientOptions() copies this value
	// into each node's Options, and the per-node Options.init() normalizes it for
	// the node's main pool. Setting it here would make the per-node init treat an
	// unset value as explicit (maxConcurrentDialsSet), which makes the pipeline
	// pool inherit the node PoolSize as its dial cap instead of widening to
	// PipelinePoolSize, and so serializes pipeline dials.
	if .ReadBufferSize == 0 {
		.ReadBufferSize = proto.DefaultBufferSize
	}
	if .WriteBufferSize == 0 {
		.WriteBufferSize = proto.DefaultBufferSize
	}

	switch .ReadTimeout {
	case -1:
		.ReadTimeout = 0
	case 0:
		.ReadTimeout = 5 * time.Second
	}
	switch .WriteTimeout {
	case -1:
		.WriteTimeout = 0
	case 0:
		.WriteTimeout = .ReadTimeout
	}

	if .MaxRetries == 0 {
		.MaxRetries = -1
	}
	switch .MinRetryBackoff {
	case -1:
		.MinRetryBackoff = 0
	case 0:
		.MinRetryBackoff = 10 * time.Millisecond
	}
	switch .MaxRetryBackoff {
	case -1:
		.MaxRetryBackoff = 0
	case 0:
		.MaxRetryBackoff = time.Second
	}

	if .NewClient == nil {
		.NewClient = NewClient
	}

	if .FailingTimeoutSeconds == 0 {
		.FailingTimeoutSeconds = 15
	}

	if .ShardPicker == nil {
		.ShardPicker = &routing.RoundRobinPicker{}
	}

	if .ClusterStateReloadInterval == 0 {
		.ClusterStateReloadInterval = 60 * time.Second
	}
}

// ParseClusterURL parses a URL into ClusterOptions that can be used to connect to Redis.
// The URL must be in the form:
//
//	redis://<user>:<password>@<host>:<port>
//	or
//	rediss://<user>:<password>@<host>:<port>
//
// To add additional addresses, specify the query parameter, "addr" one or more times. e.g:
//
//	redis://<user>:<password>@<host>:<port>?addr=<host2>:<port2>&addr=<host3>:<port3>
//	or
//	rediss://<user>:<password>@<host>:<port>?addr=<host2>:<port2>&addr=<host3>:<port3>
//
// Most Option fields can be set using query parameters, with the following restrictions:
//   - field names are mapped using snake-case conversion: to set MaxRetries, use max_retries
//   - only scalar type fields are supported (bool, int, time.Duration)
//   - for time.Duration fields, values must be a valid input for time.ParseDuration();
//     additionally a plain integer as value (i.e. without unit) is interpreted as seconds
//   - to disable a duration field, use value less than or equal to 0; to use the default
//     value, leave the value blank or remove the parameter
//   - only the last value is interpreted if a parameter is given multiple times
//   - fields "network", "addr", "username" and "password" can only be set using other
//     URL attributes (scheme, host, userinfo, resp.), query parameters using these
//     names will be treated as unknown parameters
//   - unknown parameter names will result in an error
//
// Example:
//
//	redis://user:password@localhost:6789?dial_timeout=3&read_timeout=6s&addr=localhost:6790&addr=localhost:6791
//	is equivalent to:
//	&ClusterOptions{
//		Addr:        ["localhost:6789", "localhost:6790", "localhost:6791"]
//		DialTimeout: 3 * time.Second, // no time unit = seconds
//		ReadTimeout: 6 * time.Second,
//	}
func ( string) (*ClusterOptions, error) {
	 := &ClusterOptions{}

	,  := url.Parse()
	if  != nil {
		return nil, 
	}

	// add base URL to the array of addresses
	// more addresses may be added through the URL params
	,  := getHostPortWithDefaults()
	.Addrs = append(.Addrs, net.JoinHostPort(, ))

	// setup username, password, and other configurations
	,  = setupClusterConn(, , )
	if  != nil {
		return nil, 
	}

	return , nil
}

// setupClusterConn gets the username and password from the URL and the query parameters.
func setupClusterConn( *url.URL,  string,  *ClusterOptions) (*ClusterOptions, error) {
	switch .Scheme {
	case "rediss":
		.TLSConfig = &tls.Config{ServerName: }
		fallthrough
	case "redis":
		.Username, .Password = getUserPassword()
	default:
		return nil, fmt.Errorf("redis: invalid URL scheme: %s", .Scheme)
	}

	// retrieve the configuration from the query parameters
	,  := setupClusterQueryParams(, )
	if  != nil {
		return nil, 
	}

	return , nil
}

// setupClusterQueryParams converts query parameters in u to option value in o.
func setupClusterQueryParams( *url.URL,  *ClusterOptions) (*ClusterOptions, error) {
	 := queryOptions{q: .Query()}

	.Protocol = .int("protocol")
	.ClientName = .string("client_name")
	.MaxRedirects = .int("max_redirects")
	.ReadOnly = .bool("read_only")
	.RouteByLatency = .bool("route_by_latency")
	.RouteByLatencyTolerance = .duration("route_by_latency_tolerance")
	.RouteRandomly = .bool("route_randomly")
	.MaxRetries = .int("max_retries")
	.MinRetryBackoff = .duration("min_retry_backoff")
	.MaxRetryBackoff = .duration("max_retry_backoff")
	.DialTimeout = .duration("dial_timeout")
	.DialerRetries = .int("dialer_retries")
	.DialerRetryTimeout = .duration("dialer_retry_timeout")
	.ReadTimeout = .duration("read_timeout")
	.WriteTimeout = .duration("write_timeout")
	.PoolFIFO = .bool("pool_fifo")
	.PoolSize = .int("pool_size")
	.MaxConcurrentDials = .int("max_concurrent_dials")
	.MinIdleConns = .int("min_idle_conns")
	.MaxIdleConns = .int("max_idle_conns")
	.MaxActiveConns = .int("max_active_conns")
	// Pipeline pool (per node, created by default): allow URL opt-out
	// (pipeline_pool_size=-1) / tuning, else rejected as unexpected options.
	.PipelinePoolSize = .int("pipeline_pool_size")
	.PipelineReadBufferSize = .int("pipeline_read_buffer_size")
	.PipelineWriteBufferSize = .int("pipeline_write_buffer_size")
	.PoolTimeout = .duration("pool_timeout")
	.ConnMaxLifetime = .duration("conn_max_lifetime")
	if .has("conn_max_lifetime_jitter") {
		.ConnMaxLifetimeJitter = min(.duration("conn_max_lifetime_jitter"), .ConnMaxLifetime)
	}
	.ConnMaxIdleTime = .duration("conn_max_idle_time")
	.FailingTimeoutSeconds = .int("failing_timeout_seconds")

	if .err != nil {
		return nil, .err
	}

	// addr can be specified as many times as needed
	 := .strings("addr")
	for ,  := range  {
		, ,  := net.SplitHostPort()
		if  != nil ||  == "" ||  == "" {
			return nil, fmt.Errorf("redis: unable to parse addr param: %s", )
		}

		.Addrs = append(.Addrs, net.JoinHostPort(, ))
	}

	// any parameters left?
	if  := .remaining(); len() > 0 {
		return nil, fmt.Errorf("redis: unexpected option: %s", strings.Join(, ", "))
	}

	return , nil
}

func ( *ClusterOptions) () *Options {
	// Clone MaintNotificationsConfig to avoid sharing between cluster node clients
	var  *maintnotifications.Config
	if .MaintNotificationsConfig != nil {
		 := *.MaintNotificationsConfig
		 = &
	}

	return &Options{
		ClientName: .ClientName,
		Dialer:     .Dialer,
		OnConnect:  .OnConnect,

		Protocol:                     .Protocol,
		Username:                     .Username,
		Password:                     .Password,
		CredentialsProvider:          .CredentialsProvider,
		CredentialsProviderContext:   .CredentialsProviderContext,
		StreamingCredentialsProvider: .StreamingCredentialsProvider,

		MaxRetries:      .MaxRetries,
		MinRetryBackoff: .MinRetryBackoff,
		MaxRetryBackoff: .MaxRetryBackoff,

		DialTimeout:        .DialTimeout,
		DialerRetries:      .DialerRetries,
		DialerRetryTimeout: .DialerRetryTimeout,
		DialerRetryBackoff: .DialerRetryBackoff,
		ReadTimeout:        .ReadTimeout,
		WriteTimeout:       .WriteTimeout,

		ContextTimeoutEnabled: .ContextTimeoutEnabled,

		PoolFIFO:              .PoolFIFO,
		PoolSize:              .PoolSize,
		MaxConcurrentDials:    .MaxConcurrentDials,
		PoolTimeout:           .PoolTimeout,
		MinIdleConns:          .MinIdleConns,
		MaxIdleConns:          .MaxIdleConns,
		MaxActiveConns:        .MaxActiveConns,
		ConnMaxIdleTime:       .ConnMaxIdleTime,
		ConnMaxLifetime:       .ConnMaxLifetime,
		ConnMaxLifetimeJitter: .ConnMaxLifetimeJitter,
		ReadBufferSize:        .ReadBufferSize,
		WriteBufferSize:       .WriteBufferSize,

		PipelineReadBufferSize:  .PipelineReadBufferSize,
		PipelineWriteBufferSize: .PipelineWriteBufferSize,
		PipelinePoolSize:        .PipelinePoolSize,
		DisableIdentity:         .DisableIdentity,
		DisableIndentity:        .DisableIndentity,
		IdentitySuffix:          .IdentitySuffix,
		FailingTimeoutSeconds:   .FailingTimeoutSeconds,
		TLSConfig:               .TLSConfig,
		// If ClusterSlots is populated, then we probably have an artificial
		// cluster whose nodes are not in clustering mode (otherwise there isn't
		// much use for ClusterSlots config).  This means we cannot execute the
		// READONLY command against that node -- setting readOnly to false in such
		// situations in the options below will prevent that from happening.
		readOnly:                  .ReadOnly && .ClusterSlots == nil,
		UnstableResp3:             .UnstableResp3,
		MaintNotificationsConfig:  ,
		PushNotificationProcessor: .PushNotificationProcessor,
	}
}

//------------------------------------------------------------------------------

type clusterNode struct {
	Client *Client

	latency    atomic.Uint32
	generation atomic.Uint32
	failing    atomic.Uint32
	loaded     atomic.Uint32

	// last time the latency measurement was performed for the node, stored in nanoseconds from epoch
	lastLatencyMeasurement atomic.Int64
}

func newClusterNodeWithNodeAddress( *ClusterOptions, ,  string) *clusterNode {
	 := .clientOptions()
	.Addr = 
	.NodeAddress = 
	// The default value 0 never reaches this point: ClusterOptions.init
	// already sets ReadTimeout to 5s and WriteTimeout to ReadTimeout.
	// So a 0 here can only come from -1.
	// ClusterOptions.init maps -1 (no timeout) to 0, which Options.init
	// would turn into the 5s default.
	if .ReadTimeout == 0 {
		.ReadTimeout = -1
	}
	if .WriteTimeout == 0 {
		.WriteTimeout = -1
	}
	 := clusterNode{
		Client: .NewClient(),
	}

	.latency.Store(unmeasuredNodeLatencyMicros)
	if .RouteByLatency {
		go .updateLatency()
	}

	return &
}

func ( *clusterNode) () string {
	return .Client.String()
}

func ( *clusterNode) () error {
	return .Client.Close()
}

const maximumNodeLatency = 1 * time.Minute

// Latency held by a node from creation until its first probe completes. Deliberately distinct
// from maximumNodeLatency, which marks a node whose pings all failed - the two must stay
// separable, so this is compared for equality rather than as a ">= huge" threshold.
const (
	unmeasuredNodeLatencyMicros uint32 = math.MaxUint32
	unmeasuredNodeLatency              = time.Duration(unmeasuredNodeLatencyMicros) * time.Microsecond
)

func ( *clusterNode) () {
	const  = 10
	var  uint64

	 := 0
	for  := 0;  < ; ++ {
		time.Sleep(time.Duration(10+rand.Intn(10)) * time.Millisecond)

		 := time.Now()
		 := .Client.Ping(context.TODO()).Err()
		if  == nil {
			 += uint64(time.Since() / time.Microsecond)
			++
		}
	}

	var  float64
	if  == 0 {
		// If none of the pings worked, set latency to some arbitrarily high value so this node gets
		// least priority.
		 = float64(maximumNodeLatency / time.Microsecond)
	} else {
		 = float64() / float64()
	}
	.latency.Store(uint32( + 0.5))
	.SetLastLatencyMeasurement(time.Now())
}

func ( *clusterNode) () time.Duration {
	 := .latency.Load()
	return time.Duration() * time.Microsecond
}

func ( *clusterNode) () {
	.failing.Store(uint32(time.Now().Unix()))
	.loaded.Store(0)
}

func ( *clusterNode) () bool {
	 := int64(.Client.opt.FailingTimeoutSeconds)

	 := .failing.Load()
	if  == 0 {
		return false
	}
	if time.Now().Unix()-int64() <  {
		return true
	}
	.failing.Store(0)
	return false
}

func ( *clusterNode) () uint32 {
	return .generation.Load()
}

func ( *clusterNode) () int64 {
	return .lastLatencyMeasurement.Load()
}

func ( *clusterNode) ( uint32) {
	for {
		 := .generation.Load()
		if  <  || .generation.CompareAndSwap(, ) {
			break
		}
	}
}

func ( *clusterNode) ( time.Time) {
	for {
		 := .lastLatencyMeasurement.Load()
		if .UnixNano() <  || .lastLatencyMeasurement.CompareAndSwap(, .UnixNano()) {
			break
		}
	}
}

func ( *clusterNode) () bool {
	 := .loaded.Load()
	if  == 1 {
		return false
	}

	// check if the node is loading
	,  := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer ()

	 := .Client.Ping().Err()
	 :=  != nil && isLoadingError()
	if ! {
		.loaded.Store(1)
	}
	return 
}

//------------------------------------------------------------------------------

type clusterNodes struct {
	opt *ClusterOptions

	mu          sync.RWMutex
	addrs       []string
	nodes       map[string]*clusterNode
	activeAddrs []string
	closed      bool
	onNewNode   []func(rdb *Client)

	generation atomic.Uint32
}

func newClusterNodes( *ClusterOptions) *clusterNodes {
	return &clusterNodes{
		opt:   ,
		addrs: .Addrs,
		nodes: make(map[string]*clusterNode),
	}
}

func ( *clusterNodes) () error {
	.mu.Lock()
	defer .mu.Unlock()

	if .closed {
		return nil
	}
	.closed = true

	var  error
	for ,  := range .nodes {
		if  := .Client.Close();  != nil &&  == nil {
			 = 
		}
	}

	.nodes = nil
	.activeAddrs = nil

	return 
}

func ( *clusterNodes) ( func( *Client)) {
	.mu.Lock()
	.onNewNode = append(.onNewNode, )
	.mu.Unlock()
}

func ( *clusterNodes) () ([]string, error) {
	var  []string

	.mu.RLock()
	 := .closed //nolint:ifshort
	if ! {
		if len(.activeAddrs) > 0 {
			 = make([]string, len(.activeAddrs))
			copy(, .activeAddrs)
		} else {
			 = make([]string, len(.addrs))
			copy(, .addrs)
		}
	}
	.mu.RUnlock()

	if  {
		return nil, pool.ErrClosed
	}
	if len() == 0 {
		return nil, errClusterNoNodes
	}
	return , nil
}

func ( *clusterNodes) () uint32 {
	return .generation.Add(1)
}

// GC removes unused nodes.
func ( *clusterNodes) ( uint32) {
	var  []*clusterNode

	.mu.Lock()

	.activeAddrs = .activeAddrs[:0]
	 := time.Now()
	for ,  := range .nodes {
		if .Generation() >=  {
			.activeAddrs = append(.activeAddrs, )
			if .opt.RouteByLatency && .LastLatencyMeasurement() < .Add(-minLatencyMeasurementInterval).UnixNano() {
				go .updateLatency()
			}
			continue
		}

		delete(.nodes, )
		 = append(, )
	}

	.mu.Unlock()

	for ,  := range  {
		_ = .Client.Close()
	}
}

func ( *clusterNodes) ( string) (*clusterNode, error) {
	return .GetOrCreateWithNodeAddress(, "")
}

func ( *clusterNodes) (,  string) (*clusterNode, error) {
	,  := .get()
	if  != nil {
		return nil, 
	}
	if  != nil {
		return , nil
	}

	.mu.Lock()
	defer .mu.Unlock()

	if .closed {
		return nil, pool.ErrClosed
	}

	,  := .nodes[]
	if  {
		return , nil
	}

	 = newClusterNodeWithNodeAddress(.opt, , )
	for ,  := range .onNewNode {
		(.Client)
	}

	.addrs = appendIfNotExist(.addrs, )
	.nodes[] = 

	return , nil
}

func ( *clusterNodes) ( string) (*clusterNode, error) {
	.mu.RLock()
	defer .mu.RUnlock()

	if .closed {
		return nil, pool.ErrClosed
	}
	return .nodes[], nil
}

func ( *clusterNodes) () ([]*clusterNode, error) {
	.mu.RLock()
	defer .mu.RUnlock()

	if .closed {
		return nil, pool.ErrClosed
	}

	 := make([]*clusterNode, 0, len(.nodes))
	for ,  := range .nodes {
		 = append(, )
	}
	return , nil
}

func ( *clusterNodes) () (*clusterNode, error) {
	,  := .Addrs()
	if  != nil {
		return nil, 
	}

	 := rand.Intn(len())
	return .GetOrCreate([])
}

//------------------------------------------------------------------------------

type clusterSlot struct {
	start int
	end   int
	nodes []*clusterNode

	// Round-robin cursor over the nodes inside the RouteByLatencyTolerance band. Latency
	// decides only which nodes are in the band; within it they are treated as equally close
	// and picked in turn, so this does not order them. Per slot on purpose: a counter shared
	// across slots is advanced by the other slots between two visits to this one, so with a
	// regular interleaving each slot keeps landing on the same candidate index.
	latencyBandNodeCursor atomic.Uint32
}

type clusterState struct {
	nodes   *clusterNodes
	Masters []*clusterNode
	Slaves  []*clusterNode

	slots []*clusterSlot

	generation uint32
	createdAt  time.Time
}

func newClusterState(
	 *clusterNodes,  []ClusterSlot,  string,
) (*clusterState, error) {
	 := clusterState{
		nodes: ,

		slots: make([]*clusterSlot, 0, len()),

		generation: .NextGeneration(),
		createdAt:  time.Now(),
	}

	, ,  := net.SplitHostPort()
	 := isLoopback()

	for ,  := range  {
		var  []*clusterNode
		for ,  := range .Nodes {
			// slotNode.Addr is the node address from CLUSTER SLOTS
			 := .Addr
			 := 
			if ! {
				 = replaceLoopbackHost(, )
			}
			// TLS-only clusters (`--port 0 --tls-port 6379`) report port 0
			// in CLUSTER SLOTS. Fall back to the origin port — by definition
			// reachable, since it is the port that returned this slot map.
			// See https://github.com/redis/go-redis/issues/3726.
			 = replaceZeroPort(, )

			,  := .nodes.GetOrCreateWithNodeAddress(, )
			if  != nil {
				return nil, 
			}

			.SetGeneration(.generation)
			 = append(, )

			if  == 0 {
				.Masters = appendIfNotExist(.Masters, )
			} else {
				.Slaves = appendIfNotExist(.Slaves, )
			}
		}

		.slots = append(.slots, &clusterSlot{
			start: .Start,
			end:   .End,
			nodes: ,
		})
	}

	slices.SortFunc(.slots, func(,  *clusterSlot) int {
		return cmp.Compare(.start, .start)
	})

	time.AfterFunc(time.Minute, func() {
		.GC(.generation)
	})

	return &, nil
}

func replaceLoopbackHost(,  string) string {
	, ,  := net.SplitHostPort()
	if  != nil {
		return 
	}

	 := net.ParseIP()
	if  == nil {
		return 
	}

	if !.IsLoopback() {
		return 
	}

	// Use origin host which is not loopback and node port.
	return net.JoinHostPort(, )
}

// replaceZeroPort substitutes originPort for a node port of "0", which is
// what CLUSTER SLOTS reports for TLS-only clusters started with
// `--port 0 --tls-port <port>`. Non-zero ports and addresses without a
// recoverable origin port are returned unchanged.
func replaceZeroPort(,  string) string {
	if  == "" ||  == "0" {
		return 
	}
	, ,  := net.SplitHostPort()
	if  != nil ||  != "0" {
		return 
	}
	return net.JoinHostPort(, )
}

// isLoopback returns true if the host is a loopback address.
// For IP addresses, it uses net.IP.IsLoopback().
// For hostnames, it recognizes well-known loopback hostnames like "localhost"
// and Docker-specific loopback patterns like "*.docker.internal".
func isLoopback( string) bool {
	 := net.ParseIP()
	if  != nil {
		return .IsLoopback()
	}

	if strings.ToLower() == "localhost" {
		return true
	}

	if strings.HasSuffix(strings.ToLower(), ".docker.internal") {
		return true
	}

	return false
}

func ( *clusterState) ( int) (*clusterNode, error) {
	 := .slotNodes()
	if len() > 0 {
		return [0], nil
	}
	return .nodes.Random()
}

func ( *clusterState) ( int) (*clusterNode, error) {
	 := .slotNodes()
	switch len() {
	case 0:
		return .nodes.Random()
	case 1:
		return [0], nil
	case 2:
		 := [1]
		if !.Failing() && !.Loading() {
			return , nil
		}
		return [0], nil
	default:
		var  *clusterNode
		for  := 0;  < 10; ++ {
			 := rand.Intn(len()-1) + 1
			 = []
			if !.Failing() && !.Loading() {
				return , nil
			}
		}

		// All slaves are loading - use master.
		return [0], nil
	}
}

func ( *clusterState) ( int) (*clusterNode, error) {
	 := .slotNodes()
	if len() == 0 {
		return .nodes.Random()
	}

	 := true
	var (
		 *clusterNode
		           *clusterNode
		            time.Duration
	)

	// setting the max possible duration as zerovalue for minlatency
	 = time.Duration(math.MaxInt64)

	 := time.Duration(math.MaxInt64)

	for ,  := range  {
		// Sampled once: Latency() reads an atomic the background probe writes, so two
		// reads in one iteration can disagree.
		 := .Latency()

		if  == nil ||  <  {
			 = 
			 = 
		}

		// Tracked independently of the minimum above. Nesting this inside that branch
		// meant a healthy node was only ever considered when it was also the outright
		// fastest - so a failing node with lower latency (a refused connection fails
		// fast, and often has the lowest measured latency of the slot) hid every
		// healthy node behind it, and the slot fell through to the all-failing path.
		if !.Failing() && ( == nil ||  < ) {
			 = 
			 = 
			 = false
		}
	}

	// pick the healthly node with the lowest latency
	if ! &&  != nil {
		return , nil
	}

	// if all nodes are failing, we will pick the temporarily failing node with lowest latency
	if  < maximumNodeLatency &&  != nil {
		internal.Logger.Printf(context.TODO(), "redis: all nodes are marked as failed, picking the temporarily failing node with lowest latency")
		return , nil
	}

	// If all nodes are having the maximum latency(all pings are failing) - return a random node across the cluster
	internal.Logger.Printf(context.TODO(), "redis: pings to all nodes are failing, picking a random node across the cluster")
	return .nodes.Random()
}

// slotNodeWithinLatency picks from the healthy nodes whose latency is within tolerance of the
// fastest one, rotating across them so equally-close nodes share the read traffic. Used only
// when RouteByLatencyTolerance is set; slotClosestNode keeps the strict-minimum behaviour and
// is left untouched for everyone else.
func ( *clusterState) ( int,  time.Duration) (*clusterNode, error) {
	 := .slotEntry()
	if  == nil || len(.nodes) == 0 {
		return .nodes.Random()
	}
	 := .nodes

	// Latency and health are sampled once per node. The background probe updates them
	// concurrently, so re-reading would let the candidate set disagree with the minimum it
	// is compared against - and could leave that set empty.
	type  struct {
		    *clusterNode
		 time.Duration
	}

	var (
		            = make([], 0, len())
		        *clusterNode
		 *clusterNode
		         = time.Duration(math.MaxInt64)
		  = time.Duration(math.MaxInt64)
		 bool
	)

	for ,  := range  {
		 := .Latency()
		if  <  {
			,  = , 
		}

		if .Failing() {
			continue
		}

		 = append(, {: , : })

		// Derived from the latency just captured, not from a second read of the node.
		// updateLatency publishes the latency and its timestamp as two separate stores, so
		// reading the timestamp here could observe a probe that landed after the latency
		// above was sampled - marking the set measured while every sampled latency is still
		// a sentinel, which is exactly the case this guards.
		if  != unmeasuredNodeLatency {
			 = true
		}

		// Tracked separately: a healthy node that is not the outright fastest must still be
		// preferred over a failing one.
		if  <  {
			,  = , 
		}
	}

	if  != nil {
		// Until the first probe lands, every node still holds the sentinel latency stored by
		// newClusterNodeWithNodeAddress, so every difference is zero and any positive tolerance
		// would admit the whole slot - scattering startup reads across distant zones instead of
		// preserving locality. Keep strict selection until at least one measurement exists; a
		// mix needs no special case, since an unmeasured node's sentinel latency puts it far
		// outside the band of any measured one.
		if ! {
			return , nil
		}

		 := make([]*clusterNode, 0, len())
		for ,  := range  {
			// Subtraction rather than minHealthyLatency+tolerance, which would overflow for
			// a very large tolerance. Always true for closestHealthyNode, so candidates is
			// never empty here.
			if .- <=  {
				 = append(, .)
			}
		}

		// Drop nodes that are still loading, matching slotSlaveNode. Checked here rather than
		// in the pass above so Loading() - which can cost a Ping when the node is not known
		// loaded - is only paid for nodes actually eligible for this read. Widening the
		// candidate set is what makes this matter: under a strict minimum a loading replica
		// has to be the fastest to be picked, within a tolerance band it merely has to be
		// close, and a replica is loading precisely after the full resync that a too-small
		// replication backlog causes.
		 := [:0]
		for ,  := range  {
			if !.Loading() {
				 = append(, )
			}
		}

		if len() == 0 {
			// Every node inside the band is loading. closestHealthyNode is itself in the band,
			// so returning it hands back a node we just observed loading. Widen the search to
			// the healthy nodes outside the band and take the closest ready one - which in a
			// multi-AZ layout is typically the master, still serving while the local replicas
			// reload together after a resync. Only reached in this exceptional case, so the
			// extra Loading() calls are off the hot path, and the latency comparison is
			// evaluated first so most of them are skipped.
			var (
				        *clusterNode
				 = time.Duration(math.MaxInt64)
			)
			for ,  := range  {
				if .- <=  {
					continue // in the band, already known to be loading
				}
				if . <  && !..Loading() {
					,  = ., .
				}
			}
			if  != nil {
				return , nil
			}

			// Nothing is ready anywhere. Return the closest healthy node so the caller still
			// gets a node to retry against, which is what this path did before the filter.
			return , nil
		}

		if len() == 1 {
			return [0], nil
		}

		// Reduced in the unsigned domain: the cursor wraps, and on 32-bit builds converting a
		// value past 2^31 to int before the modulo would make the index negative.
		return [(.latencyBandNodeCursor.Add(1)-1)%uint32(len())], nil
	}

	// Every node is failing. Fall back to the least-slow one, so a transient failure does
	// not take the slot down.
	if  < maximumNodeLatency &&  != nil {
		internal.Logger.Printf(context.TODO(), "redis: all nodes are marked as failed, picking the temporarily failing node with lowest latency")
		return , nil
	}

	// If all nodes are having the maximum latency(all pings are failing) - return a random node across the cluster
	internal.Logger.Printf(context.TODO(), "redis: pings to all nodes are failing, picking a random node across the cluster")
	return .nodes.Random()
}

func ( *clusterState) ( int) (*clusterNode, error) {
	 := .slotNodes()
	if len() == 0 {
		return .nodes.Random()
	}
	if len() == 1 {
		return [0], nil
	}
	 := rand.Perm(len())
	for ,  := range  {
		if  := []; !.Failing() {
			return , nil
		}
	}
	return [[0]], nil
}

func ( *clusterState) ( int,  routing.ShardPicker) (*clusterNode, error) {
	 := .slotNodes()
	if len() == 0 {
		return .nodes.Random()
	}

	// nodes[0] is master, nodes[1:] are slaves
	// First, try all slave nodes for this slot using ShardPicker order
	 := [1:]
	if len() > 0 {
		for  := 0;  < len(); ++ {
			 := .Next(len())
			 := []
			if !.Failing() && !.Loading() {
				return , nil
			}
		}
	}

	// All slaves are failing or loading - return master
	return [0], nil
}

func ( *clusterState) ( int) *clusterSlot {
	 := sort.Search(len(.slots), func( int) bool {
		return .slots[].end >= 
	})
	if  >= len(.slots) {
		return nil
	}
	 := .slots[]
	if  >= .start &&  <= .end {
		return 
	}
	return nil
}

func ( *clusterState) ( int) []*clusterNode {
	if  := .slotEntry();  != nil {
		return .nodes
	}
	return nil
}

//------------------------------------------------------------------------------

type clusterStateHolder struct {
	load func(ctx context.Context) (*clusterState, error)

	reloadInterval time.Duration
	state          atomic.Value
	reloading      atomic.Uint32
	reloadPending  atomic.Uint32 // set to 1 when reload is requested during active reload
}

func newClusterStateHolder( func( context.Context) (*clusterState, error),  time.Duration) *clusterStateHolder {
	return &clusterStateHolder{
		load:           ,
		reloadInterval: ,
	}
}

func ( *clusterStateHolder) ( context.Context) (*clusterState, error) {
	,  := .load()
	if  != nil {
		return nil, 
	}
	.state.Store()
	return , nil
}

func ( *clusterStateHolder) () {
	// If already reloading, mark that another reload is pending
	if !.reloading.CompareAndSwap(0, 1) {
		.reloadPending.Store(1)
		return
	}

	go func() {
		for {
			,  := .Reload(context.Background())
			if  != nil {
				.reloadPending.Store(0)
				.reloading.Store(0)
				return
			}

			// Clear pending flag after reload completes, before cooldown
			// This captures notifications that arrived during the reload
			.reloadPending.Store(0)

			// Wait cooldown period
			time.Sleep(200 * time.Millisecond)

			// Check if another reload was requested during cooldown
			if .reloadPending.Load() == 0 {
				// No pending reload, we're done
				.reloading.Store(0)
				return
			}

			// Pending reload requested, loop to reload again
		}
	}()
}

func ( *clusterStateHolder) ( context.Context) (*clusterState, error) {
	 := .state.Load()
	if  == nil {
		return .Reload()
	}

	 := .(*clusterState)
	if time.Since(.createdAt) > .reloadInterval {
		.LazyReload()
	}
	return , nil
}

func ( *clusterStateHolder) ( context.Context) (*clusterState, error) {
	,  := .Reload()
	if  == nil {
		return , nil
	}
	return .Get()
}

//------------------------------------------------------------------------------

// ClusterClient is a Redis Cluster client representing a pool of zero
// or more underlying connections. It's safe for concurrent use by
// multiple goroutines.
type ClusterClient struct {
	opt             *ClusterOptions
	nodes           *clusterNodes
	state           *clusterStateHolder
	cmdsInfoCache   *cmdsInfoCache
	cmdInfoResolver *commandInfoResolver
	cmdable
	hooksMixin

	// himport is the cluster-wide HIMPORT fieldset registry, shared with
	// every node client (masters and replicas alike — roles change with the
	// topology) so any connection serving an HIMPORT SET can lazily replay
	// the PREPARE (see himport.go, himport_cluster.go).
	himport *himportRegistry

	autopipelinerMu     *sync.Mutex    // guards the autopipeliner fields against concurrent first-call creation
	autopipeliner       *AutoPipeliner // blocking face (ClusterClient.AutoPipeline)
	asyncAutopipeliner  *AutoPipeliner // deferred face (ClusterClient.AsyncAutoPipeline)
	autopipelinerClosed bool           // set by Close: refuse to resurrect a pipeliner on a closed client
}

// NewClusterClient returns a Redis Cluster client as described in
// https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec.
// Passing nil ClusterOptions will cause a panic.
func ( *ClusterOptions) *ClusterClient {
	if  == nil {
		panic("redis: NewClusterClient nil options")
	}
	.init()

	 := &ClusterClient{
		opt:             ,
		nodes:           newClusterNodes(),
		himport:         newHImportRegistry(),
		autopipelinerMu: &sync.Mutex{},
	}

	// Every node client shares the cluster-wide fieldset registry, replicas
	// included: a promoted replica's connections carry no prepared flags, so
	// the first HIMPORT SET routed to it replays the PREPARE lazily.
	.nodes.OnNewNode(func( *Client) {
		.himport = .himport
	})

	.cmdsInfoCache = newCmdsInfoCache(.cmdsInfo)

	.state = newClusterStateHolder(.loadState, .ClusterStateReloadInterval)

	.SetCommandInfoResolver(NewDefaultCommandPolicyResolver())

	.cmdable = .Process
	.initHooks(hooks{
		dial:       nil,
		process:    .process,
		pipeline:   .processPipeline,
		txPipeline: .processTxPipeline,
	})

	// Set up SMIGRATED notification handling for cluster state reload
	// When a node client receives a SMIGRATED notification, it should trigger
	// cluster state reload on the parent ClusterClient
	if .MaintNotificationsConfig != nil {
		.nodes.OnNewNode(func( *Client) {
			 := .GetMaintNotificationsManager()
			if  != nil {
				.SetClusterStateReloadCallback(func( context.Context,  string,  []string) {
					// Log the migration details for now
					if internal.LogLevel.InfoOrAbove() {
						internal.Logger.Printf(, "cluster: slots %v migrated to %s, reloading cluster state", , )
					}
					// Currently we reload the entire cluster state
					// In the future, this could be optimized to reload only the specific slots
					.state.LazyReload()
				})
			}
		})
	}

	return 
}

// Options returns read-only *ClusterOptions that were used to create the client.
// Any alteration of the returned *ClusterOptions may result in undefined behaviour.
func ( *ClusterClient) () *ClusterOptions {
	return .opt
}

// ReloadState reloads cluster state. If available it calls ClusterSlots func
// to get cluster slots information.
func ( *ClusterClient) ( context.Context) {
	.state.LazyReload()
}

// Close closes the cluster client, releasing any open resources.
//
// It is rare to Close a ClusterClient, as the ClusterClient is meant
// to be long-lived and shared between many goroutines.
func ( *ClusterClient) () error {
	// Stop both cached autopipeliners (blocking and async faces) before
	// closing nodes, so its background flusher goroutines don't outlive the
	// client. AutoPipeliner.Close is idempotent and nil-safe here.
	.autopipelinerMu.Lock()
	,  := .autopipeliner, .asyncAutopipeliner
	.autopipeliner, .asyncAutopipeliner = nil, nil
	.autopipelinerClosed = true // getters refuse to resurrect on a closed client
	.autopipelinerMu.Unlock()
	var  error
	for ,  := range []*AutoPipeliner{, } {
		if  != nil {
			if  := .Close();  != nil &&  == nil {
				 = 
			}
		}
	}
	if  := .nodes.Close();  != nil &&  == nil {
		 = 
	}
	return 
}

func ( *ClusterClient) ( context.Context,  Cmder) error {
	 := .processHook(, )
	.SetErr()
	return 
}

func ( *ClusterClient) ( context.Context,  Cmder) error {
	 := .cmdSlot(, -1)
	var  *clusterNode
	var  bool
	var  bool
	var  error
	for  := 0;  <= .opt.MaxRedirects; ++ {
		// MOVED and ASK responses are not transient errors that require retry delay; they
		// should be attempted immediately.
		if  > 0 && ! && ! {
			if  := internal.Sleep(, .retryBackoff());  != nil {
				return 
			}
		}

		if  == nil {
			var  error
			if !.opt.DisableRoutingPolicies && .opt.ShardPicker != nil {
				,  = .cmdNodeWithShardPicker(, .Name(), , .opt.ShardPicker)
			} else {
				,  = .cmdNode(, .Name(), )
			}
			if  != nil {
				return 
			}
		}

		if  {
			 = false
			 := .Client.Pipeline()
			_ = .Process(, NewCmd(, "asking"))
			_ = .Process(, )
			_,  = .Exec()
		} else {
			if !.opt.DisableRoutingPolicies {
				 = .routeAndRun(, , )
			} else {
				 = .Client.Process(, )
			}
		}

		// If there is no error - we are done.
		if  == nil {
			return nil
		}
		if  := isReadOnlyError();  ||  == pool.ErrClosed {
			if  {
				.state.LazyReload()
			}
			 = nil
			continue
		}

		// If slave is loading - pick another node.
		if .opt.ReadOnly && isLoadingError() {
			.MarkAsFailing()
			 = nil
			continue
		}

		var  string
		, ,  = isMovedError()
		if  ||  {
			.state.LazyReload()

			// Record error metrics
			if  := pool.GetMetricErrorCallback();  != nil {
				 := "MOVED"
				 := "MOVED"
				if  {
					 = "ASK"
					 = "ASK"
				}
				// MOVED/ASK are not internal errors, and this is the first attempt (retry count = 0)
				(, , nil, , false, 0)
			}

			var  error
			,  = .nodes.GetOrCreate()
			if  != nil {
				return 
			}
			continue
		}

		if shouldRetry(, .readTimeout() == nil) && !.NoRetry() {
			// First retry the same node.
			if  == 0 {
				continue
			}

			// Second try another node.
			.MarkAsFailing()
			 = nil
			continue
		}

		return 
	}
	return 
}

func ( *ClusterClient) ( func( *Client)) {
	.nodes.OnNewNode()
}

// ForEachMaster concurrently calls the fn on each master node in the cluster.
// It returns the first error if any.
func ( *ClusterClient) (
	 context.Context,
	 func( context.Context,  *Client) error,
) error {
	,  := .state.ReloadOrGet()
	if  != nil {
		return 
	}

	var  sync.WaitGroup
	 := make(chan error, 1)

	for ,  := range .Masters {
		.Add(1)
		go func( *clusterNode) {
			defer .Done()
			 := (, .Client)
			if  != nil {
				select {
				case  <- :
				default:
				}
			}
		}()
	}

	.Wait()

	select {
	case  := <-:
		return 
	default:
		return nil
	}
}

// ForEachSlave concurrently calls the fn on each slave node in the cluster.
// It returns the first error if any.
func ( *ClusterClient) (
	 context.Context,
	 func( context.Context,  *Client) error,
) error {
	,  := .state.ReloadOrGet()
	if  != nil {
		return 
	}

	var  sync.WaitGroup
	 := make(chan error, 1)

	for ,  := range .Slaves {
		.Add(1)
		go func( *clusterNode) {
			defer .Done()
			 := (, .Client)
			if  != nil {
				select {
				case  <- :
				default:
				}
			}
		}()
	}

	.Wait()

	select {
	case  := <-:
		return 
	default:
		return nil
	}
}

// ForEachShard concurrently calls the fn on each known node in the cluster.
// It returns the first error if any.
func ( *ClusterClient) (
	 context.Context,
	 func( context.Context,  *Client) error,
) error {
	,  := .state.ReloadOrGet()
	if  != nil {
		return 
	}

	var  sync.WaitGroup
	 := make(chan error, 1)

	 := func( *clusterNode) {
		defer .Done()
		 := (, .Client)
		if  != nil {
			select {
			case  <- :
			default:
			}
		}
	}

	for ,  := range .Masters {
		.Add(1)
		go ()
	}
	for ,  := range .Slaves {
		.Add(1)
		go ()
	}

	.Wait()

	select {
	case  := <-:
		return 
	default:
		return nil
	}
}

// PoolStats returns accumulated connection pool stats.
func ( *ClusterClient) () *PoolStats {
	var  PoolStats
	var  pool.Stats
	 := false

	,  := .state.Get(context.TODO())
	if  == nil {
		return &
	}

	 := func( *Client) {
		 := .connPool.Stats()
		.Hits += .Hits
		.Misses += .Misses
		.Timeouts += .Timeouts
		.WaitCount += .WaitCount
		.WaitDurationNs += .WaitDurationNs

		.TotalConns += .TotalConns
		.IdleConns += .IdleConns
		.StaleConns += .StaleConns

		// The dedicated pipeline pool is now created per node by default; fold its
		// stats into acc.PipelineStats so cluster monitoring reflects it too.
		if  := .getPipelinePool();  != nil {
			 := .Stats()
			.Hits += .Hits
			.Misses += .Misses
			.Timeouts += .Timeouts
			.WaitCount += .WaitCount
			.WaitDurationNs += .WaitDurationNs
			.TotalConns += .TotalConns
			.IdleConns += .IdleConns
			.StaleConns += .StaleConns
			 = true
		}
	}

	for ,  := range .Masters {
		(.Client)
	}
	for ,  := range .Slaves {
		(.Client)
	}

	if  {
		.PipelineStats = &
	}
	return &
}

func ( *ClusterClient) ( context.Context) (*clusterState, error) {
	if .opt.ClusterSlots != nil {
		,  := .opt.ClusterSlots()
		if  != nil {
			return nil, 
		}
		return newClusterState(.nodes, , "")
	}

	,  := .nodes.Addrs()
	if  != nil {
		return nil, 
	}

	var  error

	for ,  := range rand.Perm(len()) {
		 := []

		,  := .nodes.GetOrCreate()
		if  != nil {
			if  == nil {
				 = 
			}
			continue
		}

		,  := .Client.ClusterSlots().Result()
		if  != nil {
			if  == nil {
				 = 
			}
			continue
		}

		return newClusterState(.nodes, , )
	}

	/*
	 * No node is connectable. It's possible that all nodes' IP has changed.
	 * Clear activeAddrs to let client be able to re-connect using the initial
	 * setting of the addresses (e.g. [redis-cluster-0:6379, redis-cluster-1:6379]),
	 * which might have chance to resolve domain name and get updated IP address.
	 */
	.nodes.mu.Lock()
	.nodes.activeAddrs = nil
	.nodes.mu.Unlock()

	return nil, 
}

func ( *ClusterClient) () Pipeliner {
	 := Pipeline{
		exec: pipelineExecer(.processPipelineHook),
	}
	.init()
	return &
}

// clusterAutoPipelineOptions applies the cluster shard-count default: commands
// are routed to shards by slot (see installAutoPipelineSharding), so unlike a
// standalone client — which defaults to a single deep queue — a cluster client
// wants several shards to keep concurrent nodes' batches separate. The caller's
// config is copied before the default is filled in, never mutated.
func clusterAutoPipelineOptions( *AutoPipelineOptions) *AutoPipelineOptions {
	 := *
	if .NumShards == 0 {
		.NumShards = numAutoPipelineShards()
	}
	// A cluster always routes by slot, so per-key order holds regardless of shard
	// count; mark it so construction's NumShards ordering check (which targets
	// round-robin sharding) does not reject the cluster default or an explicit
	// NumShards on the deferred (async) face.
	.contentSharded = true
	return &
}

// AutoPipeline returns the blocking autopipeliner for this cluster client: each
// command call blocks until executed (drop-in shape) while the engine batches
// concurrent callers into pipelines. Commands keep per-goroutine order; across
// nodes, ordering is per key (slot routing keeps a key on one shard and node
// sub-pipelines execute concurrently). Use AutoPipelineWithOptions to override
// DefaultBlockingAutoPipelineOptions. Cached/shared; first call's config wins.
// Close it (or the client) to release its goroutines.
//
// It returns an error if the supplied config is invalid (e.g. MaxConcurrentBatches>1
// without Unordered, or a negative size); on error no instance is cached.
//
// EXPERIMENTAL: this API is subject to change, use with caution.
func ( *ClusterClient) () (*AutoPipeliner, error) {
	return .AutoPipelineWithOptions(nil)
}

// AutoPipelineWithOptions is AutoPipeline with explicit options instead of
// ClusterOptions.AutoPipelineOptions / the default. Cached/shared; first call wins.
//
// EXPERIMENTAL: this API is subject to change, use with caution.
func ( *ClusterClient) ( *AutoPipelineOptions) (*AutoPipeliner, error) {
	return getOrCreateAutoPipeliner(.autopipelinerMu, &.autopipeliner, &.autopipelinerClosed, nil, nil, "", ,
		func() *AutoPipelineOptions {
			if .opt.AutoPipelineOptions != nil {
				return .opt.AutoPipelineOptions
			}
			return DefaultBlockingAutoPipelineOptions()
		},
		func( *AutoPipelineOptions) (*AutoPipeliner, error) {
			,  := newAutoPipeliner(, clusterAutoPipelineOptions(), true)
			if  != nil {
				return nil, 
			}
			.installAutoPipelineSharding()
			return , nil
		})
}

// installAutoPipelineSharding routes commands to shards by cluster slot so each
// shard's batch lands on a single master node, keeping per-node pipelines deep
// instead of splitting every batch across all nodes at flush. Cluster slots are
// contiguous per node, so bucketing by slot range (slot*shards/16384) keeps a
// node's slots together. Keyless commands hash to slot -1 → bucket 0; multi-node
// commands are already rejected from pipelines, so only single-node commands
// reach here.
func ( *ClusterClient) ( *AutoPipeliner) {
	// Reject commands whose request policy cannot ride a pipeline (ReqAllNodes/
	// ReqAllShards/ReqMultiShard) at submit, BEFORE they can join a merged
	// batch: mapCmdsByNode fails a whole mapping on such a command (user
	// pipelines are all-or-nothing), and one autopipeline caller must not be
	// able to poison unrelated callers' batches. Rejecting here also keeps the
	// lone-command fast path consistent with batched dispatch — the command is
	// refused regardless of what it happens to coalesce with.
	.setPreflight(func( context.Context,  Cmder) error {
		if .cmdInfoResolver == nil {
			return nil
		}
		if  := .cmdInfoResolver.GetCommandPolicy(, );  != nil && !.CanBeUsedInPipeline() {
			return fmt.Errorf(
				"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future", .Name(),
			)
		}
		return nil
	})
	// Commands whose routing is not slot-derived must not be coalesced: a solo
	// flush reaches ClusterClient.process and its special handling (FT.CURSOR
	// READ/DEL are sticky to the node holding the cursor), but inside a batch
	// mapCmdsByNode routes by slot and can hit the wrong shard — visible only
	// under concurrent traffic, which is the worst way to find it. Divert them
	// instead of rejecting: they work fine on their own connection (review
	// finding by codex on #3942).
	.setMustDivert(func( context.Context,  Cmder) bool {
		if .cmdInfoResolver == nil {
			return false
		}
		 := .cmdInfoResolver.GetCommandPolicy(, )
		return  != nil && .Request == routing.ReqSpecial
	})

	const  = 16384
	 := .numShards()
	.setShardFn(func( Cmder) int {
		// Compute the exact slot once and cache it on the command; the flush
		// router (mapCmdsByNode) reuses the cached value, so the slot is resolved
		// once per command, not twice. Keyless (slot -1) buckets to shard 0.
		 := .cmdSlot(, -1)
		if  < 0 {
			return 0
		}
		return  *  / 
	})
}

// AsyncAutoPipeline returns the deferred autopipeliner: command calls return
// immediately and the result accessors block. Submit a window then read results
// for the highest throughput. By default,
// ClusterOptions.AutoPipelineOptions is used if set, otherwise
// DefaultAutoPipelineOptions. Ordering across nodes is per key: slot routing
// keeps a key on one shard, and node sub-pipelines execute concurrently. Use
// AsyncAutoPipelineWithOptions to override. Cached/shared; first call's config wins.
//
// It returns an error if the supplied config is invalid (e.g. MaxConcurrentBatches>1
// without Unordered, or a negative size); on error no instance is cached.
//
// EXPERIMENTAL: this API is subject to change, use with caution.
func ( *ClusterClient) () (*AutoPipeliner, error) {
	return .AsyncAutoPipelineWithOptions(nil)
}

// AsyncAutoPipelineWithOptions is AsyncAutoPipeline with an explicit config
// instead of ClusterOptions.AutoPipelineOptions / the default. Cached/shared.
//
// EXPERIMENTAL: this API is subject to change, use with caution.
func ( *ClusterClient) ( *AutoPipelineOptions) (*AutoPipeliner, error) {
	return getOrCreateAutoPipeliner(.autopipelinerMu, &.asyncAutopipeliner, &.autopipelinerClosed, nil, nil, "", ,
		func() *AutoPipelineOptions {
			if .opt.AutoPipelineOptions != nil {
				return .opt.AutoPipelineOptions
			}
			return DefaultAutoPipelineOptions()
		},
		func( *AutoPipelineOptions) (*AutoPipeliner, error) {
			,  := newAutoPipeliner(, clusterAutoPipelineOptions(), false)
			if  != nil {
				return nil, 
			}
			.installAutoPipelineSharding()
			return , nil
		})
}

func ( *ClusterClient) ( context.Context,  func(Pipeliner) error) ([]Cmder, error) {
	return .Pipeline().Pipelined(, )
}

func ( *ClusterClient) ( context.Context,  []Cmder) error {
	// Only call time.Now() if pipeline operation duration callback is set to avoid overhead
	var  time.Time
	 := otel.GetPipelineOperationDurationCallback()
	if  != nil {
		 = time.Now()
	}
	 := 0

	 := newCmdsMap()

	if  := .mapCmdsByNode(, , );  != nil {
		setCmdsErr(, )
		if  != nil {
			 := time.Since()
			(, , "PIPELINE", len(), 1, , nil, 0)
		}
		return 
	}

	var  error
	for  := 0;  <= .opt.MaxRedirects; ++ {
		++
		if  > 0 {
			if  := internal.Sleep(, .retryBackoff());  != nil {
				setCmdsErr(, )
				if  != nil {
					 := time.Since()
					(, , "PIPELINE", len(), , , nil, 0)
				}
				return 
			}
		}

		 := newCmdsMap()
		var  sync.WaitGroup

		for ,  := range .m {
			.Add(1)
			go func( *clusterNode,  []Cmder) {
				defer .Done()
				.processPipelineNode(, , , )
			}(, )
		}

		.Wait()
		if len(.m) == 0 {
			break
		}
		 = 
		 = cmdsFirstErr()
	}

	// Record pipeline operation duration
	if  != nil {
		 := time.Since()
		 := cmdsFirstErr()
		if  == nil {
			 = 
		}
		(, , "PIPELINE", len(), , , nil, 0)
	}

	return cmdsFirstErr()
}

func ( *ClusterClient) ( context.Context,  *cmdsMap,  []Cmder) error {
	,  := .state.Get()
	if  != nil {
		return 
	}

	if .opt.ReadOnly && .cmdsAreReadOnly(, ) {
		for ,  := range  {
			var  *routing.CommandPolicy
			if .cmdInfoResolver != nil {
				 = .cmdInfoResolver.GetCommandPolicy(, )
			}
			if  != nil && !.CanBeUsedInPipeline() {
				// All-or-nothing: a user Pipeline() relies on the whole batch
				// either dispatching or failing before anything executes, so a
				// non-pipelineable command fails the entire mapping pre-dispatch.
				// Autopipeline batches never reach here with such a command: the
				// cluster face rejects them at submit (see the preflight installed
				// by installAutoPipelineSharding), so one caller's bad command
				// cannot poison a merged batch.
				 := fmt.Errorf(
					"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future", .Name(),
				)
				setCmdsErr(, )
				return 
			}
			 := .cmdSlot(, -1)
			var  *clusterNode
			// For keyless commands (slot == -1), use ShardPicker if routing policies are enabled
			if  == -1 && !.opt.DisableRoutingPolicies && .opt.ShardPicker != nil {
				if len(.Masters) == 0 {
					return errClusterNoNodes
				}
				// For read-only keyless commands, pick from all nodes (masters + slaves).
				// Index directly instead of building a combined slice, which would
				// append into the shared snapshot's spare capacity and race.
				 := .opt.ShardPicker.Next(len(.Masters) + len(.Slaves))
				if  < len(.Masters) {
					 = .Masters[]
				} else {
					 = .Slaves[-len(.Masters)]
				}
			} else {
				,  = .slotReadOnlyNode(, )
				if  != nil {
					return 
				}
			}
			.Add(, )
		}
		return nil
	}

	for ,  := range  {
		var  *routing.CommandPolicy
		if .cmdInfoResolver != nil {
			 = .cmdInfoResolver.GetCommandPolicy(, )
		}
		if  != nil && !.CanBeUsedInPipeline() {
			// All-or-nothing: a user Pipeline() relies on the whole batch
			// either dispatching or failing before anything executes, so a
			// non-pipelineable command fails the entire mapping pre-dispatch.
			// Autopipeline batches never reach here with such a command: the
			// cluster face rejects them at submit (see the preflight installed
			// by installAutoPipelineSharding), so one caller's bad command
			// cannot poison a merged batch.
			 := fmt.Errorf(
				"redis: cannot pipeline command %q with request policy ReqAllNodes/ReqAllShards/ReqMultiShard; Note: This behavior is subject to change in the future", .Name(),
			)
			setCmdsErr(, )
			return 
		}
		 := .cmdSlot(, -1)
		var  *clusterNode
		// For keyless commands (slot == -1), use ShardPicker if routing policies are enabled
		if  == -1 && !.opt.DisableRoutingPolicies && .opt.ShardPicker != nil {
			if len(.Masters) == 0 {
				return errClusterNoNodes
			}
			 := .opt.ShardPicker.Next(len(.Masters))
			 = .Masters[]
		} else {
			,  = .slotMasterNode()
			if  != nil {
				return 
			}
		}
		.Add(, )
	}
	return nil
}

func ( *ClusterClient) ( context.Context,  []Cmder) bool {
	for ,  := range  {
		 := .cmdInfo(, .Name())
		if  == nil || !.ReadOnly {
			return false
		}
	}
	return true
}

func ( *ClusterClient) (
	 context.Context,  *clusterNode,  []Cmder,  *cmdsMap,
) {
	// This call runs on a per-node fan-out goroutine, so register it as an
	// executor of every deferred-face batch among cmds: a NODE-level hook
	// (OnNewNode — redisotel's tracing) reading a result before next() must
	// get the not-yet-executed view from the accessor guards instead of
	// blocking on a batch only this call chain completes (reproduced as a
	// permanent wedge with a rediscmd-shaped Err() peek).
	 := registerBatchExecutors()
	defer ()

	// executed guards against a node-level hook short-circuiting (returning
	// without calling next): the inner callback then never runs, and without
	// surfacing the chain's error the cluster pipeline would report success
	// for commands that were never sent.
	 := false
	 := .Client.withProcessPipelineHook(, , func( context.Context,  []Cmder) error {
		 = true
		// Acquire through the node's dedicated pipeline pool when one is
		// configured (Pipeline*BufferSize propagate to node clients via
		// clientOptions); withPipelineConn falls back to the main pool
		// otherwise, preserving the previous behavior. entered distinguishes
		// an acquisition failure (fn never ran) from an execution error.
		 := false
		 := .Client.withPipelineConn(, func( context.Context,  *pool.Conn) error {
			 = true
			return .processPipelineNodeConn(, , , , )
		})
		if  != nil && ! {
			if !isContextError() {
				.MarkAsFailing()
			}
			_ = .mapCmdsByNode(, , )
			setCmdsErr(, )
		}
		return 
	})
	if ! {
		// A hook returned without calling next. If it supplied an error that is
		// a deliberate abort: set it and do not remap for retry (a retry would
		// re-run the same hook). If it returned nil it short-circuited
		// SUCCESSFULLY, having served the batch itself — the same thing a plain
		// Pipeline hook may do — so setCmdsErr(nil) leaves the values it set
		// intact (review finding by codex on #3942).
		setCmdsErr(, )
		return
	}
	if  != nil && cmdsFirstErr() == nil {
		// Post-next verdict from a node-level hook on an all-clean sub-batch:
		// the exec fully succeeded, so the error can only be the hook's own —
		// apply it, mirroring AutoPipeliner.dispatchCmds. On a mixed batch the
		// exec-recorded outcomes win (hooks conventionally echo next's error,
		// and stamping the echo would overwrite successful replies). No remap:
		// retrying would re-run the same hook.
		setCmdsErr(, )
	}
}

func ( *ClusterClient) (
	 context.Context,  *clusterNode,  *pool.Conn,  []Cmder,  *cmdsMap,
) error {
	// HIMPORT bookkeeping: pending discards for this session and PREPAREs
	// for registered fieldsets the batch references get written ahead of
	// the batch (see himport.go).
	 := .Client.himportInjectedCmds(, , )

	if  := .WithWriter(.context(), .opt.WriteTimeout, func( *proto.Writer) error {
		for ,  := range  {
			if  := writeCmd(, );  != nil {
				return 
			}
		}
		return writeCmds(, )
	});  != nil {
		if isBadConn(, false, .Client.getAddr()) {
			.MarkAsFailing()
		}
		if shouldRetry(, true) && !cmdsContainNoRetry() {
			_ = .mapCmdsByNode(, , )
		}
		setCmdsErr(, )
		return 
	}

	return .WithReader(.context(), .opt.ReadTimeout, func( *proto.Reader) error {
		if  := .Client.himportReadInjectedReplies(, , , );  != nil {
			// Transport error with the batch replies unread: same handling
			// as a write error — the batch may be retried on a fresh
			// connection.
			if isBadConn(, false, .Client.getAddr()) {
				.MarkAsFailing()
			}
			if shouldRetry(, true) && !cmdsContainNoRetry() {
				_ = .mapCmdsByNode(, , )
			}
			setCmdsErr(, )
			return 
		}
		 := .pipelineReadCmds(, , , , , )
		if  == nil || isRedisError() {
			.Client.himportAfterBatch(, , )
			// SETs of registered fieldsets that lost their session state
			// re-queue for the next attempt, which re-prepares lazily —
			// the cluster equivalent of himportRetryFailedSets, bounded by
			// the pipeline's attempt budget. A non-nil redis error here
			// means pipelineReadCmds already re-queued the whole batch
			// (retryable first-command error); adding the SETs again would
			// duplicate them in the next attempt.
			if  == nil {
				.himportRequeueFailedSets(, , )
			}
		}
		return 
	})
}

func ( *ClusterClient) (
	 context.Context,
	 *clusterNode,
	 *pool.Conn,
	 *proto.Reader,
	 []Cmder,
	 *cmdsMap,
) error {
	for ,  := range  {
		// Drain any buffered RESP3 push notifications before reading each
		// reply — otherwise a push frame (e.g. a maintnotifications MOVING
		// notification) is consumed AS the command's reply and every
		// subsequent reply in the pipeline shifts by one command. The
		// standalone pipeline and the cluster TxPipeline read loops already
		// do this; this loop was the only push-blind reader, and the
		// autopipeliner routes all cluster traffic through it.
		if  := .Client.processPendingPushNotificationWithReader(, , );  != nil {
			internal.Logger.Printf(, "push: error processing pending notifications before reading reply: %v", )
		}
		 := .readReply()
		.SetErr()

		if  == nil {
			continue
		}

		if .checkMovedErr(, , , ) {
			continue
		}

		if .opt.ReadOnly && isBadConn(, false, .Client.getAddr()) {
			.MarkAsFailing()
		}

		if !isRedisError() {
			if shouldRetry(, true) && !cmdsContainNoRetry() {
				_ = .mapCmdsByNode(, , )
			}
			setCmdsErr([+1:], )
			return 
		}
	}

	// rawErr: execution path; never await an async command's batch here.
	if  := [0].rawErr();  != nil && shouldRetry(, true) && !cmdsContainNoRetry() {
		_ = .mapCmdsByNode(, , )
		return 
	}

	return nil
}

func ( *ClusterClient) (
	 context.Context,  Cmder,  error,  *cmdsMap,
) bool {
	, ,  := isMovedError()
	if ! && ! {
		return false
	}

	,  := .nodes.GetOrCreate()
	if  != nil {
		return false
	}

	if  {
		.state.LazyReload()
		.Add(, )
		return true
	}

	if  {
		.Add(, NewCmd(, "asking"), )
		return true
	}

	panic("not reached")
}

// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func ( *ClusterClient) () Pipeliner {
	 := Pipeline{
		exec: func( context.Context,  []Cmder) error {
			 = wrapMultiExec(, )
			return .processTxPipelineHook(, )
		},
	}
	.init()
	return &
}

func ( *ClusterClient) ( context.Context,  func(Pipeliner) error) ([]Cmder, error) {
	return .TxPipeline().Pipelined(, )
}

// A cluster tx pipeline sends MULTI, c1..cN, EXEC — N+2 commands, or N+3 with a
// leading ASKING — and always receives exactly that many replies, so every
// redirect/abort path leaves the connection clean.
//
// Possible reply sequences:
//	1. Slot owned here, no migration:
//	     +OK,  +QUEUED x N,  *N (array of N results)   -> success
//	2. Slot already migrated away:
//	     +OK,  -MOVED x N,  -EXECABORT                 -> re-route whole tx
//	3. Slot in migrating state (still owned here, keys draining out). Per
//	   cmd, the queue reply is +QUEUED / -ASK / -TRYAGAIN (keys present /
//	   all gone / some gone); any -ASK or -TRYAGAIN dirties the tx, so
//	   EXEC is -EXECABORT. Still N+2 replies, like the cases above:
//	     +OK,  (+QUEUED|-ASK|-TRYAGAIN) x N,  -EXECABORT  -> follow first redirect
//	4. Narrow race (all +QUEUED, slot moves before EXEC):
//	     +OK,  +QUEUED x N,  -MOVED <slot> <addr>         -> re-route whole tx
//	5. Non-cluster command error (arity / ACL / unknown):
//	     +OK,  +QUEUED..., -ERR...,  -EXECABORT           -> surface, not retryable
//	6. Narrow race (all +QUEUED, slot still migrating, keys drain before EXEC):
//	     +OK,  +QUEUED x N,  -ASK / -TRYAGAIN             -> re-route on -ASK, back off on -TRYAGAIN
//
// EXEC reply — the reply that decides the outcome:
//
//	*N                    success; read N per-command results
//	-EXECABORT            a queue-stage command failed; follow the first queue
//	                      redirect (MOVED/ASK/TRYAGAIN), else surface the trigger
//	-MOVED <slot> <addr>  case 4; re-route whole tx to addr, reload topology
//	-ASK <slot> <addr>    race: slot entered migrating state; re-route to addr
//	                      with a top-level ASKING before MULTI
//	-TRYAGAIN             race: migrating with split keys, or slot being trimmed
//	                      (CLUSTER_REDIR_TRIMMING on a write); back off and retry
//	                      the whole tx (same node still owns it)
//	-CLUSTERDOWN          cluster degraded; back off and retry whole tx
//
// ASK retry: the ASKING flag is NOT cleared between commands inside a MULTI
// so one top-level ASKING before MULTI covers the whole tx and lets the importing
// slot serve at EXEC. ASKING placed inside the MULTI would be queued and leave
// the flag unset during queueing, so the keyed commands would still get MOVED.
//
// Out of scope: WATCH's null-array EXEC and -CROSSSLOT;
// cluster TxPipeline is not used with WATCH and cross-slot is rejected client-side.

type txOutcomeKind int

const (
	txSuccess       txOutcomeKind = iota // transaction executed; per-command results are set
	txRetryMoved                         // MOVED: reload topology and re-route the whole tx
	txRetryAsk                           // ASK: re-route to the target with a top-level ASKING
	txRetryTryAgain                      // TRYAGAIN: back off and re-route the whole tx
	txRetryConn                          // connection/write/read failure: re-route the whole tx
	txFatal                              // non-retryable error; surface to the caller
)

// txOutcome is the result of a single tx attempt. err is the error to report
// when the redirect/retry loop is exhausted (or the fatal error to surface);
// addr is the ASK target; execErr is the EXEC reply error used to mark
// aborted commands; unreadReplies forces the connection to be discarded
// when the read loop exited before consuming all N+2 replies, leaving bytes
// on the wire.
type txOutcome struct {
	kind          txOutcomeKind
	err           error
	addr          string
	execErr       error
	unreadReplies bool
}

// txRedirect records the first queue-stage redirect (MOVED/ASK/TRYAGAIN) seen
// while reading +QUEUED replies. Redis dirties and aborts the transaction on
// any such reply, so the EXEC reply will be EXECABORT and the client must
// follow the recorded redirect with the whole transaction.
type txRedirect struct {
	moved    bool
	ask      bool
	tryAgain bool
	addr     string
	err      error
}

// errTxDirtyConn forces releaseConn to discard a connection that may still have
// unread transaction replies on it (an early exit before consuming all N+2).
var errTxDirtyConn = errors.New("redis: connection has unread transaction replies")

func ( *ClusterClient) ( context.Context,  []Cmder) ( error) {
	var  time.Time
	 := otel.GetPipelineOperationDurationCallback()
	if  != nil {
		 = time.Now()
	}
	 := 0
	var  error

	defer func() {
		if  == nil {
			return
		}
		 := cmp.Or(, cmdsFirstErr(), )
		(, time.Since(), "MULTI", len(), , , nil, 0)
	}()

	// Trim multi .. exec.
	 = [1 : len()-1]
	if len() == 0 {
		return nil
	}

	,  := .state.Get()
	if  != nil {
		setCmdsErr(, )
		return 
	}

	 := .slottedKeyedCommands(, )
	 := -1
	switch len() {
	case 0:
		 = hashtag.RandomSlot()
	case 1:
		for  := range  {
			 = 
		}
	default:
		// TxPipeline does not support cross slot transaction.
		setCmdsErr(, ErrCrossSlot)
		return ErrCrossSlot
	}

	,  := .slotMasterNode()
	if  != nil {
		setCmdsErr(, )
		return 
	}

	 := false
	// MOVED/ASK are routing changes, not transient failures: follow them immediately.
	 := false
	for  := 0;  <= .opt.MaxRedirects; ++ {
		++
		if  > 0 && ! {
			if  := internal.Sleep(, .retryBackoff());  != nil {
				setCmdsErr(, )
				return 
			}
		}

		 := .processTxPipelineNode(, , , )
		 = .err
		 = false
		switch .kind {
		case txSuccess:
			return cmdsFirstErr()
		case txRetryMoved:
			// Route directly to the authoritative addr from the MOVED; the
			// cached slot state may be stale until LazyReload lands.
			 = true
			 = false
			.state.LazyReload()
			if ,  = .nodes.GetOrCreate(.addr);  != nil {
				setCmdsErr(, )
				return 
			}
		case txRetryAsk:
			 = true
			 = true
			if ,  = .nodes.GetOrCreate(.addr);  != nil {
				setCmdsErr(, )
				return 
			}
		case txRetryTryAgain, txRetryConn:
			// Same node, fresh connection: TRYAGAIN comes from the migrating
			// source (still the owner), and a conn failure only needs a new
			// connection. Preserve a prior ASKING flag: if we followed an ASK
			// to the importing target, the retry must still send ASKING (the
			// slot is still importing). ASKING is harmless if the migration
			// has since completed, since the flag is only consulted for
			// importing slots.
		case txFatal:
			// Mark every queued-but-never-executed command with the abort
			// error; the command that triggered EXECABORT already has its
			// own error and keeps it, so callers can tell what went wrong.
			 := cmp.Or(.execErr, .err)
			for ,  := range  {
				if .Err() == nil {
					.SetErr()
				}
			}
			return 
		}
	}

	if  != nil {
		setCmdsErr(, )
	}
	return cmdsFirstErr()
}

// slottedKeyedCommands returns a map of slot to commands taking into account
// only commands that have keys.
func ( *ClusterClient) ( context.Context,  []Cmder) map[int][]Cmder {
	 := map[int][]Cmder{}

	// Peek once outside the loop, one RLock for the whole batch instead of
	// two per command (one for the keyless check, one inside cmdSlot).
	 := .cmdsInfoCache.Peek()

	 := -1
	for ,  := range  {
		var  *CommandInfo
		if  != nil {
			 = [.Name()]
		}

		 := cmdFirstKeyPosWithInfo(, )
		if  == 0 {
			continue
		}

		 := .cmdSlotWithPos(, , )
		if  == -1 {
			 = 
		}

		[] = append([], )
	}

	return 
}

func ( *ClusterClient) (
	 context.Context,  *clusterNode,  []Cmder,  bool,
) *txOutcome {
	 := wrapMultiExec(, )
	if  {
		// ASKING must precede MULTI so the flag stays set for the whole tx.
		 = append([]Cmder{NewCmd(, "asking")}, ...)
	}

	var  *txOutcome
	// executed guards against a node-level hook short-circuiting (returning
	// without calling next) — same treatment as processPipelineNode.
	 := false
	 := .Client.withProcessPipelineHook(, , func( context.Context,  []Cmder) error {
		 = true
		// Acquire through the node's dedicated pipeline pool when configured
		// (same routing as processPipelineNode); withPipelineConn falls back
		// to the main pool otherwise. The inner fn's return value drives the
		// connection release exactly like the explicit releaseConn did:
		// redis errors keep the conn poolable, unread replies poison it.
		 := false
		 := .Client.withPipelineConn(, func( context.Context,  *pool.Conn) error {
			 = true
			 = .processTxPipelineNodeConn(, , , , , )
			 := .err
			if isRedisError(.err) {
				 = nil
			}
			if .unreadReplies {
				 = errTxDirtyConn
			}
			return 
		})
		if ! &&  != nil {
			// Connection acquisition failed — fn never ran.
			if shouldRetry(, true) && !cmdsContainNoRetry() {
				 = &txOutcome{kind: txRetryConn, err: }
			} else {
				 = &txOutcome{kind: txFatal, err: }
			}
		}
		return 
	})

	if ! &&  != nil {
		// A node-level hook aborted with an error: surface its verdict. A hook
		// that returned nil short-circuited successfully (it served the batch),
		// which is legal for plain pipelines too, so it is not turned into a
		// fatal outcome (review finding by codex on #3942).
		 = &txOutcome{kind: txFatal, err: }
	}
	if  == nil {
		 = &txOutcome{kind: txFatal, err: fmt.Errorf("redis: tx pipeline produced no outcome")}
	}
	return 
}

func ( *ClusterClient) (
	 context.Context,  *clusterNode,  *pool.Conn,  []Cmder,  []Cmder,  bool,
) *txOutcome {
	// HIMPORT bookkeeping: pending discards and PREPAREs for registered
	// fieldsets the transaction references get written ahead of the wire
	// batch (before ASKING/MULTI; the session state is visible at EXEC).
	 := .Client.himportInjectedCmds(, , )

	if  := .WithWriter(.context(), .opt.WriteTimeout, func( *proto.Writer) error {
		for ,  := range  {
			if  := writeCmd(, );  != nil {
				return 
			}
		}
		return writeCmds(, )
	});  != nil {
		// Write failure: re-route the whole tx on a fresh connection.
		if shouldRetry(, true) && !cmdsContainNoRetry() {
			return &txOutcome{kind: txRetryConn, err: }
		}
		return &txOutcome{kind: txFatal, err: }
	}

	var  *txOutcome
	 := .WithReader(.context(), .opt.ReadTimeout, func( *proto.Reader) error {
		if  := .Client.himportReadInjectedReplies(, , , );  != nil {
			// Transport error with the tx replies unread; the batch was
			// written and may have committed — fatal, discard the conn.
			 = .txReadFatal()
			return nil
		}
		 = .readTxPipelineReplies(, , , , , )
		if  != nil && .kind == txSuccess {
			.Client.himportAfterBatch(, , )
		}
		return nil
	})

	if  != nil {
		// Reader-level failure (deadline setup, nil conn) around the read loop.
		// The batch was already written, so the server may have committed;
		// surface the error as fatal and discard the suspect connection rather
		// than re-executing the transaction.
		return .txReadFatal()
	}
	return 
}

// readTxPipelineReplies reads the replies of one MULTI..EXEC unit and
// classifies the outcome. The reply count always matches the number of sent
// commands, so success/redirect paths leave the connection clean; only an early
// MULTI read failure can leave unread replies.
func ( *ClusterClient) (
	 context.Context,  *clusterNode,  *pool.Conn,  *proto.Reader,  []Cmder,  bool,
) *txOutcome {
	 := NewStatusCmd()

	 := func() error {
		.txProcessPush(, , , )
		return .readReply()
	}

	// Optional top-level ASKING reply (+OK, or a retryable error such as -LOADING).
	if  {
		if  := ();  != nil {
			return .txPreQueueErrorOutcome(, )
		}
	}

	// MULTI reply (+OK, or an error such as -LOADING during failover).
	if  := ();  != nil {
		return .txPreQueueErrorOutcome(, )
	}

	// Queue replies: +QUEUED, or a redirect / command error that dirties the tx.
	var  *txRedirect
	var  error
	for ,  := range  {
		 := ()
		if  == nil {
			continue // +QUEUED
		}
		if !isRedisError() {
			return .txReadFatal() // IO error
		}
		if , ,  := isMovedError();  ||  {
			if  == nil {
				 = &txRedirect{moved: , ask: , addr: , err: }
			}
			continue
		}
		if proto.IsTryAgainError() {
			if  == nil {
				 = &txRedirect{tryAgain: true, err: }
			}
			continue
		}
		// Non-redirect command error (e.g. wrong arity) dirties the tx.
		.SetErr()
		if  == nil {
			 = 
		}
	}

	// EXEC reply. ReadLine parses error lines into typed errors, so a non-nil
	// err means EXEC returned an error rather than the result array.
	.txProcessPush(, , , )
	,  := .ReadLine()
	if  != nil {
		if !isRedisError() {
			return .txReadFatal() // IO error
		}
		return .classifyExecError(, , )
	}

	if [0] != proto.RespArray {
		 := fmt.Errorf("redis: unexpected EXEC reply %q", )
		setCmdsErr(, )
		// A non-array aggregate reply may carry an unread payload.
		return &txOutcome{kind: txFatal, err: , unreadReplies: true}
	}

	// Success: read the N command results.
	if  := .Client.pipelineReadCmds(, , , );  != nil && !isRedisError() {
		return .txReadFatal() // IO error mid-results
	}
	return &txOutcome{kind: txSuccess}
}

func ( *ClusterClient) ( context.Context,  *clusterNode,  *pool.Conn,  *proto.Reader) {
	if  := .Client.processPendingPushNotificationWithReader(, , );  != nil {
		internal.Logger.Printf(, "push: error processing pending notifications before reading reply: %v", )
	}
}

// txReadFatal classifies a read-phase IO error. The MULTI..EXEC batch was
// already written, so the server may have committed the transaction; retrying
// would re-execute it, double-applying non-idempotent commands (INCR/APPEND,
// which are not NoRetry). Surface the error as fatal and discard the
// connection, since replies may still be unread on the wire.
func ( *ClusterClient) ( error) *txOutcome {
	return &txOutcome{kind: txFatal, err: , unreadReplies: true}
}

// txPreQueueErrorOutcome classifies a setup-phase reply error: the top-level
// ASKING reply or the MULTI reply. The transaction body never executes (EXEC
// returns -EXECABORT), so retryable errors such as -LOADING are safe to retry
// on a fresh connection. A failed setup reply still leaves the remaining
// replies on the wire -- the server replies to each following command and to
// EXEC regardless -- so the connection is always discarded.
func ( *ClusterClient) ( error,  []Cmder) *txOutcome {
	if !isRedisError() {
		return .txReadFatal()
	}
	if shouldRetry(, true) && !cmdsContainNoRetry() {
		return &txOutcome{kind: txRetryConn, err: , unreadReplies: true}
	}
	return &txOutcome{kind: txFatal, err: , unreadReplies: true}
}

// classifyExecError turns an EXEC reply error into a retry/fatal outcome.
func ( *ClusterClient) ( error,  *txRedirect,  error) *txOutcome {
	if , ,  := isMovedError();  ||  {
		// Narrow race: the slot moved after every command was queued.
		if  {
			return &txOutcome{kind: txRetryAsk, err: , addr: }
		}
		return &txOutcome{kind: txRetryMoved, err: , addr: }
	}
	if proto.IsTryAgainError() {
		return &txOutcome{kind: txRetryTryAgain, err: }
	}
	if proto.IsClusterDownError() {
		// Cluster degraded: back off and retry. Replies were fully consumed.
		return &txOutcome{kind: txRetryConn, err: }
	}
	if proto.IsExecAbortError() {
		if  != nil {
			return &txOutcome{kind: txFatal, err: , execErr: }
		}
		if  != nil {
			switch {
			case .moved:
				return &txOutcome{kind: txRetryMoved, err: .err, addr: .addr}
			case .ask:
				return &txOutcome{kind: txRetryAsk, err: .err, addr: .addr}
			case .tryAgain:
				return &txOutcome{kind: txRetryTryAgain, err: .err}
			}
		}
		return &txOutcome{kind: txFatal, err: , execErr: }
	}
	return &txOutcome{kind: txFatal, err: }
}

func ( *ClusterClient) ( context.Context,  func(*Tx) error,  ...string) error {
	if len() == 0 {
		return errNoWatchKeys
	}

	 := hashtag.Slot([0])
	for ,  := range [1:] {
		if hashtag.Slot() !=  {
			return errWatchCrosslot
		}
	}

	,  := .slotMasterNode(, )
	if  != nil {
		return 
	}

	for  := 0;  <= .opt.MaxRedirects; ++ {
		if  > 0 {
			if  := internal.Sleep(, .retryBackoff());  != nil {
				return 
			}
		}

		// Track callback errors separately to avoid retrying user failures through cluster retry classification.
		var  error
		 = .Client.Watch(, func( *Tx) error {
			 = ()
			return 
		}, ...)
		if  == nil {
			break
		}
		if  != nil {
			return 
		}

		, ,  := isMovedError()
		if  ||  {
			,  = .nodes.GetOrCreate()
			if  != nil {
				return 
			}
			continue
		}

		if  := isReadOnlyError();  ||  == pool.ErrClosed {
			if  {
				.state.LazyReload()
			}
			,  = .slotMasterNode(, )
			if  != nil {
				return 
			}
			continue
		}

		if shouldRetry(, true) {
			continue
		}

		return 
	}

	return 
}

// maintenance notifications won't work here for now
func ( *ClusterClient) () *PubSub {
	var  *clusterNode
	 := &PubSub{
		opt: .opt.clientOptions(),
		newConn: func( context.Context,  string,  []string) (*pool.Conn, error) {
			if  != nil {
				panic("node != nil")
			}

			var  error

			if len() > 0 {
				 := hashtag.Slot([0])

				// newConn in PubSub is only used for subscription connections, so it is safe to
				// assume that a slave node can always be used when client options specify ReadOnly.
				if .opt.ReadOnly {
					,  := .state.Get()
					if  != nil {
						return nil, 
					}

					,  = .slotReadOnlyNode(, )
					if  != nil {
						return nil, 
					}
				} else {
					,  = .slotMasterNode(, )
					if  != nil {
						return nil, 
					}
				}
			} else {
				,  = .nodes.Random()
				if  != nil {
					return nil, 
				}
			}
			,  := .Client.pubSubPool.NewConn(, .Client.opt.Network, .Client.opt.Addr, )
			if  != nil {
				 = nil
				return nil, 
			}
			// will return nil if already initialized
			 = .Client.initConn(, )
			if  != nil {
				_ = .Close()
				 = nil
				return nil, 
			}
			.Client.pubSubPool.TrackConn()
			return , nil
		},
		closeConn: func( *pool.Conn) error {
			// Untrack connection from PubSubPool
			.Client.pubSubPool.UntrackConn()
			 := .Close()
			 = nil
			return 
		},
	}
	.init()

	return 
}

// Subscribe subscribes the client to the specified channels.
// Channels can be omitted to create empty subscription.
func ( *ClusterClient) ( context.Context,  ...string) *PubSub {
	 := .pubSub()
	if len() > 0 {
		_ = .Subscribe(, ...)
	}
	return 
}

// PSubscribe subscribes the client to the given patterns.
// Patterns can be omitted to create empty subscription.
func ( *ClusterClient) ( context.Context,  ...string) *PubSub {
	 := .pubSub()
	if len() > 0 {
		_ = .PSubscribe(, ...)
	}
	return 
}

// SSubscribe Subscribes the client to the specified shard channels.
func ( *ClusterClient) ( context.Context,  ...string) *PubSub {
	 := .pubSub()
	if len() > 0 {
		_ = .SSubscribe(, ...)
	}
	return 
}

func ( *ClusterClient) ( int) time.Duration {
	return internal.RetryBackoff(, .opt.MinRetryBackoff, .opt.MaxRetryBackoff)
}

func ( *ClusterClient) ( context.Context) (map[string]*CommandInfo, error) {
	// Try 3 random nodes.
	const  = 3

	,  := .nodes.Addrs()
	if  != nil {
		return nil, 
	}

	var  error

	 := rand.Perm(len())
	if len() >  {
		 = [:]
	}

	for ,  := range  {
		 := []
		,  := .nodes.GetOrCreate()
		if  != nil {
			if  == nil {
				 = 
			}
			continue
		}

		,  := .Client.Command().Result()
		if  == nil {
			return , nil
		}

		if  == nil {
			 = 
		}
	}

	if  == nil {
		panic("not reached")
	}
	return nil, 
}

// cmdInfo will fetch and cache the command policies after the first execution
func ( *ClusterClient) ( context.Context,  string) *CommandInfo {
	// Use a separate context that won't be canceled to ensure command info lookup
	// doesn't fail due to original context cancellation
	 := .context()
	if .opt.ContextTimeoutEnabled &&  != nil {
		// If context timeout is enabled, still use a reasonable timeout
		var  context.CancelFunc
		,  = context.WithTimeout(context.Background(), 5*time.Second)
		defer ()
	}

	,  := .cmdsInfoCache.Get()
	if  != nil {
		internal.Logger.Printf(, "getting command info: %s", )
		return nil
	}

	 := []
	if  == nil {
		internal.Logger.Printf(, "info for cmd=%s not found", )
	}

	return 
}

// cmdInfoPeek returns the cached CommandInfo for the named command without
// triggering a round-trip to Redis. It returns nil when the cache is cold.
func ( *ClusterClient) ( string) *CommandInfo {
	if  := .cmdsInfoCache.Peek();  != nil {
		return []
	}
	return nil
}

func ( *ClusterClient) ( Cmder,  int) int {
	// Serve/populate the per-command slot cache only on the natural-slot path
	// (prefferedSlot == -1). A forced prefferedSlot (retry re-routing) must not be
	// cached or served from cache. The cache lets the autopipeline shard router
	// and the pipeline-flush router (mapCmdsByNode) share one slot computation
	// instead of each recomputing it.
	if  == -1 {
		if ,  := .cachedSlot();  {
			return 
		}
	}
	 := .cmdInfoPeek(.Name())
	 := .cmdSlotWithPos(, cmdFirstKeyPosWithInfo(, ), )
	if  == -1 &&  >= 0 {
		.setCachedSlot()
	}
	return 
}

// cmdSlotWithPos computes the cluster slot for cmd given a pre-resolved first key
// position. Separating pos resolution from slot computation lets callers that
// already know pos avoid a redundant Peek() call.
func ( *ClusterClient) ( Cmder,  int,  int) int {
	 := .Args()
	if [0] == "cluster" && ([1] == "getkeysinslot" || [1] == "countkeysinslot") {
		return [2].(int)
	}
	return cmdSlot(, , )
}

func cmdSlot( Cmder,  int,  int) int {
	if  == 0 {
		if  != -1 {
			return 
		}
		// Return -1 for keyless commands to signal that ShardPicker should be used
		return -1
	}
	 := .stringArg()
	return hashtag.Slot()
}

func ( *ClusterClient) (
	 context.Context,
	 string,
	 int,
) (*clusterNode, error) {
	,  := .state.Get()
	if  != nil {
		return nil, 
	}

	if .opt.ReadOnly {
		 := .cmdInfo(, )
		if  != nil && .ReadOnly {
			return .slotReadOnlyNode(, )
		}
	}
	return .slotMasterNode()
}

func ( *ClusterClient) (
	 context.Context,
	 string,
	 int,
	 routing.ShardPicker,
) (*clusterNode, error) {
	,  := .state.Get()
	if  != nil {
		return nil, 
	}

	// For keyless commands (slot == -1), use ShardPicker to select a shard
	// This respects the user's configured ShardPicker policy
	if  == -1 {
		if len(.Masters) == 0 {
			return nil, errClusterNoNodes
		}
		 := .Next(len(.Masters))
		return .Masters[], nil
	}

	if .opt.ReadOnly {
		 := .cmdInfo(, )
		if  != nil && .ReadOnly {
			return .slotReadOnlyNode(, )
		}
	}
	return .slotMasterNode()
}

func ( *ClusterClient) ( *clusterState,  int) (*clusterNode, error) {
	if .opt.RouteByLatency {
		if .opt.RouteByLatencyTolerance > 0 {
			return .slotNodeWithinLatency(, .opt.RouteByLatencyTolerance)
		}
		return .slotClosestNode()
	}
	if .opt.RouteRandomly {
		return .slotRandomNode()
	}

	if .opt.ShardPicker != nil {
		return .slotShardPickerSlaveNode(, .opt.ShardPicker)
	}

	return .slotSlaveNode()
}

func ( *ClusterClient) ( context.Context,  int) (*clusterNode, error) {
	,  := .state.Get()
	if  != nil {
		return nil, 
	}
	return .slotMasterNode()
}

// SlaveForKey gets a client for a replica node to run any command on it.
// This is especially useful if we want to run a particular lua script which has
// only read only commands on the replica.
// This is because other redis commands generally have a flag that points that
// they are read only and automatically run on the replica nodes
// if ClusterOptions.ReadOnly flag is set to true.
func ( *ClusterClient) ( context.Context,  string) (*Client, error) {
	,  := .state.Get()
	if  != nil {
		return nil, 
	}
	 := hashtag.Slot()
	,  := .slotReadOnlyNode(, )
	if  != nil {
		return nil, 
	}
	return .Client, 
}

// MasterForKey return a client to the master node for a particular key.
func ( *ClusterClient) ( context.Context,  string) (*Client, error) {
	 := hashtag.Slot()
	,  := .slotMasterNode(, )
	if  != nil {
		return nil, 
	}
	return .Client, nil
}

func ( *ClusterClient) ( context.Context) context.Context {
	if .opt.ContextTimeoutEnabled {
		return 
	}
	return context.Background()
}

func ( *ClusterClient) () *commandInfoResolver {
	return .cmdInfoResolver
}

func ( *ClusterClient) ( *commandInfoResolver) {
	.cmdInfoResolver = 
}

// extractCommandInfo retrieves the routing policy for a command
func ( *ClusterClient) ( context.Context,  Cmder) *routing.CommandPolicy {
	if  := .cmdInfo(, .Name());  != nil && .CommandPolicy != nil {
		return .CommandPolicy
	}

	return nil
}

// NewDynamicResolver returns a CommandInfoResolver
// that uses the underlying cmdInfo cache to resolve the policies
func ( *ClusterClient) () *commandInfoResolver {
	return &commandInfoResolver{
		resolveFunc: .extractCommandInfo,
	}
}

func appendIfNotExist[ comparable]( [],  ) [] {
	if slices.Contains(, ) {
		return 
	}
	return append(, )
}

//------------------------------------------------------------------------------

type cmdsMap struct {
	mu sync.Mutex
	m  map[*clusterNode][]Cmder
}

func newCmdsMap() *cmdsMap {
	return &cmdsMap{
		m: make(map[*clusterNode][]Cmder),
	}
}

func ( *cmdsMap) ( *clusterNode,  ...Cmder) {
	.mu.Lock()
	.m[] = append(.m[], ...)
	.mu.Unlock()
}