Skip to content

Commit 7129dcd

Browse files
committed
feat: return structured tracebacks from local process workers
1 parent 2eef6b4 commit 7129dcd

4 files changed

Lines changed: 67 additions & 40 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ dependencies = [
1515
"cloudpickle",
1616
"loky",
1717
"pluggy>=1.0.0",
18-
"pytask>=0.5.2",
18+
"pytask @ git+https://github.com/pytask-dev/pytask.git@10a51fb1647fe2befb07e7abfb4723fa74f2e39d",
1919
"rich",
2020
]
2121
dynamic = ["version"]

‎src/pytask_parallel/execute.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from pytask.tree_util import tree_map
2525
from pytask.tree_util import tree_structure
2626

27+
from pytask_parallel.backends import ParallelBackend
2728
from pytask_parallel.backends import WorkerType
2829
from pytask_parallel.backends import registry
2930
from pytask_parallel.backends import set_worker_root
@@ -152,7 +153,7 @@ def pytask_execute_build(session: Session) -> bool | None: # noqa: C901, PLR091
152153
newly_collected_reports.append(
153154
ExecutionReport.from_task_and_exception(
154155
task,
155-
cast("Any", wrapper_result.exc_info),
156+
wrapper_result.exc_info,
156157
)
157158
)
158159
running_tasks.pop(task_name)
@@ -207,7 +208,8 @@ def pytask_execute_task(session: Session, task: PTask) -> Future[WrapperResult]:
207208
executor.
208209
209210
"""
210-
parallel_backend = registry.registry[session.config["parallel_backend"]]
211+
backend_name = session.config["parallel_backend"]
212+
parallel_backend = registry.registry[backend_name]
211213
worker_type = parallel_backend.worker_type
212214
remote = parallel_backend.remote
213215

@@ -216,9 +218,9 @@ def pytask_execute_task(session: Session, task: PTask) -> Future[WrapperResult]:
216218
if is_coiled_function(task):
217219
strip_annotation_locals(task)
218220
# Prevent circular import for coiled backend.
219-
from pytask_parallel.wrappers import rewrap_task_with_coiled_function # noqa: PLC0415
221+
from pytask_parallel import wrappers # noqa: PLC0415
220222

221-
wrapper_func = rewrap_task_with_coiled_function(task)
223+
wrapper_func = wrappers.rewrap_task_with_coiled_function(task)
222224

223225
# Task modules are dynamically loaded and added to `sys.modules`. Thus,
224226
# cloudpickle believes the module of the task function is also importable in the
@@ -253,10 +255,14 @@ def pytask_execute_task(session: Session, task: PTask) -> Future[WrapperResult]:
253255
if task_module is not None and should_pickle_module_by_value(task_module):
254256
cloudpickle.register_pickle_by_value(task_module)
255257

258+
# An existing Dask client may run on machines without shared source files.
259+
console_options = (
260+
console.options if remote or backend_name == ParallelBackend.DASK else None
261+
)
256262
return session.config["_parallel_executor"].submit(
257263
wrap_task_in_process,
258264
task=task,
259-
console_options=console.options,
265+
console_options=console_options,
260266
kwargs=kwargs,
261267
remote=remote,
262268
session_filterwarnings=session.config["filterwarnings"],

‎src/pytask_parallel/wrappers.py‎

Lines changed: 22 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import functools
66
import os
7-
import sys
87
import warnings
98
from contextlib import redirect_stderr
109
from contextlib import redirect_stdout
@@ -42,6 +41,7 @@
4241

4342
from pytask import Mark
4443
from rich.console import ConsoleOptions
44+
from rich.traceback import Trace
4545

4646

4747
__all__ = ["wrap_task_in_process", "wrap_task_in_thread"]
@@ -52,7 +52,8 @@ class WrapperResult:
5252
carry_over_products: PyTree[CarryOverPath | PythonNode | None]
5353
warning_reports: list[WarningReport]
5454
exc_info: (
55-
tuple[type[BaseException], BaseException, TracebackType | str | None] | None
55+
tuple[type[BaseException], BaseException, TracebackType | Trace | str | None]
56+
| None
5657
)
5758
stdout: str
5859
stderr: str
@@ -69,16 +70,8 @@ def wrap_task_in_thread(task: PTask, *, remote: bool, **kwargs: Any) -> WrapperR
6970
__tracebackhide__ = True
7071
try:
7172
out = task.function(**kwargs)
72-
except Exception: # noqa: BLE001
73-
exc_info_raw = sys.exc_info()
74-
exc_info = (
75-
cast(
76-
"tuple[type[BaseException], BaseException, TracebackType | str | None]",
77-
exc_info_raw,
78-
)
79-
if exc_info_raw[0] is not None
80-
else None
81-
)
73+
except Exception as exc: # noqa: BLE001
74+
exc_info = (type(exc), exc, exc.__traceback__)
8275
else:
8376
_handle_function_products(task, out, remote=remote)
8477
exc_info = None
@@ -94,7 +87,7 @@ def wrap_task_in_thread(task: PTask, *, remote: bool, **kwargs: Any) -> WrapperR
9487
def wrap_task_in_process( # noqa: PLR0913
9588
task: PTask,
9689
*,
97-
console_options: ConsoleOptions,
90+
console_options: ConsoleOptions | None,
9891
kwargs: dict[str, Any],
9992
remote: bool,
10093
session_filterwarnings: tuple[str, ...],
@@ -103,8 +96,8 @@ def wrap_task_in_process( # noqa: PLR0913
10396
) -> WrapperResult:
10497
"""Execute a task in a spawned process.
10598
106-
This function receives bytes and unpickles them to a task which is them execute in a
107-
spawned process or thread.
99+
When console options are supplied, render tracebacks before returning them.
100+
Otherwise, return a Rich trace for the caller to render.
108101
109102
"""
110103
# Hide this function from tracebacks.
@@ -131,22 +124,20 @@ def wrap_task_in_process( # noqa: PLR0913
131124
for arg in mark.args:
132125
warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
133126

134-
processed_exc_info: tuple[type[BaseException], BaseException, str] | None
135-
136127
try:
137128
resolved_kwargs = _write_local_files_to_remote(kwargs)
138129
out = task.execute(**resolved_kwargs)
139-
except Exception: # noqa: BLE001
140-
exc_info = sys.exc_info()
141-
processed_exc_info = _render_traceback_to_string(
142-
(
143-
cast("type[BaseException]", exc_info[0]),
144-
cast("BaseException", exc_info[1]),
145-
exc_info[2],
146-
),
147-
show_locals,
148-
console_options,
130+
except Exception as exc: # noqa: BLE001
131+
exc_type = type(exc)
132+
traceback = Traceback(
133+
(exc_type, exc, exc.__traceback__), show_locals=show_locals
134+
)
135+
transported_traceback = (
136+
traceback.extract()
137+
if console_options is None
138+
else _render_traceback_to_string(traceback, console_options)
149139
)
140+
processed_exc_info = (exc_type, exc, transported_traceback)
150141
products = None
151142
else:
152143
products = _handle_function_products(task, out, remote=remote)
@@ -216,15 +207,12 @@ def _patch_set_trace_and_breakpoint() -> None:
216207

217208

218209
def _render_traceback_to_string(
219-
exc_info: tuple[type[BaseException], BaseException, TracebackType | None],
220-
show_locals: bool, # noqa: FBT001
210+
traceback: Traceback,
221211
console_options: ConsoleOptions,
222-
) -> tuple[type[BaseException], BaseException, str]:
223-
"""Process the exception and convert the traceback to a string."""
224-
traceback = Traceback(exc_info, show_locals=show_locals)
212+
) -> str:
213+
"""Render a traceback while the worker still has access to its source files."""
225214
segments = console.render(cast("Any", traceback), options=console_options)
226-
text = "".join(segment.text for segment in segments)
227-
return exc_info[0], exc_info[1], text
215+
return "".join(segment.text for segment in segments)
228216

229217

230218
def _handle_function_products(

‎tests/test_execute.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pytask import TaskWithoutPath
1212
from pytask import build
1313
from pytask import cli
14+
from rich.traceback import Trace
1415

1516
from pytask_parallel import ParallelBackend
1617
from pytask_parallel.execute import _Sleeper
@@ -183,6 +184,38 @@ def task_raising_error():
183184
assert ("[0, 1, 2, 3, 4]" in result.output) is show_locals
184185

185186

187+
@pytest.mark.parametrize(
188+
"parallel_backend",
189+
[
190+
ParallelBackend.PROCESSES,
191+
pytest.param(ParallelBackend.LOKY, marks=skip_if_deadlock),
192+
],
193+
)
194+
def test_process_workers_return_structured_tracebacks(tmp_path, parallel_backend):
195+
source = """
196+
def task_fail():
197+
worker_local = "worker failure"
198+
raise ValueError(worker_local)
199+
"""
200+
tmp_path.joinpath("task_example.py").write_text(textwrap.dedent(source))
201+
202+
session = build(
203+
paths=tmp_path, parallel_backend=parallel_backend, n_workers=2, show_locals=True
204+
)
205+
206+
assert session.exit_code == ExitCode.FAILED
207+
report = session.execution_reports[0]
208+
assert report.exc_info is not None
209+
exc_type, exc, traceback = report.exc_info
210+
assert exc_type is ValueError
211+
assert str(exc) == "worker failure"
212+
assert isinstance(traceback, Trace)
213+
frames = traceback.stacks[0].frames
214+
assert [frame.name for frame in frames] == ["task_fail"]
215+
assert frames[0].locals is not None
216+
assert "worker_local" in frames[0].locals
217+
218+
186219
@pytest.mark.parametrize(
187220
"parallel_backend",
188221
# Capturing warnings is not thread-safe.

0 commit comments

Comments
 (0)