
    ԋgB                       d Z 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m	Z	m
Z
 ddlmZmZ ddlmZ ddlmZ ddlmZ ddlZddl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   ejB                         Z"d"dZ#d#dZ$d$dZ%d%dZ&dddd	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ'd'dZ(d(dZ)d)dZ*d*dZ+	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+dZ,dddedd f	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZ-d-dZ.d Z/d Z0	 	 	 	 	 	 d.d Z1d! Z2y)/a,   This module contains utility functions to construct and manipulate counting
data structures for frames.

When performing statistical profiling we obtain many call stacks.  We aggregate
these call stacks into data structures that maintain counts of how many times
each function in that call stack has been called.  Because these stacks will
overlap this aggregation counting structure forms a tree, such as is commonly
visualized by profiling tools.

We represent this tree as a nested dictionary with the following form:

    {
     'identifier': 'root',
     'description': 'A long description of the line of code being run.',
     'count': 10  # the number of times we have seen this line
     'children': {  # callers of this line. Recursive dicts
         'ident-b': {'description': ...
                   'identifier': 'ident-a',
                   'count': ...
                   'children': {...}},
         'ident-b': {'description': ...
                   'identifier': 'ident-b',
                   'count': ...
                   'children': {...}}}
    }
    )annotationsN)defaultdictdeque)Callable
Collection)sleep)	FrameType)Any)	NoDefault
no_default)format_timeparse_timedelta)time)color_ofc                T   | y| j                   }	 dj                  |j                  |j                  t	        |j
                        f      S # t        $ rR |j                  r)|j                   d|j                   dt        |        cY S |j                   dt        |        cY S w xY w)zpA string identifier from a frame

    Strings are cheaper to use as indexes into dicts than tuples or dicts
    None;.:)
f_codejoinco_nameco_filenamestrco_firstlinenoAttributeError
__module____qualname__	_f_lineno)framecos     3lib/python3.12/site-packages/distributed/profile.py
identifierr#   6   s    
 }\\	?88JJNN))*   	?}}--"//):!Ie<L;MNN//*!Ie,<+=>>		?s   :A <B'
B'&B'c                    | j                   }||S | j                  }| j                  }	 |j                  }t	        j
                  |      D ]  \  }}||k  r|c S |s|} |S # t        $ r Y yw xY w)z\Work around some frames lacking an f_lineno
    See: https://bugs.python.org/issue47085
    )f_linenof_lastir   r   disfindlinestarts	Exception)r    r&   r'   code	prev_linestart	next_lines          r"   r   r   N   s     ~~HmmG<<D''	 # 2 24 8E9  %		 !9  s   /A# A# A# #	A/.A/c                    | j                   }t        |       }d|j                   d| d|j                   }t	        j
                  |j                  || j                        j                         }|dz   |z   S )z<Render a frame as a line for inclusion into a text tracebackz  File "z", line z, in z
	)r   r   r   r   	linecachegetline	f_globalslstrip)r    r!   r&   textlines        r"   
repr_framer6   f   sj    	BHbnn%XhZuRZZLIDR^^XuGNNPD&=4    c                ,   | j                   }t        |       }	 |j                  }|j                  }t	        j
                  |j                  || j                        j                         }||||dS # t        t        f$ r d}|j                  }d}Y (w xY w)N z
<built-in>filenamenameline_numberr5   )r   r   r   r   r0   r1   r2   r3   r   
IndexErrorr   )r    r!   r&   r<   r;   r5   s         r"   
info_framer?   o   s    	BH zz>>  5??KRRT 	 	 J'   s   AA1 1BB )stopomitdepthc                   |!t        dt        j                         dz        }t         fd|D              ry j                  }|dkD  rA|?|%|j
                  j                  j                  |      st        | |||dz
        }|y|}t               }	 |d   |   }	|d
