pierrejeambrun commented on code in PR #50443:
URL: https://github.com/apache/airflow/pull/50443#discussion_r2093182439


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.
+
+        :param task_ids: set of task_ids
+        :return: tuple of dict of existed task instances, set of matched 
task_ids, set of not found task_ids

Review Comment:
   ```suggestion
           :return: tuple of dict of existing task instances, set of matched 
task_ids, set of not found task_ids
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.
+
+        :param task_ids: set of task_ids
+        :return: tuple of dict of existed task instances, set of matched 
task_ids, set of not found task_ids
+        """
+        existed_task_instances = 
self.session.execute(select(TI).filter(TI.task_id.in_(task_ids))).scalars()

Review Comment:
   ```suggestion
           existing_task_instances = 
self.session.execute(select(TI).filter(TI.task_id.in_(task_ids))).scalars()
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.
+
+        :param task_ids: set of task_ids
+        :return: tuple of dict of existed task instances, set of matched 
task_ids, set of not found task_ids
+        """
+        existed_task_instances = 
self.session.execute(select(TI).filter(TI.task_id.in_(task_ids))).scalars()
+        existed_task_instances_dict = {
+            task_instance.task_id: task_instance for task_instance in 
existed_task_instances
+        }
+        matched_task_ids = set(existed_task_instances_dict.keys())
+        not_found_task_ids = task_ids - matched_task_ids
+        return existed_task_instances_dict, matched_task_ids, 
not_found_task_ids
+
+    def handle_bulk_create(
+        self, action: BulkCreateAction[BulkTaskInstanceBody], results: 
BulkActionResponse
+    ) -> None:
+        results.errors.append(
+            {
+                "error": "Task instances bulk create is not supported",
+                "status_code": status.HTTP_405_METHOD_NOT_ALLOWED,
+            }
+        )
+
+    def handle_bulk_update(
+        self, action: BulkUpdateAction[BulkTaskInstanceBody], results: 
BulkActionResponse
+    ) -> None:
+        """Bulk Update Task Instances."""
+        to_update_task_ids = {task_instance.task_id for task_instance in 
action.entities}
+        _, matched_task_ids, not_found_task_ids = 
self.categorize_task_instances(to_update_task_ids)
+
+        try:
+            if action.action_on_non_existence == BulkActionNotOnExistence.FAIL 
and not_found_task_ids:
+                raise HTTPException(
+                    status_code=status.HTTP_404_NOT_FOUND,
+                    detail=f"The task instances with these task_ids: 
{not_found_task_ids} were not found.",
+                )
+            if action.action_on_non_existence == BulkActionNotOnExistence.SKIP:
+                update_task_ids = matched_task_ids
+            else:
+                update_task_ids = to_update_task_ids
+
+            for task_instance in action.entities:
+                if task_instance.map_index is None:
+                    task_instance.map_index = -1
+
+                if task_instance.task_id in update_task_ids:
+                    dag, ti, data = _patch_ti_validate_request(

Review Comment:
   ```suggestion
                       dag, tis, data = _patch_ti_validate_request(
   ```
   This is a list at this stage. (tis)



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.
+
+        :param task_ids: set of task_ids
+        :return: tuple of dict of existed task instances, set of matched 
task_ids, set of not found task_ids
+        """
+        existed_task_instances = 
self.session.execute(select(TI).filter(TI.task_id.in_(task_ids))).scalars()

Review Comment:
   everywhere



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.

