Repository navigation
AIP-104: Task Iteration - #62922
AIP-104: Task Iteration#62922dabla wants to merge 89 commits into
Conversation
d8a30b9 to
edad5de
Compare
There was a problem hiding this comment.
Thanks for working on this — excited to see DTI taking shape for Airflow 3.2. I've gone through the full diff and have feedback on the implementation, some are bugs that would crash at runtime, others are design choices worth iterating on.
A few high-level things:
-
No tests. ~700 lines of new production code with zero test coverage. We need tests for
IterableOperator,TaskExecutor,MappedTaskInstance,HybridExecutor,XComIterable,DecoratedDeferredAsyncOperator, and theiterate/iterate_kwargsmethods — covering success, failure, retry, deferral, and edge cases. -
Worker resilience. Since DTI runs N sub-tasks inside a single worker process, we need to think through what happens when that worker dies mid-execution — the scheduler has no record of which sub-tasks completed. Worth documenting the expected behavior and trade-offs here (and whether we want to add checkpointing later).
-
Thread safety. Several shared mutable structures (
contextdict,os.environ) are accessed concurrently from multiple threads without synchronization. This needs to be addressed before merge.
Inline comments below with specifics.
Thanks for pointing this out. As mentioned earlier on Slack, this PR is currently intended as an initial draft to demonstrate the concept and gather early architectural feedback. I agree that proper test coverage is essential before this can move forward. The plan is to add unit tests covering the components you mentioned (IterableOperator, TaskExecutor, MappedTaskInstance, HybridExecutor, XComIterable, DecoratedDeferredAsyncOperator, and the iterate/iterate_kwargs APIs), including scenarios for success, retries, failures, deferral, and edge cases. Once we converge on the architectural direction, I will add the corresponding test suite.
I agree this is an important architectural concern and worth discussing further. The goal of this prototype is to explore a trade-off between observability and scheduling overhead, @ashb and @potiuk mentioned the same remark before. If we try to preserve the same visibility and lifecycle guarantees as Dynamic Task Mapping, we essentially end up re-implementing DTM semantics, which brings back the same scheduler overhead that this approach is trying to avoid. This proposal intentionally explores a different point in that trade-off space: executing iterations within a single task while allowing controlled parallelism. That does mean the scheduler has indeed less visibility (but also less load) into the internal execution units.
Good point — thread safety needs to be handled carefully here. Regarding the task context, my understanding is that operators already receive a per-task context instance, but you're right that when running iterations concurrently we should avoid sharing mutable structures across threads. One possible approach would be to create a shallow or deep copy of the context for each execution unit to ensure isolation. If you have concerns about specific structures (e.g., os.environ or others), I'm happy to address them and introduce appropriate synchronization or isolation mechanisms where needed. |
960438c to
765fcfb
Compare
|
@uranusjr You should also review this PR since it touches several important modules :) |
b11f852 to
9f2c750
Compare
16ec1fc to
3242037
Compare
|
@kaxil @amoghrajesh @ashb a design question before I go any further, as it touches the runner and the execution API rather than the operator. What I measured. I measured on a retry of an iterated task over ~16,000 items, about 15,400 of which had succeeded on the previous attempt. Since the checkpoints are written a round at a time, reading them back takes seconds. What's left of a retry is the XComs:
So an index that had already succeeded costs three requests per retry, to end up with the same XCom it started with. Nothing else is left in the retry: the task process sends its requests one at a time, and these fill the channel. The question: would you accept that, for an iterated task, the runner doesn't delete the XComs up front, and the operator removes only those whose index ends differently? For example:
The operator would then clear per index, by one rule: an index that runs again clears its own keys (
The one case per index can't cover: a clear that shortens the input leaves the keys past the new length. On the retry above, only the failed indices run again, so this removes both the 29 minutes and the 45 minutes. The alternative that keeps the runner as it is would be a bulk XCom write (and ideally a bulk delete) in the execution API: still two full passes over every key per retry, but in ~100 requests instead of ~46,000. I'd rather not add that if (a) or (b) is acceptable. Which would you prefer, or do you see a reason the up-front clear has to stay for iterated tasks? This is something that has not to be addressed in this PR, any solution could be done in a follow up PR, but I already wanted to ask what would be acceptable. |
Deadline callbacks run by executors read XComs through the same GetXCom handler as tasks (apache#74779). That handler passes the producer's region and pass to the client, None outside a loop, as the task supervisor's request tests already expect.
…k-iteration # Conflicts: # task-sdk/src/airflow/sdk/execution_time/task_runner.py
|
Answering my own question above, since The up-front clear no longer happens for a retry. Since #74222 ("Keep retried task attempts and their data under the attempt UUID", in 3.4) every attempt is its own What is left is the replay. The previous attempt's rows exist, but readers resolve the live attempt: the ORM hides superseded attempts unless a query opts in with Proposal for a follow-up PR, not this one. Let the retry take over the rows the previous attempt already wrote, and keep the checkpoint to what has no XCom row:
Does a promote call like this fit what you have in mind for clearing midway through an AIP-111 loop, where the same question arises for the iterations that are kept? If so I'd open it as its own PR once this one is in: the route and SDK message first, then the operator change. |
… hold the dataset A retry read every checkpoint batch when it started and kept all outcomes, results and pushed XComs included, for the whole attempt: on a large input that is the whole dataset, held until the attempt ends. EarlierCheckpoints still reads the batches once at the start, but keeps an entry as stored only when it carries no values; for one with a result or other XComs it keeps the batch number. state_of() fetches that batch with CheckpointBatch.aread (the async twin of read, on TaskStateStoreAccessor.aget) when one of its indexed tasks is replayed, keeping the last CACHED_BATCHES batches. Indexed tasks replayed together share one fetch per batch; a batch gone since the read leaves its indexed tasks without a checkpoint, so they run again. Measured on a retry of 1,000 items with 64 KiB results, task_concurrency 16: the memory peak drops from 73 MB to 13 MB for 63 extra reads (one per batch with results), at the same duration. Two cached batches avoid every refetch; sixteen double the peak and save no read.
AsyncAwareExecutor.imap_unordered kept its pulled iterators, its calls in flight and its exhausted flag in closure state shared by inner functions. They now live in _UnorderedMap, whose methods replace those closures; imap_unordered keeps its signature, docstring and shutdown check and yields from it. No behaviour change.
# Conflicts: # airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py # task-sdk/src/airflow/sdk/execution_time/task_runner.py
# Conflicts: # airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py # go-sdk/pkg/execution/genmodels/models.gen.go # providers/openlineage/tests/unit/openlineage/extractors/test_manager.py # task-sdk/src/airflow/sdk/definitions/mappedoperator.py # task-sdk/src/airflow/sdk/execution_time/task_runner.py
…6545, so both carry the same change
…ry the same change asend() requests now run on one worker thread owned by the decoder instead of behind one queue per event loop (_LoopQueue/_LoopQueues are gone). The abandoned marker is kept, and the worker is started by the first asend() of a process, as threads do not survive a fork. Same change and tests as apache#76545.
The provider compatibility run against Airflow 3.4.0 failed test_extract_metadata_of_an_iterated_operator_falls_back_to_its_inlets_and_outlets with "'OperatorPartial' object has no attribute 'iterate'": the test was skipped below 3.4 only, and 3.4.0 was released without iterate(). The feature lands in 3.5, so the test is skipped below 3.5 (AIRFLOW_V_3_5_PLUS is new in tests_common) and the documentation says "versionadded:: 3.5.0".
…pers from apache#76545, so both carry the same change
…k-iteration # Conflicts: # task-sdk/src/airflow/sdk/api/client.py
Was generative AI tooling used to co-author this PR?
Claude Code (Fable 5.1).
Generated-by: Claude Code (Fable 5.1) following the guidelines
Description
This PR is the initial implementation of Iterable Tasks (IT), as discussed in the devlist and building upon the foundations of AIP-104. (Originally prototyped as "Dynamic Task Iteration"; renamed to Iterable Tasks following review feedback to avoid confusion with Dynamic Task Mapping.)
For further context on the use cases and performance benefits of IT, see this Medium Article and the new
dynamic-task-mapping-vs-iteration.rstdoc added in this PR, which compares IT with Dynamic Task Mapping (DTM) and Dynamic Task Batching in depth.The XCom Database Constraint Challenge
While porting our internal "monkey-patched" version of IT (used since Airflow 2.x) to the core, I've identified a significant technical hurdle regarding XCom handling.
Around Airflow 2.10/2.11, a change was introduced to the database constraints for the XCom table. Specifically:
map_index >= 0) unless a corresponding mapped TaskInstance exists in thetask_instancetable.The drawback is that XComs wouldn't automatically be removed from the database when a TaskInstance is deleted, which is the purpose of that constraint. So appending the index to the XCom key would be a good enough solution for IT, but not for DTM.
Current implementation in this PR
XComIterable(airflow.sdk.bases.xcom) appends the indexed task's index directly to the XCom key (return_value_<index>) to bypass the constraint, and exposes the results as a lazySequence(__len__/__getitem__/__iter__) so a downstream task can consume them the same way it would consume an.expand()result.IterableOperatortracks the progress of each indexed task in the AIP-103 Task State Store rather than XCom, and participates in Airflow's standard retry mechanism: if the IterableOperator's task instance is retried (or manually cleared before it finishes), already-succeeded indexed tasks are skipped and only pending/failed ones re-run. XCom is only (re)written per index once an indexed task succeeds; once every index has succeeded, a completion marker is written so that a subsequent manual clear reruns all indices from scratch rather than replaying stale results. The checkpoints themselves are kept for the store's retention ([state_store] default_retention_days), so a manual clear of a task that exhausted its retries resumes from them.on_killpropagation are handled per indexed task: a checkpointed indexed task replays its recorded outlet events on the following attempt instead of losing them, and killing the IterableOperator's task instance propagates to any indexed tasks still in flight.I believe the cleanest long-term path is still to add a dedicated route in the Execution API that retrieves multiple XComs for a single TaskInstance by a list of keys in one round trip, so
XComIterable.__getitem__/slicing don't need one request per element. I have a PR open to address this, intentionally split out of this PR.This was also discussed in the devcall, see 2026-06-04 Dev Call Minutes.
AIP-104 itself was discussed again in the latest devcall, where the concerns raised there have also been addressed: 2026-09-10 Dev call Minutes.
Examples
The examples below assume an HTTP connection named
pokeapipointing tohttps://pokeapi.co.Task Iteration
This example fetches a list of Pokémon from the PokéAPI and then uses Iterable Tasks (IT) to retrieve the details of each Pokémon. A single task instance processes all Pokémon URLs.
Comparison
get_pokemon.expand(url=urls)get_pokemon.iterate(url=urls)This demonstrates how Task Iteration can significantly reduce TaskInstance creation overhead. Task Spreading (running one iteration over exactly
NTaskInstances with.spread(across=N).iterate()) is split out into #73688.Notable design points addressed since the initial draft
.iterate()'s dict-argument semantics now match.expand(): passing adictvalue forwards(key, value)pairs to each indexed task instead of bare keys.IterableOperator.operator_nameforwards to the wrapped operator (including@task-decorated callables with acustom_operator_name), so the iterated task reports the correct type in the UI/API instead of always showingMappedOperator/IterableOperator.XComIterable.flatten()moved out to Add flatten() to read the pages of an iterated or spread task as one sequence #73807, stacked on this PR, so this PR stays about running a task over its input.CommsDecoder: a syncsend()waits for the channel instead of raising while anasend()is in flight, one queue per event loop, a cancelledasend()drains its response) is extracted into Let a sync send() wait for the supervisor channel during an asend() #76545 againstmain. This PR depends on it and still carries the samecomms.pychange; it leaves this diff once Let a sync send() wait for the supervisor channel during an asend() #76545 is merged andmainis merged in..iterate()refuses a literal that is no collection (a scalar, a string,None) at parse time on both the classic and the@taskpath, as.expand()does, and the same value from an upstream at run time.execution_timeoutcaps the whole iteration; no limit applies per indexed task, sync or async (one of the same value, started later, could never fire first). AnAirflowTaskTimeouta sync indexed task raises itself (a hook that gave up waiting) is that task's own failure, as it is the mapped task instance's under.expand().on_kill()takes no lock, so the runner's SIGTERM handler cannot hang on the loop thread's own register/unregister; the copyprepare_for_executionmakes gets an iteration state of its own, so a kill in one attempt does not stop the next underdag.test(); anasendcancelled while it waits for the supervisor channel no longer leaves the channel's lock taken or its response unread (CommsDecoder._locked_exchange, see Let a sync send() wait for the supervisor channel during an asend() #76545).KubernetesPodOperatorreattaching,EcsRunTaskOperator(reattach=True)) are listed under "When not to use IT", with{{ ti.index }}as the label that tells the indexed tasks apart.on_kill()propagates to in-flight indexed tasks, stops the iteration from starting any other (one pulled before the kill but not yet started is counted apart and left for the next attempt), and outlet/asset events recorded by an indexed task that already succeeded are replayed from its checkpoint on a later retry instead of being lost.TriggerDagRunOperator, andShortCircuitOperator-style downstream skipping are explicitly rejected insideIterableOperatorwith actionable errors rather than being silently mishandled — see the class docstring for the full list of current limitations.multiple_outputsis ignored for iterated tasks, explicitly at theIterableOperatorlevel. A@taskwith aMappingreturn annotation infersmultiple_outputs=True, but the value the runner pushes for an iterated task is theXComIterableaggregate rather than a dict, so honouring the flag made the runner reject the result after every indexed task had already succeeded. Each indexed task's return value is pushed whole asreturn_value_<index>; keys are not fanned out into separate XComs the way.expand()does. Documented on the class and in the Task SDK docs, and pinned by a runner-level regression test for a dict-returning task under.iterate().Per-iteration keys: XComs and task state
Every iteration of an iterated task runs under the same task instance (same dag id, task id, run id and map index). Anything an iteration writes into a per-task-instance store therefore competes with its siblings for the same key, and with the async executor the winner is whichever iteration finishes last. Two stores are affected, and both now apply the same rule: a key written from inside an iteration carries that iteration's index.
IndexedTaskInstance.xcom_push/axcom_pushsuffix the key with_<index>. That is what makesreturn_value_<index>andXComIterablework, and it applies to any key an operator pushes fromexecute, including the keys of amultiple_outputsdict. Pulls are not suffixed:ti.xcom_pull(task_ids="upstream")reaches the upstream's XCom untouched.context["task_state_store"]). This was a gap: an iteration that stored a watermark or a cursor withtask_state_store.set("last_offset", ...)shared that key with every sibling.IndexedTaskStateStoreAccessorcloses it:IndexedTaskInstance.task_state_storeis the parent's accessor seen through the index, suffixing keys onget/set/deleteand their async twins, and the indexed task's context carries the same object, so an operator does not need to know it is being iterated.clear()is refused inside an iteration, since it would wipe the siblings' state and the operator's own checkpoints; an iteration deletes its own keys instead.IterableOperatorrecords per-index progress in the parent's store under_iterable_<index>and_iterable_completed, written through the parent's accessor, so they are never double-suffixed and never collide with user keys.IndexedTaskRunner(formerlyTaskExecutor, renamed because it read like one of Airflow's executors) builds the context an iteration runs against: a copy of the parent's context with the iteration's own task instance, its indexed state store view and its own outlet events. The operator binds it from thewithstatement, runs the operator inside that block, and records the outcome (checkpoint, XCom push, outlet-event merge) after it, soon_killand the failure callbacks apply to the operator's execution only.{pr_number}.significant.rstor{issue_number}.significant.rst, in airflow-core/newsfragments.