xx   dz  cc<   ||	S |	d
xx   dz  cc<   y# t        $ r dt               i |d	}	|	|d   |<   Y Bw xY w)a  Add counts from a frame stack onto existing state

    This recursively adds counts to the existing state dictionary and creates
    new entries for new functions.

    Parameters
    ----------
    frame:
        The frame to process onto the state
    child:
        For internal use only
    state:
        The profile state to accumulate this frame onto, see ``create``
    stop:
        Filename suffix that should stop processing if we encounter it
    omit:
        Filenames that we should omit from processing
    depth:
        For internal use only, how deep we are in the call stack
        Used to prevent stack overflow

    Examples
    --------
    >>> import sys, threading
    >>> ident = threading.get_ident()  # replace with your thread of interest
    >>> frame = sys._current_frames()[ident]
    >>> state = create()
    >>> process(frame, None, state)
    >>> state
    {'count': 1,
     'identifier': 'root',
     'description': 'root',
     'children': {'...'}}

    See also
    --------
    create
    merge
    Nd      c              3  h   K   | ])  }j                   j                  j                  |       + y wN)r   r   endswith).0or    s     r"   	<genexpr>zprocess.<locals>.<genexpr>   s'     
>A5<<##,,Q/s   /2r      )rA   rC   childrencountdescriptionrN   r#   rP   )minsysgetrecursionlimitanyf_backr   r   rI   processr#   KeyErrorr?   )
r    childstaterA   rB   rC   prev	new_stateidentds
   `         r"   rW   rW      s   ` }
 C..0A56

>
>><<D	\!8!8!A!A$!GD%TK	uE	%*e$ 
'NaN	'
a
  %%e,	
 $%j% %s   B? ?!C#"C#c                    | s
t               S | D ch c]  }|d   	 }}t        |      dk7  rt        d|       t        t              }| D ]&  }|d   D ]  }||   j                  |d   |           ( 	 |j                         D ci c]  \  }}|t        |  }}}t        d | D              }| d   d   ||| d   d   dS c c}w c c}}w # t        $ r i }Y =w xY w)	z$Merge multiple frame states togetherr#   rM   zExpected identifiers, got rN   c              3  &   K   | ]	  }|d      yw)rP   Nr@   )rJ   args     r"   rL   zmerge.<locals>.<genexpr>   s     -Gs   r   rQ   )rQ   rN   rP   r#   )
createlen
ValueErrorr   listappenditemsmergeRecursionErrorsum)	argsra   srN   rY   kvchildren_dictrP   s	            r"   rh   rh      s   x&*+ds\	dA+
1v{5aS9::4 H_EUO""3z?5#9: % 2:..2BC2B$!QE1I2BC ---EAw}-!1gl+	  	, D s)   C6C 	C	C 	C CCc                     di dddddddS )Nr   rootr9   r:   )rP   rN   r#   rQ   r@   r@   r7   r"   rb   rb      s!    $&1bQ	 r7   c                p    g }| }|r)|j                  t        |             |j                  }|r)|ddd   S )zWCreate a call text stack from a frame

    Returns
    -------
    list of strings
    Nr%   )rf   r6   rV   )r    L	cur_frames      r"   
call_stackru      sA     	A"'I
	I&'$$	  TrT7Nr7   c                  	
 g g g g g g g g g 	g g 
	
fd | ddd       D cg c]  }d|z  dd }}D cg c]  }|dz   	 c}	
|dS c c}w c c}w )zConvert a profile state into data useful by Bokeh

    See Also
    --------
    plot_figure
    distributed.bokeh.components.ProfilePlot
    c                   | d   sy j                  |       j                  |       j                  |       ||z
  }j                  |       j                  |        j                  t        | d   z               | d   }j                  |d          j                  |d          j                  |d          j                  |d          	 |d   }|dk(  rj                  d       nj                  t        |             	 ||z
  | d   z  }|}| d
   j	                         D ]#  \  }	}
