Skip to content

feat(dmap): add the distributed map operation - #849

Draft
nvasiu wants to merge 1 commit into
mainfrom
feat/distributed-map
Draft

nvasiu wants to merge 1 commit into
mainfrom
feat/distributed-map

Conversation

@nvasiu

@nvasiu nvasiu commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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.py

The 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_csv and reader_function. S3Source and ReaderSource are the resolved forms a factory returns.
  • DistributedMapProcessor: describes the Lambda that processes items. The report_batch_outcome and report_item_outcomes factories pick how the processor reports outcomes back. The retry option takes a DistributedMapProcessorRetryConfig holding max_retry_attempts and max_retry_duration, with DistributedMapProcessorRetryConfig.UNLIMITED for an unbounded attempt count.
  • DistributedMapCompletionConfig: defines item failure thresholds for marking the overall map run failed.
  • DistributedMapDestination: the s3_successes and s3_failures factories for routing item records to S3. SuccessDestination and FailureDestination are the resolved forms, and DistributedMapDestinationConfig holds the pair.
  • Each config validates its own arguments on construction, but only for rules that cannot change: required and mutually exclusive fields, the key and format each source type needs, lower bounds such as a positive timeout and a batch size of at least 1, non-negative retry attempts or 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.
  • The enums live here rather than in lambda_service, so config.py has no runtime import from it.

context.py

The 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 a DistributedMapResultConfig types the return as DistributedMapResult and anything else as DistributedMapSummary.
  • Requires max_concurrency to be greater than zero.

dmap/models.py

The result types a customer receives back from a map run.

  • DistributedMapSummary: what ctx.distributed_map returns, describes the run's overall outcome.
  • DistributedMapResult: returned when a DistributedMapResultConfig is 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.
  • The item counts and each collected result's item id are required. A terminal operation that omits a count, or a result that omits its item id, raises an error naming the missing field rather than substituting a value the service never sent.

dmap/helpers.py

Helpers 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_batch and read_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_items takes 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.
  • Each helper takes event as a MutableMapping[str, Any], so a customer can pass the handler's event straight through without a cast.
  • The event and page types are public, so a customer can type their own handler against them: DistributedMapProcessorEvent, DistributedMapProcessorRecord, DistributedMapReaderEvent and ReaderPage.
  • Responses are built from envelope dataclasses rather than hand-built dicts.
  • The helpers validate the invocation input and reject a record that carries no item id, since every outcome is reported against an item id.
  • Every failed item is logged at ERROR with the run ARN, the item id and the error fields, so a failure is traceable in CloudWatch without reading the run's result.

operation/dmap.py

The executor that drives the operation against the durable execution runtime.

  • Suspends the caller's function while the run executes and resumes it with the finished outcome.
  • Every terminal state resolves, and throw_if_error() opts into raising.
  • All translation between the config types and the service shapes happens here.

lambda_service.py

Serialization for carrying the operation and its results to and from the backend service.

  • One dataclass per API shape, named after the shape rather than with a Wire suffix.
  • Items, Output, and the record body are opaque strings, matching the API model, so any serdes works rather than JSON only.
  • The operation parser reads DistributedMapDetails whenever 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.py

Durable execution state handling, so a run's outcome persists across suspend and resume.

  • Records that a distributed map operation carries its outcome on the operation itself rather than as an operation-level result or error.

exceptions.py

The error type a customer catches.

  • DistributedMapError: raised when a run or an item fails.

plugin.py

Operation type registration.

  • Adds DISTRIBUTED_MAP to OperationType.

__init__.py

The package's public API surface.

  • Exports the result types, their enums, the three handler helpers, and the processor and reader event types, matching how durable_execution and durable_step are exported.
  • The input config and factory types are imported from config.

dmap/__init__.py

Empty package marker for the dmap package.

Tests

