
    pi*                        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
e
ZddZddZ G d	 d
      Zy# e$ r dZ
Y w xY w)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OptionalTFc                 p    t         r!	 t        j                         } | j                  S y# t        $ r Y yw xY w)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    X/opt/services/ai/voice_agent/venv/lib/python3.12/site-packages/numba/misc/memoryutils.pyget_available_memoryr      sB     	++-G$$$   		s   ) 	55c                 `   i } t         rj	 t        j                  t        j                               }|j                         }|j                  | d<   t        j                         }|j                  | d<   d| vrd| d<   d| vrd| d<   | S # t        j                  t        j                  f$ r Y 9w xY w)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	nnRYY[1G**,H!)K ++-G'.'8'8K$ K!E+%#'K  $$f&9&9: 		s   A)B #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	y)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| _	        y)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   sA    99;	     c              #    K   t        j                          | _        t               | _        	 |  t        j                          | _        t               | _        | j                  | j                  z
  | _        | j                  j                  dd      }| j
                  j                  dd      }|r|r||z
  | _        yd| _        y# t        j                          | _        t               | _        | j                  | j                  z
  | _        | j                  j                  dd      }| j
                  j                  dd      }|r|r||z
  | _        w d| _        w xY w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   s      ))+,.	?J !IIKDM.0DO MMDOO;DM ))--eQ7Ioo))%3G!*w  '2DN<= N !IIKDM.0DO MMDOO;DM ))--eQ7Ioo))%3G!*w  '2DN<= Ns   )EC BEBEEc                J   | j                   | j                  t        d      | j                  j                  d      }dd}t	        j
                  dt	        j                  | j                              }| j                   j                  dd      }| j                  j                  dd      }d| j                   d| j                   d	| d
| j                  ddd ||       d ||       d || j                  d       d ||       g}dj                  |      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.
        z$Memory monitoring data not availabler
   c                    | y| dk(  ry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 formatz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     A~D'!msII/ $v%"VIc?!D6::V#	$ VIc?#..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_availabler?   start_tsr-   r.   bufs          r   get_summaryzMemoryTracker.get_summary   s%    $(?CDD OO//<	/$ ==T^^DOO-LM%%))%3	//%%eQ/ TYYK DHH:hZ s+1-,y123W-./,t~~FGH\*;<=>	
 zz#r)   N)r   r   )returnr   )
__name__
__module____qualname____doc____annotations__r(   
contextlibcontextmanagerr/   rH    r)   r   r   r   T   s\     
H
I..,,	 ? ?@4r)   r   )rI   zOptional[int])rI   zDict[str, Optional[int]])rM   
__future__r   r   rO   r+   typingr   r   r   r   ImportErrorIS_SUPPORTEDr   r   r   rQ   r)   r   <module>rV      s]   	 # 	   !K
 &"Jp p  Ks   9 AA