jason810496 commented on code in PR #70570:
URL: https://github.com/apache/airflow/pull/70570#discussion_r4766886457
##########
airflow-core/adr/lang-sdk/0016-mapped-tasks-across-lang-sdks.md:
##########
@@ -253,204 +261,284 @@ Under `expand_kwargs()`, that signature decides each
instance's dict as a whole:
`partial()` parameter replaces its value instead, as Python's
`expand_kwargs(..., strict=False)`
does. Only a Python Dag's stub can set it; `spread` is always strict.
-For a stub, the supervisor resolves and checks the dict before anything is
bound, in the order
-Python does. The run context's `expand_kwargs` (below) says where this index's
dict is. The
-supervisor reads it once, runs its `map()` callables in the Python sidecar if
it has any (a skip
-from them skips the instance), fails the instance on any key that no binding
carrying `kwarg` names,
-and gives each such binding its value from the result. When `partial()` sets
every parameter, no
-binding carries `kwarg`, so any key fails, as in Python.
-
-With `spread`, the runtime fails a key that `partial()` sets (step 4) and
passes the rest on to the
-handler, whose runtime rejects an unknown one as far as it can.
+The sidecar checks the dict against the `param` entries when it resolves them,
in the order Python
+does. When a Dag definition's `map()` builds the dict, the sidecar cannot see
its keys, so the runtime
+checks them after its callables: a key that no `kwarg` binding names fails the
instance (step 4).
+With `spread`, the runtime fails a key that `partial()` sets and passes the
rest on to the handler,
+whose runtime rejects an unknown one as far as it can.
## What the Execution API sends
-The server sends coordinates, never values: an XCom binding names a row, and
for an unmapped upstream the element of it this index reads.
-The supervisor reads each one through the XCom backend, narrows it, and passes
the runtime a `literal`, so a runtime receives only `literal` and `sequence`.
-`XComRef` and `LiteralValue` carry no parameter name, so a `zip` part can be
either:
+The server resolves nothing per map index, and sends no Dag structure. For a
stub task, `ti_run` forwards its `_arg_bindings` entries as the Dag processor
wrote them, `param` and `kwargs` included.
+The wire models widen today's `xcom` and `literal` kinds, so `ti_run`
validates every kind it forwards:
```python
-class XComRef(BaseModel):
- """One upstream value, read by the supervisor."""
+class _ArgBindingBase(BaseModel):
+ name: str
+ value_schema: ArgValueSchema | None = None
- kind: Literal["xcom"]
+class XComArgBinding(_ArgBindingBase):
+ kind: Literal["xcom"]
task_id: str
- """Task whose ``return_value`` is read."""
- map_index: int | None = None
- """The row of a mapped upstream. Unset reads an unmapped upstream's only
row."""
- element_index: int | None = None
- """Then this element of the row: a list item, or a dict's ``(key, value)``
pair in stored order."""
+class LiteralArgBinding(_ArgBindingBase):
+ kind: Literal["literal"]
+ value: JsonValue | None = None
+ from_default: bool = False
-class LiteralValue(BaseModel):
- """One inline value."""
+class XComSequenceArgBinding(_ArgBindingBase):
+ """A mapped producer's whole output, read as a lazy sequence (decision
8)."""
- kind: Literal["literal"]
+ kind: Literal["sequence"]
+ task_id: str
- value: JsonValue | None = None
+class GroupArg(BaseModel):
+ group_id: str
+ key: str
-ArgPart = Annotated[XComRef | LiteralValue, Field(discriminator="kind")]
+class ParamArgBinding(_ArgBindingBase):
+ """Resolved per map index by the sidecar."""
-class _ArgBindingBase(BaseModel):
- name: str | None = None
- """The parameter. Absent only with ``spread``, which fills several."""
+ kind: Literal["param"]
+ default: JsonValue | None = None
+ """Present exactly when the parameter has a default; ``null`` is a default
of ``None``."""
- value_schema: ArgValueSchema | None = None
+ group_arg: GroupArg | None = None
- apply_map: bool = False
- """Run this argument's ``map()`` callables on the picked value (decision
6)."""
- kwarg: str | None = None
+class KwargsArgBinding(BaseModel):
"""
- ``expand_kwargs()`` only: take this key of the dict.
+ A Dag definition's own task only: this index's ``expand_kwargs()`` dict.
- Set for a parameter ``partial()`` does not set, and with ``strict=False``
for one it does too.
- A stub takes the key from the dict its run context's ``expand_kwargs``
resolves, after any
- ``map()`` callables.
+ Has no name; the binding it resolves to is named ``**``.
"""
- fallback: ArgPart | None = None
+ kind: Literal["kwargs"]
+
+
+TaskArgBinding = Annotated[
+ XComArgBinding | LiteralArgBinding | XComSequenceArgBinding |
ParamArgBinding | KwargsArgBinding,
+ Field(discriminator="kind"),
+]
+```
+
+```python
+class TIRunContext(BaseModel):
+ ...
+ arg_bindings: list[TaskArgBinding] | None = None
"""
- The value when the dict has no ``kwarg`` key.
+ The task's ``_arg_bindings`` entries, as the Dag processor wrote them.
- The signature default, or with ``strict=False`` the ``partial()`` value.
+ For a mapped instance of a Python Dag with stub TaskHandler, the
supervisor replaces them with
+ the sidecar's ``LiteralArgBinding`` and ``XComSequenceArgBinding`` results
before ``StartupDetails``.
"""
- spread: bool = False
+ needs_mapped_length: bool | None = None
"""
- ``expand_kwargs()`` on a Dag definition's own task only: spread the value
into the arguments.
+ Whether the supervisor has to measure this task's return value.
- The value, after any ``map()`` callables, is a dict the runtime spreads
into the handler's
- arguments.
+ Set only for a Lang-SDK task: True when its return value is expanded over
downstream. Derived
+ from ``not is_mapped(task) and any(task.iter_mapped_dependants())``. None
for a Python task,
+ which measures its own.
"""
+```
+## What the sidecar resolves
-class XComArgBinding(_ArgBindingBase, XComRef):
- """An argument read from an upstream task."""
+The sidecar needs the task, its task groups and the tasks it reads. It gets
them from the worker, never from the server:
+| Authoring mode | Where the task comes from |
+|---|---|
+| Python Dag with stub TaskHandler | The sidecar imports the Dag file from the
pinned bundle, as a Python task's runtime does, and takes the real task. The
supervisor asks for it before the runtime receives `StartupDetails`, for every
instance with a map index of 0 or more and `_arg_bindings`. |
+| Dag definition | The runtime sends `ResolveArgBindings` with its serialized
Dag, the JSON it writes for the Dag processor, for every instance with a map
index of 0 or more and `_arg_bindings`. The sidecar rebuilds the task as Task
SDK objects, with a placeholder operator for each upstream task and the task
groups around them. |
+
+The supervisor tells the two apart as the coordinator does when it launches
the task: a file that a coordinator's Dag importer claims is a Dag definition.
+The sidecar then resolves the expand input with the module of decision 9, as a
Python task does, but without the template rendering that
`render_template_fields` adds.
+A stub task's `partial()` literals therefore stay literal, as they do for an
unmapped stub.
+A mapped task group member is not a mapped operator, so for its arguments the
sidecar calls `XComArg.resolve` and `MappedArgument.resolve` directly, the
calls template rendering makes for a Python task.
+It reads values with the requests a Python task sends, `GetXCom`,
`GetXComCount`, `GetXComSequenceItem` and `GetTICount`.
+The supervisor answers them with the stored row, and the sidecar runs the XCom
backend's deserialize itself, so the supervisor never calls back into a sidecar
that is busy resolving.
+An argument the sidecar cannot resolve, such as a missing key or an index past
the end, fails the task with the error a Python task would raise, and follows
the task's retries as that error does.
+In either mode, a task whose parameters disagree with the stored bindings,
such as a parameter one has and the other lacks, fails without retry, since a
retry resolves the same Dag.
+A mapped instance with no `_arg_bindings`, such as one serialized before this
change, keeps ignoring its arguments and starts no sidecar to resolve them.
+
+Resolving is a new job on the sidecar protocol of #75184, beside the XCom
backend calls.
+That protocol widens: today the sidecar can send only its XCom backend call
handshake and results, `GetConnection`, `GetVariable` and `MaskSecret`, and
resolving adds the four requests above.
+The supervisor sends `ResolveTaskArgs`, and the sidecar answers
`ArgBindingsResult` or `ArgBindingsFailed`:
-class LiteralArgBinding(_ArgBindingBase, LiteralValue):
- from_default: bool = False
+```python
+class ResolveTaskArgs(BaseModel):
+ """Supervisor to sidecar: resolve this instance's arguments."""
+ type: Literal["ResolveTaskArgs"] = "ResolveTaskArgs"
+ ti: TaskInstance
+ ti_context: TIRunContext
-class TupleArgBinding(_ArgBindingBase):
- """One ``zip`` element: several values gathered into a single argument."""
+ bundle_info: BundleInfo | None = None
+ dag_rel_path: str | None = None
+ """A Python Dag with stub TaskHandler: where to import the Dag file from,
as in ``StartupDetails``."""
- kind: Literal["tuple"]
+ dag: dict[str, JsonValue] | None = None
+ """A Dag definition: the serialized Dag its runtime sent."""
- parts: list[ArgPart]
- """
- One part per zipped argument, in zip order.
- A ``fillvalue`` standing in at this index is a ``LiteralValue``.
- """
+class ArgBindingsFailed(BaseModel):
+ type: Literal["ArgBindingsFailed"] = "ArgBindingsFailed"
+ outcome: Literal["skip", "fail", "fail_without_retry"]
+ error: str
+```
+`skip` comes from a Python `map()` callable that raised
`AirflowSkipException`, `fail_without_retry` from a mismatch with the stored
bindings, and `fail` from any other error.
+The supervisor acts on it for a Python Dag with stub TaskHandler, and forwards
it to a Dag definition's runtime, which ends the task the same way.
+The supervisor waits for the answer inside its usual loop, so heartbeats keep
running while the sidecar imports and resolves.
+The 60 s limit on a backend call the supervisor makes before the task starts
does not apply, because a Dag-file import can take longer. The task's
`execution_timeout` bounds resolution instead, and a sidecar that exits before
it answers fails the task, with retries, as `fail` does.
+
+Resolution reads key order from the Dag the worker runs, never from storage,
where MySQL may sort JSON keys.
+So the order of a multi-key `expand()` and of a literal dict is the order the
SDK writes, and an SDK writes them in declaration or insertion order, the same
on every serialization.
+Two instances that saw different orders could otherwise pick the same
combination of a cross product.
+
+The sidecar turns each resolved value into a binding with the JSON rules of a
`literal`: a tuple becomes an array, and a `LazyXComSequence` becomes a
`sequence` binding.
+A value that is not JSON-serializable fails the task.
+
+### A Python Dag with stub TaskHandler
+
+The sidecar resolves the real task, `map()` callables included, so the runtime
receives finished values in `TIRunContext.arg_bindings`: `literal`, or
`sequence` for a reduce.
+A callable that raises `AirflowSkipException` skips the instance, and any
other error fails it.
+The runtime has not received `StartupDetails` yet, so the supervisor reports
that skip or failure itself and stops the runtime, as `_fail_before_start` does
for a failure today.
+Reporting a skip from there is new: `_fail_before_start` only records a retry
or a failure.
+
+### A Python task
+
+A Python task starts no sidecar. Its task process resolves the expand input
after the fork, as it does today, by calling the same resolution module the
sidecar calls.
+Both read XComs through the supervisor, with the requests a Python task
already sends.
+
+### A Dag definition
+
+A mapped producer and one instance of the task mapped over it:
+
+```mermaid
+sequenceDiagram
+ participant S as Scheduler
+ participant API as Execution API
+ participant Sup as Supervisor
+ participant Side as Python sidecar
+ participant RT as Lang SDK runtime
+
+ Note over S,RT: Upstream task
+ Sup->>API: ti_run
+ API-->>Sup: TIRunContext with needs_mapped_length
+ Sup->>RT: start task
+ RT->>Sup: return value
+ Sup->>Sup: measure map length
+ Sup->>API: push XCom and map length
+ S->>S: expand the mapped task into N task instances
+
+ Note over S,RT: Mapped task instance i
+ Sup->>API: ti_run
+ API-->>Sup: arg_bindings as stored, no arithmetic
+ Sup->>RT: start task
+ RT->>Sup: ResolveArgBindings with its serialized Dag
+ Sup->>Side: ResolveTaskArgs
+ Side->>Side: rebuild the task with placeholder upstreams
+ Side->>API: get upstream XComs (through Supervisor)
+ API-->>Side: stored rows
+ Side->>Side: deserialize through the XCom backend
+ Side->>Side: resolve the expand input at index i, leave the outermost
.map() off
+ Side-->>Sup: literal and sequence bindings
+ Sup-->>RT: literal and sequence bindings
+ opt .map() callable
+ RT->>RT: apply its own callable
+ end
+ RT->>Sup: return value
+```
-class XComSequenceArgBinding(_ArgBindingBase):
- """A producing task's whole output, as a lazy sequence (decision 8)."""
+The rebuild needs a Task SDK deserializer for the serialized Dag, which does
not exist today.
+Core's `deserialize_dag` builds scheduler objects, and those have no `resolve`.
+A placeholder upstream keeps its task id, whether it is mapped, and its task
group nesting, which `get_relevant_map_indexes` walks to pick a group member's
rows.
Review Comment:
Added it to Consequences.
Addressed in 6ffce7faa2a.
##########
airflow-core/adr/lang-sdk/0016-mapped-tasks-across-lang-sdks.md:
##########
@@ -253,204 +261,284 @@ Under `expand_kwargs()`, that signature decides each
instance's dict as a whole:
`partial()` parameter replaces its value instead, as Python's
`expand_kwargs(..., strict=False)`
does. Only a Python Dag's stub can set it; `spread` is always strict.
-For a stub, the supervisor resolves and checks the dict before anything is
bound, in the order
-Python does. The run context's `expand_kwargs` (below) says where this index's
dict is. The
-supervisor reads it once, runs its `map()` callables in the Python sidecar if
it has any (a skip
-from them skips the instance), fails the instance on any key that no binding
carrying `kwarg` names,
-and gives each such binding its value from the result. When `partial()` sets
every parameter, no
-binding carries `kwarg`, so any key fails, as in Python.
-
-With `spread`, the runtime fails a key that `partial()` sets (step 4) and
passes the rest on to the
-handler, whose runtime rejects an unknown one as far as it can.
+The sidecar checks the dict against the `param` entries when it resolves them,
in the order Python
+does. When a Dag definition's `map()` builds the dict, the sidecar cannot see
its keys, so the runtime
+checks them after its callables: a key that no `kwarg` binding names fails the
instance (step 4).
+With `spread`, the runtime fails a key that `partial()` sets and passes the
rest on to the handler,
+whose runtime rejects an unknown one as far as it can.
## What the Execution API sends
-The server sends coordinates, never values: an XCom binding names a row, and
for an unmapped upstream the element of it this index reads.
-The supervisor reads each one through the XCom backend, narrows it, and passes
the runtime a `literal`, so a runtime receives only `literal` and `sequence`.
-`XComRef` and `LiteralValue` carry no parameter name, so a `zip` part can be
either:
+The server resolves nothing per map index, and sends no Dag structure. For a
stub task, `ti_run` forwards its `_arg_bindings` entries as the Dag processor
wrote them, `param` and `kwargs` included.
+The wire models widen today's `xcom` and `literal` kinds, so `ti_run`
validates every kind it forwards:
```python
-class XComRef(BaseModel):
- """One upstream value, read by the supervisor."""
+class _ArgBindingBase(BaseModel):
+ name: str
+ value_schema: ArgValueSchema | None = None
- kind: Literal["xcom"]
+class XComArgBinding(_ArgBindingBase):
+ kind: Literal["xcom"]
task_id: str
- """Task whose ``return_value`` is read."""
- map_index: int | None = None
- """The row of a mapped upstream. Unset reads an unmapped upstream's only
row."""
- element_index: int | None = None
- """Then this element of the row: a list item, or a dict's ``(key, value)``
pair in stored order."""
+class LiteralArgBinding(_ArgBindingBase):
+ kind: Literal["literal"]
+ value: JsonValue | None = None
+ from_default: bool = False
-class LiteralValue(BaseModel):
- """One inline value."""
+class XComSequenceArgBinding(_ArgBindingBase):
+ """A mapped producer's whole output, read as a lazy sequence (decision
8)."""
- kind: Literal["literal"]
+ kind: Literal["sequence"]
+ task_id: str
- value: JsonValue | None = None
+class GroupArg(BaseModel):
+ group_id: str
+ key: str
-ArgPart = Annotated[XComRef | LiteralValue, Field(discriminator="kind")]
+class ParamArgBinding(_ArgBindingBase):
+ """Resolved per map index by the sidecar."""
-class _ArgBindingBase(BaseModel):
- name: str | None = None
- """The parameter. Absent only with ``spread``, which fills several."""
+ kind: Literal["param"]
+ default: JsonValue | None = None
+ """Present exactly when the parameter has a default; ``null`` is a default
of ``None``."""
- value_schema: ArgValueSchema | None = None
+ group_arg: GroupArg | None = None
- apply_map: bool = False
- """Run this argument's ``map()`` callables on the picked value (decision
6)."""
- kwarg: str | None = None
+class KwargsArgBinding(BaseModel):
"""
- ``expand_kwargs()`` only: take this key of the dict.
+ A Dag definition's own task only: this index's ``expand_kwargs()`` dict.
- Set for a parameter ``partial()`` does not set, and with ``strict=False``
for one it does too.
- A stub takes the key from the dict its run context's ``expand_kwargs``
resolves, after any
- ``map()`` callables.
+ Has no name; the binding it resolves to is named ``**``.
"""
- fallback: ArgPart | None = None
+ kind: Literal["kwargs"]
+
+
+TaskArgBinding = Annotated[
+ XComArgBinding | LiteralArgBinding | XComSequenceArgBinding |
ParamArgBinding | KwargsArgBinding,
+ Field(discriminator="kind"),
+]
+```
+
+```python
+class TIRunContext(BaseModel):
+ ...
+ arg_bindings: list[TaskArgBinding] | None = None
"""
- The value when the dict has no ``kwarg`` key.
+ The task's ``_arg_bindings`` entries, as the Dag processor wrote them.
- The signature default, or with ``strict=False`` the ``partial()`` value.
+ For a mapped instance of a Python Dag with stub TaskHandler, the
supervisor replaces them with
+ the sidecar's ``LiteralArgBinding`` and ``XComSequenceArgBinding`` results
before ``StartupDetails``.
"""
- spread: bool = False
+ needs_mapped_length: bool | None = None
"""
- ``expand_kwargs()`` on a Dag definition's own task only: spread the value
into the arguments.
+ Whether the supervisor has to measure this task's return value.
- The value, after any ``map()`` callables, is a dict the runtime spreads
into the handler's
- arguments.
+ Set only for a Lang-SDK task: True when its return value is expanded over
downstream. Derived
+ from ``not is_mapped(task) and any(task.iter_mapped_dependants())``. None
for a Python task,
+ which measures its own.
"""
+```
+## What the sidecar resolves
-class XComArgBinding(_ArgBindingBase, XComRef):
- """An argument read from an upstream task."""
+The sidecar needs the task, its task groups and the tasks it reads. It gets
them from the worker, never from the server:
+| Authoring mode | Where the task comes from |
+|---|---|
+| Python Dag with stub TaskHandler | The sidecar imports the Dag file from the
pinned bundle, as a Python task's runtime does, and takes the real task. The
supervisor asks for it before the runtime receives `StartupDetails`, for every
instance with a map index of 0 or more and `_arg_bindings`. |
+| Dag definition | The runtime sends `ResolveArgBindings` with its serialized
Dag, the JSON it writes for the Dag processor, for every instance with a map
index of 0 or more and `_arg_bindings`. The sidecar rebuilds the task as Task
SDK objects, with a placeholder operator for each upstream task and the task
groups around them. |
+
+The supervisor tells the two apart as the coordinator does when it launches
the task: a file that a coordinator's Dag importer claims is a Dag definition.
+The sidecar then resolves the expand input with the module of decision 9, as a
Python task does, but without the template rendering that
`render_template_fields` adds.
+A stub task's `partial()` literals therefore stay literal, as they do for an
unmapped stub.
+A mapped task group member is not a mapped operator, so for its arguments the
sidecar calls `XComArg.resolve` and `MappedArgument.resolve` directly, the
calls template rendering makes for a Python task.
+It reads values with the requests a Python task sends, `GetXCom`,
`GetXComCount`, `GetXComSequenceItem` and `GetTICount`.
+The supervisor answers them with the stored row, and the sidecar runs the XCom
backend's deserialize itself, so the supervisor never calls back into a sidecar
that is busy resolving.
+An argument the sidecar cannot resolve, such as a missing key or an index past
the end, fails the task with the error a Python task would raise, and follows
the task's retries as that error does.
+In either mode, a task whose parameters disagree with the stored bindings,
such as a parameter one has and the other lacks, fails without retry, since a
retry resolves the same Dag.
+A mapped instance with no `_arg_bindings`, such as one serialized before this
change, keeps ignoring its arguments and starts no sidecar to resolve them.
+
+Resolving is a new job on the sidecar protocol of #75184, beside the XCom
backend calls.
+That protocol widens: today the sidecar can send only its XCom backend call
handshake and results, `GetConnection`, `GetVariable` and `MaskSecret`, and
resolving adds the four requests above.
+The supervisor sends `ResolveTaskArgs`, and the sidecar answers
`ArgBindingsResult` or `ArgBindingsFailed`:
-class LiteralArgBinding(_ArgBindingBase, LiteralValue):
- from_default: bool = False
+```python
+class ResolveTaskArgs(BaseModel):
+ """Supervisor to sidecar: resolve this instance's arguments."""
+ type: Literal["ResolveTaskArgs"] = "ResolveTaskArgs"
+ ti: TaskInstance
+ ti_context: TIRunContext
-class TupleArgBinding(_ArgBindingBase):
- """One ``zip`` element: several values gathered into a single argument."""
+ bundle_info: BundleInfo | None = None
+ dag_rel_path: str | None = None
+ """A Python Dag with stub TaskHandler: where to import the Dag file from,
as in ``StartupDetails``."""
- kind: Literal["tuple"]
+ dag: dict[str, JsonValue] | None = None
+ """A Dag definition: the serialized Dag its runtime sent."""
- parts: list[ArgPart]
- """
- One part per zipped argument, in zip order.
- A ``fillvalue`` standing in at this index is a ``LiteralValue``.
- """
+class ArgBindingsFailed(BaseModel):
+ type: Literal["ArgBindingsFailed"] = "ArgBindingsFailed"
+ outcome: Literal["skip", "fail", "fail_without_retry"]
+ error: str
+```
+`skip` comes from a Python `map()` callable that raised
`AirflowSkipException`, `fail_without_retry` from a mismatch with the stored
bindings, and `fail` from any other error.
+The supervisor acts on it for a Python Dag with stub TaskHandler, and forwards
it to a Dag definition's runtime, which ends the task the same way.
+The supervisor waits for the answer inside its usual loop, so heartbeats keep
running while the sidecar imports and resolves.
+The 60 s limit on a backend call the supervisor makes before the task starts
does not apply, because a Dag-file import can take longer. The task's
`execution_timeout` bounds resolution instead, and a sidecar that exits before
it answers fails the task, with retries, as `fail` does.
Review Comment:
Done. The Dag-file import is now bounded by the file's import timeout, as a
Python task's own parse is.
Addressed in 6ffce7faa2a.
##########
airflow-core/adr/lang-sdk/0016-mapped-tasks-across-lang-sdks.md:
##########
@@ -253,204 +261,284 @@ Under `expand_kwargs()`, that signature decides each
instance's dict as a whole:
`partial()` parameter replaces its value instead, as Python's
`expand_kwargs(..., strict=False)`
does. Only a Python Dag's stub can set it; `spread` is always strict.
-For a stub, the supervisor resolves and checks the dict before anything is
bound, in the order
-Python does. The run context's `expand_kwargs` (below) says where this index's
dict is. The
-supervisor reads it once, runs its `map()` callables in the Python sidecar if
it has any (a skip
-from them skips the instance), fails the instance on any key that no binding
carrying `kwarg` names,
-and gives each such binding its value from the result. When `partial()` sets
every parameter, no
-binding carries `kwarg`, so any key fails, as in Python.
-
-With `spread`, the runtime fails a key that `partial()` sets (step 4) and
passes the rest on to the
-handler, whose runtime rejects an unknown one as far as it can.
+The sidecar checks the dict against the `param` entries when it resolves them,
in the order Python
+does. When a Dag definition's `map()` builds the dict, the sidecar cannot see
its keys, so the runtime
+checks them after its callables: a key that no `kwarg` binding names fails the
instance (step 4).
+With `spread`, the runtime fails a key that `partial()` sets and passes the
rest on to the handler,
+whose runtime rejects an unknown one as far as it can.
## What the Execution API sends
-The server sends coordinates, never values: an XCom binding names a row, and
for an unmapped upstream the element of it this index reads.
-The supervisor reads each one through the XCom backend, narrows it, and passes
the runtime a `literal`, so a runtime receives only `literal` and `sequence`.
-`XComRef` and `LiteralValue` carry no parameter name, so a `zip` part can be
either:
+The server resolves nothing per map index, and sends no Dag structure. For a
stub task, `ti_run` forwards its `_arg_bindings` entries as the Dag processor
wrote them, `param` and `kwargs` included.
+The wire models widen today's `xcom` and `literal` kinds, so `ti_run`
validates every kind it forwards:
```python
-class XComRef(BaseModel):
- """One upstream value, read by the supervisor."""
+class _ArgBindingBase(BaseModel):
+ name: str
+ value_schema: ArgValueSchema | None = None
- kind: Literal["xcom"]
+class XComArgBinding(_ArgBindingBase):
+ kind: Literal["xcom"]
task_id: str
- """Task whose ``return_value`` is read."""
- map_index: int | None = None
- """The row of a mapped upstream. Unset reads an unmapped upstream's only
row."""
- element_index: int | None = None
- """Then this element of the row: a list item, or a dict's ``(key, value)``
pair in stored order."""
+class LiteralArgBinding(_ArgBindingBase):
+ kind: Literal["literal"]
+ value: JsonValue | None = None
+ from_default: bool = False
-class LiteralValue(BaseModel):
- """One inline value."""
+class XComSequenceArgBinding(_ArgBindingBase):
+ """A mapped producer's whole output, read as a lazy sequence (decision
8)."""
- kind: Literal["literal"]
+ kind: Literal["sequence"]
+ task_id: str
- value: JsonValue | None = None
+class GroupArg(BaseModel):
+ group_id: str
+ key: str
-ArgPart = Annotated[XComRef | LiteralValue, Field(discriminator="kind")]
+class ParamArgBinding(_ArgBindingBase):
+ """Resolved per map index by the sidecar."""
-class _ArgBindingBase(BaseModel):
- name: str | None = None
- """The parameter. Absent only with ``spread``, which fills several."""
+ kind: Literal["param"]
+ default: JsonValue | None = None
+ """Present exactly when the parameter has a default; ``null`` is a default
of ``None``."""
- value_schema: ArgValueSchema | None = None
+ group_arg: GroupArg | None = None
- apply_map: bool = False
- """Run this argument's ``map()`` callables on the picked value (decision
6)."""
- kwarg: str | None = None
+class KwargsArgBinding(BaseModel):
"""
- ``expand_kwargs()`` only: take this key of the dict.
+ A Dag definition's own task only: this index's ``expand_kwargs()`` dict.
- Set for a parameter ``partial()`` does not set, and with ``strict=False``
for one it does too.
- A stub takes the key from the dict its run context's ``expand_kwargs``
resolves, after any
- ``map()`` callables.
+ Has no name; the binding it resolves to is named ``**``.
"""
- fallback: ArgPart | None = None
+ kind: Literal["kwargs"]
+
+
+TaskArgBinding = Annotated[
+ XComArgBinding | LiteralArgBinding | XComSequenceArgBinding |
ParamArgBinding | KwargsArgBinding,
+ Field(discriminator="kind"),
+]
+```
+
+```python
+class TIRunContext(BaseModel):
+ ...
+ arg_bindings: list[TaskArgBinding] | None = None
"""
- The value when the dict has no ``kwarg`` key.
+ The task's ``_arg_bindings`` entries, as the Dag processor wrote them.
- The signature default, or with ``strict=False`` the ``partial()`` value.
+ For a mapped instance of a Python Dag with stub TaskHandler, the
supervisor replaces them with
+ the sidecar's ``LiteralArgBinding`` and ``XComSequenceArgBinding`` results
before ``StartupDetails``.
"""
- spread: bool = False
+ needs_mapped_length: bool | None = None
"""
- ``expand_kwargs()`` on a Dag definition's own task only: spread the value
into the arguments.
+ Whether the supervisor has to measure this task's return value.
- The value, after any ``map()`` callables, is a dict the runtime spreads
into the handler's
- arguments.
+ Set only for a Lang-SDK task: True when its return value is expanded over
downstream. Derived
+ from ``not is_mapped(task) and any(task.iter_mapped_dependants())``. None
for a Python task,
+ which measures its own.
"""
+```
+## What the sidecar resolves
-class XComArgBinding(_ArgBindingBase, XComRef):
- """An argument read from an upstream task."""
+The sidecar needs the task, its task groups and the tasks it reads. It gets
them from the worker, never from the server:
+| Authoring mode | Where the task comes from |
+|---|---|
+| Python Dag with stub TaskHandler | The sidecar imports the Dag file from the
pinned bundle, as a Python task's runtime does, and takes the real task. The
supervisor asks for it before the runtime receives `StartupDetails`, for every
instance with a map index of 0 or more and `_arg_bindings`. |
+| Dag definition | The runtime sends `ResolveArgBindings` with its serialized
Dag, the JSON it writes for the Dag processor, for every instance with a map
index of 0 or more and `_arg_bindings`. The sidecar rebuilds the task as Task
SDK objects, with a placeholder operator for each upstream task and the task
groups around them. |
+
+The supervisor tells the two apart as the coordinator does when it launches
the task: a file that a coordinator's Dag importer claims is a Dag definition.
+The sidecar then resolves the expand input with the module of decision 9, as a
Python task does, but without the template rendering that
`render_template_fields` adds.
+A stub task's `partial()` literals therefore stay literal, as they do for an
unmapped stub.
+A mapped task group member is not a mapped operator, so for its arguments the
sidecar calls `XComArg.resolve` and `MappedArgument.resolve` directly, the
calls template rendering makes for a Python task.
+It reads values with the requests a Python task sends, `GetXCom`,
`GetXComCount`, `GetXComSequenceItem` and `GetTICount`.
+The supervisor answers them with the stored row, and the sidecar runs the XCom
backend's deserialize itself, so the supervisor never calls back into a sidecar
that is busy resolving.
+An argument the sidecar cannot resolve, such as a missing key or an index past
the end, fails the task with the error a Python task would raise, and follows
the task's retries as that error does.
+In either mode, a task whose parameters disagree with the stored bindings,
such as a parameter one has and the other lacks, fails without retry, since a
retry resolves the same Dag.
+A mapped instance with no `_arg_bindings`, such as one serialized before this
change, keeps ignoring its arguments and starts no sidecar to resolve them.
+
+Resolving is a new job on the sidecar protocol of #75184, beside the XCom
backend calls.
+That protocol widens: today the sidecar can send only its XCom backend call
handshake and results, `GetConnection`, `GetVariable` and `MaskSecret`, and
resolving adds the four requests above.
+The supervisor sends `ResolveTaskArgs`, and the sidecar answers
`ArgBindingsResult` or `ArgBindingsFailed`:
-class LiteralArgBinding(_ArgBindingBase, LiteralValue):
- from_default: bool = False
+```python
+class ResolveTaskArgs(BaseModel):
+ """Supervisor to sidecar: resolve this instance's arguments."""
+ type: Literal["ResolveTaskArgs"] = "ResolveTaskArgs"
+ ti: TaskInstance
+ ti_context: TIRunContext
-class TupleArgBinding(_ArgBindingBase):
- """One ``zip`` element: several values gathered into a single argument."""
+ bundle_info: BundleInfo | None = None
+ dag_rel_path: str | None = None
+ """A Python Dag with stub TaskHandler: where to import the Dag file from,
as in ``StartupDetails``."""
- kind: Literal["tuple"]
+ dag: dict[str, JsonValue] | None = None
+ """A Dag definition: the serialized Dag its runtime sent."""
- parts: list[ArgPart]
- """
- One part per zipped argument, in zip order.
- A ``fillvalue`` standing in at this index is a ``LiteralValue``.
- """
+class ArgBindingsFailed(BaseModel):
+ type: Literal["ArgBindingsFailed"] = "ArgBindingsFailed"
+ outcome: Literal["skip", "fail", "fail_without_retry"]
+ error: str
+```
+`skip` comes from a Python `map()` callable that raised
`AirflowSkipException`, `fail_without_retry` from a mismatch with the stored
bindings, and `fail` from any other error.
+The supervisor acts on it for a Python Dag with stub TaskHandler, and forwards
it to a Dag definition's runtime, which ends the task the same way.
+The supervisor waits for the answer inside its usual loop, so heartbeats keep
running while the sidecar imports and resolves.
+The 60 s limit on a backend call the supervisor makes before the task starts
does not apply, because a Dag-file import can take longer. The task's
`execution_timeout` bounds resolution instead, and a sidecar that exits before
it answers fails the task, with retries, as `fail` does.
+
+Resolution reads key order from the Dag the worker runs, never from storage,
where MySQL may sort JSON keys.
+So the order of a multi-key `expand()` and of a literal dict is the order the
SDK writes, and an SDK writes them in declaration or insertion order, the same
on every serialization.
+Two instances that saw different orders could otherwise pick the same
combination of a cross product.
+
+The sidecar turns each resolved value into a binding with the JSON rules of a
`literal`: a tuple becomes an array, and a `LazyXComSequence` becomes a
`sequence` binding.
+A value that is not JSON-serializable fails the task.
+
+### A Python Dag with stub TaskHandler
+
+The sidecar resolves the real task, `map()` callables included, so the runtime
receives finished values in `TIRunContext.arg_bindings`: `literal`, or
`sequence` for a reduce.
+A callable that raises `AirflowSkipException` skips the instance, and any
other error fails it.
+The runtime has not received `StartupDetails` yet, so the supervisor reports
that skip or failure itself and stops the runtime, as `_fail_before_start` does
for a failure today.
+Reporting a skip from there is new: `_fail_before_start` only records a retry
or a failure.
+
+### A Python task
+
+A Python task starts no sidecar. Its task process resolves the expand input
after the fork, as it does today, by calling the same resolution module the
sidecar calls.
+Both read XComs through the supervisor, with the requests a Python task
already sends.
+
+### A Dag definition
+
+A mapped producer and one instance of the task mapped over it:
+
+```mermaid
+sequenceDiagram
+ participant S as Scheduler
+ participant API as Execution API
+ participant Sup as Supervisor
+ participant Side as Python sidecar
+ participant RT as Lang SDK runtime
+
+ Note over S,RT: Upstream task
+ Sup->>API: ti_run
+ API-->>Sup: TIRunContext with needs_mapped_length
+ Sup->>RT: start task
+ RT->>Sup: return value
+ Sup->>Sup: measure map length
+ Sup->>API: push XCom and map length
+ S->>S: expand the mapped task into N task instances
+
+ Note over S,RT: Mapped task instance i
+ Sup->>API: ti_run
+ API-->>Sup: arg_bindings as stored, no arithmetic
+ Sup->>RT: start task
+ RT->>Sup: ResolveArgBindings with its serialized Dag
+ Sup->>Side: ResolveTaskArgs
+ Side->>Side: rebuild the task with placeholder upstreams
+ Side->>API: get upstream XComs (through Supervisor)
+ API-->>Side: stored rows
+ Side->>Side: deserialize through the XCom backend
+ Side->>Side: resolve the expand input at index i, leave the outermost
.map() off
+ Side-->>Sup: literal and sequence bindings
+ Sup-->>RT: literal and sequence bindings
+ opt .map() callable
+ RT->>RT: apply its own callable
+ end
+ RT->>Sup: return value
+```
-class XComSequenceArgBinding(_ArgBindingBase):
- """A producing task's whole output, as a lazy sequence (decision 8)."""
+The rebuild needs a Task SDK deserializer for the serialized Dag, which does
not exist today.
+Core's `deserialize_dag` builds scheduler objects, and those have no `resolve`.
+A placeholder upstream keeps its task id, whether it is mapped, and its task
group nesting, which `get_relevant_map_indexes` walks to pick a group member's
rows.
- kind: Literal["sequence"]
+The sidecar resolves from the serialized Dag the runtime sends, because that
is the version the worker runs.
+If it disagrees with the `_arg_bindings` from `ti_run`, the task fails without
retry, as above.
- task_id: str
- """
- Task whose ``return_value`` rows make up the sequence.
+The runtime sends one request before it binds anything:
- The server decides which rows are live and in what order; the runtime asks
only for offsets.
- """
+```python
+class ResolveArgBindings(BaseModel):
+ """Have the Python sidecar resolve a Dag definition's task arguments at
this map index."""
+ type: Literal["ResolveArgBindings"] = "ResolveArgBindings"
-TaskArgBinding = TypeAliasType(
- "TaskArgBinding",
- Annotated[
- XComArgBinding | LiteralArgBinding | XComSequenceArgBinding |
TupleArgBinding,
- Field(discriminator="kind", title="TaskArgBinding"),
- ],
-)
-```
+ dag: dict[str, JsonValue]
+ """The serialized Dag, as the runtime writes it for the Dag processor."""
-Before the runtime starts, the supervisor turns every binding into what the
runtime receives:
-| From the server | The supervisor | The runtime receives |
-|---|---|---|
-| `literal` | passes it on | `literal` |
-| `xcom` | GETs the row through the XCom backend, then takes `element_index`
when set | `literal` |
-| `tuple` | reads every part and puts them in one array, in zip order |
`literal` |
-| `expand_kwargs` in the run context | reads the dict once, runs any `map()`
callables in the sidecar (a skip skips the instance), and checks its keys
(*Which signature a call is checked against*) | nothing |
-| any of these with `kwarg` | takes that key from the resolved dict, else
reads `fallback`; with neither, fails the task | `literal` |
-| any of these with `apply_map` | reads the value, and leaves the callables to
the runtime | `literal`, with `apply_map` |
-| `sequence` | passes it on | `sequence` |
+class ArgBindingsResult(BaseModel):
+ type: Literal["ArgBindingsResult"] = "ArgBindingsResult"
+
+ bindings: list[ResolvedLiteralArgBinding | XComSequenceArgBinding]
+```
-The run context gains two fields:
+The callables are the runtime's, so the sidecar takes an outermost `map()` off
before it resolves, and tells the runtime what is left to do on the binding:
```python
-class TIRunContext(BaseModel):
- ...
- needs_mapped_length: bool | None = None
- """
- Whether the supervisor has to measure this task's return value.
+class ResolvedLiteralArgBinding(LiteralArgBinding):
+ apply_map: bool = False
+ """Run this argument's ``map()`` callables on the value (decision 6)."""
- Set only for a Lang-SDK task: True when its return value is expanded over
downstream. Derived
- from ``not ti.is_mapped and any(task.iter_mapped_dependants())``. None for
a Python task, which
- measures its own.
+ kwarg: str | None = None
"""
+ ``expand_kwargs()`` only: take this key of the value, after any ``map()``
callables.
- expand_kwargs: ExpandKwargsSource | None = None
- """Set only for a stub expanded with ``expand_kwargs()``."""
-
+ Set for a parameter ``partial()`` does not set, and with ``strict=False``
for one it does too.
+ """
-class ExpandKwargsSource(BaseModel):
+ fallback: JsonValue | None = None
"""
- One instance's ``expand_kwargs()`` dict, for a stub.
+ The value when the dict has no ``kwarg`` key.
- The supervisor reads it once, runs any ``map()`` callables, checks its
keys, and gives each
- ``kwarg`` binding its value from the result. It is sent even when no
binding carries ``kwarg``.
+ The signature default, or with ``strict=False`` the ``partial()`` value.
Present exactly when
+ there is one, as with ``default``, so it is dumped with
``exclude_unset=True``.
"""
- part: ArgPart
- """Where the dict is: a ``LiteralValue`` for a literal row, else an
``XComRef``."""
+ spread: bool = False
+ """
+ ``expand_kwargs()`` on a Dag definition's own task only: spread the value
into the arguments.
- apply_map: bool = False
- """Run the expand input's ``map()`` callables on the dict first, in the
Python sidecar."""
+ The value, after any ``map()`` callables, is a dict the runtime spreads
into the handler's
+ arguments. ``name`` is then ``**``.
+ """
```
-The supervisor wire gains one request, for a stub TaskHandler that needs a
Python Dag's `map()` callables run:
-
-```python
-class ApplyMap(BaseModel):
- """Run a Python Dag's ``map()`` callables for one argument, in the
supervisor's Python sidecar."""
-
- type: Literal["ApplyMap"] = "ApplyMap"
-
- name: str
- """The parameter whose expand argument holds the callables."""
-
- value: JsonValue
- """The element the supervisor picked, before the callables."""
-
-
-class MapResult(BaseModel):
- type: Literal["MapResult"] = "MapResult"
+| The resolved argument | The runtime receives |
+|---|---|
+| a value | `literal` |
+| a mapped upstream's whole output, which Python resolves to a lazy sequence |
`sequence`, unread |
+| an element under an outermost `map()` | `literal` of the element before the
callables, with `apply_map` |
+| a key of an `expand_kwargs()` dict that `map()` builds | `literal` of the
element, with `apply_map`, `kwarg` and `fallback` |
+| this index's `expand_kwargs()` dict, for a `kwargs` entry | `literal` with
`spread` |
- value: JsonValue = None
- """The argument after the callables. Unset when ``skipped``."""
+`map()` is elementwise, so taking it off cannot move an index. Over a dict it
gives each index its `(key, value)` pair, as a dict expanded directly does, so
the runtime receives that pair as a two-item array with `apply_map`.
+Python's `expand_kwargs()` needs a dict after the callables, so over a `map()`
the sidecar resolves the wrapped element instead and leaves the key to the
runtime, through `kwarg` and `fallback`.
+A failure comes back as `ArgBindingsFailed`, and the runtime ends the task as
its `outcome` says.
- skipped: bool = False
- """True when a callable raised ``AirflowSkipException``."""
-```
+### Both modes
-Any other failure, including a Dag file that fails to import, comes back as an
`ErrorResponse` of a new `APPLY_MAP_ERROR` type, whose `detail` holds the
exception's type and message.
+`zip` and `concat` need no binding kind of their own: the sidecar reads their
element as a Python task does.
+A dict expanded directly gives its `(key, value)` pair, which the runtime
receives as a two-item array.
+Inside `zip()` and `concat()` a dict behaves as it does in Python: `concat()`
gives the key, and `zip()` looks the index up as a key.
+A stub task that is neither mapped nor in a mapped task group keeps its plain
`literal` and `xcom` bindings, and its runtime reads an `xcom` one itself, as
before.
-`concat` needs no new kind: the server knows each argument's length already,
so it emits an
-ordinary `XComArgBinding` for whichever argument owns this index.
`serialization/schema.json` also
-gains `expand_input` as a declared property, which exists today only as a
`dependencies` entry, so
+`serialization/schema.json` also gains `expand_input` as a declared property,
which exists today only as a `dependencies` entry, so
the key validates by accident.
+Its `arg_binding` definition widens too: `kind` allows `sequence`, `param` and
`kwargs` besides `xcom` and `literal`, it declares `default` and `group_arg`,
and `name` is required for every kind but `kwargs`.
Each change ships behind an Execution API version with a mirrored supervisor
wire-schema version.
+An older client gets no `arg_bindings` for a mapped stub, which keeps ignoring
its arguments as before, and no `needs_mapped_length`.
+An unmapped stub whose bindings need the new version, such as a reduce's
`sequence`, cannot be sent to an older client, so `ti_run` answers 422 with the
reason `arg_bindings_need_newer_client`.
Review Comment:
`ti_run` now marks it failed without retry before answering 422, so it
doesn't wait in queued.
Addressed in 6ffce7faa2a.
##########
airflow-core/adr/lang-sdk/0016-mapped-tasks-across-lang-sdks.md:
##########
@@ -479,69 +567,64 @@ cannot change the count.
| Process | What it does |
|---|---|
| API server | Sets the flag at `ti_run` for a Lang-SDK task, off the
serialized task it already loads for the bindings when `ti.is_stub`. A Python
task's `ti_run` is unchanged and leaves it `None`. |
-| Supervisor | On `SetXCom` for `return_value`, checks the value with
`is_mappable_value` and passes `len(value)` as `mapped_length`, before the XCom
backend stores it. A value that is not mappable, such as a string, fails the
task. No `return_value` push by task end also fails it, since the consumer
would otherwise be `UPSTREAM_FAILED` with no reason. Drops the field before
forwarding the context, as it already does for `xcom_keys_to_clear`. |
+| Supervisor | On `SetXCom` for `return_value`, checks the value with
`is_mappable_value` and passes `len(value)` as `mapped_length`, before the XCom
backend stores it. A value that is not mappable, such as a string, fails the
task. No `return_value` push by task end also fails it, since the consumer
would otherwise be `UPSTREAM_FAILED` with no reason. Clears the field before
forwarding the context, as it already empties `xcom_keys_to_clear`. |
| SDK runtime | Nothing. It never receives the flag and never sends a length. |
| Python task | Unchanged: its runtime measures in `_push_xcom_if_needed`
before the value is stored. |
## Read path
-One path for both authoring modes: the supervisor narrows every binding to
this map index's value before the runtime starts.
+The sidecar resolves every binding to this map index's value. Only where it
gets the task, and who applies `map()` callables, differ by authoring mode.
```
- API SERVER ti_run ──▶ TIRunContext{ ti.map_index, expanded_ti_count,
arg_bindings }
- │ each xcom binding a coordinate: task_id, map_index,
element_index
- │
- SUPERVISOR ├─ read each value through the XCom backend, narrow it to this
index
- └─ rewrite the binding to a literal, keeping apply_map
- │
- SDK RUNTIME ├─ apply_map in a Dag definition? ──▶ runtime applies its own
callables
- ├─ apply_map in a stub TaskHandler? ──▶ ApplyMap ──▶ Python
sidecar applies them
- └─ transform({ region: "eu", row: … })
+ API SERVER ti_run ──▶ TIRunContext{ ti.map_index, expanded_ti_count,
arg_bindings }
+ │
+ SUPERVISOR ├─ Python Dag with stub TaskHandler?
+ │ └─ map index 0 or more and _arg_bindings: PYTHON
SIDECAR imports the Dag file, resolves the real task,
+ │ map() callables included ──▶ literal and sequence
bindings
+ │
+ SDK RUNTIME ├─ Dag definition with a map index of 0 or more and
_arg_bindings?
+ │ └─ ResolveArgBindings{ dag } ──▶ PYTHON SIDECAR:
rebuild the task, resolve it
+ │ ◀── literal and sequence bindings, keeping apply_map
+ │ └─ apply_map? ──▶ the runtime applies its own
callables
+ └─ transform({ region: "eu", row: … })
```
-What the server sends for each authoring form, and what the runtime receives
after the supervisor.
+What the sidecar reads for each authoring form, and what the runtime receives.
-| Authoring form | Binding from the server | The runtime receives |
+| Authoring form | The sidecar reads | The runtime receives |
|---|---|---|
-| `.expand({ row: ["a", "b"] })` | `literal`, `value` already the element |
that `literal` |
-| `.expand({ row: rows })` | `xcom`, `task_id`, `element_index=i` | `literal`:
element `i` of the row |
-| `.expand({ row: mappedUpstream })` | `xcom`, `task_id`, and the `map_index`
of the producer's `i`-th non-null row in map-index order | `literal`: that row |
-| `.expand({ a: …, b: … })` | one binding per argument, each with its own
coordinate | one `literal` per argument |
-| `.partial({ region: … })` | `literal`, or `xcom` with no index | the same
value at every index |
-| `.expandKwargs(rows)` | per parameter that `partial()` does not set (with
`strict=False`, every parameter): a binding with `kwarg` and `fallback`, read
from the run context's `expand_kwargs` | `literal`: that key of the resolved
dict, else the fallback |
-| `.expandKwargs(rows)`, from a `kwargs` entry | one `xcom` with
`element_index=i` and `spread` | `literal`: element `i`, spread into the
arguments |
-| `.zip(a, b)` | `tuple`, one part per zipped argument | `literal`: the parts
as one array |
-| `.concat(a, b)` | `xcom` for whichever argument owns this index | `literal`:
that element |
-| `.map(f)` | the wrapped form's binding, with `apply_map` | see below |
-| Mapped task group | the member's binding, taken through the innermost common
mapped ancestor | `literal` |
-| Reduce, in a downstream task | `sequence`, `task_id` | `sequence`, from
which it builds a lazy handle and fetches nothing yet |
-
-An element of a dict is its `(key, value)` pair in the stored value's order,
the pair a Python task reading the same XCom gets.
+| `.expand({ row: ["a", "b"] })` | nothing: the element is in the expand input
| `literal` |
+| `.expand({ row: rows })` | `rows`, then element `i` | `literal`: element `i`
of the row |
+| `.expand({ row: mappedUpstream })` | the producer's `i`-th non-null row, in
map-index order | `literal`: that row |
+| `.expand({ a: …, b: … })` | each argument's element, picked as Python picks
a cross product | one `literal` per argument |
+| `.partial({ region: … })` | the literal, or the upstream's whole value | the
same value at every index |
+| `.expandKwargs(rows)` | element `i`, then each parameter's key, else its
fallback | one `literal` per parameter |
+| `.expandKwargs(rows)`, from a `kwargs` entry | element `i` | `literal` with
`spread` |
+| `.zip(a, b)` | each part's element, the fill value where a part runs out |
`literal`: the parts as one array |
+| `.concat(a, b)` | the element of whichever argument owns this index |
`literal` |
+| `.map(f)` in a Python Dag with stub TaskHandler | the element, then `f` of
it | `literal` |
+| `.map(f)` in a Dag definition | the element the `map()` wraps | `literal`
with `apply_map` |
+| Mapped task group | the member's value, taken through the innermost common
mapped ancestor | `literal` |
+| Reduce, in a downstream task | nothing | `sequence`, from which it builds a
lazy handle and fetches nothing yet |
+
+An element of a dict expanded directly is its `(key, value)` pair in the
stored value's order, the pair a Python task reading the same XCom gets.
A runtime receives it as a two-item array, such as `["uk", 3]`.
-A mapped producer's null result gives the consumer no instance, so instance
`i` reads the producer's `i`-th non-null row in map-index order rather than
producer map index `i`, as Python's lazy sequence does. A Python producer
writes no row for `None`. A language-SDK producer can store a null row
([#77281](https://github.com/apache/airflow/pull/77281)), so the map length the
server counts and the sequence reads both have to leave such rows out. Neither
does yet: the count is `count(map_index)` over every row, and the reads filter
only SQL `NULL`, not a JSON `null` value.
+A mapped producer's null result gives the consumer no instance, so instance
`i` reads the producer's `i`-th non-null row in map-index order rather than
producer map index `i`, as Python's lazy sequence does. A Python producer
writes no row for `None`. A Lang-SDK producer can store a null row
([#77281](https://github.com/apache/airflow/pull/77281)), so the map length the
server counts and the sequence reads both have to leave such rows out. Neither
does yet: the count is `count(map_index)` over every row, and the reads filter
only SQL `NULL`, not a JSON `null` value.
Review Comment:
The count and the sequence reads now leave out JSON `null` rows, as they do
SQL `NULL`.
Addressed in 6ffce7faa2a.
##########
airflow-core/adr/lang-sdk/0016-mapped-tasks-across-lang-sdks.md:
##########
@@ -655,35 +733,54 @@ With the default backend no sidecar starts for XComs.
The sidecar reads connections and variables through the supervisor's API
client, as a Python task does.
The supervisor measures a value before the backend stores it, and every value
read back goes through the backend first, so nothing measures or indexes a
storage path.
A Python task keeps running the backend in its own process.
-Answering `ApplyMap` is a second job for the same sidecar, and the only one
that imports the Python Dag file.
+Resolving a mapped stub's bindings is a second job for the same sidecar, which
starts for it whatever the XCom backend.
+It imports the Dag file for a Python Dag with stub TaskHandler only, never for
a Dag definition.
## Runtime steps
What every SDK implements, in order. Nothing here is language-specific.
1. Read `ti.map_index` and `ti_context.expanded_ti_count` from
`StartupDetails`. A `map_index` of `-1` means the task is not mapped.
-2. Take the delivered binding for this map index: a `literal`, or a `sequence`
for a reduce. A kind the SDK does not implement fails the task before the
handler runs.
-3. For a binding with `apply_map`, get its `map()` callables run: a Dag
definition applies its own, and a stub TaskHandler sends `ApplyMap`. A skip
from the callables skips the instance.
-4. For a binding with `spread`, merge the value's keys into the handler's
arguments, failing the instance on one a `partial()` binding also sets.
+2. For a Dag definition's task with a `map_index` of 0 or more and bindings,
send `ResolveArgBindings` with the serialized Dag, and use the bindings it
returns. On `ArgBindingsFailed`, end the task as its `outcome` says. A stub
task of a Python Dag with stub TaskHandler gets its bindings already resolved,
and never receives `param` or `kwargs`.
+3. Take each binding for this map index: a `literal`, or a `sequence` for a
reduce. A kind from this ADR that the SDK does not implement, or a set field it
does not know, such as `apply_map`, fails the task before the handler runs,
without retry, since a retry would get the same binding.
+4. For a binding with `apply_map`, apply the Dag definition's own callables.
Then take `kwarg`, or `fallback` when the key is missing, failing the instance
when there is no `fallback` or when the dict has a key no `kwarg` binding
names; with `spread`, merge the value's keys into the handler's arguments,
failing the instance on one a `partial()` binding also sets. Run the callables
once per instance, even when several parameters share them. A skip from them
skips the instance. These failures follow the task's retries, as the same error
does in a Python task.
5. Optionally send `SetRenderedMapIndex` to label the instance.
6. Run the handler with that one element.
7. Push the return value. The supervisor adds the map length; the SDK sends
none.
## Consequences
-- **`map()` over a Python callable costs a Dag-file import per consuming task
instance.** Only tasks that consume a `map()` pay it; every other stub
TaskHandler keeps the no-parse path bindings were built to give it. The sidecar
executes Dag-file Python on the worker for a task whose body is not Python —
the same trust boundary as any Python task there, but a new one for a stub
TaskHandler.
-- **A worker running a Python `map()` for a stub TaskHandler needs the Dag
file's Python dependencies.** The sidecar imports the Dag file, so every
provider and library it imports must be installed on the workers serving that
queue,
- which a Lang-SDK worker image did not need before. A missing one fails only
the instances that consume a `map()`, at run time.
-- **`map()` callables are serialized as source text for display only.** Core
deliberately does not deserialize them
([`SchedulerMapXComArg`](https://github.com/apache/airflow/blob/27b8c82f54d44830176eb049f2e42916c7849bb0/airflow-core/src/airflow/serialization/definitions/xcom_arg.py#L105-L115)),
so an SDK emits its own source the same way and no language has to read
another's.
-- **Two resolution paths must agree.** A Python task resolves its arguments
locally, a Lang-SDK task through the server and supervisor.
- A shared conformance test runs every authoring form through both and
compares what each instance receives, as the Lang SDK serialization conformance
check does for the Dag format.
+- **A mapped stub task in a Python Dag with stub TaskHandler costs a Dag-file
import per instance.** Every instance of a stub task that is mapped or in a
mapped task group pays it, whether or not it consumes a `map()`. Any other stub
TaskHandler keeps the no-parse path that bindings give it. The sidecar executes
Dag-file Python on the worker for a task whose body is not Python: the same
trust boundary as any Python task there, but a new one for a stub TaskHandler.
The user docs will ask authors to keep top-level work in such a Dag file light.
+- **A worker running a mapped stub task of a Python Dag with stub TaskHandler
needs the Dag file's Python dependencies.** The sidecar imports the Dag file,
so every provider and library it imports must be installed on the workers
serving that queue, which a Lang-SDK worker image did not need before. A
missing one fails those instances at run time.
+- **A Dag definition's mapped task serializes its Dag once per instance**, in
memory and with no extra process, and sends it to the sidecar.
+- **The sidecar resolves the Dag the worker runs.** The scheduler counts from
the serialized Dag, and the sidecar resolves from the bundle version the task
runs, the pairing a Python task already has. In either mode, a task whose
parameters disagree with the stored bindings fails without retry.
+- **`map()` callables are serialized as source text for display only.** Core
deliberately does not deserialize them
([`SchedulerMapXComArg`](https://github.com/apache/airflow/blob/0e615367203b91eb3e812e41e92f6b5237b1499c/airflow-core/src/airflow/serialization/definitions/xcom_arg.py#L105-L113)),
so an SDK emits its own source the same way and no language has to read
another's.
+- **One resolution module serves Python and Lang-SDK tasks.** A Python task
process and the sidecar call the same code, so a fix to it reaches every SDK,
and a Python task gains no process or Dag-file import. A conformance test
resolves every authoring form from a Python Dag with stub TaskHandler and from
its serialized form, as a Dag definition sends it, and compares what each
instance receives.
+- **The sidecar starts for every Lang-SDK instance with a map index of 0 or
more and `_arg_bindings`**, with the default XCom backend too. A stub that is
neither mapped nor in a mapped task group does not start it.
Review Comment:
Added to Consequences, measured with a prototype that imports the Dag file
before the task starts: a light Dag file adds about 5 ms per mapped instance, a
heavy one about 1.05 s and 200 MB. Full numbers:
https://github.com/jason810496/airflow/blob/exp/python-full-supervisor-path/files/mapped_resolution_bench/12ffdd92ee6-summary.md
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]