o
    ;i h                    @   sT  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	m
Z
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 d dlZd dlmZ d dlmZ d dl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) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZDmEZE ddlFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN ddlOmPZPmQZQ ddlRmSZSmTZT ddlUmVZVmWZW ddlXmYZY ddlZm[Z[m\Z\ ddl]m]Z] ddl^m_Z_m`Z`maZambZb dd lcmdZdmeZe dd!lfmgZg dd"lhmiZimjZj dd#lkmlZlmmZm dd$lnmoZo dd%lpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~ dd&lmZ dd'lmZmZ dd(lmZ dd)lmZ dd*lmZ erd dlZd dlZd dlZd+ZejjejjfZejG d,d- d-ZG d.d/ d/ZG d0d1 d1Zed2d3G d4d5 d5Z	6dRd7eeeef  d8ed9eej fd:d;ZeG d<d= d=Zd>ed?ed@efdAdBZedCZejdDd2dEZejdFd2dEZejdGd2dEZG dHdI dIejeeef e#dJdKZG dLdM dMeje e#dNdKZdOee d9ej
e fdPdQZdS )S    N)AsyncGenerator
CollectionSequenceSized)	dataclass)PurePosixPath)TYPE_CHECKINGAnyAsyncIteratorCallableOptionalUnion)Message)Status)MethodWithAio)api_pb2)ModalClientModal   )LoadContext)_Objectlive_methodlive_method_gen)get_pty_info)FunctionCreationStatus)Resolver)%convert_fn_config_to_resources_config)current_input_idis_local)apply_defaultsget_callable_schema	serializeserialize_proto_paramsvalidate_parameter_values)print_server_warnings)TaskContextaclosingasync_mergecallable_to_agendeprecate_aio_usagesynchronizer!warn_if_generator_is_not_consumed)MAX_OBJECT_SIZE_BYTES)deprecation_warningwarn_if_passing_namespace)ATTEMPT_TIMEOUT_GRACE_PERIODOUTPUTS_TIMEOUTFunctionInfo_create_input_process_result_stream_function_call_dataget_function_typeis_async)RetryRetryWarningMessage)validate_network_file_systemsvalidate_volumes)	InputInfo_reconstruct_call_graph)_Client)_CloudBucketMountcloud_bucket_mounts_to_proto)config)ExecutionErrorInvalidErrorNotFoundErrorOutputExpiredError)GPU_Tparse_gpu_config)_Image)_get_client_mount_Mount)_NetworkFileSystem network_file_system_mount_protos)OutputManager)_experimental_spawn_map_async_experimental_spawn_map_sync_for_each_async_for_each_sync
_map_async_map_invocation_map_invocation_inputplane	_map_sync_spawn_map_async_spawn_map_invocation_spawn_map_sync_starmap_async_starmap_sync_SynchronizedQueue)_Proxy)RetriesRetryManager)Schedule)_Secret)_Volume   c                   @   sJ   e Zd ZU ded< ejed< eed< eed< eed< ejed< eed< d	S )
_RetryContext,api_pb2.FunctionCallInvocationType.ValueTypefunction_call_invocation_typeretry_policyfunction_call_jwt	input_jwtinput_iditemsync_client_retries_enabledN)	__name__
__module____qualname____annotations__r   FunctionRetryPolicystrFunctionPutInputsItembool rr   rr   D/home/ubuntu/.local/lib/python3.10/site-packages/modal/_functions.pyra   m   s   
 

ra   c                   @   s  e Zd ZU dZeed< 	d*dedededee	 fddZ
ed	d
dddedddedd f
ddZ					d+dedee dedeee  dejf
ddZd,ddZd*dee dejfddZdefdd Zd*dd!dee defd"d#Zd$d% Zd&ed'efd(d)ZdS )-_InvocationzVInternal client representation of a single-input call to a Modal Function or GeneratorstubNfunction_call_idclientretry_contextc                 C   s   || _ || _|| _|| _d S N)ru   rw   rv   _retry_context)selfru   rv   rw   rx   rr   rr   rs   __init__}   s   
z_Invocation.__init__Ffrom_spawn_mapfunction	_Functionrc   rb   r~   returnc             
      sd  |j sJ |j }| j}t|||| |dI d H }tj|t pdtj|g|d}	|rGd|	_|j j|	t	d dt
ddtjgdtjgd	d
I d H }
n	|j |	I d H }
|
j}|
jr{t|
jdks_J |
jd }t||
j|
j|j|j||
jd}t||||S tj||g|d}|j |I d H }|j}|std|jd }t||
j|
j|j|j||
jd}t||||S )N)r   rc    )function_idparent_input_idfunction_call_typepipelined_inputsrc   Tg      >@zWarning: `.spawn_map(...)` for function `{self._function_name}` is waiting to createmore function calls. This may be due to hitting rate limits or function backlog limits.
   )messagewarning_intervalerrors_to_warn_for)max_retries	max_delaywarning_messageadditional_status_codesretryr   r   )rc   rd   re   rf   rg   rh   ri   )r   inputsrv   zACould not create function call - the input queue seems to be full)ru   	object_idr1   r   FunctionMapRequestr   FUNCTION_CALL_TYPE_UNARYr~   FunctionMapr6   r7   r   RESOURCE_EXHAUSTEDrv   r   lenra   rd   re   rf   rg   ri   rt   FunctionPutInputsRequestFunctionPutInputsr   	Exception)r   argskwargsrw   rc   r~   ru   r   rh   requestresponserv   inputrx   request_putinputs_responseprocessed_inputsrr   rr   rs   create   s   


	
	z_Invocation.creater   indextimeoutclear_on_success
input_jwtsc           	   
      s   t   }|d u rt}ntt|}	 tj| j|d|t   |||d}| jj|t|t	 ddI d H }t
