Repository navigation
Conversation
c95ee1f to
b12de90
Compare
|
Summary of what changed since the last update on the previous PR. Changes suggested by @yaythomas
Processor retry settings
Destination factories
Fields the service is required to send
Durable processor wrappers
Operation parsing
And resolved some conflicts for the rebase. |
| *, | ||
| config: DistributedMapConfig | None = None, | ||
| ) -> DistributedMapSummary: | ||
| """Start a distributed map run and resolve with its summary. |
There was a problem hiding this comment.
Since this API is prelaunch, shouldn't DurableContext.distributed_map include the preview check here?
There was a problem hiding this comment.
Did you mean there is an existing preview check I could use here? Couldn't find any example in the SDK.
There was a problem hiding this comment.
yes, sorry, I didn't phrase that well. Wondered if there's some sort of preview check, we could usefully do while in pre-release.
There was a problem hiding this comment.
Ah yeah, I couldn't find anything that we could use in the SDK to know whether an API is unreleased/preview or not.
| error["errorType"] = self.error.type | ||
| if self.error.message is not None: | ||
| error["errorMessage"] = self.error.message | ||
| if self.error.data is not None: |
There was a problem hiding this comment.
Could we add an end-to-end test that begins with an item-handler error carrying errorData and stackTrace, then verifies that both fields are present in the parent's DistributedMapResult? The current tests verify the processor response, but not the complete round trip.
There was a problem hiding this comment.
Added the test, but it shows the opposite behaviour. We send all 4 members from the processor, but when we get the error back from the service (in DistributedMapResult), data and stack_trace come back as None.
| result["CallbackOptions"] = self.callback_options.to_dict() | ||
| if self.chained_invoke_options: | ||
| result["ChainedInvokeOptions"] = self.chained_invoke_options.to_dict() | ||
| if self.distributed_map_options: |
There was a problem hiding this comment.
Note: pending model updates in botocore for DistributedMapOptions, DistributedMapDetails, OperationType.DISTRIBUTED_MAP, and the related shapes. Nothing to change in this PR.
b12de90 to
5cbea0b
Compare
|
Another update, addressing the above comments plus a few changes to match repo conventions. Shared constants
Removed unused code
Docstrings
Tests
|
5eb064c to
e44bbbf
Compare
| self, items: Sequence[Any], serdes: SerDes | None | ||
| ) -> list[str]: | ||
| """Serialize each inline item, enforcing the 1 MB cap on the whole list.""" | ||
| serialized_items = [self._serialize(serdes, item) for item in items] |
There was a problem hiding this comment.
FileSystemSerDes keys a file by the serialization context's execution ARN and operation ID. This loop reuses that key for every inline item. The processor and reader wrappers also reuse an empty context for every output, item, and state. I reproduced the result: different values returned the same file pointer, which then read the last value written. Separate handler invocations also used the same path.
Can each serialized value keep an immutable, deterministic reference, with matching context at each producer and consumer boundary? Can tests cover inline items, processor outputs, reader items and state, replay, and concurrent calls with FileSystemSerDes?
There was a problem hiding this comment.
Added a new DistributedMapRunArn.serdes_context(role, *parts) which hashes [run id / role / parts] into the context's operation ID (existing convention in the SDK with create_id_for_step), and fills in the parent execution ARN. Used across each producer/consumer, so they always derive the same context. And added all the related test cases.
There was a problem hiding this comment.
Need to make a clarification here.
Only the processor output path derives the same context on both sides. The new serdes_context() still fixes the above defect, every value gets its own address with no key collisions. But there are 3 input paths that read under a different context than the one they were written with:
- inline items are serialized before the run exists, so there is no run id or item id to derive an address from yet
- reader items are addressed by the reader with its cursor and the item's index, and by the processor with the service's item id
- the reader's
next_stateis written as one call's output and read as the next call's input
This doesn't affect any serdes in the SDK, none of them use the context to locate a value on read. E.g. FileSystemSerDes puts the file path in the payload. A custom serdes that does use the read context will not find the value, so it raises instead of silently returning the wrong one.
ctx.invoke has a similar issue: one Lambda function serializes the payload and a different Lambda function deserializes the payload. The SDK runs only the serializing side.
This wasn't documented before, so I will add the constraint into the serdes.py docstring: a custom SerDes used with ctx.distributed_map or ctx.invoke must write a payload it can read back without the context it was given.
|
Summary of what changed since the last push. Addressing review comments
Run arn and item id reach the processor and reader functionsUpdated the helper wrappers to pass the map run ARN and the item IDs to the customer's functions, so customers can use both for their own logging. Before this change the wrappers passed only the arguments a customer's function needs to do the work. I'll make the same update in the other SDKs.
Other
Tests
|
f79c9c3 to
88be79c
Compare
|
One more quick update because of a service change. ReadCount replaced UnprocessedCount
|
88be79c to
ebb70ee
Compare
|
Improvements to the authoring helpers, following review feedback: Helpers instead of wrappers
Event types
Per-item error log
Conventions
Documentation
Tests
|
ebb70ee to
c77f431
Compare
Add ctx.distributed_map, which runs a processor function over a large item source and resolves with a summary when the run reaches a terminal state. Covers the configuration types, the handler decorators, the result types and the checkpoint translation.
c77f431 to
df9280d
Compare
| @@ -0,0 +1,727 @@ | |||
| """Authoring helpers for distributed map processor and reader Lambda functions. | |||
There was a problem hiding this comment.
dmap/helpers.py combines processor and reader event models, response models, logger construction, validation, serialization, thread-pool execution, and the three public functions process_distributed_map_items(), process_distributed_map_batch(), and read_distributed_map_page(). CONTRIBUTING forbids helper-style grab-bag modules and requires domain classes to own their logic. Can this PR delete dmap/helpers.py and split its code into domain classes as follows?
- A new
dmap/processor.pycan hold the processor event and response models plus a processor class that owns event parsing, serializers, concurrency, item execution, batch execution, context construction, and failure logging. - A new
dmap/reader.pycan hold the reader event and response models plus a reader class that owns state deserialization, page validation, serialization, and reader context construction. DistributedMapRunArncan own the envelope parsing that_run_arn_from()does now, andItemFailurecan own the camelCase error conversion that_error_fields()does now.- The three public functions can remain as thin entry points in
processor.pyandreader.py. Their explicit signatures can replace_reject_unknown_options()and the untyped*argsand**kwargsdispatcher.
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class DistributedMapCompletionConfig: |
There was a problem hiding this comment.
DistributedMapCompletionConfig holds count mode and percentage mode in three optional fields, and __post_init__ decides which combinations are legal. The JavaScript API models these as two exact variants. Can failure_count() return a frozen class with only tolerated_failure_count, and failure_percentage() one with only tolerated_failure_percentage and minimum_sample_size, with a typing test that rejects minimum_sample_size on the count class?
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class S3Source: |
There was a problem hiding this comment.
A LISTED_OBJECTS source can carry both key="in/only-this.jsonl" and key_prefix="in/". __post_init__ accepts it, and DistributedMapS3SourceConfig.from_source() drops key, so the run reads every object under in/. Can S3Source become one frozen class per S3 source type, each holding only the fields that type sends to the service, with a typing test that rejects key on the listed-objects class?
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class DistributedMapSource: |
There was a problem hiding this comment.
DistributedMapSource holds inline, S3, and reader sources as sibling optional fields, and __post_init__ checks that exactly one is set. The executor then needs cast(ReaderSource, source.reader) because mypy cannot see that check. The JavaScript DistributedMapSource holds one definition typed as an exact union. Can DistributedMapSource hold a single field typed as a union of frozen inline, S3, and reader classes, so the exactly-one check and executor cast go away?
| @classmethod | ||
| def inline( | ||
| cls, | ||
| items: Sequence[Any], |
There was a problem hiding this comment.
DistributedMapSource.inline() types its values as Sequence[Any] and its serializer as a bare SerDes. Mypy accepts DistributedMapSource.inline([Customer()], serdes=OrderSerDes()), and OrderSerDes.serialize() receives a Customer at runtime. Can one ItemT connect Sequence[ItemT] to SerDes[ItemT], with a typing test that rejects this call?
|
|
||
| item_id: str | ||
| status: DistributedMapItemStatus | ||
| output: ItemOutput | None = None |
There was a problem hiding this comment.
DistributedMapResultItem names its value field output, while Python BatchItem and the JavaScript distributed-map item both use result. Code that reads .result, including code ported from either API, gets AttributeError here. Can this field be result, with a test that converts a service Output into .result?
| ) | ||
| return DistributedMapResult.from_operation_and_items(operation, items) | ||
|
|
||
| def _deserialize_items( |
There was a problem hiding this comment.
_deserialize_items() converts each lambda_service.DistributedMapResultItem into a dmap.models.DistributedMapResultItem inside the executor. It needs only the API result item, run ARN, and result serializer, not execution state. CONTRIBUTING puts conversion in a from_x factory on the class. Can dmap.models.DistributedMapResultItem.from_api_result_item(api_item, run_arn, result_serdes) own this conversion, with the existing missing-run-ARN test moved to from_api_result_item()?
| return CheckResult.create_started() | ||
|
|
||
| # Ready to suspend (checkpoint exists but not in a terminal or started state) | ||
| return CheckResult.create_is_ready_to_execute(checkpointed_result) |
There was a problem hiding this comment.
This branch suspends on a checkpointed PENDING map without sending a second START. When this branch is replaced with raise AssertionError, all 2,614 tests in the core package still pass. Can tests cover PENDING in the synchronous START response and in a reloaded checkpoint, requiring suspension and no second START?
| WAIT = "WAIT" | ||
| CALLBACK = "CALLBACK" | ||
| CHAINED_INVOKE = "CHAINED_INVOKE" | ||
| DISTRIBUTED_MAP = "DISTRIBUTED_MAP" |
There was a problem hiding this comment.
With the local test runner, a distributed map reaches CheckpointValidator, which raises Unknown operation type, and the runner calls the handler a second time. Can the local runner raise DurableFunctionsTestError("Distributed map is not supported by the testing library yet") before it retries the invocation, with a test that requires that exception and one handler call?
| WAIT = "WAIT" | ||
| CALLBACK = "CALLBACK" | ||
| CHAINED_INVOKE = "CHAINED_INVOKE" | ||
| DISTRIBUTED_MAP = "DISTRIBUTED_MAP" |
There was a problem hiding this comment.
The testing library does not yet model distributed maps, so it is expected that events_to_operations() rejects DistributedMapStarted with InvalidParameterValueException("Unknown event type: DistributedMapStarted"). The defect is that from_execution_history() catches that exception, logs a warning, and replaces the complete operation list with [], while it still returns the execution's SUCCEEDED status. Tests then see a successful execution with no distributed-map operation. Can the cloud runner raise DurableFunctionsTestError("Distributed map is not supported by the testing library yet") from that rejection instead, with a test that requires that exception?
Issue #, if available
N/A
Description of changes
Adds the distributed map operation (
ctx.distributed_map) to the Python SDK:A map run processes a bounded dataset in parallel. A customer starts a map run from a durable function, naming a source to read items from, a processor function to invoke per batch, and concurrency, retry, and failure settings. The service reads items from the source, groups them into batches, invokes the processor for each batch, retries failures, tracks progress, routes successful results and failed items to destinations, and reports completion.
config.pyThe input types a customer constructs to describe a map run, and the distributed map enums.
DistributedMapConfig: optional settings for distributed map.DistributedMapResultConfig: subclass that additionally collects item results inline, selecting the return type statically.DistributedMapSource: factories naming where map run items come from.inline,s3_json_lines,s3_json_array,s3_csv,s3_objects,s3_flattened_json_lines,s3_flattened_json_array,s3_flattened_csvandreader_function.S3SourceandReaderSourceare the resolved forms a factory returns.DistributedMapProcessor: describes the Lambda that processes items. Thereport_batch_outcomeandreport_item_outcomesfactories pick how the processor reports outcomes back. Theretryoption takes aDistributedMapProcessorRetryConfigholdingmax_retry_attemptsandmax_retry_duration, withDistributedMapProcessorRetryConfig.UNLIMITEDfor an unbounded attempt count.DistributedMapCompletionConfig: defines item failure thresholds for marking the overall map run failed.DistributedMapDestination: thes3_successesands3_failuresfactories for routing item records to S3.SuccessDestinationandFailureDestinationare the resolved forms, andDistributedMapDestinationConfigholds the pair.UNLIMITED, a failure percentage between 0 and 100, and a 12-digit bucket owner. No service quota is validated here. The service rejects a value above a quota on the checkpoint call that submits the configuration.lambda_service, soconfig.pyhas no runtime import from it.context.pyThe customer-facing entry point on the durable execution context.
ctx.distributed_map: the method a customer calls to run a distributed map. Overloaded so passing aDistributedMapResultConfigtypes the return asDistributedMapResultand anything else asDistributedMapSummary.max_concurrencyto be greater than zero.dmap/models.pyThe result types a customer receives back from a map run.
DistributedMapSummary: whatctx.distributed_mapreturns, describes the run's overall outcome.DistributedMapResult: returned when aDistributedMapResultConfigis passed. Contains individual map run item outcomes.DistributedMapResultItem: represents a single item's result or error.DistributedMapRunArn: the parsed run ARN, exposing the run id.dmap/helpers.pyHelpers a customer calls from the processor or reader Lambda handler, so a customer writes a plain function rather than implementing the item, batch or reader protocol.
process_distributed_map_items,process_distributed_map_batchandread_distributed_map_page. Each one is called inside the Lambda handler and its return value is what the handler returns, because the service reads the outcome from that return value.process_distributed_map_itemstakes either(event, func)for a non-durable processor or(context, event, func)for a durable one, and rejects a keyword argument that does not belong to the form it was called with.eventas aMutableMapping[str, Any], so a customer can pass the handler's event straight through without a cast.DistributedMapProcessorEvent,DistributedMapProcessorRecord,DistributedMapReaderEventandReaderPage.operation/dmap.pyThe executor that drives the operation against the durable execution runtime.
throw_if_error()opts into raising.lambda_service.pySerialization for carrying the operation and its results to and from the backend service.
Wiresuffix.Items,Output, and the record body are opaque strings, matching the API model, so any serdes works rather than JSON only.DistributedMapDetailswhenever the key is present. The service sends the object on every distributed map operation and leaves it empty until the run starts, so an empty object round trips as an empty object.state.pyDurable execution state handling, so a run's outcome persists across suspend and resume.
exceptions.pyThe error type a customer catches.
DistributedMapError: raised when a run or an item fails.plugin.pyOperation type registration.
DISTRIBUTED_MAPtoOperationType.__init__.pyThe package's public API surface.
durable_executionanddurable_stepare exported.config.dmap/__init__.pyEmpty package marker for the
dmappackage.Tests
Tests are split by layer so each sits alongside its module.
tests/config_test.py: config and argument validation.tests/lambda_service_test.pyandtests/dmap/models_test.py: serialization round trips and the result types.tests/operation/dmap_test.pyandtests/context_test.py: executor behaviour and thectx.distributed_mapsurface.tests/dmap/helpers_test.py: handler helper tests, checking that they process items, report failures, and reject bad inputs.tests/dmap/typing_test.py: the static types of the helper call forms.tests/e2e/dmap_int_test.pyandtests/e2e/dmap_helpers_int_test.py: end to end tests mocking backend responses, covering suspend and resume, result collection, and throwing on failure.Future tasks
Design
See Rules for every change.
Design note (rule 3), for a new feature, a new option or a public API change: Feature planned internally.
Simpler options considered (rule 2), if the change adds logic: N/A
Net change in source lines and in public API members:
+3187lines insrcand+5781intests.New public members:
ctx.distributed_map, 16 names added to the package__all__, 19 types and 16 factory methods inconfig.py, 4 result types indmap/models.py, 3 handler helpers and 4 event types indmap/helpers.py, and 1 exception type. 24 dataclasses inlambda_service.pycarry the API shapes.Assumptions
Each assumption about the service, Lambda, the runtime or another library, with its evidence, or marked "unverified" (rule 6):
SUCCEEDED,FAILED,STOPPEDorTIMED_OUT. Unverified.DistributedMapDetails, empty until the run starts. Unverified.DistributedMapDetailscarriesSuccessCount,FailureCountandReadCount, whereReadCountis the number of items read from the source, carriesTotalCountonce the run succeeded, carriesSourceExhaustedonceDistributedMapRunArnis present, and reports a run failure asErrorthere rather than as an operation-level error. Unverified./distributed-map-run/, then a run id containing no further/. Unverified.ResultscarriesItemIdand aStatusofSUCCEEDEDorFAILED, with the item's value inOutputas a string the customer's serdes decodes. Unverified.recordslist, each record holding a non-empty stringitemIdand abodythe customer's serdes decodes. Unverified.itemIdthe processor echoes, and accepts the batch-failure and item-outcome response shapes the helpers return. Unverified.maxItemsPerPage, andstateas the reader last returned it. Unverified.MaxRetryAttemptsof-1meaning unlimited attempts andMaxRetryDurationSecondsa whole number of seconds. Unverified.Decisions not covered by the issue or the design note
One line each, with the reason (rule 7):
ExecutionError, because the other checks in the same parse path raise it.DistributedMapProcessorRetryConfig.UNLIMITEDis the string"unlimited"rather than the wire sentinel, so a caller never writes a magic number.DistributedMapSource, nameds3_json_linesand so on, so the factory name states the source kind in one call.DistributedMapDestinationcarries the factories andDistributedMapDestinationConfigholdson_successandon_failure, because a destination factory returns one half of that pair rather than the pair itself.python -Oremoves asserts and the check would then be absent from the build that most wants it.boto3_clientandpluginsrather than one config object, becausedurable_executionitself takes those two keyword arguments.Items,Outputand the record body are opaque strings, so a customer serdes other than JSON works without an SDK change.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.