fabric-user-data-functions 1.0.100__tar.gz → 1.1.0.dev4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/PKG-INFO +1 -1
  2. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/user_data_functions.py +27 -3
  3. fabric_user_data_functions-1.1.0.dev4/fabric/internal/decorators/add_batched_parameters.py +68 -0
  4. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/add_parameters.py +19 -19
  5. fabric_user_data_functions-1.1.0.dev4/fabric/internal/decorators/batch_processor.py +229 -0
  6. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/configure_fabric_function_builder.py +21 -5
  7. fabric_user_data_functions-1.1.0.dev4/fabric/internal/decorators/constants.py +50 -0
  8. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/ensure_formatted_returntype.py +76 -57
  9. fabric_user_data_functions-1.1.0.dev4/fabric/internal/decorators/ensure_formatted_returntype_batched.py +155 -0
  10. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/remove_unused_binding_params.py +10 -0
  11. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/invoke_response.py +30 -3
  12. fabric_user_data_functions-1.1.0.dev4/fabric/internal/utils/parameter_utils.py +104 -0
  13. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/pyproject.toml +2 -2
  14. fabric_user_data_functions-1.0.100/fabric/internal/decorators/constants.py +0 -24
  15. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/LICENSE.md +0 -0
  16. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/README.md +0 -0
  17. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/__init__.py +0 -0
  18. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/__init__.py +0 -0
  19. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/businessevents/__init__.py +0 -0
  20. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/businessevents/business_events_provider.py +0 -0
  21. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/businessevents/client_registration.py +0 -0
  22. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/businessevents/fabric_business_events.py +0 -0
  23. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/cosmos/__init__.py +0 -0
  24. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/cosmos/client_registration.py +0 -0
  25. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/cosmos/cosmos_client_provider.py +0 -0
  26. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/cosmosdb/__init__.py +0 -0
  27. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/cosmosdb/helpers.py +0 -0
  28. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/fabric_app.py +0 -0
  29. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/fabric_class.py +0 -0
  30. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/fabric_item.py +0 -0
  31. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/generic_audience_types.py +0 -0
  32. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/keyvault/__init__.py +0 -0
  33. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/keyvault/keyvault_client.py +0 -0
  34. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/keyvault/keyvault_provider.py +0 -0
  35. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/keyvault/keyvault_registration.py +0 -0
  36. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/providers/__init__.py +0 -0
  37. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/providers/base_fabricitem_provider.py +0 -0
  38. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/functions/udf_exception.py +0 -0
  39. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/__init__.py +0 -0
  40. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/arrow/__init__.py +0 -0
  41. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/arrow/arrow_dataframe_response.py +0 -0
  42. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/arrow/arrow_request.py +0 -0
  43. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/arrow/arrow_series_response.py +0 -0
  44. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/converters/__init__.py +0 -0
  45. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/converters/basic_datatype_converter.py +0 -0
  46. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/custom_token_credential.py +0 -0
  47. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/__init__.py +0 -0
  48. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/add_timeout.py +0 -0
  49. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/function_parameter_keywords.py +0 -0
  50. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/decorators/log_error.py +0 -0
  51. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/fabric_lakehouse_files_client.py +0 -0
  52. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/item_binding.py +0 -0
  53. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/lib_helpers/__init__.py +0 -0
  54. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/lib_helpers/module_factory.py +0 -0
  55. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/logging/__init__.py +0 -0
  56. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/logging/udf_logger.py +0 -0
  57. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/middleware/__init__.py +0 -0
  58. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/middleware/_invocationIdMiddleware/__init__.py +0 -0
  59. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/openapi_spec_generator.py +0 -0
  60. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/providers/__init__.py +0 -0
  61. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/providers/provider_factory.py +0 -0
  62. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/providers/provider_metadata.py +0 -0
  63. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/udf_binding.py +0 -0
  64. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/udf_string.py +0 -0
  65. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/user_data_function_context_binding.py +0 -0
  66. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/utils/__init__.py +0 -0
  67. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/utils/docstring_parser.py +0 -0
  68. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/internal/utils/spec_utils.py +0 -0
  69. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/metadata/__init__.py +0 -0
  70. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/metadata/__main__.py +0 -0
  71. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/metadata/metadata_generator.py +0 -0
  72. {fabric_user_data_functions-1.0.100 → fabric_user_data_functions-1.1.0.dev4}/fabric/metadata/validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: fabric-user-data-functions