|jdkr;|S |d urPtt|| t    }|dk rP|S q)NT0-0)rv   r   last_entry_idr   requested_atr   	start_idxend_idxattempt_timeoutr   r   )timer/   minr   FunctionGetOutputsRequestrv   ru   FunctionGetOutputsr6   r.   r   outputs)	r{   r   r   r   r   t0backend_timeoutr   r   rr   rr   rs   pop_function_call_outputs   s6   

z%_Invocation.pop_function_call_outputsc                    sP   | j }|s
tdtj|j|jjd}tj|j|gd}| j	
|I d H  d S )Nz0Cannot retry input when _retry_context is empty.)rf   r   )re   r   )rz   
ValueErrorr   FunctionRetryInputsItemrf   rh   r   FunctionRetryInputsRequestre   ru   FunctionRetryInputs)r{   ctxrh   r   rr   rr   rs   _retry_input  s   z_Invocation._retry_inputexpected_jwtc                    s.   | j dd d|r|gnd dI d H jd }|S )Nr   T)r   r   r   r   )r   r   )r{   r   rh   rr   rr   rs   _get_single_output  s   
z_Invocation._get_single_outputc                    s   | j }|r|jr|jjdks|jtjks|js-|  I d H }t|j	|j
| j| jI d H S t|j}	 | |jI d H }|j	jtv rPt|j	|j
| j| jI d H S |j	jtjjkrx| }|d u rnt|j	|j
| j| jI d H S t|d I d H  |  I d H  q3)Nr   T  )rz   rd   retriesrc   r   "FUNCTION_CALL_INVOCATION_TYPE_SYNCri   r   r2   resultdata_formatru   rw   r\   rf   statusTERMINAL_STATUSESGenericResultGENERIC_STATUS_INTERNAL_FAILUREget_delay_msasynciosleepr   )r{   r   rh   user_retry_managerdelay_msrr   rr   rs   run_function  s0   
z_Invocation.run_functionr   c                   sr   | j ||ddI dH }t|jdkr|jdkrt t|jdkr%t t|jd j|jd j| j	| j
I dH S )zWaits up to timeout for a result from a function.

        If timeout is `None`, waits indefinitely. This function is not
        cancellation-safe.
        F)r   r   r   Nr   )r   r   r   num_unfinished_inputsrC   TimeoutErrorr2   r   r   ru   rw   )r{   r   r   r   rr   rr   rs   poll_function:  s   
z_Invocation.poll_functionc              	   C  s   d}d }t tt| jd | jddt| j4 I d H 1}|2 z!3 d H W }t|tj	r.|j
}n|V  |d7 }|d ur?||kr? nq6 W d   I d H  d S 1 I d H sRw   Y  d S )Nr   data_out)variantr   )r%   r&   r3   rw   rv   r'   r   
isinstancer   GeneratorDoneitems_totalr{   items_receivedr   streamerrh   rr   rr   rs   run_generatorO  s(   .z_Invocation.run_generatorstart_index	end_indexc              	   C  s  d}|}||k rt || |d }tj| jdddt ||d}| jj|ttddI d	H }t	|j
}|jd
d d |D ]!}	|	j|krG nt|	j|	j| j| jI d	H }
|	j|
fV  |d7 }q>t||| d k r|| j|dI d	H }
||
fV  |d7 }||k s	d	S d	S )zTIterate over the results of the function call in the range [start_index, end_index).1   r   r   r   F)rv   r   r   r   r   r   r   r   r   Nc                 S      | j S ry   )idx)xrr   rr   rs   <lambda>y  s    z'_Invocation.enumerate.<locals>.<lambda>)keyr   )r   r   r   rv   r   ru   r   r6   r.   listr   sortr   r2   r   r   rw   r   r   )r{   r   r   limitcurrent_indexbatch_end_indexr   r   r   outputr   rr   rr   rs   	enumerated  s<   	




z_Invocation.enumeratery   )r   NFN)r   N)rj   rk   rl   __doc__r   rm   ro   r<   r   ra   r|   staticmethodrq   r   intfloatr   r   FunctionGetOutputsResponser   r   FunctionGetOutputsItemr   r	   r   r   r   r   rr   rr   rr   rs   rt   x   s^   
 
T


)	 rt   c                   @   s   e Zd ZU dZeed< dedededej	dedej
defd	d
Zedddedededd f
ddZdefddZdeeeef  defddZdd Zedededeeeef  fddZdS )_InputPlaneInvocationzoInternal client representation of a single-input call to a Modal Function using the input
    plane server API.ru   attempt_tokenrw   
input_itemr   rd   input_plane_regionc                 C   s.   || _ || _|| _|| _|| _|| _|| _d S ry   )ru   rw   r   r   r   rd   r   )r{   ru   r   rw   r   r   rd   r   rr   rr   rs   r|     s   

z_InputPlaneInvocation.__init__r   r   input_plane_urlr   c                   s   | |I d H }| j}|j}t|||| dI d H }	tj|t p!d|	d}
||I d H }|j|
|dI d H }|j	}t
||||	||j|S )N)r   r   )r   r   r   metadata)get_stubr   ru   r1   r   AttemptStartRequestr   get_input_plane_metadataAttemptStartr   r   rd   )r   r   r   rw   r   r   ru   r   control_plane_stubr   r   r   r   r   rr   rr   rs   r     s*   
z_InputPlaneInvocation.createc                    s,  t | j}d}	 tj| jtt d}| j| j	I d H }| j
j|ttt d|dI d H }|ds5q|jjjtv rMt|jj|jj| jj
| jI d H S |jjjtjjkri|d7 }|tk rh| |I d H | _qn|  }d urt|d I d H  | |I d H | _qt|jj|jj| jj
| jI d H S )	Nr   T)r   timeout_secsr   r   )r   r   r   r   r   )r\   rd   r   AttemptAwaitRequestr   r/   r   rw   r   r   ru   AttemptAwaitr6   r.   HasFieldr   r   r   r   r2   r   r   r   MAX_INTERNAL_FAILURE_COUNTr   r   r   r   )r{   r   internal_failure_countawait_requestr   await_responser   rr   rr   rs   r     sD   



z"_InputPlaneInvocation.run_functionr   c                    s<   t j| jt p	d| j| jd}| jj||dI d H }|jS )Nr   )r   r   r   r   r   )r   AttemptRetryRequestr   r   r   r   ru   AttemptRetry)r{   r   retry_requestretry_responserr   rr   rs   r     s   z"_InputPlaneInvocation._retry_inputc              	   C  s   d}d }t tt| j| jd d| jdt| j4 I d H 1}|2 z!3 d H W }t|t	j
r0|j}n|V  |d7 }|d urA||krA nq 6 W d   I d H  d S 1 I d H sTw   Y  d S )Nr   r   )rv   r   r   r   )r%   r&   r3   rw   ru   r   r'   r   r   r   r   r   r   rr   rr   rs   r     s4   .z#_InputPlaneInvocation.run_generatorc                    s8   | sg S |j sJ d|j  I d H }d| fd|fgS )NzClient is not openzx-modal-input-plane-regionzx-modal-auth-token)_auth_token_manager	get_token)r   rw   tokenrr   rr   rs   _get_metadata  s   z#_InputPlaneInvocation._get_metadataN)rj   rk   rl   r   r   rm   ro   r<   r   rp   rn   r|   r   r   r	   r   r   tupler   r   r  rr   rr   rr   rs   r     sF   
 
#0
(r   T)frozenc                   @   s"   e Zd ZU dZeed< eed< dS )FunctionStatsz;Simple data structure storing stats for a running function.backlognum_total_runnersN)rj   rk   rl   r   r   rm   rr   rr   rr   rs   r  #  s   
 r  r   r   sourcer   c                 C   sh   t | trt| ddd S t | tr|  S | d u rd S |r$d| nd}dt|  | d}t|)Ng      ?)r   initial_delaybackoff_coefficientz on r   zJRetries parameter must be an integer or instance of modal.Retries. Found: .)r   r   r[   	_to_prototyperA   )r   r  extramsgrr   rr   rs   _parse_retries+  s   

r  c                   @   s   e Zd ZU dZee ed< ee ed< e	e
 ed< eeeef ef ed< eeeef eeef f ed< eeee f ed< ee ed< eeeeeef f  ed	< eeeeeef f  ed
< ee ed< eej ed< ee ed< dS )_FunctionSpecz
    Stores information about a Function specification.
    This is used for `modal shell` to support running shells with
    the same configuration as a user-defined Function.
    imagemountssecretsnetwork_file_systemsvolumesgpuscloudcpumemoryephemeral_diskscheduler_placementproxyN)rj   rk   rl   r   r   rF   rm   r   rH   r   r^   dictr   ro   r   rI   r_   r=   rD   r   r   r  r   r   SchedulerPlacementrZ   rr   rr   rr   rs   r  ?  s   
  r  is_web_endpointis_generatorrestrict_outputc                 C   s^   | rt jg}t jt jg}||fS t jt jg}|rt jg}nt jt jg}|r+|t j ||fS ry   )r   DATA_FORMAT_ASGIDATA_FORMAT_GENERATOR_DONEDATA_FORMAT_PICKLEDATA_FORMAT_CBORappend)r)  r*  r+  supported_input_formatssupported_output_formatsrr   rr   rs   #_get_supported_input_output_formatsV  s   	
r3  P
ReturnType)	covariantOriginalReturnTypeTc                ^   @   s  e Zd ZU dZee ed< ee ed< dZ	ed ed< dZ
ed ed< dZeej ed	< ee ed
< ee ed< eed< dZee ed< eed< eedef  ed< eed< dZee ed< dZeed< dZed ed< dZeeedf  ed< dZeej ed< edddddi i dddddddddddddddddddddddddddddddddddf*deded ded eeeee f  d!eee  d"ee d#ed$e e!e"e! f d%ee ee#f e$f d&ee ee#f e e%e&f f d'eej d(ee e'e(e'e'f f  d)ee e)e(e)e)f f  d*ee* d+ee e)e+f  d,e)d-ee) d.ee) d/ee) d0ee) d1ee) d2ee) d3ee) d4ee) d5ee) d6ee d7ee ee,e f  d8ed9ed:ed;ed<ed=ed>ed?ed@ee) dAee dBedCee) dDedEeeeef  dFee dGee' dHedIeej- dJd f\dKdLZ.dMddNedO dPe/dQeeef dJd f
dRdSZ0e1dddddTd.ee) d/ee) d0ee) d1ee) dJdf
dUdVZ2e1dWe)dJdfdXdYZ3e4dZed[ed\e5fd]d^Z6e4dddd_d`e7d  dZed[edaee dbee8 dJd fdcddZ9e:dJefdedfZ;e:ddgdhZ<e:ddidjZ=e:dJefdkdlZ>e:dJefdmdnZ?dJefdodpZ@dJefdqdrZAdsdt ZBdueeC fdvdwZDdxdy ZEdzefd{d|ZFe:e1dJee fd}d~ZGe1dJee fddZHe1dJee"e  fddZIe:dJefddZJeKdeLdedededJeMedf f
ddZNe1deLdJdfddZOdJePfddZQ	ddddedJeRfddZSeT eKeUjVdd ZWeUjXe1dPeYjZdQeYj[dJePfddZ\eUjXeKdJeMedf fddZ]dd Z^dJefddZ_dJed fddZ`eUjadPeYjZdQeYj[dJebfddZceUjVe1dPeYjZdQeYj[dJdfddZdeUjVe1dPeYjZdQeYj[dJdfddZeeUjVe1dPeYjZdQeYj[dJdfddZfdJedef fddZge1dJehfddZie1dJejjfddZkelemeneUZoelepeqeUZreleseteUZueleveweUZxeleyezeUZ{dS )r   zFunctions are the basic units of serverless execution on Modal.

    Generally, you will not construct a `Function` directly. Instead, use the
    `App.function()` decorator to register your Python functions with your App.
    _info_serve_mountsNmodal.app._App_appzmodal.cls._Obj_obj_webhook_config_web_url_function_name
_is_method_spec_tag._raw_f_build_args_is_generatorr   _use_method_namezapi_pb2.ClassParameterInfo_class_parameter_infozapi_pb2.FunctionHandleMetadata_method_handle_metadata	_metadataFi,  Tinfoappr  envr  scheduler*  gpur  r  webhook_configr"  r#  r&  r   r   startup_timeoutmin_containersmax_containersbuffer_containersscaledown_windowmax_concurrent_inputstarget_concurrent_inputsbatch_max_sizebatch_wait_msr!  regionnonpreemptibleis_builder_functionis_auto_snapshot	is_serverenable_memory_snapshotblock_networkrestrict_modal_accessi6pn_enabledcluster_sizerdmasingle_use_containersr$  include_sourceexperimental_options_experimental_proxy_ip#_experimental_custom_scaling_factorr+  http_configr   c-           F   3      s  ddl m}-m}.  ,jr)j}/t|/sJ %dur( s(td|/ dnjs.J 1r2J %r6J |'r<	 ni }0t
 g|0 t|jrSd  dnd  d##durn1durhtd	|rntd
.du rvtd'pyg '|rg 't|'d&|s|rt|tr|gn|rt|nd}1tj|1|d&t'||	
& d}2durttstdtj dur܈dur܈k rtd d d$dur$dkrtdtj	$ddurdkrdD ]}3t|3}4|4r|4 dkrtd|3 d|4 d dqdur0dk s,dkr0td
s;s;td
|rP1rP1jtjkrLtdtdjrrjj}5|rftd|5 dtjj D ]}6|6j tj!j"urtd|5 d qot#|	}7d!d" |7D d#d" |7D 0t$|/durtt%std$t d%djri |-j|.& }8|8' D ]?\}9}:t(|:j)j*jj d%|9 };|:+ }<t,|:- |<d&d'}=t.|<|:j)j*pd(|+\}>}?tj/|:j)j0|;|=|>|?d)}@|@|9< qt(|d<d*tt1 f '/0fd+d, 2 r"g *g +n1duo,1jtj3k}<t.|<||+\*+d-t4d.t5d/t6d0t7t f*+1fd1d2}Ad-t4d.t5d/t6d0t7t f 	
 !"#$%&'()*+,-./01f2d3d4}Bd5, d}Crj8nt6" }Dt4j9|B|C|A |Dd6j_:_;,_<_=d_>|_?d(_@|2_A1_Bttrˈng}EtCtD'tDd7d" |ED tD|d8_E|	rtD|	jEd9< 
s&rtD
jEd:< tD&jEd;< S )=zJmdmd:hidden

        Note: This is not intended to be public API.
        r   )"_find_partial_methods_for_user_cls_PartialFunctionFlagsN	Function zF has a schedule, so it needs to support being called with no argumentsz
Function ''zClass 'z%Web endpoints do not support retries.z+Generator functions do not support retries.zTThe `timeout` parameter cannot be set to None: https://modal.com/docs/guide/timeouts)regionsr[  )r  r  r   r  r  r  r!  r"  r#  r$  r%  r&  z%`min_containers` must be an int, not z`min_containers` (z+) cannot be greater than `max_containers` ()r   z`scaledown_window` must be > 0rR  rS  rT  rU  )rR  rS  rT  `z` (z() must be a multiple of `cluster_size` (z) for clustered FunctionszL`_experimental_custom_scaling_factor` must be between 0.0 and 1.0 inclusive.default_cloudzWebhooks cannot be generators. If you want a streaming response, see https://modal.com/docs/guide/streaming-endpoints
                    zWebhooks cannot be generatorszModal batched function z cannot return generatorsz# does not accept default arguments.c                 S   "   g | ]\}}t |tr||fqS rr   )r   r=   .0kvrr   rr   rs   