Review Comment:
   ```suggestion
           Existing task instances are returned as a dict of {task_id : 
TaskInstance}.
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py:
##########
@@ -0,0 +1,249 @@
+# 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.
+
+from __future__ import annotations
+
+import structlog
+from fastapi import HTTPException, Query, status
+from fastapi.exceptions import RequestValidationError
+from pydantic import ValidationError
+from pytest import Session
+from sqlalchemy import select
+from sqlalchemy.orm import joinedload
+
+from airflow.api_fastapi.common.dagbag import DagBagDep
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.core_api.datamodels.common import (
+    BulkActionNotOnExistence,
+    BulkActionResponse,
+    BulkBody,
+    BulkCreateAction,
+    BulkDeleteAction,
+    BulkUpdateAction,
+)
+from airflow.api_fastapi.core_api.datamodels.task_instances import 
BulkTaskInstanceBody, PatchTaskInstanceBody
+from airflow.api_fastapi.core_api.security import GetUserDep
+from airflow.api_fastapi.core_api.services.public.common import BulkService
+from airflow.listeners.listener import get_listener_manager
+from airflow.models.dag import DAG
+from airflow.models.taskinstance import TaskInstance as TI
+from airflow.utils.state import TaskInstanceState
+
+log = structlog.get_logger(__name__)
+
+
+def _patch_ti_validate_request(
+    dag_id: str,
+    dag_run_id: str,
+    task_id: str,
+    dag_bag: DagBagDep,
+    body: PatchTaskInstanceBody,
+    session: SessionDep,
+    map_index: int | None = -1,
+    update_mask: list[str] | None = Query(None),
+) -> tuple[DAG, list[TI], dict]:
+    dag = dag_bag.get_dag(dag_id)
+    if not dag:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not 
found")
+
+    if not dag.has_task(task_id):
+        raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not 
found in DAG '{dag_id}'")
+
+    query = (
+        select(TI)
+        .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == 
task_id)
+        .join(TI.dag_run)
+        .options(joinedload(TI.rendered_task_instance_fields))
+    )
+    if map_index is not None:
+        query = query.where(TI.map_index == map_index)
+
+    tis = session.scalars(query).all()
+
+    err_msg_404 = (
+        f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, 
task_id: `{task_id}` and map_index: `{map_index}` was not found",
+    )
+    if len(tis) == 0:
+        raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404)
+
+    fields_to_update = body.model_fields_set
+    if update_mask:
+        fields_to_update = fields_to_update.intersection(update_mask)
+    else:
+        try:
+            PatchTaskInstanceBody.model_validate(body)
+        except ValidationError as e:
+            raise RequestValidationError(errors=e.errors())
+
+    return dag, list(tis), body.model_dump(include=fields_to_update, 
by_alias=True)
+
+
+class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
+    """Service for handling bulk operations on task instances."""
+
+    def __init__(
+        self,
+        session: Session,
+        request: BulkBody[BulkTaskInstanceBody],
+        dag_id: str,
+        dag_run_id: str,
+        dag_bag: DagBagDep,
+        user: GetUserDep,
+    ):
+        super().__init__(session, request)
+        self.dag_id = dag_id
+        self.dag_run_id = dag_run_id
+        self.dag_bag = dag_bag
+        self.user = user
+
+    def categorize_task_instances(self, task_ids: set) -> tuple[dict, set, 
set]:
+        """
+        Categorize the given task_ids into matched_task_ids and 
not_found_task_ids based on existing task_ids.
+
+        Existed task instances are returned as a dict of {task_id : 
TaskInstance}.
+
+        :param task_ids: set of task_ids
+        :return: tuple of dict of existed task instances, set of matched 
task_ids, set of not found task_ids
+        """
+        existed_task_instances = 
self.session.execute(select(TI).filter(TI.task_id.in_(task_ids))).scalars()
+        existed_task_instances_dict = {
+            task_instance.task_id: task_instance for task_instance in 
existed_task_instances
+        }
+        matched_task_ids = set(existed_task_instances_dict.keys())
+        not_found_task_ids = task_ids - matched_task_ids
+        return existed_task_instances_dict, matched_task_ids, 
not_found_task_ids

Review Comment:
   I think we are missing some logic about the `map_index`. A task_id could be 
found, but the associated map_index is not found -> This will raise a 404 in 
the middle of the operation, causing a `BulkActionNotOnExistence.FAIL`



-- 
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]

Reply via email to