3
- Version: 1.0.100
3
+ Version: 1.1.0.dev4
4
4
  Summary: This package contains bindings and middle ware required for fabric functions built on python.
5
5
  License: Proprietary
6
6
  Author: Fabric AppDev Team
@@ -13,7 +13,7 @@ from azure.functions.decorators.http import HttpTrigger, HttpOutput, HttpMethod
13
13
  from azure.functions.decorators.core import AuthLevel
14
14
  from azure.functions import FunctionApp
15
15
  import fabric.internal.decorators as fabric_decorators
16
- from fabric.internal.decorators.constants import SpecConstants
16
+ from fabric.internal.decorators.constants import SpecConstants, BatchConstants
17
17
  from typing_extensions import deprecated
18
18
 
19
19
  from fabric.internal.item_binding import FabricItemInput
@@ -79,12 +79,35 @@ class UserDataFunctions(FunctionApp):
79
79
  def register_provider(self, type: Type, provider: Type):
80
80
  self._provider_factory.register_provider(type, provider)
81
81
 
82
- def function(self, name=None):
82
+ def _validate_max_batch_size(self, max_batch_size):
83
+ """Validate and return the max batch size, applying defaults and constraints.
84
+
85
+ :param max_batch_size: The max batch size to validate (None means not a batched function)
86
+ :return: The validated max batch size, or None if not a batched function
87
+ :raises ValueError: If max_batch_size is invalid
88
+ """
89
+ # If max_batch_size is None, this is not a batched function
90
+ if max_batch_size is None:
91
+ return None
92
+
93
+ # Validate max_batch_size is an integer
94
+ if not isinstance(max_batch_size, int):
95
+ raise ValueError(f"max_batch_size must be an integer, got {type(max_batch_size).__name__}")
96
+
97
+ # Validate max_batch_size is within allowed range
98
+ if max_batch_size < BatchConstants.MIN_BATCH_SIZE or max_batch_size > BatchConstants.MAX_BATCH_SIZE:
99
+ raise ValueError(f"max_batch_size must be between {BatchConstants.MIN_BATCH_SIZE} and {BatchConstants.MAX_BATCH_SIZE}, got {max_batch_size}")
100
+
101
+ return max_batch_size
102
+
103
+ def function(self, name=None, max_batch_size=None):
83
104
  """
84
105
  This decorator is used to define a User Data Function in Fabric. The function must be decorated with this decorator in order to be recognized as a User Data Function.
85
106
 
86
107
  :param name: The name of the function. This parameter is not used in the current version of Fabric.
87
108
  :type name: str
109
+ :param max_batch_size: The maximum number of items that can be processed in a single batch execution. If not specified, the function will process single items (scalar mode). If specified, must be between 1-900.
110
+ :type max_batch_size: int
88
111
 
89
112
  .. remarks::
90
113
 
@@ -119,7 +142,8 @@ class UserDataFunctions(FunctionApp):
119
142
  # self.log_openapi_spec()
120
143
  return fb
121
144
 
122
- return fabric_decorators.configure_fabric_function_builder(self, wrap, self._functions_metadata)
145
+ validated_max_batch_size = self._validate_max_batch_size(max_batch_size)
146
+ return fabric_decorators.configure_fabric_function_builder(self, wrap, self._functions_metadata, validated_max_batch_size)
123
147
 
124
148
 
125
149
  def connection(self,
@@ -0,0 +1,68 @@
1
+ # flake8: noqa: I003
2
+ from functools import wraps
3
+ import logging
4
+ from azure.functions import HttpRequest
5
+ import inspect
6
+ import asyncio
7
+ from typing import Callable, TypeVar
8
+
9
+ from fabric.functions.udf_exception import UserDataFunctionInvalidInputError
10
+ from fabric.internal.utils.parameter_utils import apply_fabric_item_providers, parse_scalar_parameters
11
+ from .function_parameter_keywords import REQ_PARAMETER
12
+ from .constants import HeaderConstants, BatchInternalKeys, BatchErrorMessages
13
+ from fabric.internal.providers import ProviderMetadata, ProviderFactory
14
+
15
+ T = TypeVar('T')
16
+
17
+ def add_batched_parameters(func: Callable[..., T],
18
+ udfParams: list[inspect.Parameter],
19
+ fabricItemParams: list[inspect.Parameter]):
20
+ """Add parameters to a batched function"""
21
+ # Create provider instances once at decorator level
22
+ provider_factory = ProviderFactory()
23
+ provider_metadata = ProviderMetadata()
24
+
25
+ @wraps(func)
26
+ async def wrapper(*args, **kwargs):
27
+ # get request from kwargs
28
+ req: HttpRequest = None
29
+ if REQ_PARAMETER in kwargs:
30
+ req = kwargs[REQ_PARAMETER]
31
+
32
+ # Get batch size from metadata
33
+ max_batch_size = getattr(func, '__udf_metadata__', {}).get('max_batch_size', None)
34
+
35
+ # Get request body
36
+ content_type = req.headers.get('Content-Type')
37
+ if content_type == None or 'application/json' in content_type:
38
+ body = req.get_json()
39
+
40
+ # Support both batch (list) and scalar (dict) invocations for test/invoke
41
+ if isinstance(body, list):
42
+ # Process as batch
43
+ kwargs[BatchInternalKeys.IS_BATCH] = True
44
+ kwargs[BatchInternalKeys.BATCH_SIZE] = max_batch_size
45
+ kwargs[BatchInternalKeys.BATCH_ITEMS] = body
46
+ elif isinstance(body, dict):
47
+ # Process as scalar (test/invoke compatibility)
48
+ kwargs[BatchInternalKeys.IS_BATCH] = False
49
+ parse_scalar_parameters(body, udfParams, kwargs)
50
+ else:
51
+ # Invalid body type
52
+ kwargs[BatchInternalKeys.IS_BATCH] = True
53
+ kwargs[BatchInternalKeys.BATCH_VALIDATION_ERROR] = UserDataFunctionInvalidInputError(
54
+ message=BatchErrorMessages.BATCH_ARRAY_EXPECTED,
55
+ properties={'receivedType': type(body).__name__, 'expectedType': 'array'}
56
+ )
57
+
58
+ # Apply fabric item providers using shared utility
59
+ apply_fabric_item_providers(
60
+ fabricItemParams, kwargs, func.__name__, req,
61
+ provider_factory, provider_metadata
62
+ )
63
+
64
+ if asyncio.iscoroutinefunction(func):
65
+ return await func(*args, **kwargs)
66
+ else:
67
+ return func(*args, **kwargs)
68
+ return wrapper
@@ -8,6 +8,7 @@ from typing import Callable, TypeVar
8
8
  from fabric.functions.udf_exception import UserDataFunctionInvalidInputError, UserDataFunctionMissingInputError
9
9
  from fabric.internal.arrow import arrow_request
10
10
  from fabric.internal.converters.basic_datatype_converter import BasicDatatypeConverter
11
+ from fabric.internal.utils.parameter_utils import create_missing_input_error, apply_fabric_item_providers
11
12
  from .function_parameter_keywords import REQ_PARAMETER
12
13
  import json
13
14
  import asyncio
@@ -15,26 +16,27 @@ from fabric.internal.providers import ProviderMetadata, ProviderFactory
15
16
 
16
17
  T = TypeVar('T')
17
18
 
18
- def create_missing_input_error(param: inspect.Parameter):
19
- annotation_name = getattr(param.annotation, '__name__', None)
20
- properties = {'parameter_value': "Parameter not found in request"}
21
- if annotation_name:
22
- properties['parameter_type'] = annotation_name
23
- return UserDataFunctionMissingInputError(properties=properties)
24
-
25
19
  def add_parameters(func: Callable[..., T],
26
20
  udfParams: list[inspect.Parameter],
27
21
  fabricItemParams: list[inspect.Parameter]):
22
+ """Add parameters to a scalar (non-batch) function."""
23
+ # Create provider instances once at decorator level
24
+ provider_factory = ProviderFactory()
25
+ provider_metadata = ProviderMetadata()
26
+
28
27
  @wraps(func)
29
28
  async def wrapper(*args, **kwargs):
30
29
  # get request from kwargs
31
- req : HttpRequest = None
30
+ req: HttpRequest = None
32
31
  if REQ_PARAMETER in kwargs:
33
32
  req = kwargs[REQ_PARAMETER]
33
+
34
34
  # find parameters in request and add to kwargs
35
35
  content_type = req.headers.get('Content-Type')
36
36
  if content_type == None or 'application/json' in content_type:
37
37
  body = req.get_json()
38
+
39
+ # Scalar mode - process single item
38
40
  for param in udfParams:
39
41
  if param.name in body:
40
42
  #kwargs[param.name] = body[param.name]
@@ -69,10 +71,11 @@ def add_parameters(func: Callable[..., T],
69
71
  ar_request = arrow_request(arrow_part)
70
72
  pandas_df = ar_request.to_pandas()
71
73
  kwargs[file] = pandas_df
72
- except Exception as e:
73
- kwargs[arg.name] = UserDataFunctionInvalidInputError(properties={'parameter_type': param.annotation.__name__, 'parameter_value': "Unable to parse"})
74
+ except Exception:
75
+ kwargs[param.name] = UserDataFunctionInvalidInputError(properties={'parameter_type': param.annotation.__name__, 'parameter_value': "Unable to parse"})
74
76
  continue
75
-
77
+
78
+ # Validate missing parameters
76
79
  for arg in udfParams:
77
80
  if arg.name not in kwargs:
78
81
  if arg.default != inspect.Parameter.empty:
@@ -80,14 +83,11 @@ def add_parameters(func: Callable[..., T],
80
83
  else:
81
84
  kwargs[arg.name] = create_missing_input_error(arg)
82
85
 
83
- for arg in fabricItemParams:
84
- # Get Provider if it exists for annotation type
85
- provider = ProviderFactory().get_provider(arg.annotation)
86
-
87
- if provider:
88
- item_args = ProviderMetadata().get_kwargs(func.__name__, arg.name)
89
- # Create item from provider and use that instead of FabricItem
90
- kwargs[arg.name] = provider.create(item=kwargs[arg.name], req=req, **item_args)
86
+ # Apply fabric item providers using shared utility
87
+ apply_fabric_item_providers(
88
+ fabricItemParams, kwargs, func.__name__, req,
89
+ provider_factory, provider_metadata
90
+ )
91
91
 
92
92
  if asyncio.iscoroutinefunction(func):
93
93
  return await func(*args, **kwargs)
@@ -0,0 +1,229 @@
1
+ """Batch processing logic for UDF execution."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ from dataclasses import dataclass
6
+ from typing import Any, Callable, List, Optional
7
+
8
+ from ...functions import udf_exception as udf_exceptions
9
+ from ..converters.basic_datatype_converter import BasicDatatypeConverter
10
+ from ..invoke_response import BatchItemResult
11
+ from ..utils.parameter_utils import create_missing_input_error
12
+ from .constants import BatchInternalKeys
13
+
14
+
15
+ @dataclass
16
+ class BatchExecutionResult:
17
+ """Result of executing a batch item or batch operation."""
18
+ item_result: BatchItemResult
19
+ user_error: Optional[Exception] = None
20
+ timeout_error: Optional[Exception] = None
21
+ response_too_large_error: Optional[Exception] = None
22
+ internal_error: Optional[Exception] = None
23
+
24
+
25
+ def _is_parameter_required(param: inspect.Parameter) -> bool:
26
+ """Check if a parameter is required (has no default value)."""
27
+ return param.default == inspect.Parameter.empty
28
+
29
+
30
+ # Internal keys that should be excluded from user function arguments
31
+ _INTERNAL_KEYS = {
32
+ BatchInternalKeys.IS_BATCH,
33
+ BatchInternalKeys.BATCH_SIZE,
34
+ BatchInternalKeys.BATCH_ITEMS,
35
+ BatchInternalKeys.BATCH_VALIDATION_ERROR
36
+ }
37
+
38
+
39
+ async def _execute_single_batch_item(
40
+ func: Callable,
41
+ batch_item: Any,
42
+ udf_params: List,
43
+ args: tuple,
44
+ kwargs: dict,
45
+ check_args_for_exceptions: Callable,
46
+ ensure_response_is_json_serializable: Callable,
47
+ log_and_convert_to_formatted_error: Callable
48
+ ) -> BatchExecutionResult:
49
+ """
50
+ Helper function to execute the UDF for ONE batch item (called multiple times in parallel).
51
+
52
+ This function is invoked once per item in the batch, with all invocations running
53
+ concurrently via asyncio.gather() in process_batch_items().
54
+
55
+ Returns:
56
+ BatchExecutionResult containing the item result and any errors encountered
57
+ """
58
+ item_result = BatchItemResult()
59
+ user_error = None
60
+ timeout_error = None
61
+ response_too_large_error = None
62
+ has_internal_error = None
63
+
64
+ try:
65
+ # Parse batch_item arguments (e.g., {x: 1, y: 2}) into function arguments (e.g., my_func(x=1, y=2))
66
+ item_kwargs = {k: v for k, v in kwargs.items() if k not in _INTERNAL_KEYS}
67
+
68
+ # Extract parameters from dict-formatted batch_item
69
+ if isinstance(batch_item, dict):
70
+ for param in udf_params:
71
+ if param.name in batch_item:
72
+ value = batch_item[param.name]
73
+ # Handle null values: only error if parameter is required
74
+ if value is None and _is_parameter_required(param):
75
+ item_kwargs[param.name] = create_missing_input_error(param)
76
+ else:
77
+ item_kwargs[param.name] = BasicDatatypeConverter.tryconvert(param.annotation.__name__, value)
78
+ else:
79
+ # Parameter missing: only error if required (no default)
80
+ if _is_parameter_required(param):
81
+ item_kwargs[param.name] = create_missing_input_error(param)
82
+ # Otherwise, omit it so Python uses the default value
83
+ # Extract parameters from array-formatted batch_item
84
+ elif isinstance(batch_item, (list, tuple)) and len(udf_params) > 0:
85
+ for pos, param in enumerate(udf_params):
86
+ if pos < len(batch_item):
87
+ value = batch_item[pos]
88
+ # Handle null values: only error if parameter is required
89
+ if value is None and _is_parameter_required(param):
90
+ item_kwargs[param.name] = create_missing_input_error(param)
91
+ else:
92
+ item_kwargs[param.name] = BasicDatatypeConverter.tryconvert(param.annotation.__name__, value)
93
+ else:
94
+ # Parameter missing: only error if required (no default)
95
+ if _is_parameter_required(param):
96
+ item_kwargs[param.name] = create_missing_input_error(param)
97
+ # Otherwise, omit it so Python uses the default value
98
+ # Extract parameter from scalar-formatted batch_item
99
+ elif len(udf_params) == 1:
100
+ param = udf_params[0]
101
+ # Handle null values: only error if parameter is required
102
+ if batch_item is None and _is_parameter_required(param):
103
+ item_kwargs[param.name] = create_missing_input_error(param)
104
+ else:
105
+ item_kwargs[param.name] = BasicDatatypeConverter.tryconvert(param.annotation.__name__, batch_item)
106
+
107
+ # Find parameters that were set to error objects (happens above when required param is missing from item)
108
+ input_exceptions = check_args_for_exceptions(args, item_kwargs)
109
+
110
+ if input_exceptions:
111
+ user_error = input_exceptions[0]
112
+ item_result.errors.extend([log_and_convert_to_formatted_error(ex) for ex in input_exceptions])
113
+ item_result.output = None
114
+ else:
115
+ # Unwrap to original function (parameters already extracted)
116
+ base_func = func
117
+ while hasattr(base_func, '__wrapped__'):
118
+ base_func = base_func.__wrapped__
119
+
120
+ # Filter to only the parameters the original user function declares
121
+ user_param_names = {p.name for p in udf_params}
122
+
123
+ # Only pass parameters the original user function actually declares
124
+ call_kwargs = {k: v for k, v in item_kwargs.items() if k in user_param_names}
125
+
126
+ if asyncio.iscoroutinefunction(base_func):
127
+ resp = await base_func(**call_kwargs)
128
+ else:
129
+ resp = base_func(**call_kwargs)
130
+ item_result.output = ensure_response_is_json_serializable(resp)
131
+
132
+ except Exception as e:
133
+ if issubclass(type(e), udf_exceptions.UserDataFunctionError):
134
+
135
+ if type(e) is udf_exceptions.UserDataFunctionTimeoutError:
136
+ timeout_error = e # 408 Timeout - populate per-item errors
137
+ item_result.errors.append(log_and_convert_to_formatted_error(e))
138
+ elif type(e) is udf_exceptions.UserDataFunctionResponseTooLargeError:
139
+ response_too_large_error = e # 413 Response Too Large - do not populate per-item errors
140
+ elif issubclass(type(e), udf_exceptions.UserThrownError):
141
+ user_error = e # 200 Mixed Success - populate per-item errors
142
+ item_result.errors.append(log_and_convert_to_formatted_error(e))
143
+ else:
144
+ has_internal_error = e # 500 Internal Error - capture exception for top-level error
145
+ else:
146
+ has_internal_error = e
147
+ item_result.output = None
148
+
149
+ return BatchExecutionResult(
150
+ item_result=item_result,
151
+ user_error=user_error,
152
+ timeout_error=timeout_error,
153
+ response_too_large_error=response_too_large_error,
154
+ internal_error=has_internal_error
155
+ )
156
+
157
+
158
+ @dataclass
159
+ class BatchProcessingResult:
160
+ """Result of processing all batch items."""
161
+ batch_results: List[dict]
162
+ user_error: Optional[Exception] = None
163
+ timeout_error: Optional[Exception] = None
164
+ response_too_large_error: Optional[Exception] = None
165
+ internal_error: Optional[Exception] = None
166
+
167
+
168
+ async def process_batch_items(
169
+ func: Callable,
170
+ batch_items: List[Any],
171
+ args: tuple,
172
+ kwargs: dict,
173
+ check_args_for_exceptions: Callable,
174
+ ensure_response_is_json_serializable: Callable,
175
+ log_and_convert_to_formatted_error: Callable
176
+ ) -> BatchProcessingResult:
177
+ """
178
+ Execute the UDF concurrently for each item in the batch using asyncio.
179
+
180
+ Args:
181
+ func: The UDF to execute
182
+ batch_items: List of items to process
183
+ args: Positional arguments for the UDF
184
+ kwargs: Keyword arguments for the UDF
185
+ check_args_for_exceptions: Helper to check for exception objects in arguments
186
+ ensure_response_is_json_serializable: Helper to serialize response
187
+ log_and_convert_to_formatted_error: Helper to format and log errors
188
+
189
+ Returns:
190
+ BatchProcessingResult containing batch results and any errors encountered
191
+ """
192
+ udf_params = getattr(func, '__udf_metadata__', {}).get('udf_params', [])
193
+
194
+ # Execute all batch items concurrently using asyncio.gather
195
+ # Each batch_item runs in parallel via _execute_single_batch_item
196
+ results = await asyncio.gather(
197
+ *[
198
+ _execute_single_batch_item(
199
+ func, batch_item, udf_params, args, kwargs,
200
+ check_args_for_exceptions, ensure_response_is_json_serializable,
201
+ log_and_convert_to_formatted_error
202
+ )
203
+ for batch_item in batch_items
204
+ ],
205
+ return_exceptions=False # Exceptions are handled within _execute_single_batch_item
206
+ )
207
+
208
+ # Aggregate results and error flags
209
+ batch_results = []
210
+ user_error = None
211
+ timeout_error = None
212
+ response_too_large_error = None
213
+ has_internal_error = None
214
+
215
+ for result in results:
216
+ batch_results.append(result.item_result.to_dict())
217
+ # Capture first occurrence of each error type
218
+ user_error = user_error or result.user_error
219
+ timeout_error = timeout_error or result.timeout_error
220
+ response_too_large_error = response_too_large_error or result.response_too_large_error
221
+ has_internal_error = has_internal_error or result.internal_error
222
+
223
+ return BatchProcessingResult(
224
+ batch_results=batch_results,
225
+ user_error=user_error,
226
+ timeout_error=timeout_error,
227
+ response_too_large_error=response_too_large_error,
228
+ internal_error=has_internal_error
229
+ )
@@ -17,9 +17,11 @@ from fabric.internal.openapi_spec_generator import (
17
17
  )