<listcomp><     " z(_Function.from_local.<locals>.<listcomp>c                 S   rt  rr   )r   r_   ru  rr   rr   rs   ry  =  rz  z!Expected modal.Image object. Got r  T)r)  ignore_first_argumentF)rP  function_typefunction_namefunction_schemar1  r2  r   c                    s   t }| s|t  7 }r| r| D ]	\}}|| qD ]	\}}|| q(D ]\}}|jrA||j q4|S ry   )r   r0  secret)only_explicit_mountsdeps_nfsvolcloud_bucket_mount)
all_mountscloud_bucket_mountsr  r&  r  validated_network_file_systems"validated_volumes_no_cloud_bucketsrr   rs   _depsf  s    

z#_Function.from_local.<locals>._depsr{   resolverload_contextexisting_object_idc              	      s   |j sJ tj|j j |pdjrtjtdnd d}r6 D ]\}}|j| 	| q(nr>|j
	 |jj|I d H }| |j|j|j d S )Nr   r)  )app_idr}  r|  existing_function_idr~  r1  r2  )r  r   FunctionPrecreateRequestr}  raw_fr   rq   itemsmethod_definitionsCopyFromrP  rw   ru   FunctionPrecreate_hydrater   handle_metadata)r{   r  r  r  reqmethod_namemethod_definitionr   )r|  rK  r  r1  r2  rP  rr   rs   _preload  s*   
z&_Function.from_local.<locals>._preloadc                    s  t ,}.}rjrstdd}nd } rV }jd ur*tjnd }t|dkr@tdj	 dt| dt|dkrUt
dj	 dt| d nd }d }d	}	rdjrdj}	d}
jd urqjjd
k}
dd 0D }dd D dd jD B }g } ddD ]}|jstd| d|tj|jd qd }j	rtj	t1dnd }tjdci djpd	djdjd|ddd 'D drوjnd	d d|pdd|pdd d!1d"d#d$dd%t/d&|d' r jnd d(#d)|pd*d+)p|d,|d-
r"
nd	d.td/d0td1d2td2d3|	d4d5pAd*d6-pGd*d7pMd*d8pSd*d9td9d:d;tjoh  d<d=|d>d?"d@(dAt (dBt!dC&dD dE" dFdG%d ur%j#nd dHtdHdIpi dJ|
dKpd*dLddMdNd udOpd*dPpd*dQ	pd*dR$pd*dS|dT*dU+dVdW}t$t%rtj&dci d|jd|jd|jd |j'dO|j(dP|j)dR|j*d"|j+d9|j,d)|j-d+|j.dX|j/dY|j0d!|j1dZ|j2dG%d ur5%j#nd dD|j3dE|j"d;|j4d[|j5d\|j6d#|j7d$|j8dIpXi dK|j9dQ|j:dN|j;dM|j<dH|j=d2|j>dS|d?|j?dT*dU+dVdW|j@}g }tAD ](\}}t }|B| |jCBtD|!d] tj&jE||d^}|| q|jFG| d }n|jCBtD!d] |jHsJ |d u |d u ksJ tjI|jH|||pd	d_}z|jJjKL|I d H }W n ty } zd`tM|v rtdj da d }~ww |N| W d    n	1 s%w   Y  dbd D }|jOO }tP|_O| Q|jR|jJ|jS d S )dNF)shelli   rm  z
 has size z bytes when packaged. This is larger than the maximum limit of 16 MiB. Try reducing the size of the closure by using parameters or mounts, not large global variables.i   z bytes when packaged. This is larger than the recommended limit of 256 KiB. Try reducing the size of the closure by using parameters or mounts, not large global variables.r   z2024.10c                 S   &   g | ]\}}t j||jd |jdqS T)
mount_path	volume_idallow_background_commits	read_onlyr   VolumeMountr   
_read_onlyrv  pathvolumerr   rr   rs   ry        z7_Function.from_local.<locals>._load.<locals>.<listcomp>c                 S   s   h | ]}|j qS rr   r   rv  mrr   rr   rs   	<setcomp>      z6_Function.from_local.<locals>._load.<locals>.<setcomp>T)r  zDependency z isn't hydratedr  r  module_namer}  implementation_name	mount_ids
secret_idsc                 S      g | ]}|j qS rr   r  )rv  r  rr   rr   rs   ry    r  image_iddefinition_typefunction_serialized    class_serializedr|  rP  autoscaler_settingsr  method_definitions_setshared_volume_mountsvolume_mountsproxy_idrd   r   r   startup_timeout_secspty_infocloud_provider_strruntimefunction_runtimeruntime_debugfunction_runtime_debugruntime_perf_recordapp_namer\  rV  rW  rX  batch_linger_ms	worker_idr]  	is_methodcheckpointing_enabledobject_dependenciesr`  	untrustedre  
max_inputsr  r%  is_classclass_parameter_inforb  rN  snapshot_debugrg  mount_client_dependencies_experimental_group_size&_experimental_concurrent_cancellationsrh  _experimental_custom_scalingwarm_pool_sizeconcurrency_limit_experimental_buffer_containerstask_idle_timeout_secsr~  r1  r2  rj  r^  web_urlweb_url_infocustom_domain_infouse_function_iduse_method_name)r"  r#  rO  r$  rd  )rankr   )r  r   function_datar  zReceived :status = '413'z is too large to deploy.c                 S   s   h | ]}|  r|qS rr   )r   r  rr   rr   rs   r  x  s    rr   )Tr   is_interactiver   is_serializedserialized_functionuser_clsr    r   rA   r  warningswarnnamerJ  image_builder_version_mount_layersr   r   r0  r   ObjectDependencyr   rq   Functionr  r}  r  get_definition_typerJ   r?   getis_service_classr   r>   r  proto_messager   r   FunctionDatar|  r  r  r  r  r  r   r  r  r  rP  r  r  r  r  r  r  r  r  r  r  rh  r  r  r  r^  r   r  	resourcesr   RankedFunctionranked_functionsextendr  FunctionCreateRequestrw   ru   FunctionCreatero   set_responser:  	frozensetr  r   r  )r{   r  r  r  function_creation_statusr   r  r  r  r  r  r  loaded_mount_idsr  depr  r~  function_definitionr  r  _gpufunction_definition_copyranked_functionr   r   excserve_mounts2r  ri  rh  r  rL  r  rX  rY  r`  rT  r!  r  rc  r"  r_  r$  rg  r|  rO  rj  rb  r  rK  r]  r\  r^  rV  rS  r#  r  rR  objr&  rd  ra  rd   rU  rN  r%  r  re  rQ  r1  r2  tagrW  r   r  r  rP  rr   rs   _load  s`  

	
	




 !"#$%&'()*+,-.
/01345689:;=>?@AD
	
 !"#$'


  \

z#_Function.from_local.<locals>._loadz	Function()preloadr  load_context_overridesc                 S   s   g | ]}t |qS rr   )rE   )rv  r  rr   rr   rs   ry        )r  
gpu_configr  r  r!  r%  F)F_partial_functionrk  rl  get_tagr  callable
is_nullaryrA   r  get_entrypoint_mountrG   valuesr  r^   	from_dictr   ro   r   r   r(  r  r   r  rj   AutoscalerSettingsgetattrr?   r  WEBHOOK_TYPE_FUNCTIONinspect	signature
parametersdefault	Parameteremptyr9   r8   rF   interface_flagsr  r4   paramsr*  _is_web_endpointr   
_get_raw_fr3  MethodDefinitionrP  r   r  WEBHOOK_TYPE_UNSPECIFIEDr   r   r   r   _root_load_context_from_loaderrD  r9  rC  r<  r=  rF  rA  rB  r>  r'  reprrE  )FrK  rL  r  rM  r  rN  r*  rO  r  r  rP  r"  r#  r&  r   r   rQ  rR  rS  rT  rU  rV  rW  rX  rY  r!  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  re  r$  rf  rg  rh  ri  r+  rj  rk  rl  r  entrypoint_mountro  function_specfieldvalue	func_nameargvalidated_volumesinterface_methodsr  partial_functionr}  r)  method_schemamethod_input_formatsmethod_output_formatsr  r  r  repr  r   rr   r  rs   
from_local  s`  7

$ 



$
p dz_Function.from_localr  optionszmodal.cls._ServiceOptionsr   r   c              	      sh   | dt dtdtdtt f fdd}fdd}t j|d	d
|| jd}| j|_||_| j	|_	|S )zxmdmd:hidden

        Binds a class-function to a specific instance of (init params, options) or a new workspace
        param_bound_funcr  r  r  c                    s  j s I d H  jrjjsJ jr@jjtjjkr@ r%t	djj
}t|}t|| t|}tjj
dk}nddlm} t t dkoT| k}t f}|rd|  d S d urkj smJ rdd jD }	tjdi ddd jD dtjd	t|	dkd
|	dtjdtjdjdjdjdjdjdjdjdj dj!dj"dj#dj$}
nd }
tj%j&||
|j'pdd}jj(|I d H }| )|j*j|j+ d S )NzCan't use positional arguments with modal.parameter-based synthetic constructors.
Use (<parameter_name>=value) keyword arguments when constructing classes instead.r   )_ServiceOptionsc                 S   r  r  r  r  rr   rr   rs   ry    r  z=_Function._bind_parameters.<locals>._load.<locals>.<listcomp>r  c                 S   r  rr   r  )rv  srr   rr   rs   ry    r  replace_secret_idsreplace_volume_mountsr  r  replace_cloud_bucket_mountsr  rd   r  rT  r  r   rV  rW  rX  r  r%  r  r   )r   serialized_paramsfunction_optionsenvironment_namerr   ),is_hydratedhydrate_clientru   rH  formatr   ClassParameterInfo PARAM_SERIALIZATION_FORMAT_PROTOrA   schemar   r"   r!   r   	modal.clsr4  r    _hydrate_from_otherr*  FunctionOptionsr  rq   r>   r  r  rd   rS  rT  rU  r   rV  rW  rX  rY  r%  r!  FunctionBindParamsRequestr   r;  FunctionBindParamsr  bound_function_idr  )r3  r  r  r  rB  kwargs_with_defaultsr9  can_use_parentr4  r  
options_pbr  r   r   r   r2  parentrr   rs   r    s   



	


	
z)_Function._bind_parameters.<locals>._loadc                     s@    rdd  j D t j dd  jD  } dd | D S g S )Nc                 S   s   g | ]\}}|qS rr   rr   )rv  r  rx  rr   rr   rs   ry    r  z=_Function._bind_parameters.<locals>._deps.<locals>.<listcomp>c                 S   s   g | ]
\}}|j r|j qS rr   )r  )rv  r  mountrr   rr   rs   ry    s    c                 S   s   g | ]}|j s|qS rr   )r<  )rv  r  rr   rr   rs   ry    s    )r*  r   r  r  )all_deps)r2  rr   rs   r     s   z)_Function._bind_parameters.<locals>._depszFunction(parametrized)T)hydrate_lazilyr  r  )
r   r   r   r   ro   r"  _load_context_overridesr9  r=  rB  )r{   r  r2  r   r   r  r  funrr   rL  rs   _bind_parameters  s,   T
z_Function._bind_parametersrq  c                   sJ   | j rtdtj||||d}tj| j|d}| jj|I dH  dS )a  Override the current autoscaler behavior for this Function.

        Unspecified parameters will retain their current value, i.e. either the static value
        from the function decorator, or an override value from a previous call to this method.

        Subsequent deployments of the App containing this Function will reset the autoscaler back to
        its static configuration.

        Examples:

        ```python notest
        f = modal.Function.from_name("my-app", "function")

        # Always have at least 2 containers running, with an extra buffer when the Function is active
        f.update_autoscaler(min_containers=2, buffer_containers=1)

        # Limit this Function to avoid spinning up more than 5 containers
        f.update_autoscaler(max_containers=5)

        # Extend the scaledown window to increase the amount of time that idle containers stay alive
        f.update_autoscaler(scaledown_window=300)

        ```

        zTCannot call .update_autoscaler() on a method. Call it on the class instance instead.rq  )r   settingsN)	rA  rA   r   r  %FunctionUpdateSchedulingParamsRequestr   rw   ru   FunctionUpdateSchedulingParams)r{   rR  rS  rT  rU  rT  r   rr   rr   rs   update_autoscaler  s   "z_Function.update_autoscalerr  c                    s:   | j rttdtdddd | j|dI dH  dS )a  mdmd:hidden
        Set the warm pool size for the Function.

        DEPRECATED: Please adapt your code to use the more general `update_autoscaler` method instead:

        ```python notest
        f = modal.Function.from_name("my-app", "function")

        # Old pattern (deprecated)
        f.keep_warm(2)

        # New pattern
        f.update_autoscaler(min_containers=2)
        ```
        a.  
                The `.keep_warm()` method can not be used on Modal class *methods*.

                Call `.keep_warm()` on the class *instance* instead. All methods of a class are run by the same
                container pool, and this method applies to the size of that container pool.
            )     rY  zwThe .keep_warm() method has been deprecated in favor of the more general .update_autoscaler(min_containers=...) method.T)show_source)rR  N)rA  rA   textwrapdedentr,   rW  )r{   r  rr   rr   rs   	keep_warmH  s   z_Function.keep_warmr  r  r  c             	      sf   dt dtdtdtt f fdd}|jrd|jnd}d	  d
 d| d}| j||dd|dS )Nr{   r  r  r  c                    s   t j |jd}z|jj|I d H }W n* ty@ } z|jr(d|j dnd}td d  d| d| d		d d }~ww t|j | 	|j
|j|j d S )
N)r  
object_tagr;  z
 (in the 'z' environment)r   zLookup failed for Function 'z' from the 'z' appz: r  )r   FunctionGetRequestr;  rw   ru   FunctionGetrB   r#   server_warningsr  r   r  )r{   r  r  r  r   r   r   env_contextr  r  rr   rs   _load_remotew  s(   
	z*_Function._from_name.<locals>._load_remotez, environment_name=r   zmodal.Function.from_name('z', 'rn  rp  T)is_another_apprP  r  )r   r   r   r   ro   _environment_namer;  r"  )clsr  r  r  rd  environment_repr0  rr   rc  rs   
_from_namem  s"   

z_Function._from_name)	namespacer;  rw   rg  r;  rw   c                C   sd   d|v r!| dd\}}tdd| d| d| d| d| d	 t|d
 | j||t||ddS )a<  Reference a Function from a deployed App by its name.

        This is a lazy method that defers hydrating the local
        object with metadata from Modal servers until the first
        time it is actually used.

        ```python
        f = modal.Function.from_name("other-app", "function")
        ```
        r  r   )rX        zLooking up class methods using Function.from_name will be deprecated in a future version of Modal.
Use modal.Cls.from_name instead, e.g.

z = modal.Cls.from_name("z", "z")
instance = z(...)
instance.z.remote(...)
zmodal.Function.from_name)r;  rw   )r  )splitr,   r-   ri  r   )rg  r  r  rj  r;  rw   
class_namer  rr   rr   rs   	from_name  s(   
	z_Function.from_namec                 C      | j sJ | j S mdmd:hidden)rC  r{   rr   rr   rs   r       
z_Function.tagc                 C   s   | j du r	td| j S )rr  Nz;The app has not been assigned on the function at this point)r<  r@   rs  rr   rr   rs   rL    s   
z_Function.appc                 C   r   rq  )rL  rs  rr   rr   rs   ru     s   z_Function.stubc                 C   rp  rq  r9  rs  rr   rr   rs   rK    rt  z_Function.infoc                 C   rp  rq  )rB  rs  rr   rr   rs   spec  rt  z_Function.specc                 C   s   t | jo
| jjtjkS ry   )rq   r>  r  r   r   rs  rr   rr   rs   r    s   z_Function._is_web_endpointc                 C   s>   t | drt | dr| jdusJ t| j dt| j S )rr  rD  rE  N
)hasattrrD  r  	getsourcer#  rE  rs  rr   rr   rs   get_build_def  s   "z_Function.get_build_defc                 C   s6   d | _ d | _d | _d | _d | _t | _d | _d | _d S ry   )		_progressrF  r?  r@  r9  r  r:  rJ  _experimental_flash_urlsrs  rr   rr   rs   _initialize_from_empty  s   
z _Function._initialize_from_emptyr   c                 C   s   |rt |tjsJ t| d|| _|jtjjk| _|j	| _
|j| _|j| _|j| _|j| _t|j| _|j| _|j| _|j| _|drJ|jnt| _|j | _ d S )Nz is not FunctionHandleMetadatamax_object_size_bytes)!r   r   FunctionHandleMetadatar  rJ  r|  r  FUNCTION_TYPE_GENERATORrF  r  r?  r}  r@  r  rA  r  rG  r  rH  r'  method_handle_metadatarI  definition_id_definition_idr   _input_plane_urlr   _input_plane_regionr   r~  r+   _max_object_size_bytesr|  )r{   r   rr   rr   rs   _hydrate_metadata  s"   z_Function._hydrate_metadatac                 C   s   | j s
J d|  tj| j t| j| jpd| j| j| j| j	| j
| jr'| jjnd | j| j| j| j| jr7| jjng | jrA| jjdS g dS )Nz?Function name must be set before metadata can be retrieved for r   )r}  r|  r  r  r  r  r  r  r~  r   r   r~  r|  r1  r2  )r@  r   r  r4   rF  r?  rG  rA  rH  r  rI  rJ  r~  r  r  r  r|  r1  r2  rs  rr   rr   rs   r    s(   z_Function._get_metadatafn_namec                 C   s0   | j rtd| d| j  dd| j d d S )NzAA webhook function cannot be invoked for remote execution with `.z)`. Invoke this function via its web url 'z' zor call it locally: z.local())r?  rA   r@  )r{   r  rr   rr   rs   _check_no_web_url%  s   z_Function._check_no_web_urlc                    s   d}t d|dd | jS )zmdmd:hidden
        Deprecated. Use the `Function.get_web_url()` method instead.

        URL of a Function running as a web endpoint.
        z}The Function.web_url property will be removed in a future version of Modal.
Use the `Function.get_web_url()` method instead.
)rX  rY     T)pending)r,   r?  )r{   deprecation_msgrr   rr   rs   r  .  s   z_Function.web_urlc                    s   | j S )z,URL of a Function running as a web endpoint.)r?  rs  rr   rr   rs   get_web_url<  s   z_Function.get_web_urlc                    s   | j r	t| j S dS )z*URL of the flash service for the function.N)r|  r   rs  rr   rr   rs   _experimental_get_flash_urlsA  s   z&_Function._experimental_get_flash_urlsc                    s4   | j dur	| j S |  I dH  | j dusJ | j S )rr  N)rF  r=  rs  rr   rr   rs   r*  F  s   
z_Function.is_generatorinput_queueorder_outputsreturn_exceptionswrap_returned_exceptionsc              
   C  s  |  d | jrtd| jsJ t j| jdd}| jrVtt	| || j
||||4 I dH }|2 z	3 dH W }|V  q36 W d  I dH  dS 1 I dH sOw   Y  dS tt| || j
||||tj4 I dH }|2 z	3 dH W }|V  ql6 W d  I dH  dS 1 I dH sw   Y  dS )a  mdmd:hidden

        Synchronicity-wrapped map implementation. To be safe against invocations of user code in
        the synchronicity thread it doesn't accept an [async]iterator, and instead takes a
          _SynchronizedQueue instance that is fed by higher level functions like .map()

        _SynchronizedQueue is used instead of asyncio.Queue so that the main thread can put
        items in the queue safely.
        mapz7A generator function cannot be called with `.map(...)`.N)total)r  rF  rA   r@  rK   r  function_progress_callbackr  r%   rR   rw   rQ   r   r   )r{   r  r  r  r  count_update_callbackstreamrh   rr   rr   rs   _mapT  sP   


..z_Function._mapz_FunctionCall[ReturnType]c                    sV   |  d | jrtd| jsJ t| || jI d H \}}t|| jd }||_|S )N	spawn_mapz=A generator function cannot be called with `.spawn_map(...)`.)	r  rF  rA   r@  rU   rw   _FunctionCall_new_hydrated_num_inputs)r{   r  rv   
num_inputsfcrr   rr   rs   
_spawn_map  s   

z_Function._spawn_mapc                    sX   | j rtj| ||| j| j | jdI d H }ntj| ||| jtjdI d H }| I d H S N)rw   r   r   )rw   rc   )	r  r   r   rw   r  rt   r   r   r   )r{   r   r   
invocationrr   rr   rs   _call_function  s$   	z_Function._call_functionrc   rb   r~   c                    s    t j| ||| j||dI d H S )N)rw   rc   r~   )rt   r   rw   )r{   r   r   rc   r~   rr   rr   rs   _call_function_nowait  s   z_Function._call_function_nowaitc                 C  sl   | j rtj| ||| j| j | jdI d H }ntj| ||| jtjdI d H }| 2 z	3 d H W }|V  q)6 d S r  )	r  r   r   rw   r  rt   r   )FUNCTION_CALL_INVOCATION_TYPE_SYNC_LEGACYr   )r{   r   r   r  resrr   rr   rs   _call_generator  s(   	z_Function._call_generatorc                    s,   |  d | jrtd| ||I dH S )zz
        Calls the function remotely, executing it with the given arguments and returning the execution's result.
        remotezZA generator function cannot be called with `.remote(...)`. Use `.remote_gen(...)` instead.N)r  rF  rA   r  r{   r   r   rr   rr   rs   r    s   
z_Function.remotec                 O  s@   |  d | jstd| ||2 z	3 dH W }|V  q6 dS )z{
        Calls the generator remotely, executing it with the given arguments and returning the execution's result.
        
remote_genz^A non-generator function cannot be called with `.remote_gen(...)`. Use `.remote(...)` instead.N)r  rF  rA   r  )r{   r   r   rh   rr   rr   rs   r    s   
z_Function.remote_genc                 C   s
   | j d uS ry   ru  rs  rr   rr   rs   	_is_local  s   
z_Function._is_localc                 C   s   | j std| j S )Nz8Can't get info for a function that isn't locally defined)r9  r@   rs  rr   rr   rs   	_get_info  s   z_Function._get_infoc                 C   s   | j sd S | jstd| jS )NzMethod has no local object)rA  r=  r@   rs  rr   rr   rs   _get_obj   s
   z_Function._get_objc                    s   |   s
d}t||  }|jstdt r| jjs | jjr,t	d|j
 dd  |  s<|j i S  }|j|t|jrW fdd}| S    i S )a  
        Calls the function locally, executing it with the given arguments and returning the execution's result.

        The function will execute in the same environment as the caller, just like calling the underlying function
        directly in Python. In particular, only secrets available in the caller environment will be available
        through environment variables.
        zThe definition for this Function is missing, so it is not possible to invoke it locally. If this function was retrieved via `Function.from_name`, you need to use one of the remote invocation methods instead.z%Can't call .local on service functionzThe z function is executing locally zHand will not have access to the mounted Volume or NetworkFileSystem datac                      s$     I d H   i I d H S ry   )_aenterrr   r   rR  r   r  rr   rs   coro4  s   z_Function.local.<locals>.coro)r  r@   r  r  r   rv  r  r  r  r  r}  r  _cached_user_cls_instance__get__r5   _enter)r{   r   r   r  rK  user_cls_instancer  rr   r  rs   local  s0   
z_Function.localc                    s`   |  d | jrtd| j||tjdI dH }t|j|j	d}| jr+| j|_|S d|_|S )a  [Experimental] Calls the function with the given arguments, without waiting for the results.

        This experimental version of the spawn method allows up to 1 million inputs to be spawned.

        Returns a `modal.FunctionCall` object, that can later be polled or
        waited for using `.get(timeout=...)`.
        Conceptually similar to `multiprocessing.pool.apply_async`, or a Future/Promise in other contexts.
        _experimental_spawn$Cannot `spawn` a generator function.)rc   NF
