
    ԋgd                      U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZmZmZmZmZ d dlmZ d dlmZ d dlmZm Z m!Z! d dl"m#Z# d d	l$m%Z%m&Z& d d
l'm(Z(m)Z) d dl*m+Z+ d dl,m-Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z: d dl;m<Z<m=Z=m>Z>m?Z?m@Z@ d dlAZAd dlBmCZC d dlDmEZEmFZF d dlGmHZH d dlImJZJ d dlKmLZL d dlMmNZN d dlOmPZPmQZQmRZRmSZS d dlTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ d dl\m]Z] d dl^m_Z_ d dl`maZa d dlbmcZcmdZd 	 d dlemfZf d dlhmiZi d dljmkZk d dllmmZmmnZnmoZompZpmqZqmrZr d dlbZsd d lsmtZtmuZu d d!lsmvZw d d"lxmyZy d d#lzm{Z{ d d$l|m}Z} d d%l^m~Z~mZmZmZmZmZmZ d d&lmZmZmZmZmZmZmZ d d'lmZ d d(lmZmZmZ d d)lmZ d d*lmZmZ d d+lmZ d d,lmZ d d-lmZ d d.lmZ d d/lmZ d d0lmZ d d1lbmZmZmZmZmZmZmZmZmZmZmZmZ d d2lmZmZmZmZmZ d d3lmZmZmZ e0rd d4lmZ  ejx                  e      Z ej~                         Zd5ed6<   d gZ e#d7d8      Zd9ed7<   d:eiZd;Z G d< d=e      Z G d> d?e      Z G d@ dA      Z G dB dCe5      ZdudDZdvdEZdwdGZ G dH dIeq      Z G dJ dK      ZdL Z G dM dNeЫ      ZdO ZdP ZdQ Z G dR dSe6      ZeePenf   ZdTedU<   dV Z G dW dXeJ      Z G dY dFe      ZdxdZZ G d[ d\e      Zd] Zd^Zd_Zdefd`ZdefdaZdb Zdc Z G dd de      Zdf ZdydgZdh Zdi ZdydjZdk Z G dl dm      Z G dn do      Z G dp dq      Ze dr        Zds Zdt Z ej                  e       y# eg$ r e<ZfY Gw xY w)z    annotationsN)defaultdict)
Collection	CoroutineIterableIteratorSequence)ThreadPoolExecutor)DoneAndNotDoneFutures)asynccontextmanagercontextmanagersuppress)
ContextVar)partialsingledispatchmethod)PackageNotFoundErrorversion)Number)Queue)TYPE_CHECKINGAnyCallableClassVarLiteral
NamedTuple	TypedDictcast)parse)firstgroupbymergepartition_allvalmapcollections_to_dsk)flattenvalidate_key)HighLevelGraph)Layer)SubgraphCallable)tokenize)Key
NestedKeys	NoDefault
no_default)ensure_dictformat_bytesfuncnameparse_bytesparse_timedeltashorten_tracebacktypename)get_template)	OKMessage)_is_dumpable)Deadlinewait_for)
single_key)gen)IOLoop)DataNode	GraphNodeListTaskTaskRefparse_input)cluster_dump
preloading)versions)BatchedSendClientExecutor)PeriodicCallback)CommClosedErrorConnectionPoolPooledRPCCallStatusclean_exceptionconnectrpc)ForwardLoggingPluginNannyPluginSchedulerPluginSchedulerUploadFile
UploadFileWorkerPlugin_get_plugin_name)time)HasWhatSchedulerInfoWhoHas)to_serialize)dumpsloads)Datasets)PubSubClientExtension)Security)sizeof)SpanMetadata)rejoin)CancelledError
LoopRunnerNoOpAwaitableSyncMethodMixinTimeoutErrorformat_dashboard_linkhas_keywordimport_term
log_errorsnbytessyncthread_state)gather_from_workers	pack_dataretry_operationscatter_to_workersunpack_remotedata)
get_client
get_workersecede)	TypeAliasz(weakref.WeakValueDictionary[int, Client]_global_clients_current_clientdefaultzContextVar[Client | None]pubsubzforwarded-log-recordc                  D    e Zd ZU ded<   ded<   ded<   d
ddZddZd	 Zy)FutureCancelledErrorstrkeyreason
str | NonemsgNc                6    || _         |r|nd| _        || _        y )Nunknownr   r   r   )selfr   r   r   s       2lib/python3.12/site-packages/distributed/client.py__init__zFutureCancelledError.__init__   s     &fI    c                    | j                    d| j                   d}| j                  rdj                  || j                  g      }|S )N cancelled for reason: .
)r   r   r   join)r   results     r   __str__zFutureCancelledError.__str__   s@    HH:4T[[MC88YY12Fr   c                `    | j                   | j                  | j                  | j                  ffS N)	__class__r   r   r   r   s    r   
__reduce__zFutureCancelledError.__reduce__   s$    ~~$++txx@@@r   r   )r   r   r   r   r   r   returnr   )__name__
__module____qualname____annotations__r   r   r    r   r   r   r      s!    	HK	O
Ar   r   c                  &    e Zd ZU ded<   ddZd Zy)FuturesCancelledErrorlist[CancelledFuturesGroup]error_groupsc                ,    t        |d d      | _        y )Nc                ,    t        | j                        S r   lenerrorsgroups    r   <lambda>z0FuturesCancelledError.__init__.<locals>.<lambda>   s    C,=r   T)r   reverse)sortedr   )r   r   s     r   r   zFuturesCancelledError.__init__   s    "=t
r   c           	         t        t        d | j                              }| d|dkD  rdnd d}dj                  |dg| j                  D cg c]  }t	        |       c}z         S c c}w )	Nc                ,    t        | j                        S r   r   r   s    r   r   z/FuturesCancelledError.__str__.<locals>.<lambda>   s    c%,,&7r    Future   s z cancelled:r   zReasons:)summapr   r   r   )r   countr   r   s       r   r   zFuturesCancelledError.__str__   sq    C79J9JKL7'#!;;GyyZ D<M<M#N<M5CJ<M#NN
 	
#Ns   A'
N)r   r   )r   r   r   r   r   r   r   r   r   r   r      s    --


r   r   c                  @    e Zd ZU ded<   ded<    ee      ZddZd Zy)	CancelledFuturesGrouplist[FutureCancelledError]r   r   r   c                     || _         || _        y r   r   r   )r   r   r   s      r   r   zCancelledFuturesGroup.__init__   s    r   c                8   | j                   D cg c]  }|j                   }}d }| j                   D ]  }|j                  s|j                  } n t        |       dt        |      dkD  rdnd d| j                   d| dt        |      dkD  rdnd d| S c c}w )	Nr   r   r   r   r   z.
Message: z
Future: )r   r   r   r   r   )r   errorkeysexample_messages       r   r   zCancelledFuturesGroup.__str__   s    '+{{3{e		{3[[Eyy"')) ! 4ykD	A2 >>U{{m<'8 9IMSr2"TF<	
 4s   BN)r   r   r   r   )r   r   r   r   tuple	__slots__r   r   r   r   r   r   r      s#    && Ko&I
r   r   c                  6    e Zd ZU ded<   ded<   ded<   ded<   y)
SourceCoder   codeintlineno_framelineno_relativefilenameNr   r   r   r   r   r   r   r   r      s    
IMr   r   c                     t         j                         } | r| S t        t        t              d      }|D ]%  }t        |   } | j
                  dk7  r| c S t        |= ' y )NT)r   closed)r~   getr   listr}   status)cLks      r   _get_global_clientr      s[    AtO$d3AA88xH"  r   c                Z    | )d| _         | t        t        d   <   t        dxx   dz  cc<   y y )NTr   r   )_set_as_defaultr}   _global_client_indexr   s    r   _set_global_clientr      s4    } 34,Q/0Q1$ r   Clientc                p    t        t              D ]  }	 t        |   | u rt        |=  y # t        $ r Y $w xY wr   )r   r}   KeyError)r   r   s     r   _del_global_clientr      s@    /"	q!Q&#A& #  		s   )	55c                     e Zd ZU dZ eej                        Zded<   dZ	dZ
 ej                         Z ej                         j                   Zd"dZed        Zd Zd Zd	 Zed
        Zed        Zd Zd#dZd$dZd Zd#dZd Zd%dZ d Z!d Z"d Z#d#dZ$ed        Z%d Z&d&dZ'd Z(d Z)d Z*d Z+d Z,d Z-d  Z.d! Z/y)'Futurea  A remotely running computation

    A Future is a local proxy to a result running on a remote worker.  A user
    manages future objects in the local Python process to determine what
    happens in the larger cluster.

    .. note::

        Users should not instantiate futures manually. This can lead to state
        corruption and deadlocking clusters.

    Parameters
    ----------
    key: str, or tuple
        Key of remote data to which this future refers
    client: Client
        Client that should own this future.  Defaults to _get_global_client()
    inform: bool
        Do we inform the scheduler that we need an update on this future
    state: FutureState
        The state of the future

    Examples
    --------
    Futures typically emerge from Client computations

    >>> my_future = client.submit(add, 1, 2)  # doctest: +SKIP

    We can track the progress and results of a future

    >>> my_future  # doctest: +SKIP
    <Future: status: finished, key: add-8f6e709446674bad78ea8aeecfee188e>

    We can get the result or the exception and traceback from the future

    >>> my_future.result()  # doctest: +SKIP

    See Also
    --------
    Client:  Creates futures
    staticmethod[[], bool]_is_finalizingNc                    || _         d| _        || _        |xs) t        j                  t        t        j                        f| _        || _        d | _	        | j                          y )NF)r   _cleared_clientr   _uidnext_counter_id_input_state_state
_bind_late)r   r   clientstater   s        r   r   zFuture.__init__0  sN    >6;;V__(=>!r   c                :    | j                          | j                  S r   )r   r   r   s    r   r   zFuture.client9  s    ||r   c                2    || _         | j                          y r   )r   r   )r   r   s     r   bind_clientzFuture.bind_client>  s    r   c                r   | j                   r| j                  s| j                   j                  | j                         | j                   j                  | _        | j                  | j                   j                  v r)| j                   j                  | j                     | _        n=t        | j                        x| _        | j                   j                  | j                  <   | j                  8	 | j                   j                  | j                     } || j                         y y y y # t        $ r Y y w xY w)Nr   )r   r   _inc_refr   
generation_generationfuturesFutureStater   _state_handlersr   )r   handlers     r   r   zFuture._bind_lateB  s    <<LL!!$((+#||66Dxx4<<///"ll22488<?J488?TTdll22488<  ,*"ll::4;L;LMG ) - !,<   s   0#D* *	D65D6c                b    | j                   r| j                  st        t        |        d      y )Nz object not properly initialized. This can happen if the object is being deserialized outside of the context of a Client or Worker.)r   r   RuntimeErrortyper   s    r   _verify_initializedzFuture._verify_initializedT  s4    {{$++:, ' '  #.r   c                    | j                   S )z|Returns the executor, which is the client.

        Returns
        -------
        Client
            The executor
        r   r   s    r   executorzFuture.executor\  s     {{r   c                .    | j                   j                  S )z_Returns the status

        Returns
        -------
        str
            The status
        r   r   r   s    r   r   zFuture.statusg  s     {{!!!r   c                6    | j                   j                         S )zReturns whether or not the computation completed.

        Returns
        -------
        bool
            True if the computation is complete, otherwise False
        )r   doner   s    r   r  zFuture.doner  s     {{!!r   c                    | j                          t               5  | j                  j                  | j                  |      cddd       S # 1 sw Y   yxY w)a=  Wait until computation completes, gather result to local process.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``

        Raises
        ------
        dask.distributed.TimeoutError
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        Returns
        -------
        result
            The result of the computation. Or a coroutine if the client is asynchronous.
        )callback_timeoutN)r   r6   r   rr   _resultr   timeouts     r   r   zFuture.result|  s=    ( 	  " ;;##DLL7#K !  s   'AAc                  K   | j                   j                          d {    | j                  dk(  rOt        | j                   j                  | j                   j
                        }|r|\  }}}|j                  |      |S | j                         r<| j                   sJ | j                   j                  }t        |t              sJ |r||S | j                  j                  | g       d {   }|d   S 7 7 w)Nr   r   )r   waitr   rQ   	exception	tracebackwith_traceback	cancelled
isinstancerh   r   _gather)r   raiseitexctyptbr  r   s          r   r	  zFuture._result  s     kk   ;;'!!$++"7"79N9NOC"S"((,,
^^;;;--Ii888  ;;..v66F!9% 	!" 7s"   C<C8CC<.C:/
C<:C<c                   K   | j                   j                          d {    | j                  dk(  r| j                   j                  S y 7 *wNr   )r   r  r   r  r   s    r   
_exceptionzFuture._exception  @     kk   ;;'!;;(((	 	!   AA+Ac                t    | j                           | j                  j                  | j                  fd|i|S )a<  Return the exception of a failed task

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        **kwargs : dict
            Optional keyword arguments for the function

        Returns
        -------
        Exception
            The exception that was raised
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        See Also
        --------
        Future.traceback
        r  )r   r   rr   r  r   r  kwargss      r   r  zFuture.exception  s5    , 	  "t{{T'TVTTr   c                   | j                          t        }|j                  !|j                  t	        j
                         k7  r,	 t        dd      |_        t	        j
                         |_        fd}| j                  j                  j                  t        | t        |j                  j                  |             y# t        $ r t        d      |_        Y w xY w)a  Call callback on future when future has finished

        The callback ``fn`` should take the future as its only argument.  This
        will be called regardless of if the future completes successfully,
        errs, or is cancelled

        The callback is executed in a separate thread.

        Parameters
        ----------
        fn : callable
            The method or function to be called
        Nr   zDask-Callback-Thread)thread_name_prefixc                b    	  |        y # t         $ r t        j                  d|         w xY w)NzError in callback %s of %s:)BaseExceptionloggerr  )futfns    r   execute_callbackz2Future.add_done_callback.<locals>.execute_callback  s4    3    !>CHs    ".)r   r   _cb_executor_cb_executor_pidosgetpidr   	TypeErrorr   loopadd_callbackdone_callbackr   submit)r   r&  clsr'  s    `  r   add_done_callbackzFuture.add_done_callback  s     	  "#s';';ryy{'J9#5*@$ 
 $&99;C 	 	%%4)9)9)@)@BR!S	
  9#5a#8 9s   C   CCc                d    | j                           | j                  j                  | gf||d|S )zgCancel the request to run this future

        See Also
        --------
        Client.cancel
        r   r   )r   r   cancel)r   r   r   r  s       r   r5  zFuture.cancel  s5     	  "!t{{!!4&KSKFKKr   c                ^    | j                           | j                  j                  | gfi |S )zcRetry this future if it has failed

        See Also
        --------
        Client.retry
        )r   r   retryr   r  s     r   r7  zFuture.retry  s.     	  " t{{  $2622r   c                4    | j                   j                  dk(  S )zReturns True if the future has been cancelled

        Returns
        -------
        bool
            True if the future was 'cancelled', otherwise False
        r  r  r   s    r   r  zFuture.cancelled  s     {{!![00r   c                   K   | j                   j                          d {    | j                  dk(  r| j                   j                  S y 7 *wr  )r   r  r   r  r   s    r   
_tracebackzFuture._traceback  r  r  c                t    | j                           | j                  j                  | j                  fd|i|S )a  Return the traceback of a failed task

        This returns a traceback object.  You can inspect this object using the
        ``traceback`` module.  Alternatively if you call ``future.result()``
        this traceback will accompany the raised exception.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        Examples
        --------
        >>> import traceback  # doctest: +SKIP
        >>> tb = future.traceback()  # doctest: +SKIP
        >>> traceback.format_tb(tb)  # doctest: +SKIP
        [...]

        Returns
        -------
        traceback
            The traceback object. Or a coroutine if the client is asynchronous.

        See Also
        --------
        Future.exception
        r  )r   r   rr   r;  r  s      r   r  zFuture.traceback  s5    > 	  "t{{T'TVTTr   c                .    | j                   j                  S )zReturns the type)r   r   r   s    r   r   zFuture.type4  s     {{r   c                <   | j                          | j                  sq| j                  j                  | j                  k(  rMd| _        	 | j                  j
                  j                  | j                  j                  | j                         yyy# t        $ r Y yw xY w)z
        Notes
        -----
        This method can be called from different threads
        (see e.g. Client.get() or Future.__del__())
        TN)
r   r   r   r   r   r-  r.  _dec_refr   r,  r   s    r   releasezFuture.release9  s~     	  "}}!7!74;K;K!K DM  --dkk.B.BDHHM "L}  s   AB 	BBc                (    t         | j                  ffS r   )r   r   r   s    r   r   zFuture.__reduce__H  s    {""r   c                Z    t        |       j                  | j                  | j                  fS r   )r   r   r   r   r   s    r   __dask_tokenize__zFuture.__dask_tokenize__K  s!    T
##TXXtxx88r   c                z    	 | j                          y # t        $ r | j                         s Y y t        $ r Y y w xY wr   )r@  AttributeErrorr   r   r   s    r   __del__zFuture.__del__N  s@    	LLN 	 &&( ) 		s    :::c                    t        |       S r   )reprr   s    r   r   zFuture.__str__Y  s    Dzr   c                    | j                   r3d| j                   dt        | j                          d| j                   dS d| j                   d| j                   dS )Nz	<Future: z, type: z, key: >)r   r   r7   r   r   s    r   __repr__zFuture.__repr__\  sX    99DKK=$))1D0EWTXXJVWX t{{m7488*A>>r   c                    t        d      j                  t        | j                        t	        | j
                        | j                        S )Nzfuture.html.j2)r   r   r   )r8   renderr   r   r7   r   r   r   s    r   _repr_html_zFuture._repr_html_d  s>    ,-44DHH$))$;; 5 
 	
r   c                >    | j                         j                         S r   )r   	__await__r   s    r   rP  zFuture.__await__k  s    {{}&&((r   c                ,    t        | j                        S r   )hashr   r   s    r   __hash__zFuture.__hash__n  s    DHH~r   c                
    | |u S r   r   )r   others     r   __eq__zFuture.__eq__q  s    u}r   NNNr   TNN)r   zstr | tuple[Any, ...])0r   r   r   __doc__staticmethodsysis_finalizingr   r   r(  r)  	itertoolsr   r   uuiduuid4hexr   r   propertyr   r   r   r   r  r   r  r   r	  r  r  r2  r5  r7  r  r;  r  r   r@  r   rC  rF  r   rK  rN  rP  rS  rV  r   r   r   r   r      s   (T .:#:K:K-LN*LLy H4::<D  *$   " ""L0*U2"
HL31 UD    #9	?
)r   r   c                  ^    e Zd ZdZdZddZd ZddZddZd Z	d	 Z
d
 Zd Zd ZddZd Zy)r   zeA Future's internal state.

    This is shared between all Futures with the same key and client.
    )_eventr   r   r   r  r  c                X    d | _         || _        d | _        d| _        d | _        d | _        y )Npending)rd  r   r  r   r  r   r   r   s     r   r   zFutureState.__init__}  s,    	r   c                X    | j                   }|t        j                         x}| _         |S r   )rd  asyncioEvent)r   events     r   
