o
    i                  	   @  s  d Z ddlmZ ddlZddlZddlmZmZm	Z	m
Z
mZ ddlmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZmZmZmZ ddlm Z m!Z!m"Z" dd	l#m$Z$ dd
l%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZE ddlFmGZG ddlHmIZI ddlJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZSmTZTmUZU ddlVmWZW ddlXmYZYmZZZ ej[dk rddl\m]Z] ne]Z]erddl^m_Z_ e)dddZ`	 e)dddZa	 e)dddZb	 e)d ddZc	 ed!d"G d#d$ d$eec ZdeG d%d& d&Zeed!d'G d(d) d)ee`eaebecf ZfeG d*d+ d+ZgG d,d- d-ee`eaecf ZheG d.d/ d/ZieG d0d1 d1ZjeG d2d3 d3ee`eaecf Zkd?d8d9Zld@d;d<Zmed=d> ZndS )Aa  Core graph execution engine for the next version of the pydantic-graph library.

This module provides the main `Graph` class and `GraphRun` execution engine that
handles the orchestration of nodes, edges, and parallel execution paths in
the graph-based workflow system.
    )annotationsN)AsyncGeneratorAsyncIterableAsyncIteratorIterableSequence)AbstractContextManagerAsyncExitStack	ExitStackasynccontextmanagercontextmanager)	dataclassfield)	TYPE_CHECKINGAnyGenericLiteral	TypeGuardcastget_args
get_originoverload)CancelScopecreate_memory_object_streamcreate_task_group)	TaskGroup)MemoryObjectReceiveStreamMemoryObjectSendStream)TypeVarassert_never)
exceptions)AbstractSpanget_traceparentinfer_obj_namelogfire_span)Decision)ForkID	ForkStackForkStackItem
GraphRunIDJoinIDNodeID	NodeRunIDTaskID)JoinJoinNode	JoinStateReducerContext)EndNodeFork	StartNode)AnyNode)
ParentFork)BroadcastMarkerDestinationMarkerLabelMarker	MapMarkerPathTransformMarker)NodeStepStepStepContextStepNode)unpack_type_expression)BaseNodeEnd)      )ExceptionGroup)StateDiagramDirectionStateTT)infer_varianceDepsTInputTOutputTFinitc                   @  s4   e Zd ZU dZded< 	 dddZeddd	Zd
S )	EndMarkera  A marker indicating the end of graph execution with a final value.

    EndMarker is used internally to signal that the graph has completed
    execution and carries the final output value.

    Type Parameters:
        OutputT: The type of the final output value
    rL   _valuevaluec                 C  s
   || _ d S NrP   selfrQ    rV   _/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_graph/beta/graph.py__init__R   s   
zEndMarker.__init__returnc                 C  s   | j S rR   rS   rU   rV   rV   rW   rQ   V   s   zEndMarker.valueN)rQ   rL   )rY   rL   )__name__
__module____qualname____doc____annotations__rX   propertyrQ   rV   rV   rV   rW   rO   D   s   
 	
rO   c                   @  s.   e Zd ZU dZded< 	 ded< 	 ded< dS )	JoinItemzAn item representing data flowing into a join operation.

    JoinItem carries input data from a parallel execution path to a join
    node, along with metadata about which execution 'fork' it originated from.
    r*   join_idr   inputsr'   
fork_stackN)r[   r\   r]   r^   r_   rV   rV   rV   rW   ra   [   s   
 ra   reprc                      s   e Zd ZU dZded< 	 ded< 	 ded< 	 ded	< 	 d
ed< 	 ded< 	 ded< 	 ded< 	 ded< 	 ded< 	 d;ddZd<ddZdddddd d=d+d,Zedddddd d>d.d/Z	ddd0d?d5d6Z
d@ fd7d8Zd@d9d:Z  ZS )AGrapha  A complete graph definition ready for execution.

    The Graph class represents a complete workflow graph with typed inputs,
    outputs, state, and dependencies. It contains all nodes, edges, and
    metadata needed for execution.

    Type Parameters:
        StateT: The type of the graph state
        DepsT: The type of the dependencies
        InputT: The type of the input data
        OutputT: The type of the output data
    