r  rF  rA   r  r   #FUNCTION_CALL_INVOCATION_TYPE_ASYNCr  r  rv   rw   r{   r   r   r  r  rr   rr   rs   r  =  s   

z_Function._experimental_spawnc                    s8   |  d | jrtd| j||tjddI d H  d S )Nr  z-Cannot `spawn_map` over a generator function.Tr}   )r  rF  r   r  r   r  r  rr   rr   rs   _spawn_map_innerV  s
   
z_Function._spawn_map_innerc                    sF   |  d | jrtd| ||tjI dH }t|j|j	d}|S )a  Calls the function with the given arguments, without waiting for the results.

        Returns a [`modal.FunctionCall`](https://modal.com/docs/reference/modal.FunctionCall) object
        that can later be polled or waited for using
        [`.get(timeout=...)`](https://modal.com/docs/reference/modal.FunctionCall#get).
        Conceptually similar to `multiprocessing.pool.apply_async`, or a Future/Promise in other contexts.
        spawnr  Nr  r  rr   rr   rs   r  _  s   


z_Function.spawnc                 C   s   | j dusJ | j S )z>Return the inner Python object wrapped by this Modal Function.N)rD  rs  rr   rr   rs   	get_raw_ft  s   z_Function.get_raw_fc                    s:   | j jjtj| jdtdddI dH }t|j|j	dS )zZReturn a `FunctionStats` object describing the current function's queue and runner counts.)r   g      $@)total_timeoutr   N)r  r  )
rw   ru   FunctionGetCurrentStatsr   FunctionGetCurrentStatsRequestr   r6   r  r  num_total_tasks)r{   resprr   rr   rs   get_current_statsy  s   z_Function.get_current_statsc                    s   | j sJ | j jS )z?Returns recorded schema for function, internal use only for now)rJ  r~  rs  rr   rr   rs   _get_schema  s   
z_Function._get_schema)r   r;  r
  )|rj   rk   rl   r   r   r0   rm   r  rH   r<  r=  r>  r   WebhookConfigro   rq   rB  r  r   r	   r'  rF  rG  rH  rI  rJ  r  r   rF   r   r^   r]   r   rD   r   r   rI   r_   r=   r   r  r   rZ   r[   r   