_get_eventzFutureState._get_event  s)     =")--/1EDKr   Nc                    d| _         t        | j                  ||      | _        | j	                         j                          y)zCancels the operationr  r   N)r   r   r   r  rl  set)r   r   r   s      r   r5  zFutureState.cancel  s0    !-$((6sSr   c                b    d| _         | j                         j                          ||| _        yy)zSets the status to 'finished' and sets the event

        Parameters
        ----------
        type : any
            The type
        finishedN)r   rl  rn  r   )r   r   s     r   finishzFutureState.finish  s0     !DI r   c                N    d| _         | j                         j                          y)z.Sets the status to 'lost' and clears the eventlostNr   rl  clearr   s    r   losezFutureState.lose  s    !r   c                N    d| _         | j                         j                          yz1Sets the status to 'pending' and clears the eventrf  Nrt  r   s    r   r7  zFutureState.retry  s    !r   c                    t        ||      \  }}}d| _        || _        || _        | j	                         j                          y)a  Sets the error data

        Sets the status to 'error'. Sets the exception, the traceback,
        and the event

        Parameters
        ----------
        exception: Exception
            The exception
        traceback: Exception
            The traceback
        r   N)rQ   r   r  r  rl  rn  )r   r  r  _s       r   	set_errorzFutureState.set_error  s?     #2)Y"G9i""r   c                V    | j                   duxr | j                   j                         S )z<Returns 'True' if the event is not None and the event is setN)rd  is_setr   s    r   r  zFutureState.done  s#    {{$&?4;;+=+=+??r   c                `    d| _         | j                  | j                  j                          yyrx  )r   rd  ru  r   s    r   resetzFutureState.reset  s(    ;;"KK #r   c                p   K   t        | j                         j                         |       d{    y7 w)zWait for the awaitable to complete with a timeout.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        N)r<   rl  r  r
  s     r   r  zFutureState.wait  s(      t(--/999s   ,646c                P    d| j                   j                   d| j                   dS )N<r   rJ  )r   r   r   r   s    r   rK  zFutureState.__repr__  s&    4>>**+2dkk]!<<r   )r   r   rY  r   )r   r   r   rZ  r   r   rl  r5  rq  rv  r7  r{  r  r  r  rK  r   r   r   r   r   u  sG    
 NI "
"
 (@ 	:=r   r   c                   K   | j                   dk(  r2| j                  j                          d{    | j                   dk(  r2 ||        y7 w)zCoroutine that waits on the future, then calls the callback

    Parameters
    ----------
    future : asyncio.Future
        The future
    callback : callable
        The callback
    rf  N)r   r   r  )futurecallbacks     r   r/  r/    sE      --9
$mm  """ --9
$V 	#s   -AAA
Ac                      e Zd ZdZy)AllExitz.Custom exception class to exit All(...) early.N)r   r   r   rZ  r   r   r   r  r    s    8r   r  c           	        | \  }}t        |t              st        |       y |j                  d      }t        |t              st        d|      |j                  d      }|dk(  rt        j                  }n&|dk(  rt        j                  }n|t        d|      t        ||j                  d      |j                  d      ||j                  d	      d
 y )Nargsz5_handle_print: client received non-tuple print args: filer      z7_handle_print: client received unsupported file kwarg: sependflush)r  r  r  r  )	r  dictprintr   r   r,  r\  stdoutstderr)rk  rz  r   r  r  s        r   _handle_printr    s    FAsc4  	c
776?DdE" CD8L
 	
 776?Dqyzz	zz		EdXN
 	
 
	3775>swwu~DPWHXr   c                   | \  }}t        |t              st        j                  |       y d|vrt	        d      d|v rt        j                  |d         }nd }t        j                  t        j                  |d         |       y )NmessagezS_handle_warn: client received a warn event missing the required "message" argument.category)r  )r  r  warningswarnr,  picklera   )rk  rz  r   r  s       r   _handle_warnr    s    FAsc4  	cC &  ||C
O4HHLLY(	
r   c                    t         j                  j                  d      }|r	 t        |      } |d| i      S y # t        $ r}t        d| d      |d }~ww xY w)Nz"distributed.client.security-loaderzFailed to import `zP` configured at `distributed.client.security-loader` - is this module installed?address)daskconfigr   ro   	ExceptionImportError)r  security_loader_termsecurity_loaderr  s       r   _maybe_call_security_loaderr  $  su    ;;??+OP	)*>?O 	7344  	$%9$: ;  		s   9 	AAAc                  ,    e Zd ZU ded<   ded<   ded<   y)VersionsDictzdict[str, dict[str, Any]]	schedulerz$dict[str, dict[str, dict[str, Any]]]workersr   Nr   r   r   r   r  r  3  s    ((11%%r   r  r|   _T_LowLevelGraphc                z    | D ]6  }t        |t              st        |t              r%t        |t              r6 y y)NTF)r  r   r   bytes)iterableitems     r   
_is_nestedr  <  s2    tX&tS)tU+  r   c                       e Zd ZU ded<   ded<   ded<   ded<   d	ed
<   	 	 	 d	 	 	 	 	 	 	 	 	 d fdZddZedd       Zedd       ZddZ	d Z
ddZddZddZddZddZ xZS ) 	_MapLayerr   funcIterable[Any]	iterablesstr | Iterable[str] | Noner   boolpuredict[str, Any] | Noner   c           	     "   || _         |D cg c]  }t        t        t        |             c}| _        || _        || _        |j                         D 	ci c]  \  }}	|t        |	       c}	}| _        t        
| )  |       y c c}w c c}	}w )Nr   )r  r   r   rE   r  r   r  itemsr  superr   )r   r  r  r   r  r   r  r  r   vr   s             r   r   z_MapLayer.__init__N  s     #	LUVI%K :;IV/2	5;\\^D^TQq+a.(^D[1	 W Es    BBc                ^    t        |       j                   dt        | j                         dS )Nz <func='z'>)r   r   r3   r  r   s    r   rK  z_MapLayer.__repr__^  s*    t*%%&hx		/B.C2FFr   c                |    |  t        | d      r| j                  S | j                         }|| _        | j                  S N_cached_dict)hasattrr  _construct_graph)r   dsks     r   _dictz_MapLayer._dicta  s?     4($$$'')C #D   r   c                   t        | d      r| j                  S t        | j                  t              r7t        | j                  t
              s| j                  | _        | j                  S | j                  rZt        | j                  | j                        }t        | j                   D cg c]  }| j                  dz   t        ||      z     }}nwt        t        j                               }| j                  rLt        t        t!        t"        | j                                    D cg c]  }| j                   d| d|  c}ng }|| _        |S c c}w c c}w )N_cached_keys-)r  r  r  r   r   r   r  r,   r  r  zipr  r_  r`  rangeminr   r   )r   tokr  r   uidis         r   _keysz_MapLayer._keysm  s)   4($$$$((H-j36O3788!xx 99"499dkk:C %($8$8D 3#t)<<$8  
 djjl+C  >> &+3s3/G+H%I%I  $xxj#as3%I
    %)!s   *#E'Ec                ,    t        | j                        S r   )rn  r  r   s    r   get_output_keysz_MapLayer.get_output_keys      4::r   c                ,    t        | j                        S r   )r   r  r   s    r   get_ordered_keysz_MapLayer.get_ordered_keys      DJJr   c                    t        | d      S r  )r  r   s    r   is_materializedz_MapLayer.is_materialized  s    t^,,r   c                     | j                   |   S r   )r  rg  s     r   __getitem__z_MapLayer.__getitem__  s    zz#r   c                ,    t        | j                        S r   )iterr  r   s    r   __iter__z_MapLayer.__iter__  r  r   c                ,    t        | j                        S r   )r   r  r   s    r   __len__z_MapLayer.__len__  r  r   c                l   i }| j                   sPt        | j                  t        | j                         D ci c]  \  }}|t	        || j
                  g|  }}}|S i }i }| j                   j                         D ]  \  }}t        |      dkD  r/t        ||      }|j                         ||<   |||j                  <   n|||<   |j                  t        | j                  t        | j                         D ci c]   \  }}|t	        || j
                  g|i |" c}}        |S c c}}w c c}}w )Ng     j@)r  r  r  r  rC   r  r  re   r@   refr   update)r   r  r   r  kwargs2r   r  vvs           r   r  z_MapLayer._construct_graph  s2    "{{ "%TZZdnn1E!F!FIC T#tyy0400!F  , 
! GC))+1!9s?!!QB!#GAJ"$CK!"GAJ

 *-TZZdnn9M)N)NIC T#tyyC4C7CC)N , 
-"s   "D*9%D0)NTN)
r  r   r  r  r   r  r  r  r   r  r   )r   r  )r   zIterable[Key])r   zset[Key])r   r  )r   r-   r   rA   )r   zIterator[Key])r   r   )r   r   r   r   r   rK  rb  r  r  r  r  r  r  r  r  r  __classcell__)r   s   @r   r  r  G  s    
N	##
J&& +/-122 !2 (	2
 2 +2 G 	! 	!  8 - r   r  c                  j   e Zd ZU dZ eej                        Zded<    e	j                         Zded<   eedZded<   d	Zd
ed<   d	d	edd	d	dd	d	d	d	ed	dfdZedd       Zej*                  dd       Zedd       Zej*                  dd       Zed        Zedd       Zed        Zd Zd Zd Zd Zd Z d Z!d Z"efdZ#e$d        Z%dd Z&d! Z'	 d	 	 	 	 	 dd"Z(ddd#Z)d$ Z*d% Z+d& Z,d' Z-d( Z.d) Z/d* Z0d+ Z1d, Z2e$d-        Z3dd.Z4dd/Z5d0 Z6dd1Z7dd2Z8d3 Z9dd4Z:e;dd5       Z<e$ddd6       Z=efd7Z>d8 Z?d9 Z@d: ZAd	d	d	d	d;d<ddddd=
d>ZBd	d	d	d	d;dd<dddd	d?	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd@ZCddBZDddCZEddDZFd	dd	d	edfdEZGd	dd	ded	fdFZHddGZIddHZJdI ZKddJZLe$d	ddKdL       ZMdM ZNdN ZOdO ZPefdPZQefdQZRddRdSZSdT ZTdd	ddAdU	 	 	 	 	 	 	 ddVZUd	dddAdW	 	 	 	 	 	 	 ddXZVe	 d	 	 	 	 	 ddY       ZWdZ ZX	 	 	 	 	 	 	 	 dd[ZY	 	 	 	 	 	 	 	 	 	 dd\ZZd] Z[d^ Z\	 	 	 	 	 	 	 	 	 	 dd_Z]	 	 	 	 	 	 	 	 dd`Z^	 	 	 	 	 	 ddaZ_edf	 	 	 ddbZ`	 	 	 	 	 	 	 	 ddcZaedf	 	 	 	 	 dddZbddeZcdddfZdddgZeddhZfddiZgddjZhddkZieiZjddlZkddmZlddnZmddoZnddpZo	 	 	 	 	 	 	 	 	 ddqZp	 	 	 	 	 	 	 	 	 ddrZqds Zr	 	 	 	 d	 	 	 	 	 	 	 dduZsdtd	etj                  etj                  f	 	 	 	 	 	 	 ddvZwdw ZxefdxZyddyZzddzZ{dd{Z|dd|Z}ddd}Z~d~ Zd Zd Z	 d	 	 	 ddZd Z	 d	 	 	 	 	 ddZ	 d	 	 	 	 	 ddZd Zed        Zed        ZdAdddZdAddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZe	 	 	 	 	 	 dd       Zej                   dd       Zej                   	 	 	 	 	 	 	 	 dd       Zej                   dd       Z	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZd Zd ZddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZddZddZed        Zd Zd	ej>                  fdZddZy	)r   a  Connect to and submit computation to a Dask cluster

    The Client connects users to a Dask cluster.  It provides an asynchronous
    user interface around functions and futures.  This class resembles
    executors in ``concurrent.futures`` but also allows ``Future`` objects
    within ``submit/map`` calls.  When a Client is instantiated it takes over
    all ``dask.compute`` and ``dask.persist`` calls by default.

    It is also common to create a Client without specifying the scheduler
    address , like ``Client()``.  In this case the Client creates a
    :class:`LocalCluster` in the background and connects to that.  Any extra
    keywords are passed from Client to LocalCluster in this case.  See the
    LocalCluster documentation for more information.

    Parameters
    ----------
    address: string, or Cluster
        This can be the address of a ``Scheduler`` server like a string
        ``'127.0.0.1:8786'`` or a cluster object like ``LocalCluster()``
    loop
        The event loop
    timeout: int (defaults to configuration ``distributed.comm.timeouts.connect``)
        Timeout duration for initial connection to the scheduler
    set_as_default: bool (True)
        Use this Client as the global dask scheduler
    scheduler_file: string (optional)
        Path to a file with scheduler information if available
    security: Security or bool, optional
        Optional security information. If creating a local cluster can also
        pass in ``True``, in which case temporary self-signed credentials will
        be created automatically.
    asynchronous: bool (False by default)
        Set to True if using this client within async/await functions or within
        Tornado gen.coroutines.  Otherwise this should remain False for normal
        use.
    name: string (optional)
        Gives the client a name that will be included in logs generated on
        the scheduler for matters relating to this client
    heartbeat_interval: int (optional)
        Time in milliseconds between heartbeats to scheduler
    serializers
        Iterable of approaches to use when serializing the object.
        See :ref:`serialization` for more.
    deserializers
        Iterable of approaches to use when deserializing the object.
        See :ref:`serialization` for more.
    extensions : list
        The extensions
    direct_to_workers: bool (optional)
        Whether or not to connect directly to the workers, or to ask
        the scheduler to serve as intermediary.
    connection_limit : int
        The number of open comms to maintain at once in the connection pool

    **kwargs:
        If you do not pass a scheduler address, Client will create a
        ``LocalCluster`` object, passing any extra keyword arguments.

    Examples
    --------
    Provide cluster's scheduler node address on initialization:

    >>> client = Client('127.0.0.1:8786')  # doctest: +SKIP

    Use ``submit`` method to send individual computations to the cluster

    >>> a = client.submit(add, 1, 2)  # doctest: +SKIP
    >>> b = client.submit(add, 10, 20)  # doctest: +SKIP

    Continue using submit or map on results to build up larger computations

    >>> c = client.submit(add, a, b)  # doctest: +SKIP

    Gather results with the ``gather`` method.

    >>> client.gather(c)  # doctest: +SKIP
    33

    You can also call Client with no arguments in order to create your own
    local cluster.

    >>> client = Client()  # makes your own local "cluster" # doctest: +SKIP

    Extra keywords will be passed directly to LocalCluster

    >>> client = Client(n_workers=2, threads_per_worker=4)  # doctest: +SKIP

    See Also
    --------
    distributed.scheduler.Scheduler: Internal scheduler
    distributed.LocalCluster:
    r   r   z!ClassVar[weakref.WeakSet[Client]]
_instances)r  r  zpreloading.PreloadManagerpreloadsNIOLoop | None_Client__loopTFi   c           	        |t         u rt        j                  j                  d      }t	        |d      }|t        d      || _        t               | _        t        t              | _        d | _        | t        j                  j                  dd       }t        |       j                  |rd|z   dz   ndz   t        t!        j"                  t%        j&                                     z   | _        d| _        d| _        g | _        i | _        || _        || _        d | _        d | _        i | _        t=        j>                         | _         tC        |       | _"        |
| _#        ||
}|| _$        || _%        d | _&        d | _'        |8t        j                  j                  d	d       }|rtP        jS                  d
|       ||rt        dtU        |             tW        |tX        tZ        f      r|| _        ntW        t]        |dd       t              r|| _        | j6                  j,                  }|t^        j`                  t^        jb                  fv rte        d| j6                   d      tg        th              5  |jj                  }d d d        |Mt]        | j6                  dd       }n5|3tW        |t              s#tm        djo                  t        |                  |tW        |t              rtq        |      }|ts               }n_tW        |t              rts        d'i |}nC|du r$ts        jt                         }|| j4                  d<   ntW        |tr              stm        d      || _;        |dk(  r!| jv                  jy                  d      | _=        n | jv                  jy                  d      | _=        || _>        t        ||      | _@        d| _A        d | _B        d | _C        |	t        j                  j                  d      }	t	        |	d      }	t	        t        j                  j                  dd            }t               | _D        t        | j                  |dz        | j                  d<   t        | j                  |	dz        | j                  d<   || _H        || _I        |r%t        j                  j                  d      | _K        i | _L        | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  d | _U        | j                  | j                  | j                  d!| _V        t        ||
|d| jz                  || "      | _,        |j                         D ci c]  \  }}| ||        c}}| _        t        j                  j                  d#      }t        j                  j                  d$      }t        j                  | ||      | _[        | j                  |%       t        j                  j                  |        dd&l`ma}  ||        y # 1 sw Y   xY wc c}}w )(Nz!distributed.comm.timeouts.connectr   z2None is an invalid value for global client timeoutzclient-namer  )	clock_seqr   newly-createdzscheduler-addressz*Config value `scheduler-address` found: %szUnexpected keyword arguments: scheduler_addressz:Trying to connect to an already closed or closing Cluster r   securityz@Scheduler address must be a string or a Cluster instance, got {}Tz"security must be a Security objectworkerr   r-  asynchronousFzdistributed.client.heartbeatmsr   z*distributed.client.scheduler-info-intervali  zscheduler-info	heartbeatdask.distributedr  )zkey-in-memoryz	lost-datazcancelled-keysztask-retriedz
task-erredrestartr   rk  )memoryrs  erred)limitserializersdeserializersdeserializeconnection_argsr  serverzdistributed.client.preloadzdistributed.client.preload-argvr  )ReplayTaskClientr   )br0   r  r  r   r5   
ValueError_timeoutr  r   r   r   refcount_handle_report_taskr   r   r   r_  uuid1r*  r+  idr   r   _pending_msg_buffer
extensionsscheduler_file_startup_kwargsclusterr  _scheduler_identity	threadingRLock_refcount_lockrb   datasets_serializers_deserializersdirect_to_workers_previous_as_currentscheduler_commr$  infor   r  rS   rO   getattrrP   r   closingr   r   rE  r-  r,  formatr  rd   	temporaryr  get_connection_argsr  _asynchronousri   _loop_runner_connecting_to_scheduler_gather_keys_gather_future_periodic_callbacksrL   _update_scheduler_info
_heartbeat
_start_argr   rn  _set_config_event_handlers_handle_key_in_memory_handle_lost_data_handle_cancelled_keys_handle_retried_key_handle_task_erred_handle_restart_handle_error_handle_event_stream_handlersr   rN   r  rG   process_preloadsr  startr   r  adddistributed.recreate_tasksr  )r   r  r-  r  set_as_defaultr  r  r  nameheartbeat_intervalr  r  r  r  connection_limitr  r   scheduler_info_interval	extensionpreloadpreload_argvr  s                         r   r   zClient.__init__   s   $ j kkoo&IJG!'3/?QRRv#C(#' <;;??=$7DJ#'sTzCS2$**ryy{345 	
 %#% ,%#% 
 (oo/ ' 'M+!2$(! #?kkoo&94@GH'R6=fVn=MNOOg]34$DN)<dCSI"DL\\((F&--88"PQUQ]Q]P^^_`  .)|| *"4<<TB GS)ARYYM  
7C 827;HzH$'+(+H))+H/7D  ,Hh/@AA 8#'==#D#DX#ND #'==#D#DX#ND )&D|L(-% "%!%1O!P,-?N"1KKOOHRVOW#
 $(6 5E'')@4)G6
  !12 1AOO/$61
  - "-#{{9KLD! "77//"99 4411++''''	!
 00**,, 
 ""#' 00
 :D9I9I9K
9KodID)D/!9K
 ++//">?{{'HI"33D'<P

7
#d#?M *)r
s   1X;Y;Yc                R    t        j                  dt        d       | j                  S Nz"The io_loop property is deprecatedr  
stacklevelr  r  DeprecationWarningr-  r   s    r   io_loopzClient.io_loop  s#    02DQR	
 yyr   c                J    t        j                  dt        d       || _        y r:  r=  r   values     r   r?  zClient.io_loop  s     02DQR	
 	r   c                \    | j                   }|| j                  j                  x| _         }|S r   )r  r  r-  )r   r-  s     r   r-  zClient.loop  s/    {{<
 "&!2!2!7!77DK$r   c                J    t        j                  dt        d       || _        y )Nz'setting the loop property is deprecatedr  r;  )r  r  r>  r  rA  s     r   r-  zClient.loop  s     57IVW	
 r   c              #  
  K   t         j                  |       }t        j                  j                  d      5  	 d t         j	                  |       	 ddd       y# t         j	                  |       w xY w# 1 sw Y   yxY ww)zThread-local, Task-local context manager that causes the Client.current
        class method to return self. Any Future objects deserialized inside this
        context manager will be automatically attached to this Client.
        r  r  N)r~   rn  r  r  r  )r   r  s     r   
as_currentzClient.as_current  sc      !!$'[[__'9_:+%%c*	 ;:  %%c*	 ;:s2   6BA7AA7	BA44A77B <Bc                `    t         j                         }|r|S |r
t               S t        d      )a  When running within the context of `as_client`, return the context-local
        current client. Otherwise, return the latest initialised Client.
        If no Client instances exist, raise ValueError.
        If allow_global is set to False, raise ValueError if running outside of
        the `as_client` context manager.

        Parameters
        ----------
        allow_global : bool
            If True returns the default client

        Returns
        -------
        Client
            The current client

        Raises
        ------
        ValueError
            If there is no client set, a ValueError is raised

        See also
        --------
        default_client
        z3Not running inside the `as_current` context manager)r~   r   default_clientr  )r1  allow_globalouts      r   currentzClient.current  s2    6 !!#J!##NOOr   c                   	 | j                   j                  S # t        $ rh | j                         \  }}|Y y|j                  j                  d      \  }}|d   d   }|dk(  rd}n|j                  d      d   }t        ||      cY S w xY w)	am  Link to the scheduler's dashboard.

        Returns
        -------
        str
            Dashboard URL.

        Examples
        --------
        Opening the dashboard in your default web browser:

        >>> import webbrowser
        >>> from distributed import Client
        >>> client = Client()
        >>> webbrowser.open(client.dashboard_link)

        N://services	dashboardinproc	localhost:r   )r  dashboard_linkrE  _get_scheduler_infor  splitrm   )r   r  r  protocolrestporthosts          r   rS  zClient.dashboard_link%  s    &	5<<... 	5"668OIt !*!2!2!8!8!?$
#K0D8#"zz#q)(t44	5s    B	AB	B	c                $   ddl m} | j                  rqt        | j                  d      r[t	        | j                  j
                  |      r;| j                  j
                  j                         }| j                  j
                  }n| j                  j                         rO| j
                  rC| j                  s7t        | j                  | j
                  j                        }| j
                  }n| j                  }| j
                  }|t        |      fS )Nr   )	Schedulerr  )distributed.schedulerr[  r  r  r  r  identityr  
is_startedr  rr   r-  r	  r]   )r   r[  r  r  s       r   rT  zClient._get_scheduler_infoI  s    3 LLk24<<119=<<))224D..I((*t~~dFWFW		4>>#:#:;DI++DI----r   c                V   | j                   }|j                  d      }|r|j                  di       }t        |      }t        d |j	                         D              }d| j
                  j                  |||fz  }|j	                         D cg c]  }|d   	 }}t        |      r|dt        t        |            z   z  }|dz  }|S | j                  :dj                  | j
                  j                  | j                  j                        S d	| j
                  j                   d
S c c}w )Nr  r  c              3  &   K   | ]	  }|d      yw)nthreadsNr   ).0ws     r   	<genexpr>z"Client.__repr__.<locals>.<genexpr>e  s     C2BQ1Z=2B   z<%s: %r processes=%d threads=%dmemory_limitz	, memory=rJ  z<{}: scheduler={!r}>r  z: No scheduler connected>)r	  r   r   r   valuesr   r   allr2   r  r  r  )	r   r  addrr  nworkersra  textrc  r  s	            r   rK  zClient.__repr__^  s   ''xx	"hhy"-G7|HC'..2BCCH4''	8 D 291AB1AAa'1AFB6{l3v;&???CKDK^^')00''&& 
 t~~..//HII Cs   D&c           	     *   	 t        t        d            }|t        d      k  rdnd}| j                         \  }}t	        d      j                  | j                  ||| j                  | j                  | j                  |      S # t        $ r d}Y iw xY w)Nzdask-labextensionz6.0.0FTzclient.html.j2)r  r  r  r  r  rS  
jupyterlab)
parse_versionr   r   rT  r8   rM  r  r  r  rS  )r   dle_version
JUPYTERLABr  r  s        r   rN  zClient._repr_html_z  s    	'0C(DEK"-g0F"FDJ 224	4,-44wwLL....! 5 
 	
 $ 	J	s   &B BBc                6   | j                   dk7  ry| j                  j                          | j                  rt	        |        | j
                  r+t        j                   | j                  di |      | _	        yt        | j                  | j                  fi | y)z*Start scheduler running in separate threadr  Nr   )r   r  r.  r   r   r  ri  ensure_future_start_startedrr   r-  r8  s     r   r.  zClient.start  st    ;;/)!t$#11+$++2G2GHDMDKK262r   c                     t         d      r j                  j                         S  fd} |       j                         S )Nrt  c                    K    S wr   r   r   s   r   rz  zClient.__await__.<locals>._  s     s   )r  rt  rP  )r   rz  s   ` r   rP  zClient.__await__  s5    4$==**,, 3==?"r   c                    | j                   dv r	 | j                  j                  |       y | j                   dv r| j
                  j                  |       y y # t        t        f$ r | j                   dk(  r Y y w xY w)N)runningr  rx  )
connectingr  )r   r  sendrM   rE  r  appendr   r   s     r   _send_to_scheduler_safezClient._send_to_scheduler_safe  sz    ;;00##((- [[;;$$++C0 < $^4 ;;)+ ,s   A A98A9c                    | j                   dv r'| j                  j                  | j                  |       y t	        d| j                   d|      )N)rx  r  ry  r  z.Tried sending message after closing.  Status: z

Message: )r   r-  r.  r}  r  r|  s     r   _send_to_schedulerzClient._send_to_scheduler  sD    ;;OOII""4#?#?E!%c3 r   c                  K   d| _         | j                  j                          d {    |t        u r| j                  }t        |d      }| j                  }| j                  -	 | j                   d {    | j                  j                  }n%| j                  t        j                  j                  | j                        sGt!        j"                  d       d {    t        j                  j                  | j                        sGt%        d      D ]<  }	 t'        | j                        5 }t)        j*                  |      }d d d        d   } n` n^| j                  Rd	d
lm}  |d| j4                  | j6                  d| j8                   d {   | _        | j                  j                  }t!        j:                  d      | _        | j>                  | j                  |      | _        d | _         	 | jC                  |       d {    | jJ                  jM                         D ]  }|j                           tN        jP                  jS                         D ]  \  }	}
| jU                  |	|
        | jV                  j                          d {    t!        jX                  | j[                               | _.        | S 7 7 V# t        $ r t        j                  dd       Y ww xY w7 # 1 sw Y   xY w# t,        t.        f$ r" t!        j"                  d       d {  7   Y w xY w7 7 ,# tD        tF        f$ r | jI                          d {  7    w xY w7 ҭw)Nry  r   z9Tried to start cluster and received an error. Proceeding.T)exc_infog{Gz?
   r  r   )LocalClusterr     r  r   )/r   rS   r.  r0   r  r5   r!  r  r  r$  r  r  r  r*  pathexistsri  sleepr  openjsonloadr  r   distributed.deployr  r-  r  r  	Semaphore_gather_semaphorer  r  _ensure_connectedOSErrorr  _closer  rg  r   _default_event_handlersr  subscribe_topicr  create_task_handle_reportr  )r   r  r  r  rz  fcfgr  pctopicr   s              r   rs  zClient._start  s    "hhnnj mmG!'3///<<#ll"" ll44G  ,ggnnT%8%89mmD))) ggnnT%8%892Y.d112a"iil 3!)nG  __$7!- "YY!//" &&" DL
 ll44G!(!2!21!5>>!!XXg.DN"	(((999
 **113BHHJ 4 %<<BBDNE7  0 E mm!!####*#6#6t7J7J7L#M y 	 # O!   * 32 #H- .!-----.
 :% 	++-	 	$s   %M-K<M-%K 4K
5K 9A%M-K4-M-M-L1K7LAM-L8A"M-:L> L;L> BM-M+/M-
K  K1-M-0K11M-7L	<L'L5+L.,L51M-4L55M-;L> >"M( M#!M((M-c                  K   | j                   j                  j                         sJ d| _        d | _         | j                  j                         D ]  }|j                  dd        | j                  j                          | j                  }t               |z   }|dkD  r+| j                  dk(  r	 | j                  |       d {    y t         j#                  d| j                         | j                          d {    y 7 ># t        $ r. t        j                  d       d {  7   |t               z
  }Y n't        $ r | j                          d {  7   Y y w xY w|dkD  s| j                  dk(  rʌ7 {w)	Nry  zscheduler-connection-lostz_Client lost the connection to the scheduler. Please check your connection and re-run your work.r4  r   r  皙?zCFailed to reconnect to scheduler after %.2f seconds, closing client)r  commr   r   r   rg  r5  ru  r  r[   r  r  ri  r  r  r  r$  r   )r   str  deadlines       r   
_reconnectzClient._reconnect  sM    ""''..000"",,%%'BII2I   ( 	--6G#kdkk\9	,,W,=== LL*
 ++-! > ,mmC((("TV+ kkm## kdkk\9$  sx   B.E=1D DD 4E=?E; E=D !E!(D+)E!;E==E!EE!E= E!!E=*E=;E=c                  K   | j                   r| j                   j                         r| j                  s| j                  y d| _        	 t	        | j                  j
                  fd|i| j                   d {   }d|_        |#t        | j                         |       d {    n| j                          d {    |j                  d| j                  dt        j                         d       d {    	 d| _        |#t        |j!                         |       d {   }n|j!                          d {   }t#        |      dk(  sJ |d	   d
   dk(  sJ |d	   j%                  d      rt'        |d	   d         |d	   j%                  d      r.t)        j*                  t        j,                  |d	   d                t/        d| j0                        }|j3                  |       || _         d| _        | j4                  D ]  }| j7                  |        | j4                  d d = t8        j;                  d       y 7 7 7 7 T# t        $ r | j                  dk(  r	Y d| _        y  w xY w# d| _        w xY w7 ]7 Gw)NTr  zClient->Schedulerzregister-clientF)opr   replyrH   r   r   r   r  zstream-startr   warning10ms)intervalr-  rx  z+Started scheduling coroutines. Synchronized)r  r   r  r  rR   r  r  r2  r<   r  writer  version_moduleget_versionsr  r   readr   r   r  r  r  VersionMismatchWarningrI   r-  r.  r  r  r$  debug)r   r  r  r   bcomms        r   r  zClient._ensure_connected   sL    ''..0,,~~%(,%	2 &&07;?;O;O D ,DI"t::<gFFF11333**+"gg" . ; ; =	   -2D) g66C		#C3x1}}1vd|~---q6::gc!fWo..q6::i MM.??Ay@QRSV$))<D#++C##C( ,$$Q'BCY
 G3  	{{h& -2D) 		 -2D)6#s   AJ
/I 9I:*I $I%I =I>9I 7I8I =&J#J $J<J=DJI I I I I1&I4 'J/I11I4 4	I==JJc                   K   | j                   dvs| j                  y 	 t        | j                  j                          d {         | _        y 7 # t
        $ r t        j                  d       Y y w xY ww)N)rx  ry  z(Not able to query scheduler for identity)r   r  r]   r]  r	  r  r$  r  r   s    r   r  zClient._update_scheduler_infoZ  sb     ;;774>>;Q	E'44>>;R;R;T5T'UD$5T 	ELLCD	Es:   A6"A AA A6A A30A62A33A6c                  K   | j                   j                          d {   }t        |      | _        |rt	               t        |      z   }nd }d } ||      |k  r|r$t	               |kD  rt        d ||      ||fz        t        j                  d       d {    | j                   j                          d {   }t        |      | _         ||      |k  ry y 7 7 F7 &w)Nc                    t        | d   j                         D cg c]$  }|d   t        j                  j                  k(  r|& c}      S c c}w )Nr  r   )r   rg  rP   rx  r2  )r  wss     r   running_workersz1Client._wait_for_workers.<locals>.running_workersl  sT     #9o4466(|v~~':':: 6 s   )Az#Only %d/%d workers arrived after %sr  )	r  r]  r]   r	  r[   r5   rl   ri  r  )r   	n_workersr  r  r  r  s         r   _wait_for_workerszClient._wait_for_workersb  s      ^^,,..#0#6 v 88HH	 d#i/DFX-"9&t,iAB  --$$$0022D'4T':D$ d#i/! /, %2s:   C'C!A;C'C#!C'>C%?C'C'#C'%C'c                   t        |t              r|dk  rt        d| d      | j                  r2t	        | j                  d      r| j                  j                  ||      S | j                  | j                  ||      S )a#  Blocking call to wait for n workers before continuing

        Parameters
        ----------
        n_workers : int
            The number of workers
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        r   z4`n_workers` must be a positive integer. Instead got r   wait_for_workersr  )r  r   r  r  r  r  rr   r  )r   r  r  s      r   r  zClient.wait_for_workers  sw     )S)Y]FykQRS  <<GDLL2DE<<00GDDyy//GyLLr   c                (   | j                   | j                   j                  j                         sa| j                  r6| j                  j                  t
        j                  t
        j                  fv s| j                   j                  ddi       y y y y )Nr  zheartbeat-client)r  r  r   r  r   rP   r  rz  r   s    r   r   zClient._heartbeat  su    *$$++-!4!48W!W$$d,>%?@ "X . +r   c                    | j                   j                         s| j                          | j                  rt        j                  |       | _        | S r   )r  r^  r.  r   r~   rn  r  r   s    r   	__enter__zClient.__enter__  s>      ++-JJL(7(;(;D(AD%r   c                r   K   |  d {    | j                   rt        j                  |       | _        | S 7 ,wr   )r   r~   rn  r  r   s    r   
__aenter__zClient.__aenter__  s3     

(7(;(;D(AD% 	s   75-7c                B  K   | j                   r 	 t        j                  | j                          | j                  |d u       d {    y # t        $ rE}|j                  d   j                  d      s t        j                  dt        d       Y d }~fd }~ww xY w7 Vw)Nr   # was created in a different ContextzRIt is deprecated to enter and exit the Client context manager from different tasksr  r;  fast)
r  r~   r  r  r  endswithr  r  r>  r  r   exc_type	exc_valuer  es        r   	__aexit__zClient.__aexit__  s     $$
%%d&?&?@ kk $&  
 	
 	
  vvay))*OP3& 	 	
s9   BA BBB	B;BBBBc                   | j                   r 	 t        j                  | j                          | j                          y # t        $ rE}|j                  d   j                  d      s t        j                  dt        d       Y d }~Zd }~ww xY w)Nr   r  zTIt is deprecated to enter and exit the Client context manager from different threadsr  r;  )
r  r~   r  r  r  r  r  r  r>  closer  s        r   __exit__zClient.__exit__  sw    $$
%%d&?&?@ 	

  vvay))*OP5& 	 s   > 	B;BBc                >    | j                   | j                          y y r   )r  r  r   s    r   rF  zClient.__del__  s     ;;"JJL #r   c                t    | j                   5  | j                  |xx   dz  cc<   d d d        y # 1 sw Y   y xY wNr   )r  r   rg  s     r   r   zClient._inc_ref  s+      MM#!# !  s   .7c                    | j                   5  | j                  |xx   dz  cc<   | j                  |   dk(  r| j                  |= | j                  |       d d d        y # 1 sw Y   y xY w)Nr   r   )r  r   _release_keyrg  s     r   r?  zClient._dec_ref  sV      MM#!#}}S!Q&MM#&!!#&	 !  s   AAA'c                    t         j                  d|       | j                  j                  |d      }||j	                          | j
                  dk7  r!| j                  d|g| j                  d       yy)z#Release key from distributed memoryzRelease key %sNr   zclient-releases-keysr  r   r   )r$  r  r   popr5  r   r  r  )r   r   r  s      r   r  zClient._release_key  sd    %s+\\c4(>IIK;;("##-uP #r   c                f  K   	 	 | j                   y	 | j                   j                  j                          d{   }t        |t        t         f      s|f}d}|D ]  }t        j#                  d| j$                  |       d	|v r'd
|d	   v r t'        di |\  }}}|j)                  |      |j+                  d      }|dk(  s|dk(  rd} n9	 | j,                  |   } |di |}	t/        j0                  |	      r
|	 d{     |ry7 # t        $ r | j	                         rY y| j
                  dk(  r| j                  rQ| j                  j
                  t        j                  t        j                  fv r| j                          d{  7   Y yt        j                  d       t        j                  d       d| _        | j                          d{  7   Y Y yw xY w7 # t2        $ r }
t        j5                  |
       Y d}
~
d}
~
ww xY w# t6        t8        j6                  f$ r Y yw xY ww)zListen to schedulerTNrx  z(Client report stream closed to schedulerzReconnecting...ry  FzClient %s receives message %sr   r   r  r  zstream-closedr   )r  r  r  rM   r   r   r  rP   r   r  r  r$  r  r  r  r   r   r  r  rQ   r  r  r,  inspectisawaitabler  r  rh   ri  )r   msgsbreakoutr   r  r  r  r  r   r   r  s              r   r  zClient._handle_report  s    4	&&.!%!4!4!9!9!>!>!@@D( "$u6 7D CLL!@$''3O37c(m+C'6'='=S"!0044BW}o(=#',"&"7"7";!(3"..v6"(LL#  ( c  A& **,{{i/<<DLL,?,?"MM"NND - #'++-//"$NO$56&2"oo/// %P )$ ,((++,  6 67 		s   H1H H1'D
 DD
 BH 1G&<G$=G&H H1H D
 
G!#H $H1%A$G!	F
G!H H1AG!GG!H H1 G!!H $G&&	H/H
H 
HH H.+H1-H..H1c                    | j                   j                  |      }|/|r|j                  s	 t        |      }nd }|j                  |       y y # t        $ r d }Y  w xY wr   )r   r   r   ra   r  rq  )r   r   r   r  r   s        r   r$  zClient._handle_key_in_memory   sa      %EJJ  ;D LL  !  D s   A AAc                `    | j                   j                  |      }||j                          y y r   )r   r   rv  r   r   r   s      r   r%  zClient._handle_lost_data.  s*      %JJL r   c                n    |D ]0  }| j                   j                  |      }|!|j                          2 y r   )r   r   r5  )r   r   r   r   s       r   r&  zClient._handle_cancelled_keys3  s/    CLL$$S)E  r   c                `    | j                   j                  |      }||j                          y y r   )r   r   r7  r  s      r   r'  zClient._handle_retried_key9  s*      %KKM r   c                d    | j                   j                  |      }||j                  ||       y y r   )r   r   r{  )r   r   r  r  r   s        r   r(  zClient._handle_task_erred>  s/      %OOIy1 r   c                f   t         j                  d       | j                  j                         D ]  }|j	                  dd        | j                  j                          | xj                  dz  c_        | j                  5  | j                  j                          d d d        y # 1 sw Y   y xY w)Nz%Receive restart signal from schedulerzscheduler-restartz1Scheduler has restarted. Please re-run your work.r4  r   )	r$  r  r   rg  r5  ru  r   r  r   )r   r   s     r   r)  zClient._handle_restartC  s    ;<\\((*ELL*G   +
 	1  MM! !  s   B''B0c                X    t         j                  d       t         j                  |       y )NzScheduler exception:)r$  r  r  )r   r  s     r   r*  zClient._handle_errorO  s    -.#r   c                 K   t        j                         }| j                  }|d uxr ||u}|rNt        t         j                  t
              5  t        t        j                  |      d       d {    d d d        d  |r@t        t
        t         j                        5  t        ||rdnd       d {    d d d        y y 7 T# 1 sw Y   SxY w7 # 1 sw Y   y xY ww)Nr  r   r  )ri  current_taskr  r   rh   rl   r<   shield)r   r  r  handle_report_taskshould_waits        r   _wait_for_handle_report_taskz#Client._wait_for_handle_report_taskS  s     ++-!55 d*U/A/U 	 '00,?w~~.@A3GGG @ 	,(>(>?11!DDD @? 	 H @? E @?sZ   AC!#C0C1C5-C!"C6C7C;
C!CCC!CCC!c                  K   | j                   dk(  ryd| _         | j                  j                          d{    t        t              5  | j
                  j                         D ]  }|j                           	 ddd       t        |        i | _	        | j                  r8t               s.t        t              5  | j                  5  	 ddd       ddd       | j                  t        j                  j                  dd      k(  rt        j                  j                  d= | j                   r`| j                   j"                  rJ| j                   j"                  j%                         s&| j'                  ddi       | j'                  ddi       | j)                  |      4 d{    | j                   r\| j                   j"                  rF| j                   j"                  j%                         s"| j                   j+                          d{    t-        | j.                        D ]  }| j1                  |	        | j2                  :t        t              5  | j4                  j+                          d{    ddd       | j6                  j+                          d{    d| _         t               | u rt9        d       ddd      d{    t        t              5  | j:                  j=                          d{    ddd       d| _        d| _         y7 # 1 sw Y   xY w# 1 sw Y   dxY w# 1 sw Y   ixY w7 7 =7 # 1 sw Y   xY w7 7 # 1 d{  7  sw Y   xY w7 r# 1 sw Y   qxY ww)
zSend close signal and wait until scheduler completes

        If fast is True, the client will close forcefully, by cancelling tasks
        the background _handle_report_task.
        r   Nr  r   r  zclose-clientzclose-streamr  r   )r   r  teardownr   rE  r  rg  stopr   r	  r   r   r"  r   r  r  r  r  r   r  r  r  r   r   r  r!  r  rS   r   r  	close_rpc)r   r  r  r   s       r   r  zClient._closef  s     ;;("mm$$&&&n%..557	 8 & 	4 #% (:(<.)%% & * 88t{{ud33""5) ##(('',,335##T>$:;##T>$:;44$4??##'',,++00779))//111DLL)!!c!* * &n-,,,,... . ((..""""DK!#t+"4() @?, n%..**,,, & c 	'%% &% *) @ 2 / .- # @???. - &%s  5NLN0L<?N;L9L,
L9CN$M%N(A$MM	AMM6M7M;%M M!"MNMN"M5 M3M5NL)$N,L6	1L99M>	N	MMM	MNM0$M'%M0,N3M55M>:Nc                H   |t         u r| j                  dz  }| j                  dv r| j                  r
t	               S yd| _        t        t              5  | j                  j                         D ]  }|j                           	 ddd       | j                  r | j                         }|rt        ||      }|S t        | j                  | j                  d|       | j                  dk(  sJ | j                         s| j                  j                          yy# 1 sw Y   xY w)a  Close this client

        Clients will also close automatically when your Python session ends

        If you started a client without arguments like ``Client()`` then this
        will also close the local cluster that was started at the same time.


        Parameters
        ----------
        timeout : number
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``

        See Also
        --------
        Client.restart
        r  )r   r  Nr  T)r  r  r   )r0   r  r   r  rj   r   rE  r  rg  r  r  r<   rr   r-  r   r  )r   r  r  coros       r   r  zClient.close  s    & j mma'G;;55  $&n%..557	 8 & ;;=Dg.KTYY$I{{h&&&""$""$ % &%s   0DD!c                L  K   t         j                  d       d| _        | j                  j	                         D ]  }|j                           | j                         4 d {    | j                  r#| j                  j                          d {    n:t        t              5  | j                  j                          d {    d d d        d d d       d {    | j                          d {    y 7 7 j7 9# 1 sw Y   8xY w7 /# 1 d {  7  sw Y   ?xY w7 .w)Nz#Shutting down scheduler from Clientr  )r$  r  r   r  rg  r  r  r  r  r   rM   r  	terminater  )r   r  s     r   	_shutdownzClient._shutdown  s     9:**113BGGI 4 4466||ll((***o...22444 /	 76 kkm 7* 5 /.	 7666 	s   A D$"C9#D$&*DC;D%C?C=C?DD$DD$3D"4D$;D=C??D	DD$DDDD$c                8    | j                  | j                        S )zShut down the connected scheduler and workers

        Note, this may disrupt other clients that may be using the same
        scheduler and workers.

        See Also
        --------
        Client.close : close only this client
        )rr   r  r   s    r   shutdownzClient.shutdown  s     yy((r   c                    t        | fi |S )a  
        Return a concurrent.futures Executor for submitting tasks on this
        Client

        Parameters
        ----------
        **kwargs
            Any submit()- or map()- compatible arguments, such as
            `workers` or `resources`.

        Returns
        -------
        ClientExecutor
            An Executor object that's fully compatible with the
            concurrent.futures API.
        rJ   r8  s     r   get_executorzClient.get_executor  s    " d-f--r   r   z100 ms)
r   r  	resourcesretriespriorityfifo_timeoutallow_other_workersactoractorsr  c       
           t        |      st        d      |	xs |
}	|	r|	 }|dvrt        d      |K|rt        |      dz   t        ||g| z   }n,t        |      dz   t	        t        j                               z   }| j                  5  || j                  v rt        ||       cddd       S 	 ddd       |r|t        d      t        |t        t        f      r|g}|t        ||gd |D        i |j                         D ci c]  \  }}|t        |       c}}i}| j!                  ||g|||di|||||	t#        d	d
ig            }t$        j'                  dt        |      |       ||   S # 1 sw Y   xY wc c}}w )aT  Submit a function application to the scheduler

        Parameters
        ----------
        func : callable
            Callable to be scheduled as ``func(*args **kwargs)``. If ``func`` returns a
            coroutine, it will be run on the main event loop of a worker. Otherwise
            ``func`` will be run in a worker's task executor pool (see
            ``Worker.executors`` for more information.)
        *args : tuple
            Optional positional arguments
        key : str
            Unique identifier for the task.  Defaults to function-name and hash
        workers : string or iterable of strings
            A set of worker addresses or hostnames on which computations may be
            performed. Leave empty to default to all workers (common case)
        resources : dict (defaults to {})
            Defines the ``resources`` each instance of this mapped task
            requires on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        retries : int (default to 0)
            Number of allowed automatic retries if the task fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : str timedelta (default '100ms')
            Allowed amount of time between calls to consider the same priority
        allow_other_workers : bool (defaults to False)
            Used with ``workers``. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        actor : bool (default False)
            Whether this task should exist on the worker as a stateful actor.
            See :doc:`actors` for additional details.
        actors : bool (default False)
            Alias for `actor`
        pure : bool (defaults to True)
            Whether or not the function is pure.  Set ``pure=False`` for
            impure functions like ``np.random.random``. Note that if both
            ``actor`` and ``pure`` kwargs are set to True, then the value
            of ``pure`` will be reverted to False, since an actor is stateful.
            See :ref:`pure functions` for more details.
        **kwargs

        Examples
        --------
        >>> c = client.submit(add, a, b)  # doctest: +SKIP

        Notes
        -----
        The current implementation of a task graph resolution searches for occurrences of ``key``
        and replaces it with a corresponding ``Future`` result. That can lead to unwanted
        substitution of strings passed as arguments to a task if these strings match some ``key``
        that already exists on a cluster. To avoid these situations it is required to use unique
        values if a ``key`` is set manually.
        See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue.

        Returns
        -------
        Future
            If running in asynchronous mode, returns the future. Otherwise
            returns the concrete value

        Raises
        ------
        TypeError
            If 'func' is not callable, a TypeError is raised
        ValueError
            If 'allow_other_workers'is True and 'workers' is None, a
            ValueError is raised

        See Also
        --------
        Client.map : Submit on many arguments at once
        z1First input to submit must be a callable functionTFNz*allow_other_workers= must be True or FalseNr  /Only use allow_other_workers= if using workers=c              3  2   K   | ]  }t        |        y wr   )rE   rb  as     r   rd  z Client.submit.<locals>.<genexpr>{  s     /$Q+a.$   r   r   r   collections)	r  r  internal_priorityuser_priorityr  r  r  r  span_metadatazSubmit %s(...), %s)callabler,  r3   r,   r   r_  r`  r  r   r   r  r  r   rC   r  rE   _graph_to_futuresrf   r$  r  )r   r  r   r  r  r  r  r  r  r  r  r  r  r  r   r  r  r   s                     r   r0  zClient.submit  s   v ~OPP9D&99HII;tns*XdF-JT-JJtns*S->>  dll"c4( ! " ! 7?NOOgV}-iG 0$/ 28@A1k!n$@	
 ((E 3"Ah"%&VX4F3GH ) 
 	)8D>3?s|C !  As   
E4F 4E=)r   r  r  r  r  r  r  r  r  r  
batch_sizec               l   	
 t              st        d      t        d |D              st        d |D              rt        d      t        d |D              }rdkD  r|kD  rt	        t        fd|D               }t        |t              r#t        |      D cg c]  }t	        |       }}n!t        t        |            D cg c]  }| }}t        	
 fdt        ||      D        g       S |xs t              }	xs 
		r	 rt        d	      t        |f|d
}|j                         }t        t        t        f      rg!t        t        t         f      st        d      t#        t        |t        t        |                        } j%                  |||	t'        ddig            }|j)                         rJ d       t*        j-                  dt                     |D cg c]  }||   	 c}S c c}w c c}w c c}w )a  Map a function on a sequence of arguments

        Arguments can be normal objects or Futures

        Parameters
        ----------
        func : callable
            Callable to be scheduled for execution. If ``func`` returns a coroutine, it
            will be run on the main event loop of a worker. Otherwise ``func`` will be
            run in a worker's task executor pool (see ``Worker.executors`` for more
            information.)
        iterables : Iterables
            List-like objects to map over.  They should have the same length.
        key : str, list
            Prefix for task names if string.  Explicit names if list.
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        retries : int (default to 0)
            Number of allowed automatic retries if a task fails
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        fifo_timeout : str timedelta (default '100ms')
            Allowed amount of time between calls to consider the same priority
        actor : bool (default False)
            Whether these tasks should exist on the worker as stateful actors.
            See :doc:`actors` for additional details.
        actors : bool (default False)
            Alias for `actor`
        pure : bool (defaults to True)
            Whether or not the function is pure.  Set ``pure=False`` for
            impure functions like ``np.random.random``. Note that if both
            ``actor`` and ``pure`` kwargs are set to True, then the value
            of ``pure`` will be reverted to False, since an actor is stateful.
            See :ref:`pure functions` for more details.
        batch_size : int, optional (default: just one batch whose size is the entire iterable)
            Submit tasks to the scheduler in batches of (at most)
            ``batch_size``.
            The tradeoff in batch size is that large batches avoid more per-batch overhead,
            but batches that are too big can take a long time to submit and unreasonably delay
            the cluster from starting its processing.
        **kwargs : dict
            Extra keyword arguments to send to the function.
            Large values will be included explicitly in the task graph.

        Examples
        --------
        >>> L = client.map(func, sequence)  # doctest: +SKIP

        Notes
        -----
        The current implementation of a task graph resolution searches for occurrences of ``key``
        and replaces it with a corresponding ``Future`` result. That can lead to unwanted
        substitution of strings passed as arguments to a task if these strings match some ``key``
        that already exists on a cluster. To avoid these situations it is required to use unique
        values if a ``key`` is set manually.
        See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue.

        Returns
        -------
        List, iterator, or Queue of futures, depending on the type of the
        inputs.

        See Also
        --------
        Client.submit : Submit a single function
        z.First input to map must be a callable functionc              3  <   K   | ]  }t        |t                y wr   )r  pyQueue)rb  its     r   rd  zClient.map.<locals>.<genexpr>  s     ;2z"g&   c              3  <   K   | ]  }t        |t                y wr   )r  r	   rb  r  s     r   rd  zClient.map.<locals>.<genexpr>  s      C
-6Jq(#Yr	  kDask no longer supports mapping over Iterators or Queues.Consider using a normal for loop and Client.submitc              3  2   K   | ]  }t        |        y wr   r   )rb  xs     r   rd  zClient.map.<locals>.<genexpr>  s     59a3q69r  r   c              3  6   K   | ]  }t        |        y wr   )r#   )rb  r  r  s     r   rd  zClient.map.<locals>.<genexpr>  s     T)hmJ9)s   c              3  f   K   | ](  \  }} j                   g||	
d 
 * yw))
r   r  r  r  r  r  r  r  r  r  N)r   )rb  r   batchr  r  r  r  r  r  r  r  r  r  r   r  s      r   rd  zClient.map.<locals>.<genexpr>	  sf        '9
U DHH   ' '!),?%1"+#%! ! '9s   .1r  )r   r  z0Workers must be a list or set of workers or Noner   r   r  )	r  r  r  r  r  r   r  r  r  zGraph must be non-materializedzmap(%s, ...))r  r,  rh  r   r   r  r  r#   r  r   r3   r  r  r  r   r   rn  r  r  rf   r  r$  r  )r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  total_lengthbatcheselementr   rz  r  r  r   r   s   `` `````````` `         r   r   z
Client.map  s[   z ~LMM;;;s C
-6C
 @
 E  5955*q.\J-FT)TUG #t$5B:s5ST5S'W5ST%*3w<%89%8%89   '*$&8!$ ' , #Xd^9D7?NOO
 	

 
 ##%gV}-iGz'D#;'GNOO T5T+;!<=(( 3/"%&VX4F3GH ) 
 &&(J*JJ(^Xd^4$()Dq
D))C U9~ *s   )H'	H,H1raisec                
	   K   t        |d      \  }}|D cg c]  }|j                   us| }}|rVt        dt        |       dt        |       d j                   d|D ci c]  }||j                  j                   c}       |D 	cg c]  }	|	j
                   }
}	t               }i }| j                  }|;	 t               }|j                  j                   j                  j                  k(  rd}	  fd}	 t        j                  d	       t        t              5  t         j"                  j%                  |
D cg c]  }| j&                  v s ||       c}t        
       d {    d d d        d}t)               }t)               }|D ]  }	|	j
                  }| j&                  vs|	j*                  |v s,|j-                  |       dk(  r5|	j.                  }|j0                  }|j2                  }|j5                  |      dk(  r|j-                  |       d ||<   t        dz         |
D cg c]  }||vs||vs| }
}|rP|j7                  |
D ci c]!  }||j8                  v s||j8                  |   # c}       |
D cg c]	  }||vs| }
} j:                  r3 xj<                  t)        |
      z  c_         j:                   d {   }nZt)        |
       _        t?        j@                   jC                  ||            }	 j<                  d  _        n|	 _        |	 d {   }|d   dk(  rdk(  rt        jD                  nt        j                  } |dt        |d         |d          |d   D ]  } jG                  d|d        |d   D ]   }	  j&                  |   jI                          " nn|r)dk(  r$tM        |tN              r|D cg c]	  }||vs| }}|j7                  |d          tQ        |tS        ||            }|S c c}w c c}w c c}	w # t        $ r d}Y Fw xY wc c}w 7 # 1 sw Y   xY wc c}w c c}w c c}w 7 7 4# tJ        $ r Y w xY wc c}w w)NT)	byte_keysz?Cannot gather Futures created by another client. These are the z	 (out of z:) mismatched Futures and their client IDs (this client is z): Fc                   K   	 j                   |    }|j                          d{    |j                  dk7  rdk(  r