Tests are split by layer so each sits alongside its module.

  • tests/config_test.py: config and argument validation.
  • tests/lambda_service_test.py and tests/dmap/models_test.py: serialization round trips and the result types.
  • tests/operation/dmap_test.py and tests/context_test.py: executor behaviour and the ctx.distributed_map surface.
  • 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.py and tests/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

  • Add distributed map to the local emulator (in the testing package). When this is done, we can add full end to end tests using the emulator.
  • Add distributed map examples to the examples package.

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:

  • +3187 lines in src and +5781 in tests.

  • New public members: ctx.distributed_map, 16 names added to the package __all__, 19 types and 16 factory methods in config.py, 4 result types in dmap/models.py, 3 handler helpers and 4 event types in dmap/helpers.py, and 1 exception type. 24 dataclasses in lambda_service.py carry the API shapes.

Assumptions

Each assumption about the service, Lambda, the runtime or another library, with its evidence, or marked "unverified" (rule 6):

  • A distributed map operation ends in one of SUCCEEDED, FAILED, STOPPED or TIMED_OUT. Unverified.
  • Every distributed map operation carries DistributedMapDetails, empty until the run starts. Unverified.
  • A terminal operation's DistributedMapDetails carries SuccessCount, FailureCount and ReadCount, where ReadCount is the number of items read from the source, carries TotalCount once the run succeeded, carries SourceExhausted once DistributedMapRunArn is present, and reports a run failure as Error there rather than as an operation-level error. Unverified.
  • A run ARN is the parent durable execution ARN, then /distributed-map-run/, then a run id containing no further /. Unverified.
  • Every collected result in Results carries ItemId and a Status of SUCCEEDED or FAILED, with the item's value in Output as a string the customer's serdes decodes. Unverified.
  • A processor invocation payload carries a records list, each record holding a non-empty string itemId and a body the customer's serdes decodes. Unverified.
  • The service matches a reported outcome back to its item by the itemId the processor echoes, and accepts the batch-failure and item-outcome response shapes the helpers return. Unverified.
  • A reader invocation payload carries an integer maxItemsPerPage, and state as the reader last returned it. Unverified.
  • The service accepts the source, processor, completion and destination configuration the checkpoint sends, with MaxRetryAttempts of -1 meaning unlimited attempts and MaxRetryDurationSeconds a whole number of seconds. Unverified.
  • The service rejects a configuration value that exceeds one of its quotas, and does so on the checkpoint call rather than once the run has started. Verified for the inline source size, the reader state size and the S3 destination key prefix, which are validated in the service with a message naming the field and the limit. The remaining quotas are enforced by model constraints on the request, so the rejection message is generated by the service framework and its wording is unverified.

Decisions not covered by the issue or the design note

One line each, with the reason (rule 7):

  • A missing count or item id raises ExecutionError, because the other checks in the same parse path raise it.
  • DistributedMapProcessorRetryConfig.UNLIMITED is the string "unlimited" rather than the wire sentinel, so a caller never writes a magic number.
  • The source factories are flat on DistributedMapSource, named s3_json_lines and so on, so the factory name states the source kind in one call.
  • DistributedMapDestination carries the factories and DistributedMapDestinationConfig holds on_success and on_failure, because a destination factory returns one half of that pair rather than the pair itself.
  • The SDK validates no service quota, only rules that cannot change. A quota pinned in the SDK would force customers onto a new SDK version whenever the service changed that quota, and the service rejects an out-of-quota value itself.
  • The validation guards raise rather than assert, because python -O removes asserts and the check would then be absent from the build that most wants it.
  • A processor record with no item id fails the invocation before any item handler runs, rather than failing that record alone, because an outcome cannot be reported for an item that was not named.
  • The durable helpers take boto3_client and plugins rather than one config object, because durable_execution itself takes those two keyword arguments.
  • Each failed item is logged at ERROR from the helper that reports it, because the failure is otherwise visible only in the parent run's result.
  • Items, Output and the record body are opaque strings, so a customer serdes other than JSON works without an SDK change.

Checklist

  • Every new branch has a test that fails without it (rule 4)
  • For a bug fix: the first commit adds a test that fails on the current code (rule 5)
  • Every edited test expectation is listed in the description, with the reason (rule 5)

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch from c95ee1f to b12de90 Compare October 26, 2026 21:40
@nvasiu

nvasiu commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Summary of what changed since the last update on the previous PR.