HTTPConfigr1  r   rS  r   rW  r]  classmethodr   ri  r  r<   ro  propertyr  rL  ru   rK  rv  r  rz  r}  r   r  r  r  r  r  r  r*  r   rY   r   r  r  r5  r  rt   r  r*   r)   no_input_translationr  no_io_translationr4  r   r   r  r  r  r  r  nowrapr7  r  r  r  r  r  r  r  FunctionSchemar  r   rS   rP   r  rX   rW   starmaprO   rN   for_eachrV   rT   r  rM   rL   experimental_spawn_maprr   rr   rr   rs   r   m  sP  
 

 !"#$&'()*+,-./0    

y0$*#		
5
4	r   fu)type_prefixc                	   @   s  e Zd ZU dZdZeed< dZee	 ed< dd Z
ede	fd	d
Zed'dddee de	defddZedddde	dee	 dee fddZedee fddZe	d(defddZedde	d'deded dd fd!d"Zed#d$deje fd%d&ZdS ))r  a  A reference to an executed function call.

    Constructed using `.spawn(...)` on a Modal function with the same
    arguments that a function normally takes. Acts as a reference to
    an ongoing function call that can be passed around and used to
    poll or fetch function results at some later time.

    Conceptually similar to a Future/Promise/AsyncResult in other contexts and languages.
    FrF  Nr  c                 C   s   t | jj| j| jS ry   )rt   rw   ru   r   rs  rr   rr   rs   _invocation  s   z_FunctionCall._invocationr   c                    s<   | j du rtj| jd}| jj|I dH }|j| _ | j S )z.Get the number of inputs in the function call.Nrv   )r  r   FunctionCallFromIdRequestr   rw   ru   FunctionCallFromIdr  )r{   r   r  rr   rr   rs   r    s   
z_FunctionCall.num_inputsr   r   r   r   c                   s   |   j||dI dH S )a  Get the result of the index-th input of the function call.
        `.spawn()` calls have a single output, so only specifying `index=0` is valid.
        A non-zero index is useful when your function has multiple outputs, like via `.spawn_map()`.

        This function waits indefinitely by default. It takes an optional
        `timeout` argument that specifies the maximum number of seconds to wait,
        which can be set to `0` to poll for an output immediately.

        The returned coroutine is not cancellation-safe.
        )r   r   N)r  r   )r{   r   r   rr   rr   rs   r    s   z_FunctionCall.get)startendr  r  c                C  sx   |   I dH }|du r|}|dk s||kr$td| d| d| d|  j||d2 z3 dH W \}}|V  q-6 dS )a  Iterate in-order over the results of the function call.

        Optionally, specify a range [start, end) to iterate over.

        Example:
        ```python
        @app.function()
        def my_func(a):
            return a ** 2


        @app.local_entrypoint()
        def main():
            fc = my_func.spawn_map([1, 2, 3, 4])
            assert list(fc.iter()) == [1, 4, 9, 16]
            assert list(fc.iter(start=1, end=3)) == [4, 9]
        ```

        If `end` is not provided, it will iterate over all results.
        Nr   zInvalid index range: z to z for z inputs)r   r   )r  r   r  r   )r{   r  r  r  r  rh   rr   rr   rs   iter  s   "z_FunctionCall.iterc                    s>   | j r| j js
J tj| jd}| j j|I dH }t|S )a?  Returns a structure representing the call graph from a given root
        call ID, along with the status of execution for each node.

        See [`modal.call_graph`](https://modal.com/docs/reference/modal.call_graph) reference page
        for documentation on the structure of the returned `InputInfo` items.
        r  N)r>  ru   r   FunctionGetCallGraphRequestr   FunctionGetCallGraphr;   )r{   r   r   rr   rr   rs   get_call_graph  s
   z_FunctionCall.get_call_graphterminate_containersc                    s<   t j| j|d}| jr| jjsJ | jj|I dH  dS )a  Cancels the function call, which will stop its execution and mark its inputs as
        [`TERMINATED`](https://modal.com/docs/reference/modal.call_graph#modalcall_graphinputstatus).

        If `terminate_containers=True` - the containers running the cancelled inputs are all terminated
        causing any non-cancelled inputs on those containers to be rescheduled in new containers.
        )rv   r  N)r   FunctionCallCancelRequestr   r>  ru   FunctionCallCancel)r{   r  r   rr   rr   rs   cancel  s   z_FunctionCall.cancel)rX  rl     zFunctionCall.from_idrv   rw   zmodal.client.Client!modal.functions.FunctionCall[Any]c              	      sj   t tt|}dtdtdtdtt	 f fdd}d d}tj