str | Nonenameztype[StateT]
state_typeztype[DepsT]	deps_typeztype[InputT]
input_typeztype[OutputT]output_typeboolauto_instrumentzdict[NodeID, AnyNode]nodeszdict[NodeID, list[Path]]edges_by_sourcez dict[JoinID, ParentFork[NodeID]]parent_forkszdict[JoinID, set[JoinID]]intermediate_join_nodesrb   r*   rY   ParentFork[NodeID]c                 C  s(   | j |}|du rtd| d|S )a  Get the parent fork information for a join node.

        Args:
            join_id: The ID of the join node

        Returns:
            The parent fork information for the join

        Raises:
            RuntimeError: If the join ID is not found or has no parent fork
        NzNode zE is not a join node or did not have a dominating fork (this is a bug))rr   getRuntimeError)rU   rb   resultrV   rV   rW   get_parent_fork   s   zGraph.get_parent_forkc                 C  s"   | j  D ]	}||v r dS qdS )a\  Check if a join is 'final' (has no downstream joins with the same parent fork).

        A join is non-final if it appears as an intermediate node for another join
        with the same parent fork.

        Args:
            join_id: The ID of the join node

        Returns:
            True if the join is final, False if it's non-final
        FT)rs   values)rU   rb   intermediate_joinsrV   rV   rW   is_final_join   s
   zGraph.is_final_joinNTstatedepsrc   span
infer_namer}   rH   r~   rJ   rc   rK   r   +AbstractContextManager[AbstractSpan] | Noner   rL   c          	   	     s   |r| j du rt| dd}|dur|| _ | j||||dd4 I dH 4}d}	 z
||I dH }W n$ tyU   t|tsAJ dttt |j	 Y W  d  I dH  S w q'1 I dH s]w   Y  dS )a*  Execute the graph and return the final output.

        This is the main entry point for graph execution. It runs the graph
        to completion and returns the final output value.

        Args:
            state: The graph state instance
            deps: The dependencies instance
            inputs: The input data for the graph
            span: Optional span for tracing/instrumentation
            infer_name: Whether to infer the graph name from the calling frame.

        Returns:
            The final output from the graph execution
        N   depthFr|   Tz'Graph run should end with an EndMarker.)
ri   r#   iternextStopAsyncIteration
isinstancerO   r   rL   rQ   )	rU   r}   r~   rc   r   r   inferred_name	graph_runeventrV   rV   rW   run   s"   z	Graph.run/AsyncIterator[GraphRun[StateT, DepsT, OutputT]]c             
   C s   |r| j du rt| dd}|dur|| _ t ^}d}|du r,| jr+|td| d}n||}|du r7dnt|}	ttt	t
f | ||||	d4 I dH }
|
V  W d  I dH  n1 I dH saw   Y  W d   dS W d   dS 1 syw   Y  dS )aR  Create an iterator for step-by-step graph execution.

        This method allows for more fine-grained control over graph execution,
        enabling inspection of intermediate states and results.

        Args:
            state: The graph state instance
            deps: The dependencies instance
            inputs: The input data for the graph
            span: Optional span for tracing/instrumentation
            infer_name: Whether to infer the graph name from the calling frame.

        Yields:
            A GraphRun instance that can be iterated for step-by-step execution
        NrD   r   zrun graph {graph.name})graph)r   r}   r~   rc   traceparent)ri   r#   r
   ro   enter_contextr$   r"   GraphRunrH   rJ   rL   )rU   r}   r~   rc   r   r   r   stackentered_spanr   r   rV   rV   rW   r      s4   
*"z
Graph.itertitle	directionr   r   StateDiagramDirection | Nonestrc                C  s$   ddl m} || j| jj||dS )a  Render the graph as a Mermaid diagram string.

        Args:
            title: Optional title for the diagram
            direction: Optional direction for the diagram layout

        Returns:
            A string containing the Mermaid diagram representation
        r   )build_mermaid_graphr   )pydantic_graph.beta.mermaidr   rp   rq   render)rU   r   r   r   rV   rV   rW   r     s   
