phanikumv commented on code in PR #70570: URL: https://github.com/apache/airflow/pull/70570#discussion_r4681163541
########## airflow-core/src/airflow/api_fastapi/execution_api/services/stub_arg_bindings.py: ########## @@ -0,0 +1,529 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Derive the arg bindings of a stub task whose arguments differ per map index. + +That is a mapped stub, or an unmapped one inside a mapped task group. The server picks this map +index's element of every argument, mirroring how the Python task runner resolves the same Dag, +so no lang-SDK runtime re-implements the mapping arithmetic. The server sends coordinates, never +values: the supervisor reads each XCom binding, and the runtime applies any ``map()`` callables. +""" + +from __future__ import annotations + +import dataclasses +import json +from collections.abc import Callable, Mapping, Sequence +from functools import cached_property +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from pydantic import ValidationError + +from airflow.api_fastapi.execution_api.datamodels.task_arg_binding import ( + LiteralArgBinding, + LiteralValue, + TaskArgBinding, + TupleArgBinding, + XComArgBinding, + XComRef, + XComSequenceArgBinding, + get_arg_bindings_adapter, +) +from airflow.models.dynamic_region import select_current_producer_ids +from airflow.models.expandinput import ( + NotFullyPopulated, + SchedulerDictOfListsExpandInput, + SchedulerListOfDictsExpandInput, +) +from airflow.models.task_coordinates import TaskCoordinateResolver +from airflow.models.taskinstance import _get_relevant_map_indexes +from airflow.models.xcom import XCOM_RETURN_KEY, XComModel, xcom_entity +from airflow.serialization.definitions.mappedoperator import get_mapped_ti_count, is_mapped +from airflow.serialization.definitions.notset import NOTSET, ArgNotSet, is_arg_set +from airflow.serialization.definitions.xcom_arg import ( + SchedulerConcatXComArg, + SchedulerMapXComArg, + SchedulerPlainXComArg, + SchedulerXComArg, + SchedulerZipXComArg, + get_task_map_length, +) +from airflow.serialization.serialized_objects import _XComRef + +if TYPE_CHECKING: + from pydantic import BaseModel + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + from airflow.models.dynamic_region import ProducerContext + from airflow.models.taskinstance import TaskInstance + from airflow.serialization.definitions.dag import SerializedDAG + from airflow.serialization.definitions.mappedoperator import Operator + from airflow.serialization.definitions.taskgroup import SerializedMappedTaskGroup + + _BindingT = TypeVar("_BindingT", bound=BaseModel) + + +class UndeliverableMappedArgBindingsError(ValueError): + """The stub task's arguments cannot be delivered at this map index.""" + + [email protected](frozen=True) +class _GroupArg: + group_id: str + key: str + + [email protected](frozen=True) +class _ArgParam: + """One stub parameter, read from its serialized ``_arg_bindings`` entry.""" + + name: str + value_schema: dict[str, Any] | None = None + default: Any | ArgNotSet = NOTSET + group_arg: _GroupArg | None = None + expand_keys: Sequence[str] | None = None + + @classmethod + def from_entry(cls, entry: Mapping[str, Any]) -> _ArgParam: + group_arg = entry.get("group_arg") + return cls( + name=entry["name"], + value_schema=entry.get("value_schema"), + default=entry.get("default", NOTSET), + group_arg=None if group_arg is None else _GroupArg(group_arg["group_id"], group_arg["key"]), + expand_keys=entry.get("expand_keys"), + ) + + def build(self, binding_cls: type[_BindingT], **fields: Any) -> _BindingT: + # Only fields passed here count as set, so the response's exclude_unset omits the rest. + if self.value_schema is not None: + fields["value_schema"] = self.value_schema + return binding_cls(name=self.name, **fields) + + +def derive_mapped_arg_bindings( + task: Operator, + ti: TaskInstance, + entries: list[dict[str, Any]], + *, + dag_bag: DBDagBag, + session: Session, +) -> list[TaskArgBinding]: + """ + Build the bindings of *ti* at its map index from the serialized ``_arg_bindings`` *entries*. + + :raises UndeliverableMappedArgBindingsError: if an argument has no value at this map index. + """ + resolver = TaskCoordinateResolver(dag_bag, session) + try: + map_index = resolver.public_map_index(ti, dag_version_id=ti.dag_version_id) + if map_index < 0: + raise UndeliverableMappedArgBindingsError( + "the task instance has not been expanded to a map index" + ) + return _MappedArgBindingDeriver(task, ti, map_index, resolver, session=session).derive(entries) + except NotFullyPopulated as e: + raise UndeliverableMappedArgBindingsError( + f"upstream map lengths are not yet known for {sorted(e.missing)}" + ) + except ValidationError as e: + raise UndeliverableMappedArgBindingsError(f"a binding is not valid: {e}") + + +class _MappedArgBindingDeriver: + """ + Derive one map index's bindings from the serialized Dag. + + Parse time rejects the shapes some branches raise for, so only a Dag serialized by an older core + reaches those branches. + """ + + def __init__( + self, + task: Operator, + ti: TaskInstance, + map_index: int, + resolver: TaskCoordinateResolver, + *, + session: Session, + ) -> None: + self.task = task + self.ti = ti + self.map_index = map_index + self.resolver = resolver + self.session = session + self._sub_indexes: dict[int, dict[str, int]] = {} + self._lengths: dict[int, int] = {} + + @property + def dag(self) -> SerializedDAG: + if (dag := self.task.dag) is None: + raise UndeliverableMappedArgBindingsError(f"task {self.task.task_id!r} has no Dag") + return dag + + @cached_property + def producer_contexts(self) -> Mapping[str, ProducerContext]: + return self.resolver.producer_contexts(self.ti, task=self.task) + + @cached_property + def expanded_ti_count(self) -> int: + """The count the Python task runner gets as ``expanded_ti_count``, to pick relevant upstream rows.""" + count = self.resolver.get_expanded_ti_count(self.ti, task=self.task) + if count is None: + count = get_mapped_ti_count( + self.task, self.ti.run_id, session=self.session, producer_contexts=self.producer_contexts + ) + return count + + def derive(self, entries: list[dict[str, Any]]) -> list[TaskArgBinding]: + return [self._bind_entry(_ArgParam.from_entry(entry), entry) for entry in entries] + + def _bind_entry(self, param: _ArgParam, entry: dict[str, Any]) -> TaskArgBinding: + match entry["kind"]: + case "param" if param.group_arg is not None: + return self._bind_group_arg(param, param.group_arg) + case "param" if is_mapped(self.task): + return self._bind_mapped_param(param) + case "xcom" | "sequence": + # Parse time cannot tell which rows of an upstream output this map index reads. + if (producer := self.dag.task_dict.get(entry["task_id"])) is None: + raise UndeliverableMappedArgBindingsError( + f"upstream task {entry['task_id']!r} is missing" + ) + return self._bind_upstream(param, producer) + case _: + (binding,) = get_arg_bindings_adapter().validate_python([entry]) + return binding + + def _bind_mapped_param(self, param: _ArgParam) -> TaskArgBinding: + expand_input = self.task._get_specified_expand_input() + partial_kwargs = self.task.partial_kwargs.get("op_kwargs") or {} + if isinstance(expand_input, SchedulerDictOfListsExpandInput): + if param.name in expand_input.value: + index = self._get_sub_indexes(expand_input, param.expand_keys)[param.name] + return self._bind_element(param, expand_input.value[param.name], index) + # With strict=True a mapping cannot override partial(), so the partial() value binds as it is. + # A mapping read from an upstream output that also has the key fails the Python task, but + # no binding can express that check. + elif not (self.task._disallow_kwargs_override and param.name in partial_kwargs) and ( Review Comment: With strict=True this skips the upstream mapping and binds the partial() value, so consume.partial(x=1).expand_kwargs(produce()) where produce() returns [{"x": 2}] runs the stub with x=1. The same Dag fails in Python with TypeError: mapping already partial argument: x (decorator.py:793). Since no binding can express the check (as the comment above says), could _validate_expand_kwargs reject this at parse time instead: strict=True, a partial() parameter, and an expand_kwargs() value or item read from an upstream output, like _validate_kwarg_fallbacks does for strict=False? It would also need a test that pushes a colliding mapping; strict-binds-partial doesn't -- 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]
