
    wi*                        d Z ddlmZ ddlZddlZddlZddlmZmZ 	 ddl	Z	dZ
n# e$ r dZ
Y nw xY we
Zdd	ZddZ G d d          ZdS )a  
Memory monitoring utilities for measuring memory usage.

Example usage:
    tracker = MemoryTracker("my_function")
    with tracker.monitor():
        my_function()
    # Access data: tracker.rss_delta, tracker.duration, etc.
    # Get formatted string: tracker.get_summary()
    )annotationsN)DictOptionalTFreturnOptional[int]c                 j    t           r+	 t          j                    } | j        S # t          $ r Y nw xY wdS )z
    Get current available system memory in bytes.

    Used for memory threshold checking in parallel test execution.

    Returns:
        int or None: Available memory in bytes, or None if unavailable
    N)_HAS_PSUTILpsutilvirtual_memory	available	Exception)sys_mems    f/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/numba/misc/memoryutils.pyget_available_memoryr      sO      	+--G$$ 	 	 	D	 4s   # 
00Dict[str, Optional[int]]c                 B   i } t           r	 t          j        t          j                              }|                                }|j        | d<   t          j                    }|j        | d<   n!# t          j	        t          j
        f$ r Y nw xY wd| vrd| d<   d| vrd| d<   | S )a^  
    Get memory usage information needed for monitoring.

    Returns only RSS and available memory which are the fields
    actually used by the MemoryTracker.

    Returns:
        dict: Memory usage information including:
            - rss: Current process RSS (physical memory currently used)
            - available: Available system memory
    rssr   N)r	   r
   Processosgetpidmemory_infor   r   r   NoSuchProcessAccessDenied)r   processmem_infor   s       r   get_memory_usager   /   s     K 	nRY[[11G**,,H!)K +--G'.'8K$$$f&9: 	 	 	D	 K!E+%%#'K s   A A, ,B
	B
c                      e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   d	ed<   ded<   ded<   ddZej        d             ZddZ	dS )MemoryTrackerz
    A simple memory monitor that tracks RSS delta and timing.

    Stores monitoring data in instance attributes for later access.
    Each instance is typically used for monitoring a single operation.
    intpidstrnamezfloat | None
start_timeend_timezDict[str, int | None] | Nonestart_memory
end_memorydurationz
int | None	rss_deltac                    t          j                    | _        || _        d| _        d| _        d| _        d| _        d| _        d| _	        dS )z6Initialize a MemoryTracker with empty monitoring data.N)
r   r   r    r"   r#   r$   r%   r&   r'   r(   )selfr"   s     r   __init__zMemoryTracker.__init__d   sE    9;;	     c              #    K   t          j                     | _        t                      | _        	 | V  t          j                     | _        t                      | _        | j        | j        z
  | _        | j                            dd          }| j                            dd          }|r|r||z
  nd| _        dS # t          j                     | _        t                      | _        | j        | j        z
  | _        | j                            dd          }| j                            dd          }|r|r||z
  nd| _        w xY w)a  
        Context manager to monitor memory usage during function execution.

        Records start/end memory usage and timing, calculates RSS delta,
        and stores all data in instance attributes.

        Args:
            name (str): Name/identifier for the function or operation being
                        monitored

        Yields:
            self: The MemoryTracker instance for accessing stored data
        r   r   N)	timer#   r   r%   r$   r&   r'   getr(   )r*   	start_rssend_rsss      r   monitorzMemoryTracker.monitoro   sL       )++,..	?JJJ !IKKDM.00DO MDO;DM )--eQ77Io))%33G!*>/6>w22<= NNN !IKKDM.00DO MDO;DM )--eQ77Io))%33G!*>/6>w22<= N ? ? ? ?s   B: :BEr   c                "   | j         | j        t          d          | j                            d          }dd}t	          j        dt	          j        | j                            }| j                             dd          }| j                            dd          }d	| j         d
| j	         d| d| j
        ddd ||           d ||           d || j        d           d ||           g}d                    |          S )a  
        Return a formatted summary of the memory monitoring data.

        Formats the stored monitoring data into a human-readable string
        containing name, PID, RSS delta, available memory, duration,
        and start time.

        Returns:
            str: Formatted summary string with monitoring results

        Note:
            Should be called after monitor() context has completed
            to ensure all data is available.
        Nz$Memory monitoring data not availabler   Fc                    | dS | dk    rdS d}|r
| dk     rdnd}t          |           } dD ]}| d	k     r| | d
d| c S | d	z  } | | d
dS )z&Convert bytes to human readable formatNzN/Ar   z0 B -+)BKBMBGBg      @z.2f z TB)abs)	bytes_val	show_signsignunits       r   format_bytesz/MemoryTracker.get_summary.<locals>.format_bytes   s     uA~~uD 5'!mmssII/ $ $v%%":I:::D:::::V#		.I.....r,   z%H:%M:%Sr   r   zName: zPID: zStart: z
Duration: z.3fszStart RSS: z	End RSS: zRSS delta: T)r?   zAvail memory: z | )F)r%   r&   
ValueErrorr/   r.   strftime	localtimer#   r"   r    r'   r(   join)r*   current_availablerB   start_tsr0   r1   bufs          r   get_summaryzMemoryTracker.get_summary   sJ    $(?CDDD O//<<	/ 	/ 	/ 	/$ =T^DO-L-LMM%))%33	/%%eQ// !TY  DH h  -----3,,y1133/W--//H,,t~FFFHH>\\*;<<>>	
 zz#r,   N)r"   r!   )r   r!   )
__name__
__module____qualname____doc____annotations__r+   
contextlibcontextmanagerr2   rK    r,   r   r   r   T   s           HHHIII....,,,,	 	 	 	 ? ? ?@4 4 4 4 4 4r,   r   )r   r   )r   r   )rO   
__future__r   r   rQ   r.   typingr   r   r
   r	   ImportErrorIS_SUPPORTEDr   r   r   rS   r,   r   <module>rX      s   	 	 # " " " " " 				      ! ! ! ! ! ! ! !MMMKK   KKK    &" " " "Jp p p p p p p p p ps   % //