zGraph.renderc                   s*   t   }|d d  d|  d|d  S )N
)super__repr__)rU   
super_repr	__class__rV   rW   r   &  s   
 zGraph.__repr__c                 C  s   |   S )zReturn a Mermaid diagram representation of the graph.

        Returns:
            A string containing the Mermaid diagram of the graph
        )r   rZ   rV   rV   rW   __str__+  s   zGraph.__str__)rb   r*   rY   rt   )rb   r*   rY   rn   )r}   rH   r~   rJ   rc   rK   r   r   r   rn   rY   rL   )r}   rH   r~   rJ   rc   rK   r   r   r   rn   rY   r   )r   rh   r   r   rY   r   rY   r   )r[   r\   r]   r^   r_   rx   r{   r   r   r   r   r   r   __classcell__rV   rV   r   rW   rg   m   sP   
 

).rg   c                   @  sR   e Zd ZU dZded< 	 ded< 	 eddZded	< 	 ed
d ddZded< dS )	GraphTaskzA single task representing the execution of a node in the graph.

    GraphTask encapsulates all the information needed to execute a specific
    node, including its inputs and the fork context it's executing within.
    r+   node_idr   rc   Fre   r'   rd   c                   C  s   t tt S rR   )r-   r   uuiduuid4rV   rV   rV   rW   <lambda>I  s    zGraphTask.<lambda>)default_factoryrf   r-   task_idN)r[   r\   r]   r^   r_   r   rd   r   rV   rV   rV   rW   r   4  s   
 r   c                   @  s   e Zd ZdZd3ddZdd Zd4ddZedd Ze	d5ddZ
e	d6ddZ
dd d7d"dZ
d8d$d%Zd9d'd(Z	)d:d;d,d-Zed9d.d/Zed<d1d2Zd)S )=r   aZ  A single execution instance of a graph.

    GraphRun manages the execution state for a single run of a graph,
    including task scheduling, fork/join coordination, and result tracking.

    Type Parameters:
        StateT: The type of the graph state
        DepsT: The type of the dependencies
        OutputT: The type of the output data
    r   %Graph[StateT, DepsT, InputT, OutputT]r}   rH   r~   rJ   rc   rK   r   rh   c                C  s   || _ 	 || _	 || _	 || _	 i | _	 d| _	 ttt	 }t
tjt|df}ttj||d| _t | _ttttf | j | j| j| j| _| j| j| _|| _t | _dS )a#  Initialize a graph run.

        Args:
            graph: The graph to execute
            state: The graph state instance
            deps: The dependencies instance
            inputs: The input data for the graph
            traceparent: Optional trace parent for instrumentation
        Nr   )r   rc   rd   )r   r}   r~   rc   _active_reducers_nextr)   r   r   r   r(   r4   idr,   r   _first_taskr   _iterator_task_group_GraphIteratorrH   rJ   rL   _iterator_instance
iter_graph	_iterator_GraphRun__traceparentr	   _async_exit_stack)rU   r   r}   r~   rc   r   run_idinitial_fork_stackrV   rV   rW   rX   Y  s,   zGraphRun.__init__c                   s>   | j t  | j | jI d H  | j |  I d H  | S rR   )r   r   _unwrap_exception_groupsenter_async_contextr   _iterator_contextrZ   rV   rV   rW   
__aenter__  s
   zGraphRun.__aenter__exc_typer   exc_valexc_tbc                   s   | j |||I d H  d S rR   )r   	__aexit__)rU   r   r   r   rV   rV   rW   r     s   zGraphRun.__aexit__c                 C sb   zd V  W | j j  | j j  | j I d H  d S | j j  | j j  | j I d H  w rR   )r   iter_stream_sendercloseiter_stream_receiverr   acloserZ   rV   rV   rW   r     s   zGraphRun._iterator_contextrequiredLiteral[False]rY   c                C     d S rR   rV   rU   r   rV   rV   rW   _traceparent     zGraphRun._traceparentr   c                 C  r   rR   rV   rZ   rV   rV   rW   r     r   T)r   rn   c                C  s   | j du r|rtd| j S )aB  Get the trace parent for instrumentation.

        Args:
            required: Whether to raise an error if no traceparent exists

        Returns:
            The traceparent string, or None if not required and not set

        Raises:
            GraphRuntimeError: If required is True and no traceparent exists
        Nz&No span was created for this graph run)r   r    GraphRuntimeErrorr   rV   rV   rW   r     s   