Changes suggested by @yaythomas

  • DistributedMapS3SourceConfig.from_source removed all fallbacks because they invented a default value to satisfy mypy (and 3/5 were unreachable). Replaced with checks that raise and name what is missing. These use if ... raise instead of assert because python -O removes asserts.

  • report_batch_outcome() / report_item_outcomes(). Names unchanged. Their retry option now nested: one retry argument of type DistributedMapProcessorRetryConfig, holding max_retry_attempts and max_retry_duration, with UNLIMITED moved onto it.

  • ProcessorResponseMode export. Dropped. Only report_batch_outcome and report_item_outcomes set it, and nothing hands it back to a customer, so a customer never needs to name it. The other distributed map config enums were already unexported. It stays importable from config.

Processor retry settings

  • DistributedMapProcessorRetryConfig is a new frozen dataclass holding max_retry_attempts and max_retry_duration. DistributedMapProcessor and both its factories take one retry argument of that type in place of the two flat options. The UNLIMITED sentinel moved onto it.
  • UNLIMITED is declared ClassVar[Literal["unlimited"]] rather than ClassVar[str]. As a str it failed type checking when passed to max_retry_attempts, so a caller using the SDK's own constant got a mypy error. The test that passes the constant now carries a return annotation, since mypy skips an unannotated function body and that is why the suite never caught it.

Destination factories

  • DistributedMapDestination.s3_successes and DistributedMapDestination.s3_failures replace SuccessDestination.from_uri and FailureDestination.from_uri, which are deleted.
  • The class holding on_success and on_failure is renamed DistributedMapDestinationConfig, which frees the name DistributedMapDestination for the factories. DistributedMapConfig.destination takes the renamed type.
  • A destination key prefix over 900 UTF-8 bytes is rejected when the destination is constructed.

Fields the service is required to send

  • SuccessCount, FailureCount and UnprocessedCount are now int | None, defaulting to None. A terminal operation that omits one raises an error naming that count. They previously defaulted to 0, which cannot be told apart from a count the service sent as 0. TotalCount is required once the status is SUCCEEDED, since a run that failed, timed out or was stopped may never have counted its source.
  • A collected result with no ItemId raises, naming the missing field. An empty item id gives a result the caller cannot match to an item.
  • A processor record with no itemId is rejected. The wrappers copy that id onto every outcome they report, so an empty id reports the outcome against no item. The check runs over the whole batch before any item handler is called, so one unusable record fails the invocation rather than the batch running partly.

Durable processor wrappers

  • durable_distributed_map_item_handler and durable_distributed_map_batch_handler take boto3_client and plugins and pass them to durable_execution, so a durable processor can supply its own client or register instrumentation plugins.

Operation parsing

  • The operation parser reads DistributedMapDetails when the key is present rather than when its value is truthy. The service sends the object on every distributed map operation and leaves it empty until the run starts, and an empty object was previously discarded, so it did not survive a parse and serialize round trip.

And resolved some conflicts for the rebase.