|
d   |z  } |
|||z   |dz          ||z  }% y # t        $ r j                  d	       Y cw xY w)NrP   rQ   r;   r5   r=   r<   <low-level>	lightgraygrayrN   rM   )rf   r   r   r>   rg   )rZ   r-   rA   heightwidthdescfndeltax_rY   colors	filenamesheightsline_numberslinesnamesprofile_intervalstartsstatesstopstimestraversewidthss              r"   r   zplot_data.<locals>.traverse#  so   W~eTvuee[w2B!BCD]#j)*T&\"D/0T&\"	,j!B ]"k*hrl+w/j)//1HAu'NU*EUAq5y&1*5JA 2  	"MM&!	"s   E E32E3r   rM   rE   z.1f%)leftrightbottomr|   topcolorr   r;   r5   r=   r<   r   
percentager@   )rZ   r   wpercentagesr   r   r   r   r   r   r   r   r   r   r   r   r   s    `   @@@@@@@@@@@@r"   	plot_datar     s     FEGFFFEIELE" " "H UAq!.45fcAgc]!$fK5&'w!Aw'#!  6 (s   A7A<c                   t               }t               } |       st               ||z   kD  rft               }t        5  |j                  t               |f       t               }	 t	        j
                         |    }t        |d ||       ~d d d        t        |        |       sy y # t        $ r Y d d d        y w xY w# 1 sw Y   5xY w)N)rB   )	rb   r   lockrf   rS   _current_framesrX   rW   r   )		thread_idlogintervalcyclerB   rA   recentlastr    s	            r"   _watchr   Z  s     XF6Df6D5L XF

DFF+,v//1)<E tV$7  	h f    
 s/   &B>#B':B>'	B;0B>:B;;B>>C20ms2sc                      y)NFr@   r@   r7   r"   <lambda>r   {  s    ur7   c                X   |t         u r3t        j                  j                  d      }t	        |t
              s|J t        |      }t        j                  t        d| xs t        j                         t        |      t        |      |||d      }d|_        |j                          |S )aF  Gather profile information on a particular thread

    This starts a new thread to watch a particular thread and returns a deque
    that holds periodic profile information.

    Parameters
    ----------
    thread_id : int, optional
        Defaults to current thread
    interval : str
        Time per sample
    cycle : str
        Time per refreshing to a new profile state
    maxlen : int
        Passed onto deque, maximum number of periods
    omit : collection of str
        Don't include entries whose filename includes any of these substrings
    stop : callable
        Function to call to see if we should stop. It must
        accept no arguments and return a bool (True to stop,
        False to continue).

    Returns
    -------
    deque of tuples:

    - timestamp
    - dict[str, Any] (output of ``create()``)
    z&distributed.admin.low-level-log-length)maxlenProfile)r   r   r   r   rB   rA   )targetr<   kwargsT)r   daskconfigget
isinstanceintr   	threadingThreadr   	get_identr   daemonr-   )r   r   r   r   rB   rA   r   threads           r"   watchr   u  s    J !IJ&#&&.88/4F/CC";i&9&9&;'1$U+
F FM
LLNJr7   c                   |d}nt        j                  | |f      }|d}n*t        j                  | |f      dz   }|t        |       k\  rd}|dk(  r|t	        |       } n+|t        |       n|}t        ||      D cg c]  }| |   	 } }t        t        j                  d|        }	| s
t               S |rt        |	|      }	|	S c c}w )a  Collect profile information from a sequence of profile states

    Parameters
    ----------
    history : Sequence[Tuple[time, Dict]]
        A list or deque of profile states
    recent : dict
        The most recent accumulating state
    start : time
    stop : time
    Nr   rM   )
bisectbisect_leftbisect_rightrc   re   rangerh   toolzpluckrb   )
historyr   r-   rA   keyistartistopiistopiprofs
             r"   get_profiler     s     }##GeX6|##GdW59CL E{u}w-!&WE',VV'<='<!71:'<=%++a)*DxT6"K >s   <Cc           
     j   ddl m} ddlm}m} d| v rt        j                  | d      }  ||       } |dddi|}|j                  dd	d
dddd|      }d|_        d|_	         |dd      }|j                  |       d|j                  _        d|j                  _        d|j                  _        ||fS )zPlot profile data using Bokeh

    This takes the output from the function ``plot_data`` and produces a Bokeh
    figure

    See Also
    --------
    plot_data
    r   )	HoverTool)ColumnDataSourcefigurer   )datatoolsztap,box_zoom,xwheel_zoom,resetr   r   r   r   r   black   )r   
line_color
line_widthsourceNfollow_mousea3  
            <div>
                <span style="font-size: 14px; font-weight: bold;">Name:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Filename:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@filename</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Line number:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@line_number</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Line:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@line</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Time:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@time</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Percentage:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@percentage</span>
            </div>
            )point_policytooltipsFr@   )bokeh.modelsr   bokeh.plottingr   r   r   dissocquadselection_glyphnonselection_glyph	add_toolsxaxisvisibleyaxisgrid)	r   r   r   r   r   r   figrhovers	            r"   plot_figurer     s     '74||D(+4(F

B7
B6
BC 	 		A AA#E: MM%CIICIICHH;r7   c              #  >   K   | D ]  }|j                   r y |  y wrH   )	is_python)framesentrys     r"   _remove_py_stackr   !  s     ?? s   c                   | sy| j                         }| rt        | ||      }|sJ t        |j                  |j                  z
        }dj                  t        t        |j                  d|f            }	 |d   |   }|dxx   d	z  cc<   ||S |dxx   d	z  cc<   y# t        $ r* dd|j                  dt        |      di |d}||d   |<   Y Qw xY w)
aU  Add counts from low level profile information onto existing state

    This uses the ``stacktrace`` module to collect low level stack trace
    information and place it onto the given state.

    It is configured with the ``distributed.worker.profile.low-level`` config
    entry.

    See Also
    --------
    process
    ll_get_stack
    Nr   rx   rN   r   r:   rO   rP   rM   )
pop	llprocesshexaddroffsetr   mapr   r<   rX   )r   rY   rZ   r    r   r]   r^   s          r"   r   r   (  s    $ JJLE&%/L5uzzELL()DHHSuzz=$?@AE%*e$ 
'NaN	'
a
)  %)

 E
	 

 $%j% %s   6B 0CCc                Z    ddl m}  || d      }t        t        |            ddd   }|S )z2Collect low level stack information from thread idr   )get_thread_stackF)show_pythonNr%   )
stacktracer   re   r   )tidr   r   llframess       r"   ll_get_stackr   \  s/    +cu5F$V,-dd3HOr7   )r    zFrameType | Nonereturnr   )r    r	   r   r   )r    r	   r   r   )r    r	   r   dict[str, Any])r    r	   rY   object | NonerZ   r   rA   z
str | NonerB   Collection[str]rC   
int | Noner   dict[str, Any] | None)rk   r   r   r   )r   r   )r    r	   r   z	list[str])g{Gz?)r   r   r   #deque[tuple[float, dict[str, Any]]]r   floatr   r   rB   r   rA   Callable[[], bool]r   r   )r   r   r   r   r   r   r   zint | None | NoDefaultrB   r   rA   r   r   r   )NNNN)rY   r   rZ   r   r   r   )3__doc__
__future__r   r   r(   r0   rS   r   collectionsr   r   collections.abcr   r   r   r   typesr	   typingr
   tlzr   dask.configr   dask.typingr   r   
dask.utilsr   r   distributed.metricsdistributed.utilsr   Lockr   r#   r   r6   r?   rW   rh   rb   ru   r   r   r   r   r   r   r   r   r@   r7   r"   <module>r     s  6 #  
  
  * 0      - 3 $ & y~~?00 0 XXX X
 X X X Xv2IX	,  	
   
8 !%/,999 9 #	9
 9 9 )9x&RDN11 !1 	1hr7   