7AsyncIterator[EndMarker[OutputT] | Sequence[GraphTask]]c                 C  s   | S )zaReturn self as an async iterator.

        Returns:
            Self for async iteration
        rV   rZ   rV   rV   rW   	__aiter__  s   zGraphRun.__aiter__(EndMarker[OutputT] | Sequence[GraphTask]c                   s@   | j du rt| jI dH | _ | j S | j| j I dH | _ | j S )zyGet the next item in the async iteration.

        Returns:
            The next execution result from the graph
        N)r   anextr   asendrZ   rV   rV   rW   	__anext__  s   
zGraphRun.__anext__NrQ   /EndMarker[OutputT] | Sequence[GraphTask] | Nonec                   s6   | j du rt| I dH  |dur|| _ t| I dH S )av  Advance the graph execution by one step.

        This method allows for sending a value to the iterator, which is useful
        for resuming iteration or overriding intermediate results.

        Args:
            value: Optional value to send to the iterator

        Returns:
            The next execution result: either an EndMarker, or sequence of GraphTasks
        N)r   r   rT   rV   rV   rW   r     s   
zGraphRun.nextc                 C  s   | j p| jgS )zGet the next task(s) to be executed.

        Returns:
            The next execution item, or the initial task if none is set
        )r   r   rZ   rV   rV   rW   	next_task  s   zGraphRun.next_taskOutputT | Nonec                 C  s   t | jtr
| jjS dS )zGet the final output if the graph has completed.

        Returns:
            The output value if execution is complete, None otherwise
        N)r   r   rO   rQ   rZ   rV   rV   rW   output  s   zGraphRun.output)
r   r   r}   rH   r~   rJ   rc   rK   r   rh   )r   r   r   r   r   r   )r   r   rY   rh   r   )r   rn   rY   rh   )rY   r   )rY   r   rR   )rQ   r   rY   r   )rY   r   )r[   r\   r]   r^   rX   r   r   r   r   r   r   r   r   r   r`   r   r   rV   rV   rV   rW   r   M  s(    
0



r   c                   @  s   e Zd ZU ded< ded< dS )_GraphTaskAsyncIterablez"AsyncIterable[Sequence[GraphTask]]iterabler'   rd   N)r[   r\   r]   r_   rV   rV   rV   rW   r     s   
 r   c                   @  s*   e Zd ZU ded< ded< dZded< dS )	_GraphTaskResultr   sourcez/EndMarker[Any] | Sequence[GraphTask] | JoinItemrw   Trn   source_is_finishedN)r[   r\   r]   r_   r   rV   rV   rV   rW   r     s   
 r   c                   @  s  e Zd ZU ded< ded< ded< ded< ed	d
Zded< ed	d
Zded< ed	d
Zded< ed	d
Zded< ed	d
Z	ded< dd Z
d[ddZd\d d!Zd]d$d%Zd^d'd(Zd_d+d,Zd`d3d4Zdad8d9Zdbd=d>ZdcdAdBZdddFdGZdedHdIZdfdKdLZdgdSdTZdhdXdYZdZS )ir   z"Graph[StateT, DepsT, Any, OutputT]r   rH   r}   rJ   r~   r   
task_groupFrM   zdict[TaskID, CancelScope]cancel_scopeszdict[TaskID, GraphTask]active_tasksz)dict[tuple[JoinID, NodeRunID], JoinState]active_reducersz(MemoryObjectSendStream[_GraphTaskResult]r   z+MemoryObjectReceiveStream[_GraphTaskResult]r   c                 C  s(   i | _ i | _i | _tt  \| _| _d S rR   )r   r   r   r   r   r   r   rZ   rV   rV   rW   __post_init__  s   z_GraphIterator.__post_init__
first_taskr   rY   bAsyncGenerator[EndMarker[OutputT] | Sequence[GraphTask], EndMarker[OutputT] | Sequence[GraphTask]]c              
   C s  | j 4 I d H  z|| j|j< | |g | j4 I d H  | js(| jr| j2 zz3 d H W }t|jtr<|j}n|jV }t|t	rn| 
|jjI d H  | jrX| jj   W d   I d H  W W d   I d H  d S t|tr|}| j|jj}t|jd d d D ]%\}}|j|kr| j|jr|jd t|j|  }n|j}|j}	 nqtd| jj|j }
t|
tsJ d|
 | j|j|	f}|d u r|
 }t|| }| j|j|	f< t| j| j |d}|
!||j"|j#|_"|j$r| %||	I d H  n|D ]	}|| j|j< qt&| j' }g }| (|j|D ].\}}	| j)||	f}| jj| }
t|
ts?J d|
 | *|
|j"|j+}|,| q |rc|D ]	}|| j|j< qT| | t|t-rt|jt-rdd |D }|jD ]}|j|vr| 
|jI d H  qz| | |j.r| 
|jjI d H  | js nq+6 | jrt&| j/ D ]\\}}	}d}| jj0|t1 }| j|}|D ]S}| j/ D ]E\\}}}||krd }d }|j+D ]}|j|jkr|j} nq|j+D ]}|j|jkr|j} nq|r|r||krd} nq|r nq|r%q| j)||	f | jj| }
t|
ts@J d|
 | *|
|j"|j+}|V }t|t	rn| jj   W d   I d H  W W d   I d H  d S |D ]	}|| j|j< qpd	d |D }|D ]}|j|vr| 
|jI d H  q| | q| js(| js(W d   I d H  n1 I d H sw   Y  W n t2y   | jj  Y W d   I d H  d S w W d   I d H  td
1 I d H sw   Y  td
)Nr   zParent fork run not foundzExpected a `Join` but got )r}   r~   
join_statec                 S     h | ]}|j qS rV   r   .0trV   rV   rW   	<setcomp>]      z,_GraphIterator.iter_graph.<locals>.<setcomp>FTc                 S  r   rV   r   r   rV   rV   rW   r     r   zpGraph run completed, but no result was produced. This is either a bug in the graph or a bug in the graph runner.)3r   r   r   _handle_execution_requestr   r   r   rw   ra   rO   _finish_taskr   r   cancel_scopecancelr   rx   rb   fork_id	enumeraterd   r{   lennode_run_idrv   rp   r.   ru   initial_factoryr0   r1   r}   r~   reducecurrentrc   cancelled_sibling_tasks_cancel_sibling_taskslistry   _get_completed_fork_runspop_handle_non_fork_edgesdownstream_fork_stackextendr   r   itemsrs   setGeneratorExit)rU   r   task_resultmaybe_overridden_resultrw   parent_fork_idixr   fork_run_id	join_noder   r   contextnew_tasktasks_by_id_values
join_tasksrb   	new_tasksnew_task_idsr   should_skiprz   join_parent_forkintermediate_join_idother_join_id_other_join_statejoin_parent_fork_run_idother_parent_fork_run_idfsirV   rV   rW   r     s:  





P




   *     #  #z_GraphIterator.iter_graphr   r-   Nonec                   s2   | j |d }|d ur|  | j|d  d S rR   )r   r   r   r   )rU   r   scoperV   rV   rW   r     s
   z_GraphIterator._finish_taskrequestSequence[GraphTask]c                 C  s4   |D ]}|| j |j< q|D ]
}| j| j| qd S rR   )r   r   r   
start_soon_run_tracked_task)rU   r  r
  rV   rV   rW   r     s
   z(_GraphIterator._handle_execution_requestt_c                   s   t  U}|| j|j< | |I d H }t|tr=|j2 z3 d H W }| jt	||dI d H  q6 | jt	|g I d H  n| jt	||I d H  W d    d S W d    d S 1 s\w   Y  d S )NF)