t               yy7 $# t        $ r t               w xY ww)z3Want to stop the All(...) early if we find an errorNrp  r  )r   r  r   r  r   )r   r  r   r   s     r   r  zClient._gather.<locals>.wait[	  sf      \\!_ ggiyyJ&6W+<i ,=&     i s%   A%A A%A%A%A""A%z)Waiting on futures to clear before gather)quiet_exceptions)r   r  r  skipzBad value, `errors=%s`r   r   z(Couldn't gather %s keys, rescheduling %sr   z
report-key)r  r   data)*rx   r   r  r   r  r   r  r  rz   r  r  r  r$  r  r   r  distributedutilsAllr   rn  r   r/  r   r  r  r  r  r  r  r  ri  rr  _gather_remoter  r  r  r   r  r   ru   r"   )r   r   r   directlocal_workerunpacked
future_setr  mismatched_futuresr  r   bad_datar  rc  r  r   failed
exceptionsbad_keysr  r  r  r   responselogr   s   ` `                       r   r  zClient._gatherB	  s~    0DI*)3LAqxxt7KaL!!$%7!8 93w<. QKKO77)SV-?@-?Q^-?@BD  *44v

46>++F>"L ;;&&$..*@*@@!F		  LLDE'"!''++*.F$3#2ET#Y$F%, ,    # ,FJuH$jjdll*fmmv.ENN3'(#]]$&LL	$&LL	'66yAA' S)(,()AF)JKK %  $Kt!q'8Qd]AtDK6:Uda<CTCT>TQ))!,,dU $(94a1D=49 ""!!SY.!!%!4!44$'I! ..''= $$,*.D'*0D'!'<!W,(.'(9fnnv||>()V$
 $F+C++<,LM ,#F+CS)//1 , E H &(Z$-G#+A8aq/@8HAHV$%8U4%:;W M A4  , G #"2 L V9
 5 ( $  Bs'  RP$P$3R$P)RP."R
P3 AR&QQ

Q
"Q2Q
3Q7ARA:R=	QQQR#Q7Q	R	Q$Q$";RQ)AR8Q,9A0R*Q/!R(	Q>2Q>6=R3Q>RQRQQR,R/	Q;8R:Q;;Rc                |  K   | j                   4 d{    t        | j                        }d| _        d| _        |s|rt	        | j
                  j                  |       d{   }t        || j                         d{   \  }}}}d|d}	|s|rrt	        | j
                  j                  ||z          d{   }	|	d   dk(  r>|	d   j                  |       n)t	        | j
                  j                  |       d{   }	ddd      d{    |	S 7 7 7 7 c7 7 # 1 d{  7  sw Y   	S xY ww)zPerform gather with workers or scheduler

        This method exists to limit and batch many concurrent gathers into a
        few.  In controls access using a Tornado semaphore, and picks up keys
        from other requests made recently.
        Nr   )rS   OK)r   r  r   r  )r  r   r  r  rv   r  who_hasrt   rS   gatherr  )
r   r!  r"  r   r/  r  missing_keysfailed_keysrz  r*  s
             r   r   zClient._gather_remote	  s)     )))))*D $D"&D /0F0FT RR;N< 62lK 7;D+I;%4--L;4N&  H  )T1 (//5 "11F1FT!RR' *)* + * S6
  S' *)))* s   D<DD<AD&#D$D&D9D&<D =AD&D"D&D<D$D<D&D& D&"D&$D<&D9,D/-D94D<c           	     2    t        |t              rt        d      t        |t              r fd|D        S 	 t	               }t               5   j                   j                  |||      cddd       S # t
        $ r d}Y Bw xY w# 1 sw Y   yxY w)a  Gather futures from distributed memory

        Accepts a future, nested container of futures, iterator, or queue.
        The return type will match the input type.

        Parameters
        ----------
        futures : Collection of futures
            This can be a possibly nested collection of Future objects.
            Collections can be lists, sets, or dictionaries
        errors : string
            Either 'raise' or 'skip' if we should raise if a future has erred
            or skip its inclusion in the output collection
        direct : boolean
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        asynchronous: bool
            If True the client is in asynchronous mode

        Returns
        -------
        results: a collection of the same type as the input, but now with
        gathered results rather than futures

        Examples
        --------
        >>> from operator import add  # doctest: +SKIP
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> x = c.submit(add, 1, 2)  # doctest: +SKIP
        >>> c.gather(x)  # doctest: +SKIP
        3
        >>> c.gather([x, [x], x])  # support lists and dicts # doctest: +SKIP
        [3, [3], 3]

        See Also
        --------
        Client.scatter : Send data out to cluster
        zvDask no longer supports gathering over Iterators and Queues. Consider using a normal for loop and Client.submit/gatherc              3  F   K   | ]  }j                  |         yw))r   r!  N)r0  )rb  r  r!  r   r   s     r   rd  z Client.gather.<locals>.<genexpr>	  s!     R'QDKK&K@'s   !N)r   r!  r"  r  )	r  r  r,  r	   rz   r  r6   rr   r  )r   r   r   r!  r  r"  s   ` ``  r   r0  zClient.gather	  s    P gw'L 
 gx(R'RR	 %<L  99))   !   	 L	  ! s   
A< !B<B
	B
Bc                P	  K   |t         u r| j                  }t        |t        t        f      r|g}t        |t        t        d                  rt        |      }t        |      }d}	d}
t        |t              rt        |      }t        |t        t        f      rt        |      }t        |t        t        t        t        t        f      sd}
|g}t        |t        t        f      r|r2|D cg c]&  }t        |      j                  dz   t        |      z   ( }	}nD|D cg c]9  }t        |      j                  dz   t        j                          j"                  z   ; }	}t        t%        |	|            }t        |t              sJ t'        t
        |      }|| j(                  }|;	 t+               }|j,                  j.                  | j,                  j.                  k(  rd}	 |rl|j3                  |       | j,                  j3                  |D ci c]  }||j.                  g c}t'        t4        |      | j6                         d {    n-t'        t8        |      }|rd }t;               }|sa|t=        j>                  d       d {    t;               ||z   kD  rtA        d      | j,                  jC                  |	       d {   }|sa|stE        d      t        |jG                               }tI        ||| jJ                         d {   \  }}}| j,                  j3                  ||| j6                         d {    n2| j,                  jM                  ||| j6                  ||
       d {    |D ci c]  }|tO        ||        c}|jQ                         D ]$  \  }}| jR                  |   jU                  |       & |r=|r;|du rd n|}| jW                  t        jY                               ||       d {    t[        |t        t        t        t        f      r |fd|	D              |
r,t]              dk(  sJ t        jY                               d   S c c}w c c}w # t0        $ r d}Y w xY wc c}w 7 G7 	7 7 7 W7 'c c}w 7 w)Nr   FTr  )r  )r/  rq   r   r  zNo valid workers foundr  )r  r  r   	broadcastr  )r   )r  nc              3  (   K   | ]	  }|     y wr   r   )rb  r   rJ  s     r   rd  z"Client._scatter.<locals>.<genexpr>p
  s     3USVUs   r   )/r0   r  r  r   r   r   r  r   r	   rn  	frozensetr  r   r   r,   r_  r`  ra  r  r$   r  rz   r  r  r  update_datare   r  r_   r[   ri  r  rl   ncores_runningr  r   rw   rS   scatterr   r  r   rq  
_replicaterg  
issubclassr   )r   r  r  r7  r!  r"  r  rR  
input_typenamesunpackr  typesrc  r   data2ra  r.  rz  r/  rq   r   r  r8  rJ  s                           @r   _scatterzClient._scatter
  s-     j mmGgV}-iGdDqN+:D$Z
dH%:DdS),-:D$tUC CDF6DdT5M*GKLt!a))C/(1+=tLLPQDqa))C/$**,2B2BBDQE4()D$%%%tT">++F>"L ;;&&$..*@*@@!F$$$$/..,,@DE|3344Efd+ww -    <.E"+%mmC000v/*+CDD%)^^%B%B7%B%SSH #  $%=>>x}}/+=gudhh+W%W"7Fnn00#F477 1    nn,,#77'# -    ,004aq&D/!40HCLL$$#$. & i!T)yA//$szz|"4g/KKKj4Y"?@3U33Cs8q= =szz|$Q'C
S MQ   F 1  T
 &X 1 Ls   C(R&++Q,R&>Q1A	R&%
Q6 /AR&R!%R&RA R&R>R&RR&A R&R3R&R2R&5R6R&>RA4R&R$A/R&6RR&R	R&R&R&R&R&R&R&c                    |t         u r| j                  }t        |t              st        |t              rt        d      	 t               }| j                  | j                  ||||||||	      S # t        $ r d}Y 1w xY w)a  Scatter data into distributed memory

        This moves data from the local client process into the workers of the
        distributed scheduler.  Note that it is often better to submit jobs to
        your workers to have them load the data rather than loading data
        locally and then scattering it out to them.

        Parameters
        ----------
        data : list, dict, or object
            Data to scatter out to workers.  Output type matches input type.
        workers : list of tuples (optional)
            Optionally constrain locations of data.
            Specify workers as hostname/port pairs, e.g.
            ``('127.0.0.1', 8787)``.
        broadcast : bool (defaults to False)
            Whether to send each data element to all workers.
            By default we round-robin based on number of cores.

            .. note::
               Setting this flag to True is incompatible with the Active Memory
               Manager's :ref:`ReduceReplicas` policy. If you wish to use it, you must
               first disable the policy or disable the AMM entirely.
        direct : bool (defaults to automatically check)
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        hash : bool (optional)
            Whether or not to hash data to determine key.
            If False then this uses a random key
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        asynchronous: bool
            If True the client is in asynchronous mode

        Returns
        -------
        List, dict, iterator, or queue of futures matching the type of input.

        Examples
        --------
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> c.scatter(1) # doctest: +SKIP
        <Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195>

        >>> c.scatter([1, 2, 3])  # doctest: +SKIP
        [<Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195>,
         <Future: status: finished, key: 58e78e1b34eb49a68c65b54815d1b158>,
         <Future: status: finished, key: d3395e15f605bc35ab1bac6341a285e2>]

        >>> c.scatter({'x': 1, 'y': 2, 'z': 3})  # doctest: +SKIP
        {'x': <Future: status: finished, key: x>,
         'y': <Future: status: finished, key: y>,
         'z': <Future: status: finished, key: z>}

        Constrain location of data to subset of workers

        >>> c.scatter([1, 2, 3], workers=[('hostname', 8788)])   # doctest: +SKIP

        Broadcast data to all workers

        >>> [future] = c.scatter([element], broadcast=True)  # doctest: +SKIP

        Send scattered data to parallelized function using client futures
        interface

        >>> data = c.scatter(data, broadcast=True)  # doctest: +SKIP
        >>> res = [c.submit(func, data, i) for i in range(100)]

        Notes
        -----
        Scattering a dictionary uses ``dict`` keys to create ``Future`` keys.
        The current implementation of a task graph resolution searches for occurrences of ``key``
        and replaces it with a corresponding ``Future`` result. That can lead to unwanted
        substitution of strings passed as arguments to a task if these strings match some ``key``
        that already exists on a cluster. To avoid these situations it is required to use unique
        values if a ``key`` is set manually.
        See https://github.com/dask/dask/issues/9969 to track progress on resolving this issue.

        See Also
        --------
        Client.gather : Gather data back to local process
        r  N)r  r7  r!  r"  r  r  rR  )
r0   r  r  r  r	   r,  rz   r  rr   rE  )	r   r  r  r7  r!  rR  r  r  r"  s	            r   r=  zClient.scatterw
  s    | j mmGdG$
4(BE 
	 %<L yyMM%%  

 
	
  	 L	 s   
A/ /A=<A=c                
  K   t        t        |      D ch c]  }|j                   c}      }| j                  d||d       |D ]4  }| j                  j                  |d       }|"|j                  ||       6 y c c}w w)Nzcancel-keys)r  r   forcer4  )r   
futures_ofr   r  r   r  r5  )	r   r   r   r   rH  r  r   r   r  s	            r   _cancelzClient._cancel
  sy     Jw$78$7qQUU$789}dU STA!!!T*B~		S	1  9s   BA>?B(Bc                B    | j                  | j                  ||||      S )a  
        Cancel running futures
        This stops future tasks from being scheduled if they have not yet run
        and deletes them if they have already run.  After calling, this result
        and all dependent results will no longer be accessible

        Parameters
        ----------
        futures : List[Future]
            The list of Futures
        asynchronous: bool
            If True the client is in asynchronous mode
        force : boolean (False)
            Cancel this future even if other clients desire it
        reason: str
            Reason for cancelling the futures
        msg : str
            Message that will be attached to the cancelled future
        )r  rH  r   )rr   rJ  )r   r   r  rH  r   r   s         r   r5  zClient.cancel
  s)    ( yyLL'Es  
 	
r   c                  K   t        t        |      D ch c]  }|j                   c}      }| j                  j	                  || j
                         d {   }|D ]!  }| j                  |   }|j	                          # y c c}w 7 0w)N)r   r   )r   rI  r   r  r7  r  r   )r   r   r  r   r*  r   r  s          r   _retryzClient._retry  ss     Jw$78$7qQUU$789--4-HHCc"BHHJ  9Hs   BB1BB
1Bc                >    | j                  | j                  ||      S )z
        Retry failed futures

        Parameters
        ----------
        futures : list of Futures
            The list of Futures
        asynchronous: bool
            If True the client is in asynchronous mode
        )r  )rr   rM  )r   r   r  s      r   r7  zClient.retry  s     yygLyIIr   )r2  overridec               t   K   g t        j                         j                   j                  dd        fd}|r5t	        |      dk(  rt        d      t	        |      dk(  r|d   } |||       |j                         D ]  \  }} |||        t        j                    d {    y 7 w)Npublish_flush_batched_send)r  r  c                     t              D cg c]  }|j                   c} fd}j                   |              y c c}w )Nc                    K   j                   j                         d {    j                   j                  t               j                         d {    y 7 @7 w)N)r  )r   r2  r  rO  r   )r  publish_wait_flushpublish_putr_   r  )r  r   r2  rO  r   r  s   r   rz  z4Client._publish_dataset.<locals>.add_coro.<locals>._+  sg     nn77C7@@@nn00%d+%77 1    As!    A(A$:A(A&A(&A()rI  r   r{  )	r2  r  r  rz  r   
coroutinesrO  r   r  s	   ``  @r   add_coroz)Client._publish_dataset.<locals>.add_coro(  sC    #-d#34#3aAEE#34D  ac" 5s   A	r   zQIf name is provided, expecting call signature like publish_dataset(df, name='ds')r   )	r_  r`  ra  r  r   r  r  ri  r0  )	r   r2  rO  r  r  rW  r  rV  r  s	   ` `    @@r   _publish_datasetzClient._publish_dataset"  s     
jjl'CC PQ	# 4yA~ 6 
 TaAwT4  ,,.JD$T4  ) nnj)))s   B*B80B61B8c                B     | j                   | j                  g|i |S )a  
        Publish named datasets to scheduler

        This stores a named reference to a dask collection or list of futures
        on the scheduler.  These references are available to other Clients
        which can download the collection or futures with ``get_dataset``.

        Datasets are not immediately computed.  You may wish to call
        ``Client.persist`` prior to publishing a dataset.

        Parameters
        ----------
        args : list of objects to publish as name
        kwargs : dict
            named collections to publish on the scheduler

        Examples
        --------
        Publishing client:

        >>> df = dd.read_csv('s3://...')  # doctest: +SKIP
        >>> df = c.persist(df) # doctest: +SKIP
        >>> c.publish_dataset(my_dataset=df)  # doctest: +SKIP

        Alternative invocation
        >>> c.publish_dataset(df, name='my_dataset')

        Receiving client:

        >>> c.list_datasets()  # doctest: +SKIP
        ['my_dataset']
        >>> df2 = c.get_dataset('my_dataset')  # doctest: +SKIP

        Returns
        -------
        None

        See Also
        --------
        Client.list_datasets
        Client.get_dataset
        Client.unpublish_dataset
        Client.persist
        )rr   rX  )r   r  r  s      r   publish_datasetzClient.publish_datasetG  s&    Z tyy..@@@@r   c                T     | j                   | j                  j                  fd|i|S )a  
        Remove named datasets from scheduler

        Parameters
        ----------
        name : str
            The name of the dataset to unpublish

        Examples
        --------
        >>> c.list_datasets()  # doctest: +SKIP
        ['my_dataset']
        >>> c.unpublish_dataset('my_dataset')  # doctest: +SKIP
        >>> c.list_datasets()  # doctest: +SKIP
        []

        See Also
        --------
        Client.publish_dataset
        r2  )rr   r  publish_delete)r   r2  r  s      r   unpublish_datasetzClient.unpublish_datasetv  s)    * tyy66LTLVLLr   c                P     | j                   | j                  j                  fi |S )z
        List named datasets available on the scheduler

        See Also
        --------
        Client.publish_dataset
        Client.get_dataset
        )rr   r  publish_listr8  s     r   list_datasetszClient.list_datasets  s$     tyy44???r   c                ^  K   | j                         5  | j                  j                  || j                         d {   }d d d        |t        u rt        d| d      |S t        |d         D ]  }|j                  |         | j                          |d   S 7 `# 1 sw Y   _xY ww)N)r2  r   z	Dataset 'z' not foundr  )	rF  r  publish_getr  r0   r   rI  r   _inform_scheduler_of_futures)r   r2  r   rJ  r%  s        r   _get_datasetzClient._get_dataset  s     __22TWW2MMC ;*$4&<==c&k*COOD! +))+6{ N s-   B-+B!BB!AB-B!!B*&B-c                B     | j                   | j                  |fd|i|S )a  
        Get named dataset from the scheduler if present.
        Return the default or raise a KeyError if not present.

        Parameters
        ----------
        name : str
            name of the dataset to retrieve
        default : str
            optional, not set by default
            If set, do not raise a KeyError if the name is not present but
            return this default
        kwargs : dict
            additional keyword arguments to _get_dataset

        Returns
        -------
        The dataset from the scheduler, if present

        See Also
        --------
        Client.publish_dataset
        Client.list_datasets
        r   )rr   rd  )r   r2  r   r  s       r   get_datasetzClient.get_dataset  s'    2 tyy**DL'LVLLr   )r  c                  K   | j                   j                  t        |      t        |      t        |      |       d {   }|d   dk(  r t        di |\  }}}|j	                  |      |d   S 7 1w)N)functionr  r  r  r   r   r   r   )r  run_functionr`   rQ   r  )	r   rh  r  r  r  r*  r  r  r  s	            r   _run_on_schedulerzClient._run_on_scheduler  s     448_t=	 5 
 
 H(*6X6LCb$$R((H%%
s   >A4 A22A4c                D     | j                   | j                  |g|i |S )ae  Run a function on the scheduler process

        This is typically used for live debugging.  The function should take a
        keyword argument ``dask_scheduler=``, which will be given the scheduler
        object itself.

        Parameters
        ----------
        function : callable
            The function to run on the scheduler process
        *args : tuple
            Optional arguments for the function
        **kwargs : dict
            Optional keyword arguments for the function

        Examples
        --------
        >>> def get_number_of_tasks(dask_scheduler=None):
        ...     return len(dask_scheduler.tasks)

        >>> client.run_on_scheduler(get_number_of_tasks)  # doctest: +SKIP
        100

        Run asynchronous functions in the background:

        >>> async def print_state(dask_scheduler):  # doctest: +SKIP
        ...    while True:
        ...        print(dask_scheduler.status)
        ...        await asyncio.sleep(1)

        >>> c.run(print_state, wait=False)  # doctest: +SKIP

        See Also
        --------
        Client.run : Run a function on all workers
        )rr   rj  )r   rh  r  r  s       r   run_on_schedulerzClient.run_on_scheduler  s(    J tyy//KDKFKKr   )nannyr  r  on_errorc                 K   | j                   j                  t        dt        |      t        |      |t        |            ||d       d {   }i }	|j	                         D ]  \  }
}t        |t              rt        |      }t        |t              s>J |d   dk(  r!t        di |\  }}}|j                  |      }n|d   dk(  sJ |d   |	|
<   o|d	k(  r||d
k(  r||	|
<   |dk7  st        d|       |r|	S y 7 w)Nrun)r  rh  r  r  r  return_pickle)r   r  rm  rn  r   r   r.  r   r  r   ignorez5on_error must be 'raise', 'return', or 'ignore'; got r   )r  r7  r  r`   r  r  r  ra   r  rQ   r  r  )r   rh  rm  r  r  rn  r  r  	responsesresultsr   respr  rz  r  s                  r   _runzClient._run  s;     ..22x4[V} $ 3 
 
	 "*IC$&Dk!#y111h7*,4t4
3((,H~---#H~7"	X%"X% #,( ' +0 N K
s   ADD BD,Dr  r  rm  rn  c               N     | j                   | j                  |g|||||d|S )a%  
        Run a function on all workers outside of task scheduling system

        This calls a function on all currently known workers immediately,
        blocks until those results come back, and returns the results
        asynchronously as a dictionary keyed by worker address.  This method
        is generally used for side effects such as collecting diagnostic
        information or installing libraries.

        If your function takes an input argument named ``dask_worker`` then
        that variable will be populated with the worker itself.

        Parameters
        ----------
        function : callable
            The function to run
        *args : tuple
            Optional arguments for the remote function
        **kwargs : dict
            Optional keyword arguments for the remote function
        workers : list
            Workers on which to run the function. Defaults to all known
            workers.
        wait : boolean (optional)
            If the function is asynchronous whether or not to wait until that
            function finishes.
        nanny : bool, default False
            Whether to run ``function`` on the nanny. By default, the function
            is run on the worker process.  If specified, the addresses in
            ``workers`` should still be the worker addresses, not the nanny addresses.
        on_error: "raise" | "return" | "ignore"
            If the function raises an error on a worker:

            raise
                (default) Re-raise the exception on the client.
                The output from other workers will be lost.
            return
                Return the Exception object instead of the function output for
                the worker
            ignore
                Ignore the exception and remove the worker from the result dict

        Examples
        --------
        >>> c.run(os.getpid)  # doctest: +SKIP
        {'192.168.0.100:9000': 1234,
         '192.168.0.101:9000': 4321,
         '192.168.0.102:9000': 5555}

        Restrict computation to particular workers with the ``workers=``
        keyword argument.

        >>> c.run(os.getpid, workers=['192.168.0.100:9000',
        ...                           '192.168.0.101:9000'])  # doctest: +SKIP
        {'192.168.0.100:9000': 1234,
         '192.168.0.101:9000': 4321}

        >>> def get_status(dask_worker):
        ...     return dask_worker.status

        >>> c.run(get_status)  # doctest: +SKIP
        {'192.168.0.100:9000': 'running',
         '192.168.0.101:9000': 'running}

        Run asynchronous functions in the background:

        >>> async def print_state(dask_worker):  # doctest: +SKIP
        ...    while True:
        ...        print(dask_worker.status)
        ...        await asyncio.sleep(1)

        >>> c.run(print_state, wait=False)  # doctest: +SKIP
        rw  )rr   rv  )r   rh  r  r  rm  rn  r  r  s           r   rp  z
Client.run&  sI    f tyyII	
 	
 	
 	
 		
r   c           
        |dk  ryt         j                  j                  d      }t        |t              st        dt        |       d| d      t         j                  j                  d      }t        |t              st        dt        |       d| d      d	}d	}| l|r6t        j                  d
j                  |D cg c]  }d| d
 c}            }|r;t        j                  dd
j                  d |D              z   dz         }n	| dkD  r| nd} g }t        t        j                  t        j                         j                        d      D ]c  \  }\  }	}
t!        |      |k\  r nL| || k7  r#|	j"                  j$                  dv r<|r,|j'                  |	j(                  j                  dd            rj|r&|j'                  |	j"                  j*                        rt-        |
|
|	j"                  j.                  z
  |	j"                  j*                        }	 |j1                  t3        ddt5        j6                  |	      i|       tE        |	j                  d      s|	j                  j(                  d   }|dk(  r n4	 t        jF                  |   jH                  }|jM                  d      sd n tO        tQ        |            S c c}w # t8        $ rT 	 ddlm}  |       }|0|j1                  t3        dd|j>                  j@                  i|       n# tB        $ r Y nw xY wY  uw xY w# tJ        $ r Y  w xY w)a  Walk up the stack to the user code and extract the code surrounding
        the compute/submit/persist call. All modules encountered which are
        ignored through the option
        `distributed.diagnostics.computations.ignore-modules` will be ignored.
        This can be used to exclude commonly used libraries which wrap
        dask/distributed compute calls.

        ``stacklevel`` may be used to explicitly indicate from which frame on
        the stack to get the source code.
        r   r   z3distributed.diagnostics.computations.ignore-modulesz-Ignored modules must be a list. Instead got (z, )z1distributed.diagnostics.computations.ignore-filesz+Ignored files must be a list. Instead got (N|z(?:z.*[\\/](c              3      K   | ]  }|  y wr   r   )rb  mods     r   rd  z/Client._get_computation_code.<locals>.<genexpr>  s     *G,33,s   z
)([\\/]|$)r   )z
<listcomp>z
<dictcomp>r   r   )r   r   r   r   )get_ipython	f_globals__channelexec__interactiveshell))r  r  r   r  r   r,  r   recompiler   	enumerater  
walk_stackr\  	_getframef_backr   f_codeco_namematchr  co_filenamer  co_firstlinenor{  r   r  	getsourcer  IPythonr~  history_manager_i00r  r  modulesr   r   r  r   reversed)r<  nframesignore_modulesignore_filesmod_patternfname_patternr}  r   r  frr   r  r~  ipmodule_names                  r   _get_computation_codezClient._get_computation_code  s    a<A
 .$/()N+;1>  {{?
 ,-&'r,q: 
 *.+/ jjHHnEnsC5lnEF  "

#((*G,*G"GG-W!
 (2A~1J!#%.  !7!78!&
!A!L 4yG#%!z/yy  $@@{001A1A*b1QR!4!4RYY5J5J!K) ,ryy/G/G G..FJLG,=,=b,ALVLM ryy+. ii11*="33"%++k":"C"CK
 ''(:;]&
` Xd^$$w FB  3$B~J$VB4F4F4K4K$Vv$VW"  &   sN   K/KL3	L0?LL0	L)&L0(L))L0/L03	M ?M c                R    | j                  dt        | j                        d       y )Nclient-desires-keys)r  r   )r  r   r   r   s    r   rc  z#Client._inform_scheduler_of_futures  s$    +T]]+	
r   c                J   | j                   5  |"|dur|durt        | j                  |            }t        |t              s!t	        j
                  t        |      |d      }i }|r||d<   |r#t        |t        t        t        f      s|g}||d<   |	r|	|d<   |dvrt        d	      |r||d