*,
config: DistributedMapConfig | None = None,
) -> DistributedMapSummary:
"""Start a distributed map run and resolve with its summary.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this API is prelaunch, shouldn't DurableContext.distributed_map include the preview check here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean there is an existing preview check I could use here? Couldn't find any example in the SDK.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: pending model updates in botocore for DistributedMapOptions, DistributedMapDetails, OperationType.DISTRIBUTED_MAP, and the related shapes. Nothing to change in this PR.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch from b12de90 to 5cbea0b Compare October 29, 2026 00:32
@nvasiu

nvasiu commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Another update, addressing the above comments plus a few changes to match repo conventions.
Details in replies to comments above, other changes below:

Shared constants

  • constants.py: added READER_STATE_LIMIT_BYTES. The 32 KB limit was written out in both dmap/handlers.py and operation/dmap.py, so a change could miss one.
  • dmap/handlers.py, operation/dmap.py: import it, and the two _READER_STATE_LIMIT declarations are deleted. _INLINE_SIZE_LIMIT stays in operation/dmap.py, its only user.

Removed unused code

  • dmap/handlers.py: deleted ProcessorRecord.to_dict, ProcessorEvent.to_dict, ItemResult.from_dict, ItemHandlerResponse.from_dict, ReaderEvent.to_dict and ReaderResponse.from_dict. Each wrapper reads the event and writes the response, so the other direction is the service's side and had no caller. ItemFailure.from_dict stays, test_item_error_data_and_stack_trace_reach_the_parent_result uses it.

Docstrings

  • dmap/handlers.py: the module docstring said these wrappers are not imported from the package. __init__.py exports all five.

Tests

  • tests/e2e/dmap_helpers_int_test.py: durable_distributed_map_item_handler with a result type only result_serdes can write. Fails without the per_item change.
  • tests/dmap/typing_test.py: new, checks the five decorator signatures and DistributedMapResult's output type.
  • tests/config_test.py: NaN and infinity cases for tolerated_failure_percentage.
  • tests/dmap/handlers_test.py: handler calls pass a context.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch 2 times, most recently from 5eb064c to e44bbbf Compare November 2, 2026 22:00
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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_state is 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.

@nvasiu

nvasiu commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Summary of what changed since the last push.

Addressing review comments

  • operation/dmap.py:118: added DistributedMapRunArn.serdes_context(role, *parts) and used it for every value the parent, processor and reader serialize, so a pointer-style serdes no longer writes several values to one key.
    • Documented the serdes context requirement in the serdes.py module docstring. Only the processor output path derives the same context on both sides, so a custom serdes must write a payload it can read back without the context it was given. That constraint was not written down anywhere.
  • lambda_service.py:505: the two distributed map parsers test for error presence instead of truthiness, so an empty error object survives a parse and serialize round trip.
  • dmap/models.py:186: throw_if_error raises from the rebuilt operation error, so the run-level branch keeps the reconstructed cause chain that the item branch already had, and attaches no cause when the error object is empty.
  • exceptions.py:333: added DistributedMapError to _DURABLE_OPERATION_ERROR_REGISTRY, so it reconstructs as itself rather than as the DurableOperationError base.
  • plugin.py:50: _extract_error reads distributed_map_details, so a failed map run reaches the end and change hooks instead of arriving with error=None.
  • lambda_service.py:1644: the start factory copies the subtype from the identifier and the context passes a plain string, so every hook sees a str rather than an enum on the first run and a str on replay. The string sent is unchanged.
  • config.py:779: added _validate_not_bool to every numeric distributed map field, so True and False are rejected instead of being sent as JSON booleans where the API requires a number.
  • context.py:732: source is back to DistributedMapSource | Sequence[Any], consistent with .inline().
  • operation/dmap.py:171: the reader path uses a narrowing cast and the unreachable error branch is deleted.
  • dmap/handlers.py:271: both item wrappers' docstrings state that func, item_serdes and result_serdes are called from several threads when concurrency is above 1.
  • dmap/handlers.py:512: added tests/e2e/dmap_durable_item_replay_test.py, covering a wait inside an item, a resume with a custom result_serdes, and a completed sibling not running again.
  • config.py:890 and config.py:996: added the five S3Source branch tests plus one parameterized test over every named S3 factory, so those invariants and mappings cannot regress silently.
  • dmap/handlers.py:138: added the end-to-end test from an item handler error through to the parent's DistributedMapResult. It pins current behaviour, which is the opposite of what the test was expected to show: the processor sends the error type, message, errorData and stackTrace, and only the type and message reach the parent.

Run arn and item id reach the processor and reader functions

Updated 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.

  • types.py: added DistributedMapItemContext, DistributedMapBatchContext and DistributedMapReaderContext, all exported from the package root.
  • Each of the five wrappers passes the matching context as the last argument to the customer's function, with a logger that stamps the run arn and, for an item, the item id.
  • ProcessorEvent and ReaderEvent require and parse distributedMapRunArn, raising ValidationError when it is absent or invalid.

Other

  • DistributedMapResult.from_operation: new override that raises ValidationError naming from_operation_and_items. The inherited factory returned an empty all while the operation retained every item result.
  • distributed_map_reader: comment on the repeated-state check, which cannot detect a repeat when the serdes returns a pointer.

Tests

  • tests/dmap/handlers_test.py, tests/operation/dmap_test.py, tests/e2e/dmap_helpers_int_test.py: per-value keys and contexts across the parent, processor and reader paths, including concurrency, retries and a second run.
  • tests/e2e/dmap_int_test.py: FileSystemSerDes carrying every item from parent to processor and back, and the subtype arriving as a plain str on first run and replay.
  • tests/config_test.py, tests/context_test.py: the S3 factories and their rejection messages, bool on every numeric field, and any Sequence as a source.
  • Mechanical edits elsewhere: the trailing context parameter, distributedMapRunArn in every envelope, a run arn in the parent fixtures, and distributed_map_details on the PluginExecutor mock.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch 3 times, most recently from f79c9c3 to 88be79c Compare November 12, 2026 21:55
@nvasiu

nvasiu commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

One more quick update because of a service change.

ReadCount replaced UnprocessedCount

  • lambda_service.py, dmap/models.py: unprocessed_count is now read_count, parsed from and written as ReadCount, on both DistributedMapDetails and DistributedMapSummary.
  • The two fields count different things. UnprocessedCount= items read with no outcome. ReadCount = items read regardless of outcome (for inline source every admitted item counts as read).
  • Because the fields are different, all places using UnprocessedCount were updated to use the new ReadCount value.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch from 88be79c to ebb70ee Compare November 20, 2026 17:54
@nvasiu

nvasiu commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Improvements to the authoring helpers, following review feedback:

Helpers instead of wrappers

  • Replaced the five distributed_map_*_handler wrappers with process_distributed_map_items, process_distributed_map_batch and read_distributed_map_page, which customers call inside their own handler, so they keep control of the handler.
  • Durable processors use durable_execution directly, so their config is passed there like any durable function. The boto3_client and plugins options are deleted.
  • The item and batch helpers work in both non-durable and durable handlers. In a durable handler, the item helper runs items with a FLAT ctx.map by default, with a nesting_type option.
  • _validate_concurrency now runs when the helper is called, not at decoration time.

Event types

  • Exported DistributedMapProcessorEvent, DistributedMapProcessorRecord and DistributedMapReaderEvent, renamed from their internal spellings, plus ReaderPage, which a customer now constructs. The helpers take event: MutableMapping[str, Any], matching durable_execution, since the event arrives as a dict and these types are its parsed form.

Per-item error log

  • process_distributed_map_items now writes one ERROR log line for each failed item, with distributedMapRunArn, itemId and the error it returns in batchItemFailures. This means a handler that only raises still leaves a log line with the item's ID.
  • Both forms log through the item context's logger. A non-durable handler's base logger is this module's, and a durable handler's is the branch logger.

Conventions

  • Renamed dmap/handlers.py to dmap/helpers.py, since it no longer provides handlers.

Documentation

  • Each helper's docs say where to call it, which factory takes the Lambda's name, and that the handler must return the helper's result.

Tests

  • Updated the tests to the helpers, and added tests for both item forms, FLAT and nested modes, the per-item error log, and the helper and event types.

@nvasiu
nvasiu force-pushed the feat/distributed-map branch from ebb70ee to c77f431 Compare November 26, 2026 20:30
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.
@nvasiu
nvasiu force-pushed the feat/distributed-map branch from c77f431 to df9280d Compare November 26, 2026 21:21
@@ -0,0 +1,727 @@
"""Authoring helpers for distributed map processor and reader Lambda functions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py can 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.py can hold the reader event and response models plus a reader class that owns state deserialization, page validation, serialization, and reader context construction.
  • DistributedMapRunArn can own the envelope parsing that _run_arn_from() does now, and ItemFailure can own the camelCase error conversion that _error_fields() does now.
  • The three public functions can remain as thin entry points in processor.py and reader.py. Their explicit signatures can replace _reject_unknown_options() and the untyped *args and **kwargs dispatcher.



@dataclass(frozen=True)
class DistributedMapCompletionConfig:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants