UDF Error Handling and Retry
Scenario
In AI data engineering, UDFs often involve error-prone operations such as network calls, external model inference, and data parsing. When an exception occurs during UDF execution, the default behavior is to throw an exception and stop the query. However, you may need more flexible error handling policies, for example:
- Ignoring: Some data exceptions do not affect the overall result and can be ignored.
- Logs: Error information is recorded for post-event troubleshooting, but the query is not interrupted.
- Automatic retry: In scenarios such as network timeout and temporary service unavailability, automatic retry is used to improve the success rate.
- Exception type-specific strategy: Different policies are used for different types of exceptions, for example, retry upon timeout and ignoring data format errors.
UDF error handling and retry allow users to dynamically wrap the error handling capability for registered UDFs using the wrap_function API without modifying source code of the UDFs. This function supports a combination of ignoring, logging, retrying, and backoff policies.
How to Use
- Register the source UDF: Register a Python UDF (Scalar, Class, PyArrowVector, or PandasVector) following the normal process.
- Call wrap_function for wrapping: Use AuraConnection.wrap_function() to add error handling configuration to the source UDF and return a wrapped callable object.
wrapped = con.wrap_function( source_udf_name="my_func", # Source UDF name source_database="my_db", # Database where the source UDF is located config=ErrorHandlerConfig(...), # Error handling configuration wrapper_name="my_func_wrapped", # (Optional) Name of the wrapped UDF imports=["file1", "file2"], # Additional import files for wrapping the UDF packages=["module1", "module2"] # Additional dependency packages for wrapping the UDF ) - Use the wrapped UDF to perform queries: Use the wrapped UDF in operations such as ds.map() and df.select().
ds = con.load_dataset("my_table", database="my_db") result_ds = ds.map(wrapped, on="input_col", as_col="result") df = result_ds.execute() con.close()
Configuration Items
ErrorHandlerConfig is used to configure the error handling behavior. The parameters are as follows.
| Parameter | Type | Description | Default Value |
|---|---|---|---|
| on_error | OnErrorAction | Error handling policy in the calling phase.
| RAISE |
| retry_on | list[type[Exception]] | Whitelist of exception types that trigger a retry during the calling phase. If a match is found, the retry logic is triggered. If no match is found, the on_error logic is triggered. | None |
| ignore_on | list[type[Exception]] | Whitelist of exception types that trigger the exception ignoring during the calling phase. If a match is found, None is returned with the highest priority. | None |
| log_on | list[type[Exception]] | Whitelist of exception types that trigger logging during the calling phase. If a match is found, logs are recorded and None is returned. | None |
| max_retries | int | Maximum number of retries during the calling phase. | 0 |
| retry_cleanup | Callable | Cleanup callback before retry during the calling phase. Signature: (exception, instance) -> None. The framework automatically injects the is_exception_match function into __globals__ to facilitate branch processing by exception type. Exceptions thrown by the callback itself will be captured and a logged as warnings, without affecting the retry process. | None |
| init_on_error | OnErrorAction | Exception handling policy during the __init__ phase.
| RAISE |
| init_max_retries | int | Maximum number of retries during the __init__ phase. | 0 |
| init_retry_on | Sequence[Type[Exception]] | List of exception types that trigger a retry during the __init__ phase. | () |
| init_retry_cleanup | Callable | Cleanup callback before retry during the __init__ phase. Signature: (exception, None) -> None. Note that the instance parameter is None (the object has not been created). | None |
| backoff | BackoffStrategy | Backoff policy.
| FIXED |
| initial_delay_ms | int | Initial delay, in milliseconds, which is used as the base for backoff calculation. | 100 |
| max_delay_ms | int | Maximum delay, in milliseconds. The calculation results of all backoff policies are subject to this constraint. | 60000 |
| log_fn | Callable | Custom log conversion function, with the signature (exception, log_context) -> dict | None.
| None |
| local_log_path | str | Local error log path. If the value is None, the Python logger outputs warnings. | None |
| obs_log_config | ObsLogConfig | OBS log uploading configuration, including:
| None |
Error Handling Priority
If exceptions occur during UDF execution, policies are matched based on the following priorities:
┌─ Priority 1: ignore_on (highest)
│ if ignore_on and isinstance(e, ignore_on):
│ return None ← Ignore the exceptions.
│
├─ Priority 2: log_on
│ if log_on and isinstance(e, log_on):
│ _log_error(e, ...)
│ return None ← Record a log and return None.
│
├─ Priority 3: retry_on (Perform retry for a specified exception type.)
│ if retry_on and isinstance(e, retry_on)
│ and retry_count < max_retries:
│ delay = _compute_delay(...)
│ sleep(delay)
│ continue ← Retry
│
├─ Priority 4: on_error=RETRY (Perform retry for all exceptions.)
│ if on_error==RETRY and not retry_on
│ and retry_count < max_retries:
│ delay = _compute_delay(...)
│ sleep(delay)
│ continue ← Perform retry for all exceptions.
│
├─ Priority 5: on_error=IGNORE
│ if on_error == IGNORE:
│ return None ← Ignore the exceptions and return None.
│
├─ Priority 6: on_error=LOG
│ if on_error == LOG:
│ _log_error(e, ...)
│ return None ← Record a log and return None.
│
└─ Priority 7: raise (default/retry exhausted)
raise ← Throw the original exceptions. Key Rules
- ignore_on has the highest priority. After a match is found, None is returned, and the retry or logging logic is not executed.
- log_on has a higher priority than retry_on. After a match is found, a log is recorded and None is returned, and the retry logic is not executed.
- retry_on performs retry for a specified type of exceptions and performs retry for all exceptions. If both of them are used, retry_on takes precedence.
- If retries are exhausted, on_error determines the final behavior (RAISE, IGNORE, or LOG).
Backoff Policy
The retry interval is calculated based on the backoff policy and initial_delay_ms. All policies are subject to max_delay_ms.
| Backoff Policy | Formula | Example (initial = 100 ms, max = 5,000 ms) |
|---|---|---|
| FIXED | delay = initial_delay_ms | 100, 100, 100, ... |
| LINEAR | delay = initial_delay_ms × (attempt + 1) | 100, 200, 300, 400, ... |
| EXPONENTIAL | delay = initial_delay_ms × 2^attempt | 100, 200, 400, 800, 1600, 3200, ... |
All policies are subject to max_delay_ms: min(delay, max_delay_ms).
Notes and Constraints
- Custom exception restrictions: Custom exceptions defined in classes are not supported. Exceptions with the same name defined in modules with the same name are considered the same exception.
- No wrapping of BUILTIN functions: wrap_function can only wrap Python UDFs and cannot wrap built-in database functions, such as ABS() and UPPER().
- WRAPPER defaults to TEMPORARY: A wrapped UDF is temporary by default and is automatically destroyed after the session ends.
- Vectorized UDF batch failure: For UDFs of the PyarrowVector or PandasVector type, if an exception is triggered in any row of a batch, None is returned for the entire batch.
- Sensitive data security: If user-defined log fields and UDF parameters contain sensitive data (such as accounts and passwords), you need to desensitize them.
Example
Example 1: retry for a specified type of exception
When a UDF is called over the network and a TimeoutError occurs, exponential backoff is used for a maximum of three retry attempts:
from aura_frame import ErrorHandlerConfig, BackoffStrategy
from aura_frame.multimodal import ai_lake
con = ai_lake.connect(
aura_endpoint=os.getenv("aura_endpoint"), # Endpoint where the AuraJobV2 endpoint is located
aura_endpoint_id=os.getenv("aura_endpoint_id"), # AuraJobV2 endpoint ID
aura_endpoint_name=os.getenv("aura_endpoint_name"),# AuraJobV2 endpoint name
aura_workspace_id=os.getenv("aura_workspace_id"), # Workspace ID
lf_catalog_name=os.getenv("lf_catalog_name"), # LakeFormation Catalog name
access_key=os.getenv("access_key"), # Access Key ID (AK)
secret_key=os.getenv("secret_key"), # Secret Key (SK)
default_database="postgres", # LakeFormation database name
use_single_cn_mode=True, # Whether to enable the single-CN mode
logging_level=logging.INFO # Set the log level.
)
try:
wrapped = con.wrap_function(
source_udf_name="call_api",
source_database="my_db",
config=ErrorHandlerConfig(
retry_on=[TimeoutError],
max_retries=3,
backoff=BackoffStrategy.EXPONENTIAL,
initial_delay_ms=200,
max_delay_ms=5000,
),
)
ds = con.load_dataset("api_input", database="my_db")
result_ds = ds.map(wrapped, on="input", as_col="result")
df = result_ds.execute()
finally:
con.close() Example 2: combination of multiple policies
The source UDF supports retry, log degradation, and silent ignoring. Exceptions are matched based on ignore_on, log_on, retry_on, and on_error (RAISE by default) in sequence.
- IndexError: The error is silently ignored, and None is returned. No log is recorded, and no retry is performed.
- ValueError/TypeError: After the error is recorded in a log, None is returned. Since local_log_path="/tmp/udf_errors.log" is configured, the log is written to this directory.
- ConnectionError/TimeoutError:
- A maximum of five retries are allowed. Before each retry, a log is recorded, the delay is calculated, and the system enters the sleep state.
- If the exception persists after five retries, the default value of on_error is RAISE, and the original exception is thrown. The execution of this line fails.
- Other unconfigured exceptions (such as RuntimeError and KeyError): The default value of on_error is RAISE, and the original exception is thrown. The execution of this line fails.
wrapped = con.wrap_function(
source_udf_name="complex_model",
source_database="my_db",
config=ErrorHandlerConfig(
retry_on=[ConnectionError, TimeoutError],
log_on=[ValueError, TypeError],
ignore_on=[IndexError],
max_retries=5,
backoff=BackoffStrategy.LINEAR,
initial_delay_ms=500,
local_log_path="/tmp/udf_errors.log",
),
) A UDF may throw multiple exceptions. If an exception requires retrying, some cleanup actions need to be performed before the retry.
- In a UDF, you can use log_extra["key"] = "..." to add log fields and use log_fn to modify log content or define recorded log fields.
- retry_cleanup/init_retry_cleanup configures the cleanup callbacks for the call/initialization phase.
import random
import pandas
from aura_frame.error_handler import (
BackoffStrategy,
ErrorHandlerConfig,
ObsLogConfig,
OnErrorAction,
)
from aura_frame.multimodal import ai_lake
class InvalidInputError(Exception):
"""Invalid input"""
class ExceedsLength(RuntimeError):
"""The string exceeds the maximum length."""
class WriteFileError(Exception):
"""Failed to write the file."""
class DataTransformer:
"""Class UDF for invoking external HTTP services to convert data"""
def __init__(self):
self.handler = open("/tmp/demo.txt", "a+") # noqa: SIM115
def __call__(self, col: str) -> int:
import os
log_extra = globals().get("log_extra", None)
if isinstance(log_extra, dict):
log_extra.update(
{"ak": os.getenv("UDF_TEMP_AK"), "sk": os.getenv("UDF_TEMP_SK")}
)
if not isinstance(col, str) or not col:
raise InvalidInputError("The input cannot be an empty string.")
if len(col) > 10:
raise ExceedsLength("The input string is exceeds length.")
if random.random() < 0.5: # Simulate a 50% chance of file-write failure.
raise WriteFileError("Failed to write to file.")
try:
self.handler.write(col + "\n")
except Exception as e: # noqa: BLE001
raise WriteFileError(f"Failed to write to file: {e}")
return id(self.handler)
def __del__(self):
self.handler.close()
session = ai_lake.connect(
aura_endpoint="...",
aura_endpoint_name="...",
aura_workspace_id="...",
lf_catalog_name="...",
access_key="...",
secret_key="...",
security_token="...",
default_database="err_handler",
use_single_cn_mode=True,
)
session.sql("create schema if not exists err_handler;")
session.sql("set current_schema to err_handler;")
session.set_function_staging_workspace(
obs_directory_base="...",
obs_bucket_name="...",
obs_server="...",
access_key="...",
secret_key="...",
security_token="...",
)
session.delete_function("data_transformer_src", if_it_exists=True)
source_udf = session.create_scalar_function(
DataTransformer,
name="data_transformer_src",
)
def on_retry_cleanup(exc, instance):
"""Execute different cleanup logic based on the exception type before retry."""
if instance is None:
return # In the __init__ phase, the object has not been created.
# is_exception_match is automatically injected into __globals__ by the framework.
if globals()["is_exception_match"](exc, WriteFileError):
instance.handler.close()
instance.handler = open("/tmp/demo.txt", "a+") # noqa: SIM115
def custom_log_fn(exc, log_context):
"""Custom log format: Desensitization + Service label addition"""
import traceback
record = dict(log_context)
record["exc_msg"] = traceback.extract_tb(exc.__traceback__)
record["sk"] = "******" # Desensitize sensitive information.
return record
# Wrap the source UDF.
wrapped_udf = session.wrap_function(
source_udf_name="data_transformer_src",
wrapper_name="data_transformer",
config=ErrorHandlerConfig(
# Handle exceptions by category.
on_error=OnErrorAction.LOG,
ignore_on=[InvalidInputError], # Invalid input -> Ignore
log_on=[ExceedsLength], # Format error -> Log + Skip
retry_on=[WriteFileError], # Transient error -> Retry
# Retry backoff policy
backoff=BackoffStrategy.EXPONENTIAL,
# Retry control during the calling phase
max_retries=10, # A maximum of 10 retries are allowed.
initial_delay_ms=100,
max_delay_ms=5000,
retry_cleanup=on_retry_cleanup,
# Retry in the initialization phase
init_on_error=OnErrorAction.RETRY,
init_max_retries=2,
init_retry_on=[ConnectionError],
init_retry_cleanup=on_retry_cleanup,
# Log definition
log_fn=custom_log_fn, # Custom log format
local_log_path="/tmp/...", # Local log directory
obs_log_config=ObsLogConfig(
obs_server="...",
obs_bucket_name="...",
obs_directory_base="...",
max_buffer_size=4096,
flush_interval_s=300.0,
obs_log_format="parquet",
),
),
)
# Use the wrapped UDF for query (the usage is identical to the source UDF).
ds = session.from_pandas(pandas.DataFrame({"col": ["", "123", "1234", "12345", "123456", "1234567", "123456789012345"]}))
ds = ds.map(wrapped_udf, on=[ds.col])
ds.show()
session.close() What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot