
    %`i*                        d 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 ddlmZ ddlmZmZmZmZmZmZmZ ddlZddlmc mc mZ ddlZddlmZ  ej        d           G d	 d
                      Z  ej        d           G d d                      Z!d
dgZ"	 	 	 d,dede#f         de$de$de#def
dZ%	 	 d-dede	e#         f         de$de$defdZ&e	 	 d.de'de(dee(         fd            Z) G d de          Z*dee(         fd Z+dee(e(f         fd!Z,dd"d#eg df         d$e*d%eee(                  d&eee(e(f                  fd'Z- G d( d)          Z.d* Z/d+ Z0dS )/a  Test utilities for Ray.

This module contains test utility classes that are distributed with the Ray package
and can be used by external libraries and tests. These utilities must remain in
_common/ (not in tests/) to be accessible in the Ray package distribution.
    N)	Awaitable)contextmanager)Enum)AnyCallableDictIteratorListOptionalSet)build_address)num_cpusc                   @    e Zd ZdZd ZddefdZddefdZd	efd
Z	dS )SignalActorzA Ray actor for coordinating test execution through signals.

    Useful for testing async coordination, waiting for specific states,
    and synchronizing multiple actors or tasks in tests.
    c                 D    t          j                    | _        d| _        d S )Nr   )asyncioEventready_eventnum_waitersselfs    j/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_common/test_utils.py__init__zSignalActor.__init__"   s    "=??    Fclearc                 r    | j                                          |r| j                                          d S d S N)r   setr   )r   r   s     r   sendzSignalActor.send&   sD     	%""$$$$$	% 	%r   Tshould_waitc                    K   |rA| xj         dz  c_         | j                                         d {V  | xj         dz  c_         d S d S )N   )r   r   wait)r   r    s     r   r#   zSignalActor.wait+   sm       	"!"'')))))))))!	" 	"r   returnc                    K   | j         S r   )r   r   s    r   cur_num_waiterszSignalActor.cur_num_waiters1   s      r   N)F)T)
__name__
__module____qualname____doc__r   boolr   r#   intr&    r   r   r   r      s           % %$ % % % %
" "d " " " " s            r   r   c                   8    e Zd ZdZd
defdZd Zd ZdefdZ	d	S )	SemaphorezA Ray actor implementing a semaphore for test coordination.

    Useful for testing resource limiting, concurrency control,
    and coordination between multiple actors or tasks.
    r"   valuec                 :    t          j        |          | _        d S )N)r0   )r   r/   _sema)r   r0   s     r   r   zSemaphore.__init__=   s    &U333


r   c                 H   K   | j                                          d {V  d S r   )r2   acquirer   s    r   r4   zSemaphore.acquire@   s2      j  """""""""""r   c                 <   K   | j                                          d S r   )r2   releaser   s    r   r6   zSemaphore.releaseC   s       
r   r$   c                 8   K   | j                                         S r   )r2   lockedr   s    r   r8   zSemaphore.lockedF   s      z  """r   N)r"   )
r'   r(   r)   r*   r,   r   r4   r6   r+   r8   r-   r   r   r/   r/   5   sw         4 4c 4 4 4 4# # #  #d # # # # # #r   r/   
   d   Fcondition_predictor.timeoutretry_interval_msraise_exceptionskwargsc                    t          j                     }d}t          j                     |z
  |k    r	  | di |rdS nH# t          $ r; |r t          j        j                            t          j                              }Y nw xY wt          j        |dz             t          j                     |z
  |k    d}||d| z  }t          |          )ah  Wait until a condition is met or time out with an exception.

    Args:
        condition_predictor: A function that predicts the condition.
        timeout: Maximum timeout in seconds.
        retry_interval_ms: Retry interval in milliseconds.
        raise_exceptions: If true, exceptions that occur while executing
            condition_predictor won't be caught and instead will be raised.
        **kwargs: Arguments to pass to the condition_predictor.

    Returns:
        None: Returns when the condition is met.

    Raises:
        RuntimeError: If the condition is not met before the timeout expires.
    N     @@4The condition wasn't met before the timeout expired. Last exception: r-   )
time	Exceptionray_privateutilsformat_error_message	traceback
format_excsleepRuntimeError)r;   r<   r=   r>   r?   startlast_exmessages           r   wait_for_conditionrQ   M   s   . IKKEG
)++

(
(	V"",,V,,  	V 	V 	V l(==i>R>T>TUUGGG	V 	
$v-... )++

(
( EG0w000
w

s   < AB Bc                   K   t          j                     }d}t          j                     |z
  |k    r	 t          j        |           r | di | d{V rdS n
 | di |rdS n# t          $ r}|}Y d}~nd}~ww xY wt	          j        |dz             d{V  t          j                     |z
  |k    d}||d| z  }t          |          )a  Wait until a condition is met or time out with an exception.

    Args:
        condition_predictor: A function that predicts the condition.
        timeout: Maximum timeout in seconds.
        retry_interval_ms: Retry interval in milliseconds.
        **kwargs: Arguments to pass to the condition_predictor.

    Returns:
        None: Returns when the condition is met.

    Raises:
        RuntimeError: If the condition is not met before the timeout expires.
    NrA   rB   rC   r-   )rD   inspectiscoroutinefunctionrE   r   rL   rM   )r;   r<   r=   r?   rN   rO   exrP   s           r   async_wait_for_conditionrV   u   s:     ( IKKEG
)++

(
(	*+>?? ,,66v66666666 F '&0000 F 	 	 	GGGGGG	m-6777777777 )++

(
( EG0w000
w

s   "A# 	A# #
A9-A44A9  	us-west-2portregionr$   c              #     K   ddl m} t          j        }dt          j        d<   dt          j        d<   dt          j        d<   dt          j        d<   dt	          d	|            } || 
          }|                                 dt          j                    j         d| d| }|V  |	                                 |t          _        dS )zContext manager that simulates an S3 bucket and yields the URI.

    Args:
        port: The port of the localhost endpoint where S3 is being served.
        region: The S3 region.

    Yields:
        str: URI for the simulated S3 bucket.
    r   )ThreadedMotoServertestingAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SECURITY_TOKENAWS_SESSION_TOKENzhttp://	localhost)rY   zs3://z?region=z&endpoint_override=N)
moto.serverr\   osenvironr   rN   uuiduuid4hexstop)rY   rZ   r\   old_env	s3_serverserverurls          r   simulate_s3_bucketrn      s       /.....jG&/BJ"#*3BJ&''0BJ#$&/BJ"#<-T::<<IT***F
LLNNN
R$*,,"
R
RF
R
Ry
R
RC
III
KKMMMBJJJr   c                       e Zd ZdZdZdZdS )TelemetryCallsitedriveractortaskN)r'   r(   r)   DRIVERACTORTASKr-   r   r   rp   rp      s        FEDDDr   rp   c                      t          t          j        t          j        j                                                            S r   )r   ray_usage_libget_library_usages_to_reportrF   experimentalinternal_kvinternal_kv_get_gcs_clientr-   r   r   _get_library_usagesr}      s9    2(CCEE	
 	
  r   c                  l    t          j        t          j        j                                                  S r   )rx   get_extra_usage_tags_to_reportrF   rz   r{   r|   r-   r   r   _get_extra_usage_tagsr      s,    7$??AA  r   )expected_extra_usage_tags
use_lib_fncallsiteexpected_library_usagesr   c                    t          t                                dk    sJ t                                  |t          j        k    r               n|t          j        k    rat
          j         G  fdd                      }|                                }t          j        |j                                                   n[|t          j	        k    r>t
          j         fd            }t          j        |                                           nJ d|             t                      }t                      ||v s
J |            |r7t          fd|                                D                       sJ             dS dS )	a  Helper for writing tests to validate library usage telemetry.

    `use_lib_fn` is a callable that will be called from the provided callsite.
    After calling it, the telemetry data to export will be validated against
    expected_library_usages and expected_extra_usage_tags.
    r   c                       e Zd Z fdZdS )(check_library_usage_telemetry.<locals>.Ac                                   d S r   r-   )r   r   s    r   r   z1check_library_usage_telemetry.<locals>.A.__init__   s    
r   N)r'   r(   r)   r   r   s   r   Ar      s.              r   r   c                                     d S r   r-   r   s   r   fz(check_library_usage_telemetry.<locals>.f   s    JLLLLLr   FzUnrecognized callsite: c                 .    g | ]\  }}|         |k    S r-   r-   ).0kvextra_usage_tagss      r   
<listcomp>z1check_library_usage_telemetry.<locals>.<listcomp>   s(    TTT$!Qa A%TTTr   N)lenr}   rp   rt   ru   rF   remoteget__ray_ready__rv   r   allitems)	r   r   r   r   r   ar   library_usagesr   s	   `       @r   check_library_usage_telemetryr      s    "$$%%***,?,A,A***$+++
	&,	,	,		 	 	 	 	 	 	 	 	 
	 HHJJ&&(())))	&+	+	+		 	 	 	 
	 	

