jason810496 commented on code in PR #69757: URL: https://github.com/apache/airflow/pull/69757#discussion_r3654479476
########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: + """ + Build the per-map-index arg spec for a mapped (``.expand()``) stub task. + + A mapped stub never instantiates at parse time, so no spec is captured in the + serialized Dag; it is derived here from the serialized expand input instead, with + the map-index decomposition delegated to + ``SchedulerDictOfListsExpandInput.resolve_expansion_sub_indexes``. + Value schemas come from the stub function's annotations, which are not available + server-side, so mapped bindings omit them (runtimes fall back to decode-only checks). + """ + expand_input = task._get_specified_expand_input() + if not isinstance(expand_input, SchedulerDictOfListsExpandInput): + _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") Review Comment: ```suggestion # TODO: Support the `expand_kwargs` path once #69757 merged and all the Lang-SDKs adapt it. if not isinstance(expand_input, SchedulerDictOfListsExpandInput): _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") ``` ########## airflow-core/src/airflow/api_fastapi/execution_api/datamodels/task_arg_binding.py: ########## @@ -0,0 +1,102 @@ +# 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. +""" +Positional-argument binding spec for stub (foreign-runtime) tasks. + +Captured at parse time from the ``@task.stub`` TaskFlow call, stored in the serialized +Dag, and delivered to the lang-SDK runtime via ``TIRunContext.arg_bindings``. +""" + +from __future__ import annotations + +from functools import cache +from typing import Annotated, Literal + +from pydantic import Field, JsonValue, TypeAdapter +from typing_extensions import TypeAliasType + +from airflow.api_fastapi.core_api.base import BaseModel + +# A named, titled alias (like TaskArgBinding below) kept as free-form JSON rather than a +# typed model, so unknown JSON-schema keywords survive re-serialization along the way. +ArgValueSchema = TypeAliasType( + "ArgValueSchema", Annotated[dict[str, JsonValue], Field(title="ArgValueSchema")] +) +"""JSON-schema fragment constraining the value a stub-task argument binds to; generated +by pydantic from the stub annotation, carried verbatim, unknown keywords ignored.""" + + +class XComArgBinding(BaseModel): + """One positional stub-task argument pulled from an upstream task's XCom.""" + + # No default: it would drop ``kind`` from ``required``, and the generated task-sdk + # client then types it ``Literal | None``, invalid as a tagged-union discriminator. + kind: Literal["xcom"] + + name: str + """The stub function's parameter name this binding fills, in declaration order.""" + + value_schema: ArgValueSchema | None = None + """Schema fragment from the stub function's annotation; omitted when unconstrained.""" + + task_id: str + """Upstream task id whose ``return_value`` XCom is pulled.""" + + map_index: int = -1 + """Map index of the upstream XCom row to pull; -1 is the unmapped row.""" + + element_index: int | None = None + """When set, the pulled value is a sequence and this binding takes the element at + this index (the stub was expanded over an unmapped upstream's output).""" Review Comment: ```suggestion this index (the stub was expanded over an unmapped upstream's output). The Lang-SDK side will GET the single row (task_id, map_index=-1), decode it, take value[i].""" ``` ########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: + """ + Build the per-map-index arg spec for a mapped (``.expand()``) stub task. + + A mapped stub never instantiates at parse time, so no spec is captured in the + serialized Dag; it is derived here from the serialized expand input instead, with + the map-index decomposition delegated to + ``SchedulerDictOfListsExpandInput.resolve_expansion_sub_indexes``. + Value schemas come from the stub function's annotations, which are not available + server-side, so mapped bindings omit them (runtimes fall back to decode-only checks). + """ + expand_input = task._get_specified_expand_input() + if not isinstance(expand_input, SchedulerDictOfListsExpandInput): + _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") + if ti.map_index < 0: + _unsupported_arg_bindings("the task instance has not been expanded to a map index") + + expand_value = expand_input.value + try: + sub_indexes = expand_input.resolve_expansion_sub_indexes(ti.map_index, ti.run_id, session=session) + except NotFullyPopulated as e: + _unsupported_arg_bindings(f"upstream map lengths are not yet known for {sorted(e.missing)}") Review Comment: ```suggestion except NotFullyPopulated as e: # In most of the happy path, this shouldn't happed at all unless someone clear upstream TIs or XCom themself during the DagRun. _unsupported_arg_bindings(f"upstream map lengths are not yet known for {sorted(e.missing)}") ``` ########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: + """ + Build the per-map-index arg spec for a mapped (``.expand()``) stub task. + + A mapped stub never instantiates at parse time, so no spec is captured in the + serialized Dag; it is derived here from the serialized expand input instead, with + the map-index decomposition delegated to + ``SchedulerDictOfListsExpandInput.resolve_expansion_sub_indexes``. + Value schemas come from the stub function's annotations, which are not available + server-side, so mapped bindings omit them (runtimes fall back to decode-only checks). + """ + expand_input = task._get_specified_expand_input() + if not isinstance(expand_input, SchedulerDictOfListsExpandInput): + _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") + if ti.map_index < 0: + _unsupported_arg_bindings("the task instance has not been expanded to a map index") + + expand_value = expand_input.value + try: + sub_indexes = expand_input.resolve_expansion_sub_indexes(ti.map_index, ti.run_id, session=session) + except NotFullyPopulated as e: + _unsupported_arg_bindings(f"upstream map lengths are not yet known for {sorted(e.missing)}") + + spec = [ + _bind_mapped_stub_arg(name, value, sub_index=None) + for name, value in (task.partial_kwargs.get("op_kwargs") or {}).items() + ] + spec += [ + _bind_mapped_stub_arg(name, value, sub_index=sub_indexes[name]) + for name, value in expand_value.items() + ] + return spec + + +def _bind_mapped_stub_arg(name: str, value: Any, *, sub_index: int | None) -> dict[str, Any]: + """Build one arg-binding dict; ``sub_index`` is set for expanded kwargs, None for partial ones.""" + if isinstance(value, SchedulerPlainXComArg): + if value.key != "return_value": + _unsupported_arg_bindings(f"parameter {name!r} references the XCom key {value.key!r}") + entry: dict[str, Any] = {"name": name, "kind": "xcom", "task_id": value.operator.task_id} + if sub_index is not None: + if value.operator.is_mapped: + entry["map_index"] = sub_index + else: + entry["element_index"] = sub_index + return entry + if isinstance(value, SchedulerXComArg): + _unsupported_arg_bindings( + f"parameter {name!r} received a {type(value).__name__}; only direct upstream" + " task outputs and literals are supported" + ) + if sub_index is not None: + items = list(value.items()) if isinstance(value, dict) else value Review Comment: ```suggestion if sub_index is not None: # this kwarg was expanded over a literal collection written in the Dag file items = list(value.items()) if isinstance(value, dict) else value ``` ########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: + """ + Build the per-map-index arg spec for a mapped (``.expand()``) stub task. + + A mapped stub never instantiates at parse time, so no spec is captured in the + serialized Dag; it is derived here from the serialized expand input instead, with + the map-index decomposition delegated to + ``SchedulerDictOfListsExpandInput.resolve_expansion_sub_indexes``. + Value schemas come from the stub function's annotations, which are not available + server-side, so mapped bindings omit them (runtimes fall back to decode-only checks). + """ + expand_input = task._get_specified_expand_input() + if not isinstance(expand_input, SchedulerDictOfListsExpandInput): + _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") + if ti.map_index < 0: + _unsupported_arg_bindings("the task instance has not been expanded to a map index") + + expand_value = expand_input.value + try: + sub_indexes = expand_input.resolve_expansion_sub_indexes(ti.map_index, ti.run_id, session=session) + except NotFullyPopulated as e: + _unsupported_arg_bindings(f"upstream map lengths are not yet known for {sorted(e.missing)}") + + spec = [ + _bind_mapped_stub_arg(name, value, sub_index=None) + for name, value in (task.partial_kwargs.get("op_kwargs") or {}).items() + ] + spec += [ + _bind_mapped_stub_arg(name, value, sub_index=sub_indexes[name]) + for name, value in expand_value.items() + ] + return spec + + +def _bind_mapped_stub_arg(name: str, value: Any, *, sub_index: int | None) -> dict[str, Any]: Review Comment: Would it be possible to set the `value_schema` (typing) as well? ########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: + """ + Build the per-map-index arg spec for a mapped (``.expand()``) stub task. + + A mapped stub never instantiates at parse time, so no spec is captured in the + serialized Dag; it is derived here from the serialized expand input instead, with + the map-index decomposition delegated to + ``SchedulerDictOfListsExpandInput.resolve_expansion_sub_indexes``. + Value schemas come from the stub function's annotations, which are not available + server-side, so mapped bindings omit them (runtimes fall back to decode-only checks). + """ + expand_input = task._get_specified_expand_input() + if not isinstance(expand_input, SchedulerDictOfListsExpandInput): + _unsupported_arg_bindings("expand_kwargs() is not supported on stub tasks") + if ti.map_index < 0: + _unsupported_arg_bindings("the task instance has not been expanded to a map index") + + expand_value = expand_input.value + try: + sub_indexes = expand_input.resolve_expansion_sub_indexes(ti.map_index, ti.run_id, session=session) + except NotFullyPopulated as e: + _unsupported_arg_bindings(f"upstream map lengths are not yet known for {sorted(e.missing)}") + + spec = [ + _bind_mapped_stub_arg(name, value, sub_index=None) + for name, value in (task.partial_kwargs.get("op_kwargs") or {}).items() + ] + spec += [ + _bind_mapped_stub_arg(name, value, sub_index=sub_indexes[name]) + for name, value in expand_value.items() + ] Review Comment: ```suggestion # partial() kwargs spec = [ _bind_mapped_stub_arg(name, value, sub_index=None) for name, value in (task.partial_kwargs.get("op_kwargs") or {}).items() ] # expand() kwargs spec += [ _bind_mapped_stub_arg(name, value, sub_index=sub_indexes[name]) for name, value in expand_value.items() ] ``` ########## airflow-core/src/airflow/api_fastapi/execution_api/services/task_instances.py: ########## @@ -0,0 +1,128 @@ +# 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. +"""Business logic backing the task-instance execution routes.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, NoReturn + +from fastapi import HTTPException, status + +from airflow.models.expandinput import NotFullyPopulated, SchedulerDictOfListsExpandInput +from airflow.serialization.definitions.xcom_arg import SchedulerPlainXComArg, SchedulerXComArg + +if TYPE_CHECKING: + from sqlalchemy.orm import Session + + from airflow.models.dagbag import DBDagBag + +# Task type recorded on the TI row (``TaskInstance.operator``) for +# ``airflow.providers.standard.decorators.stub._StubOperator``. Used to gate the +# serialized-Dag lookup for ``arg_bindings`` so regular tasks never pay for it. +# The gate matches the exact class name; a subclass would need its own entry here. +STUB_TASK_TYPE = "_StubOperator" + + +def get_arg_bindings(dag_bag: DBDagBag, ti: Any, *, session: Session) -> list | None: + """Extract or derive the stub task's TaskFlow arg spec from its Dag version.""" + if ti.dag_version_id is None: + return None + if (dag := dag_bag.get_dag(ti.dag_version_id, session=session)) is None: + return None + if (task := dag.task_dict.get(ti.task_id)) is None: + return None + if task.is_mapped: + return _resolve_mapped_stub_arg_bindings(task, ti, session=session) + return getattr(task, "_arg_bindings", None) + + +def _unsupported_arg_bindings(detail: str) -> NoReturn: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail={ + "reason": "invalid_arg_bindings", + "message": f"The stub task's TaskFlow arguments cannot be delivered: {detail}.", + }, + ) + + +def _resolve_mapped_stub_arg_bindings(task: Any, ti: Any, *, session: Session) -> list[dict[str, Any]]: Review Comment: The task should be annotated with `Operator` where `Operator` is ``` Operator: TypeAlias = BaseOperator | MappedOperator ``` at `TYPE_CHECKING` level. -- 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]
