22
33from __future__ import annotations
44
5- import inspect
6- import sys
75from typing import TYPE_CHECKING
86from typing import Any
97
108from _pytask .config import hookimpl
11- from _pytask .exceptions import NodeLoadError
12- from _pytask .node_protocols import PNode
13- from _pytask .node_protocols import PProvisionalNode
9+ from _pytask .dag import create_dag_from_session
10+ from _pytask .exceptions import CollectionError
11+ from _pytask .execute_utils import execute_task
1412from _pytask .node_protocols import PTask
1513from _pytask .node_protocols import PTaskWithPath
1614from _pytask .outcomes import CollectionOutcome
15+ from _pytask .outcomes import WouldBeExecuted
1716from _pytask .provisional_utils import TASKS_WITH_PROVISIONAL_NODES
1817from _pytask .provisional_utils import collect_provisional_nodes
1918from _pytask .provisional_utils import recreate_dag
20- from _pytask .reports import ExecutionReport
2119from _pytask .task_utils import COLLECTED_TASKS
2220from _pytask .task_utils import parse_collected_tasks_with_task_marker
2321from _pytask .task_utils import validate_unique_task_signatures
24- from _pytask .tree_util import tree_map
2522from _pytask .tree_util import tree_map_with_path
2623from _pytask .typing import is_task_generator
2724from pytask import TaskOutcome
3027 from collections .abc import Callable
3128 from collections .abc import Mapping
3229
30+ from _pytask .reports import CollectionReport
31+ from _pytask .reports import ExecutionReport
3332 from _pytask .session import Session
3433
3534
@@ -48,78 +47,96 @@ def pytask_execute_task_setup(session: Session, task: PTask) -> None:
4847 recreate_dag (session , task )
4948
5049
51- def _safe_load (node : PNode | PProvisionalNode , task : PTask , is_product : bool ) -> Any :
52- try :
53- return node .load (is_product = is_product )
54- except Exception as e :
55- msg = f"Exception while loading node { node .name !r} of task { task .name !r} "
56- raise NodeLoadError (msg ) from e
57-
58-
5950@hookimpl
6051def pytask_execute_task (session : Session , task : PTask ) -> bool | None :
6152 """Execute task generators and collect the tasks."""
62- if is_task_generator (task ):
63- kwargs = {}
64- for name , value in task .depends_on .items ():
65- kwargs [name ] = tree_map (lambda x : _safe_load (x , task , False ), value )
66-
67- parameters = inspect .signature (task .function ).parameters
68- for name , value in task .produces .items ():
69- if name in parameters :
70- kwargs [name ] = tree_map (lambda x : _safe_load (x , task , True ), value )
71-
72- task .execute (** kwargs )
73-
74- # Parse tasks created with @task.
75- name_to_function : Mapping [str , Callable [..., Any ] | PTask ]
76- if isinstance (task , PTaskWithPath ) and task .path in COLLECTED_TASKS :
77- tasks = COLLECTED_TASKS .pop (task .path )
78- name_to_function = parse_collected_tasks_with_task_marker (tasks )
79- elif None in COLLECTED_TASKS :
80- tasks = COLLECTED_TASKS .pop (None )
81- name_to_function = parse_collected_tasks_with_task_marker (tasks )
82- else :
83- msg = "The task generator {task.name!r} did not create any tasks."
84- raise RuntimeError (msg )
85-
86- new_reports = []
87- for name , function in name_to_function .items ():
88- report = session .hook .pytask_collect_task_protocol (
89- session = session ,
90- reports = session .collection_reports ,
91- path = task .path if isinstance (task , PTaskWithPath ) else None ,
92- name = name ,
93- obj = function ,
94- )
53+ if not is_task_generator (task ):
54+ return None
55+
56+ execute_task (task )
57+
58+ name_to_function : Mapping [str , Callable [..., Any ] | PTask ]
59+ if isinstance (task , PTaskWithPath ) and task .path in COLLECTED_TASKS :
60+ tasks = COLLECTED_TASKS .pop (task .path )
61+ name_to_function = parse_collected_tasks_with_task_marker (tasks )
62+ elif None in COLLECTED_TASKS :
63+ tasks = COLLECTED_TASKS .pop (None )
64+ name_to_function = parse_collected_tasks_with_task_marker (tasks )
65+ else :
66+ msg = f"The task generator { task .name !r} did not create any tasks."
67+ raise RuntimeError (msg )
68+
69+ new_reports : list [CollectionReport ] = []
70+ for name , function in name_to_function .items ():
71+ report = session .hook .pytask_collect_task_protocol (
72+ session = session ,
73+ reports = new_reports ,
74+ path = task .path if isinstance (task , PTaskWithPath ) else None ,
75+ name = name ,
76+ obj = function ,
77+ )
78+ if report is not None :
9579 new_reports .append (report )
9680
97- session .tasks .extend (
98- i .node
99- for i in new_reports
100- if i .outcome == CollectionOutcome .SUCCESS and isinstance (i .node , PTask )
81+ session .collection_reports .extend (new_reports )
82+ failed_reports = [
83+ report for report in new_reports if report .outcome == CollectionOutcome .FAIL
84+ ]
85+ if failed_reports :
86+ _raise_error_for_failed_generated_tasks (task , failed_reports )
87+
88+ generated_tasks = [
89+ report .node
90+ for report in new_reports
91+ if report .outcome == CollectionOutcome .SUCCESS
92+ and isinstance (report .node , PTask )
93+ ]
94+ _commit_generated_tasks (session , generated_tasks )
95+ # Generators must run to discover tasks even in simulation modes.
96+ if session .config ["dry_run" ] or session .config ["explain" ]:
97+ raise WouldBeExecuted
98+ return True
99+
100+
101+ def _raise_error_for_failed_generated_tasks (
102+ task : PTask , reports : list [CollectionReport ]
103+ ) -> None :
104+ """Raise one generator error containing every child collection failure."""
105+ lines = [f"The task generator { task .name !r} created tasks that failed collection:" ]
106+ for report in reports :
107+ assert report .exc_info is not None
108+ exception = report .exc_info [1 ]
109+ node_name = report .node .name if report .node is not None else "<unknown>"
110+ lines .append (f"- { node_name !r} : { type (exception ).__name__ } : { exception } " )
111+
112+ error = CollectionError ("\n " .join (lines ))
113+ first_exception = reports [0 ].exc_info
114+ assert first_exception is not None
115+ raise error from first_exception [1 ]
116+
117+
118+ def _commit_generated_tasks (session : Session , generated_tasks : list [PTask ]) -> None :
119+ """Atomically commit generated tasks and the corresponding execution state."""
120+ previous_tasks = session .tasks
121+ session .tasks = [* previous_tasks , * generated_tasks ]
122+ try :
123+ session .hook .pytask_collect_modify_tasks (session = session , tasks = session .tasks )
124+ validate_unique_task_signatures (session .tasks )
125+ dag = create_dag_from_session (session )
126+ scheduler = (
127+ session .scheduler .rebuild (dag ) if session .scheduler is not None else None
101128 )
102-
103- try :
104- session .hook .pytask_collect_modify_tasks (
105- session = session , tasks = session .tasks
106- )
107- validate_unique_task_signatures (session .tasks )
108- # Append the last collection report after successful modification
109- if report :
110- session .collection_reports .append (report )
111- except Exception : # noqa: BLE001 # pragma: no cover
112- exec_report = ExecutionReport .from_task_and_exception (
113- task = task , exc_info = sys .exc_info ()
114- )
115- session .execution_reports .append (exec_report )
116- session .should_stop = True
117- return None
118-
119- recreate_dag (session , task )
120- return True
121-
122- return None
129+ except BaseException :
130+ # Rejected children remain available in collection_reports for diagnostics.
131+ # This restores list membership, not arbitrary plugin mutations to tasks.
132+ session .tasks = previous_tasks
133+ session .should_stop = True
134+ raise
135+
136+ previous_tasks [:] = session .tasks
137+ session .tasks = previous_tasks
138+ session .dag = dag
139+ session .scheduler = scheduler
123140
124141
125142@hookimpl
0 commit comments