18
18
  from fabric.internal.utils.docstring_parser import extract_summary_description
19
19
  from .ensure_formatted_returntype import ensure_formatted_returntype
20
+ from .ensure_formatted_returntype_batched import ensure_formatted_returntype_batched
20
21
  from .add_timeout import add_timeout
21
22
  from .remove_unused_binding_params import remove_unused_binding_params
22
23
  from .add_parameters import add_parameters
24
+ from .add_batched_parameters import add_batched_parameters
23
25
  from .log_error import log_error
24
26
  from fabric.internal.fabric_lakehouse_files_client import FabricLakehouseFilesClient
25
27
  from pydantic import BaseModel
@@ -33,7 +35,7 @@ from .function_parameter_keywords import (
33
35
 
34
36
 
35
37
  def configure_fabric_function_builder(
36
- udf: FunctionApp, wrap, functions_metadata: List[FunctionMetadata]
38
+ udf: FunctionApp, wrap, functions_metadata: List[FunctionMetadata], max_batch_size=None
37
39
  ) -> Callable[..., Any]:
38
40
  def decorator(func):
39
41
  sig = inspect.signature(func)
@@ -83,14 +85,28 @@ def configure_fabric_function_builder(
83
85
  annotations["return"] = HttpResponse
84
86
  func.__annotations__ = annotations
85
87
 
88
+ # Store udfParams on the function before decorating so batch processing can access them
89
+ if not hasattr(func, '__udf_metadata__'):
90
+ func.__udf_metadata__ = {}
91
+ func.__udf_metadata__['udf_params'] = udfParams
92
+ func.__udf_metadata__['max_batch_size'] = max_batch_size
93
+
94
+ # Check if this is a batched function
95
+ is_batched = max_batch_size is not None
96
+
86
97
  # Add wrapper for function to handle ensure all return values are parsed to HttpResponse
87
98
  user_func = log_error(func)
88
99
  user_func = remove_unused_binding_params(user_func)
89
100
  user_func = add_timeout(user_func)
90
- user_func = ensure_formatted_returntype(user_func)
91
-
92
- # Add parameters to the function
93
- user_func = add_parameters(user_func, udfParams, fabricItemParams)
101
+
102
+ # Use appropriate decorators based on whether function is batched
103
+ if is_batched:
104
+ user_func = ensure_formatted_returntype_batched(user_func)
105
+ user_func = add_batched_parameters(user_func, udfParams, fabricItemParams)
106
+ else:
107
+ user_func = ensure_formatted_returntype(user_func)
108
+ user_func = add_parameters(user_func, udfParams, fabricItemParams)
109
+
94
110
  fb = udf._validate_type(user_func)
95
111
  udf._function_builders.append(fb)
96
112
 
@@ -0,0 +1,50 @@
1
+ class Timeout:
2
+
3
+ FUNC_TIMEOUT_IN_SECONDS = 200
4
+
5
+
6
+ class SizeLimit:
7
+
8
+ RESPONSE_SIZE_LIMIT_IN_MB = 30
9
+
10
+
11
+ class SpecConstants:
12
+ LOCAL_HOST_URL = "http://localhost:7071/api/"
13
+ PUBLIC_URL_DESC = "The public URL to invoke the User Data Function."
14
+ SPEC_FUNCTION_NAME_JSON = "get_udf_oai_spec_json"
15
+ SPEC_FUNCTION_NAME_YAML = "get_udf_oai_spec_yaml"
16
+
17
+
18
+ class HeaderConstants:
19
+ IS_BATCH = "x-ms-fabric-isbatch"
20
+
21
+
22
+ class BatchConstants:
23
+ """Constants for batch execution validation."""
24
+ MIN_BATCH_SIZE = 1
25
+ MAX_BATCH_SIZE = 900
26
+ DEFAULT_BATCH_SIZE = MAX_BATCH_SIZE
27
+
28
+
29
+ class BatchInternalKeys:
30
+ """Internal kwargs keys for batch execution state."""
31
+ IS_BATCH = '__is_batch__'
32
+ BATCH_SIZE = '__batch_size__'
33
+ BATCH_ITEMS = '__batch_items__'
34
+ BATCH_VALIDATION_ERROR = '__batch_validation_error__'
35
+
36
+
37
+ class UDFExceptionCodes:
38
+ INVALID_INPUT = "InvalidInput"
39
+ MISSING_INPUT = "MissingInput"
40
+ RESPONSE_TOO_LARGE = "ResponseTooLarge"
41
+ TIMEOUT = "Timeout"
42
+ USER_THROWN = "UserThrown"
43
+ INTERNAL_ERROR = "InternalError"
44
+
45
+
46
+ class BatchErrorMessages:
47
+ """Error messages for batch execution validation."""
48
+ BATCH_TOO_SMALL = "Batch must contain at least {min_required} item(s)"
49
+ BATCH_TOO_LARGE = "Batch size {batch_size} exceeds maximum allowed size of {max_allowed}"
50
+ BATCH_ARRAY_EXPECTED = "This function is configured for batch execution and expects an array of items as input. The provided data is not an array."