::::::u(**N,..4444n444  TTTT2K2Q2Q2S2STTT
 
 	 		 	 
 	 	r   c                   f    e Zd Zddee         fdZddee         fdZdefdZdefdZd	efd
Z	dS )	FakeTimerN
start_timec                 b    t          j                    | _        |                     |           d S )N)r   )	threadingLock_lockresetr   r   s     r   r   zFakeTimer.__init__   s+    ^%%


j
)))))r   c                 ~    | j         5  |t          j                    }|| _        d d d            d S # 1 swxY w Y   d S r   )r   rD   _currr   s     r   r   zFakeTimer.reset  s    Z 	$ 	$!!Y[[
#DJ	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s   266r$   c                     | j         S r   )r   r   s    r   rD   zFakeTimer.time  s
    zr   byc                 f    | j         5  | xj        |z  c_        d d d            d S # 1 swxY w Y   d S r   r   r   )r   r   s     r   advancezFakeTimer.advance  s~    Z 	 	JJ"JJ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   &**amtc                 l    | j         5  | xj        |dz   z  c_        d d d            d S # 1 swxY w Y   d S )NgMbP?r   )r   r   s     r   realistic_sleepzFakeTimer.realistic_sleep  s    Z 	& 	&JJ#+%JJ	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   )--r   )
r'   r(   r)   r   floatr   r   rD   r   r   r-   r   r   r   r      s        * *8E? * * * *$ $ $ $ $ $e    %    &5 & & & & & &r   r   c                     | j         }t          |          dk    s|d         t          urdS t          | dd          }t	          |t                    sdS t          d |D                       S )z7Return True if cls is a namedtuple and False otherwise.r"   r   F_fieldsNc              3   B   K   | ]}t          |          t          u V  d S r   )typestr)r   ns     r   	<genexpr>z!is_named_tuple.<locals>.<genexpr>  s,      ))!tAww#~))))))r   )	__bases__r   tuplegetattr
isinstancer   )clsbr   s      r   is_named_tupler     sp    A
1vv{{ad%''uY%%Aa u))q))))))r   c                    ddl }t          | |j                  r$t          ||j                  r| j        |j        k    sJ d| j         d|j                     | j        |j        k    sJ d| j         d|j                     | j        j        |j        j        k    sJ d| j         d|j                     |                                 }|                                }| j        j        s| j        j	        r$|
                    ||dd	          s
J d
            n |                    ||          s
J d            dS t          |           t          |          ur/t          dt          |            dt          |                     t          t          |                     rJt          |           t          |          k    sJ t          | |          D ]\  }}t!          ||           dS t          | t"                    rO|                                 |                                k    sJ | D ]}t!          | |         ||                    dS t          | t&          t(          f          rJt          |           t          |          k    sJ t          | |          D ]\  }}t!          ||           dS t+          | d          rt+          |d          rd | j                                        D             }d |j                                        D             }	||	k    sJ d| d|	             |D ](}t!          | j        |         |j        |                    )dS | |k    sJ d|  d|             dS )a  
    Recursively compare objects with special handling for torch.Tensor.

    Tensors are considered equivalent if:
      - Same dtype and shape
      - Same device type (e.g., both 'cpu' or both 'cuda'), index ignored
      - Values are equal (or close for floats)
    r   Nzdtype mismatch: z vs zshape mismatch: zDevice type mismatch: gư>gh㈵>)atolrtolz Floating-point tensors not closezInteger/bool tensors not equalzType mismatch: __dict__c                 H    h | ]}|                     d           s|dk    | S _ray__pytype_
startswithr   r   s     r   	<setcomp>z,assert_tensors_equivalent.<locals>.<setcomp>R  ?     
 
 
<<((
 ./*__ -<__r   c                 H    h | ]}|                     d           s|dk    | S r   r   r   s     r   r   z,assert_tensors_equivalent.<locals>.<setcomp>W  r   r   zObject attribute keys differ: zNon-tensor values differ: )torchr   Tensordtypeshapedevicer   cpuis_floating_point
is_complexallcloseequalAssertionErrorr   r   zipassert_tensors_equivalentdictkeyslistr   hasattrr   )
obj1obj2r   t1_cput2_cpur   r   r   keys1keys2s
             r   r   r     s    LLL$%% *T5<*H*H zTZ''')XDJ)X)XDJ)X)X'''zTZ''')XDJ)X)XDJ)X)X''' K 0000BDKBBT[BB 100 :' 	Q4:+@ 	Q>>T "   2 212 2  2 ;;vv..PP0PPP. Dzzd##KtDzzKKtDzzKKLLL d4jj!! K4yyCII%%%%dOO 	, 	,DAq%a++++	, 	,	D$		 Kyy{{diikk)))) 	8 	8A%d1gtAw7777	8 	8	D4-	(	( K4yyCII%%%%dOO 	, 	,DAq%a++++	, 	,	z	"	" KwtZ'@'@ K
 
]''))
 
 


 
]''))
 
 

 ~~~RRR5RR~~~ 	J 	JA%dmA&6a8HIIII	J 	J t|||J$JJDJJ|||||r   )r9   r:   F)r9   r:   )rW   rX   )1r*   r   rS   rd   r   rD   rJ   rf   collections.abcr   
contextlibr   enumr   typingr   r   r   r	   r
   r   r   rF   ray._common.usage.usage_lib_commonusage	usage_librx   ray._private.utilsray._common.network_utilsr   r   r   r/   __all__r+   r   rQ   rV   r,   r   rn   rp   r}   r   r   r   r   r   r-   r   r   <module>r      s      				           % % % % % % % % % % % %       E E E E E E E E E E E E E E E E E E 



 3 3 3 3 3 3 3 3 3 3 3 3     3 3 3 3 3 3 Q               4 Q# # # # # # # #( +
&
 ""	%  % !#t),% %  %  	% 
 %  %  %  % T "$  $ !#y"67$ $  $  	$  $  $  $ N  
 c]   <       SX    tCH~     ;?+ + +T"+  + "#c(^	+
  (S#X7+ + + +\& & & & & & & &.* * *BK BK BK BK BKr   