||d	t|d
d}t dt|S )a5  Instantiate a FunctionCall object from an existing ID.

        Examples:

        ```python notest
        # Spawn a FunctionCall and keep track of its object ID
        fc = my_func.spawn()
        fc_id = fc.object_id

        # Later, use the ID to re-instantiate the FunctionCall object
        fc = FunctionCall.from_id(fc_id)
        result = fc.get()
        ```

        Note that it's only necessary to re-instantiate the `FunctionCall` with this method
        if you no longer have access to the original object returned from `Function.spawn`.

        r{   r  r  r  c                    s   |   |jd  d S ry   )r  rw   )r{   r  r  r  r  rr   rs   r    s   z$_FunctionCall.from_id.<locals>._loadzFunctionCall.from_id(rp  T)rw   )rP  r  r  )typingcastr<   r)   _translate_inr  r   r   r   ro   r"  _translate_out)rg  rv   rw   r>  r  r0  impl_instancerr   r  rs   from_id  s   z_FunctionCall.from_idfunction_callsz_FunctionCall[T]c               
      s<   zt jdd | D  I dH W S  ty } z|d}~ww )aV  Wait until all Modal FunctionCall objects have results before returning.

        Accepts a variable number of `FunctionCall` objects, as returned by `Function.spawn()`.

        Returns a list of results from each FunctionCall, or raises an exception
        from the first failing function call.

        Examples:

        ```python notest
        fc1 = slow_func_1.spawn()
        fc2 = slow_func_2.spawn()

        result_1, result_2 = modal.FunctionCall.gather(fc1, fc2)
        ```

        *Added in v0.73.69*: This method replaces the deprecated `modal.functions.gather` function.
        c                 S   s   g | ]}|  qS rr   )r  )rv  r  rr   rr   rs   ry  2  r  z(_FunctionCall.gather.<locals>.<listcomp>N)r$   gatherr   )r  r   rr   rr   rs   r    s   z_FunctionCall.gatherry   r
  ) rj   rk   rl   r   rF  rq   rm   r  r   r   r  r   r  r   r5  r  r   r
   r  r   r:   r  r  r(   r  ro   r  r   r  r   r8  r  rr   rr   rr   rs   r    s<   
 
$(#r  r  r  c                     s   t dd tj|  I dH S )zMmdmd:hidden
    Deprecated: Please use `modal.FunctionCall.gather()` instead.)rX  rk     z[`modal.functions.gather()` is deprecated; please use `modal.FunctionCall.gather()` instead.N)r,   r  r  )r  rr   rr   rs   _gather8  s   r  )r   )r   dataclassesr  r[  r   r  r  collections.abcr   r   r   r   r   pathlibr   r   r	   r
   r   r   r   typing_extensionsgoogle.protobuf.messager   grpclibr   synchronicity.combined_typesr   modal_protor   modal_proto.modal_api_grpcr   _load_contextr   _objectr   r   r   _output.ptyr   _output.statusr   	_resolverr   
_resourcesr   _runtime.execution_contextr   r   _serializationr   r   r    r!   r"   
_tracebackr#   _utils.async_utilsr$   r%   r&   r'   r(   r)   r*   _utils.blob_utilsr+   _utils.deprecationr,   r-   _utils.function_utilsr.   r/   r0   r1   r2   r3   r4   r5   _utils.grpc_utilsr6   r7   _utils.mount_utilsr8   r9   
call_graphr:   r;   rw   r<   r  r=   r>   r?   	exceptionr@   rA   rB   rC   rO  rD   rE   r  rF   rN  rG   rH   network_file_systemrI   rJ   r   rK   parallel_maprL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   r&  rZ   r   r[   r\   rN  r]   r  r^   r  r_   	modal.appmodalrC  modal.functionsr   r   GENERIC_STATUS_SUCCESSGENERIC_STATUS_TERMINATEDr   ra   rt   r   r  r   ro   rn   r  r  rq   r3  	ParamSpecr4  TypeVarr5  r7  r8  Genericr   r  r  rr   rr   rr   rs   <module>   s    $	(
@
   	

"          0  &