function-sequence 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,58 @@
1
+ """Public errors without automatic inclusion of application values."""
2
+
3
+
4
+ class ScriptError(Exception):
5
+ """Base error for script definition and execution."""
6
+
7
+
8
+ class PipelineError(ScriptError, ValueError):
9
+ """An explicit composition definition or value is invalid."""
10
+
11
+
12
+ class DefinitionError(PipelineError):
13
+ """The queue cannot be executed as defined."""
14
+
15
+
16
+ class ExecutionLimitError(DefinitionError):
17
+ """A configured composition operation or nesting budget is exhausted."""
18
+
19
+
20
+ class InvalidValueError(PipelineError):
21
+ """A value is not bounded, strict JSON data."""
22
+
23
+
24
+ class ResolutionError(PipelineError):
25
+ """An earlier result does not contain the requested path."""
26
+
27
+
28
+ class BusyError(ScriptError):
29
+ """The script or checkpoint is already in use."""
30
+
31
+
32
+ class CheckpointError(ScriptError):
33
+ """Progress could not be read, validated or safely stored."""
34
+
35
+
36
+ class DefinitionMismatchError(CheckpointError):
37
+ """Progress belongs to a different script definition."""
38
+
39
+
40
+ class RecoveryRequiredError(ScriptError):
41
+ """An uncertain step requires explicit retry or restart."""
42
+
43
+
44
+ class StepFailedError(ScriptError):
45
+ """A callable or its result could not be committed."""
46
+
47
+ def __init__(self, step_id: str):
48
+ self.step_id = step_id
49
+ super().__init__(f"Step '{step_id}' did not complete; explicit recovery is required")
50
+
51
+
52
+ class StepError(PipelineError):
53
+ """A selected operation or its mapped value failed."""
54
+
55
+ def __init__(self, step, message):
56
+ self.step_id = step.id
57
+ self.operation = step.operation
58
+ super().__init__(f"step {step.id!r} ({step.operation}): {message}")
@@ -0,0 +1,114 @@
1
+ """Immutable explicit mappings over the same strict values and sequence references."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from .definitions import Ref, _identifier
6
+ from .errors import DefinitionError, InvalidValueError, ResolutionError
7
+ from .values import copy_json as _copy_json, encode_json
8
+
9
+ MAX_BYTES = 1_048_576
10
+ MAX_DEPTH = 32
11
+ MAX_STEPS = 256
12
+
13
+
14
+ def canonical(value):
15
+ return encode_json(value, max_bytes=MAX_BYTES, max_depth=MAX_DEPTH)
16
+
17
+
18
+ def copy_json(value):
19
+ copied = _copy_json(value, max_depth=MAX_DEPTH)
20
+ canonical(copied)
21
+ return copied
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Input:
26
+ name: str
27
+ path: tuple[str | int, ...] = ()
28
+
29
+ def __post_init__(self):
30
+ _identifier(self.name)
31
+ Ref(self.name, self.path)
32
+ if len(self.path) > MAX_DEPTH:
33
+ raise DefinitionError("Input paths exceed the supported limit")
34
+
35
+ def __getitem__(self, part):
36
+ return Input(self.name, (*self.path, part))
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class _Object:
41
+ items: tuple
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class _Array:
46
+ items: tuple
47
+
48
+
49
+ def freeze(value, depth=0):
50
+ if depth > MAX_DEPTH:
51
+ raise DefinitionError("Expression nesting exceeds the supported limit")
52
+ if isinstance(value, (Input, Ref)):
53
+ if len(value.path) > MAX_DEPTH:
54
+ raise DefinitionError("Expression paths exceed the supported limit")
55
+ return value
56
+ if type(value) is dict:
57
+ if any(type(key) is not str for key in value):
58
+ raise DefinitionError("Object keys must be strings")
59
+ return _Object(tuple((key, freeze(item, depth + 1)) for key, item in value.items()))
60
+ if type(value) is list:
61
+ return _Array(tuple(freeze(item, depth + 1) for item in value))
62
+ try:
63
+ return _copy_json(value, depth, max_depth=MAX_DEPTH)
64
+ except InvalidValueError as error:
65
+ raise DefinitionError(str(error)) from error
66
+
67
+
68
+ def thaw(value):
69
+ if isinstance(value, _Object):
70
+ return {key: thaw(item) for key, item in value.items}
71
+ if isinstance(value, _Array):
72
+ return [thaw(item) for item in value.items]
73
+ return value
74
+
75
+
76
+ def expression(value):
77
+ if isinstance(value, Input):
78
+ return {"input": {"name": value.name, "path": list(value.path)}}
79
+ if isinstance(value, Ref):
80
+ return {"ref": {"step": value.step_id, "path": list(value.path)}}
81
+ if isinstance(value, _Object):
82
+ return {"object": {key: expression(item) for key, item in value.items}}
83
+ if isinstance(value, _Array):
84
+ return {"array": [expression(item) for item in value.items]}
85
+ return {"value": value}
86
+
87
+
88
+ def references(value):
89
+ if isinstance(value, (Input, Ref)):
90
+ yield value
91
+ elif isinstance(value, (_Object, _Array)):
92
+ for item in (item for _, item in value.items) if isinstance(value, _Object) else value.items:
93
+ yield from references(item)
94
+
95
+
96
+ def resolve(value, inputs, results):
97
+ if isinstance(value, (Input, Ref)):
98
+ selected = inputs if isinstance(value, Input) else results
99
+ name = value.name if isinstance(value, Input) else value.step_id
100
+ try:
101
+ selected = selected[name]
102
+ for part in value.path:
103
+ if (type(part) is str and type(selected) is dict) or (type(part) is int and type(selected) is list):
104
+ selected = selected[part]
105
+ else:
106
+ raise KeyError(part)
107
+ except (KeyError, IndexError) as error:
108
+ raise ResolutionError("Expression path cannot be resolved") from error
109
+ return copy_json(selected)
110
+ if isinstance(value, _Object):
111
+ return {key: resolve(item, inputs, results) for key, item in value.items}
112
+ if isinstance(value, _Array):
113
+ return [resolve(item, inputs, results) for item in value.items]
114
+ return value
@@ -0,0 +1,191 @@
1
+ """Explicit immutable operation contracts and native Python resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ import inspect
8
+ from types import MappingProxyType, UnionType
9
+ from typing import Any, Literal, Protocol, Union, get_args, get_origin, get_type_hints, runtime_checkable
10
+
11
+ from ._validation import check_schema, validate_value
12
+ from ._budget import consume_operation, execution_scope
13
+ from .definitions import _identifier, _is_async_callable
14
+ from .errors import DefinitionError
15
+ from .expressions import canonical, copy_json
16
+
17
+
18
+ def schema_json(value):
19
+ if isinstance(value, Mapping):
20
+ return {key: schema_json(item) for key, item in value.items()}
21
+ if isinstance(value, (list, tuple)):
22
+ return [schema_json(item) for item in value]
23
+ return value
24
+
25
+
26
+ def _immutable(value):
27
+ if type(value) is dict:
28
+ return MappingProxyType({key: _immutable(item) for key, item in value.items()})
29
+ if type(value) is list:
30
+ return tuple(_immutable(item) for item in value)
31
+ return value
32
+
33
+
34
+ def validate_json_value(schema, value, path="$value"):
35
+ schema = schema_json(schema)
36
+ check_schema(schema)
37
+ value = copy_json(value)
38
+ validate_value(schema, value, path)
39
+ return value
40
+
41
+
42
+ def _annotation_schema(annotation):
43
+ if annotation in (inspect.Signature.empty, Any):
44
+ return {}
45
+ if annotation is None or annotation is type(None):
46
+ return {"type": "null"}
47
+ primitive = {str: "string", bool: "boolean", int: "integer", float: "number", list: "array", dict: "object"}
48
+ if annotation in primitive:
49
+ return {"type": primitive[annotation]}
50
+ origin, args = get_origin(annotation), get_args(annotation)
51
+ if origin in (Union, UnionType):
52
+ return {"anyOf": [_annotation_schema(item) for item in args]}
53
+ if origin is Literal:
54
+ return {"enum": list(args)}
55
+ if origin is list:
56
+ return {"type": "array", "items": _annotation_schema(args[0]) if args else {}}
57
+ if origin is dict and (not args or args[0] is str):
58
+ return {"type": "object", "additionalProperties": _annotation_schema(args[1]) if args else {}}
59
+ # Native callables may omit a portable annotation contract. Callers can
60
+ # supply explicit schemas; native execution does not require a model system.
61
+ return {}
62
+
63
+
64
+ def _signature_contract(function):
65
+ signature = inspect.signature(function)
66
+ try:
67
+ hints = get_type_hints(function)
68
+ except Exception:
69
+ hints = {}
70
+ properties, required, additional = {}, [], False
71
+ for name, parameter in signature.parameters.items():
72
+ if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.VAR_POSITIONAL):
73
+ raise DefinitionError("Resolved operations require keyword arguments; use Script for positional calls")
74
+ if parameter.kind is parameter.VAR_KEYWORD:
75
+ additional = True
76
+ continue
77
+ properties[name] = _annotation_schema(hints.get(name, parameter.annotation))
78
+ if parameter.default is parameter.empty:
79
+ required.append(name)
80
+ return signature, {"type": "object", "properties": properties, "required": required,
81
+ "additionalProperties": additional}, _annotation_schema(hints.get("return", signature.return_annotation))
82
+
83
+
84
+ @dataclass(frozen=True, init=False)
85
+ class Operation:
86
+ name: str
87
+ version: str
88
+ input_schema: Mapping
89
+ output_schema: Mapping | None
90
+ is_async: bool
91
+ _function: Any
92
+ _signature: inspect.Signature
93
+ _serializer: Any
94
+
95
+ def __init__(self, name, function, *, version="1", input_schema=None,
96
+ output_schema=None, is_async=None, serializer=None):
97
+ if type(name) is not str or not name or len(name) > 512:
98
+ raise DefinitionError("Operation names require 1–512 characters")
99
+ copy_json(name)
100
+ _identifier(version)
101
+ if not callable(function):
102
+ raise DefinitionError("An operation requires an explicit callable")
103
+ signature, inferred_input, inferred_output = _signature_contract(function)
104
+ input_schema = copy_json(schema_json(inferred_input if input_schema is None else input_schema))
105
+ output_schema = copy_json(schema_json(inferred_output if output_schema is None else output_schema))
106
+ check_schema(input_schema)
107
+ check_schema(output_schema)
108
+ if input_schema.get("type") != "object":
109
+ raise DefinitionError("Operation inputs require an object contract")
110
+ asynchronous = _is_async_callable(function) if is_async is None else is_async
111
+ if type(asynchronous) is not bool or (serializer is not None and not callable(serializer)):
112
+ raise DefinitionError("Use a boolean async flag and a callable result serializer")
113
+ for key, value in (("name", name), ("version", version), ("input_schema", _immutable(input_schema)),
114
+ ("output_schema", _immutable(output_schema)), ("is_async", asynchronous),
115
+ ("_function", function), ("_signature", signature), ("_serializer", serializer)):
116
+ object.__setattr__(self, key, value)
117
+ canonical(self.describe())
118
+
119
+ def describe(self):
120
+ return {"id": self.name, "version": self.version, "input": schema_json(self.input_schema),
121
+ "output": schema_json(self.output_schema), "async": self.is_async}
122
+
123
+ def validate_shape(self, names):
124
+ try:
125
+ self._signature.bind(**dict.fromkeys(names))
126
+ except TypeError as error:
127
+ raise DefinitionError(str(error)) from error
128
+
129
+ def validate(self, arguments):
130
+ value = validate_json_value(self.input_schema, arguments, "$arguments")
131
+ self.validate_shape(value)
132
+ return value
133
+
134
+ def invoke(self, arguments):
135
+ values = self.validate(arguments)
136
+ consume_operation()
137
+ return self._function(**values)
138
+
139
+ def serialize_result(self, result):
140
+ if self._serializer is not None:
141
+ result = self._serializer(result)
142
+ return validate_json_value(self.output_schema, result, "$result")
143
+
144
+ async def ainvoke(self, arguments):
145
+ with execution_scope():
146
+ result = self.invoke(arguments)
147
+ if inspect.isawaitable(result):
148
+ result = await result
149
+ return self.serialize_result(result)
150
+
151
+
152
+ @runtime_checkable
153
+ class Resolver(Protocol):
154
+ def resolve(self, name: str) -> Operation:
155
+ """Return only an explicitly selected operation."""
156
+ ...
157
+
158
+
159
+ class NativeResolver:
160
+ """Snapshot explicitly supplied ordinary functions or contracted operations."""
161
+
162
+ def __init__(self, operations: Mapping[str, Any], *, version="1"):
163
+ _identifier(version)
164
+ if not isinstance(operations, Mapping):
165
+ raise DefinitionError("Supply an explicit mapping of operation names")
166
+ selected = {}
167
+ for name, function in operations.items():
168
+ operation = function if isinstance(function, Operation) else Operation(name, function, version=version)
169
+ if operation.name != name:
170
+ raise DefinitionError("Operation mapping name does not match its identity")
171
+ selected[name] = operation
172
+ self._operations = MappingProxyType(selected)
173
+ self.version = version
174
+
175
+ def resolve(self, name):
176
+ try:
177
+ return self._operations[name]
178
+ except KeyError as error:
179
+ raise DefinitionError(f"Operation {name!r} is not selected") from error
180
+
181
+ def describe(self, name):
182
+ return self.resolve(name)
183
+
184
+ def invoke(self, name, arguments):
185
+ return self.resolve(name).invoke(arguments)
186
+
187
+ def serialize_result(self, name, result):
188
+ return self.resolve(name).serialize_result(result)
189
+
190
+ def definitions(self):
191
+ return tuple(self._operations[name] for name in sorted(self._operations))
@@ -0,0 +1,279 @@
1
+ """Immutable explicit pipelines over application-supplied operation resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import hashlib
7
+ import inspect
8
+
9
+ from .definitions import Script, _identifier as identifier
10
+ from .errors import DefinitionError, PipelineError, StepError, StepFailedError, ResolutionError
11
+ from .expressions import Input, Ref, _Array, _Object, MAX_STEPS, canonical, copy_json, expression, freeze, references, resolve, thaw
12
+ from .operations import NativeResolver, Operation, Resolver, schema_json as _schema_json, validate_json_value
13
+
14
+
15
+ @dataclass(frozen=True, init=False)
16
+ class Step:
17
+ id: str
18
+ operation: str
19
+ _arguments: _Object
20
+
21
+ def __init__(self, id: str, operation: str, arguments: dict):
22
+ identifier(id)
23
+ if type(operation) is not str or not operation or len(operation) > 512:
24
+ raise DefinitionError("A step requires a bounded operation name")
25
+ if type(arguments) is not dict:
26
+ raise DefinitionError("Step arguments must be an object")
27
+ object.__setattr__(self, "id", id)
28
+ object.__setattr__(self, "operation", operation)
29
+ object.__setattr__(self, "_arguments", freeze(arguments))
30
+ canonical(expression(self._arguments))
31
+
32
+ @property
33
+ def arguments(self):
34
+ return thaw(self._arguments)
35
+
36
+
37
+ @dataclass(frozen=True, init=False)
38
+ class Pipeline:
39
+ name: str
40
+ version: str
41
+ steps: tuple[Step, ...]
42
+ _outputs: _Object
43
+
44
+ def __init__(self, name: str, *, version: str, steps: tuple[Step, ...], outputs: dict):
45
+ identifier(name)
46
+ identifier(version)
47
+ if type(steps) is not tuple or not 1 <= len(steps) <= MAX_STEPS or any(type(step) is not Step for step in steps):
48
+ raise DefinitionError(f"A pipeline requires a tuple of 1–{MAX_STEPS} Steps")
49
+ previous = set()
50
+ for step in steps:
51
+ if step.id in previous:
52
+ raise DefinitionError(f"Duplicate step {step.id!r}")
53
+ for ref in references(step._arguments):
54
+ if isinstance(ref, Ref) and ref.step_id not in previous:
55
+ raise DefinitionError(f"step {step.id!r}: reference must name an earlier step: {ref.step_id!r}")
56
+ previous.add(step.id)
57
+ if type(outputs) is not dict:
58
+ raise DefinitionError("Outputs must be an explicit object")
59
+ frozen = freeze(outputs)
60
+ if any(isinstance(ref, Ref) and ref.step_id not in previous for ref in references(frozen)):
61
+ raise DefinitionError("Output reference names an unknown step")
62
+ for key, value in (("name", name), ("version", version), ("steps", steps), ("_outputs", frozen)):
63
+ object.__setattr__(self, key, value)
64
+ canonical(self.manifest)
65
+
66
+ @property
67
+ def outputs(self):
68
+ return thaw(self._outputs)
69
+
70
+ @property
71
+ def manifest(self):
72
+ return {"schema": 2, "name": self.name, "version": self.version,
73
+ "steps": [{"id": step.id, "operation": step.operation,
74
+ "arguments": expression(step._arguments)} for step in self.steps],
75
+ "outputs": expression(self._outputs)}
76
+
77
+ def bind(self, resolver: Resolver, *, resolver_version: str) -> BoundPipeline:
78
+ return BoundPipeline(self, resolver, resolver_version)
79
+
80
+
81
+ def _partial(schema, value, inputs=None):
82
+ """Validate known portions; unknown producer values are checked at invocation."""
83
+ if isinstance(value, Ref):
84
+ return
85
+ if isinstance(value, Input):
86
+ if inputs is not None:
87
+ validate_json_value(schema, resolve(value, inputs, {}))
88
+ return
89
+ if "anyOf" in schema:
90
+ for branch in schema["anyOf"]:
91
+ try:
92
+ _partial(branch, value, inputs)
93
+ break
94
+ except (ValueError, TypeError):
95
+ pass
96
+ else:
97
+ raise DefinitionError("Mapping does not match any declared type")
98
+ if isinstance(value, _Object):
99
+ values = dict(value.items)
100
+ if "type" in schema:
101
+ validate_json_value({"type": schema["type"]}, {})
102
+ if any(name not in values for name in schema.get("required", ())):
103
+ raise DefinitionError("A required argument is missing")
104
+ properties = schema.get("properties", {})
105
+ additional = schema.get("additionalProperties", True)
106
+ for key, item in value.items:
107
+ if key not in properties and additional is False:
108
+ raise DefinitionError(f"Unexpected argument {key!r}")
109
+ _partial(properties.get(key, additional if isinstance(additional, dict) else {}), item, inputs)
110
+ elif isinstance(value, _Array):
111
+ if "type" in schema:
112
+ validate_json_value({"type": schema["type"]}, [])
113
+ for item in value.items:
114
+ _partial(schema.get("items", {}), item, inputs)
115
+ else:
116
+ validate_json_value(schema, value)
117
+ if not tuple(references(value)):
118
+ validate_json_value(schema, thaw(value))
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class Result:
123
+ """A run's caller-owned JSON snapshots."""
124
+
125
+ results: dict
126
+ outputs: dict
127
+
128
+
129
+ @dataclass(frozen=True, init=False)
130
+ class BoundPipeline:
131
+ definition: Pipeline
132
+ resolver: Resolver
133
+ resolver_version: str
134
+
135
+ def __init__(self, definition, resolver, resolver_version):
136
+ if not isinstance(resolver, Resolver):
137
+ raise DefinitionError("Bind an explicitly selected Resolver")
138
+ identifier(resolver_version)
139
+ selected = {}
140
+ for step in definition.steps:
141
+ try:
142
+ operation = resolver.resolve(step.operation)
143
+ if not isinstance(operation, Operation):
144
+ raise DefinitionError("Resolvers must return an Operation")
145
+ selected[step.operation] = operation
146
+ except Exception as error:
147
+ raise StepError(step, str(error)) from error
148
+ resolver = NativeResolver(selected, version=resolver_version)
149
+ for step in definition.steps:
150
+ try:
151
+ operation = resolver.resolve(step.operation)
152
+ operation.validate_shape(step.arguments)
153
+ schema = _schema_json(operation.input_schema)
154
+ _partial(schema, step._arguments)
155
+ except Exception as error:
156
+ raise StepError(step, str(error)) from error
157
+ object.__setattr__(self, "definition", definition)
158
+ object.__setattr__(self, "resolver", resolver)
159
+ object.__setattr__(self, "resolver_version", resolver_version)
160
+ canonical(self.manifest)
161
+
162
+ @property
163
+ def manifest(self):
164
+ names = sorted({step.operation for step in self.definition.steps})
165
+ return {"definition": self.definition.manifest, "resolver_version": self.resolver_version,
166
+ "operations": [self.resolver.resolve(name).describe() for name in names]}
167
+
168
+ @property
169
+ def fingerprint(self):
170
+ return hashlib.sha256(canonical(self.manifest)).hexdigest()
171
+
172
+ def prepare(self, inputs: dict):
173
+ if type(inputs) is not dict:
174
+ raise PipelineError("Run inputs must be a JSON object")
175
+ inputs = copy_json(inputs)
176
+ for step in self.definition.steps:
177
+ try:
178
+ _partial(_schema_json(self.resolver.describe(step.operation).input_schema), step._arguments, inputs)
179
+ except Exception as error:
180
+ raise StepError(step, str(error)) from error
181
+ for ref in references(self.definition._outputs):
182
+ if isinstance(ref, Input):
183
+ resolve(ref, inputs, {})
184
+ return inputs
185
+
186
+ def finish(self, inputs, results):
187
+ return Result(copy_json(results), resolve(self.definition._outputs, inputs, results))
188
+
189
+ def as_operation(self, name=None, *, input_schema, output_schema):
190
+ """Expose this bound composition through the ordinary operation contract."""
191
+ asynchronous = any(self.resolver.describe(step.operation).is_async for step in self.definition.steps)
192
+ def invoke(**arguments):
193
+ return self.run(arguments).outputs
194
+ async def ainvoke(**arguments):
195
+ return (await self.arun(arguments)).outputs
196
+ return Operation(name or self.definition.name, ainvoke if asynchronous else invoke,
197
+ version=self.fingerprint, input_schema=input_schema,
198
+ output_schema=output_schema, is_async=asynchronous)
199
+
200
+ def compile(self, inputs, *, asynchronous=False):
201
+ """Create a fresh Script; its public runners own pacing and recovery."""
202
+ return compile_script(self, inputs, asynchronous=asynchronous)
203
+
204
+ def run(self, inputs: dict) -> Result:
205
+ inputs = self.prepare(inputs)
206
+ try:
207
+ progress = self.compile(inputs).run()
208
+ except (StepFailedError, ResolutionError) as error:
209
+ _raise_pipeline_error(self, error)
210
+ return self.finish(inputs, progress.results)
211
+
212
+ async def arun(self, inputs: dict) -> Result:
213
+ inputs = self.prepare(inputs)
214
+ try:
215
+ progress = await self.compile(inputs, asynchronous=True).arun()
216
+ except (StepFailedError, ResolutionError) as error:
217
+ _raise_pipeline_error(self, error)
218
+ return self.finish(inputs, progress.results)
219
+
220
+
221
+ def _mapping(value, inputs):
222
+ if isinstance(value, Input):
223
+ return resolve(value, inputs, {})
224
+ if isinstance(value, Ref):
225
+ return value
226
+ if isinstance(value, _Object):
227
+ return {key: _mapping(item, inputs) for key, item in value.items}
228
+ if isinstance(value, _Array):
229
+ return [_mapping(item, inputs) for item in value.items]
230
+ return value
231
+
232
+
233
+ def _wrapper(bound, step, asynchronous):
234
+ def invoke(arguments):
235
+ try:
236
+ result = bound.resolver.invoke(step.operation, arguments)
237
+ if inspect.isawaitable(result):
238
+ if inspect.iscoroutine(result):
239
+ result.close()
240
+ raise DefinitionError("Operation returned an awaitable; use asynchronous execution")
241
+ return copy_json(bound.resolver.serialize_result(step.operation, result))
242
+ except Exception as error:
243
+ raise StepError(step, str(error)) from error
244
+
245
+ async def ainvoke(arguments):
246
+ try:
247
+ result = bound.resolver.invoke(step.operation, arguments)
248
+ if inspect.isawaitable(result):
249
+ result = await result
250
+ return copy_json(bound.resolver.serialize_result(step.operation, result))
251
+ except Exception as error:
252
+ raise StepError(step, str(error)) from error
253
+ return ainvoke if asynchronous else invoke
254
+
255
+
256
+ def compile_script(bound: BoundPipeline, inputs: dict, *, asynchronous=False) -> Script:
257
+ if type(asynchronous) is not bool:
258
+ raise DefinitionError("asynchronous must be a boolean")
259
+ inputs = bound.prepare(inputs)
260
+ if not asynchronous and any(bound.resolver.describe(step.operation).is_async for step in bound.definition.steps):
261
+ raise DefinitionError("Async operations require asynchronous execution")
262
+ version = hashlib.sha256(canonical({"pipeline": bound.fingerprint, "inputs": inputs,
263
+ "asynchronous": asynchronous})).hexdigest()
264
+ script = Script(bound.definition.name, version=version)
265
+ for step in bound.definition.steps:
266
+ script.add_function(_wrapper(bound, step, asynchronous),
267
+ _mapping(step._arguments, inputs), step_id=step.id)
268
+ return script
269
+
270
+
271
+ def _raise_pipeline_error(bound, error):
272
+ if isinstance(error, StepFailedError) and isinstance(error.__cause__, StepError):
273
+ step_error = error.__cause__
274
+ raise step_error from step_error.__cause__
275
+ if isinstance(error, ResolutionError):
276
+ for step in bound.definition.steps:
277
+ if step.id == getattr(error, "step_id", None):
278
+ raise StepError(step, str(error)) from error
279
+ raise error
File without changes