<   |r||d<   t        t        j                         |      }t        |      }|D ]  }t        |        |D ci c]  }|t        ||        }}ddlm} ddlm}  | ||      d      \  }}t'        t)        t*        |g|z               }|t-        t        j.                  j1                  d            kD  r"t3        j4                  dt7        |       d       | j9                  t        j.                  j1                  d            }| j;                  d||t        |      |t=        t>        dd       |
| ||       ||       ||      d       |cd d d        S c c}w # 1 sw Y   y xY w)NTFr   dependenciesr  r  r  r  z1allow_other_workers= must be True, False, or Noner  r  r   )	serialize)ToPickler  rn  z/distributed.admin.large-graph-warning-thresholdzSending large graph of size a  .
This may cause some slowdown.
Consider loading the data with Dask directly
 or using futures or delayed objects to embed the data into the graph without repetition.
See also https://docs.dask.org/en/stable/best-practices.html#load-data-with-dask for more information.z,distributed.diagnostics.computations.nframesr  zupdate-graphr   )r  graph_headergraph_framesr   r  submitting_taskr  r  r   r   r  ) r  r   _expand_keyr  r)   from_collectionsr  r   rn  r,  r"   r  get_annotationsr(   r   distributed.protocolr  distributed.protocol.serializer  r   r   rq   r4   r  r   r  r  r2   r  r  r  rs   )r   r  r   r  r  r  r  r   r  r  r  r  r   keysetr   r   r  r  headerframespickled_sizecomputationss                         r   r  zClient._graph_to_futures  s9      !fD&8V5=Pd..v67c>2$55bgsQSTK*7J'!'D%+=>&iG)0I&)0I&"*== STT"5H12+4K(   4 4 6DK YF S!  :@@#sF3--G@6?&x}wGNFFs6F8f+<=>Lk QR  2<3M2N O} }  55(VW 6 L ##($*$*I):'.|UD'I$0$$\2#+K#8%-m%< O ! D AE ! s   C'H4HDHHH"c                :   | j                  |t        t        |g            |||||	|
|t        ddig      
      }t	        ||      }|rwt        t        dd      r	 t                d}	 | j                  |||      }|j                         D ]  }|j                           t        t        dd      rr
t                |S |S # t        $ r d}Y hw xY w# |j                         D ]  }|j                           t        t        dd      rrt                w w w xY w)	a	  Compute dask graph

        Parameters
        ----------
        dsk : dict
        keys : object, or nested lists of objects
        workers : string or iterable of strings
            A set of worker addresses or hostnames on which computations may be
            performed. Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with ``workers``. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        resources : dict (defaults to {})
            Defines the ``resources`` each instance of this mapped task
            requires on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        sync : bool (optional)
            Returns Futures if False or concrete values if True (default).
        asynchronous: bool
            If True the client is in asynchronous mode
        direct : bool
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.


        Returns
        -------
        results
            If 'sync' is True, returns the results. Otherwise, returns the
            known data packed
            If 'sync' is False, returns the known data. Otherwise, returns
            the results

        Examples
        --------
        >>> from operator import add  # doctest: +SKIP
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> c.get({'x': (add, 1, 2)}, 'x')  # doctest: +SKIP
        3

        See Also
        --------
        Client.compute : Compute asynchronous collections
        r   zlow-level-graphr  )	r   r  r  r  r  r  r   r  r  r   FT)r  r!  )r  rn  r'   rf   ru   r  rs   r{   r  r0  rg  r@  rg   )r   r  r   r  r  r  rr   r  r!  r  r  r  r  r  r   packedshould_rejoinrt  r  s                      r   r   z
Client.getG  s   R ((WdV_% 3%"&V=N4O3PQ ) 
 4)|UE2*H$(M++f<PV+W )AIIK *<6=HN ! *$)M*
 !)AIIK *<6=H <I6s   C )C CCADc                   | j                   5  d}t        |      D ]/  }|| j                  v s|sd}t        |      }t	        ||       ||<   1 	 ddd       r#t
        j                  j                  ||      \  }}|S # 1 sw Y   0xY w)aw  Replace known keys in dask graph with Futures

        When given a Dask graph that might have overlapping keys with our known
        results we replace the values of that graph with futures.  This can be
        used as an optimization to avoid recomputation.

        This returns the same graph if unchanged but a new graph if any changes
        were necessary.
        FTN)r  r   r   r1   r   r  optimizationcull)r   r  r   changedr   rz  s         r   _optimize_insert_futureszClient._optimize_insert_futures  s       GCy$,,&""&)#.%c40CH ! ! &&++C6FC
 ! s   A= A==Bc                    |j                         }| j                  ||j                               }||u r|S t        ||      S )a`  
        Replace collection's tasks by already existing futures if they exist

        This normalizes the tasks within a collections task graph against the
        known futures within the scheduler.  It returns a copy of the
        collection with a task graph that includes the overlapping futures.

        Parameters
        ----------
        collection : dask object
            Collection like dask.array or dataframe or dask.value objects

        Returns
        -------
        collection : dask object
            Collection with its tasks replaced with any existing futures.

        Examples
        --------
        >>> len(x.__dask_graph__())  # x is a dask collection with 100 tasks  # doctest: +SKIP
        100
        >>> set(client.futures).intersection(x.__dask_graph__())  # some overlap exists  # doctest: +SKIP
        10

        >>> x = client.normalize_collection(x)  # doctest: +SKIP
        >>> len(x.__dask_graph__())  # smaller computational graph  # doctest: +SKIP
        20

        See Also
        --------
        Client.persist : trigger computation of collection's tasks
        )__dask_graph__r  __dask_keys__redict_collection)r   
collectiondsk_origr  s       r   normalize_collectionzClient.normalize_collection  sH    B ,,.++Hj6N6N6PQ(?$Z55r   c                   t        |t        t        t        t        f      rd}n|g}d}|rt        d |D              }|D cg c]  }t        j                  |      s| }}t        |D cg c]  }t        |       c}      } | j                  ||fi |}|D cg c]  }dt        |      z   }}i }t        t        ||            D ]r  \  }\  }}|j                         \  }}|j                         }|t        u rt!        |      dk(  r|s	|d   ||<   Mt#        ||t%        |      g| }|||j&                  <   t t        |t(              s!t)        j*                  t-        |      |d	      }t        |      }||i}|j/                  |j0                         |t        |j0                  j3                               i}|j/                  |j4                         t)        ||      }| j7                  ||||||||	|
|

      }d}g }|D ]E  } t        j                  |       r|j9                  |||             |dz  }5|j9                  |        G |r| j;                  |      }!n|}!|rt=        |!      S |!S c c}w c c}w c c}w )ab  Compute dask collections on cluster

        Parameters
        ----------
        collections : iterable of dask objects or single dask object
            Collections like dask.array or dataframe or dask.value objects
        sync : bool (optional)
            Returns Futures if False (default) or concrete values if True
        optimize_graph : bool
            Whether or not to optimize the underlying graphs
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        traverse : bool (defaults to True)
            By default dask traverses builtin python collections looking for
            dask objects passed to ``compute``. For large collections this can
            be expensive. If none of the arguments contain any dask objects,
            set ``traverse=False`` to avoid doing this traversal.
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.
        **kwargs
            Options to pass to the graph optimize calls

        Returns
        -------
        List of Futures if input is a sequence, or a single future otherwise

        Examples
        --------
        >>> from dask import delayed
        >>> from operator import add
        >>> x = delayed(add)(1, 2)
        >>> y = delayed(add)(x, x)
        >>> xx, yy = client.compute([x, y])  # doctest: +SKIP
        >>> xx  # doctest: +SKIP
        <Future: status: finished, key: add-8f6e709446674bad78ea8aeecfee188e>
        >>> xx.result()  # doctest: +SKIP
        3
        >>> yy.result()  # doctest: +SKIP
        6

        Also support single arguments

        >>> xx = client.compute(x)  # doctest: +SKIP

        See Also
        --------
        Client.get : Normal synchronous dask.get function
        FTc           	   3     K   | ]@  }t        |t        t        t        t        t
        f      rt        j                  |      n| B y wr   )r  r   rn  r   r  r	   r  delayedr  s     r   rd  z!Client.compute.<locals>.<genexpr>G  sC        %A "!dCh%GH LLO %s   AAr  zfinalize-%sr   r   r   r  r  r  r  r  r   r  r  r  )r  r   r   rn  r:  r  is_dask_collectionrf   get_collections_metadatar&   r,   r  r  __dask_postcompute__r  r=   r   rC   _convert_dask_keysr   r)   r  r  r  layersr   r  r  r{  r0  r    )"r   r  rr   optimize_graphr  r  r  r  r  r  r  traverser  	singletonr  	variablesr  metadatar  rA  dsk2r  r2  r  
extra_argsr   tfinalize_namer  r  futures_dictr   argr   s"                                     r   computezClient.compute  s   b kD%i#@AI&-KI   %  K !,J1t/F/Fq/IQ	J>GHi1!4iH
 &d%%iJ6J6?@i!,i@%c%&;<LAya 557D*??$Dz!c$i1nZ7at%7%=K
KQUU = #~. 11"S'3RPC !&cjj!%s3::??+<'=>C,,-V\2-- 3"%" . 
 C&&s+|E!H56Qs#  [[)FF= Mu KH As   I5I5+I:I?c
                   t        |t        t        t        t        f      rd}nd}|g}t        t        t        j                  |            sJ t        |D cg c]  }t        |       c}      } | j                  ||fi |
}|D ch c]"  }t        |j                               D ]  }| $ }}}| j                  |||||||||	|
      }|D cg c]  }|j                          }}t!        ||      D cg c]:  \  \  }}} |t        |j                               D ci c]  }|||   
 c}g| < }}}}}|rt#        |      S |S c c}w c c}}w c c}w c c}w c c}}}}w )a  Persist dask collections on cluster

        Starts computation of the collection on the cluster in the background.
        Provides a new dask collection that is semantically identical to the
        previous one, but now based off of futures currently in execution.

        Parameters
        ----------
        collections : sequence or single dask object
            Collections like dask.array or dataframe or dask.value objects
        optimize_graph : bool
            Whether or not to optimize the underlying graphs
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.
        **kwargs
            Options to pass to the graph optimize calls

        Returns
        -------
        List of collections, or single collection, depending on type of input.

        Examples
        --------
        >>> xx = client.persist(x)  # doctest: +SKIP
        >>> xx, yy = client.persist([x, y])  # doctest: +SKIP

        See Also
        --------
        Client.compute
        FTr  r  )r  r   r   rn  r:  rh  r   r  r  rf   r  r&   r'   r  r  __dask_postpersist__r  r    )r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   rA  r   postpersistsr  r  r   s                          r   persistzClient.persist  s   ~ kE4i#@AII&-K3t..<===>IJk1!4kJ
 &d%%k>LVL'LKq9J1KA1KKL(( 3"%" ) 
 ;FF+Q..0+F $'|[#A
#Ata 1B)CD)CA!WQZ-)CDLtL#A 	 

 = M9 K M GD
s*   E
'EE=(E%
%E 2
E%
 E%
c                   K   |t         u r| j                  dz  }t        t        d|      d      }| j                  j                  ||dt                       d {    y 7 w)N   str|int|floatr   zclient-restart-)r  r  stimulus_id)r0   r  r5   r   r  r  r[   r   r  r  s      r   _restartzClient._restart  sd      j mma'G!$"@#Fnn$$-)$&2 % 
 	
 	
s   AA$A"A$c                >    | j                  | j                  ||      S )a%  
        Restart all workers. Reset local state. Optionally wait for workers to return.

        Workers without nannies are shut down, hoping an external deployment system
        will restart them. Therefore, if not using nannies and your deployment system
        does not automatically restart workers, ``restart`` will just shut down all
        workers, then time out!

        After ``restart``, all connected workers are new, regardless of whether ``TimeoutError``
        was raised. Any workers that failed to shut down in time are removed, and
        may or may not shut down on their own in the future.

        Parameters
        ----------
        timeout:
            How long to wait for workers to shut down and come back, if ``wait_for_workers``
            is True, otherwise just how long to wait for workers to shut down.
            Raises ``asyncio.TimeoutError`` if this is exceeded.
        wait_for_workers:
            Whether to wait for all workers to reconnect, or just for them to shut down
            (default True). Use ``restart(wait_for_workers=False)`` combined with
            :meth:`Client.wait_for_workers` for granular control over how many workers to
            wait for.

        See also
        --------
        Scheduler.restart
        Client.restart_workers
        )r  r  )rr   r  r  s      r   r  zClient.restart  s'    D yyMM7=M  
 	
r   c                @  K   |t         u r| j                  dz  }t        t        d|      d      }| j	                         }|d   j                         D ci c]  \  }}|d   | }}}|D cg c]  }|j                  ||       }	}| j                  j                  |	||rdnddt                	       d {   }
t        ||	      D ci c]  \  }}||
|    }
}}|r't        d
 |
j                         D              sJ |
       |
S c c}}w c c}w 7 \c c}}w w)Nr  r  r   r  r2  r  r   zclient-restart-workers-)r  r  rn  r  c              3  &   K   | ]	  }|d k(    yw)r.  Nr   )rb  r  s     r   rd  z*Client._restart_workers.<locals>.<genexpr>=  s     7,QqDy,re  )r0   r  r5   r   scheduler_infor  r   r  restart_workersr[   r  rh  rg  )r   r  r  raise_for_errorr  ri  metaname_to_addrrc  worker_addrsrJ  w_addrs               r   _restart_workerszClient._restart_workers$  s2     j mma'G!$"@#F""$=A)_=R=R=TU=TztTVd*=TU8?@1((A.@ ..00$$35dfX>	 1   	 037L/IJ/I)!Vq#f+~/IJ7#**,77<<7
 V@ Ks<   ADD&D-D3D9D:DD:DDc                    | j                         }|d   j                         D ]1  \  }}||v s|d   |v s|d   t        d| d|d   |   d    d       | j                  | j                  |||      S )	a  Restart a specified set of workers

        .. note::

            Only workers being monitored by a :class:`distributed.Nanny` can be restarted.
            See ``Nanny.restart`` for more details.

        Parameters
        ----------
        workers : list[str]
            Workers to restart. This can be a list of worker addresses, names, or a both.
        timeout : int | float | None
            Number of seconds to wait
        raise_for_error: bool (default True)
            Whether to raise a :py:class:`TimeoutError` if restarting worker(s) doesn't
            finish within ``timeout``, or another exception caused from restarting
            worker(s).

        Returns
        -------
        dict[str, "OK" | "removed" | "timed out"]
            Mapping of worker and restart status, the keys will match the original
            values passed in via ``workers``.

        Notes
        -----
        This method differs from :meth:`Client.restart` in that this method
        simply restarts the specified set of workers, while ``Client.restart``
        will restart all workers and also reset local state on the cluster
        (e.g. all keys are released).

        Additionally, this method does not gracefully handle tasks that are
        being executed when a worker is restarted. These tasks may fail or have
        their suspicious count incremented.

        Examples
        --------
        You can get information about active workers using the following:

        >>> workers = client.scheduler_info()['workers']

        From that list you may want to select some workers to restart

        >>> client.restart_workers(workers=['tcp://address:port', ...])

        See Also
        --------
        Client.restart
        r  r2  rm  z7Restarting workers requires a nanny to be used. Worker z
 has type r   r   )r  r  r  )r  r  r  rr   r  )r   r  r  r  r  r  r  s          r   r  zClient.restart_workers@  s    n ""$ O113LFD'!T&\W%<$w-BW Mhji)@)H(IL  4 yy!!+	  
 	
r   c                  K   "t         j                  j                  |      d   t        |d      5 }|j	                         d d d        | j                  g       d {   \  }|j                  | j                  |       d {    dfd	}| j                  |       d {   }t        fd|j                         D              sJ y # 1 sw Y   xY w7 |7 W7 9w)Nr   rbc                J   t         j                  j                        s+t         j                  j                  | j                        }n}t        |d      5 }|j                  | j                            d d d        t        | j                           S # 1 sw Y   !xY w)Nwb)	r*  r  isabsr   local_directoryr  r  r  r   )dask_workerr&  r  r   remote_filenames      r   dump_to_filez/Client._upload_large_file.<locals>.dump_to_file  sy    77==1WW\\+"="=O$b$1((-.   {'',--  s   BB"c              3  :   K   | ]  }t              |k(    y wr   r  )rb  r  r  s     r   rd  z,Client._upload_large_file.<locals>.<genexpr>  s     =+<a3t9>+<s   r   )r*  r  rU  r  r  rE  r   r>  rv  rh  rg  )	r   local_filenamer  r  r  r  r*  r  r   s	     `    @@r   _upload_large_filezClient._upload_large_file  s     " ggmmN;A>O.$'1668D ( v..jjoof%%%	. <00=8??+<====' (' /% 1sL   1C'CC'$C!%&C'C#C'+C%,)C'CC'#C'%C'c                |     t        t        j                               z    fd} j                  |      S )a  Upload local package to scheduler and workers

        This sends a local file up to the scheduler and all worker nodes.
        This file is placed into the working directory of each node, see config option
        ``temporary-directory`` (defaults to :py:func:`tempfile.gettempdir`).

        This directory will be added to the Python's system path so any ``.py``,
        ``.egg`` or ``.zip``  files will be importable.

        Parameters
        ----------
        filename : string
            Filename of ``.py``, ``.egg``, or ``.zip`` file to send to workers
        load : bool, optional
            Whether or not to import the module as part of the upload process.
            Defaults to ``True``.

        Examples
        --------
        >>> client.upload_file('mylibrary.egg')  # doctest: +SKIP
        >>> from mylibrary import myfunc  # doctest: +SKIP
        >>> L = client.map(myfunc, seq)  # doctest: +SKIP
        >>>
        >>> # Where did that file go? Use `dask_worker.local_directory`.
        >>> def where_is_mylibrary(dask_worker):
        >>>     path = pathlib.Path(dask_worker.local_directory) / 'mylibrary.egg'
        >>>     assert path.exists()
        >>>     return str(path)
        >>>
        >>> client.run(where_is_mylibrary)  # doctest: +SKIP
        c            	        K   t        j                  j                  t                    j                  t	                           d {   } | d   S 7 	w)N)r  r2  r   )ri  r0  register_pluginrW   rX   )rt  r   r  r2  r   s    r   rz  zClient.upload_file.<locals>._  sf     #NN$$'t<4 %  $$Zt%D4$P G 1:s   AA!A
A!)r   r_  r`  rr   )r   r   r  rz  r2  s   ``` @r   upload_filezClient.upload_file  s0    @ #djjl++	 yy|r   c                L  K   |Ft        |       d {    t        | j                  |      D ch c]  }|j                   c}      }nd }| j                  j                  ||       d {   }|d   dk(  rt        d|d          |d   dk(  sJ |       y 7 c c}w 7 4w)N)r   r  r   zpartial-failzCould not rebalance keys: r   r.  )_waitr   rI  r   r  	rebalancer   )r   r   r  r  r   r   s         r   
_rebalancezClient._rebalance  s     .  (@A(@1(@ABDD~~//T7/KK(~-7v7GHIIh4'//' !A Ls,   B$BB$B*B$-B"..B$B$c                @     | j                   | j                  ||fi |S )a  Rebalance data within network

        Move data between workers to roughly balance memory burden.  This
        either affects a subset of the keys/workers or the entire network,
        depending on keyword arguments.

        For details on the algorithm and configuration options, refer to the matching
        scheduler-side method :meth:`~distributed.scheduler.Scheduler.rebalance`.

        .. warning::
           This operation is generally not well tested against normal operation of the
           scheduler. It is not recommended to use it while waiting on computations.

        Parameters
        ----------
        futures : list, optional
            A list of futures to balance, defaults all data
        workers : list, optional
            A list of workers on which to balance, defaults to all workers
        **kwargs : dict
            Optional keyword arguments for the function
        )rr   r   )r   r   r  r  s       r   r  zClient.rebalance  s"    . tyy'7EfEEr   c                   K   | j                  |      }t        |       d {    |D ch c]  }|j                   }}| j                  j	                  t        |      |||       d {    y 7 Nc c}w 7 w)N)r   r8  r  branching_factor)rI  r  r   r  	replicater   )r   r   r8  r  r  r  r   s          r   r>  zClient._replicate  su     //'*Gn&'w!w'nn&&dq'DT ' 
 	
 	
 	'	
s+    A:A1A:A3-A:+A8,A:3A:c                F     | j                   | j                  |f|||d|S )a  Set replication of futures within network

        Copy data onto many workers.  This helps to broadcast frequently
        accessed data and can improve resilience.

        This performs a tree copy of the data throughout the network
        individually on each piece of data.  This operation blocks until
        complete.  It does not guarantee replication of data to future workers.

        .. note::
           This method is incompatible with the Active Memory Manager's
           :ref:`ReduceReplicas` policy. If you wish to use it, you must first disable
           the policy or disable the AMM entirely.

        Parameters
        ----------
        futures : list of futures
            Futures we wish to replicate
        n : int, optional
            Number of processes on the cluster on which to replicate the data.
            Defaults to all.
        workers : list of worker addresses
            Workers on which we want to restrict the replication.
            Defaults to all.
        branching_factor : int, optional
            The number of workers that can copy data in each generation
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x = c.submit(func, *args)  # doctest: +SKIP
        >>> c.replicate([x])  # send to all workers  # doctest: +SKIP
        >>> c.replicate([x], n=3)  # send to three workers  # doctest: +SKIP
        >>> c.replicate([x], workers=['alice', 'bob'])  # send to specific  # doctest: +SKIP
        >>> c.replicate([x], n=1, workers=['alice', 'bob'])  # send to one of specific workers  # doctest: +SKIP
        >>> c.replicate([x], n=1)  # reduce replications # doctest: +SKIP

        See Also
        --------
        Client.rebalance
        )r8  r  r  )rr   r>  )r   r   r8  r  r  r  s         r   r  zClient.replicate  s<    V tyyOO
 -
 
 	
r   c                    t        |t              rt        d |D              rt        |      }|t        |t        t        t        f      s|g} | j
                  | j                  j                  fd|i|S )a  The number of threads/cores available on each worker node

        Parameters
        ----------
        workers : list (optional)
            A list of workers that we care about specifically.
            Leave empty to receive information about all workers.
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> c.nthreads()  # doctest: +SKIP
        {'192.168.1.141:46784': 8,
         '192.167.1.142:47548': 8,
         '192.167.1.143:47329': 8,
         '192.167.1.144:37297': 8}

        See Also
        --------
        Client.who_has
        Client.has_what
        c              3  H   K   | ]  }t        |t        t        f        y wr   r  r   r   r  s     r   rd  z"Client.nthreads.<locals>.<genexpr>E        .
18AJq3,'    "r  )r  r   rh  r   rn  rr   r  ncores)r   r  r  s      r   ra  zClient.nthreads-  so    0 gu%# .
18.
 +
 7mGz'E4;M'NiGtyy..JJ6JJr   c                     |5 j                  |      }t        |D ch c]  }|j                   c}      nd fd} j                  |      S c c}w )a  The workers storing each future's data

        Parameters
        ----------
        futures : list (optional)
            A list of futures, defaults to all data
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> wait([x, y, z])  # doctest: +SKIP
        >>> c.who_has()  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'],
         'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784'],
         'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': ['192.168.1.141:46784']}

        >>> c.who_has([x, y])  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'],
         'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784']}

        See Also
        --------
        Client.has_what
        Client.nthreads
        Nc                 n   K   t         j                  j                  dd i d {         S 7 w)Nr   r   )r^   r  r/  )r   r  r   s   r   rz  zClient.who_has.<locals>._q  s2      6 6 6 KD KF KKLLK   '53	5)rI  r   r   rr   )r   r   r  r  rz  r   s   ` `  @r   r/  zClient.who_hasO  sV    8 oog.G0101DD	M yy| 1s   Ac                     t        t              rt        d D              rt              t        t        t        t        f      sg fd} j                  |      S )aa  Which keys are held by which workers

        This returns the keys of the data that are held in each worker's
        memory.

        Parameters
        ----------
        workers : list (optional)
            A list of worker addresses, defaults to all
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> wait([x, y, z])  # doctest: +SKIP
        >>> c.has_what()  # doctest: +SKIP
        {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea',
                                 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b',
                                 'inc-1e297fc27658d7b67b3a758f16bcf47a']}

        See Also
        --------
        Client.who_has
        Client.nthreads
        Client.processing
        c              3  H   K   | ]  }t        |t        t        f        y wr   r  r  s     r   rd  z"Client.has_what.<locals>.<genexpr>  r	  r
  c                 n   K   t         j                  j                  ddi  d {         S 7 w)Nr  r   )r\   r  has_what)r  r   r  s   r   rz  zClient.has_what.<locals>._  s2     !8!8!8!S!SF!SSTTSr  )r  r   rh  r   rn  rr   )r   r  r  rz  s   ``` r   r  zClient.has_whatv  sa    8 gu%# .
18.
 +
 7mGz'E4;M'NiG	U yy|r   c                    t        |t              rt        d |D              rt        |      }|t        |t        t        t        f      s|g}| j                  | j                  j                  |      S )a  The tasks currently running on each worker

        Parameters
        ----------
        workers : list (optional)
            A list of worker addresses, defaults to all

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> c.processing()  # doctest: +SKIP
        {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea',
                                 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b',
                                 'inc-1e297fc27658d7b67b3a758f16bcf47a']}

        See Also
        --------
        Client.who_has
        Client.has_what
        Client.nthreads
        c              3  H   K   | ]  }t        |t        t        f        y wr   r  r  s     r   rd  z$Client.processing.<locals>.<genexpr>  r	  r
  r6  )r  r   rh  r   rn  rr   r  
processing)r   r  s     r   r  zClient.processing  sg    , gu%# .
18.
 +
 7mGz'E4;M'NiGyy22GyDDr   c                V     | j                   | j                  j                  f||d|S )ax  The bytes taken up by each key on the cluster

        This is as measured by ``sys.getsizeof`` which may not accurately
        reflect the true cost.

        Parameters
        ----------
        keys : list (optional)
            A list of keys, defaults to all keys
        summary : boolean, (optional)
            Summarize keys into key types
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> c.nbytes(summary=False)  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': 28,
         'inc-1e297fc27658d7b67b3a758f16bcf47a': 28,
         'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': 28}

        >>> c.nbytes(summary=True)  # doctest: +SKIP
        {'inc': 84}

        See Also
        --------
        Client.who_has
        )r   summary)rr   r  rq   )r   r   r  r  s       r   rq   zClient.nbytes  s+    < tyy..UT7UfUUr   c                    |xs g }|7| j                  |      }|t        |D ch c]  }|j                   c}      z  }| j                  | j                  j
                  |xs d      S c c}w )a  The actively running call stack of all relevant keys

        You can specify data of interest either by providing futures or
        collections in the ``futures=`` keyword or a list of explicit keys in
        the ``keys=`` keyword.  If neither are provided then all call stacks
        will be returned.

        Parameters
        ----------
        futures : list (optional)
            List of futures, defaults to all data
        keys : list (optional)
            List of key names, defaults to all data

        Examples
        --------
        >>> df = dd.read_parquet(...).persist()  # doctest: +SKIP
        >>> client.call_stack(df)  # call on collections

        >>> client.call_stack()  # Or call with no arguments for all activity  # doctest: +SKIP
        Nr-  )rI  r   r   rr   r  
call_stack)r   r   r   r  s       r   r  zClient.call_stack  si    , zroog.GD1A!%%122Dyy22yFF 2s   A+
c
                L    | j                  | j                  |||||||||	
      S )ak  Collect statistical profiling information about recent work

        Parameters
        ----------
        key : str
            Key prefix to select, this is typically a function name like 'inc'
            Leave as None to collect all data
        start : time
        stop : time
        workers : list
            List of workers to restrict profile information
        server : bool
            If true, return the profile of the worker's administrative thread
            rather than the worker threads.
            This is useful when profiling Dask itself, rather than user code.
        scheduler : bool
            If true, return the profile information from the scheduler's
            administrative thread rather than the workers.
            This is useful when profiling Dask's scheduling itself.
        plot : boolean or string
            Whether or not to return a plot object
        filename : str
            Filename to save the plot

        Examples
        --------
        >>> client.profile()  # call on collections
        >>> client.profile(filename='dask-profile.html')  # save to html file
        )	r   r  merge_workersr.  r  plotr   r  r  )rr   _profile)
r   r   r.  r  r  r  r  r   r  r  s
             r   profilezClient.profile  s=    R yyMM'  
 	
r   c
           	     T  K   t        |t        t        f      r|g}| j                  j	                  |||||||	       d {   }
|rd}|rXddlm} |j                  |
      }|j                  |d      \  }}|dk(  r|sd}|rdd	lm	}m
}  ||d
        |||       |
|fS |
S 7 dw)N)r   r  r  r.  r  r  r  Tr   )r  stretch_bothsizing_modesavezdask-profile.htmloutput_filer#  zDask Profiler   title)r   )r  r   r   r  r  r  	plot_dataplot_figurebokeh.plottingr%  r#  )r   r   r.  r  r  r  r  r   r  r  r   r  r  figuresourcer%  r#  s                    r   r  zClient._profile.  s      gV}-iGnn,,' - 
 
 D+$$U+D$00>0RNFFv~h.<X^DVh/6?" L=
s   ?B(B&A%B(c                h    | j                   s| j                  | j                         | j                  S )a  Basic information about the workers in the cluster

        Parameters
        ----------
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> c.scheduler_info()  # doctest: +SKIP
        {'id': '2de2b6da-69ee-11e6-ab6a-e82aea155996',
         'services': {},
         'type': 'Scheduler',
         'workers': {'127.0.0.1:40575': {'active': 0,
                                         'last-seen': 1472038237.4845693,
                                         'name': '127.0.0.1:40575',
                                         'services': {},
                                         'stored': 0,
                                         'time-delay': 0.0061032772064208984}}}
        )r  rr   r  r	  r8  s     r   r  zClient.scheduler_info]  s+    *   IId112'''r   dask-cluster-dumpc                F     | j                   | j                  f||||d|S )a  Extract a dump of the entire cluster state and persist to disk or a URL.
        This is intended for debugging purposes only.

        Warning: Memory usage on the scheduler (and client, if writing the dump locally)
        can be large. On a large or long-running cluster, this can take several minutes.
        The scheduler may be unresponsive while the dump is processed.

        Results will be stored in a dict::

            {
                "scheduler": {...},  # scheduler state
                "workers": {
                    worker_addr: {...},  # worker state
                    ...
                }
                "versions": {
                    "scheduler": {...},
                    "workers": {
                        worker_addr: {...},
                        ...
                    }
                }
            }

        Parameters
        ----------
        filename:
            The path or URL to write to. The appropriate file suffix (``.msgpack.gz`` or
            ``.yaml``) will be appended automatically.

            Must be a path supported by :func:`fsspec.open` (like ``s3://my-bucket/cluster-dump``,
            or ``cluster-dumps/dump``). See ``write_from_scheduler`` to control whether
            the dump is written directly to ``filename`` from the scheduler, or sent
            back to the client over the network, then written locally.
        write_from_scheduler:
            If None (default), infer based on whether ``filename`` looks like a URL
            or a local path: True if the filename contains ``://`` (like
            ``s3://my-bucket/cluster-dump``), False otherwise (like ``local_dir/cluster-dump``).

            If True, write cluster state directly to ``filename`` from the scheduler.
            If ``filename`` is a local path, the dump will be written to that
            path on the *scheduler's* filesystem, so be careful if the scheduler is running
            on ephemeral hardware. Useful when the scheduler is attached to a network
            filesystem or persistent disk, or for writing to buckets.

            If False, transfer cluster state from the scheduler back to the client
            over the network, then write it to ``filename``. This is much less
            efficient for large dumps, but useful when the scheduler doesn't have
            access to any persistent storage.
        exclude:
            A collection of attribute names which are supposed to be excluded
            from the dump, e.g. to exclude code, tracebacks, logs, etc.

            Defaults to exclude ``run_spec``, which is the serialized user code.
            This is typically not required for debugging. To allow serialization
            of this, pass an empty tuple.
        format:
            Either ``"msgpack"`` or ``"yaml"``. If msgpack is used (default),
            the output will be stored in a gzipped file as msgpack.

            To read::

                import gzip, msgpack
                with gzip.open("filename") as fd:
                    state = msgpack.unpack(fd)

            or::

                import yaml
                try:
                    from yaml import CLoader as Loader
                except ImportError:
                    from yaml import Loader
                with open("filename") as fd:
                    state = yaml.load(fd, Loader=Loader)
        **storage_options:
            Any additional arguments to :func:`fsspec.open` when writing to a URL.
        )r   write_from_schedulerexcluder  )rr   _dump_cluster_stater   r   r0  r1  r  storage_optionss         r   dump_cluster_statezClient.dump_cluster_statev  s<    l tyy$$
!5
 
 	
r   c                
  K   t        |      }|d|v }|r) | j                  j                  d|||d| d {    y t        j                  t        | j                  j                  |      ||fi | d {    y 7 E7 w)NrM  )urlr1  r  )r1  r   )r   r  dump_cluster_state_to_urlrF   write_stater   get_cluster_stater3  s         r   r2  zClient._dump_cluster_state  s      x='#(H#4 :$..::  "	   **88'J "	  s!   7BA??B9B:BBc                    | j                   rt        d      || _         t        | j                   d      5 }t        j                  | j                         |d       ddd       y# 1 sw Y   yxY w)a  Write the scheduler information to a json file.

        This facilitates easy sharing of scheduler information using a file
        system. The scheduler file can be used to instantiate a second Client
        using the same scheduler.

        Parameters
        ----------
        scheduler_file : str
            Path to a write the scheduler file.

        Examples
        --------
        >>> client = Client()  # doctest: +SKIP
        >>> client.write_scheduler_file('scheduler.json')  # doctest: +SKIP
        # connect to previous client's scheduler
        >>> client2 = Client(scheduler_file='scheduler.json')  # doctest: +SKIP
        zScheduler file already setrc  r  )indentN)r  r  r  r  dumpr  )r   r  r  s      r   write_scheduler_filezClient.write_scheduler_file  sX    & 9::"0D$%%s+qIId))+Qq9 ,++s   'A%%A.c                    t        |t        t        f      s|f}| j                  | j                  j
                  ||      S )a  Get arbitrary metadata from scheduler

        See set_metadata for the full docstring with examples

        Parameters
        ----------
        keys : key or list
            Key to access.  If a list then gets within a nested collection
        default : optional
            If the key does not exist then return this value instead.
            If not provided then this raises a KeyError if the key is not
            present

        See Also
        --------
        Client.set_metadata
        )r   r   )r  r   r   rr   r  get_metadata)r   r   r   s      r   r@  zClient.get_metadata  s8    $ $u.7Dyy444yQQr   c                P    | j                  | j                  j                  |      S )aQ  Get logs from scheduler

        Parameters
        ----------
        n : int
            Number of logs to retrieve.  Maxes out at 10000 by default,
            configurable via the ``distributed.admin.log-length``
            configuration value.

        Returns
        -------
        Logs in reversed order (newest first)
        )r8  )rr   r  logs)r   r8  s     r   get_scheduler_logszClient.get_scheduler_logs!  s!     yy,,y22r   c                T    | j                  | j                  j                  |||      S )a  Get logs from workers

        Parameters
        ----------
        n : int
            Number of logs to retrieve.  Maxes out at 10000 by default,
            configurable via the ``distributed.admin.log-length``
            configuration value.
        workers : iterable
            List of worker addresses to retrieve.  Gets all workers by default.
        nanny : bool, default False
            Whether to get the logs from the workers (False) or the nannies
            (True). If specified, the addresses in `workers` should still be
            the worker addresses, not the nanny addresses.

        Returns
        -------
        Dictionary mapping worker address to logs.
        Logs are returned in reversed order (newest first)
        )r8  r  rm  )rr   r  worker_logs)r   r8  r  rm  s       r   get_worker_logszClient.get_worker_logs1  s&    * yy33q'QVyWWr   c                L    | j                  | j                  j                        S )ay  
        Run a benchmark on the workers for memory, disk, and network bandwidths

        Returns
        -------
        result: dict
            A dictionary mapping the names "disk", "memory", and "network" to
            dictionaries mapping sizes to bandwidths.  These bandwidths are
            averaged over many workers running computations across the cluster.
        )rr   r  benchmark_hardwarer   s    r   rH  zClient.benchmark_hardwareH  s     yy::;;r   c                    t        |      st        dt        |      d      | j                  | j                  j
                  ||      S )a  Log an event under a given topic

        Parameters
        ----------
        topic : str, list[str]
            Name of the topic under which to log an event. To log the same
            event under multiple topics, pass a list of topic names.
        msg
            Event message to log. Note this must be msgpack serializable.

        Examples
        --------
        >>> from time import time
        >>> client.log_event("current-time", time())
        z4Message must be msgpack serializable. Got type(msg)=z	 instead.)r  r   )r:   r,  r   rr   r  	log_eventr   r  r   s      r   rJ  zClient.log_eventU  sJ      C GT#YL	R  yy11CyHHr   c                P    | j                  | j                  j                  |      S )zRetrieve structured topic logs

        Parameters
        ----------
        topic : str, optional
            Name of topic log to retrieve events for. If no ``topic`` is
            provided, then logs for all topics will be returned.
        )r  )rr   r  events)r   r  s     r   
get_eventszClient.get_eventsk  s!     yy..ey<<r   c                   K   || j                   vr| j                  |       y | j                   |   } ||      }t        j                  |      r| d {    y y 7 wr   )r#  unsubscribe_topicr  r  )r   r  rk  r   rets        r   r+  zClient._handle_eventv  s[     ,,,""5)&&u-ens#II $s   AAAAc                    || j                   v rt        j                  d|       || j                   |<   d|| j                  d}| j	                  |       y)a&  Subscribe to a topic and execute a handler for every received event

        Parameters
        ----------
        topic: str
            The topic name
        handler: callable or coroutine function
            A handler called for every received event. The handler must accept a
            single argument `event` which is a tuple `(timestamp, msg)` where
            timestamp refers to the clock on the scheduler.

        Examples
        --------

        >>> import logging
        >>> logger = logging.getLogger("myLogger")  # Log config not shown
        >>> client.subscribe_topic("topic-name", lambda: logger.info)

        See Also
        --------
        dask.distributed.Client.unsubscribe_topic
        dask.distributed.Client.get_events
        dask.distributed.Client.log_event
        z(Handler for %s already set. Overwriting.zsubscribe-topicr  r  r   N)r#  r$  r  r  r  )r   r  r   r   s       r   r  zClient.subscribe_topic  sO    2 D(((KKBEJ&-U#&$''J$r   c                    || j                   v r"d|| j                  d}| j                  |       yt        d| d      )zUnsubscribe from a topic and remove event handler

        See Also
        --------
        dask.distributed.Client.subscribe_topic
        dask.distributed.Client.get_events
        dask.distributed.Client.log_event
        zunsubscribe-topicrS  z!No event handler known for topic r   N)r#  r  r  r  rK  s      r   rP  zClient.unsubscribe_topic  sE     D(((,uPC##C(@qIJJr   c                V     | j                   | j                  j                  f||d|S )a  Retire certain workers on the scheduler

        See :meth:`distributed.Scheduler.retire_workers` for the full docstring.

        Parameters
        ----------
        workers
        close_workers
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        You can get information about active workers using the following:

        >>> workers = client.scheduler_info()['workers']

        From that list you may want to select some workers to close

        >>> client.retire_workers(workers=['tcp://address:port', ...])

        See Also
        --------
        dask.distributed.Scheduler.retire_workers
        )r  close_workers)rr   r  retire_workers)r   r  rV  r  s       r   rW  zClient.retire_workers  s9    8 tyyNN))
'
 	
 	
r   c                x    t        |t              s|f}| j                  | j                  j                  ||      S )av  Set arbitrary metadata in the scheduler

        This allows you to store small amounts of data on the central scheduler
        process for administrative purposes.  Data should be msgpack
        serializable (ints, strings, lists, dicts)

        If the key corresponds to a task then that key will be cleaned up when
        the task is forgotten by the scheduler.

        If the key is a list then it will be assumed that you want to index
        into a nested dictionary structure using those keys.  For example if
        you call the following::

            >>> client.set_metadata(['a', 'b', 'c'], 123)

        Then this is the same as setting

            >>> scheduler.task_metadata['a']['b']['c'] = 123

        The lower level dictionaries will be created on demand.

        Examples
        --------
        >>> client.set_metadata('x', 123)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        123

        >>> client.set_metadata(['x', 'y'], 123)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        {'y': 123}

        >>> client.set_metadata(['x', 'w', 'z'], 456)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        {'y': 123, 'w': {'z': 456}}

        >>> client.get_metadata(['x', 'w'])  # doctest: +SKIP
        {'z': 456}

        See Also
        --------
        get_metadata
        )r   rB  )r  r   rr   r  set_metadata)r   r   rB  s      r   rY  zClient.set_metadata  s5    V #t$&Cyy443eyLLr   c                F    | j                  | j                  ||xs g       S )a  Return version info for the scheduler, all workers and myself

        Parameters
        ----------
        check
            raise ValueError if all required & optional packages
            do not match
        packages
            Extra package names to check

        Examples
        --------
        >>> c.get_versions()  # doctest: +SKIP

        >>> c.get_versions(packages=['sklearn', 'geopandas'])  # doctest: +SKIP
        )checkpackages)rr   _get_versions)r   r[  r\  s      r   r  zClient.get_versions  s#    & yy++58>ryRRr   c                  K   |xs g }t        j                  |      }| j                  j                  |       d {   }| j                  j	                  d|dd       d {   }t        |||      }|rGt        j                  |||      }|d   rt        j                  |d          |d   rt        |d         |S 7 7 _w)	N)r\  rH   )r  r\  rr  r   rn  )r  r  r   r  r   )
r  r  r  rH   r7  r  error_messager  r  r  )r   r[  r\  r   r  r  r   r   s           r   r]  zClient._get_versions  s      >r,,h?..1181DD	00!x8 1 
 
 	76R ..y'6JC9~c)n-7| W.. E
s"   <CC'C&C'ACCc                    t        ||       S )z|Wrapper method of futures_of

        Parameters
        ----------
        futures : tuple
            The futures
        r  )rI  )r   r   s     r   rI  zClient.futures_of)  s     '$//r   c              #     K   t        |t              s|f}|D ]4  }t        j                  |      r|j	                         E d{    1| 6 y7 w)zs
        Expand a user-provided task key specification, e.g. in a resources
        or retries dictionary.
        N)r  r   r  r  r  )r1  r   kks      r   r  zClient._expand_key3  sK      !U#AB&&r*++---	 -s   AAAAc                     t        | g|i |S )zEConvert many collections into a single dask graph, after optimizationr%   )r  r  r  s      r   r&   zClient.collections_to_dskA  s     "+????r   r  c                 K   |dv sJ 	 | j                   j                  |       d {   }|D cg c]  }dg|
 }}| j                   j	                  d|d|	       d {   }|j                         D ]  \  }|j                  fd
|D               ! |S 7 sc c}w # t        $ r |dk(  r |dk(  rg }nt        dd       Y w xY w7 jw)N)r  rr  )keys_or_stimulir  r  rr  zon_error not in 	get_story)r  rf  r_  c              3  *   K   | ]
  }g|  y wr   r   )rb  r   r  s     r   rd  z Client._story.<locals>.<genexpr>[  s     B'3#'s   )r  rg  r  r  r7  r  extend)r   rn  rf  flat_storiesr   rs  storiesr  s          @r   _storyzClient._storyF  s    ....	I!%!9!9 / ": " L <HH<C[/3/<LH ..22"G 3 
 
	  )0OFGB'BB  1% I 	I7"X%! #34E3F!GHH 		I
sU   CB% BB% B  B% #C%C&8CB%  B% %%C
CCCc               B     | j                   | j                  g|d|iS )z@Returns a cluster-wide story for the given keys or stimulus_id'srn  )rr   rl  )r   rn  rf  s      r   storyzClient.story^  s!    tyyJJJJr   c           	     F    | j                  | j                  ||||||      S )a~  Get task stream data from scheduler

        This collects the data present in the diagnostic "Task Stream" plot on
        the dashboard.  It includes the start, stop, transfer, and
        deserialization time of every task for a particular duration.

        Note that the task stream diagnostic does not run by default.  You may
        wish to call this function once before you start work to ensure that
        things start recording, and then again after you have completed.

        Parameters
        ----------
        start : Number or string
            When you want to start recording
            If a number it should be the result of calling time()
            If a string then it should be a time difference before now,
            like '60s' or '500 ms'
        stop : Number or string
            When you want to stop recording
        count : int
            The number of desired records, ignored if both start and stop are
            specified
        plot : boolean, str
            If true then also return a Bokeh figure
            If plot == 'save' then save the figure to a file
        filename : str (optional)
            The filename to save to if you set ``plot='save'``
        bokeh_resources : bokeh.resources.Resources (optional)
            Specifies if the resource component is INLINE or CDN

        Examples
        --------
        >>> client.get_task_stream()  # prime plugin if not already connected
        >>> x.compute()  # do some work
        >>> client.get_task_stream()
        [{'task': ...,
          'type': ...,
          'thread': ...,
          ...}]

        Pass the ``plot=True`` or ``plot='save'`` keywords to get back a Bokeh
        figure

        >>> data, figure = client.get_task_stream(plot='save', filename='myfile.html')

        Alternatively consider the context manager

        >>> from dask.distributed import get_task_stream
        >>> with get_task_stream() as ts:
        ...     x.compute()
        >>> ts.data
        [...]

        Returns
        -------
        L: List[Dict]

        See Also
        --------
        get_task_stream : a context manager version of this method
        )r.  r  r   r  r   bokeh_resources)rr   _get_task_stream)r   r.  r  r   r  r   rp  s          r   get_task_streamzClient.get_task_streamb  s6    L yy!!+  
 	
r   c                $  K   | j                   j                  |||       d {   }|raddlm}  ||      }	ddlm}
  |
d      \  }}|j                  j                  |	       |dk(  rddlm	}m
}  ||d	
        ||||       ||fS |S 7 iw)N)r.  r  r   r   )
rectangles)task_stream_figurer   r!  r#  r$  zDask Task Streamr&  )r   r  )r  rr  #distributed.diagnostics.task_streamrt  *distributed.dashboard.components.schedulerru  r  r  r*  r%  r#  )r   r.  r  r   r  r   rp  r  rt  rectsru  r,  r+  r%  r#  s                  r   rq  zClient._get_task_stream  s      ^^33%dRW3XXFt$EU/NKNFFKKu%v~<X5GHVh/J&>!K! Ys   "BBA*Bc                    |t        |      }|sJ |t        j                  dt        d       nt	        |dd      }t        |t              sJ | j                  |||      S )a$  Register a plugin.

        See https://distributed.readthedocs.io/en/latest/plugins.html

        Parameters
        ----------
        plugin :
            A nanny, scheduler, or worker plugin to register.
        name :
            Name for the plugin; if None, a name is taken from the
            plugin instance or automatically generated if not present.
        idempotent :
            Do not re-register if a plugin of the given name already exists.
            If None, ``plugin.idempotent`` is taken if defined, False otherwise.
        zThe `idempotent` argument is deprecated and will be removed in a future version. Please mark your plugin as idempotent by setting its `.idempotent` attribute to `True`.r  r;  
idempotentF)rZ   r  r  FutureWarningr  r  r  _register_pluginr   pluginr2  rz  s       r   r  zClient.register_plugin  sn    * <#F+Dt!MM5  !u=J*d+++$$VT:>>r   c                    t        |t              rt        d      t        d |j                  j
                  D              rt        d      t        d      )Nz3Please provide an instance of a plugin, not a type.c              3  6   K   | ]  }d t        |      v   yw)z#dask.distributed.diagnostics.pluginN)r   )rb  r   s     r   rd  z*Client._register_plugin.<locals>.<genexpr>  s!      
/ 2SV;/s   zImporting plugin base classes from `dask.distributed.diagnostics.plugin` is not supported. Please import directly from `distributed.diagnostics.plugin` instead.zRegistering duck-typed plugins is not allowed. Please inherit from NannyPlugin, WorkerPlugin, or SchedulerPlugin to create a plugin.)r  r   r,  anyr   	__bases__r}  s       r   r|  zClient._register_plugin  se     fd#QRR 
%%//
 
 X  P
 	
r   c                @    | j                  | j                  |||      S Nr~  r2  rz  )rr   _register_scheduler_pluginr}  s       r   rz  zClient._  s*    yy++!	  
 	
r   c                @    | j                  | j                  |||      S r  )rr   _register_nanny_pluginr}  s       r   rz  zClient._  s,     yy''!	  
 	
r   c                @    | j                  | j                  |||      S r  )rr   _register_worker_pluginr}  s       r   rz  zClient._  s*    yy((!	  
 	
r   c                l   K   | j                   j                  t        |      ||       d {   S 7 wr  )r  register_scheduler_pluginr`   r}  s       r   r  z!Client._register_scheduler_plugin%  s;      ^^===! > 
 
 	
 