r   r   r   	_run_taskr   r   r   r   sendr   )rU   r  r  rw   r  rV   rV   rW   r    s   
"z _GraphIterator._run_tracked_tasktaskMEndMarker[OutputT] | Sequence[GraphTask] | _GraphTaskAsyncIterable | JoinItemc                   s.  | j }| j}|j}|j}|j}| jj| }t|tt	B r$| 
|||S t|trqt +}| jjr<|td|j|d ttttf |||d}	||	I d H }
W d    n1 sZw   Y  t|trj| |
|S | 
||
|S t|tr|t|||S t|tr| |||S t|trt|S t| d S )Nzrun node {node_id})r   noder}   r~   rc   )r}   r~   r   rc   rd   r   rp   r   r4   r3   _handle_edgesr>   r
   ro   r   r$   r   r?   rH   rJ   r   callr=   _handle_noder.   ra   r%   _handle_decisionr2   rO   r   )rU   r!  r}   r~   r   rc   rd   r#  r   step_contextr   rV   rV   rW   r    s4   




z_GraphIterator._run_taskdecisionDecision[StateT, DepsT, Any]rc   r   rd   r'   c           	      C  s   |j D ]R}|j}|d ur||}n8t|j}|tthv rd}n*t|tu r,|t|v }nzt	||}W n t
yH } z	td| d|d }~ww |rU| |j||  S qtd| d| d)NTzDecision branch source z is not a valid type.zNo branch matched inputs z for decision node .)branchesmatchesrA   r   r   objectr   r   r   r   	TypeErrorrv   _handle_pathpath)	rU   r*  rc   rd   branchmatch_testerinputs_matchbranch_sourceerV   rV   rW   r(    s&   


z_GraphIterator._handle_decision	next_node'BaseNode[StateT, DepsT, Any] | End[Any]3Sequence[GraphTask] | JoinItem | EndMarker[OutputT]c                 C  s~   t |trt|jj|j|gS t |trt|jj|j|S t |t	r/t
|j}t|j||gS t |tr9t|jS t| d S rR   )r   r@   r   stepr   rc   r/   ra   joinrB   r=   r   rC   rO   datar   )rU   r8  rd   	node_steprV   rV   rW   r'    s   





