Skip to content

Commit d6289ce

Browse files
committed
Discard child registrations when a task generator fails
1 parent 0f730d0 commit d6289ce

1 file changed

Lines changed: 26 additions & 10 deletions

File tree

‎src/_pytask/provisional.py‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
if TYPE_CHECKING:
2828
from collections.abc import Callable
2929
from collections.abc import Mapping
30+
from pathlib import Path
3031

3132
from _pytask.reports import CollectionReport
3233
from _pytask.reports import ExecutionReport
@@ -55,20 +56,13 @@ def pytask_execute_task(session: Session, task: PTask) -> bool | None:
5556
if not is_task_generator(task):
5657
return None
5758

58-
registered_functions = {
59-
id(function) for functions in COLLECTED_TASKS.values() for function in functions
59+
registered_task_counts = {
60+
path: len(functions) for path, functions in COLLECTED_TASKS.items()
6061
}
6162
try:
6263
execute_task(task)
6364
except BaseException:
64-
# Children can be registered before the generator raises, without reaching
65-
# collection below. Release only their snapshots and preserve the exception.
66-
_clear_annotation_locals(
67-
function
68-
for functions in COLLECTED_TASKS.values()
69-
for function in functions
70-
if id(function) not in registered_functions
71-
)
65+
_discard_generator_registrations(registered_task_counts)
7266
raise
7367

7468
tasks: list[TaskFunction] = []
@@ -118,6 +112,28 @@ def pytask_execute_task(session: Session, task: PTask) -> bool | None:
118112
_clear_annotation_locals(tasks)
119113

120114

115+
def _discard_generator_registrations(
116+
registered_task_counts: Mapping[Path | None, int],
117+
) -> None:
118+
"""Remove registrations appended during a failed generator invocation."""
119+
discarded: list[TaskFunction] = []
120+
for path, functions in list(COLLECTED_TASKS.items()):
121+
registered_count = registered_task_counts.get(path)
122+
if registered_count is None:
123+
discarded.extend(COLLECTED_TASKS.pop(path))
124+
else:
125+
discarded.extend(functions[registered_count:])
126+
del functions[registered_count:]
127+
128+
# A callable that was registered again may still have a pending entry.
129+
pending = {
130+
id(function) for functions in COLLECTED_TASKS.values() for function in functions
131+
}
132+
_clear_annotation_locals(
133+
function for function in discarded if id(function) not in pending
134+
)
135+
136+
121137
def _raise_error_for_failed_generated_tasks(
122138
task: PTask, reports: list[CollectionReport]
123139
) -> None:

0 commit comments

Comments
 (0)