Repository navigation
[Data] Support UDF retries in case of transient exceptions - #63023
Conversation
Signed-off-by: Ayush Kumar <[email protected]>
…tryable Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements a retry mechanism for User Defined Functions (UDFs) within Ray Data map tasks, allowing for transient error recovery based on configurable exception patterns. Key changes include the addition of retried_udf_errors and max_udf_retries to the DataContext, updates to the iterate_with_retry utility to include exception causes in pattern matching, and the integration of this retry logic into the MapOperator. Feedback focuses on refactoring duplicated iterator creation logic in map_operator.py to improve maintainability and simplifying the exception string construction in util.py.
Signed-off-by: Ayush Kumar <[email protected]>
…04_25_trans_retries
richardliaw
left a comment
There was a problem hiding this comment.
A couple comments:
- I'm not that big of a fan of putting
udfin the naming - Is there really a use case where you want to actually separate the read task exception classes from the map task exception classes?
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Signed-off-by: Ayush Kumar <[email protected]>
…04_25_trans_retries
I think it makes sense to deduplicate behaviour by unifying the transient failures in map tasks and read tasks. The only counter-example I can think of is when a user explicitly wants RateLimit errors to be retried in the IO stage, and not in the |
That being said, if we decide to unify io errors and map tasks, I think that would be better as a follow-up PR to limit scope. |
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
…ixtures Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
…04_25_trans_retries
…error for next test Signed-off-by: Ayush Kumar <[email protected]>
…ed in iterate_with_retry Signed-off-by: Ayush Kumar <[email protected]>
…to retry.py Signed-off-by: Ayush Kumar <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 4c44074. Configure here.
Kunchd
left a comment
There was a problem hiding this comment.
Looks good overall, left some nits for core side.
MengjinYan
left a comment
There was a problem hiding this comment.
Only nit comments for the core side change.
…ches_error and format_exception, updated docstrings Signed-off-by: Ayush Kumar <[email protected]>
…ct#63023) ## Description Adds support for retrying UDF exceptions in Ray Data map tasks. Previously, any exception raised inside a `map_batches` / `map` UDF would immediately fail the task. This PR allows users to configure which exceptions should trigger a retry, enabling more resilient pipelines for transient errors (e.g. rate limits, flaky external services). Two new `DataContext` fields control the behavior of UDF retries: - `retried_map_errors`: False (default, no retries), True (retry any exception), or a `List[str]` (retry only when the exception message contains one of the input substrings). - `max_map_retries`: Maximum retry attempts per task. Default is 3. Retries use the existing `iterate_with_retry` utility fn with exponential backoff. We unwrap `UserCodeException.__cause__` so that the original UDF error message is matched, not the Ray Data wrapper for all exceptions arising from user code. Example usage: To retry a transform in the case of a rate limit error which has the following stack trace: ``` openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}} ``` We can set the following parameters in `DataContext` ``` ctx = ray.data.DataContext.get_current() ctx.retried_map_errors = ["RateLimit", "429"] ctx.max_map_retries = 5 ds.map_batches(my_udf).take_all() ``` ## Additional information ### Implementation - In `_map_task`, read `retried_map_errors` from the context. If set, wrap the transform pipeline in a factory function and pass it to the existing `iterate_with_retry` utility instead of iterating directly - `iterate_with_retry` catches exceptions, checks if the message matches any of the input patterns, and retries with backoff in `max_map_retries` attempts. We extend `iterate_with_retry` to check for `e.__cause__` to unwrap the `UserCodeException` into the actual exception from the UDF - 4 unit tests added in `test_map.py` to test retries exhausted, successful, retry all and non-matching exceptions --------- Signed-off-by: Ayush Kumar <[email protected]> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…ct#63023) ## Description Adds support for retrying UDF exceptions in Ray Data map tasks. Previously, any exception raised inside a `map_batches` / `map` UDF would immediately fail the task. This PR allows users to configure which exceptions should trigger a retry, enabling more resilient pipelines for transient errors (e.g. rate limits, flaky external services). Two new `DataContext` fields control the behavior of UDF retries: - `retried_map_errors`: False (default, no retries), True (retry any exception), or a `List[str]` (retry only when the exception message contains one of the input substrings). - `max_map_retries`: Maximum retry attempts per task. Default is 3. Retries use the existing `iterate_with_retry` utility fn with exponential backoff. We unwrap `UserCodeException.__cause__` so that the original UDF error message is matched, not the Ray Data wrapper for all exceptions arising from user code. Example usage: To retry a transform in the case of a rate limit error which has the following stack trace: ``` openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}} ``` We can set the following parameters in `DataContext` ``` ctx = ray.data.DataContext.get_current() ctx.retried_map_errors = ["RateLimit", "429"] ctx.max_map_retries = 5 ds.map_batches(my_udf).take_all() ``` ## Additional information ### Implementation - In `_map_task`, read `retried_map_errors` from the context. If set, wrap the transform pipeline in a factory function and pass it to the existing `iterate_with_retry` utility instead of iterating directly - `iterate_with_retry` catches exceptions, checks if the message matches any of the input patterns, and retries with backoff in `max_map_retries` attempts. We extend `iterate_with_retry` to check for `e.__cause__` to unwrap the `UserCodeException` into the actual exception from the UDF - 4 unit tests added in `test_map.py` to test retries exhausted, successful, retry all and non-matching exceptions --------- Signed-off-by: Ayush Kumar <[email protected]> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Signed-off-by: Alexandr Plashchinsky <[email protected]>
…64587) ## Description When a UDF passed to a Ray Data transform raises, the error surfaced to the user is buried: the same `RayTaskError`/`UserCodeException` traceback is printed several times (driver propagation, abort log, executor shutdown log), and each copy is padded with Ray Data internal frames (executor / scheduler / planner) the user cannot act on. This PR makes user-code errors concise while leaving genuine internal/system errors fully verbose. Every behavior change is gated on `isinstance(..., UserCodeException)`: - `RayTaskError.__str__` strips `ray/data/_internal/` frames (and their continuation / caret lines) when the root cause is a `UserCodeException`. - The driver-side handler (`omit_traceback_stdout`) logs only the cleaned worker-side trace for user-code errors instead of re-dumping the full driver→worker traceback. - The abort log (`process_completed_tasks`) and the executor shutdown log no longer re-dump the traceback for user-code errors, since it is already logged once (cleaned). **Internal frames are now always omitted from `stdout`.** The renamed `DataContext.log_internal_stack_trace` flag controls only whether the full internal trace is written to the **Ray Data log file** (off by default). The old `log_internal_stack_trace_to_stdout` name still works but is deprecated (removal January 2027) and forwards to the new flag with a `DeprecationWarning`. Internal/system errors are untouched — full tracebacks in every channel. `RAY_DATA_RAISE_ORIGINAL_MAP_EXCEPTION=1` still bypasses the wrapping entirely. ## Before / after Repro — a UDF that divides by zero: ```python import ray def f(row): return {"x": 1 / 0} ray.data.range(1).map(f).take_all() ``` ### Console (stdout) **Before (master):** the traceback is dumped **twice**, each copy padded with internal `map_operator` / `map_transformer` / `plan_udf_map_op` frames: ```text ERROR streaming_executor_state.py:708 -- An exception was raised from a task of operator "Map(f)". ... Traceback (most recent call last): File ".../ray/data/_internal/execution/streaming_executor_state.py", line 673, in process_completed_tasks bytes_read = task.on_data_ready( File ".../ray/data/_internal/execution/interfaces/physical_operator.py", line 276, in on_data_ready raise ex from None ... (worker.py / auto_init_hook / client_mode_hook frames) ... ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=5427, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=5427, ip=127.0.0.1) File ".../ray/data/_internal/execution/operators/map_operator.py", line 855, in _map_task File ".../ray/data/_internal/execution/operators/map_transformer.py", line 221, in __next__ File ".../ray/data/_internal/planner/plan_udf_map_op.py", line 470, in _wrapped_udf_map_fn _try_wrap_udf_exception(e) File ".../ray/data/_internal/planner/plan_udf_map_op.py", line 486, in _try_wrap_udf_exception raise UserCodeException("UDF failed to process a data block.") from e ray.exceptions.UserCodeException: UDF failed to process a data block. INFO streaming_executor.py:338 --⚠️ Dataset dataset_1_0 execution failed ERROR exceptions.py:63 -- Exception occurred in user code ... set `DataContext.log_internal_stack_trace_to_stdout` to True. Traceback (most recent call last): ... (the ENTIRE traceback above is repeated a second time) ... ray.exceptions.UserCodeException: UDF failed to process a data block. ``` **After (identical for `log_internal_stack_trace` = False *or* True):** printed once, only the user's frame: ```text ERROR exceptions.py:68 -- Exception occurred in user code, with the abbreviated stack trace below. The Ray Data internal stack frames are omitted from stdout. To also write the full stack trace to the Ray Data log file at `.../logs/ray-data`, set `DataContext.log_internal_stack_trace` to True. Traceback (most recent call last): File ".../scratchpad/repro.py", line 13, in <module> ray.data.range(1).map(f).take_all() ... (a few driver frames) ... File ".../ray/data/exceptions.py", line 101, in handle_trace raise e.with_traceback(None) ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=3655, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=3655, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` (With `log_internal_stack_trace=True` the stdout is the same, minus the one "Exception occurred in user code" advisory line — the flag never adds internal frames to stdout.) ### Log file (`.../logs/ray-data/ray-data.log`) **Before (master):** the log file always contained the full driver + worker trace (internal frames included). **After, `log_internal_stack_trace=False` (default):** only the cleaned worker-side trace, no internal frames: ```text ERROR exceptions.py:95 -- Full stack trace: ray::Map(f)() (pid=3655, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=3655, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` **After, `log_internal_stack_trace=True`:** the full driver + worker trace is restored to the log file (equivalent to master's old log-file content), while stdout stays clean: ```text ERROR exceptions.py:91 -- Full stack trace: Traceback (most recent call last): File ".../ray/data/exceptions.py", line 49, in handle_trace File ".../ray/data/dataset.py", line 7748, in _execute_to_iterator File ".../ray/data/_internal/execution/streaming_executor.py", line 767, in get_next File ".../ray/data/_internal/execution/streaming_executor_state.py", line 502, in get_output_blocking File ".../ray/data/_internal/execution/streaming_executor_state.py", line 723, in process_completed_tasks File ".../ray/data/_internal/execution/interfaces/physical_operator.py", line 284, in on_data_ready File ".../ray/_private/worker.py", line 1050, in get_objects raise value.as_instanceof_cause() ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=4137, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=4137, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` ## Related issues Follow-up to #63023. ## Additional information Extends `test_exceptions.py` to assert: the "Full stack trace:" record is always hidden from stdout (`hide=True`) for user-code errors; the record carries only the cleaned inlined trace by default (`exc_info is None`) and the full traceback via `exc_info` when `log_internal_stack_trace=True`; system exceptions keep `hide=False`; and the deprecated `log_internal_stack_trace_to_stdout` alias still forwards with a `DeprecationWarning`. --------- Signed-off-by: Aarrya <[email protected]> Signed-off-by: AarryaSaraf <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
…ay-project#64587) ## Description When a UDF passed to a Ray Data transform raises, the error surfaced to the user is buried: the same `RayTaskError`/`UserCodeException` traceback is printed several times (driver propagation, abort log, executor shutdown log), and each copy is padded with Ray Data internal frames (executor / scheduler / planner) the user cannot act on. This PR makes user-code errors concise while leaving genuine internal/system errors fully verbose. Every behavior change is gated on `isinstance(..., UserCodeException)`: - `RayTaskError.__str__` strips `ray/data/_internal/` frames (and their continuation / caret lines) when the root cause is a `UserCodeException`. - The driver-side handler (`omit_traceback_stdout`) logs only the cleaned worker-side trace for user-code errors instead of re-dumping the full driver→worker traceback. - The abort log (`process_completed_tasks`) and the executor shutdown log no longer re-dump the traceback for user-code errors, since it is already logged once (cleaned). **Internal frames are now always omitted from `stdout`.** The renamed `DataContext.log_internal_stack_trace` flag controls only whether the full internal trace is written to the **Ray Data log file** (off by default). The old `log_internal_stack_trace_to_stdout` name still works but is deprecated (removal January 2027) and forwards to the new flag with a `DeprecationWarning`. Internal/system errors are untouched — full tracebacks in every channel. `RAY_DATA_RAISE_ORIGINAL_MAP_EXCEPTION=1` still bypasses the wrapping entirely. ## Before / after Repro — a UDF that divides by zero: ```python import ray def f(row): return {"x": 1 / 0} ray.data.range(1).map(f).take_all() ``` ### Console (stdout) **Before (master):** the traceback is dumped **twice**, each copy padded with internal `map_operator` / `map_transformer` / `plan_udf_map_op` frames: ```text ERROR streaming_executor_state.py:708 -- An exception was raised from a task of operator "Map(f)". ... Traceback (most recent call last): File ".../ray/data/_internal/execution/streaming_executor_state.py", line 673, in process_completed_tasks bytes_read = task.on_data_ready( File ".../ray/data/_internal/execution/interfaces/physical_operator.py", line 276, in on_data_ready raise ex from None ... (worker.py / auto_init_hook / client_mode_hook frames) ... ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=5427, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=5427, ip=127.0.0.1) File ".../ray/data/_internal/execution/operators/map_operator.py", line 855, in _map_task File ".../ray/data/_internal/execution/operators/map_transformer.py", line 221, in __next__ File ".../ray/data/_internal/planner/plan_udf_map_op.py", line 470, in _wrapped_udf_map_fn _try_wrap_udf_exception(e) File ".../ray/data/_internal/planner/plan_udf_map_op.py", line 486, in _try_wrap_udf_exception raise UserCodeException("UDF failed to process a data block.") from e ray.exceptions.UserCodeException: UDF failed to process a data block. INFO streaming_executor.py:338 --⚠️ Dataset dataset_1_0 execution failed ERROR exceptions.py:63 -- Exception occurred in user code ... set `DataContext.log_internal_stack_trace_to_stdout` to True. Traceback (most recent call last): ... (the ENTIRE traceback above is repeated a second time) ... ray.exceptions.UserCodeException: UDF failed to process a data block. ``` **After (identical for `log_internal_stack_trace` = False *or* True):** printed once, only the user's frame: ```text ERROR exceptions.py:68 -- Exception occurred in user code, with the abbreviated stack trace below. The Ray Data internal stack frames are omitted from stdout. To also write the full stack trace to the Ray Data log file at `.../logs/ray-data`, set `DataContext.log_internal_stack_trace` to True. Traceback (most recent call last): File ".../scratchpad/repro.py", line 13, in <module> ray.data.range(1).map(f).take_all() ... (a few driver frames) ... File ".../ray/data/exceptions.py", line 101, in handle_trace raise e.with_traceback(None) ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=3655, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=3655, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` (With `log_internal_stack_trace=True` the stdout is the same, minus the one "Exception occurred in user code" advisory line — the flag never adds internal frames to stdout.) ### Log file (`.../logs/ray-data/ray-data.log`) **Before (master):** the log file always contained the full driver + worker trace (internal frames included). **After, `log_internal_stack_trace=False` (default):** only the cleaned worker-side trace, no internal frames: ```text ERROR exceptions.py:95 -- Full stack trace: ray::Map(f)() (pid=3655, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=3655, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` **After, `log_internal_stack_trace=True`:** the full driver + worker trace is restored to the log file (equivalent to master's old log-file content), while stdout stays clean: ```text ERROR exceptions.py:91 -- Full stack trace: Traceback (most recent call last): File ".../ray/data/exceptions.py", line 49, in handle_trace File ".../ray/data/dataset.py", line 7748, in _execute_to_iterator File ".../ray/data/_internal/execution/streaming_executor.py", line 767, in get_next File ".../ray/data/_internal/execution/streaming_executor_state.py", line 502, in get_output_blocking File ".../ray/data/_internal/execution/streaming_executor_state.py", line 723, in process_completed_tasks File ".../ray/data/_internal/execution/interfaces/physical_operator.py", line 284, in on_data_ready File ".../ray/_private/worker.py", line 1050, in get_objects raise value.as_instanceof_cause() ray.exceptions.RayTaskError(UserCodeException): ray::Map(f)() (pid=4137, ip=127.0.0.1) File ".../scratchpad/repro.py", line 11, in f return {"x": 1 / 0} ~~^~~ ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: ray::Map(f)() (pid=4137, ip=127.0.0.1) ray.exceptions.UserCodeException: UDF failed to process a data block. ``` ## Related issues Follow-up to ray-project#63023. ## Additional information Extends `test_exceptions.py` to assert: the "Full stack trace:" record is always hidden from stdout (`hide=True`) for user-code errors; the record carries only the cleaned inlined trace by default (`exc_info is None`) and the full traceback via `exc_info` when `log_internal_stack_trace=True`; system exceptions keep `hide=False`; and the deprecated `log_internal_stack_trace_to_stdout` alias still forwards with a `DeprecationWarning`. --------- Signed-off-by: Aarrya <[email protected]> Signed-off-by: AarryaSaraf <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Ayush Kumar <[email protected]> Signed-off-by: 400Ping <[email protected]>