z_GraphIterator._handle_noder   Iterable[GraphTask]list[tuple[JoinID, NodeRunID]]c                 C  s`   g }dd t |jD }| j D ]\}}||}|d u rq| |||r-|||f q|S )Nc                 S  s   i | ]\}}|j |qS rV   r   )r   r  r  rV   rV   rW   
<dictcomp>#  s    z;_GraphIterator._get_completed_fork_runs.<locals>.<dictcomp>)r   rd   r   keysru   _is_fork_run_completedappend)rU   r   r   completed_fork_runsfork_run_indicesrb   r  fork_run_indexrV   rV   rW   r     s   
z'_GraphIterator._get_completed_fork_runsr2  r;   c                 C  s   |j sg S |j d }t|ttB rJ dt|tr"t|j||gS t|tr;|t	| j
| j|d}| |j||S t|trH| |j||S t| d S )Nr   z@These markers should be removed from paths during graph buildingr$  )r   r   r:   r7   r8   r   destination_idr<   	transformr?   r}   r~   r1  	next_pathr9   r   )rU   r2  rc   rd   itemrV   rV   rW   r1  /  s   



z_GraphIterator._handle_pathr#  r5   -Sequence[GraphTask] | _GraphTaskAsyncIterablec                 C  s&   t |tr| |||S | |||S rR   )r   r3   _handle_fork_edgesr   )rU   r#  rc   rd   rV   rV   rW   r%  A  s   
z_GraphIterator._handle_edgesc                 C  s4   | j j|jg }t|dksJ | |d ||S )N   r   )r   rq   ru   r   r   r1  )rU   r#  rc   rd   edgesrV   rV   rW   r   I  s   z%_GraphIterator._handle_non_fork_edgesFork[Any, Any]c                   sP  j jjg  t dksttrjrJ  jfg }tt	t
 jrj }d urKj j| }t|ts?J t| j|f< trotD ]\}} d |tj|f }	||	7 }qS|S trd fdd}
t|
 S tdt D ]\}}||tj|f 7 }q|S )	NrO  r   rY   "AsyncIterator[Sequence[GraphTask]]c               
    sN   d} 2 z3 d H W }  d |tj| f }|V  | d7 } q6 d S )Nr   rO  )r1  r(   r   )thread_index
input_item
item_tasksrP  rd   rc   r#  r   rU   rV   rW   handle_async_iterablei  s   
z@_GraphIterator._handle_fork_edges.<locals>.handle_async_iterablezCannot map non-iterable value: )rY   rR  )r   rq   ru   r   r   r   r3   is_mapr,   r   r   r   downstream_join_idrp   r.   r0   r   r   _is_any_iterabler   r1  r(   _is_any_async_iterabler   rv   )rU   r#  rc   rd   r  rb   r  rS  rT  rU  rW  r  r2  rV   rV  rW   rN  N  s4   
	$z!_GraphIterator._handle_fork_edgestasksrb   r*   r  r,   rn   c                 C  sN   | j |}|D ]}|dd |jD v r#|j|jv s|j|kr" dS q	 qdS )Nc                 S  r   rV   rA  )r   r  rV   rV   rW   r     r   z8_GraphIterator._is_fork_run_completed.<locals>.<setcomp>FT)r   rx   rd   r   intermediate_nodes)rU   r\  rb   r  parent_forkr   rV   rV   rW   rD  {  s   z%_GraphIterator._is_fork_run_completedr  r&   r   c                   sn   t t  }| j D ]\}}|jD ]}|j|kr%|j|kr%||  n	 qq|D ]
}| |I d H  q*d S rR   )	r   r-   r   r   rd   r   r   addr   )rU   r  r   task_ids_to_cancelr   r   rL  rV   rV   rW   r     s   


z$_GraphIterator._cancel_sibling_tasksN)r   r   rY   r   )r   r-   rY   r  )r  r  rY   r  )r  r   )r!  r   rY   r"  )r*  r+  rc   r   rd   r'   rY   r  )r8  r9  rd   r'   rY   r:  )r   r   r   r?  rY   r@  )r2  r;   rc   r   rd   r'   rY   r  )r#  r5   rc   r   rd   r'   rY   rM  )r#  r5   rc   r   rd   r'   rY   r  )r#  rQ  rc   r   rd   r'   rY   rM  )r\  r?  rb   r*   r  r,   rY   rn   )r  r&   r   r,   )r[   r\   r]   r_   r   r   r   r   r   r   r   r   r   r   r  r  r(  r'  r   r1  r%  r   rN  rD  r   rV   rV   rV   rW   r     s4   
 
 
*



#






-r   r  r   rY   TypeGuard[Iterable[Any]]c                 C  
   t | tS rR   )r   r   r  rV   rV   rW   rZ       
rZ  TypeGuard[AsyncIterable[Any]]c                 C  rb  rR   )r   r   rc  rV   rV   rW   r[    rd  r[  c               
   c  sT    t rd V  d S zd V  W d S  ty) }  z| jd }|jd u r#d |_|d } ~ ww )Nr   )r   rF   r    	__cause__)r7  	exceptionrV   rV   rW   r     s   


r   )r  r   rY   ra  )r  r   rY   re  )or^   
__future__r   _annotationssysr   collections.abcr   r   r   r   r   
contextlibr   r	   r
   r   r   dataclassesr   r   typingr   r   r   r   r   r   r   r   r   anyior   r   r   	anyio.abcr   anyio.streams.memoryr   r   typing_extensionsr   r   pydantic_graphr    pydantic_graph._utilsr!   r"   r#   r$   pydantic_graph.beta.decisionr%   pydantic_graph.beta.id_typesr&   r'   r(   r)   r*   r+   r,   r-   pydantic_graph.beta.joinr.   r/   r0   r1   pydantic_graph.beta.noder2   r3   r4   pydantic_graph.beta.node_typesr5    pydantic_graph.beta.parent_forksr6   pydantic_graph.beta.pathsr7   r8   r9   r:   r;   r<   pydantic_graph.beta.stepr=   r>   r?   r@   pydantic_graph.beta.utilrA   pydantic_graph.nodesrB   rC   version_infoexceptiongrouprF   r   rG   rH   rJ   rK   rL   rO   ra   rg   r   r   r   r   r   rZ  r[  r   rV   rV   rV   rW   <module>   sz    ,( 
 G "   

