
    %`is                        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mZ d dlmZmZ d dlZd dlmc m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 d dlm Z  d d	l!m"Z"m#Z#m$Z$ d d
l%m&Z&m'Z'm(Z( d dl)m*Z*  edg d          Z+ edg d          Z,	  ej-        e.          Z/de0de'dee0         fdZ1 G d d          Z2dS )    N)defaultdict
namedtuple)CallableOptional)cloudpickle)pickle_dumps)ray_constants)is_class_methodis_function_or_methodis_static_method)KV_NAMESPACE_FUNCTION_TABLE)check_oversized_function
ensure_strformat_error_message)&WORKER_PROCESS_SETUP_HOOK_KEY_NAME_GCSJobIDPythonFunctionDescriptor)RemoteFunctionFunctionExecutionInfofunctionfunction_name	max_callsImportedFunctionInfojob_idfunction_idr   r   moduler   key_typer   keyc                     |;d                     | |                                                                g          S d                     | |                                                                |g          S )N   :)joinhexencode)r   r   r    s      q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/function_manager.pymake_function_table_keyr'   3   s_    
{yy(FJJLL$7$7$9$9:;;;yy(FJJLL$7$7$9$93?@@@    c                       e Zd ZdZd Zd Zd Zd Zd Z	 dde	d	e
e         d
efdZd Z	 dded	e
e         d
e
e         fdZd Zd Zd ZddefdZd Zd Zd Zd Zd ZdefdZdS )FunctionActorManagerar  A class used to export/load remote functions and actors.
    Attributes:
        _worker: The associated worker that this manager related.
        _functions_to_export: The remote functions to export when
            the worker gets connected.
        _actors_to_export: The actors to export when the worker gets
            connected.
        _function_execution_info: The function_id
            and execution_info.
        _num_task_executions: The function
            execution times.
        imported_actor_classes: The set of actor classes keys (format:
            ActorClass:function_id) that are already in GCS.
    c                 4   || _         g | _        g | _        t          d           | _        t          d           | _        t                      | _        i | _        t          j
                    | _        i | _        d| _        t          j                    | _        d S )Nc                      i S N r.   r(   r&   <lambda>z/FunctionActorManager.__init__.<locals>.<lambda>Q   s    B r(   c                      i S r-   r.   r.   r(   r&   r/   z/FunctionActorManager.__init__.<locals>.<lambda>R   s     r(   r   )_worker_functions_to_export_actors_to_exportr   _function_execution_info_num_task_executionssetimported_actor_classes_loaded_actor_classes	threadingRLocklockexecution_infos_num_exportedLock_export_lock)selfworkers     r&   __init__zFunctionActorManager.__init__J   s    $&!!# )4JJ(?(?%$/

$;$;! '*ee#%'" O%%	! %N,,r(   c                 >    |j         }| j        |xx         dz  cc<   d S )N   r   r5   r@   function_descriptorr   s      r&   increase_task_counterz*FunctionActorManager.increase_task_counterg   s/    )5!+...!3.....r(   c                 *    |j         }| j        |         S r-   rE   rF   s      r&   get_task_counterz%FunctionActorManager.get_task_counterk   s    )5(55r(   c                    ddl }|                                }t          j        ||d           |j        dz   |                                z   }t          j        |                    d                                                    S )aD  The identifier is used to detect excessive duplicate exports.
        The identifier is used to determine when the same function or class is
        exported many times. This can yield false positives.
        Args:
            function_or_class: The function or class to compute an identifier
                for.
        Returns:
            The identifier. Note that different functions or classes can give
                rise to same identifier. However, the same function should
                hopefully always give rise to the same identifier. TODO(rkn):
                verify if this is actually the case. Note that if the
                identifier is incorrect in any way, then we may give warnings
                unnecessarily or fail to give warnings, but the application's
                behavior won't change.
        r   N   )filedepth:zutf-8)	ioStringIOdis__name__getvaluehashlibsha1r%   digest)r@   function_or_classrP   string_filecollision_identifiers        r&   compute_collision_identifierz1FunctionActorManager.compute_collision_identifiero   s~      				kkmm!1====09C?+BVBVBXBXX |077@@AAHHJJJr(   c                     t          j        |          }d |                    d          D             }|}	 |D ]}t          ||          }|S # t          $ r Y dS w xY w)z9Try to load a function or class in the module from local.c                     g | ]}||S r.   r.   ).0parts     r&   
<listcomp>zJFunctionActorManager.load_function_or_class_from_local.<locals>.<listcomp>   s    LLL$tLLLLr(   .N)	importlibimport_modulesplitgetattr	Exception)r@   module_namefunction_or_class_namer   partsobjectr_   s          r&   !load_function_or_class_from_localz6FunctionActorManager.load_function_or_class_from_local   s    (55LL"8">">s"C"CLLL	 / / ..M 	 	 	44	s   A 
AAN
setup_functimeoutreturnc           	      ~   t          |d|j                   }t          j        |                              t
          j                  }t          t          j	                    | j
        j                                        |          }t          ||j        d| j
                   	 | j
        j                            |t!          j        | j
        j                                        ||d          dt
          j        |           n7# t&          $ r*}t(                              d|j         d           |d}~ww xY w|S )	z2Export the setup hook function and return the key.z/Cannot serialize the worker_process_setup_hook r   )r   r   r   Trm   z Failed to export the setup hook ra   N)r   rS   rU   	shake_128rW   r	   ID_SIZEr'   r   r%   r1   current_job_idbinaryr   
gcs_clientinternal_kv_putpickledumpsr   rf   logger	exception)r@   rl   rm   pickled_functionfunction_to_run_idr    es          r&   export_setup_funcz&FunctionActorManager.export_setup_func   so    (VATVV
 

 %./?@@GG!
 
 & 39;;L'..00
 
 	!j1:t|	
 	
 	
	L#33"&,"="D"D"F"F'9$4   9 4      	 	 	Lj6ILLL   G		 
s   %A D 
D:%D55D:c           
         | j         j        r.|j        }|j        |j        }}|                     ||          	 dS |j        }|j        }t          ||j	        d| j                    t          d| j         j        |j        j                                                  }| j         j                            |t                     rdS t#          j        | j         j                                        |j        j                                        |j	        |j        ||                     |          |j        d          }| j         j                            ||dt                      dS )zPickle a remote function and export it to redis.
        Args:
            remote_function: the RemoteFunction object.
        Nzremote function   RemoteFunction)r   r   r   r   r   rZ   r   T)r1   load_code_from_local_function_descriptorrg   r   rk   	_function_pickled_functionr   _function_namer'   rs   r   rt   ru   internal_kv_existsr   rw   rx   
__module__r[   
_max_callsrv   )	r@   remote_functionrG   rg   r   r   r{   r    vals	            r&   exportzFunctionActorManager.export   sx   
 <, 	"1"F#/#1 'K 66{MRR ",*< *L		
 	
 	
 &L'0<CCEE
 

 <"55c;VWW 	Fl,5<<>>.COVVXX!0!?"-,(,(I(I((S(S,7 

 

 	//d7	
 	
 	
 	
 	
r(   r    c                     | j         j                            |t          |          d S t	          j                  g d}t                              fd|D                       S )Nrp   r   c              3   B   K   | ]}                     |          V  d S r-   getr^   fieldvalss     r&   	<genexpr>z?FunctionActorManager.fetch_registered_method.<locals>.<genexpr>  s-      -R-R%dhhuoo-R-R-R-R-R-Rr(   )r1   ru   internal_kv_getr   rw   loadsr   _make)r@   r    rm   fieldsr   s       @r&   fetch_registered_methodz,FunctionActorManager.fetch_registered_method   s     |&66,g 7 
 
 <4<%%D  F (---R-R-R-R6-R-R-RRRRr(   c                    |                      |          }|sdS |\  }}}}}}t          j        |          }	t          j        |          }
t	          |          }| j        5  d| j        |	<   	 t          j        |          }||_	        t          |||          | j        |	<   n# t          $ r{ t          t          j                              fd}t          |||          | j        |	<   t                               d| d|	                                 d|
 d d		           Y nw xY wd
d
d
           n# 1 swxY w Y   dS )zImport a remote function.Fr   r   c                  B    t          dt          j         d           )NzThe remote function failed to import on the worker. This may be because needed library dependencies are not installed in the worker environment or cannot be found from sys.path z:

)RuntimeErrorsyspath)argskwargstraceback_strs     r&   fzBFunctionActorManager.fetch_and_register_remote_function.<locals>.f)  s:    &: 8	: : +8	: :  r(   z(Failed to unpickle the remote function 'z' with function ID z	. Job ID:z.Traceback:
z. NT)r   ray
FunctionIDr   intr;   r5   rw   r   r   r   r4   rf   r   	traceback
format_excry   debugr$   )r@   r    remote_function_info
job_id_strfunction_id_strr   serialized_functionr   r   r   r   r   r   r   s                @r&   "fetch_and_register_remote_functionz7FunctionActorManager.fetch_and_register_remote_function	  s   #;;C@@# 	5 !	
 n_55:&&	NN	
 Y ,	 ,	56D%k2)!<(;<<J '-#=R%]i> > >-k::K     !5Y5I5K5K L L     >Smy> > >-k: 5%5 5#.??#4#45 5 %5 5 $1	5 5 5    /,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	 ,	Z ts7   "D8.B$"D8$BD)&D8(D))D88D<?D<c                    |j         }|| j        v r| j        |         S | j        j        r8|                                s$|                     |          du r| j        |         S t          j        d          5  |                     ||           ddd           n# 1 swxY w Y   	 |j         }| j        |         }n,# t          $ r}d|d|d|}t          |          d}~ww xY w|S )a  Get the FunctionExecutionInfo of a remote function.
        Args:
            job_id: ID of the job that the function belongs to.
            function_descriptor: The FunctionDescriptor of the function to get.
        Returns:
            A FunctionExecutionInfo object.
        Twait_for_functionNz,Error occurs in get_execution_info: job_id: z, function_descriptor: z. Message: )
r   r4   r1   r   is_actor_method_load_function_from_local	profilingprofile_wait_for_functionKeyError)r@   r   rG   r   infor}   messages          r&   get_execution_infoz'FunctionActorManager.get_execution_infoM  s    *5 $7770==<, 	F&6688 F 112EFF$NN8EE 233 	A 	A##$7@@@	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A		$-9K0=DD 	$ 	$ 	$ 	$ 66...3 
 7###	$ s*   6BB B%B: :
C#CC#c                    |                                 rJ |j        }|j        |j        }}|                     ||          }|Et          |t                    r|j        }n|}t          ||d          | j	        |<   d| j
        |<   dS dS )Nr   r   TF)r   r   rg   r   rk   
isinstancer   r   r   r4   r5   )r@   rG   r   rg   r   rj   r   s          r&   r   z.FunctionActorManager._load_function_from_localv  s    &6688888)5  +- #
 77]SS &.11 "!+!9N!+: : :D)+6
 67D%k245r(   
   r   c           	         t          j                     }d}	 | j        5  | j        j                                        rj|j        | j        v r	 ddd           dS t          d||j                                                  }| 	                    |          du r	 ddd           dS nH| j        j                                        rJ | j        j        | j        j
        v sJ 	 ddd           dS 	 ddd           n# 1 swxY w Y   t          j                     |z
  |k    rd| d| j        j         d| j        j                                         dt          j                     d		}|sQt                               |           t$          j        j                            | j        t,          j        ||
           d}t          j        d           )a{  Wait until the function to be executed is present on this worker.
        This method will simply loop until the import thread has imported the
        relevant function. If we spend too long in this loop, that may indicate
        a problem somewhere and we will push an error message to the user.
        If this worker is an actor, then this will wait until the actor has
        been defined.
        Args:
            function_descriptor : The FunctionDescriptor of the function that
                we want to execute.
            job_id: The ID of the job to push the error message to
                if this times out.
        FTNr   zJThis worker was asked to execute a function that has not been registered (z, node=z, worker_id=z, pid=z). You may have to restart Ray.)r   gMbP?)timer;   r1   actor_idis_nilr   r4   r'   rt   r   actorsnode_ip_address	worker_idr$   osgetpidry   errorr   _privateutilspush_error_to_driverr	   WAIT_FOR_FUNCTION_PUSH_ERRORsleep)r@   rG   r   rm   
start_timewarning_sentr    warning_messages           r&   r   z'FunctionActorManager._wait_for_function  s    Y[[
$	  <(//11 *6$:WWW       
 6-"/;BBDD 
  BB3GG4OO!        P  $|4;;=====<0DL4GGGGG!        P              $ y{{Z''11H5HH H L8H H "&!7!;!;!=!=H H 9;;	H H H   $ LL111L&;;%B'%	 <     $JuI$	s   .C<A C<&<C<<D D c           
         | j         j        r'|j        |j        }}|                     ||          	 d S | j         j                                        r
J d            | j         j        }t          d||j        	                                          }t          |d|j                   }|j                            d          d         |j        ||	                                |                     |          t          j        t!          |                    d}	t#          |	d         |	d         d	| j                    | j         j                            |t)          j        |	          d
t*                     d S )Nz~You might have started a background thread in a non-actor task, please make sure the thread finishes before the task finishes.
   ActorClassz$Could not serialize the actor class ra   )
class_namer   classr   rZ   actor_method_namesr   r   actorT)r1   r   rg   r   rk   rs   r   r'   r   rt   r   reprrd   r[   jsonrx   listr   ru   rv   rw   r   )
r@   Class"actor_creation_function_descriptorr   rg   r   r   r    serialized_actor_classactor_class_infos
             r&   export_actor_classz'FunctionActorManager.export_actor_class  s    <, 	2>2= $K 66{JOO  <.5577 	
 	
	
 	
7
 ,%.:AACC
 

 ".9169 9"
 "
 =GMMcRRSUV8D+mmoo$($E$Ee$L$L"&*T2D-E-E"F"F
 
 	!W%\*L		
 	
 	
 	//.//7R	
 	
 	
 	
 	
r(   c                 .   |j         }| j                            |d          }|| j        j        r.|                     |          }||                     ||          }n|                     ||          }|| j        |<   |j        }|j        }t          j
        |t                    }|D ]`\  }}	|dk    r|}
nt          |||          }
|
j         }|                     ||	          }t          ||d          | j        |<   d| j        |<   ad| j        |<   |S )zLoad the actor class.
        Args:
            job_id: job ID of the actor.
            actor_creation_function_descriptor: Function descriptor of
                the actor constructor.
        Returns:
            The actor class.
        N)	predicaterB   r   r   )r   r8   r   r1   r   _load_actor_class_from_local_load_actor_class_from_gcsrg   r   inspect
getmembersr   r   _make_actor_method_executorr   r4   r5   )r@   r   r   r   actor_classrg   actor_class_nameactor_methodsactor_method_nameactor_methodmethod_descriptor	method_idexecutors                r&   load_actor_classz%FunctionActorManager.load_actor_class  s    9D044[$GG|0 "??6  &"&"A"A B# #K #==>  7BD&{3 =HKAL#.'<  M 4A 9 9/!< %
22(J%%(@#%68H) )% .9	;;%|  <Q%"3< < <-i8
 89))4456D%k2r(   c                     |j         |j        }}|                     ||          }|-t          |t          j        j                  r|j        j        S |S dS )z!Load actor class from local code.N)	rg   r   rk   r   r   r   
ActorClass__ray_metadata__modified_class)r@   r   rg   r   rj   s        r&   r   z1FunctionActorManager._load_actor_class_from_localF  sa     /:.9  
 77ZPP&#)"677 .==4r(   c                 \     G d d          }fd}|D ]}t          |||           |S )Nc                       e Zd Zd ZdS )EFunctionActorManager._create_fake_actor_class.<locals>.TemporaryActorc                 
   K   dS )zDummy method for this fake actor class to work for async actors.
                Without this method, this temporary actor class fails to initialize
                if the original actor class was async.Nr.   )r@   s    r&   __dummy_methodzTFunctionActorManager._create_fake_actor_class.<locals>.TemporaryActor.__dummy_method[  s       r(   N)rS   r   __qualname___TemporaryActor__dummy_methodr.   r(   r&   TemporaryActorr   Z  s#            r(   r   c                  .    t          d d           )NzThe actor with name z failed to import on the worker. This may be because needed library dependencies are not installed in the worker environment:

)r   )r   r   r   r   s     r&   temporary_actor_methodzMFunctionActorManager._create_fake_actor_class.<locals>.temporary_actor_methoda  s6    :'7 : : +8: :  r(   )setattr)r@   r   r   r   r   r   methods    ` `   r&   _create_fake_actor_classz-FunctionActorManager._create_fake_actor_classW  sy    	 	 	 	 	 	 	 		 	 	 	 	 	 ) 	D 	DFNF,BCCCCr(   c                    t          d||j                                                  }| j        j                            |t                    g d}i nt          j                  fd|D             \  }}}}}	t          |          }t          |          }
t          j        |          }t          j        t          |	                    }	d}	 | j        5  t          j        |          }ddd           n# 1 swxY w Y   nb# t          $ rU t                              d|           t#          t%          j                              }|                     ||	|          }Y nw xY w|
|_        |S )zLoad actor class from GCS.r   )r   r   r   r   r   Nc              3   B   K   | ]}                     |          V  d S r-   r   r   s     r&   r   zBFunctionActorManager._load_actor_class_from_gcs.<locals>.<genexpr>}  sF       O
 O
 %DHHUOOO
 O
 O
 O
 O
 O
