|
27 | 27 | if TYPE_CHECKING: |
28 | 28 | from collections.abc import Callable |
29 | 29 | from collections.abc import Mapping |
| 30 | + from pathlib import Path |
30 | 31 |
|
31 | 32 | from _pytask.reports import CollectionReport |
32 | 33 | from _pytask.reports import ExecutionReport |
@@ -55,20 +56,13 @@ def pytask_execute_task(session: Session, task: PTask) -> bool | None: |
55 | 56 | if not is_task_generator(task): |
56 | 57 | return None |
57 | 58 |
|
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() |
60 | 61 | } |
61 | 62 | try: |
62 | 63 | execute_task(task) |
63 | 64 | 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) |
72 | 66 | raise |
73 | 67 |
|
74 | 68 | tasks: list[TaskFunction] = [] |
@@ -118,6 +112,28 @@ def pytask_execute_task(session: Session, task: PTask) -> bool | None: |
118 | 112 | _clear_annotation_locals(tasks) |
119 | 113 |
|
120 | 114 |
|
| 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 | + |
121 | 137 | def _raise_error_for_failed_generated_tasks( |
122 | 138 | task: PTask, reports: list[CollectionReport] |
123 | 139 | ) -> None: |
|
0 commit comments