AIP-104: Task Iteration - #62922
AIP-104: Task Iteration#62922dabla wants to merge 10 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
|
Scope change: this PR is now Task Iteration only. Following the feedback from today's Airflow dev call, I have split AIP-104 in two so this PR stays focused on
The split commit is a3d7f65. Besides removing spreading it changes one thing in what stays here: The description and title are updated accordingly. Suggested reading order for the remaining diff: Drafted-by: Claude Fable 5.1; reviewed by @dabla before posting |
Rework:
|
|
Follow-up for the one cost this rework leaves on the table: a mapped upstream ( |
|
Brought level with |
|
|
|
#62922 — AIP-104 Task Iteration (base of the stack) #73688 — AIP-104 Task Spreading #73790 — Chunked reads of a mapped upstream's #73807 — |
|
#70223 (the |
|
Three more commits, following up on the earlier remark about suffixing on the pull side and a gap it uncovered on the state store:
The four stacked PRs are restacked on top; each still one commit. |
|
Small amend: the rename commit is now 742d8b1, binding the runner straight from the |
|
Level with |
|
6579f20 moves |
|
Level with |
|
|
||
| .. _sdk-dynamic-task-mapping-vs-iteration: | ||
|
|
||
| Dynamic Task Mapping vs Iterable Tasks |
There was a problem hiding this comment.
Ash mentioned on Sept 17, in the Slack thread about renaming the AIP, that he wants to softly rename "Dynamic Task Mapping" to just "task mapping" or "mapped tasks", since Loops and the dynamic execution graph are more dynamic than mapping is. This page still uses "Dynamic Task Mapping (DTM)" throughout: the title here, the headings at lines 67 and 370, the comparison table, and "DTM" as shorthand across the prose. Since the page is new, this is the cheap moment to follow that, including the file name and the sdk-dynamic-task-mapping-vs-iteration label that deferred-vs-async-operators.rst links to. Something like "Mapped tasks vs iterable tasks" would read well.
| list_pokemon_task >> get_pokemon_task | ||
|
|
||
|
|
||
| The scheduler only manages a single task. With sync tasks, iterations are |
There was a problem hiding this comment.
This paragraph has it backwards. Threads overlap blocking I/O fine up to task_concurrency: the sync HttpOperator example above, with the request stubbed to sleep, ran 8 requests at once and finished about seven times faster than serially. Pure-Python CPU-bound work gets no speedup from threads under the GIL, which also contradicts "avoid Iterable Tasks when each item represents a long-running or heavy computation" further down. Maybe: threads overlap blocking I/O up to task_concurrency, async scales further because coroutines are cheaper than threads, and CPU-bound work doesn't speed up. A few smaller claims on the page are off too. The benchmark table at the top compares mapped SFTPOperator with hand-written @task loops, none of which use .iterate(), so it should be labelled that way or get an .iterate() row. Line 225 says "For 5 Pokémon" but the example fetches limit=100. Line 258 says iterations share the event loop "(and connection)", but nothing shares a connection, since HttpAsyncHook.session() opens a new session per call.
| them, so a ``dict`` return annotation on the task does not fan its keys out into separate | ||
| XComs the way it does with ``expand()``. Every key an iteration pushes or stores carries its | ||
| index the same way: ``ti.xcom_push("foo", v)`` in iteration 2 lands under ``foo_2``, and so | ||
| does ``task_state_store.set("foo", v)``, so iterations never overwrite each other's values. |
There was a problem hiding this comment.
This holds inside the iteration's own thread or coroutine, but a threading.Thread the task starts, or loop.run_in_executor, doesn't carry the context over. get_current_context() there falls back to the parent's context with its un-indexed ti and task_state_store, so keys pushed from such a thread get no suffix and iterations overwrite each other: with iterate(x=[1, 2, 3]) and a push from a helper thread, only one row survived. A sentence here pointing at asyncio.to_thread or contextvars.copy_context().run(...), both of which do carry it, would cover it.
| entered.append(index) | ||
| if len(entered) == 2: | ||
| both_entered.set() | ||
| await both_entered.wait() |
There was a problem hiding this comment.
The second task finds both_entered already set, so its wait() returns without yielding, and it reads its context and leaves its block before iteration 0 resumes. The reads happen in nesting order, so swapping the ContextVar for a plain thread-local stack still passes this test (and the rest of the context, runner and iterate suites). An await asyncio.sleep(0) after the wait, with both tasks reading while the other is still inside its block, would make it catch that regression.
|
Can you squash commits please? |
Add Iterable Tasks: `.iterate()` and `.iterate_kwargs()` on operators and `@task`, the counterpart of `.expand()` that processes every item inside one task instance instead of creating one task instance per item. - IterableOperator resolves the input by index as `.expand()` does and runs the items on AsyncAwareExecutor: sync operators in a thread pool, async operators concurrently on one event loop, up to `task_concurrency` at a time. - Each item's return value is pushed as `return_value_<index>`, and the task returns an XComIterable, a lazy read-only Sequence over them that a downstream `.expand()` or `.iterate()` consumes. Skipped items are left out, and downstream tasks with `all_success` are skipped, as with a mapped upstream. - Per-item progress is checkpointed in the task state store (AIP-103), tied to the item's input and the attempt that wrote it, so a retry or a clear after a failure resumes the items that already succeeded and a clear after success runs them all again. Outlet events are replayed from the checkpoint. - XComs and task state written from an item carry its index, and each item runs against its own view of the context. - Deferral, reschedule-mode sensors, TriggerDagRunOperator and downstream skipping from an item are rejected with a clear error. - Documented in task-sdk/docs/dynamic-task-mapping-vs-iteration.rst. Co-Authored-By: Tzu-ping Chung <uranusjr@gmail.com> Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The error an iterated async task gets for a synchronous SDK call already points at Variable.aget/aset, which apache#72329 adds; the class docstring still said Variable had no async equivalent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
partial() already prefixes the wrapped operator's task id with the task group, and BaseOperator.__init__ prefixed it again for the IterableOperator, so inside a TaskGroup the task was registered as "tg.tg.f" while its items pushed their XComs for "tg.f", a task id with no task instance. The IterableOperator now gets the bare id, and an iteration takes the task id of the task instance that runs it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BaseOperator.__deepcopy__ calls copy.copy on every attribute in shallow_copy_attrs, which held the lock guarding the sub-tasks in flight, and a lock cannot be copied: deepcopy of an iterated task and dag.partial_subset() failed on any Dag using .iterate(). A copy is another task with nothing in flight, so it now gets a fresh lock and an empty set through the deepcopy memo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The execution timeout unwinds through the executor, which cancels every item's coroutine, and each one left the register of operators in flight before the runner called on_kill(); sync items too, since they were registered in the coroutine rather than in the thread still running execute. The register was also a set, and the sub-operators of one iterated task compare equal, so it never held more than one of them. on_kill() now runs before the executor cancels, operators are registered where their code runs and keyed by identity, the item the timeout strikes directly is killed as it unwinds, and each is killed once although the runner calls on_kill() again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_indexed_task built the indexed task instance without the parent's _ti_context_from_server, so every iteration had no logical date, a template context without dag_run or ds, and get_previous_ti() and get_previous_dagrun() answered for no run at all. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every item failure reached the runner inside a BaseExceptionGroup, and the runner decides by exception type: a retry_policy rule never matched the group, and AirflowSensorTimeout, which the runner fails without a retry, was retried. Fail-fast exceptions are now raised on their own, a single failure unwrapped, and with several failures the retry policy is evaluated on each item's exception and the one whose decision weighs most is raised, the others attached as its cause. IndexedTaskRunner treats the fail-fast exceptions as final for the callbacks too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An iteration is unmapped from the MappedOperator, whose downstream task ids are empty because the edges land on the IterableOperator, so a ShortCircuitOperator took its "no downstream tasks" early return and a branch operator found nothing to skip: every downstream task ran. .iterate() now refuses any SkipMixin operator when the Dag is defined. The check is on the class, since the @task path's can_skip_downstream is False even for @task.short_circuit and @task.branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SUCCESS checkpoint was written before the result was pushed to XCom, and a failing push fell through to the handler that overwrites it with UP_FOR_RETRY, so the retry ran the operator again for work that had finished. Publishing now fails on its own: the checkpoint stays, the task retries, and the retry replays the result from the checkpoint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Squashed commit like you asked, all current commits are related to each comment of the last review round. |
The runner deletes every XCom of the task before an attempt, and a retry that skips an item which already succeeded replayed only its return value and outlet events, so any other key it pushed was lost although the task then succeeded. The keys an item pushes are now kept in memory while it runs, written once with its SUCCESS checkpoint and pushed again when a retry skips it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Was generative AI tooling used to co-author this PR?
Claude Code (Fable 5.1).
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 sub-task 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.XComIterable.flatten()returns aFlattenedXComIterablethat lazily expands nested iterables (e.g. a list of pages into a single stream of items) without ever materializing the flattened stream in memory —__len__/__getitem__/__iter__all speak consistently in flattened items.IterableOperatortracks per-sub-task progress 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 sub-tasks are skipped and only pending/failed ones re-run. XCom is only (re)written per index once a sub-task succeeds; once every index has succeeded, checkpoints are dropped so a subsequent manual clear reruns all indices from scratch rather than replaying stale results.on_killpropagation are handled per sub-task: a checkpointed sub-task replays its recorded outlet events on the following attempt instead of losing them, and killing the IterableOperator's task instance propagates to any sub-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.batch(size=N).iterate(), to be renamed.spread()) 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 sub-task instead of bare keys.IterableOperator.task_typeand.operator_nameboth forward to the wrapped operator (including@task-decorated callables with acustom_operator_name), so sub-tasks report the correct type in the UI/API instead of always showingMappedOperator/IterableOperator.XComIterable.flatten()moved out to Add XComIterable.flatten() to read an iterated task's pages as one sequence #73807, stacked on this PR, so this PR stays about running a task over its input.on_kill()propagates to in-flight sub-tasks, and outlet/asset events recorded by a sub-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 sub-task had already succeeded. Each sub-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 sub-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.