r(   zFailed to load actor class %s.)r'   r   rt   r1   ru   r   r   rw   r   r   r   r   r   r;   rf   ry   r   r   r   r   r   r   )r@   r   r   r    r   r   r   r   pickled_classr   rg   r   r   r   s                @r&   r   z/FunctionActorManager._load_actor_class_from_gcsn  s   %.:AACC
 
 |&66s<WXXRRR<DD<%%DO
 O
 O
 O
)/O
 O
 O
KZ8J  
++
 ((:&&!Z
3E(F(FGG	 : :$l=99: : : : : : : : : : : : : : : 
	 
	 
	LL9:FFF 11E1G1GHHM 77. KKK
	" "-s7   D
 C>2D
 >DD
 DD
 
AE)(E)method_namec                 2    fd}|_         |_        |S )a  Make an executor that wraps a user-defined actor method.
        The wrapped method updates the worker's internal state and performs any
        necessary checkpointing operations.
        Args:
            method_name: The name of the actor method.
            method: The actor method to wrap. This should be a
                method defined on the actor class and should therefore take an
                instance of the actor as the first argument.
        Returns:
            A function that executes the given actor method on the worker's
                stored instance of the actor. The function also updates the
                worker's internal state to record the executed method.
        c                     t                    pt          t          |                     }|r |i |S  | g|R i |S r-   )r
   r   type) _FunctionActorManager__ray_actorr   r   is_boundr   r   s       r&   actor_method_executorzOFunctionActorManager._make_actor_method_executor.<locals>.actor_method_executor  sn    &v.. 2B[!!;3 3H  <vt.v...vk;D;;;F;;;r(   )namer   )r@   r   r   r  s    `` r&   r   z0FunctionActorManager._make_actor_method_executor  s<    	< 	< 	< 	< 	< 	< &1"'-$$$r(   r-   )r   )rS   r   r   __doc__rB   rH   rJ   r[   rk   r   r   r   bytesr~   r   strr   r   r   r   r   r   r   r   r   r   r   r   r.   r(   r&   r*   r*   :   s        - - -:4 4 46 6 6K K K2
 
 
 >B. .".-5c].	. . . .`/
 /
 /
d 26S SS!)#S	&	'S S S S(B B BH' ' 'R  64 4c 4 4 4 4l7
 7
 7
xA A AF  "  .. . .`!%s !% !% !% !% !% !%r(   r*   )3rR   rU   rb   r   r   loggingr   r   r9   r   r   collectionsr   r   typingr   r   r   ray._private.profilingr   r   r   rw   ray._common.serializationr   ray._privater	   ray._private.inspect_utilr
   r   r   ray._private.ray_constantsr   ray._private.utilsr   r   r   ray._rayletr   r   r   ray.remote_functionr   r   r   	getLoggerrS   ry   r	  r'   r*   r.   r(   r&   <module>r     s   



         				 



          / / / / / / / / % % % % % % % % 



 * * * * * * * * * % % % % % % 2 2 2 2 2 2 & & & & & &         
 C B B B B B         
         
 / . . . . ."
GGG   "zQQQ  
 P		8	$	$Ae AU A% A A A AE
% E
% E
% E
% E
% E
% E
% E
% E
% E
%r(   