s   +424c                |    t        j                  dt        d       t        t        | j                  |||            S )al  
        Register a scheduler plugin.

        .. deprecated:: 2023.9.2
            Use :meth:`Client.register_plugin` instead.

        See https://distributed.readthedocs.io/en/latest/plugins.html#scheduler-plugins

        Parameters
        ----------
        plugin : SchedulerPlugin
            SchedulerPlugin instance to pass to the scheduler.
        name : str
            Name for the plugin; if None, a name is taken from the
            plugin instance or automatically generated if not present.
        idempotent : bool
            Do not re-register if a plugin of the given name already exists.
        z_`Client.register_scheduler_plugin` has been deprecated; please `Client.register_plugin` insteadr  r;  )r  r  r>  r   r9   r  r}  s       r   r  z Client.register_scheduler_plugin.  s9    0 	6		
 It33FD*MNNr   c                V   K   | j                   j                  |       d {   S 7 wNr  )r  unregister_scheduler_pluginr   r2  s     r   _unregister_scheduler_pluginz#Client._unregister_scheduler_pluginN  s$     ^^??T?JJJJs    )')c                <    | j                  | j                  |      S )a1  Unregisters a scheduler plugin

        See https://distributed.readthedocs.io/en/latest/plugins.html#scheduler-plugins

        Parameters
        ----------
        name : str
            Name of the plugin to unregister. See the :meth:`Client.register_scheduler_plugin`
            docstring for more information.

        Examples
        --------
        >>> class MyPlugin(SchedulerPlugin):
        ...     def __init__(self, *args, **kwargs):
        ...         pass  # the constructor is up to you
        ...     async def start(self, scheduler: Scheduler) -> None:
        ...         pass
        ...     async def before_close(self) -> None:
        ...         pass
        ...     async def close(self) -> None:
        ...         pass
        ...     def restart(self, scheduler: Scheduler) -> None:
        ...         pass

        >>> plugin = MyPlugin(1, 2, 3)
        >>> client.register_plugin(plugin, name='foo')
        >>> client.unregister_scheduler_plugin(name='foo')

        See Also
        --------
        register_scheduler_plugin
        r  )rr   r  r  s     r   r  z"Client.unregister_scheduler_pluginQ  s    B yy::yFFr   c                6    | j                  t        |            S )a  
        Registers a setup callback function for all current and future workers.

        This registers a new setup function for workers in this cluster. The
        function will run immediately on all currently connected workers. It
        will also be run upon connection by any workers that are added in the
        future. Multiple setup functions can be registered - these will be
        called in the order they were added.

        If the function takes an input argument named ``dask_worker`` then
        that variable will be populated with the worker itself.

        Parameters
        ----------
        setup : callable(dask_worker: Worker) -> None
            Function to register and run on all workers
        )r  _WorkerSetupPluginr   setups     r   register_worker_callbacksz Client.register_worker_callbackst  s    $ ##$6u$=>>r   c                6  K   | j                   j                  t        |      ||       d {   }|j                         D ]5  }|d   dk(  st	        |d   |d         \  }}}|sJ |j                  |       t        t        t        t        f   |      S 7 iwNr  r   r   r  r  )
r  register_worker_pluginr`   rg  rQ   r  r   r  r   r9   	r   r~  r2  rz  rs  r*  rz  r  r  s	            r   r  zClient._register_worker_plugin  s      ..??=t
 @ 
 
	 "((*H!W,,[)8K+@
3 
s((,, + Di()44
   +BBBA
Bc                6  K   | j                   j                  t        |      ||       d {   }|j                         D ]5  }|d   dk(  st	        |d   |d         \  }}}|sJ |j                  |       t        t        t        t        f   |      S 7 iwr  )
r  register_nanny_pluginr`   rg  rQ   r  r   r  r   r9   r  s	            r   r  zClient._register_nanny_plugin  s      ..>>=t
 ? 
 
	 "((*H!W,,[)8K+@
3 
s((,, + Di()44
r  c                   t        j                  dt        d       |t        |      }|sJ t	        |t
              r-| j                  }|du rt        j                  dt        d       nt	        |t              r-| j                  }|du rt        j                  dt        d       nt	        |t              rH|rt        j                  dt        d       nt        j                  d	t        d       | j                  }n9t        j                  d
t        d       |du r| j                  }n| j                  }| j                  |||d      S )a
  
        Registers a lifecycle worker plugin for all current and future workers.

        .. deprecated:: 2023.9.2
            Use :meth:`Client.register_plugin` instead.

        This registers a new object to handle setup, task state transitions and
        teardown for workers in this cluster. The plugin will instantiate
        itself on all currently connected workers. It will also be run on any
        worker that connects in the future.

        The plugin may include methods ``setup``, ``teardown``, ``transition``,
        and ``release_key``.  See the
        ``dask.distributed.WorkerPlugin`` class or the examples below for the
        interface and docstrings.  It must be serializable with the pickle or
        cloudpickle modules.

        If the plugin has a ``name`` attribute, or if the ``name=`` keyword is
        used then that will control idempotency.  If a plugin with that name has
        already been registered, then it will be removed and replaced by the new one.

        For alternatives to plugins, you may also wish to look into preload
        scripts.

        Parameters
        ----------
        plugin : WorkerPlugin or NannyPlugin
            WorkerPlugin or NannyPlugin instance to register.
        name : str, optional
            A name for the plugin.
            Registering a plugin with the same name will have no effect.
            If plugin has no name attribute a random name is used.
        nanny : bool, optional
            Whether to register the plugin with workers or nannies.

        Examples
        --------
        >>> class MyPlugin(WorkerPlugin):
        ...     def __init__(self, *args, **kwargs):
        ...         pass  # the constructor is up to you
        ...     def setup(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def teardown(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def transition(self, key: str, start: str, finish: str,
        ...                    **kwargs):
        ...         pass
        ...     def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool):
        ...         pass

        >>> plugin = MyPlugin(1, 2, 3)
        >>> client.register_plugin(plugin)

        You can get access to the plugin with the ``get_worker`` function

        >>> client.register_plugin(other_plugin, name='my-plugin')
        >>> def f():
        ...    worker = get_worker()
        ...    plugin = worker.plugins['my-plugin']
        ...    return plugin.my_state

        >>> future = client.run(f)

        See Also
        --------
        distributed.WorkerPlugin
        unregister_worker_plugin
        z``Client.register_worker_plugin` has been deprecated; please use `Client.register_plugin` insteadr  r;  TzRegistering a `WorkerPlugin` as a nanny plugin is not allowed, registering as a worker plugin instead. To register as a nanny plugin, inherit from `NannyPlugin`.FzRegistering a `NannyPlugin` as a worker plugin is not allowed, registering as a nanny plugin instead. To register as a worker plugin, inherit from `WorkerPlugin`.zRegistering a `SchedulerPlugin` as a nanny plugin is not allowed, registering as a scheduler plugin instead. To register as a nanny plugin, inherit from `NannyPlugin`.zRegistering a `SchedulerPlugin` as a worker plugin is not allowed, registering as a scheduler plugin instead. To register as a worker plugin, inherit from `WorkerPlugin`.zRegistering duck-typed plugins has been deprecated. Please make sure your plugin inherits from `NannyPlugin` or `WorkerPlugin`.r  )r  r  r>  rZ   r  rY   r  UserWarningrU   r  rV   r  rr   )r   r~  r2  rm  methods        r   r  zClient.register_worker_plugin  sE   T 	:		
 <#F+Dt fl+11F}Q    ,00F~S    0Q    S    44FMM% # }4455yyTeyLLr   c                &  K   |r%| j                   j                  |       d {   }n$| j                   j                  |       d {   }|j                         D ]*  }|d   dk(  st	        di |\  }}}|j                  |       |S 7 h7 Ew)Nr  r   r   r   )r  unregister_nanny_pluginunregister_worker_pluginrg  rQ   r  )r   r2  rm  rs  r*  rz  r  r  s           r   _unregister_worker_pluginz Client._unregister_worker_plugin1  s     "nnDD$DOOI"nnEE4EPPI!((*H!W,,8x8
3((,, +  PPs'   "BB$B	B
B*$BBc                >    | j                  | j                  ||      S )a  Unregisters a lifecycle worker plugin

        This unregisters an existing worker plugin. As part of the unregistration process
        the plugin's ``teardown`` method will be called.

        Parameters
        ----------
        name : str
            Name of the plugin to unregister. See the :meth:`Client.register_plugin`
            docstring for more information.

        Examples
        --------
        >>> class MyPlugin(WorkerPlugin):
        ...     def __init__(self, *args, **kwargs):
        ...         pass  # the constructor is up to you
        ...     def setup(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def teardown(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def transition(self, key: str, start: str, finish: str, **kwargs):
        ...         pass
        ...     def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool):
        ...         pass

        >>> plugin = MyPlugin(1, 2, 3)
        >>> client.register_plugin(plugin, name='foo')
        >>> client.unregister_worker_plugin(name='foo')

        See Also
        --------
        register_plugin
        )r2  rm  )rr   r  )r   r2  rm  s      r   r  zClient.unregister_worker_plugin=  s     D yy77d%yPPr   c                    ddl m}  ||       S )z:Convenience accessors for the :doc:`active_memory_manager`r   )AMMClientProxy)!distributed.active_memory_managerr  )r   r  s     r   ammz
Client.amma  s     	Ed##r   c                    |\  }}t        j                  |      }t        j                  |j                        }|j	                  |       y r   )loggingmakeLogRecord	getLoggerr2  handle)r   rk  rz  record_attrsrecorddest_loggers         r   _handle_forwarded_log_recordz#Client._handle_forwarded_log_recordh  s=    <&&|4''46"r   c                    d|xs d }t          d| }| j                  || j                         | j                  t	        |||      |      S )a  
        Begin forwarding the given logger (by default the root) and all loggers
        under it from worker tasks to the client process. Whenever the named
        logger handles a LogRecord on the worker-side, the record will be
        serialized, sent to the client, and handled by the logger with the same
        name on the client-side.

        Note that worker-side loggers will only handle LogRecords if their level
        is set appropriately, and the client-side logger will only emit the
        forwarded LogRecord if its own level is likewise set appropriately. For
        example, if your submitted task logs a DEBUG message to logger "foo",
        then in order for ``forward_logging()`` to cause that message to be
        emitted in your client session, you must ensure that the logger "foo"
        have its level set to DEBUG (or lower) in the worker process *and* in the
        client process.

        Parameters
        ----------
        logger_name : str, optional
            The name of the logger to begin forwarding. The usual rules of the
            ``logging`` module's hierarchical naming system apply. For example,
            if ``name`` is ``"foo"``, then not only ``"foo"``, but also
            ``"foo.bar"``, ``"foo.baz"``, etc. will be forwarded. If ``name`` is
            ``None``, this indicates the root logger, and so *all* loggers will
            be forwarded.

            Note that a logger will only forward a given LogRecord if the
            logger's level is sufficient for the LogRecord to be handled at all.

        level : str | int, optional
            Optionally restrict forwarding to LogRecords of this level or
            higher, even if the forwarded logger's own level is lower.

        Examples
        --------
        For purposes of the examples, suppose we configure client-side logging
        as a user might: with a single StreamHandler attached to the root logger
        with an output level of INFO and a simple output format::

            import logging
            import distributed
            import io, yaml

            TYPICAL_LOGGING_CONFIG = '''
            version: 1
            handlers:
              console:
                class : logging.StreamHandler
                formatter: default
                level   : INFO
            formatters:
              default:
                format: '%(asctime)s %(levelname)-8s [worker %(worker)s] %(name)-15s %(message)s'
                datefmt: '%Y-%m-%d %H:%M:%S'
            root:
              handlers:
                - console
            '''
            config = yaml.safe_load(io.StringIO(TYPICAL_LOGGING_CONFIG))
            logging.config.dictConfig(config)

        Now create a client and begin forwarding the root logger from workers
        back to our local client process.

        >>> client = distributed.Client()
        >>> client.forward_logging()  # forward the root logger at any handled level

        Then submit a task that does some error logging on a worker. We see
        output from the client-side StreamHandler.

        >>> def do_error():
        ...     logging.getLogger("user.module").error("Hello error")
        ...     return 42
        >>> client.submit(do_error).result()
        2022-11-09 03:43:25 ERROR    [worker tcp://127.0.0.1:34783] user.module     Hello error
        42

        Note how an attribute ``"worker"`` is also added by dask to the
        forwarded LogRecord, which our custom formatter uses. This is useful for
        identifying exactly which worker logged the error.

        One nuance worth highlighting: even though our client-side root logger
        is configured with a level of INFO, the worker-side root loggers still
        have their default level of ERROR because we haven't done any explicit
        logging configuration on the workers. Therefore worker-side INFO logs
        will *not* be forwarded because they never even get handled in the first
        place.

        >>> def do_info_1():
        ...     # no output on the client side
        ...     logging.getLogger("user.module").info("Hello info the first time")
        ...     return 84
        >>> client.submit(do_info_1).result()
        84

        It is necessary to set the client-side logger's level to INFO before the info
        message will be handled and forwarded to the client. In other words, the
        "effective" level of the client-side forwarded logging is the maximum of each
        logger's client-side and worker-side levels.

        >>> def do_info_2():
        ...     logger = logging.getLogger("user.module")
        ...     logger.setLevel(logging.INFO)
        ...     # now produces output on the client side
        ...     logger.info("Hello info the second time")
        ...     return 84
        >>> client.submit(do_info_2).result()
        2022-11-09 03:57:39 INFO     [worker tcp://127.0.0.1:42815] user.module     Hello info the second time
        84
        forward-logging-<root>r  )!TOPIC_PREFIX_FORWARDED_LOG_RECORDr  r  r  rT   )r   logger_namelevelplugin_namer  s        r   forward_loggingzClient.forward_loggingn  sa    ` ))@(AB45Q{mDUD$E$EF
 ## eU;[
 	
r   c                n    d|xs d }t          d| }| j                  |       | j                  |      S )zr
        Stop forwarding the given logger (default root) from worker tasks to the
        client process.
        r  r  r  )r  rP  r  )r   r  r  r  s       r   unforward_loggingzClient.unforward_logging  sF    
 ))@(AB45Q{mDu%,,[99r   )r   r  )rB  r?   r   NonerX  r   )r  r   r  zfloat | Noner   r  rW  )F)r  r  r   r  )r  r   r  r   r   zstr | list | Noner  r  r  
int | Noner  r  r  r   r  r  r  r   r  r  r  r  r  r  )r  NN)r!  r  r"  r  r   zdict[str, Any])NNF)NFNN)rm  r  r  list[str] | Noner  r  rn  $Literal['raise', 'return', 'ignore'])r  r  r  r  rm  r  rn  r  r  )r<  r  r  r   r   ztuple[SourceCode, ...])NNNr   NNr   N)
NNNTNNNr   60sN)
FTNFNr   r   r  NT)TNNNNr   r  N)r  str | int | float | NoDefaultr  r  r   r  )r  r  r  r  )r  	list[str]r  r  r  r  r   z0dict[str, Literal['OK', 'removed', 'timed out']])r  r  r  r  r  r  )r  r  rY  )NNr  )NT)	NNNNTFNFF)r.  Nr   msgpack)r   r   r0  bool | Noner1  zCollection[str]r  zLiteral['msgpack', 'yaml'])r   r  )r  zstr | Collection[str]r   r   )r  r   )r  r  rV  r  )FN)r[  r  r\  Sequence[str] | Noner   z0VersionsDict | Coroutine[Any, Any, VersionsDict])r[  r  r\  r  r   r  )rf  r   )NNNFtask-stream.htmlN)r~  ,NannyPlugin | SchedulerPlugin | WorkerPluginr2  r   rz  r  )r~  r  r2  r   rz  r  )r~  rV   r2  r   rz  r  )r~  rU   r2  r   rz  r  r   dict[str, OKMessage])r~  rY   r2  r   rz  r  )r~  rV   r2  r   rz  r  )r~  rY   r2  r   rz  r  r   r  )r~  zNannyPlugin | WorkerPluginr2  r   rm  r  )r   r   r   rZ  r[  r\  r]  r   r   weakrefWeakSetr  r  r  r  r  r0   DEFAULT_EXTENSIONSr   rb  r?  setterr-  r   rF  classmethodrK  rS  rT  rK  rN  r.  rP  r}  r  rs  rp   r  r  r  r  r  r   r  r  r  r  rF  r   r?  r  r  r$  r%  r&  r'  r(  r)  r*  r   r  r  r  r  r  r  r0  r   r  r   r0  rE  r=  rJ  r5  rM  r7  rX  rZ  r]  r`  rd  rf  rj  rl  rv  rp  r  rc  r  r   r  r  r  r  r  r  r  r  r  r  r   r  r>  r  ra  r  r/  r  r  rq   r  r  r  r  r5  rF   DEFAULT_CLUSTER_DUMP_EXCLUDEDEFAULT_CLUSTER_DUMP_FORMATr2  r>  r@  rC  rF  rH  rJ  rN  r+  r  rP  rW  rY  r  r]  rI  r  r&   rl  rn  rr  rq  r  r   r|  registerrz  r  r  r  r  r  r  r  r  r  r  r  r  r  NOTSETr  r  r   r   r   r   r     s	   [z .:#:K:K-LN*L4CGOO4EJ1E(5|L'' FM  %tl   ^^    
[[  
+ 
+ P PB !5 !5F.*J8
&3#1 $. ?B $  $ L8DtE 7;;;'3;	;:M*A
&$'	 6 6p

2

"$ E E$ ? ?B ' *%X 
).. !Ld "&.2"+/$)$o*o* o* 	o*
 ,o* o* )o* o* "o* o* o* o* o*bm^<>F fV t
l2
0J 15 "* "*H-A^M.	@ 0:  )3 M6 =A &%LV $(9@0 	0
 "0 0 70l %)9@\
 "	\

 \
 \
 7\
| 67a%a%03a%	a% a%F
  Uv  eN0'6X ![@  cJ
4
HL
	
 2<!%$
.$
 $
L / 	
 
:> 2< $	D
D
 /D
 	D
L>2,\	0F2
2
hK@ F%N&PE<V@G< 4
p -^(6 ,,0#%-6]
]
 *]
 !	]

 +]
B ,,0#/#L#L-9-U-U * !	
 +6:6 *4 R,3 X.<I,	=%>K  GK!
'!
?C!
F-M` EISS-AS	9S, EI-A	*0   @ @ <C 0 07 K #N
d #<  "&	#?<#? #?  	#?J 
<
 
 	
 
* 
 
 
!
),
:>
	
 
 
 

%
-0
>B
  "&	OO O  	O@K!GF?(5"5*-5;?5	55!5),5:>5	5$  !	IM*IM IM 	IMV
"QH $ $# +/gnn z
x:r   c                    t        | t              sJ g }| D ]G  }t        |t              r|j                  t        |             .|j                  t	        |             I t        | S r   )r  r   r{  r  rD   rB   )r   new_keysr   s      r   r  r    sY    dD!!!%'Hc4 OO.s34OOGCL)	 
 ?r   c                      e Zd ZdZd Zd Zy)r  z:This is used to support older setup functions as callbacksc                    || _         y r   )_setupr  s     r   r   z_WorkerSetupPlugin.__init__  s	    r   c                r    t        | j                  d      r| j                  |      S | j                         S )Nr  )r  )rn   r  )r   r  s     r   r  z_WorkerSetupPlugin.setup  s-    t{{M2;;6;22;;= r   N)r   r   r   rZ  r   r  r   r   r   r  r     s    D!r   r  c                     t        d      )Nz7This has been moved to the Client.get_executor() methodr  r  r  s     r   CompatibleExecutorr    s    
M
NNr   ALL_COMPLETEDFIRST_COMPLETEDc                  K   |t        |t              st        d      t        |       } |t        k(  rFt
        j                  j                  | D ch c]  }|j                  j                          c}      }nZ|t        k(  rFt
        j                  j                  | D ch c]  }|j                  j                          c}      }nt        d      |t        ||      }| d {    | D ch c]  }|j                  dk7  s| c}| D ch c]  }|j                  dk(  s| c}}}t        t               }|D ]Y  }|j#                         s|j                  j$                  }	t        |	t&              sJ ||	j(                     j+                  |	       [ |r8|j-                         D 
cg c]  \  }
}t/        ||
       }}
}t1        |      t3        ||      S c c}w c c}w 7 c c}w c c}w c c}}
w w)Nztimeout= keyword received a non-numeric value.
Beware that wait expects a list of values
  Bad:  wait(x, y, z)
  Good: wait([x, y, z])zDOnly return_when='ALL_COMPLETED' and 'FIRST_COMPLETED' are supportedrf  r   )r  r   r,  rI  r  r  r  r  r   r  r  r   NotImplementedErrorr<   r   r   r   r  r  r   r   r{  r  r   r   r   )fsr  return_whenr  r  fur  not_donecancelled_errorsr  r   r   groupss                r   r  r    s    :gv#>&
 	
 
BBm#""&&'DA'DE		'""&&'DA'DE!R
 	
 &'*
LL 3bBII2b33bBII2b3 D #4({{}HH&&	)%9:::))*11)<   #3"8"8":
": "?": 	 
 $F++ x00= (E'D  	43
sa   AG<!G2.G< !G$&G<'G)(G<0G,G,	G<G1$G1(BG<.G6%G<,G<c                    |#t        |t        t        f      rt        |d      }t	               }|j                  t        | ||      }|S )a  Wait until all/any futures are finished

    Parameters
    ----------
    fs : List[Future]
    timeout : number, string, optional
        Time after which to raise a ``dask.distributed.TimeoutError``.
        Can be a string like ``"10 minutes"`` or a number of seconds to wait.
    return_when : str, optional
        One of `ALL_COMPLETED` or `FIRST_COMPLETED`

    Returns
    -------
    Named tuple of completed, not completed
    r   r   )r  r  )r  r   r   r5   rH  rr   r  )r  r  r  r   r   s        r   r  r  @  sF      z'FC=A!'37F[[G[MFMr   c           
       K   t        |       } t        d |       }|j                         D cg c]  }|d   	 }}t        j                  t        t        j                  |D cg c]  }|j                  j                          c}       }|j                         s^|j                          d {    ||j                     }||j                     D ]  }|j                  |        |j                         s]y y c c}w c c}w 7 Uw)Nc                    | j                   S r   r   )r  s    r   r   z_as_completed.<locals>.<lambda>Y  s    quur   r   )rI  r!   rg  r>   WaitIteratorr   ri  rr  r   r  r  r   current_indexr   
put_nowait)r  queuer  r  firstsr  wait_iteratorr  s           r   _as_completedr  W  s     	BB_b)F"MMO,OqadOF,$$	W""f$EfQXX]]_f$E	FM   "  """334

#AQ $	   " -$E 	#s.   +DC:)D"!C?+D.D/AD8Dc                   K   t        j                         }t        | |       d{    |j                          d{   }|S 7 7 w)zJReturn a single completed future

    See Also:
        _as_completed
    N)ri  r   r  r   )r   qr   s      r   _first_completedr  g  s>      	A

###557]FM $s   $A	AA	AA	A	c                      e Zd ZdZ	 	 	 	 ddddZed        Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd Zd ZeZddZd Zd Zy)as_completeda`  
    Return futures in the order in which they complete

    This returns an iterator that yields the input future objects in the order
    in which they complete.  Calling ``next`` on the iterator will block until
    the next future completes, irrespective of order.

    Additionally, you can also add more futures to this object during
    computation with the ``.add`` method

    Parameters
    ----------
    futures: Collection of futures
        A list of Future objects to be iterated over in the order in which they
        complete
    with_results: bool (False)
        Whether to wait and include results of futures as well;
        in this case ``as_completed`` yields a tuple of (future, result)
    raise_errors: bool (True)
        Whether we should raise when the result of a future raises an
        exception; only affects behavior when ``with_results=True``.
    timeout: int (optional)
        The returned iterator raises a ``dask.distributed.TimeoutError``
        if ``__next__()`` or ``__anext__()`` is called and the result
        isn't available after timeout seconds from the original call to
        ``as_completed()``. If timeout is not specified or ``None``, there is no limit
        to the wait time.

    Examples
    --------
    >>> x, y, z = client.map(inc, [1, 2, 3])  # doctest: +SKIP
    >>> for future in as_completed([x, y, z]):  # doctest: +SKIP
    ...     print(future.result())  # doctest: +SKIP
    3
    2
    4

    Add more futures during computation

    >>> x, y, z = client.map(inc, [1, 2, 3])  # doctest: +SKIP
    >>> ac = as_completed([x, y, z])  # doctest: +SKIP
    >>> for future in ac:  # doctest: +SKIP
    ...     print(future.result())  # doctest: +SKIP
    ...     if random.random() < 0.5:  # doctest: +SKIP
    ...         ac.add(c.submit(double, future))  # doctest: +SKIP
    4
    2
    8
    3
    6
    12
    24

    Optionally wait until the result has been gathered as well

    >>> ac = as_completed([x, y, z], with_results=True)  # doctest: +SKIP
    >>> for future, result in ac:  # doctest: +SKIP
    ...     print(result)  # doctest: +SKIP
    2
    4
    3
    Nr  c               z   |g }t        t              | _        t               | _        t        j                         | _        |xs t               j                  | _	        t        j                         | _        || _        || _        t        j                  t!        |            | _        |r| j%                  |       y y r   )r   r   r   r  r  r
  LocklockrH  r-  	Conditionthread_conditionwith_resultsraise_errorsr;   afterr5   	_deadliner  )r   r   r-  r  r  r  s         r   r   zas_completed.__init__  s     ?G"3'Y
NN$	1N,11	 ) 3 3 5((!(@AKK  r   c                    	 | j                   S # t        $ r( t        j                         | _         | j                   cY S w xY wr   )
_conditionrE  ri  r  r   s    r   	conditionzas_completed.condition  s:    	#??" 	#%//1DO??"	#s    .??c                T  K   	 t        |       d {    | j                  r	 |j                  d       d {   }| j                  5  || j
                  v r| j
                  |xx   dz  cc<   | j
                  |   s| j
                  |= | j                  r| j                  j                  |f       n| j                  j                  |       | j                  4 d {    | j                  j                          d d d       d {    | j                  5  | j                  j                          d d d        d d d        y 7 6# t        $ r Y @w xY w7 "# t        $ r}|}Y d }~1d }~ww xY w7 7 m# 1 d {  7  sw Y   }xY w# 1 sw Y   ZxY w# 1 sw Y   y xY ww)NF)r  r   )r  rh   r  r	  r  r   r  r  r  notifyr  )r   r  r   r  s       r   _track_futurezas_completed._track_future  sD    	- %~~e~<< YY%V$)$||F+V,$$JJ))66*:;JJ))&1>>>NN))+ *>**))002 + Y   		 =!  *>>>>** Ys   F(E EE F(E EE F(
BF!E7"F%E; FE9FF7F?	F(E 	EF(EF(E 	E4'E/)F(/E44F(7F9F;F	FF		FF	FF%!F(c                   ddl m} | j                  5  |D ]_  }t        |t        |f      st        d|z        | j                  |xx   dz  cc<   | j                  j                  | j                  |       a 	 ddd       y# 1 sw Y   yxY w)zoAdd multiple futures to the collection.

        The added futures will emit from the iterator once they finishr   )BaseActorFuturezInput must be a future, got %sr   N)
distributed.actorr  r  r  r   r,  r   r-  r.  r  )r   r   r  r  s       r   r  zas_completed.update  sn     	6YY!!fo%>?#$Dq$HIIQ1$		&&t'9'91=	  YYs   A%BBc                (    | j                  |f       y)ziAdd a future to the collection

        This future will emit from the iterator once it finishes
        N)r  )r   r  s     r   r/  zas_completed.add  s    
 	VIr   c                $    | j                          S )z7Returns True if there no completed or computing futures)r   r   s    r   is_emptyzas_completed.is_empty  s    ::<r   c                8    | j                   j                          S )z6Returns True if there are completed futures available.)r  emptyr   s    r   	has_readyzas_completed.has_ready  s    ::##%%%r   c                    | j                   5  t        | j                        t        | j                  j                        z   cddd       S # 1 sw Y   yxY w)zReturn the number of futures yet to be returned

        This includes both the number of futures still computing, as well as
        those that are finished, but have not yet been returned from this
        iterator.
        N)r  r   r   r  r   s    r   r   zas_completed.count  s5     YYt||$s4::+;+;'<< YYs   5AAc                    dj                  t        | j                        t        | j                  j                              S )Nz"<as_completed: waiting={} done={}>)r  r   r   r  r   s    r   rK  zas_completed.__repr__  s2    3::s4::#3#34
 	
r   c                    | S r   r   r   s    r   r  zas_completed.__iter__      r   c                    | S r   r   r   s    r   	__aiter__zas_completed.__aiter__  r  r   c                    | j                   j                         }| j                  r7|\  }}| j                  r&|j                  dk(  r|\  }}}|j                  |      |S r  )r  r   r  r  r   r  )r   resr  r   r  r  r  s          r   _get_and_raisezas_completed._get_and_raise  sY    jjnn NFF  V]]g%=%S"((,,
r   c                z   | j                   j                         r| j                  j                  r
t	               | j                         r
t               | j                  5  | j                  j                  d       d d d        | j                   j                         r| j                         S # 1 sw Y   4xY w)Nr  r  )
r  r  r   expiredrl   r  StopIterationr  r  r  r   s    r   __next__zas_completed.__next__$  s    jj ~~%%"n$}}#o%&&%%**5*9 ' jj  ""$$ '&s   !B11B:c                   K   | j                   j                  s| j                          d {   S t        | j                         | j                   j                         d {   S 7 :7 wr   )r   expires_anextr<   	remainingr   s    r   	__anext__zas_completed.__anext__.  sK     ~~%%&&dkkmT^^-E-EFFF 'Fs!   *A+A'5A+"A)#A+)A+c                  K   | j                   s | j                  j                         rt        | j                  j                         rt| j                   st        | j                  4 d {    | j                  j                          d {    d d d       d {    | j                  j                         rt| j                         S 7 a7 A7 3# 1 d {  7  sw Y   CxY wwr   )r   r  r  StopAsyncIterationr  r  r  r   s    r   r  zas_completed._anext3  s     ||

 0 0 2$$jj <<((~~~nn))+++ &~ jj  ""$$ &+ &~~~s`   A)C(+C,C(/CCCC(CC(=C(CC(C%CC%!C(c                    |rt        |       g}ng }| j                  j                         sD|j                  | j                  j	                                | j                  j                         sD|S )aY  Get the next batch of completed futures.

        Parameters
        ----------
        block : bool, optional
            If True then wait until we have some result, otherwise return
            immediately, even with an empty list.  Defaults to True.

        Examples
        --------
        >>> ac = as_completed(futures)  # doctest: +SKIP
        >>> client.gather(ac.next_batch())  # doctest: +SKIP
        [4, 1, 3]

        >>> client.gather(ac.next_batch(block=False))  # doctest: +SKIP
        []

        Returns
        -------
        List of futures or (future, result) tuples
        )r   r  r  r{  r   )r   blockr  s      r   
next_batchzas_completed.next_batch@  sU    , $ZLEE**""$LL)* **""$r   c              #  V   K   	 	 | j                  d       # t        $ r Y yw xY ww)a3  
        Yield all finished futures at once rather than one-by-one

        This returns an iterator of lists of futures or lists of
        (future, result) tuples rather than individual futures or individual
        (future, result) tuples.  It will yield these as soon as possible
        without waiting.

        Examples
        --------
        >>> for batch in as_completed(futures).batches():  # doctest: +SKIP
        ...     results = client.gather(batch)
        ...     print(results)
        [4, 2]
        [1, 3, 7]
        [5]
        [6]
        T)r%  N)r&  r  r   s    r   r  zas_completed.batches^  s9     & ooDo11  ! s   ) )	&)&)c                   | j                   5  | j                  j                          | j                  j	                         s5| j                  j                          | j                  j	                         s5ddd       y# 1 sw Y   yxY w)zClear out all submitted futuresN)r  r   ru  r  r  r   r   s    r   ru  zas_completed.clearw  sS    YYLL jj&&(

  jj&&( YYs   A)B  B	)NNFTrX  )r   r   r   rZ  r   rb  r  r  r  r/  r  r  r   rK  r  r  r  r  r!  r  r   r&  r  ru  r   r   r   r  r  s  s    =B ! !. # #30> &=

%G
	% D<2!r   r  c                     t        d      )NzThis has moved to as_completedr  r  s     r   AsCompletedr*    s    
4
55r   c                <    | xs
 t               } | r| S t        d      )a!  Return a client if one has started

    Parameters
    ----------
    c : Client
        The client to return. If None, the default client is returned.

    Returns
    -------
    c : Client
        The client, if one has started

    See also
    --------
    Client.current (alias)
    zNo clients found
Start a client and point it to the scheduler address
  from distributed import Client
  client = Client('ip-addr-of-scheduler:8786')
)r   r  r   s    r   rH  rH    s,    " 	
!!A?
 	
r   c                    t        |        y)zEnsures the client passed as argument is set as the default

    Parameters
    ----------
    client : Client
        The client
    N)r   r  s    r   ensure_default_clientr-    s     vr   c                    ddl m} t        | |      r || j                  |      S t	        j                  |       }||_        |S )a  Change the dictionary in the collection

    Parameters
    ----------
    c : collection
        The collection
    dsk : dict
        The dictionary

    Returns
    -------
    c : Delayed
        If the collection is a 'Delayed' object the collection is returned
    cc : collection
        If the collection is not a 'Delayed' object a copy of the
        collection with xthe new dictionary is returned

    r   )Delayed)dask.delayedr/  r  r   copyr  )r   r  r/  ccs       r   r  r    s;    & %!Wquuc""YYq\	r   c                   | g}t               }t               }|r'|j                         }t        |      t        t         t        fv r|j                  |       nt        |      t        u r |j                  |j                                nt        |      t        u r*|j                  |j                  j                                nyt        |t              r'||vre|j                  |       |j                  |       nBt        j                  |      r-|j                  |j!                         j                                |r'|t#        t              }|D ]Y  }|j%                         s|j&                  j(                  }t        |t*              sJ ||j,                     j                  |       [ |r8|j/                         D 	
cg c]  \  }	}
t1        |
|	       }}	}
t3        |      |ddd   S c c}
}	w )a  Future objects in a collection

    Parameters
    ----------
    o : collection
        A possibly nested collection of Dask objects
    client : Client, optional
        The client

    Examples
    --------
    >>> futures_of(my_dask_dataframe)
    [<Future: finished key: ...>,
     <Future: pending  key: ...>]

    Raises
    ------
    CancelledError
        If one of the futures is cancelled a CancelledError is raised

    Returns
    -------
    futures : List[Future]
        A list of futures held by those collections
    Nr   )rn  r   r  r   r   ri  r  rg  r+   r  r  rD   r/  r{  r  r  r  r   r  r   r  r   r   r  r   r   )or   stackseenr   r  r  r  r  r   r   r  s               r   rI  rI    s   4 CE5DfG
IIK7uc4((LLO!W_LL$!W((LL(7#}q!$$Q'LL))+2245  &t,A;;=**Ii)=>>>Y--.55i@   '7&<&<&>&>NFF &VFC&>   (//4R4=s   G3c                |    t        |       }|D ],  }|j                  j                  d|j                  gdd       . y)an  Run tasks at least once, even if we release the futures

    Under normal operation Dask will not run any tasks for which there is not
    an active future (this avoids unnecessary work in many situations).
    However sometimes you want to just fire off a task, not track its future,
    and expect it to finish eventually.  You can use this function on a future
    or collection of futures to ask Dask to complete the task even if no active
    client is tracking it.

    The results will not be kept in memory after the task completes (unless
    there is an active future) so this is only useful for tasks that depend on
    side effects.

    Parameters
    ----------
    obj : Future, list, dict, dask collection
        The futures that you want to run at least once

    Examples
    --------
    >>> fire_and_forget(client.submit(func, *args))  # doctest: +SKIP
    r  zfire-and-forgetr  N)rI  r   r  r   )objr   r  s      r   fire_and_forgetr:    s=    . oG((++	
 r   c                  0    e Zd ZdZddZd Zd Zd Zd Zy)	rr  a  
    Collect task stream within a context block

    This provides diagnostic information about every task that was run during
    the time when this block was active.

    This must be used as a context manager.

    Parameters
    ----------
    plot: boolean, str
        If true then also return a Bokeh figure
        If plot == 'save' then save the figure to a file
    filename: str (optional)
        The filename to save to if you set ``plot='save'``

    Examples
    --------
    >>> with get_task_stream() as ts:
    ...     x.compute()
    >>> ts.data
    [...]

    Get back a Bokeh figure and optionally save to a file

    >>> with get_task_stream(plot='save', filename='task-stream.html') as ts:
    ...    x.compute()
    >>> ts.figure
    <Bokeh Figure>

    To share this file with others you may wish to upload and serve it online.
    A common way to do this is to upload the file as a gist, and then serve it
    on https://raw.githack.com ::

       $ python -m pip install gist
       $ gist task-stream.html
       https://gist.github.com/8a5b3c74b10b413f612bb5e250856ceb

    You can then navigate to that site, click the "Raw" button to the right of
    the ``task-stream.html`` file, and then provide that URL to
    https://raw.githack.com .  This process should provide a sharable link that
    others can use to see your task stream plot.

    See Also
    --------
    Client.get_task_stream: Function version of this context manager
    Nc                    g | _         || _        || _        d | _        |xs
 t	               | _        | j
                  j                  dd       y )Nr   r.  r  )r  _plot	_filenamer+  rH  r   rr  )r   r   r  r   s       r   r   zget_task_stream.__init__X  sD    	
!0 0##!!#4r   c                $    t               | _        | S r   )r[   r.  r   s    r   r  zget_task_stream.__enter__`  s    V
r   c                    | j                   j                  | j                  | j                  | j                        }| j                  r
|\  }| _        | j                  j                  |       y N)r.  r  r   r   rr  r.  r>  r?  r+  r  ri  r   r  r  r  r   s        r   r  zget_task_stream.__exit__d  sT    KK''**4:: ( 
 ::NAt{		r   c                   K   | S wr   r   r   s    r   r  zget_task_stream.__aenter__l  s     s   c                   K   | j                   j                  | j                  | j                  | j                         d {   }| j                  r
|\  }| _        | j                  j                  |       y 7 6wrB  rC  rD  s        r   r  zget_task_stream.__aexit__o  sb     ++--**4:: . 
 
 ::NAt{		
s   A A;A97A;)NFr  )	r   r   r   rZ  r   r  r  r  r  r   r   r   rr  rr  '  s!    .`5r   rr  c                  4    e Zd ZdZ	 ddZd Zd	dZd Zd Zy)
performance_reporta  Gather performance report

    This creates a static HTML file that includes many of the same plots of the
    dashboard for later viewing.

    The resulting file uses JavaScript, and so must be viewed with a web
    browser.  Locally we recommend using ``python -m http.server`` or hosting
    the file live online.

    Parameters
    ----------
    filename: str, optional
        The filename to save the performance report locally

    stacklevel: int, optional
        The code execution frame utilized for populating the Calling Code section
        of the report. Defaults to `1` which is the frame calling ``performance_report``

    mode: str, optional
        Mode parameter to pass to :func:`bokeh.io.output.output_file`. Defaults to ``None``.

    storage_options: dict, optional
         Any additional arguments to :func:`fsspec.open` when writing to a URL.

    Examples
    --------
    >>> with performance_report(filename="myfile.html", stacklevel=1):
    ...     x.compute()
    Nc                R    || _         |dkD  r|nd| _        || _        |xs i | _        y )Nr   r   )r   _stacklevelmoder4  )r   r   r<  rK  r4  s        r   r   zperformance_report.__init__  s/     !)3a:Q	.4"r   c                   K   t               | _        t               j                  d        d {   | _        t               j                  dd       d {    y 7 -7 w)Nc                .    | j                   j                  S r   )monitorr   )dask_schedulers    r   r   z/performance_report.__aenter__.<locals>.<lambda>  s    >#9#9#?#?r   r   r=  )r[   r.  ry   rl  
last_countrr  r   s    r   r  zperformance_report.__aenter__  sS     V
 * = =?!
 
 l***;;;
 	<s!   -A!A'A!AA!A!c                  K   dd l }t               }|3|j                  | j                  dz   d      }|r|d   j                  nd}|j
                  j                  | j                  | j                  || j                         d {   } |j                  | j                  fddd| j                  5 }	|	j                  |       d d d        y 7 I# 1 sw Y   y xY ww)	Nr   r   r  <Code not available>)r.  rP  r   rK  rc  infer)rK  compression)fsspecry   r  rJ  r   r  rH  r.  rP  rK  r  r   r4  r  )
r   r  r  r  r   rU  r   r  r  r  s
             r   r  zperformance_report.__aexit__  s     <11$2B2BQ2FPQ1RF%+6!9>>1GD%%88**t$)) 9 
 
 V[[MM
 #
<@<P<P
GGDM
 


 
s*   BCC.C5C
CCCc                J    t               j                  | j                         y r   ry   rr   r  r   s    r   r  zperformance_report.__enter__  s    $//*r   c                    t               }|j                  | j                  dz   d      }|r|d   j                  nd}|j	                  | j
                  ||||       y )Nr   r  r   rR  )r   )ry   r  rJ  r   rr   r  )r   r  r  r  r   r  r   s          r   r  zperformance_report.__exit__  sU    --d.>.>.BA-N!'vay~~-CDNNHiNr   )zdask-report.htmlr   NNr   	r   r   r   rZ  r   r  r  r  r  r   r   r   rH  rH  x  s(    > UY5<+Or   rH  c                  .    e Zd ZdZd Zd Zd Zd Zd Zy)get_task_metadataaw  Collect task metadata within a context block

    This gathers ``TaskState`` metadata and final state from the scheduler
    for tasks which are submitted and finished within the scope of this
    context manager.

    Examples
    --------
    >>> with get_task_metadata() as tasks:
    ...     x.compute()
    >>> tasks.metadata
    {...}
    >>> tasks.state
    {...}
    c                    dt        j                         j                   | _        t	               | _        d | _        d | _        y )Nztask-metadata-)r_  r`  ra  r2  rn  r   r  r   r   s    r   r   zget_task_metadata.__init__  s4    $TZZ\%5%5$67	E	
r   c                ~   K   t               j                  j                  | j                         d {    | S 7 wr  )ry   r  start_task_metadatar2  r   s    r   r  zget_task_metadata.__aenter__  s4     l$$88dii8HHH 	Is   2=;=c                   K   t               j                  j                  | j                         d {   }|d   | _        |d   | _        y 7 w)Nr  r  r   )ry   r  stop_task_metadatar2  r  r   )r   r  r  r  r*  s        r   r  zget_task_metadata.__aexit__  sF     #//BB		BRR ,g&
 Ss   2AAAc                H    t               j                  | j                        S r   rW  r   s    r   r  zget_task_metadata.__enter__  s    |  11r   c                N    t               j                  | j                  |||      S r   )ry   rr   r  )r   r  r  r  s       r   r  zget_task_metadata.__exit__  s    |  9iPPr   NrY  r   r   r   r[  r[    s!     '
2Qr   r[  c              #     K   t               }t        |        	 | j                         5  d ddd       t        |       y# 1 sw Y   xY w# t        |       w xY ww)a  Set the default client for the duration of the context

    .. note::
       This function should be used exclusively for unit testing the default
       client functionality. In all other cases, please use
       ``Client.as_current`` instead.

    .. note::
       Unlike ``Client.as_current``, this context manager is neither
       thread-local nor task-local.

    Parameters
    ----------
    c : Client
        This is what default_client() will return within the with-block.
    N)rH  r   rF  )r   old_execs     r   temp_default_clientre    sJ     $ Hq%\\^  	8$ ^ 	8$s1   AA AA AAA AAc                 
   t               } | kd| _        t        t        t              5  | j
                  r(| j                  j                  | j                  d       n| j                  d       ddd       yy# 1 sw Y   yxY w)z}
    Force close of global client.  This cleans up when a client
    wasn't close explicitly, e.g. interactive sessions.
    NF   r  )	r   _should_close_loopr   rl   r   r  r-  r.  r  r   s    r   _close_global_clientri    sg    
 	A}$lL1~~##AGGQ#7"	 21 11s   AA99Bc                0    dt        |       j                  iS )Nr   )r   r   )r  s    r   r  r    s    Z )) r   )r   Client | None)r   rk  r   r  )r   r   r   r  )r   r.   r   rB   r   )
__future__r   ri  atexitr1  r  r^  r  r  r*  r  r  r\  r
  r  r_  r  r  r  r   collections.abcr   r   r   r	   r
   concurrent.futuresr   concurrent.futures._baser   
contextlibr   r   r   contextvarsr   	functoolsr   r   importlib.metadatar   r   numbersr   r  r   r  typingr   r   r   r   r   r   r   r   packaging.versionr   rn  tlzr    r!   r"   r#   r$   r  	dask.baser&   	dask.corer'   r(   dask.highlevelgraphr)   dask.layersr*   dask.optimizationr+   dask.tokenizer,   dask.typingr-   r.   r/   r0   
dask.utilsr1   r2   r3   r4   r5   r6   r7   dask.widgetsr8   distributed.corer9   r  r:   distributed.utilsr;   r<   r0  r=   r  tornador>   tornado.ioloopr?   dask._task_specr@   rA   rB   rC   rD   rE   r  rF   rG   rH   r  distributed.batchedrI   distributed.cfexecutorrK   distributed.compatibilityrL   rM   rN   rO   rP   rQ   rR   rS   distributed.diagnostics.pluginrT   rU   rV   rW   rX   rY   rZ   distributed.metricsr[   distributed.objectsr\   r]   r^   r  r_   distributed.protocol.pickler`   ra   distributed.publishrb   distributed.pubsubrc   distributed.securityrd   distributed.sizeofre   distributed.spansrf   distributed.threadpoolexecutorrg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   distributed.utils_commrt   ru   rv   rw   rx   distributed.workerry   rz   r{   typing_extensionsr|   r  r   r$  WeakValueDictionaryr}   r   r   r~   r  r  r   r   r   r   r   r   r   r   r   r/  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r*  rH  r-  r  rI  r:  rr  rH  r[  re  ri  r  r  r   r   r   <module>r     sO   "        	  	 
      # O O 1 : D D " 3 <  "	 	 	 5 < <  ( + .  . " > >   & & 7 0'  ! Q Q  0 2 + 1 6     % > > - 4 ( 4 ) % * 1     > =+			8	$  G! 9  s -78ISW-X* X #  %; !A> A(
N 
 
 
: %uW up`= `=F9i 9@
2&9 & #3	>2 ) 2o odyH:_ yH:xQ
! 
!O  # !m (1V } .  	I! I!X6
:::z
DN NbEO EOP$Q $QN % %4# $ %gF  Js   M" "M-,M-