Description
Adds support for retrying UDF exceptions in Ray Data map tasks. Previously, any exception raised inside a
map_batches/mapUDF would immediately fail the task. This PR allows users to configure which exceptions should trigger a retry, enabling more resilient pipelines for transient errors (e.g. rate limits, flaky external services).Two new
DataContextfields control the behavior of UDF retries:retried_map_errors: False (default, no retries), True (retry any exception), or aList[str](retry only when the exception message contains one of the input substrings).max_map_retries: Maximum retry attempts per task. Default is 3.Retries use the existing
iterate_with_retryutility fn with exponential backoff. We unwrapUserCodeException.__cause__so that the original UDF error message is matched, not the Ray Data wrapper for all exceptions arising from user code.Example usage:
To retry a transform in the case of a rate limit error which has the following stack trace:
We can set the following parameters in
DataContextAdditional information
Implementation
_map_task, readretried_map_errorsfrom the context. If set, wrap the transform pipeline in a factory function and pass it to the existingiterate_with_retryutility instead of iterating directlyiterate_with_retrycatches exceptions, checks if the message matches any of the input patterns, and retries with backoff inmax_map_retriesattempts. We extenditerate_with_retryto check fore.__cause__to unwrap theUserCodeExceptioninto the actual exception from the UDFtest_map.pyto test retries exhausted, successful, retry all and non-matching exceptions